sqlite3.c 7.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624161625161626161627161628161629161630161631161632161633161634161635161636161637161638161639161640161641161642161643161644161645161646161647161648161649161650161651161652161653161654161655161656161657161658161659161660161661161662161663161664161665161666161667161668161669161670161671161672161673161674161675161676161677161678161679161680161681161682161683161684161685161686161687161688161689161690161691161692161693161694161695161696161697161698161699161700161701161702161703161704161705161706161707161708161709161710161711161712161713161714161715161716161717161718161719161720161721161722161723161724161725161726161727161728161729161730161731161732161733161734161735161736161737161738161739161740161741161742161743161744161745161746161747161748161749161750161751161752161753161754161755161756161757161758161759161760161761161762161763161764161765161766161767161768161769161770161771161772161773161774161775161776161777161778161779161780161781161782161783161784161785161786161787161788161789161790161791161792161793161794161795161796161797161798161799161800161801161802161803161804161805161806161807161808161809161810161811161812161813161814161815161816161817161818161819161820161821161822161823161824161825161826161827161828161829161830161831161832161833161834161835161836161837161838161839161840161841161842161843161844161845161846161847161848161849161850161851161852161853161854161855161856161857161858161859161860161861161862161863161864161865161866161867161868161869161870161871161872161873161874161875161876161877161878161879161880161881161882161883161884161885161886161887161888161889161890161891161892161893161894161895161896161897161898161899161900161901161902161903161904161905161906161907161908161909161910161911161912161913161914161915161916161917161918161919161920161921161922161923161924161925161926161927161928161929161930161931161932161933161934161935161936161937161938161939161940161941161942161943161944161945161946161947161948161949161950161951161952161953161954161955161956161957161958161959161960161961161962161963161964161965161966161967161968161969161970161971161972161973161974161975161976161977161978161979161980161981161982161983161984161985161986161987161988161989161990161991161992161993161994161995161996161997161998161999162000162001162002162003162004162005162006162007162008162009162010162011162012162013162014162015162016162017162018162019162020162021162022162023162024162025162026162027162028162029162030162031162032162033162034162035162036162037162038162039162040162041162042162043162044162045162046162047162048162049162050162051162052162053162054162055162056162057162058162059162060162061162062162063162064162065162066162067162068162069162070162071162072162073162074162075162076162077162078162079162080162081162082162083162084162085162086162087162088162089162090162091162092162093162094162095162096162097162098162099162100162101162102162103162104162105162106162107162108162109162110162111162112162113162114162115162116162117162118162119162120162121162122162123162124162125162126162127162128162129162130162131162132162133162134162135162136162137162138162139162140162141162142162143162144162145162146162147162148162149162150162151162152162153162154162155162156162157162158162159162160162161162162162163162164162165162166162167162168162169162170162171162172162173162174162175162176162177162178162179162180162181162182162183162184162185162186162187162188162189162190162191162192162193162194162195162196162197162198162199162200162201162202162203162204162205162206162207162208162209162210162211162212162213162214162215162216162217162218162219162220162221162222162223162224162225162226162227162228162229162230162231162232162233162234162235162236162237162238162239162240162241162242162243162244162245162246162247162248162249162250162251162252162253162254162255162256162257162258162259162260162261162262162263162264162265162266162267162268162269162270162271162272162273162274162275162276162277162278162279162280162281162282162283162284162285162286162287162288162289162290162291162292162293162294162295162296162297162298162299162300162301162302162303162304162305162306162307162308162309162310162311162312162313162314162315162316162317162318162319162320162321162322162323162324162325162326162327162328162329162330162331162332162333162334162335162336162337162338162339162340162341162342162343162344162345162346162347162348162349162350162351162352162353162354162355162356162357162358162359162360162361162362162363162364162365162366162367162368162369162370162371162372162373162374162375162376162377162378162379162380162381162382162383162384162385162386162387162388162389162390162391162392162393162394162395162396162397162398162399162400162401162402162403162404162405162406162407162408162409162410162411162412162413162414162415162416162417162418162419162420162421162422162423162424162425162426162427162428162429162430162431162432162433162434162435162436162437162438162439162440162441162442162443162444162445162446162447162448162449162450162451162452162453162454162455162456162457162458162459162460162461162462162463162464162465162466162467162468162469162470162471162472162473162474162475162476162477162478162479162480162481162482162483162484162485162486162487162488162489162490162491162492162493162494162495162496162497162498162499162500162501162502162503162504162505162506162507162508162509162510162511162512162513162514162515162516162517162518162519162520162521162522162523162524162525162526162527162528162529162530162531162532162533162534162535162536162537162538162539162540162541162542162543162544162545162546162547162548162549162550162551162552162553162554162555162556162557162558162559162560162561162562162563162564162565162566162567162568162569162570162571162572162573162574162575162576162577162578162579162580162581162582162583162584162585162586162587162588162589162590162591162592162593162594162595162596162597162598162599162600162601162602162603162604162605162606162607162608162609162610162611162612162613162614162615162616162617162618162619162620162621162622162623162624162625162626162627162628162629162630162631162632162633162634162635162636162637162638162639162640162641162642162643162644162645162646162647162648162649162650162651162652162653162654162655162656162657162658162659162660162661162662162663162664162665162666162667162668162669162670162671162672162673162674162675162676162677162678162679162680162681162682162683162684162685162686162687162688162689162690162691162692162693162694162695162696162697162698162699162700162701162702162703162704162705162706162707162708162709162710162711162712162713162714162715162716162717162718162719162720162721162722162723162724162725162726162727162728162729162730162731162732162733162734162735162736162737162738162739162740162741162742162743162744162745162746162747162748162749162750162751162752162753162754162755162756162757162758162759162760162761162762162763162764162765162766162767162768162769162770162771162772162773162774162775162776162777162778162779162780162781162782162783162784162785162786162787162788162789162790162791162792162793162794162795162796162797162798162799162800162801162802162803162804162805162806162807162808162809162810162811162812162813162814162815162816162817162818162819162820162821162822162823162824162825162826162827162828162829162830162831162832162833162834162835162836162837162838162839162840162841162842162843162844162845162846162847162848162849162850162851162852162853162854162855162856162857162858162859162860162861162862162863162864162865162866162867162868162869162870162871162872162873162874162875162876162877162878162879162880162881162882162883162884162885162886162887162888162889162890162891162892162893162894162895162896162897162898162899162900162901162902162903162904162905162906162907162908162909162910162911162912162913162914162915162916162917162918162919162920162921162922162923162924162925162926162927162928162929162930162931162932162933162934162935162936162937162938162939162940162941162942162943162944162945162946162947162948162949162950162951162952162953162954162955162956162957162958162959162960162961162962162963162964162965162966162967162968162969162970162971162972162973162974162975162976162977162978162979162980162981162982162983162984162985162986162987162988162989162990162991162992162993162994162995162996162997162998162999163000163001163002163003163004163005163006163007163008163009163010163011163012163013163014163015163016163017163018163019163020163021163022163023163024163025163026163027163028163029163030163031163032163033163034163035163036163037163038163039163040163041163042163043163044163045163046163047163048163049163050163051163052163053163054163055163056163057163058163059163060163061163062163063163064163065163066163067163068163069163070163071163072163073163074163075163076163077163078163079163080163081163082163083163084163085163086163087163088163089163090163091163092163093163094163095163096163097163098163099163100163101163102163103163104163105163106163107163108163109163110163111163112163113163114163115163116163117163118163119163120163121163122163123163124163125163126163127163128163129163130163131163132163133163134163135163136163137163138163139163140163141163142163143163144163145163146163147163148163149163150163151163152163153163154163155163156163157163158163159163160163161163162163163163164163165163166163167163168163169163170163171163172163173163174163175163176163177163178163179163180163181163182163183163184163185163186163187163188163189163190163191163192163193163194163195163196163197163198163199163200163201163202163203163204163205163206163207163208163209163210163211163212163213163214163215163216163217163218163219163220163221163222163223163224163225163226163227163228163229163230163231163232163233163234163235163236163237163238163239163240163241163242163243163244163245163246163247163248163249163250163251163252163253163254163255163256163257163258163259163260163261163262163263163264163265163266163267163268163269163270163271163272163273163274163275163276163277163278163279163280163281163282163283163284163285163286163287163288163289163290163291163292163293163294163295163296163297163298163299163300163301163302163303163304163305163306163307163308163309163310163311163312163313163314163315163316163317163318163319163320163321163322163323163324163325163326163327163328163329163330163331163332163333163334163335163336163337163338163339163340163341163342163343163344163345163346163347163348163349163350163351163352163353163354163355163356163357163358163359163360163361163362163363163364163365163366163367163368163369163370163371163372163373163374163375163376163377163378163379163380163381163382163383163384163385163386163387163388163389163390163391163392163393163394163395163396163397163398163399163400163401163402163403163404163405163406163407163408163409163410163411163412163413163414163415163416163417163418163419163420163421163422163423163424163425163426163427163428163429163430163431163432163433163434163435163436163437163438163439163440163441163442163443163444163445163446163447163448163449163450163451163452163453163454163455163456163457163458163459163460163461163462163463163464163465163466163467163468163469163470163471163472163473163474163475163476163477163478163479163480163481163482163483163484163485163486163487163488163489163490163491163492163493163494163495163496163497163498163499163500163501163502163503163504163505163506163507163508163509163510163511163512163513163514163515163516163517163518163519163520163521163522163523163524163525163526163527163528163529163530163531163532163533163534163535163536163537163538163539163540163541163542163543163544163545163546163547163548163549163550163551163552163553163554163555163556163557163558163559163560163561163562163563163564163565163566163567163568163569163570163571163572163573163574163575163576163577163578163579163580163581163582163583163584163585163586163587163588163589163590163591163592163593163594163595163596163597163598163599163600163601163602163603163604163605163606163607163608163609163610163611163612163613163614163615163616163617163618163619163620163621163622163623163624163625163626163627163628163629163630163631163632163633163634163635163636163637163638163639163640163641163642163643163644163645163646163647163648163649163650163651163652163653163654163655163656163657163658163659163660163661163662163663163664163665163666163667163668163669163670163671163672163673163674163675163676163677163678163679163680163681163682163683163684163685163686163687163688163689163690163691163692163693163694163695163696163697163698163699163700163701163702163703163704163705163706163707163708163709163710163711163712163713163714163715163716163717163718163719163720163721163722163723163724163725163726163727163728163729163730163731163732163733163734163735163736163737163738163739163740163741163742163743163744163745163746163747163748163749163750163751163752163753163754163755163756163757163758163759163760163761163762163763163764163765163766163767163768163769163770163771163772163773163774163775163776163777163778163779163780163781163782163783163784163785163786163787163788163789163790163791163792163793163794163795163796163797163798163799163800163801163802163803163804163805163806163807163808163809163810163811163812163813163814163815163816163817163818163819163820163821163822163823163824163825163826163827163828163829163830163831163832163833163834163835163836163837163838163839163840163841163842163843163844163845163846163847163848163849163850163851163852163853163854163855163856163857163858163859163860163861163862163863163864163865163866163867163868163869163870163871163872163873163874163875163876163877163878163879163880163881163882163883163884163885163886163887163888163889163890163891163892163893163894163895163896163897163898163899163900163901163902163903163904163905163906163907163908163909163910163911163912163913163914163915163916163917163918163919163920163921163922163923163924163925163926163927163928163929163930163931163932163933163934163935163936163937163938163939163940163941163942163943163944163945163946163947163948163949163950163951163952163953163954163955163956163957163958163959163960163961163962163963163964163965163966163967163968163969163970163971163972163973163974163975163976163977163978163979163980163981163982163983163984163985163986163987163988163989163990163991163992163993163994163995163996163997163998163999164000164001164002164003164004164005164006164007164008164009164010164011164012164013164014164015164016164017164018164019164020164021164022164023164024164025164026164027164028164029164030164031164032164033164034164035164036164037164038164039164040164041164042164043164044164045164046164047164048164049164050164051164052164053164054164055164056164057164058164059164060164061164062164063164064164065164066164067164068164069164070164071164072164073164074164075164076164077164078164079164080164081164082164083164084164085164086164087164088164089164090164091164092164093164094164095164096164097164098164099164100164101164102164103164104164105164106164107164108164109164110164111164112164113164114164115164116164117164118164119164120164121164122164123164124164125164126164127164128164129164130164131164132164133164134164135164136164137164138164139164140164141164142164143164144164145164146164147164148164149164150164151164152164153164154164155164156164157164158164159164160164161164162164163164164164165164166164167164168164169164170164171164172164173164174164175164176164177164178164179164180164181164182164183164184164185164186164187164188164189164190164191164192164193164194164195164196164197164198164199164200164201164202164203164204164205164206164207164208164209164210164211164212164213164214164215164216164217164218164219164220164221164222164223164224164225164226164227164228164229164230164231164232164233164234164235164236164237164238164239164240164241164242164243164244164245164246164247164248164249164250164251164252164253164254164255164256164257164258164259164260164261164262164263164264164265164266164267164268164269164270164271164272164273164274164275164276164277164278164279164280164281164282164283164284164285164286164287164288164289164290164291164292164293164294164295164296164297164298164299164300164301164302164303164304164305164306164307164308164309164310164311164312164313164314164315164316164317164318164319164320164321164322164323164324164325164326164327164328164329164330164331164332164333164334164335164336164337164338164339164340164341164342164343164344164345164346164347164348164349164350164351164352164353164354164355164356164357164358164359164360164361164362164363164364164365164366164367164368164369164370164371164372164373164374164375164376164377164378164379164380164381164382164383164384164385164386164387164388164389164390164391164392164393164394164395164396164397164398164399164400164401164402164403164404164405164406164407164408164409164410164411164412164413164414164415164416164417164418164419164420164421164422164423164424164425164426164427164428164429164430164431164432164433164434164435164436164437164438164439164440164441164442164443164444164445164446164447164448164449164450164451164452164453164454164455164456164457164458164459164460164461164462164463164464164465164466164467164468164469164470164471164472164473164474164475164476164477164478164479164480164481164482164483164484164485164486164487164488164489164490164491164492164493164494164495164496164497164498164499164500164501164502164503164504164505164506164507164508164509164510164511164512164513164514164515164516164517164518164519164520164521164522164523164524164525164526164527164528164529164530164531164532164533164534164535164536164537164538164539164540164541164542164543164544164545164546164547164548164549164550164551164552164553164554164555164556164557164558164559164560164561164562164563164564164565164566164567164568164569164570164571164572164573164574164575164576164577164578164579164580164581164582164583164584164585164586164587164588164589164590164591164592164593164594164595164596164597164598164599164600164601164602164603164604164605164606164607164608164609164610164611164612164613164614164615164616164617164618164619164620164621164622164623164624164625164626164627164628164629164630164631164632164633164634164635164636164637164638164639164640164641164642164643164644164645164646164647164648164649164650164651164652164653164654164655164656164657164658164659164660164661164662164663164664164665164666164667164668164669164670164671164672164673164674164675164676164677164678164679164680164681164682164683164684164685164686164687164688164689164690164691164692164693164694164695164696164697164698164699164700164701164702164703164704164705164706164707164708164709164710164711164712164713164714164715164716164717164718164719164720164721164722164723164724164725164726164727164728164729164730164731164732164733164734164735164736164737164738164739164740164741164742164743164744164745164746164747164748164749164750164751164752164753164754164755164756164757164758164759164760164761164762164763164764164765164766164767164768164769164770164771164772164773164774164775164776164777164778164779164780164781164782164783164784164785164786164787164788164789164790164791164792164793164794164795164796164797164798164799164800164801164802164803164804164805164806164807164808164809164810164811164812164813164814164815164816164817164818164819164820164821164822164823164824164825164826164827164828164829164830164831164832164833164834164835164836164837164838164839164840164841164842164843164844164845164846164847164848164849164850164851164852164853164854164855164856164857164858164859164860164861164862164863164864164865164866164867164868164869164870164871164872164873164874164875164876164877164878164879164880164881164882164883164884164885164886164887164888164889164890164891164892164893164894164895164896164897164898164899164900164901164902164903164904164905164906164907164908164909164910164911164912164913164914164915164916164917164918164919164920164921164922164923164924164925164926164927164928164929164930164931164932164933164934164935164936164937164938164939164940164941164942164943164944164945164946164947164948164949164950164951164952164953164954164955164956164957164958164959164960164961164962164963164964164965164966164967164968164969164970164971164972164973164974164975164976164977164978164979164980164981164982164983164984164985164986164987164988164989164990164991164992164993164994164995164996164997164998164999165000165001165002165003165004165005165006165007165008165009165010165011165012165013165014165015165016165017165018165019165020165021165022165023165024165025165026165027165028165029165030165031165032165033165034165035165036165037165038165039165040165041165042165043165044165045165046165047165048165049165050165051165052165053165054165055165056165057165058165059165060165061165062165063165064165065165066165067165068165069165070165071165072165073165074165075165076165077165078165079165080165081165082165083165084165085165086165087165088165089165090165091165092165093165094165095165096165097165098165099165100165101165102165103165104165105165106165107165108165109165110165111165112165113165114165115165116165117165118165119165120165121165122165123165124165125165126165127165128165129165130165131165132165133165134165135165136165137165138165139165140165141165142165143165144165145165146165147165148165149165150165151165152165153165154165155165156165157165158165159165160165161165162165163165164165165165166165167165168165169165170165171165172165173165174165175165176165177165178165179165180165181165182165183165184165185165186165187165188165189165190165191165192165193165194165195165196165197165198165199165200165201165202165203165204165205165206165207165208165209165210165211165212165213165214165215165216165217165218165219165220165221165222165223165224165225165226165227165228165229165230165231165232165233165234165235165236165237165238165239165240165241165242165243165244165245165246165247165248165249165250165251165252165253165254165255165256165257165258165259165260165261165262165263165264165265165266165267165268165269165270165271165272165273165274165275165276165277165278165279165280165281165282165283165284165285165286165287165288165289165290165291165292165293165294165295165296165297165298165299165300165301165302165303165304165305165306165307165308165309165310165311165312165313165314165315165316165317165318165319165320165321165322165323165324165325165326165327165328165329165330165331165332165333165334165335165336165337165338165339165340165341165342165343165344165345165346165347165348165349165350165351165352165353165354165355165356165357165358165359165360165361165362165363165364165365165366165367165368165369165370165371165372165373165374165375165376165377165378165379165380165381165382165383165384165385165386165387165388165389165390165391165392165393165394165395165396165397165398165399165400165401165402165403165404165405165406165407165408165409165410165411165412165413165414165415165416165417165418165419165420165421165422165423165424165425165426165427165428165429165430165431165432165433165434165435165436165437165438165439165440165441165442165443165444165445165446165447165448165449165450165451165452165453165454165455165456165457165458165459165460165461165462165463165464165465165466165467165468165469165470165471165472165473165474165475165476165477165478165479165480165481165482165483165484165485165486165487165488165489165490165491165492165493165494165495165496165497165498165499165500165501165502165503165504165505165506165507165508165509165510165511165512165513165514165515165516165517165518165519165520165521165522165523165524165525165526165527165528165529165530165531165532165533165534165535165536165537165538165539165540165541165542165543165544165545165546165547165548165549165550165551165552165553165554165555165556165557165558165559165560165561165562165563165564165565165566165567165568165569165570165571165572165573165574165575165576165577165578165579165580165581165582165583165584165585165586165587165588165589165590165591165592165593165594165595165596165597165598165599165600165601165602165603165604165605165606165607165608165609165610165611165612165613165614165615165616165617165618165619165620165621165622165623165624165625165626165627165628165629165630165631165632165633165634165635165636165637165638165639165640165641165642165643165644165645165646165647165648165649165650165651165652165653165654165655165656165657165658165659165660165661165662165663165664165665165666165667165668165669165670165671165672165673165674165675165676165677165678165679165680165681165682165683165684165685165686165687165688165689165690165691165692165693165694165695165696165697165698165699165700165701165702165703165704165705165706165707165708165709165710165711165712165713165714165715165716165717165718165719165720165721165722165723165724165725165726165727165728165729165730165731165732165733165734165735165736165737165738165739165740165741165742165743165744165745165746165747165748165749165750165751165752165753165754165755165756165757165758165759165760165761165762165763165764165765165766165767165768165769165770165771165772165773165774165775165776165777165778165779165780165781165782165783165784165785165786165787165788165789165790165791165792165793165794165795165796165797165798165799165800165801165802165803165804165805165806165807165808165809165810165811165812165813165814165815165816165817165818165819165820165821165822165823165824165825165826165827165828165829165830165831165832165833165834165835165836165837165838165839165840165841165842165843165844165845165846165847165848165849165850165851165852165853165854165855165856165857165858165859165860165861165862165863165864165865165866165867165868165869165870165871165872165873165874165875165876165877165878165879165880165881165882165883165884165885165886165887165888165889165890165891165892165893165894165895165896165897165898165899165900165901165902165903165904165905165906165907165908165909165910165911165912165913165914165915165916165917165918165919165920165921165922165923165924165925165926165927165928165929165930165931165932165933165934165935165936165937165938165939165940165941165942165943165944165945165946165947165948165949165950165951165952165953165954165955165956165957165958165959165960165961165962165963165964165965165966165967165968165969165970165971165972165973165974165975165976165977165978165979165980165981165982165983165984165985165986165987165988165989165990165991165992165993165994165995165996165997165998165999166000166001166002166003166004166005166006166007166008166009166010166011166012166013166014166015166016166017166018166019166020166021166022166023166024166025166026166027166028166029166030166031166032166033166034166035166036166037166038166039166040166041166042166043166044166045166046166047166048166049166050166051166052166053166054166055166056166057166058166059166060166061166062166063166064166065166066166067166068166069166070166071166072166073166074166075166076166077166078166079166080166081166082166083166084166085166086166087166088166089166090166091166092166093166094166095166096166097166098166099166100166101166102166103166104166105166106166107166108166109166110166111166112166113166114166115166116166117166118166119166120166121166122166123166124166125166126166127166128166129166130166131166132166133166134166135166136166137166138166139166140166141166142166143166144166145166146166147166148166149166150166151166152166153166154166155166156166157166158166159166160166161166162166163166164166165166166166167166168166169166170166171166172166173166174166175166176166177166178166179166180166181166182166183166184166185166186166187166188166189166190166191166192166193166194166195166196166197166198166199166200166201166202166203166204166205166206166207166208166209166210166211166212166213166214166215166216166217166218166219166220166221166222166223166224166225166226166227166228166229166230166231166232166233166234166235166236166237166238166239166240166241166242166243166244166245166246166247166248166249166250166251166252166253166254166255166256166257166258166259166260166261166262166263166264166265166266166267166268166269166270166271166272166273166274166275166276166277166278166279166280166281166282166283166284166285166286166287166288166289166290166291166292166293166294166295166296166297166298166299166300166301166302166303166304166305166306166307166308166309166310166311166312166313166314166315166316166317166318166319166320166321166322166323166324166325166326166327166328166329166330166331166332166333166334166335166336166337166338166339166340166341166342166343166344166345166346166347166348166349166350166351166352166353166354166355166356166357166358166359166360166361166362166363166364166365166366166367166368166369166370166371166372166373166374166375166376166377166378166379166380166381166382166383166384166385166386166387166388166389166390166391166392166393166394166395166396166397166398166399166400166401166402166403166404166405166406166407166408166409166410166411166412166413166414166415166416166417166418166419166420166421166422166423166424166425166426166427166428166429166430166431166432166433166434166435166436166437166438166439166440166441166442166443166444166445166446166447166448166449166450166451166452166453166454166455166456166457166458166459166460166461166462166463166464166465166466166467166468166469166470166471166472166473166474166475166476166477166478166479166480166481166482166483166484166485166486166487166488166489166490166491166492166493166494166495166496166497166498166499166500166501166502166503166504166505166506166507166508166509166510166511166512166513166514166515166516166517166518166519166520166521166522166523166524166525166526166527166528166529166530166531166532166533166534166535166536166537166538166539166540166541166542166543166544166545166546166547166548166549166550166551166552166553166554166555166556166557166558166559166560166561166562166563166564166565166566166567166568166569166570166571166572166573166574166575166576166577166578166579166580166581166582166583166584166585166586166587166588166589166590166591166592166593166594166595166596166597166598166599166600166601166602166603166604166605166606166607166608166609166610166611166612166613166614166615166616166617166618166619166620166621166622166623166624166625166626166627166628166629166630166631166632166633166634166635166636166637166638166639166640166641166642166643166644166645166646166647166648166649166650166651166652166653166654166655166656166657166658166659166660166661166662166663166664166665166666166667166668166669166670166671166672166673166674166675166676166677166678166679166680166681166682166683166684166685166686166687166688166689166690166691166692166693166694166695166696166697166698166699166700166701166702166703166704166705166706166707166708166709166710166711166712166713166714166715166716166717166718166719166720166721166722166723166724166725166726166727166728166729166730166731166732166733166734166735166736166737166738166739166740166741166742166743166744166745166746166747166748166749166750166751166752166753166754166755166756166757166758166759166760166761166762166763166764166765166766166767166768166769166770166771166772166773166774166775166776166777166778166779166780166781166782166783166784166785166786166787166788166789166790166791166792166793166794166795166796166797166798166799166800166801166802166803166804166805166806166807166808166809166810166811166812166813166814166815166816166817166818166819166820166821166822166823166824166825166826166827166828166829166830166831166832166833166834166835166836166837166838166839166840166841166842166843166844166845166846166847166848166849166850166851166852166853166854166855166856166857166858166859166860166861166862166863166864166865166866166867166868166869166870166871166872166873166874166875166876166877166878166879166880166881166882166883166884166885166886166887166888166889166890166891166892166893166894166895166896166897166898166899166900166901166902166903166904166905166906166907166908166909166910166911166912166913166914166915166916166917166918166919166920166921166922166923166924166925166926166927166928166929166930166931166932166933166934166935166936166937166938166939166940166941166942166943166944166945166946166947166948166949166950166951166952166953166954166955166956166957166958166959166960166961166962166963166964166965166966166967166968166969166970166971166972166973166974166975166976166977166978166979166980166981166982166983166984166985166986166987166988166989166990166991166992166993166994166995166996166997166998166999167000167001167002167003167004167005167006167007167008167009167010167011167012167013167014167015167016167017167018167019167020167021167022167023167024167025167026167027167028167029167030167031167032167033167034167035167036167037167038167039167040167041167042167043167044167045167046167047167048167049167050167051167052167053167054167055167056167057167058167059167060167061167062167063167064167065167066167067167068167069167070167071167072167073167074167075167076167077167078167079167080167081167082167083167084167085167086167087167088167089167090167091167092167093167094167095167096167097167098167099167100167101167102167103167104167105167106167107167108167109167110167111167112167113167114167115167116167117167118167119167120167121167122167123167124167125167126167127167128167129167130167131167132167133167134167135167136167137167138167139167140167141167142167143167144167145167146167147167148167149167150167151167152167153167154167155167156167157167158167159167160167161167162167163167164167165167166167167167168167169167170167171167172167173167174167175167176167177167178167179167180167181167182167183167184167185167186167187167188167189167190167191167192167193167194167195167196167197167198167199167200167201167202167203167204167205167206167207167208167209167210167211167212167213167214167215167216167217167218167219167220167221167222167223167224167225167226167227167228167229167230167231167232167233167234167235167236167237167238167239167240167241167242167243167244167245167246167247167248167249167250167251167252167253167254167255167256167257167258167259167260167261167262167263167264167265167266167267167268167269167270167271167272167273167274167275167276167277167278167279167280167281167282167283167284167285167286167287167288167289167290167291167292167293167294167295167296167297167298167299167300167301167302167303167304167305167306167307167308167309167310167311167312167313167314167315167316167317167318167319167320167321167322167323167324167325167326167327167328167329167330167331167332167333167334167335167336167337167338167339167340167341167342167343167344167345167346167347167348167349167350167351167352167353167354167355167356167357167358167359167360167361167362167363167364167365167366167367167368167369167370167371167372167373167374167375167376167377167378167379167380167381167382167383167384167385167386167387167388167389167390167391167392167393167394167395167396167397167398167399167400167401167402167403167404167405167406167407167408167409167410167411167412167413167414167415167416167417167418167419167420167421167422167423167424167425167426167427167428167429167430167431167432167433167434167435167436167437167438167439167440167441167442167443167444167445167446167447167448167449167450167451167452167453167454167455167456167457167458167459167460167461167462167463167464167465167466167467167468167469167470167471167472167473167474167475167476167477167478167479167480167481167482167483167484167485167486167487167488167489167490167491167492167493167494167495167496167497167498167499167500167501167502167503167504167505167506167507167508167509167510167511167512167513167514167515167516167517167518167519167520167521167522167523167524167525167526167527167528167529167530167531167532167533167534167535167536167537167538167539167540167541167542167543167544167545167546167547167548167549167550167551167552167553167554167555167556167557167558167559167560167561167562167563167564167565167566167567167568167569167570167571167572167573167574167575167576167577167578167579167580167581167582167583167584167585167586167587167588167589167590167591167592167593167594167595167596167597167598167599167600167601167602167603167604167605167606167607167608167609167610167611167612167613167614167615167616167617167618167619167620167621167622167623167624167625167626167627167628167629167630167631167632167633167634167635167636167637167638167639167640167641167642167643167644167645167646167647167648167649167650167651167652167653167654167655167656167657167658167659167660167661167662167663167664167665167666167667167668167669167670167671167672167673167674167675167676167677167678167679167680167681167682167683167684167685167686167687167688167689167690167691167692167693167694167695167696167697167698167699167700167701167702167703167704167705167706167707167708167709167710167711167712167713167714167715167716167717167718167719167720167721167722167723167724167725167726167727167728167729167730167731167732167733167734167735167736167737167738167739167740167741167742167743167744167745167746167747167748167749167750167751167752167753167754167755167756167757167758167759167760167761167762167763167764167765167766167767167768167769167770167771167772167773167774167775167776167777167778167779167780167781167782167783167784167785167786167787167788167789167790167791167792167793167794167795167796167797167798167799167800167801167802167803167804167805167806167807167808167809167810167811167812167813167814167815167816167817167818167819167820167821167822167823167824167825167826167827167828167829167830167831167832167833167834167835167836167837167838167839167840167841167842167843167844167845167846167847167848167849167850167851167852167853167854167855167856167857167858167859167860167861167862167863167864167865167866167867167868167869167870167871167872167873167874167875167876167877167878167879167880167881167882167883167884167885167886167887167888167889167890167891167892167893167894167895167896167897167898167899167900167901167902167903167904167905167906167907167908167909167910167911167912167913167914167915167916167917167918167919167920167921167922167923167924167925167926167927167928167929167930167931167932167933167934167935167936167937167938167939167940167941167942167943167944167945167946167947167948167949167950167951167952167953167954167955167956167957167958167959167960167961167962167963167964167965167966167967167968167969167970167971167972167973167974167975167976167977167978167979167980167981167982167983167984167985167986167987167988167989167990167991167992167993167994167995167996167997167998167999168000168001168002168003168004168005168006168007168008168009168010168011168012168013168014168015168016168017168018168019168020168021168022168023168024168025168026168027168028168029168030168031168032168033168034168035168036168037168038168039168040168041168042168043168044168045168046168047168048168049168050168051168052168053168054168055168056168057168058168059168060168061168062168063168064168065168066168067168068168069168070168071168072168073168074168075168076168077168078168079168080168081168082168083168084168085168086168087168088168089168090168091168092168093168094168095168096168097168098168099168100168101168102168103168104168105168106168107168108168109168110168111168112168113168114168115168116168117168118168119168120168121168122168123168124168125168126168127168128168129168130168131168132168133168134168135168136168137168138168139168140168141168142168143168144168145168146168147168148168149168150168151168152168153168154168155168156168157168158168159168160168161168162168163168164168165168166168167168168168169168170168171168172168173168174168175168176168177168178168179168180168181168182168183168184168185168186168187168188168189168190168191168192168193168194168195168196168197168198168199168200168201168202168203168204168205168206168207168208168209168210168211168212168213168214168215168216168217168218168219168220168221168222168223168224168225168226168227168228168229168230168231168232168233168234168235168236168237168238168239168240168241168242168243168244168245168246168247168248168249168250168251168252168253168254168255168256168257168258168259168260168261168262168263168264168265168266168267168268168269168270168271168272168273168274168275168276168277168278168279168280168281168282168283168284168285168286168287168288168289168290168291168292168293168294168295168296168297168298168299168300168301168302168303168304168305168306168307168308168309168310168311168312168313168314168315168316168317168318168319168320168321168322168323168324168325168326168327168328168329168330168331168332168333168334168335168336168337168338168339168340168341168342168343168344168345168346168347168348168349168350168351168352168353168354168355168356168357168358168359168360168361168362168363168364168365168366168367168368168369168370168371168372168373168374168375168376168377168378168379168380168381168382168383168384168385168386168387168388168389168390168391168392168393168394168395168396168397168398168399168400168401168402168403168404168405168406168407168408168409168410168411168412168413168414168415168416168417168418168419168420168421168422168423168424168425168426168427168428168429168430168431168432168433168434168435168436168437168438168439168440168441168442168443168444168445168446168447168448168449168450168451168452168453168454168455168456168457168458168459168460168461168462168463168464168465168466168467168468168469168470168471168472168473168474168475168476168477168478168479168480168481168482168483168484168485168486168487168488168489168490168491168492168493168494168495168496168497168498168499168500168501168502168503168504168505168506168507168508168509168510168511168512168513168514168515168516168517168518168519168520168521168522168523168524168525168526168527168528168529168530168531168532168533168534168535168536168537168538168539168540168541168542168543168544168545168546168547168548168549168550168551168552168553168554168555168556168557168558168559168560168561168562168563168564168565168566168567168568168569168570168571168572168573168574168575168576168577168578168579168580168581168582168583168584168585168586168587168588168589168590168591168592168593168594168595168596168597168598168599168600168601168602168603168604168605168606168607168608168609168610168611168612168613168614168615168616168617168618168619168620168621168622168623168624168625168626168627168628168629168630168631168632168633168634168635168636168637168638168639168640168641168642168643168644168645168646168647168648168649168650168651168652168653168654168655168656168657168658168659168660168661168662168663168664168665168666168667168668168669168670168671168672168673168674168675168676168677168678168679168680168681168682168683168684168685168686168687168688168689168690168691168692168693168694168695168696168697168698168699168700168701168702168703168704168705168706168707168708168709168710168711168712168713168714168715168716168717168718168719168720168721168722168723168724168725168726168727168728168729168730168731168732168733168734168735168736168737168738168739168740168741168742168743168744168745168746168747168748168749168750168751168752168753168754168755168756168757168758168759168760168761168762168763168764168765168766168767168768168769168770168771168772168773168774168775168776168777168778168779168780168781168782168783168784168785168786168787168788168789168790168791168792168793168794168795168796168797168798168799168800168801168802168803168804168805168806168807168808168809168810168811168812168813168814168815168816168817168818168819168820168821168822168823168824168825168826168827168828168829168830168831168832168833168834168835168836168837168838168839168840168841168842168843168844168845168846168847168848168849168850168851168852168853168854168855168856168857168858168859168860168861168862168863168864168865168866168867168868168869168870168871168872168873168874168875168876168877168878168879168880168881168882168883168884168885168886168887168888168889168890168891168892168893168894168895168896168897168898168899168900168901168902168903168904168905168906168907168908168909168910168911168912168913168914168915168916168917168918168919168920168921168922168923168924168925168926168927168928168929168930168931168932168933168934168935168936168937168938168939168940168941168942168943168944168945168946168947168948168949168950168951168952168953168954168955168956168957168958168959168960168961168962168963168964168965168966168967168968168969168970168971168972168973168974168975168976168977168978168979168980168981168982168983168984168985168986168987168988168989168990168991168992168993168994168995168996168997168998168999169000169001169002169003169004169005169006169007169008169009169010169011169012169013169014169015169016169017169018169019169020169021169022169023169024169025169026169027169028169029169030169031169032169033169034169035169036169037169038169039169040169041169042169043169044169045169046169047169048169049169050169051169052169053169054169055169056169057169058169059169060169061169062169063169064169065169066169067169068169069169070169071169072169073169074169075169076169077169078169079169080169081169082169083169084169085169086169087169088169089169090169091169092169093169094169095169096169097169098169099169100169101169102169103169104169105169106169107169108169109169110169111169112169113169114169115169116169117169118169119169120169121169122169123169124169125169126169127169128169129169130169131169132169133169134169135169136169137169138169139169140169141169142169143169144169145169146169147169148169149169150169151169152169153169154169155169156169157169158169159169160169161169162169163169164169165169166169167169168169169169170169171169172169173169174169175169176169177169178169179169180169181169182169183169184169185169186169187169188169189169190169191169192169193169194169195169196169197169198169199169200169201169202169203169204169205169206169207169208169209169210169211169212169213169214169215169216169217169218169219169220169221169222169223169224169225169226169227169228169229169230169231169232169233169234169235169236169237169238169239169240169241169242169243169244169245169246169247169248169249169250169251169252169253169254169255169256169257169258169259169260169261169262169263169264169265169266169267169268169269169270169271169272169273169274169275169276169277169278169279169280169281169282169283169284169285169286169287169288169289169290169291169292169293169294169295169296169297169298169299169300169301169302169303169304169305169306169307169308169309169310169311169312169313169314169315169316169317169318169319169320169321169322169323169324169325169326169327169328169329169330169331169332169333169334169335169336169337169338169339169340169341169342169343169344169345169346169347169348169349169350169351169352169353169354169355169356169357169358169359169360169361169362169363169364169365169366169367169368169369169370169371169372169373169374169375169376169377169378169379169380169381169382169383169384169385169386169387169388169389169390169391169392169393169394169395169396169397169398169399169400169401169402169403169404169405169406169407169408169409169410169411169412169413169414169415169416169417169418169419169420169421169422169423169424169425169426169427169428169429169430169431169432169433169434169435169436169437169438169439169440169441169442169443169444169445169446169447169448169449169450169451169452169453169454169455169456169457169458169459169460169461169462169463169464169465169466169467169468169469169470169471169472169473169474169475169476169477169478169479169480169481169482169483169484169485169486169487169488169489169490169491169492169493169494169495169496169497169498169499169500169501169502169503169504169505169506169507169508169509169510169511169512169513169514169515169516169517169518169519169520169521169522169523169524169525169526169527169528169529169530169531169532169533169534169535169536169537169538169539169540169541169542169543169544169545169546169547169548169549169550169551169552169553169554169555169556169557169558169559169560169561169562169563169564169565169566169567169568169569169570169571169572169573169574169575169576169577169578169579169580169581169582169583169584169585169586169587169588169589169590169591169592169593169594169595169596169597169598169599169600169601169602169603169604169605169606169607169608169609169610169611169612169613169614169615169616169617169618169619169620169621169622169623169624169625169626169627169628169629169630169631169632169633169634169635169636169637169638169639169640169641169642169643169644169645169646169647169648169649169650169651169652169653169654169655169656169657169658169659169660169661169662169663169664169665169666169667169668169669169670169671169672169673169674169675169676169677169678169679169680169681169682169683169684169685169686169687169688169689169690169691169692169693169694169695169696169697169698169699169700169701169702169703169704169705169706169707169708169709169710169711169712169713169714169715169716169717169718169719169720169721169722169723169724169725169726169727169728169729169730169731169732169733169734169735169736169737169738169739169740169741169742169743169744169745169746169747169748169749169750169751169752169753169754169755169756169757169758169759169760169761169762169763169764169765169766169767169768169769169770169771169772169773169774169775169776169777169778169779169780169781169782169783169784169785169786169787169788169789169790169791169792169793169794169795169796169797169798169799169800169801169802169803169804169805169806169807169808169809169810169811169812169813169814169815169816169817169818169819169820169821169822169823169824169825169826169827169828169829169830169831169832169833169834169835169836169837169838169839169840169841169842169843169844169845169846169847169848169849169850169851169852169853169854169855169856169857169858169859169860169861169862169863169864169865169866169867169868169869169870169871169872169873169874169875169876169877169878169879169880169881169882169883169884169885169886169887169888169889169890169891169892169893169894169895169896169897169898169899169900169901169902169903169904169905169906169907169908169909169910169911169912169913169914169915169916169917169918169919169920169921169922169923169924169925169926169927169928169929169930169931169932169933169934169935169936169937169938169939169940169941169942169943169944169945169946169947169948169949169950169951169952169953169954169955169956169957169958169959169960169961169962169963169964169965169966169967169968169969169970169971169972169973169974169975169976169977169978169979169980169981169982169983169984169985169986169987169988169989169990169991169992169993169994169995169996169997169998169999170000170001170002170003170004170005170006170007170008170009170010170011170012170013170014170015170016170017170018170019170020170021170022170023170024170025170026170027170028170029170030170031170032170033170034170035170036170037170038170039170040170041170042170043170044170045170046170047170048170049170050170051170052170053170054170055170056170057170058170059170060170061170062170063170064170065170066170067170068170069170070170071170072170073170074170075170076170077170078170079170080170081170082170083170084170085170086170087170088170089170090170091170092170093170094170095170096170097170098170099170100170101170102170103170104170105170106170107170108170109170110170111170112170113170114170115170116170117170118170119170120170121170122170123170124170125170126170127170128170129170130170131170132170133170134170135170136170137170138170139170140170141170142170143170144170145170146170147170148170149170150170151170152170153170154170155170156170157170158170159170160170161170162170163170164170165170166170167170168170169170170170171170172170173170174170175170176170177170178170179170180170181170182170183170184170185170186170187170188170189170190170191170192170193170194170195170196170197170198170199170200170201170202170203170204170205170206170207170208170209170210170211170212170213170214170215170216170217170218170219170220170221170222170223170224170225170226170227170228170229170230170231170232170233170234170235170236170237170238170239170240170241170242170243170244170245170246170247170248170249170250170251170252170253170254170255170256170257170258170259170260170261170262170263170264170265170266170267170268170269170270170271170272170273170274170275170276170277170278170279170280170281170282170283170284170285170286170287170288170289170290170291170292170293170294170295170296170297170298170299170300170301170302170303170304170305170306170307170308170309170310170311170312170313170314170315170316170317170318170319170320170321170322170323170324170325170326170327170328170329170330170331170332170333170334170335170336170337170338170339170340170341170342170343170344170345170346170347170348170349170350170351170352170353170354170355170356170357170358170359170360170361170362170363170364170365170366170367170368170369170370170371170372170373170374170375170376170377170378170379170380170381170382170383170384170385170386170387170388170389170390170391170392170393170394170395170396170397170398170399170400170401170402170403170404170405170406170407170408170409170410170411170412170413170414170415170416170417170418170419170420170421170422170423170424170425170426170427170428170429170430170431170432170433170434170435170436170437170438170439170440170441170442170443170444170445170446170447170448170449170450170451170452170453170454170455170456170457170458170459170460170461170462170463170464170465170466170467170468170469170470170471170472170473170474170475170476170477170478170479170480170481170482170483170484170485170486170487170488170489170490170491170492170493170494170495170496170497170498170499170500170501170502170503170504170505170506170507170508170509170510170511170512170513170514170515170516170517170518170519170520170521170522170523170524170525170526170527170528170529170530170531170532170533170534170535170536170537170538170539170540170541170542170543170544170545170546170547170548170549170550170551170552170553170554170555170556170557170558170559170560170561170562170563170564170565170566170567170568170569170570170571170572170573170574170575170576170577170578170579170580170581170582170583170584170585170586170587170588170589170590170591170592170593170594170595170596170597170598170599170600170601170602170603170604170605170606170607170608170609170610170611170612170613170614170615170616170617170618170619170620170621170622170623170624170625170626170627170628170629170630170631170632170633170634170635170636170637170638170639170640170641170642170643170644170645170646170647170648170649170650170651170652170653170654170655170656170657170658170659170660170661170662170663170664170665170666170667170668170669170670170671170672170673170674170675170676170677170678170679170680170681170682170683170684170685170686170687170688170689170690170691170692170693170694170695170696170697170698170699170700170701170702170703170704170705170706170707170708170709170710170711170712170713170714170715170716170717170718170719170720170721170722170723170724170725170726170727170728170729170730170731170732170733170734170735170736170737170738170739170740170741170742170743170744170745170746170747170748170749170750170751170752170753170754170755170756170757170758170759170760170761170762170763170764170765170766170767170768170769170770170771170772170773170774170775170776170777170778170779170780170781170782170783170784170785170786170787170788170789170790170791170792170793170794170795170796170797170798170799170800170801170802170803170804170805170806170807170808170809170810170811170812170813170814170815170816170817170818170819170820170821170822170823170824170825170826170827170828170829170830170831170832170833170834170835170836170837170838170839170840170841170842170843170844170845170846170847170848170849170850170851170852170853170854170855170856170857170858170859170860170861170862170863170864170865170866170867170868170869170870170871170872170873170874170875170876170877170878170879170880170881170882170883170884170885170886170887170888170889170890170891170892170893170894170895170896170897170898170899170900170901170902170903170904170905170906170907170908170909170910170911170912170913170914170915170916170917170918170919170920170921170922170923170924170925170926170927170928170929170930170931170932170933170934170935170936170937170938170939170940170941170942170943170944170945170946170947170948170949170950170951170952170953170954170955170956170957170958170959170960170961170962170963170964170965170966170967170968170969170970170971170972170973170974170975170976170977170978170979170980170981170982170983170984170985170986170987170988170989170990170991170992170993170994170995170996170997170998170999171000171001171002171003171004171005171006171007171008171009171010171011171012171013171014171015171016171017171018171019171020171021171022171023171024171025171026171027171028171029171030171031171032171033171034171035171036171037171038171039171040171041171042171043171044171045171046171047171048171049171050171051171052171053171054171055171056171057171058171059171060171061171062171063171064171065171066171067171068171069171070171071171072171073171074171075171076171077171078171079171080171081171082171083171084171085171086171087171088171089171090171091171092171093171094171095171096171097171098171099171100171101171102171103171104171105171106171107171108171109171110171111171112171113171114171115171116171117171118171119171120171121171122171123171124171125171126171127171128171129171130171131171132171133171134171135171136171137171138171139171140171141171142171143171144171145171146171147171148171149171150171151171152171153171154171155171156171157171158171159171160171161171162171163171164171165171166171167171168171169171170171171171172171173171174171175171176171177171178171179171180171181171182171183171184171185171186171187171188171189171190171191171192171193171194171195171196171197171198171199171200171201171202171203171204171205171206171207171208171209171210171211171212171213171214171215171216171217171218171219171220171221171222171223171224171225171226171227171228171229171230171231171232171233171234171235171236171237171238171239171240171241171242171243171244171245171246171247171248171249171250171251171252171253171254171255171256171257171258171259171260171261171262171263171264171265171266171267171268171269171270171271171272171273171274171275171276171277171278171279171280171281171282171283171284171285171286171287171288171289171290171291171292171293171294171295171296171297171298171299171300171301171302171303171304171305171306171307171308171309171310171311171312171313171314171315171316171317171318171319171320171321171322171323171324171325171326171327171328171329171330171331171332171333171334171335171336171337171338171339171340171341171342171343171344171345171346171347171348171349171350171351171352171353171354171355171356171357171358171359171360171361171362171363171364171365171366171367171368171369171370171371171372171373171374171375171376171377171378171379171380171381171382171383171384171385171386171387171388171389171390171391171392171393171394171395171396171397171398171399171400171401171402171403171404171405171406171407171408171409171410171411171412171413171414171415171416171417171418171419171420171421171422171423171424171425171426171427171428171429171430171431171432171433171434171435171436171437171438171439171440171441171442171443171444171445171446171447171448171449171450171451171452171453171454171455171456171457171458171459171460171461171462171463171464171465171466171467171468171469171470171471171472171473171474171475171476171477171478171479171480171481171482171483171484171485171486171487171488171489171490171491171492171493171494171495171496171497171498171499171500171501171502171503171504171505171506171507171508171509171510171511171512171513171514171515171516171517171518171519171520171521171522171523171524171525171526171527171528171529171530171531171532171533171534171535171536171537171538171539171540171541171542171543171544171545171546171547171548171549171550171551171552171553171554171555171556171557171558171559171560171561171562171563171564171565171566171567171568171569171570171571171572171573171574171575171576171577171578171579171580171581171582171583171584171585171586171587171588171589171590171591171592171593171594171595171596171597171598171599171600171601171602171603171604171605171606171607171608171609171610171611171612171613171614171615171616171617171618171619171620171621171622171623171624171625171626171627171628171629171630171631171632171633171634171635171636171637171638171639171640171641171642171643171644171645171646171647171648171649171650171651171652171653171654171655171656171657171658171659171660171661171662171663171664171665171666171667171668171669171670171671171672171673171674171675171676171677171678171679171680171681171682171683171684171685171686171687171688171689171690171691171692171693171694171695171696171697171698171699171700171701171702171703171704171705171706171707171708171709171710171711171712171713171714171715171716171717171718171719171720171721171722171723171724171725171726171727171728171729171730171731171732171733171734171735171736171737171738171739171740171741171742171743171744171745171746171747171748171749171750171751171752171753171754171755171756171757171758171759171760171761171762171763171764171765171766171767171768171769171770171771171772171773171774171775171776171777171778171779171780171781171782171783171784171785171786171787171788171789171790171791171792171793171794171795171796171797171798171799171800171801171802171803171804171805171806171807171808171809171810171811171812171813171814171815171816171817171818171819171820171821171822171823171824171825171826171827171828171829171830171831171832171833171834171835171836171837171838171839171840171841171842171843171844171845171846171847171848171849171850171851171852171853171854171855171856171857171858171859171860171861171862171863171864171865171866171867171868171869171870171871171872171873171874171875171876171877171878171879171880171881171882171883171884171885171886171887171888171889171890171891171892171893171894171895171896171897171898171899171900171901171902171903171904171905171906171907171908171909171910171911171912171913171914171915171916171917171918171919171920171921171922171923171924171925171926171927171928171929171930171931171932171933171934171935171936171937171938171939171940171941171942171943171944171945171946171947171948171949171950171951171952171953171954171955171956171957171958171959171960171961171962171963171964171965171966171967171968171969171970171971171972171973171974171975171976171977171978171979171980171981171982171983171984171985171986171987171988171989171990171991171992171993171994171995171996171997171998171999172000172001172002172003172004172005172006172007172008172009172010172011172012172013172014172015172016172017172018172019172020172021172022172023172024172025172026172027172028172029172030172031172032172033172034172035172036172037172038172039172040172041172042172043172044172045172046172047172048172049172050172051172052172053172054172055172056172057172058172059172060172061172062172063172064172065172066172067172068172069172070172071172072172073172074172075172076172077172078172079172080172081172082172083172084172085172086172087172088172089172090172091172092172093172094172095172096172097172098172099172100172101172102172103172104172105172106172107172108172109172110172111172112172113172114172115172116172117172118172119172120172121172122172123172124172125172126172127172128172129172130172131172132172133172134172135172136172137172138172139172140172141172142172143172144172145172146172147172148172149172150172151172152172153172154172155172156172157172158172159172160172161172162172163172164172165172166172167172168172169172170172171172172172173172174172175172176172177172178172179172180172181172182172183172184172185172186172187172188172189172190172191172192172193172194172195172196172197172198172199172200172201172202172203172204172205172206172207172208172209172210172211172212172213172214172215172216172217172218172219172220172221172222172223172224172225172226172227172228172229172230172231172232172233172234172235172236172237172238172239172240172241172242172243172244172245172246172247172248172249172250172251172252172253172254172255172256172257172258172259172260172261172262172263172264172265172266172267172268172269172270172271172272172273172274172275172276172277172278172279172280172281172282172283172284172285172286172287172288172289172290172291172292172293172294172295172296172297172298172299172300172301172302172303172304172305172306172307172308172309172310172311172312172313172314172315172316172317172318172319172320172321172322172323172324172325172326172327172328172329172330172331172332172333172334172335172336172337172338172339172340172341172342172343172344172345172346172347172348172349172350172351172352172353172354172355172356172357172358172359172360172361172362172363172364172365172366172367172368172369172370172371172372172373172374172375172376172377172378172379172380172381172382172383172384172385172386172387172388172389172390172391172392172393172394172395172396172397172398172399172400172401172402172403172404172405172406172407172408172409172410172411172412172413172414172415172416172417172418172419172420172421172422172423172424172425172426172427172428172429172430172431172432172433172434172435172436172437172438172439172440172441172442172443172444172445172446172447172448172449172450172451172452172453172454172455172456172457172458172459172460172461172462172463172464172465172466172467172468172469172470172471172472172473172474172475172476172477172478172479172480172481172482172483172484172485172486172487172488172489172490172491172492172493172494172495172496172497172498172499172500172501172502172503172504172505172506172507172508172509172510172511172512172513172514172515172516172517172518172519172520172521172522172523172524172525172526172527172528172529172530172531172532172533172534172535172536172537172538172539172540172541172542172543172544172545172546172547172548172549172550172551172552172553172554172555172556172557172558172559172560172561172562172563172564172565172566172567172568172569172570172571172572172573172574172575172576172577172578172579172580172581172582172583172584172585172586172587172588172589172590172591172592172593172594172595172596172597172598172599172600172601172602172603172604172605172606172607172608172609172610172611172612172613172614172615172616172617172618172619172620172621172622172623172624172625172626172627172628172629172630172631172632172633172634172635172636172637172638172639172640172641172642172643172644172645172646172647172648172649172650172651172652172653172654172655172656172657172658172659172660172661172662172663172664172665172666172667172668172669172670172671172672172673172674172675172676172677172678172679172680172681172682172683172684172685172686172687172688172689172690172691172692172693172694172695172696172697172698172699172700172701172702172703172704172705172706172707172708172709172710172711172712172713172714172715172716172717172718172719172720172721172722172723172724172725172726172727172728172729172730172731172732172733172734172735172736172737172738172739172740172741172742172743172744172745172746172747172748172749172750172751172752172753172754172755172756172757172758172759172760172761172762172763172764172765172766172767172768172769172770172771172772172773172774172775172776172777172778172779172780172781172782172783172784172785172786172787172788172789172790172791172792172793172794172795172796172797172798172799172800172801172802172803172804172805172806172807172808172809172810172811172812172813172814172815172816172817172818172819172820172821172822172823172824172825172826172827172828172829172830172831172832172833172834172835172836172837172838172839172840172841172842172843172844172845172846172847172848172849172850172851172852172853172854172855172856172857172858172859172860172861172862172863172864172865172866172867172868172869172870172871172872172873172874172875172876172877172878172879172880172881172882172883172884172885172886172887172888172889172890172891172892172893172894172895172896172897172898172899172900172901172902172903172904172905172906172907172908172909172910172911172912172913172914172915172916172917172918172919172920172921172922172923172924172925172926172927172928172929172930172931172932172933172934172935172936172937172938172939172940172941172942172943172944172945172946172947172948172949172950172951172952172953172954172955172956172957172958172959172960172961172962172963172964172965172966172967172968172969172970172971172972172973172974172975172976172977172978172979172980172981172982172983172984172985172986172987172988172989172990172991172992172993172994172995172996172997172998172999173000173001173002173003173004173005173006173007173008173009173010173011173012173013173014173015173016173017173018173019173020173021173022173023173024173025173026173027173028173029173030173031173032173033173034173035173036173037173038173039173040173041173042173043173044173045173046173047173048173049173050173051173052173053173054173055173056173057173058173059173060173061173062173063173064173065173066173067173068173069173070173071173072173073173074173075173076173077173078173079173080173081173082173083173084173085173086173087173088173089173090173091173092173093173094173095173096173097173098173099173100173101173102173103173104173105173106173107173108173109173110173111173112173113173114173115173116173117173118173119173120173121173122173123173124173125173126173127173128173129173130173131173132173133173134173135173136173137173138173139173140173141173142173143173144173145173146173147173148173149173150173151173152173153173154173155173156173157173158173159173160173161173162173163173164173165173166173167173168173169173170173171173172173173173174173175173176173177173178173179173180173181173182173183173184173185173186173187173188173189173190173191173192173193173194173195173196173197173198173199173200173201173202173203173204173205173206173207173208173209173210173211173212173213173214173215173216173217173218173219173220173221173222173223173224173225173226173227173228173229173230173231173232173233173234173235173236173237173238173239173240173241173242173243173244173245173246173247173248173249173250173251173252173253173254173255173256173257173258173259173260173261173262173263173264173265173266173267173268173269173270173271173272173273173274173275173276173277173278173279173280173281173282173283173284173285173286173287173288173289173290173291173292173293173294173295173296173297173298173299173300173301173302173303173304173305173306173307173308173309173310173311173312173313173314173315173316173317173318173319173320173321173322173323173324173325173326173327173328173329173330173331173332173333173334173335173336173337173338173339173340173341173342173343173344173345173346173347173348173349173350173351173352173353173354173355173356173357173358173359173360173361173362173363173364173365173366173367173368173369173370173371173372173373173374173375173376173377173378173379173380173381173382173383173384173385173386173387173388173389173390173391173392173393173394173395173396173397173398173399173400173401173402173403173404173405173406173407173408173409173410173411173412173413173414173415173416173417173418173419173420173421173422173423173424173425173426173427173428173429173430173431173432173433173434173435173436173437173438173439173440173441173442173443173444173445173446173447173448173449173450173451173452173453173454173455173456173457173458173459173460173461173462173463173464173465173466173467173468173469173470173471173472173473173474173475173476173477173478173479173480173481173482173483173484173485173486173487173488173489173490173491173492173493173494173495173496173497173498173499173500173501173502173503173504173505173506173507173508173509173510173511173512173513173514173515173516173517173518173519173520173521173522173523173524173525173526173527173528173529173530173531173532173533173534173535173536173537173538173539173540173541173542173543173544173545173546173547173548173549173550173551173552173553173554173555173556173557173558173559173560173561173562173563173564173565173566173567173568173569173570173571173572173573173574173575173576173577173578173579173580173581173582173583173584173585173586173587173588173589173590173591173592173593173594173595173596173597173598173599173600173601173602173603173604173605173606173607173608173609173610173611173612173613173614173615173616173617173618173619173620173621173622173623173624173625173626173627173628173629173630173631173632173633173634173635173636173637173638173639173640173641173642173643173644173645173646173647173648173649173650173651173652173653173654173655173656173657173658173659173660173661173662173663173664173665173666173667173668173669173670173671173672173673173674173675173676173677173678173679173680173681173682173683173684173685173686173687173688173689173690173691173692173693173694173695173696173697173698173699173700173701173702173703173704173705173706173707173708173709173710173711173712173713173714173715173716173717173718173719173720173721173722173723173724173725173726173727173728173729173730173731173732173733173734173735173736173737173738173739173740173741173742173743173744173745173746173747173748173749173750173751173752173753173754173755173756173757173758173759173760173761173762173763173764173765173766173767173768173769173770173771173772173773173774173775173776173777173778173779173780173781173782173783173784173785173786173787173788173789173790173791173792173793173794173795173796173797173798173799173800173801173802173803173804173805173806173807173808173809173810173811173812173813173814173815173816173817173818173819173820173821173822173823173824173825173826173827173828173829173830173831173832173833173834173835173836173837173838173839173840173841173842173843173844173845173846173847173848173849173850173851173852173853173854173855173856173857173858173859173860173861173862173863173864173865173866173867173868173869173870173871173872173873173874173875173876173877173878173879173880173881173882173883173884173885173886173887173888173889173890173891173892173893173894173895173896173897173898173899173900173901173902173903173904173905173906173907173908173909173910173911173912173913173914173915173916173917173918173919173920173921173922173923173924173925173926173927173928173929173930173931173932173933173934173935173936173937173938173939173940173941173942173943173944173945173946173947173948173949173950173951173952173953173954173955173956173957173958173959173960173961173962173963173964173965173966173967173968173969173970173971173972173973173974173975173976173977173978173979173980173981173982173983173984173985173986173987173988173989173990173991173992173993173994173995173996173997173998173999174000174001174002174003174004174005174006174007174008174009174010174011174012174013174014174015174016174017174018174019174020174021174022174023174024174025174026174027174028174029174030174031174032174033174034174035174036174037174038174039174040174041174042174043174044174045174046174047174048174049174050174051174052174053174054174055174056174057174058174059174060174061174062174063174064174065174066174067174068174069174070174071174072174073174074174075174076174077174078174079174080174081174082174083174084174085174086174087174088174089174090174091174092174093174094174095174096174097174098174099174100174101174102174103174104174105174106174107174108174109174110174111174112174113174114174115174116174117174118174119174120174121174122174123174124174125174126174127174128174129174130174131174132174133174134174135174136174137174138174139174140174141174142174143174144174145174146174147174148174149174150174151174152174153174154174155174156174157174158174159174160174161174162174163174164174165174166174167174168174169174170174171174172174173174174174175174176174177174178174179174180174181174182174183174184174185174186174187174188174189174190174191174192174193174194174195174196174197174198174199174200174201174202174203174204174205174206174207174208174209174210174211174212174213174214174215174216174217174218174219174220174221174222174223174224174225174226174227174228174229174230174231174232174233174234174235174236174237174238174239174240174241174242174243174244174245174246174247174248174249174250174251174252174253174254174255174256174257174258174259174260174261174262174263174264174265174266174267174268174269174270174271174272174273174274174275174276174277174278174279174280174281174282174283174284174285174286174287174288174289174290174291174292174293174294174295174296174297174298174299174300174301174302174303174304174305174306174307174308174309174310174311174312174313174314174315174316174317174318174319174320174321174322174323174324174325174326174327174328174329174330174331174332174333174334174335174336174337174338174339174340174341174342174343174344174345174346174347174348174349174350174351174352174353174354174355174356174357174358174359174360174361174362174363174364174365174366174367174368174369174370174371174372174373174374174375174376174377174378174379174380174381174382174383174384174385174386174387174388174389174390174391174392174393174394174395174396174397174398174399174400174401174402174403174404174405174406174407174408174409174410174411174412174413174414174415174416174417174418174419174420174421174422174423174424174425174426174427174428174429174430174431174432174433174434174435174436174437174438174439174440174441174442174443174444174445174446174447174448174449174450174451174452174453174454174455174456174457174458174459174460174461174462174463174464174465174466174467174468174469174470174471174472174473174474174475174476174477174478174479174480174481174482174483174484174485174486174487174488174489174490174491174492174493174494174495174496174497174498174499174500174501174502174503174504174505174506174507174508174509174510174511174512174513174514174515174516174517174518174519174520174521174522174523174524174525174526174527174528174529174530174531174532174533174534174535174536174537174538174539174540174541174542174543174544174545174546174547174548174549174550174551174552174553174554174555174556174557174558174559174560174561174562174563174564174565174566174567174568174569174570174571174572174573174574174575174576174577174578174579174580174581174582174583174584174585174586174587174588174589174590174591174592174593174594174595174596174597174598174599174600174601174602174603174604174605174606174607174608174609174610174611174612174613174614174615174616174617174618174619174620174621174622174623174624174625174626174627174628174629174630174631174632174633174634174635174636174637174638174639174640174641174642174643174644174645174646174647174648174649174650174651174652174653174654174655174656174657174658174659174660174661174662174663174664174665174666174667174668174669174670174671174672174673174674174675174676174677174678174679174680174681174682174683174684174685174686174687174688174689174690174691174692174693174694174695174696174697174698174699174700174701174702174703174704174705174706174707174708174709174710174711174712174713174714174715174716174717174718174719174720174721174722174723174724174725174726174727174728174729174730174731174732174733174734174735174736174737174738174739174740174741174742174743174744174745174746174747174748174749174750174751174752174753174754174755174756174757174758174759174760174761174762174763174764174765174766174767174768174769174770174771174772174773174774174775174776174777174778174779174780174781174782174783174784174785174786174787174788174789174790174791174792174793174794174795174796174797174798174799174800174801174802174803174804174805174806174807174808174809174810174811174812174813174814174815174816174817174818174819174820174821174822174823174824174825174826174827174828174829174830174831174832174833174834174835174836174837174838174839174840174841174842174843174844174845174846174847174848174849174850174851174852174853174854174855174856174857174858174859174860174861174862174863174864174865174866174867174868174869174870174871174872174873174874174875174876174877174878174879174880174881174882174883174884174885174886174887174888174889174890174891174892174893174894174895174896174897174898174899174900174901174902174903174904174905174906174907174908174909174910174911174912174913174914174915174916174917174918174919174920174921174922174923174924174925174926174927174928174929174930174931174932174933174934174935174936174937174938174939174940174941174942174943174944174945174946174947174948174949174950174951174952174953174954174955174956174957174958174959174960174961174962174963174964174965174966174967174968174969174970174971174972174973174974174975174976174977174978174979174980174981174982174983174984174985174986174987174988174989174990174991174992174993174994174995174996174997174998174999175000175001175002175003175004175005175006175007175008175009175010175011175012175013175014175015175016175017175018175019175020175021175022175023175024175025175026175027175028175029175030175031175032175033175034175035175036175037175038175039175040175041175042175043175044175045175046175047175048175049175050175051175052175053175054175055175056175057175058175059175060175061175062175063175064175065175066175067175068175069175070175071175072175073175074175075175076175077175078175079175080175081175082175083175084175085175086175087175088175089175090175091175092175093175094175095175096175097175098175099175100175101175102175103175104175105175106175107175108175109175110175111175112175113175114175115175116175117175118175119175120175121175122175123175124175125175126175127175128175129175130175131175132175133175134175135175136175137175138175139175140175141175142175143175144175145175146175147175148175149175150175151175152175153175154175155175156175157175158175159175160175161175162175163175164175165175166175167175168175169175170175171175172175173175174175175175176175177175178175179175180175181175182175183175184175185175186175187175188175189175190175191175192175193175194175195175196175197175198175199175200175201175202175203175204175205175206175207175208175209175210175211175212175213175214175215175216175217175218175219175220175221175222175223175224175225175226175227175228175229175230175231175232175233175234175235175236175237175238175239175240175241175242175243175244175245175246175247175248175249175250175251175252175253175254175255175256175257175258175259175260175261175262175263175264175265175266175267175268175269175270175271175272175273175274175275175276175277175278175279175280175281175282175283175284175285175286175287175288175289175290175291175292175293175294175295175296175297175298175299175300175301175302175303175304175305175306175307175308175309175310175311175312175313175314175315175316175317175318175319175320175321175322175323175324175325175326175327175328175329175330175331175332175333175334175335175336175337175338175339175340175341175342175343175344175345175346175347175348175349175350175351175352175353175354175355175356175357175358175359175360175361175362175363175364175365175366175367175368175369175370175371175372175373175374175375175376175377175378175379175380175381175382175383175384175385175386175387175388175389175390175391175392175393175394175395175396175397175398175399175400175401175402175403175404175405175406175407175408175409175410175411175412175413175414175415175416175417175418175419175420175421175422175423175424175425175426175427175428175429175430175431175432175433175434175435175436175437175438175439175440175441175442175443175444175445175446175447175448175449175450175451175452175453175454175455175456175457175458175459175460175461175462175463175464175465175466175467175468175469175470175471175472175473175474175475175476175477175478175479175480175481175482175483175484175485175486175487175488175489175490175491175492175493175494175495175496175497175498175499175500175501175502175503175504175505175506175507175508175509175510175511175512175513175514175515175516175517175518175519175520175521175522175523175524175525175526175527175528175529175530175531175532175533175534175535175536175537175538175539175540175541175542175543175544175545175546175547175548175549175550175551175552175553175554175555175556175557175558175559175560175561175562175563175564175565175566175567175568175569175570175571175572175573175574175575175576175577175578175579175580175581175582175583175584175585175586175587175588175589175590175591175592175593175594175595175596175597175598175599175600175601175602175603175604175605175606175607175608175609175610175611175612175613175614175615175616175617175618175619175620175621175622175623175624175625175626175627175628175629175630175631175632175633175634175635175636175637175638175639175640175641175642175643175644175645175646175647175648175649175650175651175652175653175654175655175656175657175658175659175660175661175662175663175664175665175666175667175668175669175670175671175672175673175674175675175676175677175678175679175680175681175682175683175684175685175686175687175688175689175690175691175692175693175694175695175696175697175698175699175700175701175702175703175704175705175706175707175708175709175710175711175712175713175714175715175716175717175718175719175720175721175722175723175724175725175726175727175728175729175730175731175732175733175734175735175736175737175738175739175740175741175742175743175744175745175746175747175748175749175750175751175752175753175754175755175756175757175758175759175760175761175762175763175764175765175766175767175768175769175770175771175772175773175774175775175776175777175778175779175780175781175782175783175784175785175786175787175788175789175790175791175792175793175794175795175796175797175798175799175800175801175802175803175804175805175806175807175808175809175810175811175812175813175814175815175816175817175818175819175820175821175822175823175824175825175826175827175828175829175830175831175832175833175834175835175836175837175838175839175840175841175842175843175844175845175846175847175848175849175850175851175852175853175854175855175856175857175858175859175860175861175862175863175864175865175866175867175868175869175870175871175872175873175874175875175876175877175878175879175880175881175882175883175884175885175886175887175888175889175890175891175892175893175894175895175896175897175898175899175900175901175902175903175904175905175906175907175908175909175910175911175912175913175914175915175916175917175918175919175920175921175922175923175924175925175926175927175928175929175930175931175932175933175934175935175936175937175938175939175940175941175942175943175944175945175946175947175948175949175950175951175952175953175954175955175956175957175958175959175960175961175962175963175964175965175966175967175968175969175970175971175972175973175974175975175976175977175978175979175980175981175982175983175984175985175986175987175988175989175990175991175992175993175994175995175996175997175998175999176000176001176002176003176004176005176006176007176008176009176010176011176012176013176014176015176016176017176018176019176020176021176022176023176024176025176026176027176028176029176030176031176032176033176034176035176036176037176038176039176040176041176042176043176044176045176046176047176048176049176050176051176052176053176054176055176056176057176058176059176060176061176062176063176064176065176066176067176068176069176070176071176072176073176074176075176076176077176078176079176080176081176082176083176084176085176086176087176088176089176090176091176092176093176094176095176096176097176098176099176100176101176102176103176104176105176106176107176108176109176110176111176112176113176114176115176116176117176118176119176120176121176122176123176124176125176126176127176128176129176130176131176132176133176134176135176136176137176138176139176140176141176142176143176144176145176146176147176148176149176150176151176152176153176154176155176156176157176158176159176160176161176162176163176164176165176166176167176168176169176170176171176172176173176174176175176176176177176178176179176180176181176182176183176184176185176186176187176188176189176190176191176192176193176194176195176196176197176198176199176200176201176202176203176204176205176206176207176208176209176210176211176212176213176214176215176216176217176218176219176220176221176222176223176224176225176226176227176228176229176230176231176232176233176234176235176236176237176238176239176240176241176242176243176244176245176246176247176248176249176250176251176252176253176254176255176256176257176258176259176260176261176262176263176264176265176266176267176268176269176270176271176272176273176274176275176276176277176278176279176280176281176282176283176284176285176286176287176288176289176290176291176292176293176294176295176296176297176298176299176300176301176302176303176304176305176306176307176308176309176310176311176312176313176314176315176316176317176318176319176320176321176322176323176324176325176326176327176328176329176330176331176332176333176334176335176336176337176338176339176340176341176342176343176344176345176346176347176348176349176350176351176352176353176354176355176356176357176358176359176360176361176362176363176364176365176366176367176368176369176370176371176372176373176374176375176376176377176378176379176380176381176382176383176384176385176386176387176388176389176390176391176392176393176394176395176396176397176398176399176400176401176402176403176404176405176406176407176408176409176410176411176412176413176414176415176416176417176418176419176420176421176422176423176424176425176426176427176428176429176430176431176432176433176434176435176436176437176438176439176440176441176442176443176444176445176446176447176448176449176450176451176452176453176454176455176456176457176458176459176460176461176462176463176464176465176466176467176468176469176470176471176472176473176474176475176476176477176478176479176480176481176482176483176484176485176486176487176488176489176490176491176492176493176494176495176496176497176498176499176500176501176502176503176504176505176506176507176508176509176510176511176512176513176514176515176516176517176518176519176520176521176522176523176524176525176526176527176528176529176530176531176532176533176534176535176536176537176538176539176540176541176542176543176544176545176546176547176548176549176550176551176552176553176554176555176556176557176558176559176560176561176562176563176564176565176566176567176568176569176570176571176572176573176574176575176576176577176578176579176580176581176582176583176584176585176586176587176588176589176590176591176592176593176594176595176596176597176598176599176600176601176602176603176604176605176606176607176608176609176610176611176612176613176614176615176616176617176618176619176620176621176622176623176624176625176626176627176628176629176630176631176632176633176634176635176636176637176638176639176640176641176642176643176644176645176646176647176648176649176650176651176652176653176654176655176656176657176658176659176660176661176662176663176664176665176666176667176668176669176670176671176672176673176674176675176676176677176678176679176680176681176682176683176684176685176686176687176688176689176690176691176692176693176694176695176696176697176698176699176700176701176702176703176704176705176706176707176708176709176710176711176712176713176714176715176716176717176718176719176720176721176722176723176724176725176726176727176728176729176730176731176732176733176734176735176736176737176738176739176740176741176742176743176744176745176746176747176748176749176750176751176752176753176754176755176756176757176758176759176760176761176762176763176764176765176766176767176768176769176770176771176772176773176774176775176776176777176778176779176780176781176782176783176784176785176786176787176788176789176790176791176792176793176794176795176796176797176798176799176800176801176802176803176804176805176806176807176808176809176810176811176812176813176814176815176816176817176818176819176820176821176822176823176824176825176826176827176828176829176830176831176832176833176834176835176836176837176838176839176840176841176842176843176844176845176846176847176848176849176850176851176852176853176854176855176856176857176858176859176860176861176862176863176864176865176866176867176868176869176870176871176872176873176874176875176876176877176878176879176880176881176882176883176884176885176886176887176888176889176890176891176892176893176894176895176896176897176898176899176900176901176902176903176904176905176906176907176908176909176910176911176912176913176914176915176916176917176918176919176920176921176922176923176924176925176926176927176928176929176930176931176932176933176934176935176936176937176938176939176940176941176942176943176944176945176946176947176948176949176950176951176952176953176954176955176956176957176958176959176960176961176962176963176964176965176966176967176968176969176970176971176972176973176974176975176976176977176978176979176980176981176982176983176984176985176986176987176988176989176990176991176992176993176994176995176996176997176998176999177000177001177002177003177004177005177006177007177008177009177010177011177012177013177014177015177016177017177018177019177020177021177022177023177024177025177026177027177028177029177030177031177032177033177034177035177036177037177038177039177040177041177042177043177044177045177046177047177048177049177050177051177052177053177054177055177056177057177058177059177060177061177062177063177064177065177066177067177068177069177070177071177072177073177074177075177076177077177078177079177080177081177082177083177084177085177086177087177088177089177090177091177092177093177094177095177096177097177098177099177100177101177102177103177104177105177106177107177108177109177110177111177112177113177114177115177116177117177118177119177120177121177122177123177124177125177126177127177128177129177130177131177132177133177134177135177136177137177138177139177140177141177142177143177144177145177146177147177148177149177150177151177152177153177154177155177156177157177158177159177160177161177162177163177164177165177166177167177168177169177170177171177172177173177174177175177176177177177178177179177180177181177182177183177184177185177186177187177188177189177190177191177192177193177194177195177196177197177198177199177200177201177202177203177204177205177206177207177208177209177210177211177212177213177214177215177216177217177218177219177220177221177222177223177224177225177226177227177228177229177230177231177232177233177234177235177236177237177238177239177240177241177242177243177244177245177246177247177248177249177250177251177252177253177254177255177256177257177258177259177260177261177262177263177264177265177266177267177268177269177270177271177272177273177274177275177276177277177278177279177280177281177282177283177284177285177286177287177288177289177290177291177292177293177294177295177296177297177298177299177300177301177302177303177304177305177306177307177308177309177310177311177312177313177314177315177316177317177318177319177320177321177322177323177324177325177326177327177328177329177330177331177332177333177334177335177336177337177338177339177340177341177342177343177344177345177346177347177348177349177350177351177352177353177354177355177356177357177358177359177360177361177362177363177364177365177366177367177368177369177370177371177372177373177374177375177376177377177378177379177380177381177382177383177384177385177386177387177388177389177390177391177392177393177394177395177396177397177398177399177400177401177402177403177404177405177406177407177408177409177410177411177412177413177414177415177416177417177418177419177420177421177422177423177424177425177426177427177428177429177430177431177432177433177434177435177436177437177438177439177440177441177442177443177444177445177446177447177448177449177450177451177452177453177454177455177456177457177458177459177460177461177462177463177464177465177466177467177468177469177470177471177472177473177474177475177476177477177478177479177480177481177482177483177484177485177486177487177488177489177490177491177492177493177494177495177496177497177498177499177500177501177502177503177504177505177506177507177508177509177510177511177512177513177514177515177516177517177518177519177520177521177522177523177524177525177526177527177528177529177530177531177532177533177534177535177536177537177538177539177540177541177542177543177544177545177546177547177548177549177550177551177552177553177554177555177556177557177558177559177560177561177562177563177564177565177566177567177568177569177570177571177572177573177574177575177576177577177578177579177580177581177582177583177584177585177586177587177588177589177590177591177592177593177594177595177596177597177598177599177600177601177602177603177604177605177606177607177608177609177610177611177612177613177614177615177616177617177618177619177620177621177622177623177624177625177626177627177628177629177630177631177632177633177634177635177636177637177638177639177640177641177642177643177644177645177646177647177648177649177650177651177652177653177654177655177656177657177658177659177660177661177662177663177664177665177666177667177668177669177670177671177672177673177674177675177676177677177678177679177680177681177682177683177684177685177686177687177688177689177690177691177692177693177694177695177696177697177698177699177700177701177702177703177704177705177706177707177708177709177710177711177712177713177714177715177716177717177718177719177720177721177722177723177724177725177726177727177728177729177730177731177732177733177734177735177736177737177738177739177740177741177742177743177744177745177746177747177748177749177750177751177752177753177754177755177756177757177758177759177760177761177762177763177764177765177766177767177768177769177770177771177772177773177774177775177776177777177778177779177780177781177782177783177784177785177786177787177788177789177790177791177792177793177794177795177796177797177798177799177800177801177802177803177804177805177806177807177808177809177810177811177812177813177814177815177816177817177818177819177820177821177822177823177824177825177826177827177828177829177830177831177832177833177834177835177836177837177838177839177840177841177842177843177844177845177846177847177848177849177850177851177852177853177854177855177856177857177858177859177860177861177862177863177864177865177866177867177868177869177870177871177872177873177874177875177876177877177878177879177880177881177882177883177884177885177886177887177888177889177890177891177892177893177894177895177896177897177898177899177900177901177902177903177904177905177906177907177908177909177910177911177912177913177914177915177916177917177918177919177920177921177922177923177924177925177926177927177928177929177930177931177932177933177934177935177936177937177938177939177940177941177942177943177944177945177946177947177948177949177950177951177952177953177954177955177956177957177958177959177960177961177962177963177964177965177966177967177968177969177970177971177972177973177974177975177976177977177978177979177980177981177982177983177984177985177986177987177988177989177990177991177992177993177994177995177996177997177998177999178000178001178002178003178004178005178006178007178008178009178010178011178012178013178014178015178016178017178018178019178020178021178022178023178024178025178026178027178028178029178030178031178032178033178034178035178036178037178038178039178040178041178042178043178044178045178046178047178048178049178050178051178052178053178054178055178056178057178058178059178060178061178062178063178064178065178066178067178068178069178070178071178072178073178074178075178076178077178078178079178080178081178082178083178084178085178086178087178088178089178090178091178092178093178094178095178096178097178098178099178100178101178102178103178104178105178106178107178108178109178110178111178112178113178114178115178116178117178118178119178120178121178122178123178124178125178126178127178128178129178130178131178132178133178134178135178136178137178138178139178140178141178142178143178144178145178146178147178148178149178150178151178152178153178154178155178156178157178158178159178160178161178162178163178164178165178166178167178168178169178170178171178172178173178174178175178176178177178178178179178180178181178182178183178184178185178186178187178188178189178190178191178192178193178194178195178196178197178198178199178200178201178202178203178204178205178206178207178208178209178210178211178212178213178214178215178216178217178218178219178220178221178222178223178224178225178226178227178228178229178230178231178232178233178234178235178236178237178238178239178240178241178242178243178244178245178246178247178248178249178250178251178252178253178254178255178256178257178258178259178260178261178262178263178264178265178266178267178268178269178270178271178272178273178274178275178276178277178278178279178280178281178282178283178284178285178286178287178288178289178290178291178292178293178294178295178296178297178298178299178300178301178302178303178304178305178306178307178308178309178310178311178312178313178314178315178316178317178318178319178320178321178322178323178324178325178326178327178328178329178330178331178332178333178334178335178336178337178338178339178340178341178342178343178344178345178346178347178348178349178350178351178352178353178354178355178356178357178358178359178360178361178362178363178364178365178366178367178368178369178370178371178372178373178374178375178376178377178378178379178380178381178382178383178384178385178386178387178388178389178390178391178392178393178394178395178396178397178398178399178400178401178402178403178404178405178406178407178408178409178410178411178412178413178414178415178416178417178418178419178420178421178422178423178424178425178426178427178428178429178430178431178432178433178434178435178436178437178438178439178440178441178442178443178444178445178446178447178448178449178450178451178452178453178454178455178456178457178458178459178460178461178462178463178464178465178466178467178468178469178470178471178472178473178474178475178476178477178478178479178480178481178482178483178484178485178486178487178488178489178490178491178492178493178494178495178496178497178498178499178500178501178502178503178504178505178506178507178508178509178510178511178512178513178514178515178516178517178518178519178520178521178522178523178524178525178526178527178528178529178530178531178532178533178534178535178536178537178538178539178540178541178542178543178544178545178546178547178548178549178550178551178552178553178554178555178556178557178558178559178560178561178562178563178564178565178566178567178568178569178570178571178572178573178574178575178576178577178578178579178580178581178582178583178584178585178586178587178588178589178590178591178592178593178594178595178596178597178598178599178600178601178602178603178604178605178606178607178608178609178610178611178612178613178614178615178616178617178618178619178620178621178622178623178624178625178626178627178628178629178630178631178632178633178634178635178636178637178638178639178640178641178642178643178644178645178646178647178648178649178650178651178652178653178654178655178656178657178658178659178660178661178662178663178664178665178666178667178668178669178670178671178672178673178674178675178676178677178678178679178680178681178682178683178684178685178686178687178688178689178690178691178692178693178694178695178696178697178698178699178700178701178702178703178704178705178706178707178708178709178710178711178712178713178714178715178716178717178718178719178720178721178722178723178724178725178726178727178728178729178730178731178732178733178734178735178736178737178738178739178740178741178742178743178744178745178746178747178748178749178750178751178752178753178754178755178756178757178758178759178760178761178762178763178764178765178766178767178768178769178770178771178772178773178774178775178776178777178778178779178780178781178782178783178784178785178786178787178788178789178790178791178792178793178794178795178796178797178798178799178800178801178802178803178804178805178806178807178808178809178810178811178812178813178814178815178816178817178818178819178820178821178822178823178824178825178826178827178828178829178830178831178832178833178834178835178836178837178838178839178840178841178842178843178844178845178846178847178848178849178850178851178852178853178854178855178856178857178858178859178860178861178862178863178864178865178866178867178868178869178870178871178872178873178874178875178876178877178878178879178880178881178882178883178884178885178886178887178888178889178890178891178892178893178894178895178896178897178898178899178900178901178902178903178904178905178906178907178908178909178910178911178912178913178914178915178916178917178918178919178920178921178922178923178924178925178926178927178928178929178930178931178932178933178934178935178936178937178938178939178940178941178942178943178944178945178946178947178948178949178950178951178952178953178954178955178956178957178958178959178960178961178962178963178964178965178966178967178968178969178970178971178972178973178974178975178976178977178978178979178980178981178982178983178984178985178986178987178988178989178990178991178992178993178994178995178996178997178998178999179000179001179002179003179004179005179006179007179008179009179010179011179012179013179014179015179016179017179018179019179020179021179022179023179024179025179026179027179028179029179030179031179032179033179034179035179036179037179038179039179040179041179042179043179044179045179046179047179048179049179050179051179052179053179054179055179056179057179058179059179060179061179062179063179064179065179066179067179068179069179070179071179072179073179074179075179076179077179078179079179080179081179082179083179084179085179086179087179088179089179090179091179092179093179094179095179096179097179098179099179100179101179102179103179104179105179106179107179108179109179110179111179112179113179114179115179116179117179118179119179120179121179122179123179124179125179126179127179128179129179130179131179132179133179134179135179136179137179138179139179140179141179142179143179144179145179146179147179148179149179150179151179152179153179154179155179156179157179158179159179160179161179162179163179164179165179166179167179168179169179170179171179172179173179174179175179176179177179178179179179180179181179182179183179184179185179186179187179188179189179190179191179192179193179194179195179196179197179198179199179200179201179202179203179204179205179206179207179208179209179210179211179212179213179214179215179216179217179218179219179220179221179222179223179224179225179226179227179228179229179230179231179232179233179234179235179236179237179238179239179240179241179242179243179244179245179246179247179248179249179250179251179252179253179254179255179256179257179258179259179260179261179262179263179264179265179266179267179268179269179270179271179272179273179274179275179276179277179278179279179280179281179282179283179284179285179286179287179288179289179290179291179292179293179294179295179296179297179298179299179300179301179302179303179304179305179306179307179308179309179310179311179312179313179314179315179316179317179318179319179320179321179322179323179324179325179326179327179328179329179330179331179332179333179334179335179336179337179338179339179340179341179342179343179344179345179346179347179348179349179350179351179352179353179354179355179356179357179358179359179360179361179362179363179364179365179366179367179368179369179370179371179372179373179374179375179376179377179378179379179380179381179382179383179384179385179386179387179388179389179390179391179392179393179394179395179396179397179398179399179400179401179402179403179404179405179406179407179408179409179410179411179412179413179414179415179416179417179418179419179420179421179422179423179424179425179426179427179428179429179430179431179432179433179434179435179436179437179438179439179440179441179442179443179444179445179446179447179448179449179450179451179452179453179454179455179456179457179458179459179460179461179462179463179464179465179466179467179468179469179470179471179472179473179474179475179476179477179478179479179480179481179482179483179484179485179486179487179488179489179490179491179492179493179494179495179496179497179498179499179500179501179502179503179504179505179506179507179508179509179510179511179512179513179514179515179516179517179518179519179520179521179522179523179524179525179526179527179528179529179530179531179532179533179534179535179536179537179538179539179540179541179542179543179544179545179546179547179548179549179550179551179552179553179554179555179556179557179558179559179560179561179562179563179564179565179566179567179568179569179570179571179572179573179574179575179576179577179578179579179580179581179582179583179584179585179586179587179588179589179590179591179592179593179594179595179596179597179598179599179600179601179602179603179604179605179606179607179608179609179610179611179612179613179614179615179616179617179618179619179620179621179622179623179624179625179626179627179628179629179630179631179632179633179634179635179636179637179638179639179640179641179642179643179644179645179646179647179648179649179650179651179652179653179654179655179656179657179658179659179660179661179662179663179664179665179666179667179668179669179670179671179672179673179674179675179676179677179678179679179680179681179682179683179684179685179686179687179688179689179690179691179692179693179694179695179696179697179698179699179700179701179702179703179704179705179706179707179708179709179710179711179712179713179714179715179716179717179718179719179720179721179722179723179724179725179726179727179728179729179730179731179732179733179734179735179736179737179738179739179740179741179742179743179744179745179746179747179748179749179750179751179752179753179754179755179756179757179758179759179760179761179762179763179764179765179766179767179768179769179770179771179772179773179774179775179776179777179778179779179780179781179782179783179784179785179786179787179788179789179790179791179792179793179794179795179796179797179798179799179800179801179802179803179804179805179806179807179808179809179810179811179812179813179814179815179816179817179818179819179820179821179822179823179824179825179826179827179828179829179830179831179832179833179834179835179836179837179838179839179840179841179842179843179844179845179846179847179848179849179850179851179852179853179854179855179856179857179858179859179860179861179862179863179864179865179866179867179868179869179870179871179872179873179874179875179876179877179878179879179880179881179882179883179884179885179886179887179888179889179890179891179892179893179894179895179896179897179898179899179900179901179902179903179904179905179906179907179908179909179910179911179912179913179914179915179916179917179918179919179920179921179922179923179924179925179926179927179928179929179930179931179932179933179934179935179936179937179938179939179940179941179942179943179944179945179946179947179948179949179950179951179952179953179954179955179956179957179958179959179960179961179962179963179964179965179966179967179968179969179970179971179972179973179974179975179976179977179978179979179980179981179982179983179984179985179986179987179988179989179990179991179992179993179994179995179996179997179998179999180000180001180002180003180004180005180006180007180008180009180010180011180012180013180014180015180016180017180018180019180020180021180022180023180024180025180026180027180028180029180030180031180032180033180034180035180036180037180038180039180040180041180042180043180044180045180046180047180048180049180050180051180052180053180054180055180056180057180058180059180060180061180062180063180064180065180066180067180068180069180070180071180072180073180074180075180076180077180078180079180080180081180082180083180084180085180086180087180088180089180090180091180092180093180094180095180096180097180098180099180100180101180102180103180104180105180106180107180108180109180110180111180112180113180114180115180116180117180118180119180120180121180122180123180124180125180126180127180128180129180130180131180132180133180134180135180136180137180138180139180140180141180142180143180144180145180146180147180148180149180150180151180152180153180154180155180156180157180158180159180160180161180162180163180164180165180166180167180168180169180170180171180172180173180174180175180176180177180178180179180180180181180182180183180184180185180186180187180188180189180190180191180192180193180194180195180196180197180198180199180200180201180202180203180204180205180206180207180208180209180210180211180212180213180214180215180216180217180218180219180220180221180222180223180224180225180226180227180228180229180230180231180232180233180234180235180236180237180238180239180240180241180242180243180244180245180246180247180248180249180250180251180252180253180254180255180256180257180258180259180260180261180262180263180264180265180266180267180268180269180270180271180272180273180274180275180276180277180278180279180280180281180282180283180284180285180286180287180288180289180290180291180292180293180294180295180296180297180298180299180300180301180302180303180304180305180306180307180308180309180310180311180312180313180314180315180316180317180318180319180320180321180322180323180324180325180326180327180328180329180330180331180332180333180334180335180336180337180338180339180340180341180342180343180344180345180346180347180348180349180350180351180352180353180354180355180356180357180358180359180360180361180362180363180364180365180366180367180368180369180370180371180372180373180374180375180376180377180378180379180380180381180382180383180384180385180386180387180388180389180390180391180392180393180394180395180396180397180398180399180400180401180402180403180404180405180406180407180408180409180410180411180412180413180414180415180416180417180418180419180420180421180422180423180424180425180426180427180428180429180430180431180432180433180434180435180436180437180438180439180440180441180442180443180444180445180446180447180448180449180450180451180452180453180454180455180456180457180458180459180460180461180462180463180464180465180466180467180468180469180470180471180472180473180474180475180476180477180478180479180480180481180482180483180484180485180486180487180488180489180490180491180492180493180494180495180496180497180498180499180500180501180502180503180504180505180506180507180508180509180510180511180512180513180514180515180516180517180518180519180520180521180522180523180524180525180526180527180528180529180530180531180532180533180534180535180536180537180538180539180540180541180542180543180544180545180546180547180548180549180550180551180552180553180554180555180556180557180558180559180560180561180562180563180564180565180566180567180568180569180570180571180572180573180574180575180576180577180578180579180580180581180582180583180584180585180586180587180588180589180590180591180592180593180594180595180596180597180598180599180600180601180602180603180604180605180606180607180608180609180610180611180612180613180614180615180616180617180618180619180620180621180622180623180624180625180626180627180628180629180630180631180632180633180634180635180636180637180638180639180640180641180642180643180644180645180646180647180648180649180650180651180652180653180654180655180656180657180658180659180660180661180662180663180664180665180666180667180668180669180670180671180672180673180674180675180676180677180678180679180680180681180682180683180684180685180686180687180688180689180690180691180692180693180694180695180696180697180698180699180700180701180702180703180704180705180706180707180708180709180710180711180712180713180714180715180716180717180718180719180720180721180722180723180724180725180726180727180728180729180730180731180732180733180734180735180736180737180738180739180740180741180742180743180744180745180746180747180748180749180750180751180752180753180754180755180756180757180758180759180760180761180762180763180764180765180766180767180768180769180770180771180772180773180774180775180776180777180778180779180780180781180782180783180784180785180786180787180788180789180790180791180792180793180794180795180796180797180798180799180800180801180802180803180804180805180806180807180808180809180810180811180812180813180814180815180816180817180818180819180820180821180822180823180824180825180826180827180828180829180830180831180832180833180834180835180836180837180838180839180840180841180842180843180844180845180846180847180848180849180850180851180852180853180854180855180856180857180858180859180860180861180862180863180864180865180866180867180868180869180870180871180872180873180874180875180876180877180878180879180880180881180882180883180884180885180886180887180888180889180890180891180892180893180894180895180896180897180898180899180900180901180902180903180904180905180906180907180908180909180910180911180912180913180914180915180916180917180918180919180920180921180922180923180924180925180926180927180928180929180930180931180932180933180934180935180936180937180938180939180940180941180942180943180944180945180946180947180948180949180950180951180952180953180954180955180956180957180958180959180960180961180962180963180964180965180966180967180968180969180970180971180972180973180974180975180976180977180978180979180980180981180982180983180984180985180986180987180988180989180990180991180992180993180994180995180996180997180998180999181000181001181002181003181004181005181006181007181008181009181010181011181012181013181014181015181016181017181018181019181020181021181022181023181024181025181026181027181028181029181030181031181032181033181034181035181036181037181038181039181040181041181042181043181044181045181046181047181048181049181050181051181052181053181054181055181056181057181058181059181060181061181062181063181064181065181066181067181068181069181070181071181072181073181074181075181076181077181078181079181080181081181082181083181084181085181086181087181088181089181090181091181092181093181094181095181096181097181098181099181100181101181102181103181104181105181106181107181108181109181110181111181112181113181114181115181116181117181118181119181120181121181122181123181124181125181126181127181128181129181130181131181132181133181134181135181136181137181138181139181140181141181142181143181144181145181146181147181148181149181150181151181152181153181154181155181156181157181158181159181160181161181162181163181164181165181166181167181168181169181170181171181172181173181174181175181176181177181178181179181180181181181182181183181184181185181186181187181188181189181190181191181192181193181194181195181196181197181198181199181200181201181202181203181204181205181206181207181208181209181210181211181212181213181214181215181216181217181218181219181220181221181222181223181224181225181226181227181228181229181230181231181232181233181234181235181236181237181238181239181240181241181242181243181244181245181246181247181248181249181250181251181252181253181254181255181256181257181258181259181260181261181262181263181264181265181266181267181268181269181270181271181272181273181274181275181276181277181278181279181280181281181282181283181284181285181286181287181288181289181290181291181292181293181294181295181296181297181298181299181300181301181302181303181304181305181306181307181308181309181310181311181312181313181314181315181316181317181318181319181320181321181322181323181324181325181326181327181328181329181330181331181332181333181334181335181336181337181338181339181340181341181342181343181344181345181346181347181348181349181350181351181352181353181354181355181356181357181358181359181360181361181362181363181364181365181366181367181368181369181370181371181372181373181374181375181376181377181378181379181380181381181382181383181384181385181386181387181388181389181390181391181392181393181394181395181396181397181398181399181400181401181402181403181404181405181406181407181408181409181410181411181412181413181414181415181416181417181418181419181420181421181422181423181424181425181426181427181428181429181430181431181432181433181434181435181436181437181438181439181440181441181442181443181444181445181446181447181448181449181450181451181452181453181454181455181456181457181458181459181460181461181462181463181464181465181466181467181468181469181470181471181472181473181474181475181476181477181478181479181480181481181482181483181484181485181486181487181488181489181490181491181492181493181494181495181496181497181498181499181500181501181502181503181504181505181506181507181508181509181510181511181512181513181514181515181516181517181518181519181520181521181522181523181524181525181526181527181528181529181530181531181532181533181534181535181536181537181538181539181540181541181542181543181544181545181546181547181548181549181550181551181552181553181554181555181556181557181558181559181560181561181562181563181564181565181566181567181568181569181570181571181572181573181574181575181576181577181578181579181580181581181582181583181584181585181586181587181588181589181590181591181592181593181594181595181596181597181598181599181600181601181602181603181604181605181606181607181608181609181610181611181612181613181614181615181616181617181618181619181620181621181622181623181624181625181626181627181628181629181630181631181632181633181634181635181636181637181638181639181640181641181642181643181644181645181646181647181648181649181650181651181652181653181654181655181656181657181658181659181660181661181662181663181664181665181666181667181668181669181670181671181672181673181674181675181676181677181678181679181680181681181682181683181684181685181686181687181688181689181690181691181692181693181694181695181696181697181698181699181700181701181702181703181704181705181706181707181708181709181710181711181712181713181714181715181716181717181718181719181720181721181722181723181724181725181726181727181728181729181730181731181732181733181734181735181736181737181738181739181740181741181742181743181744181745181746181747181748181749181750181751181752181753181754181755181756181757181758181759181760181761181762181763181764181765181766181767181768181769181770181771181772181773181774181775181776181777181778181779181780181781181782181783181784181785181786181787181788181789181790181791181792181793181794181795181796181797181798181799181800181801181802181803181804181805181806181807181808181809181810181811181812181813181814181815181816181817181818181819181820181821181822181823181824181825181826181827181828181829181830181831181832181833181834181835181836181837181838181839181840181841181842181843181844181845181846181847181848181849181850181851181852181853181854181855181856181857181858181859181860181861181862181863181864181865181866181867181868181869181870181871181872181873181874181875181876181877181878181879181880181881181882181883181884181885181886181887181888181889181890181891181892181893181894181895181896181897181898181899181900181901181902181903181904181905181906181907181908181909181910181911181912181913181914181915181916181917181918181919181920181921181922181923181924181925181926181927181928181929181930181931181932181933181934181935181936181937181938181939181940181941181942181943181944181945181946181947181948181949181950181951181952181953181954181955181956181957181958181959181960181961181962181963181964181965181966181967181968181969181970181971181972181973181974181975181976181977181978181979181980181981181982181983181984181985181986181987181988181989181990181991181992181993181994181995181996181997181998181999182000182001182002182003182004182005182006182007182008182009182010182011182012182013182014182015182016182017182018182019182020182021182022182023182024182025182026182027182028182029182030182031182032182033182034182035182036182037182038182039182040182041182042182043182044182045182046182047182048182049182050182051182052182053182054182055182056182057182058182059182060182061182062182063182064182065182066182067182068182069182070182071182072182073182074182075182076182077182078182079182080182081182082182083182084182085182086182087182088182089182090182091182092182093182094182095182096182097182098182099182100182101182102182103182104182105182106182107182108182109182110182111182112182113182114182115182116182117182118182119182120182121182122182123182124182125182126182127182128182129182130182131182132182133182134182135182136182137182138182139182140182141182142182143182144182145182146182147182148182149182150182151182152182153182154182155182156182157182158182159182160182161182162182163182164182165182166182167182168182169182170182171182172182173182174182175182176182177182178182179182180182181182182182183182184182185182186182187182188182189182190182191182192182193182194182195182196182197182198182199182200182201182202182203182204182205182206182207182208182209182210182211182212182213182214182215182216182217182218182219182220182221182222182223182224182225182226182227182228182229182230182231182232182233182234182235182236182237182238182239182240182241182242182243182244182245182246182247182248182249182250182251182252182253182254182255182256182257182258182259182260182261182262182263182264182265182266182267182268182269182270182271182272182273182274182275182276182277182278182279182280182281182282182283182284182285182286182287182288182289182290182291182292182293182294182295182296182297182298182299182300182301182302182303182304182305182306182307182308182309182310182311182312182313182314182315182316182317182318182319182320182321182322182323182324182325182326182327182328182329182330182331182332182333182334182335182336182337182338182339182340182341182342182343182344182345182346182347182348182349182350182351182352182353182354182355182356182357182358182359182360182361182362182363182364182365182366182367182368182369182370182371182372182373182374182375182376182377182378182379182380182381182382182383182384182385182386182387182388182389182390182391182392182393182394182395182396182397182398182399182400182401182402182403182404182405182406182407182408182409182410182411182412182413182414182415182416182417182418182419182420182421182422182423182424182425182426182427182428182429182430182431182432182433182434182435182436182437182438182439182440182441182442182443182444182445182446182447182448182449182450182451182452182453182454182455182456182457182458182459182460182461182462182463182464182465182466182467182468182469182470182471182472182473182474182475182476182477182478182479182480182481182482182483182484182485182486182487182488182489182490182491182492182493182494182495182496182497182498182499182500182501182502182503182504182505182506182507182508182509182510182511182512182513182514182515182516182517182518182519182520182521182522182523182524182525182526182527182528182529182530182531182532182533182534182535182536182537182538182539182540182541182542182543182544182545182546182547182548182549182550182551182552182553182554182555182556182557182558182559182560182561182562182563182564182565182566182567182568182569182570182571182572182573182574182575182576182577182578182579182580182581182582182583182584182585182586182587182588182589182590182591182592182593182594182595182596182597182598182599182600182601182602182603182604182605182606182607182608182609182610182611182612182613182614182615182616182617182618182619182620182621182622182623182624182625182626182627182628182629182630182631182632182633182634182635182636182637182638182639182640182641182642182643182644182645182646182647182648182649182650182651182652182653182654182655182656182657182658182659182660182661182662182663182664182665182666182667182668182669182670182671182672182673182674182675182676182677182678182679182680182681182682182683182684182685182686182687182688182689182690182691182692182693182694182695182696182697182698182699182700182701182702182703182704182705182706182707182708182709182710182711182712182713182714182715182716182717182718182719182720182721182722182723182724182725182726182727182728182729182730182731182732182733182734182735182736182737182738182739182740182741182742182743182744182745182746182747182748182749182750182751182752182753182754182755182756182757182758182759182760182761182762182763182764182765182766182767182768182769182770182771182772182773182774182775182776182777182778182779182780182781182782182783182784182785182786182787182788182789182790182791182792182793182794182795182796182797182798182799182800182801182802182803182804182805182806182807182808182809182810182811182812182813182814182815182816182817182818182819182820182821182822182823182824182825182826182827182828182829182830182831182832182833182834182835182836182837182838182839182840182841182842182843182844182845182846182847182848182849182850182851182852182853182854182855182856182857182858182859182860182861182862182863182864182865182866182867182868182869182870182871182872182873182874182875182876182877182878182879182880182881182882182883182884182885182886182887182888182889182890182891182892182893182894182895182896182897182898182899182900182901182902182903182904182905182906182907182908182909182910182911182912182913182914182915182916182917182918182919182920182921182922182923182924182925182926182927182928182929182930182931182932182933182934182935182936182937182938182939182940182941182942182943182944182945182946182947182948182949182950182951182952182953182954182955182956182957182958182959182960182961182962182963182964182965182966182967182968182969182970182971182972182973182974182975182976182977182978182979182980182981182982182983182984182985182986182987182988182989182990182991182992182993182994182995182996182997182998182999183000183001183002183003183004183005183006183007183008183009183010183011183012183013183014183015183016183017183018183019183020183021183022183023183024183025183026183027183028183029183030183031183032183033183034183035183036183037183038183039183040183041183042183043183044183045183046183047183048183049183050183051183052183053183054183055183056183057183058183059183060183061183062183063183064183065183066183067183068183069183070183071183072183073183074183075183076183077183078183079183080183081183082183083183084183085183086183087183088183089183090183091183092183093183094183095183096183097183098183099183100183101183102183103183104183105183106183107183108183109183110183111183112183113183114183115183116183117183118183119183120183121183122183123183124183125183126183127183128183129183130183131183132183133183134183135183136183137183138183139183140183141183142183143183144183145183146183147183148183149183150183151183152183153183154183155183156183157183158183159183160183161183162183163183164183165183166183167183168183169183170183171183172183173183174183175183176183177183178183179183180183181183182183183183184183185183186183187183188183189183190183191183192183193183194183195183196183197183198183199183200183201183202183203183204183205183206183207183208183209183210183211183212183213183214183215183216183217183218183219183220183221183222183223183224183225183226183227183228183229183230183231183232183233183234183235183236183237183238183239183240183241183242183243183244183245183246183247183248183249183250183251183252183253183254183255183256183257183258183259183260183261183262183263183264183265183266183267183268183269183270183271183272183273183274183275183276183277183278183279183280183281183282183283183284183285183286183287183288183289183290183291183292183293183294183295183296183297183298183299183300183301183302183303183304183305183306183307183308183309183310183311183312183313183314183315183316183317183318183319183320183321183322183323183324183325183326183327183328183329183330183331183332183333183334183335183336183337183338183339183340183341183342183343183344183345183346183347183348183349183350183351183352183353183354183355183356183357183358183359183360183361183362183363183364183365183366183367183368183369183370183371183372183373183374183375183376183377183378183379183380183381183382183383183384183385183386183387183388183389183390183391183392183393183394183395183396183397183398183399183400183401183402183403183404183405183406183407183408183409183410183411183412183413183414183415183416183417183418183419183420183421183422183423183424183425183426183427183428183429183430183431183432183433183434183435183436183437183438183439183440183441183442183443183444183445183446183447183448183449183450183451183452183453183454183455183456183457183458183459183460183461183462183463183464183465183466183467183468183469183470183471183472183473183474183475183476183477183478183479183480183481183482183483183484183485183486183487183488183489183490183491183492183493183494183495183496183497183498183499183500183501183502183503183504183505183506183507183508183509183510183511183512183513183514183515183516183517183518183519183520183521183522183523183524183525183526183527183528183529183530183531183532183533183534183535183536183537183538183539183540183541183542183543183544183545183546183547183548183549183550183551183552183553183554183555183556183557183558183559183560183561183562183563183564183565183566183567183568183569183570183571183572183573183574183575183576183577183578183579183580183581183582183583183584183585183586183587183588183589183590183591183592183593183594183595183596183597183598183599183600183601183602183603183604183605183606183607183608183609183610183611183612183613183614183615183616183617183618183619183620183621183622183623183624183625183626183627183628183629183630183631183632183633183634183635183636183637183638183639183640183641183642183643183644183645183646183647183648183649183650183651183652183653183654183655183656183657183658183659183660183661183662183663183664183665183666183667183668183669183670183671183672183673183674183675183676183677183678183679183680183681183682183683183684183685183686183687183688183689183690183691183692183693183694183695183696183697183698183699183700183701183702183703183704183705183706183707183708183709183710183711183712183713183714183715183716183717183718183719183720183721183722183723183724183725183726183727183728183729183730183731183732183733183734183735183736183737183738183739183740183741183742183743183744183745183746183747183748183749183750183751183752183753183754183755183756183757183758183759183760183761183762183763183764183765183766183767183768183769183770183771183772183773183774183775183776183777183778183779183780183781183782183783183784183785183786183787183788183789183790183791183792183793183794183795183796183797183798183799183800183801183802183803183804183805183806183807183808183809183810183811183812183813183814183815183816183817183818183819183820183821183822183823183824183825183826183827183828183829183830183831183832183833183834183835183836183837183838183839183840183841183842183843183844183845183846183847183848183849183850183851183852183853183854183855183856183857183858183859183860183861183862183863183864183865183866183867183868183869183870183871183872183873183874183875183876183877183878183879183880183881183882183883183884183885183886183887183888183889183890183891183892183893183894183895183896183897183898183899183900183901183902183903183904183905183906183907183908183909183910183911183912183913183914183915183916183917183918183919183920183921183922183923183924183925183926183927183928183929183930183931183932183933183934183935183936183937183938183939183940183941183942183943183944183945183946183947183948183949183950183951183952183953183954183955183956183957183958183959183960183961183962183963183964183965183966183967183968183969183970183971183972183973183974183975183976183977183978183979183980183981183982183983183984183985183986183987183988183989183990183991183992183993183994183995183996183997183998183999184000184001184002184003184004184005184006184007184008184009184010184011184012184013184014184015184016184017184018184019184020184021184022184023184024184025184026184027184028184029184030184031184032184033184034184035184036184037184038184039184040184041184042184043184044184045184046184047184048184049184050184051184052184053184054184055184056184057184058184059184060184061184062184063184064184065184066184067184068184069184070184071184072184073184074184075184076184077184078184079184080184081184082184083184084184085184086184087184088184089184090184091184092184093184094184095184096184097184098184099184100184101184102184103184104184105184106184107184108184109184110184111184112184113184114184115184116184117184118184119184120184121184122184123184124184125184126184127184128184129184130184131184132184133184134184135184136184137184138184139184140184141184142184143184144184145184146184147184148184149184150184151184152184153184154184155184156184157184158184159184160184161184162184163184164184165184166184167184168184169184170184171184172184173184174184175184176184177184178184179184180184181184182184183184184184185184186184187184188184189184190184191184192184193184194184195184196184197184198184199184200184201184202184203184204184205184206184207184208184209184210184211184212184213184214184215184216184217184218184219184220184221184222184223184224184225184226184227184228184229184230184231184232184233184234184235184236184237184238184239184240184241184242184243184244184245184246184247184248184249184250184251184252184253184254184255184256184257184258184259184260184261184262184263184264184265184266184267184268184269184270184271184272184273184274184275184276184277184278184279184280184281184282184283184284184285184286184287184288184289184290184291184292184293184294184295184296184297184298184299184300184301184302184303184304184305184306184307184308184309184310184311184312184313184314184315184316184317184318184319184320184321184322184323184324184325184326184327184328184329184330184331184332184333184334184335184336184337184338184339184340184341184342184343184344184345184346184347184348184349184350184351184352184353184354184355184356184357184358184359184360184361184362184363184364184365184366184367184368184369184370184371184372184373184374184375184376184377184378184379184380184381184382184383184384184385184386184387184388184389184390184391184392184393184394184395184396184397184398184399184400184401184402184403184404184405184406184407184408184409184410184411184412184413184414184415184416184417184418184419184420184421184422184423184424184425184426184427184428184429184430184431184432184433184434184435184436184437184438184439184440184441184442184443184444184445184446184447184448184449184450184451184452184453184454184455184456184457184458184459184460184461184462184463184464184465184466184467184468184469184470184471184472184473184474184475184476184477184478184479184480184481184482184483184484184485184486184487184488184489184490184491184492184493184494184495184496184497184498184499184500184501184502184503184504184505184506184507184508184509184510184511184512184513184514184515184516184517184518184519184520184521184522184523184524184525184526184527184528184529184530184531184532184533184534184535184536184537184538184539184540184541184542184543184544184545184546184547184548184549184550184551184552184553184554184555184556184557184558184559184560184561184562184563184564184565184566184567184568184569184570184571184572184573184574184575184576184577184578184579184580184581184582184583184584184585184586184587184588184589184590184591184592184593184594184595184596184597184598184599184600184601184602184603184604184605184606184607184608184609184610184611184612184613184614184615184616184617184618184619184620184621184622184623184624184625184626184627184628184629184630184631184632184633184634184635184636184637184638184639184640184641184642184643184644184645184646184647184648184649184650184651184652184653184654184655184656184657184658184659184660184661184662184663184664184665184666184667184668184669184670184671184672184673184674184675184676184677184678184679184680184681184682184683184684184685184686184687184688184689184690184691184692184693184694184695184696184697184698184699184700184701184702184703184704184705184706184707184708184709184710184711184712184713184714184715184716184717184718184719184720184721184722184723184724184725184726184727184728184729184730184731184732184733184734184735184736184737184738184739184740184741184742184743184744184745184746184747184748184749184750184751184752184753184754184755184756184757184758184759184760184761184762184763184764184765184766184767184768184769184770184771184772184773184774184775184776184777184778184779184780184781184782184783184784184785184786184787184788184789184790184791184792184793184794184795184796184797184798184799184800184801184802184803184804184805184806184807184808184809184810184811184812184813184814184815184816184817184818184819184820184821184822184823184824184825184826184827184828184829184830184831184832184833184834184835184836184837184838184839184840184841184842184843184844184845184846184847184848184849184850184851184852184853184854184855184856184857184858184859184860184861184862184863184864184865184866184867184868184869184870184871184872184873184874184875184876184877184878184879184880184881184882184883184884184885184886184887184888184889184890184891184892184893184894184895184896184897184898184899184900184901184902184903184904184905184906184907184908184909184910184911184912184913184914184915184916184917184918184919184920184921184922184923184924184925184926184927184928184929184930184931184932184933184934184935184936184937184938184939184940184941184942184943184944184945184946184947184948184949184950184951184952184953184954184955184956184957184958184959184960184961184962184963184964184965184966184967184968184969184970184971184972184973184974184975184976184977184978184979184980184981184982184983184984184985184986184987184988184989184990184991184992184993184994184995184996184997184998184999185000185001185002185003185004185005185006185007185008185009185010185011185012185013185014185015185016185017185018185019185020185021185022185023185024185025185026185027185028185029185030185031185032185033185034185035185036185037185038185039185040185041185042185043185044185045185046185047185048185049185050185051185052185053185054185055185056185057185058185059185060185061185062185063185064185065185066185067185068185069185070185071185072185073185074185075185076185077185078185079185080185081185082185083185084185085185086185087185088185089185090185091185092185093185094185095185096185097185098185099185100185101185102185103185104185105185106185107185108185109185110185111185112185113185114185115185116185117185118185119185120185121185122185123185124185125185126185127185128185129185130185131185132185133185134185135185136185137185138185139185140185141185142185143185144185145185146185147185148185149185150185151185152185153185154185155185156185157185158185159185160185161185162185163185164185165185166185167185168185169185170185171185172185173185174185175185176185177185178185179185180185181185182185183185184185185185186185187185188185189185190185191185192185193185194185195185196185197185198185199185200185201185202185203185204185205185206185207185208185209185210185211185212185213185214185215185216185217185218185219185220185221185222185223185224185225185226185227185228185229185230185231185232185233185234185235185236185237185238185239185240185241185242185243185244185245185246185247185248185249185250185251185252185253185254185255185256185257185258185259185260185261185262185263185264185265185266185267185268185269185270185271185272185273185274185275185276185277185278185279185280185281185282185283185284185285185286185287185288185289185290185291185292185293185294185295185296185297185298185299185300185301185302185303185304185305185306185307185308185309185310185311185312185313185314185315185316185317185318185319185320185321185322185323185324185325185326185327185328185329185330185331185332185333185334185335185336185337185338185339185340185341185342185343185344185345185346185347185348185349185350185351185352185353185354185355185356185357185358185359185360185361185362185363185364185365185366185367185368185369185370185371185372185373185374185375185376185377185378185379185380185381185382185383185384185385185386185387185388185389185390185391185392185393185394185395185396185397185398185399185400185401185402185403185404185405185406185407185408185409185410185411185412185413185414185415185416185417185418185419185420185421185422185423185424185425185426185427185428185429185430185431185432185433185434185435185436185437185438185439185440185441185442185443185444185445185446185447185448185449185450185451185452185453185454185455185456185457185458185459185460185461185462185463185464185465185466185467185468185469185470185471185472185473185474185475185476185477185478185479185480185481185482185483185484185485185486185487185488185489185490185491185492185493185494185495185496185497185498185499185500185501185502185503185504185505185506185507185508185509185510185511185512185513185514185515185516185517185518185519185520185521185522185523185524185525185526185527185528185529185530185531185532185533185534185535185536185537185538185539185540185541185542185543185544185545185546185547185548185549185550185551185552185553185554185555185556185557185558185559185560185561185562185563185564185565185566185567185568185569185570185571185572185573185574185575185576185577185578185579185580185581185582185583185584185585185586185587185588185589185590185591185592185593185594185595185596185597185598185599185600185601185602185603185604185605185606185607185608185609185610185611185612185613185614185615185616185617185618185619185620185621185622185623185624185625185626185627185628185629185630185631185632185633185634185635185636185637185638185639185640185641185642185643185644185645185646185647185648185649185650185651185652185653185654185655185656185657185658185659185660185661185662185663185664185665185666185667185668185669185670185671185672185673185674185675185676185677185678185679185680185681185682185683185684185685185686185687185688185689185690185691185692185693185694185695185696185697185698185699185700185701185702185703185704185705185706185707185708185709185710185711185712185713185714185715185716185717185718185719185720185721185722185723185724185725185726185727185728185729185730185731185732185733185734185735185736185737185738185739185740185741185742185743185744185745185746185747185748185749185750185751185752185753185754185755185756185757185758185759185760185761185762185763185764185765185766185767185768185769185770185771185772185773185774185775185776185777185778185779185780185781185782185783185784185785185786185787185788185789185790185791185792185793185794185795185796185797185798185799185800185801185802185803185804185805185806185807185808185809185810185811185812185813185814185815185816185817185818185819185820185821185822185823185824185825185826185827185828185829185830185831185832185833185834185835185836185837185838185839185840185841185842185843185844185845185846185847185848185849185850185851185852185853185854185855185856185857185858185859185860185861185862185863185864185865185866185867185868185869185870185871185872185873185874185875185876185877185878185879185880185881185882185883185884185885185886185887185888185889185890185891185892185893185894185895185896185897185898185899185900185901185902185903185904185905185906185907185908185909185910185911185912185913185914185915185916185917185918185919185920185921185922185923185924185925185926185927185928185929185930185931185932185933185934185935185936185937185938185939185940185941185942185943185944185945185946185947185948185949185950185951185952185953185954185955185956185957185958185959185960185961185962185963185964185965185966185967185968185969185970185971185972185973185974185975185976185977185978185979185980185981185982185983185984185985185986185987185988185989185990185991185992185993185994185995185996185997185998185999186000186001186002186003186004186005186006186007186008186009186010186011186012186013186014186015186016186017186018186019186020186021186022186023186024186025186026186027186028186029186030186031186032186033186034186035186036186037186038186039186040186041186042186043186044186045186046186047186048186049186050186051186052186053186054186055186056186057186058186059186060186061186062186063186064186065186066186067186068186069186070186071186072186073186074186075186076186077186078186079186080186081186082186083186084186085186086186087186088186089186090186091186092186093186094186095186096186097186098186099186100186101186102186103186104186105186106186107186108186109186110186111186112186113186114186115186116186117186118186119186120186121186122186123186124186125186126186127186128186129186130186131186132186133186134186135186136186137186138186139186140186141186142186143186144186145186146186147186148186149186150186151186152186153186154186155186156186157186158186159186160186161186162186163186164186165186166186167186168186169186170186171186172186173186174186175186176186177186178186179186180186181186182186183186184186185186186186187186188186189186190186191186192186193186194186195186196186197186198186199186200186201186202186203186204186205186206186207186208186209186210186211186212186213186214186215186216186217186218186219186220186221186222186223186224186225186226186227186228186229186230186231186232186233186234186235186236186237186238186239186240186241186242186243186244186245186246186247186248186249186250186251186252186253186254186255186256186257186258186259186260186261186262186263186264186265186266186267186268186269186270186271186272186273186274186275186276186277186278186279186280186281186282186283186284186285186286186287186288186289186290186291186292186293186294186295186296186297186298186299186300186301186302186303186304186305186306186307186308186309186310186311186312186313186314186315186316186317186318186319186320186321186322186323186324186325186326186327186328186329186330186331186332186333186334186335186336186337186338186339186340186341186342186343186344186345186346186347186348186349186350186351186352186353186354186355186356186357186358186359186360186361186362186363186364186365186366186367186368186369186370186371186372186373186374186375186376186377186378186379186380186381186382186383186384186385186386186387186388186389186390186391186392186393186394186395186396186397186398186399186400186401186402186403186404186405186406186407186408186409186410186411186412186413186414186415186416186417186418186419186420186421186422186423186424186425186426186427186428186429186430186431186432186433186434186435186436186437186438186439186440186441186442186443186444186445186446186447186448186449186450186451186452186453186454186455186456186457186458186459186460186461186462186463186464186465186466186467186468186469186470186471186472186473186474186475186476186477186478186479186480186481186482186483186484186485186486186487186488186489186490186491186492186493186494186495186496186497186498186499186500186501186502186503186504186505186506186507186508186509186510186511186512186513186514186515186516186517186518186519186520186521186522186523186524186525186526186527186528186529186530186531186532186533186534186535186536186537186538186539186540186541186542186543186544186545186546186547186548186549186550186551186552186553186554186555186556186557186558186559186560186561186562186563186564186565186566186567186568186569186570186571186572186573186574186575186576186577186578186579186580186581186582186583186584186585186586186587186588186589186590186591186592186593186594186595186596186597186598186599186600186601186602186603186604186605186606186607186608186609186610186611186612186613186614186615186616186617186618186619186620186621186622186623186624186625186626186627186628186629186630186631186632186633186634186635186636186637186638186639186640186641186642186643186644186645186646186647186648186649186650186651186652186653186654186655186656186657186658186659186660186661186662186663186664186665186666186667186668186669186670186671186672186673186674186675186676186677186678186679186680186681186682186683186684186685186686186687186688186689186690186691186692186693186694186695186696186697186698186699186700186701186702186703186704186705186706186707186708186709186710186711186712186713186714186715186716186717186718186719186720186721186722186723186724186725186726186727186728186729186730186731186732186733186734186735186736186737186738186739186740186741186742186743186744186745186746186747186748186749186750186751186752186753186754186755186756186757186758186759186760186761186762186763186764186765186766186767186768186769186770186771186772186773186774186775186776186777186778186779186780186781186782186783186784186785186786186787186788186789186790186791186792186793186794186795186796186797186798186799186800186801186802186803186804186805186806186807186808186809186810186811186812186813186814186815186816186817186818186819186820186821186822186823186824186825186826186827186828186829186830186831186832186833186834186835186836186837186838186839186840186841186842186843186844186845186846186847186848186849186850186851186852186853186854186855186856186857186858186859186860186861186862186863186864186865186866186867186868186869186870186871186872186873186874186875186876186877186878186879186880186881186882186883186884186885186886186887186888186889186890186891186892186893186894186895186896186897186898186899186900186901186902186903186904186905186906186907186908186909186910186911186912186913186914186915186916186917186918186919186920186921186922186923186924186925186926186927186928186929186930186931186932186933186934186935186936186937186938186939186940186941186942186943186944186945186946186947186948186949186950186951186952186953186954186955186956186957186958186959186960186961186962186963186964186965186966186967186968186969186970186971186972186973186974186975186976186977186978186979186980186981186982186983186984186985186986186987186988186989186990186991186992186993186994186995186996186997186998186999187000187001187002187003187004187005187006187007187008187009187010187011187012187013187014187015187016187017187018187019187020187021187022187023187024187025187026187027187028187029187030187031187032187033187034187035187036187037187038187039187040187041187042187043187044187045187046187047187048187049187050187051187052187053187054187055187056187057187058187059187060187061187062187063187064187065187066187067187068187069187070187071187072187073187074187075187076187077187078187079187080187081187082187083187084187085187086187087187088187089187090187091187092187093187094187095187096187097187098187099187100187101187102187103187104187105187106187107187108187109187110187111187112187113187114187115187116187117187118187119187120187121187122187123187124187125187126187127187128187129187130187131187132187133187134187135187136187137187138187139187140187141187142187143187144187145187146187147187148187149187150187151187152187153187154187155187156187157187158187159187160187161187162187163187164187165187166187167187168187169187170187171187172187173187174187175187176187177187178187179187180187181187182187183187184187185187186187187187188187189187190187191187192187193187194187195187196187197187198187199187200187201187202187203187204187205187206187207187208187209187210187211187212187213187214187215187216187217187218187219187220187221187222187223187224187225187226187227187228187229187230187231187232187233187234187235187236187237187238187239187240187241187242187243187244187245187246187247187248187249187250187251187252187253187254187255187256187257187258187259187260187261187262187263187264187265187266187267187268187269187270187271187272187273187274187275187276187277187278187279187280187281187282187283187284187285187286187287187288187289187290187291187292187293187294187295187296187297187298187299187300187301187302187303187304187305187306187307187308187309187310187311187312187313187314187315187316187317187318187319187320187321187322187323187324187325187326187327187328187329187330187331187332187333187334187335187336187337187338187339187340187341187342187343187344187345187346187347187348187349187350187351187352187353187354187355187356187357187358187359187360187361187362187363187364187365187366187367187368187369187370187371187372187373187374187375187376187377187378187379187380187381187382187383187384187385187386187387187388187389187390187391187392187393187394187395187396187397187398187399187400187401187402187403187404187405187406187407187408187409187410187411187412187413187414187415187416187417187418187419187420187421187422187423187424187425187426187427187428187429187430187431187432187433187434187435187436187437187438187439187440187441187442187443187444187445187446187447187448187449187450187451187452187453187454187455187456187457187458187459187460187461187462187463187464187465187466187467187468187469187470187471187472187473187474187475187476187477187478187479187480187481187482187483187484187485187486187487187488187489187490187491187492187493187494187495187496187497187498187499187500187501187502187503187504187505187506187507187508187509187510187511187512187513187514187515187516187517187518187519187520187521187522187523187524187525187526187527187528187529187530187531187532187533187534187535187536187537187538187539187540187541187542187543187544187545187546187547187548187549187550187551187552187553187554187555187556187557187558187559187560187561187562187563187564187565187566187567187568187569187570187571187572187573187574187575187576187577187578187579187580187581187582187583187584187585187586187587187588187589187590187591187592187593187594187595187596187597187598187599187600187601187602187603187604187605187606187607187608187609187610187611187612187613187614187615187616187617187618187619187620187621187622187623187624187625187626187627187628187629187630187631187632187633187634187635187636187637187638187639187640187641187642187643187644187645187646187647187648187649187650187651187652187653187654187655187656187657187658187659187660187661187662187663187664187665187666187667187668187669187670187671187672187673187674187675187676187677187678187679187680187681187682187683187684187685187686187687187688187689187690187691187692187693187694187695187696187697187698187699187700187701187702187703187704187705187706187707187708187709187710187711187712187713187714187715187716187717187718187719187720187721187722187723187724187725187726187727187728187729187730187731187732187733187734187735187736187737187738187739187740187741187742187743187744187745187746187747187748187749187750187751187752187753187754187755187756187757187758187759187760187761187762187763187764187765187766187767187768187769187770187771187772187773187774187775187776187777187778187779187780187781187782187783187784187785187786187787187788187789187790187791187792187793187794187795187796187797187798187799187800187801187802187803187804187805187806187807187808187809187810187811187812187813187814187815187816187817187818187819187820187821187822187823187824187825187826187827187828187829187830187831187832187833187834187835187836187837187838187839187840187841187842187843187844187845187846187847187848187849187850187851187852187853187854187855187856187857187858187859187860187861187862187863187864187865187866187867187868187869187870187871187872187873187874187875187876187877187878187879187880187881187882187883187884187885187886187887187888187889187890187891187892187893187894187895187896187897187898187899187900187901187902187903187904187905187906187907187908187909187910187911187912187913187914187915187916187917187918187919187920187921187922187923187924187925187926187927187928187929187930187931187932187933187934187935187936187937187938187939187940187941187942187943187944187945187946187947187948187949187950187951187952187953187954187955187956187957187958187959187960187961187962187963187964187965187966187967187968187969187970187971187972187973187974187975187976187977187978187979187980187981187982187983187984187985187986187987187988187989187990187991187992187993187994187995187996187997187998187999188000188001188002188003188004188005188006188007188008188009188010188011188012188013188014188015188016188017188018188019188020188021188022188023188024188025188026188027188028188029188030188031188032188033188034188035188036188037188038188039188040188041188042188043188044188045188046188047188048188049188050188051188052188053188054188055188056188057188058188059188060188061188062188063188064188065188066188067188068188069188070188071188072188073188074188075188076188077188078188079188080188081188082188083188084188085188086188087188088188089188090188091188092188093188094188095188096188097188098188099188100188101188102188103188104188105188106188107188108188109188110188111188112188113188114188115188116188117188118188119188120188121188122188123188124188125188126188127188128188129188130188131188132188133188134188135188136188137188138188139188140188141188142188143188144188145188146188147188148188149188150188151188152188153188154188155188156188157188158188159188160188161188162188163188164188165188166188167188168188169188170188171188172188173188174188175188176188177188178188179188180188181188182188183188184188185188186188187188188188189188190188191188192188193188194188195188196188197188198188199188200188201188202188203188204188205188206188207188208188209188210188211188212188213188214188215188216188217188218188219188220188221188222188223188224188225188226188227188228188229188230188231188232188233188234188235188236188237188238188239188240188241188242188243188244188245188246188247188248188249188250188251188252188253188254188255188256188257188258188259188260188261188262188263188264188265188266188267188268188269188270188271188272188273188274188275188276188277188278188279188280188281188282188283188284188285188286188287188288188289188290188291188292188293188294188295188296188297188298188299188300188301188302188303188304188305188306188307188308188309188310188311188312188313188314188315188316188317188318188319188320188321188322188323188324188325188326188327188328188329188330188331188332188333188334188335188336188337188338188339188340188341188342188343188344188345188346188347188348188349188350188351188352188353188354188355188356188357188358188359188360188361188362188363188364188365188366188367188368188369188370188371188372188373188374188375188376188377188378188379188380188381188382188383188384188385188386188387188388188389188390188391188392188393188394188395188396188397188398188399188400188401188402188403188404188405188406188407188408188409188410188411188412188413188414188415188416188417188418188419188420188421188422188423188424188425188426188427188428188429188430188431188432188433188434188435188436188437188438188439188440188441188442188443188444188445188446188447188448188449188450188451188452188453188454188455188456188457188458188459188460188461188462188463188464188465188466188467188468188469188470188471188472188473188474188475188476188477188478188479188480188481188482188483188484188485188486188487188488188489188490188491188492188493188494188495188496188497188498188499188500188501188502188503188504188505188506188507188508188509188510188511188512188513188514188515188516188517188518188519188520188521188522188523188524188525188526188527188528188529188530188531188532188533188534188535188536188537188538188539188540188541188542188543188544188545188546188547188548188549188550188551188552188553188554188555188556188557188558188559188560188561188562188563188564188565188566188567188568188569188570188571188572188573188574188575188576188577188578188579188580188581188582188583188584188585188586188587188588188589188590188591188592188593188594188595188596188597188598188599188600188601188602188603188604188605188606188607188608188609188610188611188612188613188614188615188616188617188618188619188620188621188622188623188624188625188626188627188628188629188630188631188632188633188634188635188636188637188638188639188640188641188642188643188644188645188646188647188648188649188650188651188652188653188654188655188656188657188658188659188660188661188662188663188664188665188666188667188668188669188670188671188672188673188674188675188676188677188678188679188680188681188682188683188684188685188686188687188688188689188690188691188692188693188694188695188696188697188698188699188700188701188702188703188704188705188706188707188708188709188710188711188712188713188714188715188716188717188718188719188720188721188722188723188724188725188726188727188728188729188730188731188732188733188734188735188736188737188738188739188740188741188742188743188744188745188746188747188748188749188750188751188752188753188754188755188756188757188758188759188760188761188762188763188764188765188766188767188768188769188770188771188772188773188774188775188776188777188778188779188780188781188782188783188784188785188786188787188788188789188790188791188792188793188794188795188796188797188798188799188800188801188802188803188804188805188806188807188808188809188810188811188812188813188814188815188816188817188818188819188820188821188822188823188824188825188826188827188828188829188830188831188832188833188834188835188836188837188838188839188840188841188842188843188844188845188846188847188848188849188850188851188852188853188854188855188856188857188858188859188860188861188862188863188864188865188866188867188868188869188870188871188872188873188874188875188876188877188878188879188880188881188882188883188884188885188886188887188888188889188890188891188892188893188894188895188896188897188898188899188900188901188902188903188904188905188906188907188908188909188910188911188912188913188914188915188916188917188918188919188920188921188922188923188924188925188926188927188928188929188930188931188932188933188934188935188936188937188938188939188940188941188942188943188944188945188946188947188948188949188950188951188952188953188954188955188956188957188958188959188960188961188962188963188964188965188966188967188968188969188970188971188972188973188974188975188976188977188978188979188980188981188982188983188984188985188986188987188988188989188990188991188992188993188994188995188996188997188998188999189000189001189002189003189004189005189006189007189008189009189010189011189012189013189014189015189016189017189018189019189020189021189022189023189024189025189026189027189028189029189030189031189032189033189034189035189036189037189038189039189040189041189042189043189044189045189046189047189048189049189050189051189052189053189054189055189056189057189058189059189060189061189062189063189064189065189066189067189068189069189070189071189072189073189074189075189076189077189078189079189080189081189082189083189084189085189086189087189088189089189090189091189092189093189094189095189096189097189098189099189100189101189102189103189104189105189106189107189108189109189110189111189112189113189114189115189116189117189118189119189120189121189122189123189124189125189126189127189128189129189130189131189132189133189134189135189136189137189138189139189140189141189142189143189144189145189146189147189148189149189150189151189152189153189154189155189156189157189158189159189160189161189162189163189164189165189166189167189168189169189170189171189172189173189174189175189176189177189178189179189180189181189182189183189184189185189186189187189188189189189190189191189192189193189194189195189196189197189198189199189200189201189202189203189204189205189206189207189208189209189210189211189212189213189214189215189216189217189218189219189220189221189222189223189224189225189226189227189228189229189230189231189232189233189234189235189236189237189238189239189240189241189242189243189244189245189246189247189248189249189250189251189252189253189254189255189256189257189258189259189260189261189262189263189264189265189266189267189268189269189270189271189272189273189274189275189276189277189278189279189280189281189282189283189284189285189286189287189288189289189290189291189292189293189294189295189296189297189298189299189300189301189302189303189304189305189306189307189308189309189310189311189312189313189314189315189316189317189318189319189320189321189322189323189324189325189326189327189328189329189330189331189332189333189334189335189336189337189338189339189340189341189342189343189344189345189346189347189348189349189350189351189352189353189354189355189356189357189358189359189360189361189362189363189364189365189366189367189368189369189370189371189372189373189374189375189376189377189378189379189380189381189382189383189384189385189386189387189388189389189390189391189392189393189394189395189396189397189398189399189400189401189402189403189404189405189406189407189408189409189410189411189412189413189414189415189416189417189418189419189420189421189422189423189424189425189426189427189428189429189430189431189432189433189434189435189436189437189438189439189440189441189442189443189444189445189446189447189448189449189450189451189452189453189454189455189456189457189458189459189460189461189462189463189464189465189466189467189468189469189470189471189472189473189474189475189476189477189478189479189480189481189482189483189484189485189486189487189488189489189490189491189492189493189494189495189496189497189498189499189500189501189502189503189504189505189506189507189508189509189510189511189512189513189514189515189516189517189518189519189520189521189522189523189524189525189526189527189528189529189530189531189532189533189534189535189536189537189538189539189540189541189542189543189544189545189546189547189548189549189550189551189552189553189554189555189556189557189558189559189560189561189562189563189564189565189566189567189568189569189570189571189572189573189574189575189576189577189578189579189580189581189582189583189584189585189586189587189588189589189590189591189592189593189594189595189596189597189598189599189600189601189602189603189604189605189606189607189608189609189610189611189612189613189614189615189616189617189618189619189620189621189622189623189624189625189626189627189628189629189630189631189632189633189634189635189636189637189638189639189640189641189642189643189644189645189646189647189648189649189650189651189652189653189654189655189656189657189658189659189660189661189662189663189664189665189666189667189668189669189670189671189672189673189674189675189676189677189678189679189680189681189682189683189684189685189686189687189688189689189690189691189692189693189694189695189696189697189698189699189700189701189702189703189704189705189706189707189708189709189710189711189712189713189714189715189716189717189718189719189720189721189722189723189724189725189726189727189728189729189730189731189732189733189734189735189736189737189738189739189740189741189742189743189744189745189746189747189748189749189750189751189752189753189754189755189756189757189758189759189760189761189762189763189764189765189766189767189768189769189770189771189772189773189774189775189776189777189778189779189780189781189782189783189784189785189786189787189788189789189790189791189792189793189794189795189796189797189798189799189800189801189802189803189804189805189806189807189808189809189810189811189812189813189814189815189816189817189818189819189820189821189822189823189824189825189826189827189828189829189830189831189832189833189834189835189836189837189838189839189840189841189842189843189844189845189846189847189848189849189850189851189852189853189854189855189856189857189858189859189860189861189862189863189864189865189866189867189868189869189870189871189872189873189874189875189876189877189878189879189880189881189882189883189884189885189886189887189888189889189890189891189892189893189894189895189896189897189898189899189900189901189902189903189904189905189906189907189908189909189910189911189912189913189914189915189916189917189918189919189920189921189922189923189924189925189926189927189928189929189930189931189932189933189934189935189936189937189938189939189940189941189942189943189944189945189946189947189948189949189950189951189952189953189954189955189956189957189958189959189960189961189962189963189964189965189966189967189968189969189970189971189972189973189974189975189976189977189978189979189980189981189982189983189984189985189986189987189988189989189990189991189992189993189994189995189996189997189998189999190000190001190002190003190004190005190006190007190008190009190010190011190012190013190014190015190016190017190018190019190020190021190022190023190024190025190026190027190028190029190030190031190032190033190034190035190036190037190038190039190040190041190042190043190044190045190046190047190048190049190050190051190052190053190054190055190056190057190058190059190060190061190062190063190064190065190066190067190068190069190070190071190072190073190074190075190076190077190078190079190080190081190082190083190084190085190086190087190088190089190090190091190092190093190094190095190096190097190098190099190100190101190102190103190104190105190106190107190108190109190110190111190112190113190114190115190116190117190118190119190120190121190122190123190124190125190126190127190128190129190130190131190132190133190134190135190136190137190138190139190140190141190142190143190144190145190146190147190148190149190150190151190152190153190154190155190156190157190158190159190160190161190162190163190164190165190166190167190168190169190170190171190172190173190174190175190176190177190178190179190180190181190182190183190184190185190186190187190188190189190190190191190192190193190194190195190196190197190198190199190200190201190202190203190204190205190206190207190208190209190210190211190212190213190214190215190216190217190218190219190220190221190222190223190224190225190226190227190228190229190230190231190232190233190234190235190236190237190238190239190240190241190242190243190244190245190246190247190248190249190250190251190252190253190254190255190256190257190258190259190260190261190262190263190264190265190266190267190268190269190270190271190272190273190274190275190276190277190278190279190280190281190282190283190284190285190286190287190288190289190290190291190292190293190294190295190296190297190298190299190300190301190302190303190304190305190306190307190308190309190310190311190312190313190314190315190316190317190318190319190320190321190322190323190324190325190326190327190328190329190330190331190332190333190334190335190336190337190338190339190340190341190342190343190344190345190346190347190348190349190350190351190352190353190354190355190356190357190358190359190360190361190362190363190364190365190366190367190368190369190370190371190372190373190374190375190376190377190378190379190380190381190382190383190384190385190386190387190388190389190390190391190392190393190394190395190396190397190398190399190400190401190402190403190404190405190406190407190408190409190410190411190412190413190414190415190416190417190418190419190420190421190422190423190424190425190426190427190428190429190430190431190432190433190434190435190436190437190438190439190440190441190442190443190444190445190446190447190448190449190450190451190452190453190454190455190456190457190458190459190460190461190462190463190464190465190466190467190468190469190470190471190472190473190474190475190476190477190478190479190480190481190482190483190484190485190486190487190488190489190490190491190492190493190494190495190496190497190498190499190500190501190502190503190504190505190506190507190508190509190510190511190512190513190514190515190516190517190518190519190520190521190522190523190524190525190526190527190528190529190530190531190532190533190534190535190536190537190538190539190540190541190542190543190544190545190546190547190548190549190550190551190552190553190554190555190556190557190558190559190560190561190562190563190564190565190566190567190568190569190570190571190572190573190574190575190576190577190578190579190580190581190582190583190584190585190586190587190588190589190590190591190592190593190594190595190596190597190598190599190600190601190602190603190604190605190606190607190608190609190610190611190612190613190614190615190616190617190618190619190620190621190622190623190624190625190626190627190628190629190630190631190632190633190634190635190636190637190638190639190640190641190642190643190644190645190646190647190648190649190650190651190652190653190654190655190656190657190658190659190660190661190662190663190664190665190666190667190668190669190670190671190672190673190674190675190676190677190678190679190680190681190682190683190684190685190686190687190688190689190690190691190692190693190694190695190696190697190698190699190700190701190702190703190704190705190706190707190708190709190710190711190712190713190714190715190716190717190718190719190720190721190722190723190724190725190726190727190728190729190730190731190732190733190734190735190736190737190738190739190740190741190742190743190744190745190746190747190748190749190750190751190752190753190754190755190756190757190758190759190760190761190762190763190764190765190766190767190768190769190770190771190772190773190774190775190776190777190778190779190780190781190782190783190784190785190786190787190788190789190790190791190792190793190794190795190796190797190798190799190800190801190802190803190804190805190806190807190808190809190810190811190812190813190814190815190816190817190818190819190820190821190822190823190824190825190826190827190828190829190830190831190832190833190834190835190836190837190838190839190840190841190842190843190844190845190846190847190848190849190850190851190852190853190854190855190856190857190858190859190860190861190862190863190864190865190866190867190868190869190870190871190872190873190874190875190876190877190878190879190880190881190882190883190884190885190886190887190888190889190890190891190892190893190894190895190896190897190898190899190900190901190902190903190904190905190906190907190908190909190910190911190912190913190914190915190916190917190918190919190920190921190922190923190924190925190926190927190928190929190930190931190932190933190934190935190936190937190938190939190940190941190942190943190944190945190946190947190948190949190950190951190952190953190954190955190956190957190958190959190960190961190962190963190964190965190966190967190968190969190970190971190972190973190974190975190976190977190978190979190980190981190982190983190984190985190986190987190988190989190990190991190992190993190994190995190996190997190998190999191000191001191002191003191004191005191006191007191008191009191010191011191012191013191014191015191016191017191018191019191020191021191022191023191024191025191026191027191028191029191030191031191032191033191034191035191036191037191038191039191040191041191042191043191044191045191046191047191048191049191050191051191052191053191054191055191056191057191058191059191060191061191062191063191064191065191066191067191068191069191070191071191072191073191074191075191076191077191078191079191080191081191082191083191084191085191086191087191088191089191090191091191092191093191094191095191096191097191098191099191100191101191102191103191104191105191106191107191108191109191110191111191112191113191114191115191116191117191118191119191120191121191122191123191124191125191126191127191128191129191130191131191132191133191134191135191136191137191138191139191140191141191142191143191144191145191146191147191148191149191150191151191152191153191154191155191156191157191158191159191160191161191162191163191164191165191166191167191168191169191170191171191172191173191174191175191176191177191178191179191180191181191182191183191184191185191186191187191188191189191190191191191192191193191194191195191196191197191198191199191200191201191202191203191204191205191206191207191208191209191210191211191212191213191214191215191216191217191218191219191220191221191222191223191224191225191226191227191228191229191230191231191232191233191234191235191236191237191238191239191240191241191242191243191244191245191246191247191248191249191250191251191252191253191254191255191256191257191258191259191260191261191262191263191264191265191266191267191268191269191270191271191272191273191274191275191276191277191278191279191280191281191282191283191284191285191286191287191288191289191290191291191292191293191294191295191296191297191298191299191300191301191302191303191304191305191306191307191308191309191310191311191312191313191314191315191316191317191318191319191320191321191322191323191324191325191326191327191328191329191330191331191332191333191334191335191336191337191338191339191340191341191342191343191344191345191346191347191348191349191350191351191352191353191354191355191356191357191358191359191360191361191362191363191364191365191366191367191368191369191370191371191372191373191374191375191376191377191378191379191380191381191382191383191384191385191386191387191388191389191390191391191392191393191394191395191396191397191398191399191400191401191402191403191404191405191406191407191408191409191410191411191412191413191414191415191416191417191418191419191420191421191422191423191424191425191426191427191428191429191430191431191432191433191434191435191436191437191438191439191440191441191442191443191444191445191446191447191448191449191450191451191452191453191454191455191456191457191458191459191460191461191462191463191464191465191466191467191468191469191470191471191472191473191474191475191476191477191478191479191480191481191482191483191484191485191486191487191488191489191490191491191492191493191494191495191496191497191498191499191500191501191502191503191504191505191506191507191508191509191510191511191512191513191514191515191516191517191518191519191520191521191522191523191524191525191526191527191528191529191530191531191532191533191534191535191536191537191538191539191540191541191542191543191544191545191546191547191548191549191550191551191552191553191554191555191556191557191558191559191560191561191562191563191564191565191566191567191568191569191570191571191572191573191574191575191576191577191578191579191580191581191582191583191584191585191586191587191588191589191590191591191592191593191594191595191596191597191598191599191600191601191602191603191604191605191606191607191608191609191610191611191612191613191614191615191616191617191618191619191620191621191622191623191624191625191626191627191628191629191630191631191632191633191634191635191636191637191638191639191640191641191642191643191644191645191646191647191648191649191650191651191652191653191654191655191656191657191658191659191660191661191662191663191664191665191666191667191668191669191670191671191672191673191674191675191676191677191678191679191680191681191682191683191684191685191686191687191688191689191690191691191692191693191694191695191696191697191698191699191700191701191702191703191704191705191706191707191708191709191710191711191712191713191714191715191716191717191718191719191720191721191722191723191724191725191726191727191728191729191730191731191732191733191734191735191736191737191738191739191740191741191742191743191744191745191746191747191748191749191750191751191752191753191754191755191756191757191758191759191760191761191762191763191764191765191766191767191768191769191770191771191772191773191774191775191776191777191778191779191780191781191782191783191784191785191786191787191788191789191790191791191792191793191794191795191796191797191798191799191800191801191802191803191804191805191806191807191808191809191810191811191812191813191814191815191816191817191818191819191820191821191822191823191824191825191826191827191828191829191830191831191832191833191834191835191836191837191838191839191840191841191842191843191844191845191846191847191848191849191850191851191852191853191854191855191856191857191858191859191860191861191862191863191864191865191866191867191868191869191870191871191872191873191874191875191876191877191878191879191880191881191882191883191884191885191886191887191888191889191890191891191892191893191894191895191896191897191898191899191900191901191902191903191904191905191906191907191908191909191910191911191912191913191914191915191916191917191918191919191920191921191922191923191924191925191926191927191928191929191930191931191932191933191934191935191936191937191938191939191940191941191942191943191944191945191946191947191948191949191950191951191952191953191954191955191956191957191958191959191960191961191962191963191964191965191966191967191968191969191970191971191972191973191974191975191976191977191978191979191980191981191982191983191984191985191986191987191988191989191990191991191992191993191994191995191996191997191998191999192000192001192002192003192004192005192006192007192008192009192010192011192012192013192014192015192016192017192018192019192020192021192022192023192024192025192026192027192028192029192030192031192032192033192034192035192036192037192038192039192040192041192042192043192044192045192046192047192048192049192050192051192052192053192054192055192056192057192058192059192060192061192062192063192064192065192066192067192068192069192070192071192072192073192074192075192076192077192078192079192080192081192082192083192084192085192086192087192088192089192090192091192092192093192094192095192096192097192098192099192100192101192102192103192104192105192106192107192108192109192110192111192112192113192114192115192116192117192118192119192120192121192122192123192124192125192126192127192128192129192130192131192132192133192134192135192136192137192138192139192140192141192142192143192144192145192146192147192148192149192150192151192152192153192154192155192156192157192158192159192160192161192162192163192164192165192166192167192168192169192170192171192172192173192174192175192176192177192178192179192180192181192182192183192184192185192186192187192188192189192190192191192192192193192194192195192196192197192198192199192200192201192202192203192204192205192206192207192208192209192210192211192212192213192214192215192216192217192218192219192220192221192222192223192224192225192226192227192228192229192230192231192232192233192234192235192236192237192238192239192240192241192242192243192244192245192246192247192248192249192250192251192252192253192254192255192256192257192258192259192260192261192262192263192264192265192266192267192268192269192270192271192272192273192274192275192276192277192278192279192280192281192282192283192284192285192286192287192288192289192290192291192292192293192294192295192296192297192298192299192300192301192302192303192304192305192306192307192308192309192310192311192312192313192314192315192316192317192318192319192320192321192322192323192324192325192326192327192328192329192330192331192332192333192334192335192336192337192338192339192340192341192342192343192344192345192346192347192348192349192350192351192352192353192354192355192356192357192358192359192360192361192362192363192364192365192366192367192368192369192370192371192372192373192374192375192376192377192378192379192380192381192382192383192384192385192386192387192388192389192390192391192392192393192394192395192396192397192398192399192400192401192402192403192404192405192406192407192408192409192410192411192412192413192414192415192416192417192418192419192420192421192422192423192424192425192426192427192428192429192430192431192432192433192434192435192436192437192438192439192440192441192442192443192444192445192446192447192448192449192450192451192452192453192454192455192456192457192458192459192460192461192462192463192464192465192466192467192468192469192470192471192472192473192474192475192476192477192478192479192480192481192482192483192484192485192486192487192488192489192490192491192492192493192494192495192496192497192498192499192500192501192502192503192504192505192506192507192508192509192510192511192512192513192514192515192516192517192518192519192520192521192522192523192524192525192526192527192528192529192530192531192532192533192534192535192536192537192538192539192540192541192542192543192544192545192546192547192548192549192550192551192552192553192554192555192556192557192558192559192560192561192562192563192564192565192566192567192568192569192570192571192572192573192574192575192576192577192578192579192580192581192582192583192584192585192586192587192588192589192590192591192592192593192594192595192596192597192598192599192600192601192602192603192604192605192606192607192608192609192610192611192612192613192614192615192616192617192618192619192620192621192622192623192624192625192626192627192628192629192630192631192632192633192634192635192636192637192638192639192640192641192642192643192644192645192646192647192648192649192650192651192652192653192654192655192656192657192658192659192660192661192662192663192664192665192666192667192668192669192670192671192672192673192674192675192676192677192678192679192680192681192682192683192684192685192686192687192688192689192690192691192692192693192694192695192696192697192698192699192700192701192702192703192704192705192706192707192708192709192710192711192712192713192714192715192716192717192718192719192720192721192722192723192724192725192726192727192728192729192730192731192732192733192734192735192736192737192738192739192740192741192742192743192744192745192746192747192748192749192750192751192752192753192754192755192756192757192758192759192760192761192762192763192764192765192766192767192768192769192770192771192772192773192774192775192776192777192778192779192780192781192782192783192784192785192786192787192788192789192790192791192792192793192794192795192796192797192798192799192800192801192802192803192804192805192806192807192808192809192810192811192812192813192814192815192816192817192818192819192820192821192822192823192824192825192826192827192828192829192830192831192832192833192834192835192836192837192838192839192840192841192842192843192844192845192846192847192848192849192850192851192852192853192854192855192856192857192858192859192860192861192862192863192864192865192866192867192868192869192870192871192872192873192874192875192876192877192878192879192880192881192882192883192884192885192886192887192888192889192890192891192892192893192894192895192896192897192898192899192900192901192902192903192904192905192906192907192908192909192910192911192912192913192914192915192916192917192918192919192920192921192922192923192924192925192926192927192928192929192930192931192932192933192934192935192936192937192938192939192940192941192942192943192944192945192946192947192948192949192950192951192952192953192954192955192956192957192958192959192960192961192962192963192964192965192966192967192968192969192970192971192972192973192974192975192976192977192978192979192980192981192982192983192984192985192986192987192988192989192990192991192992192993192994192995192996192997192998192999193000193001193002193003193004193005193006193007193008193009193010193011193012193013193014193015193016193017193018193019193020193021193022193023193024193025193026193027193028193029193030193031193032193033193034193035193036193037193038193039193040193041193042193043193044193045193046193047193048193049193050193051193052193053193054193055193056193057193058193059193060193061193062193063193064193065193066193067193068193069193070193071193072193073193074193075193076193077193078193079193080193081193082193083193084193085193086193087193088193089193090193091193092193093193094193095193096193097193098193099193100193101193102193103193104193105193106193107193108193109193110193111193112193113193114193115193116193117193118193119193120193121193122193123193124193125193126193127193128193129193130193131193132193133193134193135193136193137193138193139193140193141193142193143193144193145193146193147193148193149193150193151193152193153193154193155193156193157193158193159193160193161193162193163193164193165193166193167193168193169193170193171193172193173193174193175193176193177193178193179193180193181193182193183193184193185193186193187193188193189193190193191193192193193193194193195193196193197193198193199193200193201193202193203193204193205193206193207193208193209193210193211193212193213193214193215193216193217193218193219193220193221193222193223193224193225193226193227193228193229193230193231193232193233193234193235193236193237193238193239193240193241193242193243193244193245193246193247193248193249193250193251193252193253193254193255193256193257193258193259193260193261193262193263193264193265193266193267193268193269193270193271193272193273193274193275193276193277193278193279193280193281193282193283193284193285193286193287193288193289193290193291193292193293193294193295193296193297193298193299193300193301193302193303193304193305193306193307193308193309193310193311193312193313193314193315193316193317193318193319193320193321193322193323193324193325193326193327193328193329193330193331193332193333193334193335193336193337193338193339193340193341193342193343193344193345193346193347193348193349193350193351193352193353193354193355193356193357193358193359193360193361193362193363193364193365193366193367193368193369193370193371193372193373193374193375193376193377193378193379193380193381193382193383193384193385193386193387193388193389193390193391193392193393193394193395193396193397193398193399193400193401193402193403193404193405193406193407193408193409193410193411193412193413193414193415193416193417193418193419193420193421193422193423193424193425193426193427193428193429193430193431193432193433193434193435193436193437193438193439193440193441193442193443193444193445193446193447193448193449193450193451193452193453193454193455193456193457193458193459193460193461193462193463193464193465193466193467193468193469193470193471193472193473193474193475193476193477193478193479193480193481193482193483193484193485193486193487193488193489193490193491193492193493193494193495193496193497193498193499193500193501193502193503193504193505193506193507193508193509193510193511193512193513193514193515193516193517193518193519193520193521193522193523193524193525193526193527193528193529193530193531193532193533193534193535193536193537193538193539193540193541193542193543193544193545193546193547193548193549193550193551193552193553193554193555193556193557193558193559193560193561193562193563193564193565193566193567193568193569193570193571193572193573193574193575193576193577193578193579193580193581193582193583193584193585193586193587193588193589193590193591193592193593193594193595193596193597193598193599193600193601193602193603193604193605193606193607193608193609193610193611193612193613193614193615193616193617193618193619193620193621193622193623193624193625193626193627193628193629193630193631193632193633193634193635193636193637193638193639193640193641193642193643193644193645193646193647193648193649193650193651193652193653193654193655193656193657193658193659193660193661193662193663193664193665193666193667193668193669193670193671193672193673193674193675193676193677193678193679193680193681193682193683193684193685193686193687193688193689193690193691193692193693193694193695193696193697193698193699193700193701193702193703193704193705193706193707193708193709193710193711193712193713193714193715193716193717193718193719193720193721193722193723193724193725193726193727193728193729193730193731193732193733193734193735193736193737193738193739193740193741193742193743193744193745193746193747193748193749193750193751193752193753193754193755193756193757193758193759193760193761193762193763193764193765193766193767193768193769193770193771193772193773193774193775193776193777193778193779193780193781193782193783193784193785193786193787193788193789193790193791193792193793193794193795193796193797193798193799193800193801193802193803193804193805193806193807193808193809193810193811193812193813193814193815193816193817193818193819193820193821193822193823193824193825193826193827193828193829193830193831193832193833193834193835193836193837193838193839193840193841193842193843193844193845193846193847193848193849193850193851193852193853193854193855193856193857193858193859193860193861193862193863193864193865193866193867193868193869193870193871193872193873193874193875193876193877193878193879193880193881193882193883193884193885193886193887193888193889193890193891193892193893193894193895193896193897193898193899193900193901193902193903193904193905193906193907193908193909193910193911193912193913193914193915193916193917193918193919193920193921193922193923193924193925193926193927193928193929193930193931193932193933193934193935193936193937193938193939193940193941193942193943193944193945193946193947193948193949193950193951193952193953193954193955193956193957193958193959193960193961193962193963193964193965193966193967193968193969193970193971193972193973193974193975193976193977193978193979193980193981193982193983193984193985193986193987193988193989193990193991193992193993193994193995193996193997193998193999194000194001194002194003194004194005194006194007194008194009194010194011194012194013194014194015194016194017194018194019194020194021194022194023194024194025194026194027194028194029194030194031194032194033194034194035194036194037194038194039194040194041194042194043194044194045194046194047194048194049194050194051194052194053194054194055194056194057194058194059194060194061194062194063194064194065194066194067194068194069194070194071194072194073194074194075194076194077194078194079194080194081194082194083194084194085194086194087194088194089194090194091194092194093194094194095194096194097194098194099194100194101194102194103194104194105194106194107194108194109194110194111194112194113194114194115194116194117194118194119194120194121194122194123194124194125194126194127194128194129194130194131194132194133194134194135194136194137194138194139194140194141194142194143194144194145194146194147194148194149194150194151194152194153194154194155194156194157194158194159194160194161194162194163194164194165194166194167194168194169194170194171194172194173194174194175194176194177194178194179194180194181194182194183194184194185194186194187194188194189194190194191194192194193194194194195194196194197194198194199194200194201194202194203194204194205194206194207194208194209194210194211194212194213194214194215194216194217194218194219194220194221194222194223194224194225194226194227194228194229194230194231194232194233194234194235194236194237194238194239194240194241194242194243194244194245194246194247194248194249194250194251194252194253194254194255194256194257194258194259194260194261194262194263194264194265194266194267194268194269194270194271194272194273194274194275194276194277194278194279194280194281194282194283194284194285194286194287194288194289194290194291194292194293194294194295194296194297194298194299194300194301194302194303194304194305194306194307194308194309194310194311194312194313194314194315194316194317194318194319194320194321194322194323194324194325194326194327194328194329194330194331194332194333194334194335194336194337194338194339194340194341194342194343194344194345194346194347194348194349194350194351194352194353194354194355194356194357194358194359194360194361194362194363194364194365194366194367194368194369194370194371194372194373194374194375194376194377194378194379194380194381194382194383194384194385194386194387194388194389194390194391194392194393194394194395194396194397194398194399194400194401194402194403194404194405194406194407194408194409194410194411194412194413194414194415194416194417194418194419194420194421194422194423194424194425194426194427194428194429194430194431194432194433194434194435194436194437194438194439194440194441194442194443194444194445194446194447194448194449194450194451194452194453194454194455194456194457194458194459194460194461194462194463194464194465194466194467194468194469194470194471194472194473194474194475194476194477194478194479194480194481194482194483194484194485194486194487194488194489194490194491194492194493194494194495194496194497194498194499194500194501194502194503194504194505194506194507194508194509194510194511194512194513194514194515194516194517194518194519194520194521194522194523194524194525194526194527194528194529194530194531194532194533194534194535194536194537194538194539194540194541194542194543194544194545194546194547194548194549194550194551194552194553194554194555194556194557194558194559194560194561194562194563194564194565194566194567194568194569194570194571194572194573194574194575194576194577194578194579194580194581194582194583194584194585194586194587194588194589194590194591194592194593194594194595194596194597194598194599194600194601194602194603194604194605194606194607194608194609194610194611194612194613194614194615194616194617194618194619194620194621194622194623194624194625194626194627194628194629194630194631194632194633194634194635194636194637194638194639194640194641194642194643194644194645194646194647194648194649194650194651194652194653194654194655194656194657194658194659194660194661194662194663194664194665194666194667194668194669194670194671194672194673194674194675194676194677194678194679194680194681194682194683194684194685194686194687194688194689194690194691194692194693194694194695194696194697194698194699194700194701194702194703194704194705194706194707194708194709194710194711194712194713194714194715194716194717194718194719194720194721194722194723194724194725194726194727194728194729194730194731194732194733194734194735194736194737194738194739194740194741194742194743194744194745194746194747194748194749194750194751194752194753194754194755194756194757194758194759194760194761194762194763194764194765194766194767194768194769194770194771194772194773194774194775194776194777194778194779194780194781194782194783194784194785194786194787194788194789194790194791194792194793194794194795194796194797194798194799194800194801194802194803194804194805194806194807194808194809194810194811194812194813194814194815194816194817194818194819194820194821194822194823194824194825194826194827194828194829194830194831194832194833194834194835194836194837194838194839194840194841194842194843194844194845194846194847194848194849194850194851194852194853194854194855194856194857194858194859194860194861194862194863194864194865194866194867194868194869194870194871194872194873194874194875194876194877194878194879194880194881194882194883194884194885194886194887194888194889194890194891194892194893194894194895194896194897194898194899194900194901194902194903194904194905194906194907194908194909194910194911194912194913194914194915194916194917194918194919194920194921194922194923194924194925194926194927194928194929194930194931194932194933194934194935194936194937194938194939194940194941194942194943194944194945194946194947194948194949194950194951194952194953194954194955194956194957194958194959194960194961194962194963194964194965194966194967194968194969194970194971194972194973194974194975194976194977194978194979194980194981194982194983194984194985194986194987194988194989194990194991194992194993194994194995194996194997194998194999195000195001195002195003195004195005195006195007195008195009195010195011195012195013195014195015195016195017195018195019195020195021195022195023195024195025195026195027195028195029195030195031195032195033195034195035195036195037195038195039195040195041195042195043195044195045195046195047195048195049195050195051195052195053195054195055195056195057195058195059195060195061195062195063195064195065195066195067195068195069195070195071195072195073195074195075195076195077195078195079195080195081195082195083195084195085195086195087195088195089195090195091195092195093195094195095195096195097195098195099195100195101195102195103195104195105195106195107195108195109195110195111195112195113195114195115195116195117195118195119195120195121195122195123195124195125195126195127195128195129195130195131195132195133195134195135195136195137195138195139195140195141195142195143195144195145195146195147195148195149195150195151195152195153195154195155195156195157195158195159195160195161195162195163195164195165195166195167195168195169195170195171195172195173195174195175195176195177195178195179195180195181195182195183195184195185195186195187195188195189195190195191195192195193195194195195195196195197195198195199195200195201195202195203195204195205195206195207195208195209195210195211195212195213195214195215195216195217195218195219195220195221195222195223195224195225195226195227195228195229195230195231195232195233195234195235195236195237195238195239195240195241195242195243195244195245195246195247195248195249195250195251195252195253195254195255195256195257195258195259195260195261195262195263195264195265195266195267195268195269195270195271195272195273195274195275195276195277195278195279195280195281195282195283195284195285195286195287195288195289195290195291195292195293195294195295195296195297195298195299195300195301195302195303195304195305195306195307195308195309195310195311195312195313195314195315195316195317195318195319195320195321195322195323195324195325195326195327195328195329195330195331195332195333195334195335195336195337195338195339195340195341195342195343195344195345195346195347195348195349195350195351195352195353195354195355195356195357195358195359195360195361195362195363195364195365195366195367195368195369195370195371195372195373195374195375195376195377195378195379195380195381195382195383195384195385195386195387195388195389195390195391195392195393195394195395195396195397195398195399195400195401195402195403195404195405195406195407195408195409195410195411195412195413195414195415195416195417195418195419195420195421195422195423195424195425195426195427195428195429195430195431195432195433195434195435195436195437195438195439195440195441195442195443195444195445195446195447195448195449195450195451195452195453195454195455195456195457195458195459195460195461195462195463195464195465195466195467195468195469195470195471195472195473195474195475195476195477195478195479195480195481195482195483195484195485195486195487195488195489195490195491195492195493195494195495195496195497195498195499195500195501195502195503195504195505195506195507195508195509195510195511195512195513195514195515195516195517195518195519195520195521195522195523195524195525195526195527195528195529195530195531195532195533195534195535195536195537195538195539195540195541195542195543195544195545195546195547195548195549195550195551195552195553195554195555195556195557195558195559195560195561195562195563195564195565195566195567195568195569195570195571195572195573195574195575195576195577195578195579195580195581195582195583195584195585195586195587195588195589195590195591195592195593195594195595195596195597195598195599195600195601195602195603195604195605195606195607195608195609195610195611195612195613195614195615195616195617195618195619195620195621195622195623195624195625195626195627195628195629195630195631195632195633195634195635195636195637195638195639195640195641195642195643195644195645195646195647195648195649195650195651195652195653195654195655195656195657195658195659195660195661195662195663195664195665195666195667195668195669195670195671195672195673195674195675195676195677195678195679195680195681195682195683195684195685195686195687195688195689195690195691195692195693195694195695195696195697195698195699195700195701195702195703195704195705195706195707195708195709195710195711195712195713195714195715195716195717195718195719195720195721195722195723195724195725195726195727195728195729195730195731195732195733195734195735195736195737195738195739195740195741195742195743195744195745195746195747195748195749195750195751195752195753195754195755195756195757195758195759195760195761195762195763195764195765195766195767195768195769195770195771195772195773195774195775195776195777195778195779195780195781195782195783195784195785195786195787195788195789195790195791195792195793195794195795195796195797195798195799195800195801195802195803195804195805195806195807195808195809195810195811195812195813195814195815195816195817195818195819195820195821195822195823195824195825195826195827195828195829195830195831195832195833195834195835195836195837195838195839195840195841195842195843195844195845195846195847195848195849195850195851195852195853195854195855195856195857195858195859195860195861195862195863195864195865195866195867195868195869195870195871195872195873195874195875195876195877195878195879195880195881195882195883195884195885195886195887195888195889195890195891195892195893195894195895195896195897195898195899195900195901195902195903195904195905195906195907195908195909195910195911195912195913195914195915195916195917195918195919195920195921195922195923195924195925195926195927195928195929195930195931195932195933195934195935195936195937195938195939195940195941195942195943195944195945195946195947195948195949195950195951195952195953195954195955195956195957195958195959195960195961195962195963195964195965195966195967195968195969195970195971195972195973195974195975195976195977195978195979195980195981195982195983195984195985195986195987195988195989195990195991195992195993195994195995195996195997195998195999196000196001196002196003196004196005196006196007196008196009196010196011196012196013196014196015196016196017196018196019196020196021196022196023196024196025196026196027196028196029196030196031196032196033196034196035196036196037196038196039196040196041196042196043196044196045196046196047196048196049196050196051196052196053196054196055196056196057196058196059196060196061196062196063196064196065196066196067196068196069196070196071196072196073196074196075196076196077196078196079196080196081196082196083196084196085196086196087196088196089196090196091196092196093196094196095196096196097196098196099196100196101196102196103196104196105196106196107196108196109196110196111196112196113196114196115196116196117196118196119196120196121196122196123196124196125196126196127196128196129196130196131196132196133196134196135196136196137196138196139196140196141196142196143196144196145196146196147196148196149196150196151196152196153196154196155196156196157196158196159196160196161196162196163196164196165196166196167196168196169196170196171196172196173196174196175196176196177196178196179196180196181196182196183196184196185196186196187196188196189196190196191196192196193196194196195196196196197196198196199196200196201196202196203196204196205196206196207196208196209196210196211196212196213196214196215196216196217196218196219196220196221196222196223196224196225196226196227196228196229196230196231196232196233196234196235196236196237196238196239196240196241196242196243196244196245196246196247196248196249196250196251196252196253196254196255196256196257196258196259196260196261196262196263196264196265196266196267196268196269196270196271196272196273196274196275196276196277196278196279196280196281196282196283196284196285196286196287196288196289196290196291196292196293196294196295196296196297196298196299196300196301196302196303196304196305196306196307196308196309196310196311196312196313196314196315196316196317196318196319196320196321196322196323196324196325196326196327196328196329196330196331196332196333196334196335196336196337196338196339196340196341196342196343196344196345196346196347196348196349196350196351196352196353196354196355196356196357196358196359196360196361196362196363196364196365196366196367196368196369196370196371196372196373196374196375196376196377196378196379196380196381196382196383196384196385196386196387196388196389196390196391196392196393196394196395196396196397196398196399196400196401196402196403196404196405196406196407196408196409196410196411196412196413196414196415196416196417196418196419196420196421196422196423196424196425196426196427196428196429196430196431196432196433196434196435196436196437196438196439196440196441196442196443196444196445196446196447196448196449196450196451196452196453196454196455196456196457196458196459196460196461196462196463196464196465196466196467196468196469196470196471196472196473196474196475196476196477196478196479196480196481196482196483196484196485196486196487196488196489196490196491196492196493196494196495196496196497196498196499196500196501196502196503196504196505196506196507196508196509196510196511196512196513196514196515196516196517196518196519196520196521196522196523196524196525196526196527196528196529196530196531196532196533196534196535196536196537196538196539196540196541196542196543196544196545196546196547196548196549196550196551196552196553196554196555196556196557196558196559196560196561196562196563196564196565196566196567196568196569196570196571196572196573196574196575196576196577196578196579196580196581196582196583196584196585196586196587196588196589196590196591196592196593196594196595196596196597196598196599196600196601196602196603196604196605196606196607196608196609196610196611196612196613196614196615196616196617196618196619196620196621196622196623196624196625196626196627196628196629196630196631196632196633196634196635196636196637196638196639196640196641196642196643196644196645196646196647196648196649196650196651196652196653196654196655196656196657196658196659196660196661196662196663196664196665196666196667196668196669196670196671196672196673196674196675196676196677196678196679196680196681196682196683196684196685196686196687196688196689196690196691196692196693196694196695196696196697196698196699196700196701196702196703196704196705196706196707196708196709196710196711196712196713196714196715196716196717196718196719196720196721196722196723196724196725196726196727196728196729196730196731196732196733196734196735196736196737196738196739196740196741196742196743196744196745196746196747196748196749196750196751196752196753196754196755196756196757196758196759196760196761196762196763196764196765196766196767196768196769196770196771196772196773196774196775196776196777196778196779196780196781196782196783196784196785196786196787196788196789196790196791196792196793196794196795196796196797196798196799196800196801196802196803196804196805196806196807196808196809196810196811196812196813196814196815196816196817196818196819196820196821196822196823196824196825196826196827196828196829196830196831196832196833196834196835196836196837196838196839196840196841196842196843196844196845196846196847196848196849196850196851196852196853196854196855196856196857196858196859196860196861196862196863196864196865196866196867196868196869196870196871196872196873196874196875196876196877196878196879196880196881196882196883196884196885196886196887196888196889196890196891196892196893196894196895196896196897196898196899196900196901196902196903196904196905196906196907196908196909196910196911196912196913196914196915196916196917196918196919196920196921196922196923196924196925196926196927196928196929196930196931196932196933196934196935196936196937196938196939196940196941196942196943196944196945196946196947196948196949196950196951196952196953196954196955196956196957196958196959196960196961196962196963196964196965196966196967196968196969196970196971196972196973196974196975196976196977196978196979196980196981196982196983196984196985196986196987196988196989196990196991196992196993196994196995196996196997196998196999197000197001197002197003197004197005197006197007197008197009197010197011197012197013197014197015197016197017197018197019197020197021197022197023197024197025197026197027197028197029197030197031197032197033197034197035197036197037197038197039197040197041197042197043197044197045197046197047197048197049197050197051197052197053197054197055197056197057197058197059197060197061197062197063197064197065197066197067197068197069197070197071197072197073197074197075197076197077197078197079197080197081197082197083197084197085197086197087197088197089197090197091197092197093197094197095197096197097197098197099197100197101197102197103197104197105197106197107197108197109197110197111197112197113197114197115197116197117197118197119197120197121197122197123197124197125197126197127197128197129197130197131197132197133197134197135197136197137197138197139197140197141197142197143197144197145197146197147197148197149197150197151197152197153197154197155197156197157197158197159197160197161197162197163197164197165197166197167197168197169197170197171197172197173197174197175197176197177197178197179197180197181197182197183197184197185197186197187197188197189197190197191197192197193197194197195197196197197197198197199197200197201197202197203197204197205197206197207197208197209197210197211197212197213197214197215197216197217197218197219197220197221197222197223197224197225197226197227197228197229197230197231197232197233197234197235197236197237197238197239197240197241197242197243197244197245197246197247197248197249197250197251197252197253197254197255197256197257197258197259197260197261197262197263197264197265197266197267197268197269197270197271197272197273197274197275197276197277197278197279197280197281197282197283197284197285197286197287197288197289197290197291197292197293197294197295197296197297197298197299197300197301197302197303197304197305197306197307197308197309197310197311197312197313197314197315197316197317197318197319197320197321197322197323197324197325197326197327197328197329197330197331197332197333197334197335197336197337197338197339197340197341197342197343197344197345197346197347197348197349197350197351197352197353197354197355197356197357197358197359197360197361197362197363197364197365197366197367197368197369197370197371197372197373197374197375197376197377197378197379197380197381197382197383197384197385197386197387197388197389197390197391197392197393197394197395197396197397197398197399197400197401197402197403197404197405197406197407197408197409197410197411197412197413197414197415197416197417197418197419197420197421197422197423197424197425197426197427197428197429197430197431197432197433197434197435197436197437197438197439197440197441197442197443197444197445197446197447197448197449197450197451197452197453197454197455197456197457197458197459197460197461197462197463197464197465197466197467197468197469197470197471197472197473197474197475197476197477197478197479197480197481197482197483197484197485197486197487197488197489197490197491197492197493197494197495197496197497197498197499197500197501197502197503197504197505197506197507197508197509197510197511197512197513197514197515197516197517197518197519197520197521197522197523197524197525197526197527197528197529197530197531197532197533197534197535197536197537197538197539197540197541197542197543197544197545197546197547197548197549197550197551197552197553197554197555197556197557197558197559197560197561197562197563197564197565197566197567197568197569197570197571197572197573197574197575197576197577197578197579197580197581197582197583197584197585197586197587197588197589197590197591197592197593197594197595197596197597197598197599197600197601197602197603197604197605197606197607197608197609197610197611197612197613197614197615197616197617197618197619197620197621197622197623197624197625197626197627197628197629197630197631197632197633197634197635197636197637197638197639197640197641197642197643197644197645197646197647197648197649197650197651197652197653197654197655197656197657197658197659197660197661197662197663197664197665197666197667197668197669197670197671197672197673197674197675197676197677197678197679197680197681197682197683197684197685197686197687197688197689197690197691197692197693197694197695197696197697197698197699197700197701197702197703197704197705197706197707197708197709197710197711197712197713197714197715197716197717197718197719197720197721197722197723197724197725197726197727197728197729197730197731197732197733197734197735197736197737197738197739197740197741197742197743197744197745197746197747197748197749197750197751197752197753197754197755197756197757197758197759197760197761197762197763197764197765197766197767197768197769197770197771197772197773197774197775197776197777197778197779197780197781197782197783197784197785197786197787197788197789197790197791197792197793197794197795197796197797197798197799197800197801197802197803197804197805197806197807197808197809197810197811197812197813197814197815197816197817197818197819197820197821197822197823197824197825197826197827197828197829197830197831197832197833197834197835197836197837197838197839197840197841197842197843197844197845197846197847197848197849197850197851197852197853197854197855197856197857197858197859197860197861197862197863197864197865197866197867197868197869197870197871197872197873197874197875197876197877197878197879197880197881197882197883197884197885197886197887197888197889197890197891197892197893197894197895197896197897197898197899197900197901197902197903197904197905197906197907197908197909197910197911197912197913197914197915197916197917197918197919197920197921197922197923197924197925197926197927197928197929197930197931197932197933197934197935197936197937197938197939197940197941197942197943197944197945197946197947197948197949197950197951197952197953197954197955197956197957197958197959197960197961197962197963197964197965197966197967197968197969197970197971197972197973197974197975197976197977197978197979197980197981197982197983197984197985197986197987197988197989197990197991197992197993197994197995197996197997197998197999198000198001198002198003198004198005198006198007198008198009198010198011198012198013198014198015198016198017198018198019198020198021198022198023198024198025198026198027198028198029198030198031198032198033198034198035198036198037198038198039198040198041198042198043198044198045198046198047198048198049198050198051198052198053198054198055198056198057198058198059198060198061198062198063198064198065198066198067198068198069198070198071198072198073198074198075198076198077198078198079198080198081198082198083198084198085198086198087198088198089198090198091198092198093198094198095198096198097198098198099198100198101198102198103198104198105198106198107198108198109198110198111198112198113198114198115198116198117198118198119198120198121198122198123198124198125198126198127198128198129198130198131198132198133198134198135198136198137198138198139198140198141198142198143198144198145198146198147198148198149198150198151198152198153198154198155198156198157198158198159198160198161198162198163198164198165198166198167198168198169198170198171198172198173198174198175198176198177198178198179198180198181198182198183198184198185198186198187198188198189198190198191198192198193198194198195198196198197198198198199198200198201198202198203198204198205198206198207198208198209198210198211198212198213198214198215198216198217198218198219198220198221198222198223198224198225198226198227198228198229198230198231198232198233198234198235198236198237198238198239198240198241198242198243198244198245198246198247198248198249198250198251198252198253198254198255198256198257198258198259198260198261198262198263198264198265198266198267198268198269198270198271198272198273198274198275198276198277198278198279198280198281198282198283198284198285198286198287198288198289198290198291198292198293198294198295198296198297198298198299198300198301198302198303198304198305198306198307198308198309198310198311198312198313198314198315198316198317198318198319198320198321198322198323198324198325198326198327198328198329198330198331198332198333198334198335198336198337198338198339198340198341198342198343198344198345198346198347198348198349198350198351198352198353198354198355198356198357198358198359198360198361198362198363198364198365198366198367198368198369198370198371198372198373198374198375198376198377198378198379198380198381198382198383198384198385198386198387198388198389198390198391198392198393198394198395198396198397198398198399198400198401198402198403198404198405198406198407198408198409198410198411198412198413198414198415198416198417198418198419198420198421198422198423198424198425198426198427198428198429198430198431198432198433198434198435198436198437198438198439198440198441198442198443198444198445198446198447198448198449198450198451198452198453198454198455198456198457198458198459198460198461198462198463198464198465198466198467198468198469198470198471198472198473198474198475198476198477198478198479198480198481198482198483198484198485198486198487198488198489198490198491198492198493198494198495198496198497198498198499198500198501198502198503198504198505198506198507198508198509198510198511198512198513198514198515198516198517198518198519198520198521198522198523198524198525198526198527198528198529198530198531198532198533198534198535198536198537198538198539198540198541198542198543198544198545198546198547198548198549198550198551198552198553198554198555198556198557198558198559198560198561198562198563198564198565198566198567198568198569198570198571198572198573198574198575198576198577198578198579198580198581198582198583198584198585198586198587198588198589198590198591198592198593198594198595198596198597198598198599198600198601198602198603198604198605198606198607198608198609198610198611198612198613198614198615198616198617198618198619198620198621198622198623198624198625198626198627198628198629198630198631198632198633198634198635198636198637198638198639198640198641198642198643198644198645198646198647198648198649198650198651198652198653198654198655198656198657198658198659198660198661198662198663198664198665198666198667198668198669198670198671198672198673198674198675198676198677198678198679198680198681198682198683198684198685198686198687198688198689198690198691198692198693198694198695198696198697198698198699198700198701198702198703198704198705198706198707198708198709198710198711198712198713198714198715198716198717198718198719198720198721198722198723198724198725198726198727198728198729198730198731198732198733198734198735198736198737198738198739198740198741198742198743198744198745198746198747198748198749198750198751198752198753198754198755198756198757198758198759198760198761198762198763198764198765198766198767198768198769198770198771198772198773198774198775198776198777198778198779198780198781198782198783198784198785198786198787198788198789198790198791198792198793198794198795198796198797198798198799198800198801198802198803198804198805198806198807198808198809198810198811198812198813198814198815198816198817198818198819198820198821198822198823198824198825198826198827198828198829198830198831198832198833198834198835198836198837198838198839198840198841198842198843198844198845198846198847198848198849198850198851198852198853198854198855198856198857198858198859198860198861198862198863198864198865198866198867198868198869198870198871198872198873198874198875198876198877198878198879198880198881198882198883198884198885198886198887198888198889198890198891198892198893198894198895198896198897198898198899198900198901198902198903198904198905198906198907198908198909198910198911198912198913198914198915198916198917198918198919198920198921198922198923198924198925198926198927198928198929198930198931198932198933198934198935198936198937198938198939198940198941198942198943198944198945198946198947198948198949198950198951198952198953198954198955198956198957198958198959198960198961198962198963198964198965198966198967198968198969198970198971198972198973198974198975198976198977198978198979198980198981198982198983198984198985198986198987198988198989198990198991198992198993198994198995198996198997198998198999199000199001199002199003199004199005199006199007199008199009199010199011199012199013199014199015199016199017199018199019199020199021199022199023199024199025199026199027199028199029199030199031199032199033199034199035199036199037199038199039199040199041199042199043199044199045199046199047199048199049199050199051199052199053199054199055199056199057199058199059199060199061199062199063199064199065199066199067199068199069199070199071199072199073199074199075199076199077199078199079199080199081199082199083199084199085199086199087199088199089199090199091199092199093199094199095199096199097199098199099199100199101199102199103199104199105199106199107199108199109199110199111199112199113199114199115199116199117199118199119199120199121199122199123199124199125199126199127199128199129199130199131199132199133199134199135199136199137199138199139199140199141199142199143199144199145199146199147199148199149199150199151199152199153199154199155199156199157199158199159199160199161199162199163199164199165199166199167199168199169199170199171199172199173199174199175199176199177199178199179199180199181199182199183199184199185199186199187199188199189199190199191199192199193199194199195199196199197199198199199199200199201199202199203199204199205199206199207199208199209199210199211199212199213199214199215199216199217199218199219199220199221199222199223199224199225199226199227199228199229199230199231199232199233199234199235199236199237199238199239199240199241199242199243199244199245199246199247199248199249199250199251199252199253199254199255199256199257199258199259199260199261199262199263199264199265199266199267199268199269199270199271199272199273199274199275199276199277199278199279199280199281199282199283199284199285199286199287199288199289199290199291199292199293199294199295199296199297199298199299199300199301199302199303199304199305199306199307199308199309199310199311199312199313199314199315199316199317199318199319199320199321199322199323199324199325199326199327199328199329199330199331199332199333199334199335199336199337199338199339199340199341199342199343199344199345199346199347199348199349199350199351199352199353199354199355199356199357199358199359199360199361199362199363199364199365199366199367199368199369199370199371199372199373199374199375199376199377199378199379199380199381199382199383199384199385199386199387199388199389199390199391199392199393199394199395199396199397199398199399199400199401199402199403199404199405199406199407199408199409199410199411199412199413199414199415199416199417199418199419199420199421199422199423199424199425199426199427199428199429199430199431199432199433199434199435199436199437199438199439199440199441199442199443199444199445199446199447199448199449199450199451199452199453199454199455199456199457199458199459199460199461199462199463199464199465199466199467199468199469199470199471199472199473199474199475199476199477199478199479199480199481199482199483199484199485199486199487199488199489199490199491199492199493199494199495199496199497199498199499199500199501199502199503199504199505199506199507199508199509199510199511199512199513199514199515199516199517199518199519199520199521199522199523199524199525199526199527199528199529199530199531199532199533199534199535199536199537199538199539199540199541199542199543199544199545199546199547199548199549199550199551199552199553199554199555199556199557199558199559199560199561199562199563199564199565199566199567199568199569199570199571199572199573199574199575199576199577199578199579199580199581199582199583199584199585199586199587199588199589199590199591199592199593199594199595199596199597199598199599199600199601199602199603199604199605199606199607199608199609199610199611199612199613199614199615199616199617199618199619199620199621199622199623199624199625199626199627199628199629199630199631199632199633199634199635199636199637199638199639199640199641199642199643199644199645199646199647199648199649199650199651199652199653199654199655199656199657199658199659199660199661199662199663199664199665199666199667199668199669199670199671199672199673199674199675199676199677199678199679199680199681199682199683199684199685199686199687199688199689199690199691199692199693199694199695199696199697199698199699199700199701199702199703199704199705199706199707199708199709199710199711199712199713199714199715199716199717199718199719199720199721199722199723199724199725199726199727199728199729199730199731199732199733199734199735199736199737199738199739199740199741199742199743199744199745199746199747199748199749199750199751199752199753199754199755199756199757199758199759199760199761199762199763199764199765199766199767199768199769199770199771199772199773199774199775199776199777199778199779199780199781199782199783199784199785199786199787199788199789199790199791199792199793199794199795199796199797199798199799199800199801199802199803199804199805199806199807199808199809199810199811199812199813199814199815199816199817199818199819199820199821199822199823199824199825199826199827199828199829199830199831199832199833199834199835199836199837199838199839199840199841199842199843199844199845199846199847199848199849199850199851199852199853199854199855199856199857199858199859199860199861199862199863199864199865199866199867199868199869199870199871199872199873199874199875199876199877199878199879199880199881199882199883199884199885199886199887199888199889199890199891199892199893199894199895199896199897199898199899199900199901199902199903199904199905199906199907199908199909199910199911199912199913199914199915199916199917199918199919199920199921199922199923199924199925199926199927199928199929199930199931199932199933199934199935199936199937199938199939199940199941199942199943199944199945199946199947199948199949199950199951199952199953199954199955199956199957199958199959199960199961199962199963199964199965199966199967199968199969199970199971199972199973199974199975199976199977199978199979199980199981199982199983199984199985199986199987199988199989199990199991199992199993199994199995199996199997199998199999200000200001200002200003200004200005200006200007200008200009200010200011200012200013200014200015200016200017200018200019200020200021200022200023200024200025200026200027200028200029200030200031200032200033200034200035200036200037200038200039200040200041200042200043200044200045200046200047200048200049200050200051200052200053200054200055200056200057200058200059200060200061200062200063200064200065200066200067200068200069200070200071200072200073200074200075200076200077200078200079200080200081200082200083200084200085200086200087200088200089200090200091200092200093200094200095200096200097200098200099200100200101200102200103200104200105200106200107200108200109200110200111200112200113200114200115200116200117200118200119200120200121200122200123200124200125200126200127200128200129200130200131200132200133200134200135200136200137200138200139200140200141200142200143200144200145200146200147200148200149200150200151200152200153200154200155200156200157200158200159200160200161200162200163200164200165200166200167200168200169200170200171200172200173200174200175200176200177200178200179200180200181200182200183200184200185200186200187200188200189200190200191200192200193200194200195200196200197200198200199200200200201200202200203200204200205200206200207200208200209200210200211200212200213200214200215200216200217200218200219200220200221200222200223200224200225200226200227200228200229200230200231200232200233200234200235200236200237200238200239200240200241200242200243200244200245200246200247200248200249200250200251200252200253200254200255200256200257200258200259200260200261200262200263200264200265200266200267200268200269200270200271200272200273200274200275200276200277200278200279200280200281200282200283200284200285200286200287200288200289200290200291200292200293200294200295200296200297200298200299200300200301200302200303200304200305200306200307200308200309200310200311200312200313200314200315200316200317200318200319200320200321200322200323200324200325200326200327200328200329200330200331200332200333200334200335200336200337200338200339200340200341200342200343200344200345200346200347200348200349200350200351200352200353200354200355200356200357200358200359200360200361200362200363200364200365200366200367200368200369200370200371200372200373200374200375200376200377200378200379200380200381200382200383200384200385200386200387200388200389200390200391200392200393200394200395200396200397200398200399200400200401200402200403200404200405200406200407200408200409200410200411200412200413200414200415200416200417200418200419200420200421200422200423200424200425200426200427200428200429200430200431200432200433200434200435200436200437200438200439200440200441200442200443200444200445200446200447200448200449200450200451200452200453200454200455200456200457200458200459200460200461200462200463200464200465200466200467200468200469200470200471200472200473200474200475200476200477200478200479200480200481200482200483200484200485200486200487200488200489200490200491200492200493200494200495200496200497200498200499200500200501200502200503200504200505200506200507200508200509200510200511200512200513200514200515200516200517200518200519200520200521200522200523200524200525200526200527200528200529200530200531200532200533200534200535200536200537200538200539200540200541200542200543200544200545200546200547200548200549200550200551200552200553200554200555200556200557200558200559200560200561200562200563200564200565200566200567200568200569200570200571200572200573200574200575200576200577200578200579200580200581200582200583200584200585200586200587200588200589200590200591200592200593200594200595200596200597200598200599200600200601200602200603200604200605200606200607200608200609200610200611200612200613200614200615200616200617200618200619200620200621200622200623200624200625200626200627200628200629200630200631200632200633200634200635200636200637200638200639200640200641200642200643200644200645200646200647200648200649200650200651200652200653200654200655200656200657200658200659200660200661200662200663200664200665200666200667200668200669200670200671200672200673200674200675200676200677200678200679200680200681200682200683200684200685200686200687200688200689200690200691200692200693200694200695200696200697200698200699200700200701200702200703200704200705200706200707200708200709200710200711200712200713200714200715200716200717200718200719200720200721200722200723200724200725200726200727200728200729200730200731200732200733200734200735200736200737200738200739200740200741200742200743200744200745200746200747200748200749200750200751200752200753200754200755200756200757200758200759200760200761200762200763200764200765200766200767200768200769200770200771200772200773200774200775200776200777200778200779200780200781200782200783200784200785200786200787200788200789200790200791200792200793200794200795200796200797200798200799200800200801200802200803200804200805200806200807200808200809200810200811200812200813200814200815200816200817200818200819200820200821200822200823200824200825200826200827200828200829200830200831200832200833200834200835200836200837200838200839200840200841200842200843200844200845200846200847200848200849200850200851200852200853200854200855200856200857200858200859200860200861200862200863200864200865200866200867200868200869200870200871200872200873200874200875200876200877200878200879200880200881200882200883200884200885200886200887200888200889200890200891200892200893200894200895200896200897200898200899200900200901200902200903200904200905200906200907200908200909200910200911200912200913200914200915200916200917200918200919200920200921200922200923200924200925200926200927200928200929200930200931200932200933200934200935200936200937200938200939200940200941200942200943200944200945200946200947200948200949200950200951200952200953200954200955200956200957200958200959200960200961200962200963200964200965200966200967200968200969200970200971200972200973200974200975200976200977200978200979200980200981200982200983200984200985200986200987200988200989200990200991200992200993200994200995200996200997200998200999201000201001201002201003201004201005201006201007201008201009201010201011201012201013201014201015201016201017201018201019201020201021201022201023201024201025201026201027201028201029201030201031201032201033201034201035201036201037201038201039201040201041201042201043201044201045201046201047201048201049201050201051201052201053201054201055201056201057201058201059201060201061201062201063201064201065201066201067201068201069201070201071201072201073201074201075201076201077201078201079201080201081201082201083201084201085201086201087201088201089201090201091201092201093201094201095201096201097201098201099201100201101201102201103201104201105201106201107201108201109201110201111201112201113201114201115201116201117201118201119201120201121201122201123201124201125201126201127201128201129201130201131201132201133201134201135201136201137201138201139201140201141201142201143201144201145201146201147201148201149201150201151201152201153201154201155201156201157201158201159201160201161201162201163201164201165201166201167201168201169201170201171201172201173201174201175201176201177201178201179201180201181201182201183201184201185201186201187201188201189201190201191201192201193201194201195201196201197201198201199201200201201201202201203201204201205201206201207201208201209201210201211201212201213201214201215201216201217201218201219201220201221201222201223201224201225201226201227201228201229201230201231201232201233201234201235201236201237201238201239201240201241201242201243201244201245201246201247201248201249201250201251201252201253201254201255201256201257201258201259201260201261201262201263201264201265201266201267201268201269201270201271201272201273201274201275201276201277201278201279201280201281201282201283201284201285201286201287201288201289201290201291201292201293201294201295201296201297201298201299201300201301201302201303201304201305201306201307201308201309201310201311201312201313201314201315201316201317201318201319201320201321201322201323201324201325201326201327201328201329201330201331201332201333201334201335201336201337201338201339201340201341201342201343201344201345201346201347201348201349201350201351201352201353201354201355201356201357201358201359201360201361201362201363201364201365201366201367201368201369201370201371201372201373201374201375201376201377201378201379201380201381201382201383201384201385201386201387201388201389201390201391201392201393201394201395201396201397201398201399201400201401201402201403201404201405201406201407201408201409201410201411201412201413201414201415201416201417201418201419201420201421201422201423201424201425201426201427201428201429201430201431201432201433201434201435201436201437201438201439201440201441201442201443201444201445201446201447201448201449201450201451201452201453201454201455201456201457201458201459201460201461201462201463201464201465201466201467201468201469201470201471201472201473201474201475201476201477201478201479201480201481201482201483201484201485201486201487201488201489201490201491201492201493201494201495201496201497201498201499201500201501201502201503201504201505201506201507201508201509201510201511201512201513201514201515201516201517201518201519201520201521201522201523201524201525201526201527201528201529201530201531201532201533201534201535201536201537201538201539201540201541201542201543201544201545201546201547201548201549201550201551201552201553201554201555201556201557201558201559201560201561201562201563201564201565201566201567201568201569201570201571201572201573201574201575201576201577201578201579201580201581201582201583201584201585201586201587201588201589201590201591201592201593201594201595201596201597201598201599201600201601201602201603201604201605201606201607201608201609201610201611201612201613201614201615201616201617201618201619201620201621201622201623201624201625201626201627201628201629201630201631201632201633201634201635201636201637201638201639201640201641201642201643201644201645201646201647201648201649201650201651201652201653201654201655201656201657201658201659201660201661201662201663201664201665201666201667201668201669201670201671201672201673201674201675201676201677201678201679201680201681201682201683201684201685201686201687201688201689201690201691201692201693201694201695201696201697201698201699201700201701201702201703201704201705201706201707201708201709201710201711201712201713201714201715201716201717201718201719201720201721201722201723201724201725201726201727201728201729201730201731201732201733201734201735201736201737201738201739201740201741201742201743201744201745201746201747201748201749201750201751201752201753201754201755201756201757201758201759201760201761201762201763201764201765201766201767201768201769201770201771201772201773201774201775201776201777201778201779201780201781201782201783201784201785201786201787201788201789201790201791201792201793201794201795201796201797201798201799201800201801201802201803201804201805201806201807201808201809201810201811201812201813201814201815201816201817201818201819201820201821201822201823201824201825201826201827201828201829201830201831201832201833201834201835201836201837201838201839201840201841201842201843201844201845201846201847201848201849201850201851201852201853201854201855201856201857201858201859201860201861201862201863201864201865201866201867201868201869201870201871201872201873201874201875201876201877201878201879201880201881201882201883201884201885201886201887201888201889201890201891201892201893201894201895201896201897201898201899201900201901201902201903201904201905201906201907201908201909201910201911201912201913201914201915201916201917201918201919201920201921201922201923201924201925201926201927201928201929201930201931201932201933201934201935201936201937201938201939201940201941201942201943201944201945201946201947201948201949201950201951201952201953201954201955201956201957201958201959201960201961201962201963201964201965201966201967201968201969201970201971201972201973201974201975201976201977201978201979201980201981201982201983201984201985201986201987201988201989201990201991201992201993201994201995201996201997201998201999202000202001202002202003202004202005202006202007202008202009202010202011202012202013202014202015202016202017202018202019202020202021202022202023202024202025202026202027202028202029202030202031202032202033202034202035202036202037202038202039202040202041202042202043202044202045202046202047202048202049202050202051202052202053202054202055202056202057202058202059202060202061202062202063202064202065202066202067202068202069202070202071202072202073202074202075202076202077202078202079202080202081202082202083202084202085202086202087202088202089202090202091202092202093202094202095202096202097202098202099202100202101202102202103202104202105202106202107202108202109202110202111202112202113202114202115202116202117202118202119202120202121202122202123202124202125202126202127202128202129202130202131202132202133202134202135202136202137202138202139202140202141202142202143202144202145202146202147202148202149202150202151202152202153202154202155202156202157202158202159202160202161202162202163202164202165202166202167202168202169202170202171202172202173202174202175202176202177202178202179202180202181202182202183202184202185202186202187202188202189202190202191202192202193202194202195202196202197202198202199202200202201202202202203202204202205202206202207202208202209202210202211202212202213202214202215202216202217202218202219202220202221202222202223202224202225202226202227202228202229202230202231202232202233202234202235202236202237202238202239202240202241202242202243202244202245202246202247202248202249202250202251202252202253202254202255202256202257202258202259202260202261202262202263202264202265202266202267202268202269202270202271202272202273202274202275202276202277202278202279202280202281202282202283202284202285202286202287202288202289202290202291202292202293202294202295202296202297202298202299202300202301202302202303202304202305202306202307202308202309202310202311202312202313202314202315202316202317202318202319202320202321202322202323202324202325202326202327202328202329202330202331202332202333202334202335202336202337202338202339202340202341202342202343202344202345202346202347202348202349202350202351202352202353202354202355202356202357202358202359202360202361202362202363202364202365202366202367202368202369202370202371202372202373202374202375202376202377202378202379202380202381202382202383202384202385202386202387202388202389202390202391202392202393202394202395202396202397202398202399202400202401202402202403202404202405202406202407202408202409202410202411202412202413202414202415202416202417202418202419202420202421202422202423202424202425202426202427202428202429202430202431202432202433202434202435202436202437202438202439202440202441202442202443202444202445202446202447202448202449202450202451202452202453202454202455202456202457202458202459202460202461202462202463202464202465202466202467202468202469202470202471202472202473202474202475202476202477202478202479202480202481202482202483202484202485202486202487202488202489202490202491202492202493202494202495202496202497202498202499202500202501202502202503202504202505202506202507202508202509202510202511202512202513202514202515202516202517202518202519202520202521202522202523202524202525202526202527202528202529202530202531202532202533202534202535202536202537202538202539202540202541202542202543202544202545202546202547202548202549202550202551202552202553202554202555202556202557202558202559202560202561202562202563202564202565202566202567202568202569202570202571202572202573202574202575202576202577202578202579202580202581202582202583202584202585202586202587202588202589202590202591202592202593202594202595202596202597202598202599202600202601202602202603202604202605202606202607202608202609202610202611202612202613202614202615202616202617202618202619202620202621202622202623202624202625202626202627202628202629202630202631202632202633202634202635202636202637202638202639202640202641202642202643202644202645202646202647202648202649202650202651202652202653202654202655202656202657202658202659202660202661202662202663202664202665202666202667202668202669202670202671202672202673202674202675202676202677202678202679202680202681202682202683202684202685202686202687202688202689202690202691202692202693202694202695202696202697202698202699202700202701202702202703202704202705202706202707202708202709202710202711202712202713202714202715202716202717202718202719202720202721202722202723202724202725202726202727202728202729202730202731202732202733202734202735202736202737202738202739202740202741202742202743202744202745202746202747202748202749202750202751202752202753202754202755202756202757202758202759202760202761202762202763202764202765202766202767202768202769202770202771202772202773202774202775202776202777202778202779202780202781202782202783202784202785202786202787202788202789202790202791202792202793202794202795202796202797202798202799202800202801202802202803202804202805202806202807202808202809202810202811202812202813202814202815202816202817202818202819202820202821202822202823202824202825202826202827202828202829202830202831202832202833202834202835202836202837202838202839202840202841202842202843202844202845202846202847202848202849202850202851202852202853202854202855202856202857202858202859202860202861202862202863202864202865202866202867202868202869202870202871202872202873202874202875202876202877202878202879202880202881202882202883202884202885202886202887202888202889202890202891202892202893202894202895202896202897202898202899202900202901202902202903202904202905202906202907202908202909202910202911202912202913202914202915202916202917202918202919202920202921202922202923202924202925202926202927202928202929202930202931202932202933202934202935202936202937202938202939202940202941202942202943202944202945202946202947202948202949202950202951202952202953202954202955202956202957202958202959202960202961202962202963202964202965202966202967202968202969202970202971202972202973202974202975202976202977202978202979202980202981202982202983202984202985202986202987202988202989202990202991202992202993202994202995202996202997202998202999203000203001203002203003203004203005203006203007203008203009203010203011203012203013203014203015203016203017203018203019203020203021203022203023203024203025203026203027203028203029203030203031203032203033203034203035203036203037203038203039203040203041203042203043203044203045203046203047203048203049203050203051203052203053203054203055203056203057203058203059203060203061203062203063203064203065203066203067203068203069203070203071203072203073203074203075203076203077203078203079203080203081203082203083203084203085203086203087203088203089203090203091203092203093203094203095203096203097203098203099203100203101203102203103203104203105203106203107203108203109203110203111203112203113203114203115203116203117203118203119203120203121203122203123203124203125203126203127203128203129203130203131203132203133203134203135203136203137203138203139203140203141203142203143203144203145203146203147203148203149203150203151203152203153203154203155203156203157203158203159203160203161203162203163203164203165203166203167203168203169203170203171203172203173203174203175203176203177203178203179203180203181203182203183203184203185203186203187203188203189203190203191203192203193203194203195203196203197203198203199203200203201203202203203203204203205203206203207203208203209203210203211203212203213203214203215203216203217203218203219203220203221203222203223203224203225203226203227203228203229203230203231203232203233203234203235203236203237203238203239203240203241203242203243203244203245203246203247203248203249203250203251203252203253203254203255203256203257203258203259203260203261203262203263203264203265203266203267203268203269203270203271203272203273203274203275203276203277203278203279203280203281203282203283203284203285203286203287203288203289203290203291203292203293203294203295203296203297203298203299203300203301203302203303203304203305203306203307203308203309203310203311203312203313203314203315203316203317203318203319203320203321203322203323203324203325203326203327203328203329203330203331203332203333203334203335203336203337203338203339203340203341203342203343203344203345203346203347203348203349203350203351203352203353203354203355203356203357203358203359203360203361203362203363203364203365203366203367203368203369203370203371203372203373203374203375203376203377203378203379203380203381203382203383203384203385203386203387203388203389203390203391203392203393203394203395203396203397203398203399203400203401203402203403203404203405203406203407203408203409203410203411203412203413203414203415203416203417203418203419203420203421203422203423203424203425203426203427203428203429203430203431203432203433203434203435203436203437203438203439203440203441203442203443203444203445203446203447203448203449203450203451203452203453203454203455203456203457203458203459203460203461203462203463203464203465203466203467203468203469203470203471203472203473203474203475203476203477203478203479203480203481203482203483203484203485203486203487203488203489203490203491203492203493203494203495203496203497203498203499203500203501203502203503203504203505203506203507203508203509203510203511203512203513203514203515203516203517203518203519203520203521203522203523203524203525203526203527203528203529203530203531203532203533203534203535203536203537203538203539203540203541203542203543203544203545203546203547203548203549203550203551203552203553203554203555203556203557203558203559203560203561203562203563203564203565203566203567203568203569203570203571203572203573203574203575203576203577203578203579203580203581203582203583203584203585203586203587203588203589203590203591203592203593203594203595203596203597203598203599203600203601203602203603203604203605203606203607203608203609203610203611203612203613203614203615203616203617203618203619203620203621203622203623203624203625203626203627203628203629203630203631203632203633203634203635203636203637203638203639203640203641203642203643203644203645203646203647203648203649203650203651203652203653203654203655203656203657203658203659203660203661203662203663203664203665203666203667203668203669203670203671203672203673203674203675203676203677203678203679203680203681203682203683203684203685203686203687203688203689203690203691203692203693203694203695203696203697203698203699203700203701203702203703203704203705203706203707203708203709203710203711203712203713203714203715203716203717203718203719203720203721203722203723203724203725203726203727203728203729203730203731203732203733203734203735203736203737203738203739203740203741203742203743203744203745203746203747203748203749203750203751203752203753203754203755203756203757203758203759203760203761203762203763203764203765203766203767203768203769203770203771203772203773203774203775203776203777203778203779203780203781203782203783203784203785203786203787203788203789203790203791203792203793203794203795203796203797203798203799203800203801203802203803203804203805203806203807203808203809203810203811203812203813203814203815203816203817203818203819203820203821203822203823203824203825203826203827203828203829203830203831203832203833203834203835203836203837203838203839203840203841203842203843203844203845203846203847203848203849203850203851203852203853203854203855203856203857203858203859203860203861203862203863203864203865203866203867203868203869203870203871203872203873203874203875203876203877203878203879203880203881203882203883203884203885203886203887203888203889203890203891203892203893203894203895203896203897203898203899203900203901203902203903203904203905203906203907203908203909203910203911203912203913203914203915203916203917203918203919203920203921203922203923203924203925203926203927203928203929203930203931203932203933203934203935203936203937203938203939203940203941203942203943203944203945203946203947203948203949203950203951203952203953203954203955203956203957203958203959203960203961203962203963203964203965203966203967203968203969203970203971203972203973203974203975203976203977203978203979203980203981203982203983203984203985203986203987203988203989203990203991203992203993203994203995203996203997203998203999204000204001204002204003204004204005204006204007204008204009204010204011204012204013204014204015204016204017204018204019204020204021204022204023204024204025204026204027204028204029204030204031204032204033204034204035204036204037204038204039204040204041204042204043204044204045204046204047204048204049204050204051204052204053204054204055204056204057204058204059204060204061204062204063204064204065204066204067204068204069204070204071204072204073204074204075204076204077204078204079204080204081204082204083204084204085204086204087204088204089204090204091204092204093204094204095204096204097204098204099204100204101204102204103204104204105204106204107204108204109204110204111204112204113204114204115204116204117204118204119204120204121204122204123204124204125204126204127204128204129204130204131204132204133204134204135204136204137204138204139204140204141204142204143204144204145204146204147204148204149204150204151204152204153204154204155204156204157204158204159204160204161204162204163204164204165204166204167204168204169204170204171204172204173204174204175204176204177204178204179204180204181204182204183204184204185204186204187204188204189204190204191204192204193204194204195204196204197204198204199204200204201204202204203204204204205204206204207204208204209204210204211204212204213204214204215204216204217204218204219204220204221204222204223204224204225204226204227204228204229204230204231204232204233204234204235204236204237204238204239204240204241204242204243204244204245204246204247204248204249204250204251204252204253204254204255204256204257204258204259204260204261204262204263204264204265204266204267204268204269204270204271204272204273204274204275204276204277204278204279204280204281204282204283204284204285204286204287204288204289204290204291204292204293204294204295204296204297204298204299204300204301204302204303204304204305204306204307204308204309204310204311204312204313204314204315204316204317204318204319204320204321204322204323204324204325204326204327204328204329204330204331204332204333204334204335204336204337204338204339204340204341204342204343204344204345204346204347204348204349204350204351204352204353204354204355204356204357204358204359204360204361204362204363204364204365204366204367204368204369204370204371204372204373204374204375204376204377204378204379204380204381204382204383204384204385204386204387204388204389204390204391204392204393204394204395204396204397204398204399204400204401204402204403204404204405204406204407204408204409204410204411204412204413204414204415204416204417204418204419204420204421204422204423204424204425204426204427204428204429204430204431204432204433204434204435204436204437204438204439204440204441204442204443204444204445204446204447204448204449204450204451204452204453204454204455204456204457204458204459204460204461204462204463204464204465204466204467204468204469204470204471204472204473204474204475204476204477204478204479204480204481204482204483204484204485204486204487204488204489204490204491204492204493204494204495204496204497204498204499204500204501204502204503204504204505204506204507204508204509204510204511204512204513204514204515204516204517204518204519204520204521204522204523204524204525204526204527204528204529204530204531204532204533204534204535204536204537204538204539204540204541204542204543204544204545204546204547204548204549204550204551204552204553204554204555204556204557204558204559204560204561204562204563204564204565204566204567204568204569204570204571204572204573204574204575204576204577204578204579204580204581204582204583204584204585204586204587204588204589204590204591204592204593204594204595204596204597204598204599204600204601204602204603204604204605204606204607204608204609204610204611204612204613204614204615204616204617204618204619204620204621204622204623204624204625204626204627204628204629204630204631204632204633204634204635204636204637204638204639204640204641204642204643204644204645204646204647204648204649204650204651204652204653204654204655204656204657204658204659204660204661204662204663204664204665204666204667204668204669204670204671204672204673204674204675204676204677204678204679204680204681204682204683204684204685204686204687204688204689204690204691204692204693204694204695204696204697204698204699204700204701204702204703204704204705204706204707204708204709204710204711204712204713204714204715204716204717204718204719204720204721204722204723204724204725204726204727204728204729204730204731204732204733204734204735204736204737204738204739204740204741204742204743204744204745204746204747204748204749204750204751204752204753204754204755204756204757204758204759204760204761204762204763204764204765204766204767204768204769204770204771204772204773204774204775204776204777204778204779204780204781204782204783204784204785204786204787204788204789204790204791204792204793204794204795204796204797204798204799204800204801204802204803204804204805204806204807204808204809204810204811204812204813204814204815204816204817204818204819204820204821204822204823204824204825204826204827204828204829204830204831204832204833204834204835204836204837204838204839204840204841204842204843204844204845204846204847204848204849204850204851204852204853204854204855204856204857204858204859204860204861204862204863204864204865204866204867204868204869204870204871204872204873204874204875204876204877204878204879204880204881204882204883204884204885204886204887204888204889204890204891204892204893204894204895204896204897204898204899204900204901204902204903204904204905204906204907204908204909204910204911204912204913204914204915204916204917204918204919204920204921204922204923204924204925204926204927204928204929204930204931204932204933204934204935204936204937204938204939204940204941204942204943204944204945204946204947204948204949204950204951204952204953204954204955204956204957204958204959204960204961204962204963204964204965204966204967204968204969204970204971204972204973204974204975204976204977204978204979204980204981204982204983204984204985204986204987204988204989204990204991204992204993204994204995204996204997204998204999205000205001205002205003205004205005205006205007205008205009205010205011205012205013205014205015205016205017205018205019205020205021205022205023205024205025205026205027205028205029205030205031205032205033205034205035205036205037205038205039205040205041205042205043205044205045205046205047205048205049205050205051205052205053205054205055205056205057205058205059205060205061205062205063205064205065205066205067205068205069205070205071205072205073205074205075205076205077205078205079205080205081205082205083205084205085205086205087205088205089205090205091205092205093205094205095205096205097205098205099205100205101205102205103205104205105205106205107205108205109205110205111205112205113205114205115205116205117205118205119205120205121205122205123205124205125205126205127205128205129205130205131205132205133205134205135205136205137205138205139205140205141205142205143205144205145205146205147205148205149205150205151205152205153205154205155205156205157205158205159205160205161205162205163205164205165205166205167205168205169205170205171205172205173205174205175205176205177205178205179205180205181205182205183205184205185205186205187205188205189205190205191205192205193205194205195205196205197205198205199205200205201205202205203205204205205205206205207205208205209205210205211205212205213205214205215205216205217205218205219205220205221205222205223205224205225205226205227205228205229205230205231205232205233205234205235205236205237205238205239205240205241205242205243205244205245205246205247205248205249205250205251205252205253205254205255205256205257205258205259205260205261205262205263205264205265205266205267205268205269205270205271205272205273205274205275205276205277205278205279205280205281205282205283205284205285205286205287205288205289205290205291205292205293205294205295205296205297205298205299205300205301205302205303205304205305205306205307205308205309205310205311205312205313205314205315205316205317205318205319205320205321205322205323205324205325205326205327205328205329205330205331205332205333205334205335205336205337205338205339205340205341205342205343205344205345205346205347205348205349205350205351205352205353205354205355205356205357205358205359205360205361205362205363205364205365205366205367205368205369205370205371205372205373205374205375205376205377205378205379205380205381205382205383205384205385205386205387205388205389205390205391205392205393205394205395205396205397205398205399205400205401205402205403205404205405205406205407205408205409205410205411205412205413205414205415205416205417205418205419205420205421205422205423205424205425205426205427205428205429205430205431205432205433205434205435205436205437205438205439205440205441205442205443205444205445205446205447205448205449205450205451205452205453205454205455205456205457205458205459205460205461205462205463205464205465205466205467205468205469205470205471205472205473205474205475205476205477205478205479205480205481205482205483205484205485205486205487205488205489205490205491205492205493205494205495205496205497205498205499205500205501205502205503205504205505205506205507205508205509205510205511205512205513205514205515205516205517205518205519205520205521205522205523205524205525205526205527205528205529205530205531205532205533205534205535205536205537205538205539205540205541205542205543205544205545205546205547205548205549205550205551205552205553205554205555205556205557205558205559205560205561205562205563205564205565205566205567205568205569205570205571205572205573205574205575205576205577205578205579205580205581205582205583205584205585205586205587205588205589205590205591205592205593205594205595205596205597205598205599205600205601205602205603205604205605205606205607205608205609205610205611205612205613205614205615205616205617205618205619205620205621205622205623205624205625205626205627205628205629205630205631205632205633205634205635205636205637205638205639205640205641205642205643205644205645205646205647205648205649205650205651205652205653205654205655205656205657205658205659205660205661205662205663205664205665205666205667205668205669205670205671205672205673205674205675205676205677205678205679205680205681205682205683205684205685205686205687205688205689205690205691205692205693205694205695205696205697205698205699205700205701205702205703205704205705205706205707205708205709205710205711205712205713205714205715205716205717205718205719205720205721205722205723205724205725205726205727205728205729205730205731205732205733205734205735205736205737205738205739205740205741205742205743205744205745205746205747205748205749205750205751205752205753205754205755205756205757205758205759205760205761205762205763205764205765205766205767205768205769205770205771205772205773205774205775205776205777205778205779205780205781205782205783205784205785205786205787205788205789205790205791205792205793205794205795205796205797205798205799205800205801205802205803205804205805205806205807205808205809205810205811205812205813205814205815205816205817205818205819205820205821205822205823205824205825205826205827205828205829205830205831205832205833205834205835205836205837205838205839205840205841205842205843205844205845205846205847205848205849205850205851205852205853205854205855205856205857205858205859205860205861205862205863205864205865205866205867205868205869205870205871205872205873205874205875205876205877205878205879205880205881205882205883205884205885205886205887205888205889205890205891205892205893205894205895205896205897205898205899205900205901205902205903205904205905205906205907205908205909205910205911205912205913205914205915205916205917205918205919205920205921205922205923205924205925205926205927205928205929205930205931205932205933205934205935205936205937205938205939205940205941205942205943205944205945205946205947205948205949205950205951205952205953205954205955205956205957205958205959205960205961205962205963205964205965205966205967205968205969205970205971205972205973205974205975205976205977205978205979205980205981205982205983205984205985205986205987205988205989205990205991205992205993205994205995205996205997205998205999206000206001206002206003206004206005206006206007206008206009206010206011206012206013206014206015206016206017206018206019206020206021206022206023206024206025206026206027206028206029206030206031206032206033206034206035206036206037206038206039206040206041206042206043206044206045206046206047206048206049206050206051206052206053206054206055206056206057206058206059206060206061206062206063206064206065206066206067206068206069206070206071206072206073206074206075206076206077206078206079206080206081206082206083206084206085206086206087206088206089206090206091206092206093206094206095206096206097206098206099206100206101206102206103206104206105206106206107206108206109206110206111206112206113206114206115206116206117206118206119206120206121206122206123206124206125206126206127206128206129206130206131206132206133206134206135206136206137206138206139206140206141206142206143206144206145206146206147206148206149206150206151206152206153206154206155206156206157206158206159206160206161206162206163206164206165206166206167206168206169206170206171206172206173206174206175206176206177206178206179206180206181206182206183206184206185206186206187206188206189206190206191206192206193206194206195206196206197206198206199206200206201206202206203206204206205206206206207206208206209206210206211206212206213206214206215206216206217206218206219206220206221206222206223206224206225206226206227206228206229206230206231206232206233206234206235206236206237206238206239206240206241206242206243206244206245206246206247206248206249206250206251206252206253206254206255206256206257206258206259206260206261206262206263206264206265206266206267206268206269206270206271206272206273206274206275206276206277206278206279206280206281206282206283206284206285206286206287206288206289206290206291206292206293206294206295206296206297206298206299206300206301206302206303206304206305206306206307206308206309206310206311206312206313206314206315206316206317206318206319206320206321206322206323206324206325206326206327206328206329206330206331206332206333206334206335206336206337206338206339206340206341206342206343206344206345206346206347206348206349206350206351206352206353206354206355206356206357206358206359206360206361206362206363206364206365206366206367206368206369206370206371206372206373206374206375206376206377206378206379206380206381206382206383206384206385206386206387206388206389206390206391206392206393206394206395206396206397206398206399206400206401206402206403206404206405206406206407206408206409206410206411206412206413206414206415206416206417206418206419206420206421206422206423206424206425206426206427206428206429206430206431206432206433206434206435206436206437206438206439206440206441206442206443206444206445206446206447206448206449206450206451206452206453206454206455206456206457206458206459206460206461206462206463206464206465206466206467206468206469206470206471206472206473206474206475206476206477206478206479206480206481206482206483206484206485206486206487206488206489206490206491206492206493206494206495206496206497206498206499206500206501206502206503206504206505206506206507206508206509206510206511206512206513206514206515206516206517206518206519206520206521206522206523206524206525206526206527206528206529206530206531206532206533206534206535206536206537206538206539206540206541206542206543206544206545206546206547206548206549206550206551206552206553206554206555206556206557206558206559206560206561206562206563206564206565206566206567206568206569206570206571206572206573206574206575206576206577206578206579206580206581206582206583206584206585206586206587206588206589206590206591206592206593206594206595206596206597206598206599206600206601206602206603206604206605206606206607206608206609206610206611206612206613206614206615206616206617206618206619206620206621206622206623206624206625206626206627206628206629206630206631206632206633206634206635206636206637206638206639206640206641206642206643206644206645206646206647206648206649206650206651206652206653206654206655206656206657206658206659206660206661206662206663206664206665206666206667206668206669206670206671206672206673206674206675206676206677206678206679206680206681206682206683206684206685206686206687206688206689206690206691206692206693206694206695206696206697206698206699206700206701206702206703206704206705206706206707206708206709206710206711206712206713206714206715206716206717206718206719206720206721206722206723206724206725206726206727206728206729206730206731206732206733206734206735206736206737206738206739206740206741206742206743206744206745206746206747206748206749206750206751206752206753206754206755206756206757206758206759206760206761206762206763206764206765206766206767206768206769206770206771206772206773206774206775206776206777206778206779206780206781206782206783206784206785206786206787206788206789206790206791206792206793206794206795206796206797206798206799206800206801206802206803206804206805206806206807206808206809206810206811206812206813206814206815206816206817206818206819206820206821206822206823206824206825206826206827206828206829206830206831206832206833206834206835206836206837206838206839206840206841206842206843206844206845206846206847206848206849206850206851206852206853206854206855206856206857206858206859206860206861206862206863206864206865206866206867206868206869206870206871206872206873206874206875206876206877206878206879206880206881206882206883206884206885206886206887206888206889206890206891206892206893206894206895206896206897206898206899206900206901206902206903206904206905206906206907206908206909206910206911206912206913206914206915206916206917206918206919206920206921206922206923206924206925206926206927206928206929206930206931206932206933206934206935206936206937206938206939206940206941206942206943206944206945206946206947206948206949206950206951206952206953206954206955206956206957206958206959206960206961206962206963206964206965206966206967206968206969206970206971206972206973206974206975206976206977206978206979206980206981206982206983206984206985206986206987206988206989206990206991206992206993206994206995206996206997206998206999207000207001207002207003207004207005207006207007207008207009207010207011207012207013207014207015207016207017207018207019207020207021207022207023207024207025207026207027207028207029207030207031207032207033207034207035207036207037207038207039207040207041207042207043207044207045207046207047207048207049207050207051207052207053207054207055207056207057207058207059207060207061207062207063207064207065207066207067207068207069207070207071207072207073207074207075207076207077207078207079207080207081207082207083207084207085207086207087207088207089207090207091207092207093207094207095207096207097207098207099207100207101207102207103207104207105207106207107207108207109207110207111207112207113207114207115207116207117207118207119207120207121207122207123207124207125207126207127207128207129207130207131207132207133207134207135207136207137207138207139207140207141207142207143207144207145207146207147207148207149207150207151207152207153207154207155207156207157207158207159207160207161207162207163207164207165207166207167207168207169207170207171207172207173207174207175207176207177207178207179207180207181207182207183207184207185207186207187207188207189207190207191207192207193207194207195207196207197207198207199207200207201207202207203207204207205207206207207207208207209207210207211207212207213207214207215207216207217207218207219207220207221207222207223207224207225207226207227207228207229207230207231207232207233207234207235207236207237207238207239207240207241207242207243207244207245207246207247207248207249207250207251207252207253207254207255207256207257207258207259207260207261207262207263207264207265207266207267207268207269207270207271207272207273207274207275207276207277207278207279207280207281207282207283207284207285207286207287207288207289207290207291207292207293207294207295207296207297207298207299207300207301207302207303207304207305207306207307207308207309207310207311207312207313207314207315207316207317207318207319207320207321207322207323207324207325207326207327207328207329207330207331207332207333207334207335207336207337207338207339207340207341207342207343207344207345207346207347207348207349207350207351207352207353207354207355207356207357207358207359207360207361207362207363207364207365207366207367207368207369207370207371207372207373207374207375207376207377207378207379207380207381207382207383207384207385207386207387207388207389207390207391207392207393207394207395207396207397207398207399207400207401207402207403207404207405207406207407207408207409207410207411207412207413207414207415207416207417207418207419207420207421207422207423207424207425207426207427207428207429207430207431207432207433207434207435207436207437207438207439207440207441207442207443207444207445207446207447207448207449207450207451207452207453207454207455207456207457207458207459207460207461207462207463207464207465207466207467207468207469207470207471207472207473207474207475207476207477207478207479207480207481207482207483207484207485207486207487207488207489207490207491207492207493207494207495207496207497207498207499207500207501207502207503207504207505207506207507207508207509207510207511207512207513207514207515207516207517207518207519207520207521207522207523207524207525207526207527207528207529207530207531207532207533207534207535207536207537207538207539207540207541207542207543207544207545207546207547207548207549207550207551207552207553207554207555207556207557207558207559207560207561207562207563207564207565207566207567207568207569207570207571207572207573207574207575207576207577207578207579207580207581207582207583207584207585207586207587207588207589207590207591207592207593207594207595207596207597207598207599207600207601207602207603207604207605207606207607207608207609207610207611207612207613207614207615207616207617207618207619207620207621207622207623207624207625207626207627207628207629207630207631207632207633207634207635207636207637207638207639207640207641207642207643207644207645207646207647207648207649207650207651207652207653207654207655207656207657207658207659207660207661207662207663207664207665207666207667207668207669207670207671207672207673207674207675207676207677207678207679207680207681207682207683207684207685207686207687207688207689207690207691207692207693207694207695207696207697207698207699207700207701207702207703207704207705207706207707207708207709207710207711207712207713207714207715207716207717207718207719207720207721207722207723207724207725207726207727207728207729207730207731207732207733207734207735207736207737207738207739207740207741207742207743207744207745207746207747207748207749207750207751207752207753207754207755207756207757207758207759207760207761207762207763207764207765207766207767207768207769207770207771207772207773207774207775207776207777207778207779207780207781207782207783207784207785207786207787207788207789207790207791207792207793207794207795207796207797207798207799207800207801207802207803207804207805207806207807207808207809207810207811207812207813207814207815207816207817207818207819207820207821207822207823207824207825207826207827207828207829207830207831207832207833207834207835207836207837207838207839207840207841207842207843207844207845207846207847207848207849207850207851207852207853207854207855207856207857207858207859207860207861207862207863207864207865207866207867207868207869207870207871207872207873207874207875207876207877207878207879207880207881207882207883207884207885207886207887207888207889207890207891207892207893207894207895207896207897207898207899207900207901207902207903207904207905207906207907207908207909207910207911207912207913207914207915207916207917207918207919207920207921207922207923207924207925207926207927207928207929207930207931207932207933207934207935207936207937207938207939207940207941207942207943207944207945207946207947207948207949207950207951207952207953207954207955207956207957207958207959207960207961207962207963207964207965207966207967207968207969207970207971207972207973207974207975207976207977207978207979207980207981207982207983207984207985207986207987207988207989207990207991207992207993207994207995207996207997207998207999208000208001208002208003208004208005208006208007208008208009208010208011208012208013208014208015208016208017208018208019208020208021208022208023208024208025208026208027208028208029208030208031208032208033208034208035208036208037208038208039208040208041208042208043208044208045208046208047208048208049208050208051208052208053208054208055208056208057208058208059208060208061208062208063208064208065208066208067208068208069208070208071208072208073208074208075208076208077208078208079208080208081208082208083208084208085208086208087208088208089208090208091208092208093208094208095208096208097208098208099208100208101208102208103208104208105208106208107208108208109208110208111208112208113208114208115208116208117208118208119208120208121208122208123208124208125208126208127208128208129208130208131208132208133208134208135208136208137208138208139208140208141208142208143208144208145208146208147208148208149208150208151208152208153208154208155208156208157208158208159208160208161208162208163208164208165208166208167208168208169208170208171208172208173208174208175208176208177208178208179208180208181208182208183208184208185208186208187208188208189208190208191208192208193208194208195208196208197208198208199208200208201208202208203208204208205208206208207208208208209208210208211208212208213208214208215208216208217208218208219208220208221208222208223208224208225208226208227208228208229208230208231208232208233208234208235208236208237208238208239208240208241208242208243208244208245208246208247208248208249208250208251208252208253208254208255208256208257208258208259208260208261208262208263208264208265208266208267208268208269208270208271208272208273208274208275208276208277208278208279208280208281208282208283208284208285208286208287208288208289208290208291208292208293208294208295208296208297208298208299208300208301208302208303208304208305208306208307208308208309208310208311208312208313208314208315208316208317208318208319208320208321208322208323208324208325208326208327208328208329208330208331208332208333208334208335208336208337208338208339208340208341208342208343208344208345208346208347208348208349208350208351208352208353208354208355208356208357208358208359208360208361208362208363208364208365208366208367208368208369208370208371208372208373208374208375208376208377208378208379208380208381208382208383208384208385208386208387208388208389208390208391208392208393208394208395208396208397208398208399208400208401208402208403208404208405208406208407208408208409208410208411208412208413208414208415208416208417208418208419208420208421208422208423208424208425208426208427208428208429208430208431208432208433208434208435208436208437208438208439208440208441208442208443208444208445208446208447208448208449208450208451208452208453208454208455208456208457208458208459208460208461208462208463208464208465208466208467208468208469208470208471208472208473208474208475208476208477208478208479208480208481208482208483208484208485208486208487208488208489208490208491208492208493208494208495208496208497208498208499208500208501208502208503208504208505208506208507208508208509208510208511208512208513208514208515208516208517208518208519208520208521208522208523208524208525208526208527208528208529208530208531208532208533208534208535208536208537208538208539208540208541208542208543208544208545208546208547208548208549208550208551208552208553208554208555208556208557208558208559208560208561208562208563208564208565208566208567208568208569208570208571208572208573208574208575208576208577208578208579208580208581208582208583208584208585208586208587208588208589208590208591208592208593208594208595208596208597208598208599208600208601208602208603208604208605208606208607208608208609208610208611208612208613208614208615208616208617208618208619208620208621208622208623208624208625208626208627208628208629208630208631208632208633208634208635208636208637208638208639208640208641208642208643208644208645208646208647208648208649208650208651208652208653208654208655208656208657208658208659208660208661208662208663208664208665208666208667208668208669208670208671208672208673208674208675208676208677208678208679208680208681208682208683208684208685208686208687208688208689208690208691208692208693208694208695208696208697208698208699208700208701208702208703208704208705208706208707208708208709208710208711208712208713208714208715208716208717208718208719208720208721208722208723208724208725208726208727208728208729208730208731208732208733208734208735208736208737208738208739208740208741208742208743208744208745208746208747208748208749208750208751208752208753208754208755208756208757208758208759208760208761208762208763208764208765208766208767208768208769208770208771208772208773208774208775208776208777208778208779208780208781208782208783208784208785208786208787208788208789208790208791208792208793208794208795208796208797208798208799208800208801208802208803208804208805208806208807208808208809208810208811208812208813208814208815208816208817208818208819208820208821208822208823208824208825208826208827208828208829208830208831208832208833208834208835208836208837208838208839208840208841208842208843208844208845208846208847208848208849208850208851208852208853208854208855208856208857208858208859208860208861208862208863208864208865208866208867208868208869208870208871208872208873208874208875208876208877208878208879208880208881208882208883208884208885208886208887208888208889208890208891208892208893208894208895208896208897208898208899208900208901208902208903208904208905208906208907208908208909208910208911208912208913208914208915208916208917208918208919208920208921208922208923208924208925208926208927208928208929208930208931208932208933208934208935208936208937208938208939208940208941208942208943208944208945208946208947208948208949208950208951208952208953208954208955208956208957208958208959208960208961208962208963208964208965208966208967208968208969208970208971208972208973208974208975208976208977208978208979208980208981208982208983208984208985208986208987208988208989208990208991208992208993208994208995208996208997208998208999209000209001209002209003209004209005209006209007209008209009209010209011209012209013209014209015209016209017209018209019209020209021209022209023209024209025209026209027209028209029209030209031209032209033209034209035209036209037209038209039209040209041209042209043209044209045209046209047209048209049209050209051209052209053209054209055209056209057209058209059209060209061209062209063209064209065209066209067209068209069209070209071209072209073209074209075209076209077209078209079209080209081209082209083209084209085209086209087209088209089209090209091209092209093209094209095209096209097209098209099209100209101209102209103209104209105209106209107209108209109209110209111209112209113209114209115209116209117209118209119209120209121209122209123209124209125209126209127209128209129209130209131209132209133209134209135209136209137209138209139209140209141209142209143209144209145209146209147209148209149209150209151209152209153209154209155209156209157209158209159209160209161209162209163209164209165209166209167209168209169209170209171209172209173209174209175209176209177209178209179209180209181209182209183209184209185209186209187209188209189209190209191209192209193209194209195209196209197209198209199209200209201209202209203209204209205209206209207209208209209209210209211209212209213209214209215209216209217209218209219209220209221209222209223209224209225209226209227209228209229209230209231209232209233209234209235209236209237209238209239209240209241209242209243209244209245209246209247209248209249209250209251209252209253209254209255209256209257209258209259209260209261209262209263209264209265209266209267209268209269209270209271209272209273209274209275209276209277209278209279209280209281209282209283209284209285209286209287209288209289209290209291209292209293209294209295209296209297209298209299209300209301209302209303209304209305209306209307209308209309209310209311209312209313209314209315209316209317209318209319209320209321209322209323209324209325209326209327209328209329209330209331209332209333209334209335209336209337209338209339209340209341209342209343209344209345209346209347209348209349209350209351209352209353209354209355209356209357209358209359209360209361209362209363209364209365209366209367209368209369209370209371209372209373209374209375209376209377209378209379209380209381209382209383209384209385209386209387209388209389209390209391209392209393209394209395209396209397209398209399209400209401209402209403209404209405209406209407209408209409209410209411209412209413209414209415209416209417209418209419209420209421209422209423209424209425209426209427209428209429209430209431209432209433209434209435209436209437209438209439209440209441209442209443209444209445209446209447209448209449209450209451209452209453209454209455209456209457209458209459209460209461209462209463209464209465209466209467209468209469209470209471209472209473209474209475209476209477209478209479209480209481209482209483209484209485209486209487209488209489209490209491209492209493209494209495209496209497209498209499209500209501209502209503209504209505209506209507209508209509209510209511209512209513209514209515209516209517209518209519209520209521209522209523209524209525209526209527209528209529209530209531209532209533209534209535209536209537209538209539209540209541209542209543209544209545209546209547209548209549209550209551209552209553209554209555209556209557209558209559209560209561209562209563209564209565209566209567209568209569209570209571209572209573209574209575209576209577209578209579209580209581209582209583209584209585209586209587209588209589209590209591209592209593209594209595209596209597209598209599209600209601209602209603209604209605209606209607209608209609209610209611209612209613209614209615209616209617209618209619209620209621209622209623209624209625209626209627209628209629209630209631209632209633209634209635209636209637209638209639209640209641209642209643209644209645209646209647209648209649209650209651209652209653209654209655209656209657209658209659209660209661209662209663209664209665209666209667209668209669209670209671209672209673209674209675209676209677209678209679209680209681209682209683209684209685209686209687209688209689209690209691209692209693209694209695209696209697209698209699209700209701209702209703209704209705209706209707209708209709209710209711209712209713209714209715209716209717209718209719209720209721209722209723209724209725209726209727209728209729209730209731209732209733209734209735209736209737209738209739209740209741209742209743209744209745209746209747209748209749209750209751209752209753209754209755209756209757209758209759209760209761209762209763209764209765209766209767209768209769209770209771209772209773209774209775209776209777209778209779209780209781209782209783209784209785209786209787209788209789209790209791209792209793209794209795209796209797209798209799209800209801209802209803209804209805209806209807209808209809209810209811209812209813209814209815209816209817209818209819209820209821209822209823209824209825209826209827209828209829209830209831209832209833209834209835209836209837209838209839209840209841209842209843209844209845209846209847209848209849209850209851209852209853209854209855209856209857209858209859209860209861209862209863209864209865209866209867209868209869209870209871209872209873209874209875209876209877209878209879209880209881209882209883209884209885209886209887209888209889209890209891209892209893209894209895209896209897209898209899209900209901209902209903209904209905209906209907209908209909209910209911209912209913209914209915209916209917209918209919209920209921209922209923209924209925209926209927209928209929209930209931209932209933209934209935209936209937209938209939209940209941209942209943209944209945209946209947209948209949209950209951209952209953209954209955209956209957209958209959209960209961209962209963209964209965209966209967209968209969209970209971209972209973209974209975209976209977209978209979209980209981209982209983209984209985209986209987209988209989209990209991209992209993209994209995209996209997209998209999210000210001210002210003210004210005210006210007210008210009210010210011210012210013210014210015210016210017210018210019210020210021210022210023210024210025210026210027210028210029210030210031210032210033210034210035210036210037210038210039210040210041210042210043210044210045210046210047210048210049210050210051210052210053210054210055210056210057210058210059210060210061210062210063210064210065210066210067210068210069210070210071210072210073210074210075210076210077210078210079210080210081210082210083210084210085210086210087210088210089210090210091210092210093210094210095210096210097210098210099210100210101210102210103210104210105210106210107210108210109210110210111210112210113210114210115210116210117210118210119210120210121210122210123210124210125210126210127210128210129210130210131210132210133210134210135210136210137210138210139210140210141210142210143210144210145210146210147210148210149210150210151210152210153210154210155210156210157210158210159210160210161210162210163210164210165210166210167210168210169210170210171210172210173210174210175210176210177210178210179210180210181210182210183210184210185210186210187210188210189210190210191210192210193210194210195210196210197210198210199210200210201210202210203210204210205210206210207210208210209210210210211210212210213210214210215210216210217210218210219210220210221210222210223210224210225210226210227210228210229210230210231210232210233210234210235210236210237210238210239210240210241210242210243210244210245210246210247210248210249210250210251210252210253210254210255210256210257210258210259210260210261210262210263210264210265210266210267210268210269210270210271210272210273210274210275210276210277210278210279210280210281210282210283210284210285210286210287210288210289210290210291210292210293210294210295210296210297210298210299210300210301210302210303210304210305210306210307210308210309210310210311210312210313210314210315210316210317210318210319210320210321210322210323210324210325210326210327210328210329210330210331210332210333210334210335210336210337210338210339210340210341210342210343210344210345210346210347210348210349210350210351210352210353210354210355210356210357210358210359210360210361210362210363210364210365210366210367210368210369210370210371210372210373210374210375210376210377210378210379210380210381210382210383210384210385210386210387210388210389210390210391210392210393210394210395210396210397210398210399210400210401210402210403210404210405210406210407210408210409210410210411210412210413210414210415210416210417210418210419210420210421210422210423210424210425210426210427210428210429210430210431210432210433210434210435210436210437210438210439210440210441210442210443210444210445210446210447210448210449210450210451210452210453210454210455210456210457210458210459210460210461210462210463210464210465210466210467210468210469210470210471210472210473210474210475210476210477210478210479210480210481210482210483210484210485210486210487210488210489210490210491210492210493210494210495210496210497210498210499210500210501210502210503210504210505210506210507210508210509210510210511210512210513210514210515210516210517210518210519210520210521210522210523210524210525210526210527210528210529210530210531210532210533210534210535210536210537210538210539210540210541210542210543210544210545210546210547210548210549210550210551210552210553210554210555210556210557210558210559210560210561210562210563210564210565210566210567210568210569210570210571210572210573210574210575210576210577210578210579210580210581210582210583210584210585210586210587210588210589210590210591210592210593210594210595210596210597210598210599210600210601210602210603210604210605210606210607210608210609210610210611210612210613210614210615210616210617210618210619210620210621210622210623210624210625210626210627210628210629210630210631210632210633210634210635210636210637210638210639210640210641210642210643210644210645210646210647210648210649210650210651210652210653210654210655210656210657210658210659210660210661210662210663210664210665210666210667210668210669210670210671210672210673210674210675210676210677210678210679210680210681210682210683210684210685210686210687210688210689210690210691210692210693210694210695210696210697210698210699210700210701210702210703210704210705210706210707210708210709210710210711210712210713210714210715210716210717210718210719210720210721210722210723210724210725210726210727210728210729210730210731210732210733210734210735210736210737210738210739210740210741210742210743210744210745210746210747210748210749210750210751210752210753210754210755210756210757210758210759210760210761210762210763210764210765210766210767210768210769210770210771210772210773210774210775210776210777210778210779210780210781210782210783210784210785210786210787210788210789210790210791210792210793210794210795210796210797210798210799210800210801210802210803210804210805210806210807210808210809210810210811210812210813210814210815210816210817210818210819210820210821210822210823210824210825210826210827210828210829210830210831210832210833210834210835210836210837210838210839210840210841210842210843210844210845210846210847210848210849210850210851210852210853210854210855210856210857210858210859210860210861210862210863210864210865210866210867210868210869210870210871210872210873210874210875210876210877210878210879210880210881210882210883210884210885210886210887210888210889210890210891210892210893210894210895210896210897210898210899210900210901210902210903210904210905210906210907210908210909210910210911210912210913210914210915210916210917210918210919210920210921210922210923210924210925210926210927210928210929210930210931210932210933210934210935210936210937210938210939210940210941210942210943210944210945210946210947210948210949210950210951210952210953210954210955210956210957210958210959210960210961210962210963210964210965210966210967210968210969210970210971210972210973210974210975210976210977210978210979210980210981210982210983210984210985210986210987210988210989210990210991210992210993210994210995210996210997210998210999211000211001211002211003211004211005211006211007211008211009211010211011211012211013211014211015211016211017211018211019211020211021211022211023211024211025211026211027211028211029211030211031211032211033211034211035211036211037211038211039211040211041211042211043211044211045211046211047211048211049211050211051211052211053211054211055211056211057211058211059211060211061211062211063211064211065211066211067211068211069211070211071211072211073211074211075211076211077211078211079211080211081211082211083211084211085211086211087211088211089211090211091211092211093211094211095211096211097211098211099211100211101211102211103211104211105211106211107211108211109211110211111211112211113211114211115211116211117211118211119211120211121211122211123211124211125211126211127211128211129211130211131211132211133211134211135211136211137211138211139211140211141211142211143211144211145211146211147211148211149211150211151211152211153211154211155211156211157211158211159211160211161211162211163211164211165211166211167211168211169211170211171211172211173211174211175211176211177211178211179211180211181211182211183211184211185211186211187211188211189211190211191211192211193211194211195211196211197211198211199211200211201211202211203211204211205211206211207211208211209211210211211211212211213211214211215211216211217211218211219211220211221211222211223211224211225211226211227211228211229211230211231211232211233211234211235211236211237211238211239211240211241211242211243211244211245211246211247211248211249211250211251211252211253211254211255211256211257211258211259211260211261211262211263211264211265211266211267211268211269211270211271211272211273211274211275211276211277211278211279211280211281211282211283211284211285211286211287211288211289211290211291211292211293211294211295211296211297211298211299211300211301211302211303211304211305211306211307211308211309211310211311211312211313211314211315211316211317211318211319211320211321211322211323211324211325211326211327211328211329211330211331211332211333211334211335211336211337211338211339211340211341211342211343211344211345211346211347211348211349211350211351211352211353211354211355211356211357211358211359211360211361211362211363211364211365211366211367211368211369211370211371211372211373211374211375211376211377211378211379211380211381211382211383211384211385211386211387211388211389211390211391211392211393211394211395211396211397211398211399211400211401211402211403211404211405211406211407211408211409211410211411211412211413211414211415211416211417211418211419211420211421211422211423211424211425211426211427211428211429211430211431211432211433211434211435211436211437211438211439211440211441211442211443211444211445211446211447211448211449211450211451211452211453211454211455211456211457211458211459211460211461211462211463211464211465211466211467211468211469211470211471211472211473211474211475211476211477211478211479211480211481211482211483211484211485211486211487211488211489211490211491211492211493211494211495211496211497211498211499211500211501211502211503211504211505211506211507211508211509211510211511211512211513211514211515211516211517211518211519211520211521211522211523211524211525211526211527211528211529211530211531211532211533211534211535211536211537211538211539211540211541211542211543211544211545211546211547211548211549211550211551211552211553211554211555211556211557211558211559211560211561211562211563211564211565211566211567211568211569211570211571211572211573211574211575211576211577211578211579211580211581211582211583211584211585211586211587211588211589211590211591211592211593211594211595211596211597211598211599211600211601211602211603211604211605211606211607211608211609211610211611211612211613211614211615211616211617211618211619211620211621211622211623211624211625211626211627211628211629211630211631211632211633211634211635211636211637211638211639211640211641211642211643211644211645211646211647211648211649211650211651211652211653211654211655211656211657211658211659211660211661211662211663211664211665211666211667211668211669211670211671211672211673211674211675211676211677211678211679211680211681211682211683211684211685211686211687211688211689211690211691211692211693211694211695211696211697211698211699211700211701211702211703211704211705211706211707211708211709211710211711211712211713211714211715211716211717211718211719211720211721211722211723211724211725211726211727211728211729211730211731211732211733211734211735211736211737211738211739211740211741211742211743211744211745211746211747211748211749211750211751211752211753211754211755211756211757211758211759211760211761211762211763211764211765211766211767211768211769211770211771211772211773211774211775211776211777211778211779211780211781211782211783211784211785211786211787211788211789211790211791211792211793211794211795211796211797211798211799211800211801211802211803211804211805211806211807211808211809211810211811211812211813211814211815211816211817211818211819211820211821211822211823211824211825211826211827211828211829211830211831211832211833211834211835211836211837211838211839211840211841211842211843211844211845211846211847211848211849211850211851211852211853211854211855211856211857211858211859211860211861211862211863211864211865211866211867211868211869211870211871211872211873211874211875211876211877211878211879211880211881211882211883211884211885211886211887211888211889211890211891211892211893211894211895211896211897211898211899211900211901211902211903211904211905211906211907211908211909211910211911211912211913211914211915211916211917211918211919211920211921211922211923211924211925211926211927211928211929211930211931211932211933211934211935211936211937211938211939211940211941211942211943211944211945211946211947211948211949211950211951211952211953211954211955211956211957211958211959211960211961211962211963211964211965211966211967211968211969211970211971211972211973211974211975211976211977211978211979211980211981211982211983211984211985211986211987211988211989211990211991211992211993211994211995211996211997211998211999212000212001212002212003212004212005212006212007212008212009212010212011212012212013212014212015212016212017212018212019212020212021212022212023212024212025212026212027212028212029212030212031212032212033212034212035212036212037212038212039212040212041212042212043212044212045212046212047212048212049212050212051212052212053212054212055212056212057212058212059212060212061212062212063212064212065212066212067212068212069212070212071212072212073212074212075212076212077212078212079212080212081212082212083212084212085212086212087212088212089212090212091212092212093212094212095212096212097212098212099212100212101212102212103212104212105212106212107212108212109212110212111212112212113212114212115212116212117212118212119212120212121212122212123212124212125212126212127212128212129212130212131212132212133212134212135212136212137212138212139212140212141212142212143212144212145212146212147212148212149212150212151212152212153212154212155212156212157212158212159212160212161212162212163212164212165212166212167212168212169212170212171212172212173212174212175212176212177212178212179212180212181212182212183212184212185212186212187212188212189212190212191212192212193212194212195212196212197212198212199212200212201212202212203212204212205212206212207212208212209212210212211212212212213212214212215212216212217212218212219212220212221212222212223212224212225212226212227212228212229212230212231212232212233212234212235212236212237212238212239212240212241212242212243212244212245212246212247212248212249212250212251212252212253212254212255212256212257212258212259212260212261212262212263212264212265212266212267212268212269212270212271212272212273212274212275212276212277212278212279212280212281212282212283212284212285212286212287212288212289212290212291212292212293212294212295212296212297212298212299212300212301212302212303212304212305212306212307212308212309212310212311212312212313212314212315212316212317212318212319212320212321212322212323212324212325212326212327212328212329212330212331212332212333212334212335212336212337212338212339212340212341212342212343212344212345212346212347212348212349212350212351212352212353212354212355212356212357212358212359212360212361212362212363212364212365212366212367212368212369212370212371212372212373212374212375212376212377212378212379212380212381212382212383212384212385212386212387212388212389212390212391212392212393212394212395212396212397212398212399212400212401212402212403212404212405212406212407212408212409212410212411212412212413212414212415212416212417212418212419212420212421212422212423212424212425212426212427212428212429212430212431212432212433212434212435212436212437212438212439212440212441212442212443212444212445212446212447212448212449212450212451212452212453212454212455212456212457212458212459212460212461212462212463212464212465212466212467212468212469212470212471212472212473212474212475212476212477212478212479212480212481212482212483212484212485212486212487212488212489212490212491212492212493212494212495212496212497212498212499212500212501212502212503212504212505212506212507212508212509212510212511212512212513212514212515212516212517212518212519212520212521212522212523212524212525212526212527212528212529212530212531212532212533212534212535212536212537212538212539212540212541212542212543212544212545212546212547212548212549212550212551212552212553212554212555212556212557212558212559212560212561212562212563212564212565212566212567212568212569212570212571212572212573212574212575212576212577212578212579212580212581212582212583212584212585212586212587212588212589212590212591212592212593212594212595212596212597212598212599212600212601212602212603212604212605212606212607212608212609212610212611212612212613212614212615212616212617212618212619212620212621212622212623212624212625212626212627212628212629212630212631212632212633212634212635212636212637212638212639212640212641212642212643212644212645212646212647212648212649212650212651212652212653212654212655212656212657212658212659212660212661212662212663212664212665212666212667212668212669212670212671212672212673212674212675212676212677212678212679212680212681212682212683212684212685212686212687212688212689212690212691212692212693212694212695212696212697212698212699212700212701212702212703212704212705212706212707212708212709212710212711212712212713212714212715212716212717212718212719212720212721212722212723212724212725212726212727212728212729212730212731212732212733212734212735212736212737212738212739212740212741212742212743212744212745212746212747212748212749212750212751212752212753212754212755212756212757212758212759212760212761212762212763212764212765212766212767212768212769212770212771212772212773212774212775212776212777212778212779212780212781212782212783212784212785212786212787212788212789212790212791212792212793212794212795212796212797212798212799212800212801212802212803212804212805212806212807212808212809212810212811212812212813212814212815212816212817212818212819212820212821212822212823212824212825212826212827212828212829212830212831212832212833212834212835212836212837212838212839212840212841212842212843212844212845212846212847212848212849212850212851212852212853212854212855212856212857212858212859212860212861212862212863212864212865212866212867212868212869212870212871212872212873212874212875212876212877212878212879212880212881212882212883212884212885212886212887212888212889212890212891212892212893212894212895212896212897212898212899212900212901212902212903212904212905212906212907212908212909212910212911212912212913212914212915212916212917212918212919212920212921212922212923212924212925212926212927212928212929212930212931212932212933212934212935212936212937212938212939212940212941212942212943212944212945212946212947212948212949212950212951212952212953212954212955212956212957212958212959212960212961212962212963212964212965212966212967212968212969212970212971212972212973212974212975212976212977212978212979212980212981212982212983212984212985212986212987212988212989212990212991212992212993212994212995212996212997212998212999213000213001213002213003213004213005213006213007213008213009213010213011213012213013213014213015213016213017213018213019213020213021213022213023213024213025213026213027213028213029213030213031213032213033213034213035213036213037213038213039213040213041213042213043213044213045213046213047213048213049213050213051213052213053213054213055213056213057213058213059213060213061213062213063213064213065213066213067213068213069213070213071213072213073213074213075213076213077213078213079213080213081213082213083213084213085213086213087213088213089213090213091213092213093213094213095213096213097213098213099213100213101213102213103213104213105213106213107213108213109213110213111213112213113213114213115213116213117213118213119213120213121213122213123213124213125213126213127213128213129213130213131213132213133213134213135213136213137213138213139213140213141213142213143213144213145213146213147213148213149213150213151213152213153213154213155213156213157213158213159213160213161213162213163213164213165213166213167213168213169213170213171213172213173213174213175213176213177213178213179213180213181213182213183213184213185213186213187213188213189213190213191213192213193213194213195213196213197213198213199213200213201213202213203213204213205213206213207213208213209213210213211213212213213213214213215213216213217213218213219213220213221213222213223213224213225213226213227213228213229213230213231213232213233213234213235213236213237213238213239213240213241213242213243213244213245213246213247213248213249213250213251213252213253213254213255213256213257213258213259213260213261213262213263213264213265213266213267213268213269213270213271213272213273213274213275213276213277213278213279213280213281213282213283213284213285213286213287213288213289213290213291213292213293213294213295213296213297213298213299213300213301213302213303213304213305213306213307213308213309213310213311213312213313213314213315213316213317213318213319213320213321213322213323213324213325213326213327213328213329213330213331213332213333213334213335213336213337213338213339213340213341213342213343213344213345213346213347213348213349213350213351213352213353213354213355213356213357213358213359213360213361213362213363213364213365213366213367213368213369213370213371213372213373213374213375213376213377213378213379213380213381213382213383213384213385213386213387213388213389213390213391213392213393213394213395213396213397213398213399213400213401213402213403213404213405213406213407213408213409213410213411213412213413213414213415213416213417213418213419213420213421213422213423213424213425213426213427213428213429213430213431213432213433213434213435213436213437213438213439213440213441213442213443213444213445213446213447213448213449213450213451213452213453213454213455213456213457213458213459213460213461213462213463213464213465213466213467213468213469213470213471213472213473213474213475213476213477213478213479213480213481213482213483213484213485213486213487213488213489213490213491213492213493213494213495213496213497213498213499213500213501213502213503213504213505213506213507213508213509213510213511213512213513213514213515213516213517213518213519213520213521213522213523213524213525213526213527213528213529213530213531213532213533213534213535213536213537213538213539213540213541213542213543213544213545213546213547213548213549213550213551213552213553213554213555213556213557213558213559213560213561213562213563213564213565213566213567213568213569213570213571213572213573213574213575213576213577213578213579213580213581213582213583213584213585213586213587213588213589213590213591213592213593213594213595213596213597213598213599213600213601213602213603213604213605213606213607213608213609213610213611213612213613213614213615213616213617213618213619213620213621213622213623213624213625213626213627213628213629213630213631213632213633213634213635213636213637213638213639213640213641213642213643213644213645213646213647213648213649213650213651213652213653213654213655213656213657213658213659213660213661213662213663213664213665213666213667213668213669213670213671213672213673213674213675213676213677213678213679213680213681213682213683213684213685213686213687213688213689213690213691213692213693213694213695213696213697213698213699213700213701213702213703213704213705213706213707213708213709213710213711213712213713213714213715213716213717213718213719213720213721213722213723213724213725213726213727213728213729213730213731213732213733213734213735213736213737213738213739213740213741213742213743213744213745213746213747213748213749213750213751213752213753213754213755213756213757213758213759213760213761213762213763213764213765213766213767213768213769213770213771213772213773213774213775213776213777213778213779213780213781213782213783213784213785213786213787213788213789213790213791213792213793213794213795213796213797213798213799213800213801213802213803213804213805213806213807213808213809213810213811213812213813213814213815213816213817213818213819213820213821213822213823213824213825213826213827213828213829213830213831213832213833213834213835213836213837213838213839213840213841213842213843213844213845213846213847213848213849213850213851213852213853213854213855213856213857213858213859213860213861213862213863213864213865213866213867213868213869213870213871213872213873213874213875213876213877213878213879213880213881213882213883213884213885213886213887213888213889213890213891213892213893213894213895213896213897213898213899213900213901213902213903213904213905213906213907213908213909213910213911213912213913213914213915213916213917213918213919213920213921213922213923213924213925213926213927213928213929213930213931213932213933213934213935213936213937213938213939213940213941213942213943213944213945213946213947213948213949213950213951213952213953213954213955213956213957213958213959213960213961213962213963213964213965213966213967213968213969213970213971213972213973213974213975213976213977213978213979213980213981213982213983213984213985213986213987213988213989213990213991213992213993213994213995213996213997213998213999214000214001214002214003214004214005214006214007214008214009214010214011214012214013214014214015214016214017214018214019214020214021214022214023214024214025214026214027214028214029214030214031214032214033214034214035214036214037214038214039214040214041214042214043214044214045214046214047214048214049214050214051214052214053214054214055214056214057214058214059214060214061214062214063214064214065214066214067214068214069214070214071214072214073214074214075214076214077214078214079214080214081214082214083214084214085214086214087214088214089214090214091214092214093214094214095214096214097214098214099214100214101214102214103214104214105214106214107214108214109214110214111214112214113214114214115214116214117214118214119214120214121214122214123214124214125214126214127214128214129214130214131214132214133214134214135214136214137214138214139214140214141214142214143214144214145214146214147214148214149214150214151214152214153214154214155214156214157214158214159214160214161214162214163214164214165214166214167214168214169214170214171214172214173214174214175214176214177214178214179214180214181214182214183214184214185214186214187214188214189214190214191214192214193214194214195214196214197214198214199214200214201214202214203214204214205214206214207214208214209214210214211214212214213214214214215214216214217214218214219214220214221214222214223214224214225214226214227214228214229214230214231214232214233214234214235214236214237214238214239214240214241214242214243214244214245214246214247214248214249214250214251214252214253214254214255214256214257214258214259214260214261214262214263214264214265214266214267214268214269214270214271214272214273214274214275214276214277214278214279214280214281214282214283214284214285214286214287214288214289214290214291214292214293214294214295214296214297214298214299214300214301214302214303214304214305214306214307214308214309214310214311214312214313214314214315214316214317214318214319214320214321214322214323214324214325214326214327214328214329214330214331214332214333214334214335214336214337214338214339214340214341214342214343214344214345214346214347214348214349214350214351214352214353214354214355214356214357214358214359214360214361214362214363214364214365214366214367214368214369214370214371214372214373214374214375214376214377214378214379214380214381214382214383214384214385214386214387214388214389214390214391214392214393214394214395214396214397214398214399214400214401214402214403214404214405214406214407214408214409214410214411214412214413214414214415214416214417214418214419214420214421214422214423214424214425214426214427214428214429214430214431214432214433214434214435214436214437214438214439214440214441214442214443214444214445214446214447214448214449214450214451214452214453214454214455214456214457214458214459214460214461214462214463214464214465214466214467214468214469214470214471214472214473214474214475214476214477214478214479214480214481214482214483214484214485214486214487214488214489214490214491214492214493214494214495214496214497214498214499214500214501214502214503214504214505214506214507214508214509214510214511214512214513214514214515214516214517214518214519214520214521214522214523214524214525214526214527214528214529214530214531214532214533214534214535214536214537214538214539214540214541214542214543214544214545214546214547214548214549214550214551214552214553214554214555214556214557214558214559214560214561214562214563214564214565214566214567214568214569214570214571214572214573214574214575214576214577214578214579214580214581214582214583214584214585214586214587214588214589214590214591214592214593214594214595214596214597214598214599214600214601214602214603214604214605214606214607214608214609214610214611214612214613214614214615214616214617214618214619214620214621214622214623214624214625214626214627214628214629214630214631214632214633214634214635214636214637214638214639214640214641214642214643214644214645214646214647214648214649214650214651214652214653214654214655214656214657214658214659214660214661214662214663214664214665214666214667214668214669214670214671214672214673214674214675214676214677214678214679214680214681214682214683214684214685214686214687214688214689214690214691214692214693214694214695214696214697214698214699214700214701214702214703214704214705214706214707214708214709214710214711214712214713214714214715214716214717214718214719214720214721214722214723214724214725214726214727214728214729214730214731214732214733214734214735214736214737214738214739214740214741214742214743214744214745214746214747214748214749214750214751214752214753214754214755214756214757214758214759214760214761214762214763214764214765214766214767214768214769214770214771214772214773214774214775214776214777214778214779214780214781214782214783214784214785214786214787214788214789214790214791214792214793214794214795214796214797214798214799214800214801214802214803214804214805214806214807214808214809214810214811214812214813214814214815214816214817214818214819214820214821214822214823214824214825214826214827214828214829214830214831214832214833214834214835214836214837214838214839214840214841214842214843214844214845214846214847214848214849214850214851214852214853214854214855214856214857214858214859214860214861214862214863214864214865214866214867214868214869214870214871214872214873214874214875214876214877214878214879214880214881214882214883214884214885214886214887214888214889214890214891214892214893214894214895214896214897214898214899214900214901214902214903214904214905214906214907214908214909214910214911214912214913214914214915214916214917214918214919214920214921214922214923214924214925214926214927214928214929214930214931214932214933214934214935214936214937214938214939214940214941214942214943214944214945214946214947214948214949214950214951214952214953214954214955214956214957214958214959214960214961214962214963214964214965214966214967214968214969214970214971214972214973214974214975214976214977214978214979214980214981214982214983214984214985214986214987214988214989214990214991214992214993214994214995214996214997214998214999215000215001215002215003215004215005215006215007215008215009215010215011215012215013215014215015215016215017215018215019215020215021215022215023215024215025215026215027215028215029215030215031215032215033215034215035215036215037215038215039215040215041215042215043215044215045215046215047215048215049215050215051215052215053215054215055215056215057215058215059215060215061215062215063215064215065215066215067215068215069215070215071215072215073215074215075215076215077215078215079215080215081215082215083215084215085215086215087215088215089215090215091215092215093215094215095215096215097215098215099215100215101215102215103215104215105215106215107215108215109215110215111215112215113215114215115215116215117215118215119215120215121215122215123215124215125215126215127215128215129215130215131215132215133215134215135215136215137215138215139215140215141215142215143215144215145215146215147215148215149215150215151215152215153215154215155215156215157215158215159215160215161215162215163215164215165215166215167215168215169215170215171215172215173215174215175215176215177215178215179215180215181215182215183215184215185215186215187215188215189215190215191215192215193215194215195215196215197215198215199215200215201215202215203215204215205215206215207215208215209215210215211215212215213215214215215215216215217215218215219215220215221215222215223215224215225215226215227215228215229215230215231215232215233215234215235215236215237215238215239215240215241215242215243215244215245215246215247215248215249215250215251215252215253215254215255215256215257215258215259215260215261215262215263215264215265215266215267215268215269215270215271215272215273215274215275215276215277215278215279215280215281215282215283215284215285215286215287215288215289215290215291215292215293215294215295215296215297215298215299215300215301215302215303215304215305215306215307215308215309215310215311215312215313215314215315215316215317215318215319215320215321215322215323215324215325215326215327215328215329215330215331215332215333215334215335215336215337215338215339215340215341215342215343215344215345215346215347215348215349215350215351215352215353215354215355215356215357215358215359215360215361215362215363215364215365215366215367215368215369215370215371215372215373215374215375215376215377215378215379215380215381215382215383215384215385215386215387215388215389215390215391215392215393215394215395215396215397215398215399215400215401215402215403215404215405215406215407215408215409215410215411215412215413215414215415215416215417215418215419215420215421215422215423215424215425215426215427215428215429215430215431215432215433215434215435215436215437215438215439215440215441215442215443215444215445215446215447215448215449215450215451215452215453215454215455215456215457215458215459215460215461215462215463215464215465215466215467215468215469215470215471215472215473215474215475215476215477215478215479215480215481215482215483215484215485215486215487215488215489215490215491215492215493215494215495215496215497215498215499215500215501215502215503215504215505215506215507215508215509215510215511215512215513215514215515215516215517215518215519215520215521215522215523215524215525215526215527215528215529215530215531215532215533215534215535215536215537215538215539215540215541215542215543215544215545215546215547215548215549215550215551215552215553215554215555215556215557215558215559215560215561215562215563215564215565215566215567215568215569215570215571215572215573215574215575215576215577215578215579215580215581215582215583215584215585215586215587215588215589215590215591215592215593215594215595215596215597215598215599215600215601215602215603215604215605215606215607215608215609215610215611215612215613215614215615215616215617215618215619215620215621215622215623215624215625215626215627215628215629215630215631215632215633215634215635215636215637215638215639215640215641215642215643215644215645215646215647215648215649215650215651215652215653215654215655215656215657215658215659215660215661215662215663215664215665215666215667215668215669215670215671215672215673215674215675215676215677215678215679215680215681215682215683215684215685215686215687215688215689215690215691215692215693215694215695215696215697215698215699215700215701215702215703215704215705215706215707215708215709215710215711215712215713215714215715215716215717215718215719215720215721215722215723215724215725215726215727215728215729215730215731215732215733215734215735215736215737215738215739215740215741215742215743215744215745215746215747215748215749215750215751215752215753215754215755215756215757215758215759215760215761215762215763215764215765215766215767215768215769215770215771215772215773215774215775215776215777215778215779215780215781215782215783215784215785215786215787215788215789215790215791215792215793215794215795215796215797215798215799215800215801215802215803215804215805215806215807215808215809215810215811215812215813215814215815215816215817215818215819215820215821215822215823215824215825215826215827215828215829215830215831215832215833215834215835215836215837215838215839215840215841215842215843215844215845215846215847215848215849215850215851215852215853215854215855215856215857215858215859215860215861215862215863215864215865215866215867215868215869215870215871215872215873215874215875215876215877215878215879215880215881215882215883215884215885215886215887215888215889215890215891215892215893215894215895215896215897215898215899215900215901215902215903215904215905215906215907215908215909215910215911215912215913215914215915215916215917215918215919215920215921215922215923215924215925215926215927215928215929215930215931215932215933215934215935215936215937215938215939215940215941215942215943215944215945215946215947215948215949215950215951215952215953215954215955215956215957215958215959215960215961215962215963215964215965215966215967215968215969215970215971215972215973215974215975215976215977215978215979215980215981215982215983215984215985215986215987215988215989215990215991215992215993215994215995215996215997215998215999216000216001216002216003216004216005216006216007216008216009216010216011216012216013216014216015216016216017216018216019216020216021216022216023216024216025216026216027216028216029216030216031216032216033216034216035216036216037216038216039216040216041216042216043216044216045216046216047216048216049216050216051216052216053216054216055216056216057216058216059216060216061216062216063216064216065216066216067216068216069216070216071216072216073216074216075216076216077216078216079216080216081216082216083216084216085216086216087216088216089216090216091216092216093216094216095216096216097216098216099216100216101216102216103216104216105216106216107216108216109216110216111216112216113216114216115216116216117216118216119216120216121216122216123216124216125216126216127216128216129216130216131216132216133216134216135216136216137216138216139216140216141216142216143216144216145216146216147216148216149216150216151216152216153216154216155216156216157216158216159216160216161216162216163216164216165216166216167216168216169216170216171216172216173216174216175216176216177216178216179216180216181216182216183216184216185216186216187216188216189216190216191216192216193216194216195216196216197216198216199216200216201216202216203216204216205216206216207216208216209216210216211216212216213216214216215216216216217216218216219216220216221216222216223216224216225216226216227216228216229216230216231216232216233216234216235216236216237216238216239216240216241216242216243216244216245216246216247216248216249216250216251216252216253216254216255216256216257216258216259216260216261216262216263216264216265216266216267216268216269216270216271216272216273216274216275216276216277216278216279216280216281216282216283216284216285216286216287216288216289216290216291216292216293216294216295216296216297216298216299216300216301216302216303216304216305216306216307216308216309216310216311216312216313216314216315216316216317216318216319216320216321216322216323216324216325216326216327216328216329216330216331216332216333216334216335216336216337216338216339216340216341216342216343216344216345216346216347216348216349216350216351216352216353216354216355216356216357216358216359216360216361216362216363216364216365216366216367216368216369216370216371216372216373216374216375216376216377216378216379216380216381216382216383216384216385216386216387216388216389216390216391216392216393216394216395216396216397216398216399216400216401216402216403216404216405216406216407216408216409216410216411216412216413216414216415216416216417216418216419216420216421216422216423216424216425216426216427216428216429216430216431216432216433216434216435216436216437216438216439216440216441216442216443216444216445216446216447216448216449216450216451216452216453216454216455216456216457216458216459216460216461216462216463216464216465216466216467216468216469216470216471216472216473216474216475216476216477216478216479216480216481216482216483216484216485216486216487216488216489216490216491216492216493216494216495216496216497216498216499216500216501216502216503216504216505216506216507216508216509216510216511216512216513216514216515216516216517216518216519216520216521216522216523216524216525216526216527216528216529216530216531216532216533216534216535216536216537216538216539216540216541216542216543216544216545216546216547216548216549216550216551216552216553216554216555216556216557216558216559216560216561216562216563216564216565216566216567216568216569216570216571216572216573216574216575216576216577216578216579216580216581216582216583216584216585216586216587216588216589216590216591216592216593216594216595216596216597216598216599216600216601216602216603216604216605216606216607216608216609216610216611216612216613216614216615216616216617216618216619216620216621216622216623216624216625216626216627216628216629216630216631216632216633216634216635216636216637216638216639216640216641216642216643216644216645216646216647216648216649216650216651216652216653216654216655216656216657216658216659216660216661216662216663216664216665216666216667216668216669216670216671216672216673216674216675216676216677216678216679216680216681216682216683216684216685216686216687216688216689216690216691216692216693216694216695216696216697216698216699216700216701216702216703216704216705216706216707216708216709216710216711216712216713216714216715216716216717216718216719216720216721216722216723216724216725216726216727216728216729216730216731216732216733216734216735216736216737216738216739216740216741216742216743216744216745216746216747216748216749216750216751216752216753216754216755216756216757216758216759216760216761216762216763216764216765216766216767216768216769216770216771216772216773216774216775216776216777216778216779216780216781216782216783216784216785216786216787216788216789216790216791216792216793216794216795216796216797216798216799216800216801216802216803216804216805216806216807216808216809216810216811216812216813216814216815216816216817216818216819216820216821216822216823216824216825216826216827216828216829216830216831216832216833216834216835216836216837216838216839216840216841216842216843216844216845216846216847216848216849216850216851216852216853216854216855216856216857216858216859216860216861216862216863216864216865216866216867216868216869216870216871216872216873216874216875216876216877216878216879216880216881216882216883216884216885216886216887216888216889216890216891216892216893216894216895216896216897216898216899216900216901216902216903216904216905216906216907216908216909216910216911216912216913216914216915216916216917216918216919216920216921216922216923216924216925216926216927216928216929216930216931216932216933216934216935216936216937216938216939216940216941216942216943216944216945216946216947216948216949216950216951216952216953216954216955216956216957216958216959216960216961216962216963216964216965216966216967216968216969216970216971216972216973216974216975216976216977216978216979216980216981216982216983216984216985216986216987216988216989216990216991216992216993216994216995216996216997216998216999217000217001217002217003217004217005217006217007217008217009217010217011217012217013217014217015217016217017217018217019217020217021217022217023217024217025217026217027217028217029217030217031217032217033217034217035217036217037217038217039217040217041217042217043217044217045217046217047217048217049217050217051217052217053217054217055217056217057217058217059217060217061217062217063217064217065217066217067217068217069217070217071217072217073217074217075217076217077217078217079217080217081217082217083217084217085217086217087217088217089217090217091217092217093217094217095217096217097217098217099217100217101217102217103217104217105217106217107217108217109217110217111217112217113217114217115217116217117217118217119217120217121217122217123217124217125217126217127217128217129217130217131217132217133217134217135217136217137217138217139217140217141217142217143217144217145217146217147217148217149217150217151217152217153217154217155217156217157217158217159217160217161217162217163217164217165217166217167217168217169217170217171217172217173217174217175217176217177217178217179217180217181217182217183217184217185217186217187217188217189217190217191217192217193217194217195217196217197217198217199217200217201217202217203217204217205217206217207217208217209217210217211217212217213217214217215217216217217217218217219217220217221217222217223217224217225217226217227217228217229217230217231217232217233217234217235217236217237217238217239217240217241217242217243217244217245217246217247217248217249217250217251217252217253217254217255217256217257217258217259217260217261217262217263217264217265217266217267217268217269217270217271217272217273217274217275217276217277217278217279217280217281217282217283217284217285217286217287217288217289217290217291217292217293217294217295217296217297217298217299217300217301217302217303217304217305217306217307217308217309217310217311217312217313217314217315217316217317217318217319217320217321217322217323217324217325217326217327217328217329217330217331217332217333217334217335217336217337217338217339217340217341217342217343217344217345217346217347217348217349217350217351217352217353217354217355217356217357217358217359217360217361217362217363217364217365217366217367217368217369217370217371217372217373217374217375217376217377217378217379217380217381217382217383217384217385217386217387217388217389217390217391217392217393217394217395217396217397217398217399217400217401217402217403217404217405217406217407217408217409217410217411217412217413217414217415217416217417217418217419217420217421217422217423217424217425217426217427217428217429217430217431217432217433217434217435217436217437217438217439217440217441217442217443217444217445217446217447217448217449217450217451217452217453217454217455217456217457217458217459217460217461217462217463217464217465217466217467217468217469217470217471217472217473217474217475217476217477217478217479217480217481217482217483217484217485217486217487217488217489217490217491217492217493217494217495217496217497217498217499217500217501217502217503217504217505217506217507217508217509217510217511217512217513217514217515217516217517217518217519217520217521217522217523217524217525217526217527217528217529217530217531217532217533217534217535217536217537217538217539217540217541217542217543217544217545217546217547217548217549217550217551217552217553217554217555217556217557217558217559217560217561217562217563217564217565217566217567217568217569217570217571217572217573217574217575217576217577217578217579217580217581217582217583217584217585217586217587217588217589217590217591217592217593217594217595217596217597217598217599217600217601217602217603217604217605217606217607217608217609217610217611217612217613217614217615217616217617217618217619217620217621217622217623217624217625217626217627217628217629217630217631217632217633217634217635217636217637217638217639217640217641217642217643217644217645217646217647217648217649217650217651217652217653217654217655217656217657217658217659217660217661217662217663217664217665217666217667217668217669217670217671217672217673217674217675217676217677217678217679217680217681217682217683217684217685217686217687217688217689217690217691217692217693217694217695217696217697217698217699217700217701217702217703217704217705217706217707217708217709217710217711217712217713217714217715217716217717217718217719217720217721217722217723217724217725217726217727217728217729217730217731217732217733217734217735217736217737217738217739217740217741217742217743217744217745217746217747217748217749217750217751217752217753217754217755217756217757217758217759217760217761217762217763217764217765217766217767217768217769217770217771217772217773217774217775217776217777217778217779217780217781217782217783217784217785217786217787217788217789217790217791217792217793217794217795217796217797217798217799217800217801217802217803217804217805217806217807217808217809217810217811217812217813217814217815217816217817217818217819217820217821217822217823217824217825217826217827217828217829217830217831217832217833217834217835217836217837217838217839217840217841217842217843217844217845217846217847217848217849217850217851217852217853217854217855217856217857217858217859217860217861217862217863217864217865217866217867217868217869217870217871217872217873217874217875217876217877217878217879217880217881217882217883217884217885217886217887217888217889217890217891217892217893217894217895217896217897217898217899217900217901217902217903217904217905217906217907217908217909217910217911217912217913217914217915217916217917217918217919217920217921217922217923217924217925217926217927217928217929217930217931217932217933217934217935217936217937217938217939217940217941217942217943217944217945217946217947217948217949217950217951217952217953217954217955217956217957217958217959217960217961217962217963217964217965217966217967217968217969217970217971217972217973217974217975217976217977217978217979217980217981217982217983217984217985217986217987217988217989217990217991217992217993217994217995217996217997217998217999218000218001218002218003218004218005218006218007218008218009218010218011218012218013218014218015218016218017218018218019218020218021218022218023218024218025218026218027218028218029218030218031218032218033218034218035218036218037218038218039218040218041218042218043218044218045218046218047218048218049218050218051218052218053218054218055218056218057218058218059218060218061218062218063218064218065218066218067218068218069218070218071218072218073218074218075218076218077218078218079218080218081218082218083218084218085218086218087218088218089218090218091218092218093218094218095218096218097218098218099218100218101218102218103218104218105218106218107218108218109218110218111218112218113218114218115218116218117218118218119218120218121218122218123218124218125218126218127218128218129218130218131218132218133218134218135218136218137218138218139218140218141218142218143218144218145218146218147218148218149218150218151218152218153218154218155218156218157218158218159218160218161218162218163218164218165218166218167218168218169218170218171218172218173218174218175218176218177218178218179218180218181218182218183218184218185218186218187218188218189218190218191218192218193218194218195218196218197218198218199218200218201218202218203218204218205218206218207218208218209218210218211218212218213218214218215218216218217218218218219218220218221218222218223218224218225218226218227218228218229218230218231218232218233218234218235218236218237218238218239218240218241218242218243218244218245218246218247218248218249218250218251218252218253218254218255218256218257218258218259218260218261218262218263218264218265218266218267218268218269218270218271218272218273218274218275218276218277218278218279218280218281218282218283218284218285218286218287218288218289218290218291218292218293218294218295218296218297218298218299218300218301218302218303218304218305218306218307218308218309218310218311218312218313218314218315218316218317218318218319218320218321218322218323218324218325218326218327218328218329218330218331218332218333218334218335218336218337218338218339218340218341218342218343218344218345218346218347218348218349218350218351218352218353218354218355218356218357218358218359218360218361218362218363218364218365218366218367218368218369218370218371218372218373218374218375218376218377218378218379218380218381218382218383218384218385218386218387218388218389218390218391218392218393218394218395218396218397218398218399218400218401218402218403218404218405218406218407218408218409218410218411218412218413218414218415218416218417218418218419218420218421218422218423218424218425218426218427218428218429218430218431218432218433218434218435218436218437218438218439218440218441218442218443218444218445218446218447218448218449218450218451218452218453218454218455218456218457218458218459218460218461218462218463218464218465218466218467218468218469218470218471218472218473218474218475218476218477218478218479218480218481218482218483218484218485218486218487218488218489218490218491218492218493218494218495218496218497218498218499218500218501218502218503218504218505218506218507218508218509218510218511218512218513218514218515218516218517218518218519218520218521218522218523218524218525218526218527218528218529218530218531218532218533218534218535218536218537218538218539218540218541218542218543218544218545218546218547218548218549218550218551218552218553218554218555218556218557218558218559218560218561218562218563218564218565218566218567218568218569218570218571218572218573218574218575218576218577218578218579218580218581218582218583218584218585218586218587218588218589218590218591218592218593218594218595218596218597218598218599218600218601218602218603218604218605218606218607218608218609218610218611218612218613218614218615218616218617218618218619218620218621218622218623218624218625218626218627218628218629218630218631218632218633218634218635218636218637218638218639218640218641218642218643218644218645218646218647218648218649218650218651218652218653218654218655218656218657218658218659218660218661218662218663218664218665218666218667218668218669218670218671218672218673218674218675218676218677218678218679218680218681218682218683218684218685218686218687218688218689218690218691218692218693218694218695218696218697218698218699218700218701218702218703218704218705218706218707218708218709218710218711218712218713218714218715218716218717218718218719218720218721218722218723218724218725218726218727218728218729218730218731218732218733218734218735218736218737218738218739218740218741218742218743218744218745218746218747218748218749218750218751218752218753218754218755218756218757218758218759218760218761218762218763218764218765218766218767218768218769218770218771218772218773218774218775218776218777218778218779218780218781218782218783218784218785218786218787218788218789218790218791218792218793218794218795218796218797218798218799218800218801218802218803218804218805218806218807218808218809218810218811218812218813218814218815218816218817218818218819218820218821218822218823218824218825218826218827218828218829218830218831218832218833218834218835218836218837218838218839218840218841218842218843218844218845218846218847218848218849218850218851218852218853218854218855218856218857218858218859218860218861218862218863218864218865218866218867218868218869218870218871218872218873218874218875218876218877218878218879218880218881218882218883218884218885218886218887218888218889218890218891218892218893218894218895218896218897218898218899218900218901218902218903218904218905218906218907218908218909218910218911218912218913218914218915218916218917218918218919218920218921218922218923218924218925218926218927218928218929218930218931218932218933218934218935218936218937218938218939218940218941218942218943218944218945218946218947218948218949218950218951218952218953218954218955218956218957218958218959218960218961218962218963218964218965218966218967218968218969218970218971218972218973218974218975218976218977218978218979218980218981218982218983218984218985218986218987218988218989218990218991218992218993218994218995218996218997218998218999219000219001219002219003219004219005219006219007219008219009219010219011219012219013219014219015219016219017219018219019219020219021219022219023219024219025219026219027219028219029219030219031219032219033219034219035219036219037219038219039219040219041219042219043219044219045219046219047219048219049219050219051219052219053219054219055219056219057219058219059219060219061219062219063219064219065219066219067219068219069219070219071219072219073219074219075219076219077219078219079219080219081219082219083219084219085219086219087219088219089219090219091219092219093219094219095219096219097219098219099219100219101219102219103219104219105219106219107219108219109219110219111219112219113219114219115219116219117219118219119219120219121219122219123219124219125219126219127219128219129219130219131219132219133219134219135219136219137219138219139219140219141219142219143219144219145219146219147219148219149219150219151219152219153219154219155219156219157219158219159219160219161219162219163219164219165219166219167219168219169219170219171219172219173219174219175219176219177219178219179219180219181219182219183219184219185219186219187219188219189219190219191219192219193219194219195219196219197219198219199219200219201219202219203219204219205219206219207219208219209219210219211219212219213219214219215219216219217219218219219219220219221219222219223219224219225219226219227219228219229219230219231219232219233219234219235219236219237219238219239219240219241219242219243219244219245219246219247219248219249219250219251219252219253219254219255219256219257219258219259219260219261219262219263219264219265219266219267219268219269219270219271219272219273219274219275219276219277219278219279219280219281219282219283219284219285219286219287219288219289219290219291219292219293219294219295219296219297219298219299219300219301219302219303219304219305219306219307219308219309219310219311219312219313219314219315219316219317219318219319219320219321219322219323219324219325219326219327219328219329219330219331219332219333219334219335219336219337219338219339219340219341219342219343219344219345219346219347219348219349219350219351219352219353219354219355219356219357219358219359219360219361219362219363219364219365219366219367219368219369219370219371219372219373219374219375219376219377219378219379219380219381219382219383219384219385219386219387219388219389219390219391219392219393219394219395219396219397219398219399219400219401219402219403219404219405219406219407219408219409219410219411219412219413219414219415219416219417219418219419219420219421219422219423219424219425219426219427219428219429219430219431219432219433219434219435219436219437219438219439219440219441219442219443219444219445219446219447219448219449219450219451219452219453219454219455219456219457219458219459219460219461219462219463219464219465219466219467219468219469219470219471219472219473219474219475219476219477219478219479219480219481219482219483219484219485219486219487219488219489219490219491219492219493219494219495219496219497219498219499219500219501219502219503219504219505219506219507219508219509219510219511219512219513219514219515219516219517219518219519219520219521219522219523219524219525219526219527219528219529219530219531219532219533219534219535219536219537219538219539219540219541219542219543219544219545219546219547219548219549219550219551219552219553219554219555219556219557219558219559219560219561219562219563219564219565219566219567219568219569219570219571219572219573219574219575219576219577219578219579219580219581219582219583219584219585219586219587219588219589219590219591219592219593219594219595219596219597219598219599219600219601219602219603219604219605219606219607219608219609219610219611219612219613219614219615219616219617219618219619219620219621219622219623219624219625219626219627219628219629219630219631219632219633219634219635219636219637219638219639219640219641219642219643219644219645219646219647219648219649219650219651219652219653219654219655219656219657219658219659219660219661219662219663219664219665219666219667219668219669219670219671219672219673219674219675219676219677219678219679219680219681219682219683219684219685219686219687219688219689219690219691219692219693219694219695219696219697219698219699219700219701219702219703219704219705219706219707219708219709219710219711219712219713219714219715219716219717219718219719219720219721219722219723219724219725219726219727219728219729219730219731219732219733219734219735219736219737219738219739219740219741219742219743219744219745219746219747219748219749219750219751219752219753219754219755219756219757219758219759219760219761219762219763219764219765219766219767219768219769219770219771219772219773219774219775219776219777219778219779219780219781219782219783219784219785219786219787219788219789219790219791219792219793219794219795219796219797219798219799219800219801219802219803219804219805219806219807219808219809219810219811219812219813219814219815219816219817219818219819219820219821219822219823219824219825219826219827219828219829219830219831219832219833219834219835219836219837219838219839219840219841219842219843219844219845219846219847219848219849219850219851219852219853219854219855219856219857219858219859219860219861219862219863219864219865219866219867219868219869219870219871219872219873219874219875219876219877219878219879219880219881219882219883219884219885219886219887219888219889219890219891219892219893219894219895219896219897219898219899219900219901219902219903219904219905219906219907219908219909219910219911219912219913219914219915219916219917219918219919219920219921219922219923219924219925219926219927219928219929219930219931219932219933219934219935219936219937219938219939219940219941219942219943219944219945219946219947219948219949219950219951219952219953219954219955219956219957219958219959219960219961219962219963219964219965219966219967219968219969219970219971219972219973219974219975219976219977219978219979219980219981219982219983219984219985219986219987219988219989219990219991219992219993219994219995219996219997219998219999220000220001220002220003220004220005220006220007220008220009220010220011220012220013220014220015220016220017220018220019220020220021220022220023220024220025220026220027220028220029220030220031220032220033220034220035220036220037220038220039220040220041220042220043220044220045220046220047220048220049220050220051220052220053220054220055220056220057220058220059220060220061220062220063220064220065220066220067220068220069220070220071220072220073220074220075220076220077220078220079220080220081220082220083220084220085220086220087220088220089220090220091220092220093220094220095220096220097220098220099220100220101220102220103220104220105220106220107220108220109220110220111220112220113220114220115220116220117220118220119220120220121220122220123220124220125220126220127220128220129220130220131220132220133220134220135220136220137220138220139220140220141220142220143220144220145220146220147220148220149220150220151220152220153220154220155220156220157220158220159220160220161220162220163220164220165220166220167220168220169220170220171220172220173220174220175220176220177220178220179220180220181220182220183220184220185220186220187220188220189220190220191220192220193220194220195220196220197220198220199220200220201220202220203220204220205220206220207220208220209220210220211220212220213220214220215220216220217220218220219220220220221220222220223220224220225220226220227220228220229220230220231220232220233220234220235220236220237220238220239220240220241220242220243220244220245220246220247220248220249220250220251220252220253220254220255220256220257220258220259220260220261220262220263220264220265220266220267220268220269220270220271220272220273220274220275220276220277220278220279220280220281220282220283220284220285220286220287220288220289220290220291220292220293220294220295220296220297220298220299220300220301220302220303220304220305220306220307220308220309220310220311220312220313220314220315220316220317220318220319220320220321220322220323220324220325220326220327220328220329220330220331220332220333220334220335220336220337220338220339220340220341220342220343220344220345220346220347220348220349220350220351220352220353220354220355220356220357220358220359220360220361220362220363220364220365220366220367220368220369220370220371220372220373220374220375220376220377220378220379220380220381220382220383220384220385220386220387220388220389220390220391220392220393220394220395220396220397220398220399220400220401220402220403220404220405220406220407220408220409220410220411220412220413220414220415220416220417220418220419220420220421220422220423220424220425220426220427220428220429220430220431220432220433220434220435220436220437220438220439220440220441220442220443220444220445220446220447220448220449220450220451220452220453220454220455220456220457220458220459220460220461220462220463220464220465220466220467220468220469220470220471220472220473220474220475220476220477220478220479220480220481220482220483220484220485220486220487220488220489220490220491220492220493220494220495220496220497220498220499220500220501220502220503220504220505220506220507220508220509220510220511220512220513220514220515220516220517220518220519220520220521220522220523220524220525220526220527220528220529220530220531220532220533220534220535220536220537220538220539220540220541220542220543220544220545220546220547220548220549220550220551220552220553220554220555220556220557220558220559220560220561220562220563220564220565220566220567220568220569220570220571220572220573220574220575220576220577220578220579220580220581220582220583220584220585220586220587220588220589220590220591220592220593220594220595220596220597220598220599220600220601220602220603220604220605220606220607220608220609220610220611220612220613220614220615220616220617220618220619220620220621220622220623220624220625220626220627220628220629220630220631220632220633220634220635220636220637220638220639220640220641220642220643220644220645220646220647220648220649220650220651220652220653220654220655220656220657220658220659220660220661220662220663220664220665220666220667220668220669220670220671220672220673220674220675220676220677220678220679220680220681220682220683220684220685220686220687220688220689220690220691220692220693220694220695220696220697220698220699220700220701220702220703220704220705220706220707220708220709220710220711220712220713220714220715220716220717220718220719220720220721220722220723220724220725220726220727220728220729220730220731220732220733220734220735220736220737220738220739220740220741220742220743220744220745220746220747220748220749220750220751220752220753220754220755220756220757220758220759220760220761220762220763220764220765220766220767220768220769220770220771220772220773220774220775220776220777220778220779220780220781220782220783220784220785220786220787220788220789220790220791220792220793220794220795220796220797220798220799220800220801220802220803220804220805220806220807220808220809220810220811220812220813220814220815220816220817220818220819220820220821220822220823220824220825220826220827220828220829220830220831220832220833220834220835220836220837220838220839220840220841220842220843220844220845220846220847220848220849220850220851220852220853220854220855220856220857220858220859220860220861220862220863220864220865220866220867220868220869220870220871220872220873220874220875220876220877220878220879220880220881220882220883220884220885220886220887220888220889220890220891220892220893220894220895220896220897220898220899220900220901220902220903220904220905220906220907220908220909220910220911220912220913220914220915220916220917220918220919220920220921220922220923220924220925220926220927220928220929220930220931220932220933220934220935220936220937220938220939220940220941220942220943220944220945220946220947220948220949220950220951220952220953220954220955220956220957220958220959220960220961220962220963220964220965220966220967220968220969220970220971220972220973220974220975220976220977220978220979220980220981220982220983220984220985220986220987220988220989220990220991220992220993220994220995220996220997220998220999221000221001221002221003221004221005221006221007221008221009221010221011221012221013221014221015221016221017221018221019221020221021221022221023221024221025221026221027221028221029221030221031221032221033221034221035221036221037221038221039221040221041221042221043221044221045221046221047221048221049221050221051221052221053221054221055221056221057221058221059221060221061221062221063221064221065221066221067221068221069221070221071221072221073221074221075221076221077221078221079221080221081221082221083221084221085221086221087221088221089221090221091221092221093221094221095221096221097221098221099221100221101221102221103221104221105221106221107221108221109221110221111221112221113221114221115221116221117221118221119221120221121221122221123221124221125221126221127221128221129221130221131221132221133221134221135221136221137221138221139221140221141221142221143221144221145221146221147221148221149221150221151221152221153221154221155221156221157221158221159221160221161221162221163221164221165221166221167221168221169221170221171221172221173221174221175221176221177221178221179221180221181221182221183221184221185221186221187221188221189221190221191221192221193221194221195221196221197221198221199221200221201221202221203221204221205221206221207221208221209221210221211221212221213221214221215221216221217221218221219221220221221221222221223221224221225221226221227221228221229221230221231221232221233221234221235221236221237221238221239221240221241221242221243221244221245221246221247221248221249221250221251221252221253221254221255221256221257221258221259221260221261221262221263221264221265221266221267221268221269221270221271221272221273221274221275221276221277221278221279221280221281221282221283221284221285221286221287221288221289221290221291221292221293221294221295221296221297221298221299221300221301221302221303221304221305221306221307221308221309221310221311221312221313221314221315221316221317221318221319221320221321221322221323221324221325221326221327221328221329221330221331221332221333221334221335221336221337221338221339221340221341221342221343221344221345221346221347221348221349221350221351221352221353221354221355221356221357221358221359221360221361221362221363221364221365221366221367221368221369221370221371221372221373221374221375221376221377221378221379221380221381221382221383221384221385221386221387221388221389221390221391221392221393221394221395221396221397221398221399221400221401221402221403221404221405221406221407221408221409221410221411221412221413221414221415221416221417221418221419221420221421221422221423221424221425221426221427221428221429221430221431221432221433221434221435221436221437221438221439221440221441221442221443221444221445221446221447221448221449221450221451221452221453221454221455221456221457221458221459221460221461221462221463221464221465221466221467221468221469221470221471221472221473221474221475221476221477221478221479221480221481221482221483221484221485221486221487221488221489221490221491221492221493221494221495221496221497221498221499221500221501221502221503221504221505221506221507221508221509221510221511221512221513221514221515221516221517221518221519221520221521221522221523221524221525221526221527221528221529221530221531221532221533221534221535221536221537221538221539221540221541221542221543221544221545221546221547221548221549221550221551221552221553221554221555221556221557221558221559221560221561221562221563221564221565221566221567221568221569221570221571221572221573221574221575221576221577221578221579221580221581221582221583221584221585221586221587221588221589221590221591221592221593221594221595221596221597221598221599221600221601221602221603221604221605221606221607221608221609221610221611221612221613221614221615221616221617221618221619221620221621221622221623221624221625221626221627221628221629221630221631221632221633221634221635221636221637221638221639221640221641221642221643221644221645221646221647221648221649221650221651221652221653221654221655221656221657221658221659221660221661221662221663221664221665221666221667221668221669221670221671221672221673221674221675221676221677221678221679221680221681221682221683221684221685221686221687221688221689221690221691221692221693221694221695221696221697221698221699221700221701221702221703221704221705221706221707221708221709221710221711221712221713221714221715221716221717221718221719221720221721221722221723221724221725221726221727221728221729221730221731221732221733221734221735221736221737221738221739221740221741221742221743221744221745221746221747221748221749221750221751221752221753221754221755221756221757221758221759221760221761221762221763221764221765221766221767221768221769221770221771221772221773221774221775221776221777221778221779221780221781221782221783221784221785221786221787221788221789221790221791221792221793221794221795221796221797221798221799221800221801221802221803221804221805221806221807221808221809221810221811221812221813221814221815221816221817221818221819221820221821221822221823221824221825221826221827221828221829221830221831221832221833221834221835221836221837221838221839221840221841221842221843221844221845221846221847221848221849221850221851221852221853221854221855221856221857221858221859221860221861221862221863221864221865221866221867221868221869221870221871221872221873221874221875221876221877221878221879221880221881221882221883221884221885221886221887221888221889221890221891221892221893221894221895221896221897221898221899221900221901221902221903221904221905221906221907221908221909221910221911221912221913221914221915221916221917221918221919221920221921221922221923221924221925221926221927221928221929221930221931221932221933221934221935221936221937221938221939221940221941221942221943221944221945221946221947221948221949221950221951221952221953221954221955221956221957221958221959221960221961221962221963221964221965221966221967221968221969221970221971221972221973221974221975221976221977221978221979221980221981221982221983221984221985221986221987221988221989221990221991221992221993221994221995221996221997221998221999222000222001222002222003222004222005222006222007222008222009222010222011222012222013222014222015222016222017222018222019222020222021222022222023222024222025222026222027222028222029222030222031222032222033222034222035222036222037222038222039222040222041222042222043222044222045222046222047222048222049222050222051222052222053222054222055222056222057222058222059222060222061222062222063222064222065222066222067222068222069222070222071222072222073222074222075222076222077222078222079222080222081222082222083222084222085222086222087222088222089222090222091222092222093222094222095222096222097222098222099222100222101222102222103222104222105222106222107222108222109222110222111222112222113222114222115222116222117222118222119222120222121222122222123222124222125222126222127222128222129222130222131222132222133222134222135222136222137222138222139222140222141222142222143222144222145222146222147222148222149222150222151222152222153222154222155222156222157222158222159222160222161222162222163222164222165222166222167222168222169222170222171222172222173222174222175222176222177222178222179222180222181222182222183222184222185222186222187222188222189222190222191222192222193222194222195222196222197222198222199222200222201222202222203222204222205222206222207222208222209222210222211222212222213222214222215222216222217222218222219222220222221222222222223222224222225222226222227222228222229222230222231222232222233222234222235222236222237222238222239222240222241222242222243222244222245222246222247222248222249222250222251222252222253222254222255222256222257222258222259222260222261222262222263222264222265222266222267222268222269222270222271222272222273222274222275222276222277222278222279222280222281222282222283222284222285222286222287222288222289222290222291222292222293222294222295222296222297222298222299222300222301222302222303222304222305222306222307222308222309222310222311222312222313222314222315222316222317222318222319222320222321222322222323222324222325222326222327222328222329222330222331222332222333222334222335222336222337222338222339222340222341222342222343222344222345222346222347222348222349222350222351222352222353222354222355222356222357222358222359222360222361222362222363222364222365222366222367222368222369222370222371222372222373222374222375222376222377222378222379222380222381222382222383222384222385222386222387222388222389222390222391222392222393222394222395222396222397222398222399222400222401222402222403222404222405222406222407222408222409222410222411222412222413222414222415222416222417222418222419222420222421222422222423222424222425222426222427222428222429222430222431222432222433222434222435222436222437222438222439222440222441222442222443222444222445222446222447222448222449222450222451222452222453222454222455222456222457222458222459222460222461222462222463222464222465222466222467222468222469222470222471222472222473222474222475222476222477222478222479222480222481222482222483222484222485222486222487222488222489222490222491222492222493222494222495222496222497222498222499222500222501222502222503222504222505222506222507222508222509222510222511222512222513222514222515222516222517222518222519222520222521222522222523222524222525222526222527222528222529222530222531222532222533222534222535222536222537222538222539222540222541222542222543222544222545222546222547222548222549222550222551222552222553222554222555222556222557222558222559222560222561222562222563222564222565222566222567222568222569222570222571222572222573222574222575222576222577222578222579222580222581222582222583222584222585222586222587222588222589222590222591222592222593222594222595222596222597222598222599222600222601222602222603222604222605222606222607222608222609222610222611222612222613222614222615222616222617222618222619222620222621222622222623222624222625222626222627222628222629222630222631222632222633222634222635222636222637222638222639222640222641222642222643222644222645222646222647222648222649222650222651222652222653222654222655222656222657222658222659222660222661222662222663222664222665222666222667222668222669222670222671222672222673222674222675222676222677222678222679222680222681222682222683222684222685222686222687222688222689222690222691222692222693222694222695222696222697222698222699222700222701222702222703222704222705222706222707222708222709222710222711222712222713222714222715222716222717222718222719222720222721222722222723222724222725222726222727222728222729222730222731222732222733222734222735222736222737222738222739222740222741222742222743222744222745222746222747222748222749222750222751222752222753222754222755222756222757222758222759222760222761222762222763222764222765222766222767222768222769222770222771222772222773222774222775222776222777222778222779222780222781222782222783222784222785222786222787222788222789222790222791222792222793222794222795222796222797222798222799222800222801222802222803222804222805222806222807222808222809222810222811222812222813222814222815222816222817222818222819222820222821222822222823222824222825222826222827222828222829222830222831222832222833222834222835222836222837222838222839222840222841222842222843222844222845222846222847222848222849222850222851222852222853222854222855222856222857222858222859222860222861222862222863222864222865222866222867222868222869222870222871222872222873222874222875222876
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.28.0. By combining all the individual C code files into this
  4. ** single large file, the entire code can be compiled as a single translation
  5. ** unit. This allows many compilers to do optimizations that would not be
  6. ** possible if the files were compiled separately. Performance improvements
  7. ** of 5% or more are commonly seen when SQLite is compiled as a single
  8. ** translation unit.
  9. **
  10. ** This file is all you need to compile SQLite. To use SQLite in other
  11. ** programs, you need this file and the "sqlite3.h" header file that defines
  12. ** the programming interface to the SQLite library. (If you do not have
  13. ** the "sqlite3.h" header file at hand, you will find a copy embedded within
  14. ** the text of this file. Search for "Begin file sqlite3.h" to find the start
  15. ** of the embedded sqlite3.h header file.) Additional code files may be needed
  16. ** if you want a wrapper to interface SQLite with your choice of programming
  17. ** language. The code for the "sqlite3" command-line shell is also in a
  18. ** separate file. This file contains only code for the core SQLite library.
  19. */
  20. #define SQLITE_CORE 1
  21. #define SQLITE_AMALGAMATION 1
  22. #ifndef SQLITE_PRIVATE
  23. # define SQLITE_PRIVATE static
  24. #endif
  25. /************** Begin file ctime.c *******************************************/
  26. /*
  27. ** 2010 February 23
  28. **
  29. ** The author disclaims copyright to this source code. In place of
  30. ** a legal notice, here is a blessing:
  31. **
  32. ** May you do good and not evil.
  33. ** May you find forgiveness for yourself and forgive others.
  34. ** May you share freely, never taking more than you give.
  35. **
  36. *************************************************************************
  37. **
  38. ** This file implements routines used to report what compile-time options
  39. ** SQLite was built with.
  40. */
  41. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  42. /*
  43. ** Include the configuration header output by 'configure' if we're using the
  44. ** autoconf-based build
  45. */
  46. #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
  47. #include "config.h"
  48. #define SQLITECONFIG_H 1
  49. #endif
  50. /* These macros are provided to "stringify" the value of the define
  51. ** for those options in which the value is meaningful. */
  52. #define CTIMEOPT_VAL_(opt) #opt
  53. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  54. /* Like CTIMEOPT_VAL, but especially for SQLITE_DEFAULT_LOOKASIDE. This
  55. ** option requires a separate macro because legal values contain a single
  56. ** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
  57. #define CTIMEOPT_VAL2_(opt1,opt2) #opt1 "," #opt2
  58. #define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)
  59. /*
  60. ** An array of names of all compile-time options. This array should
  61. ** be sorted A-Z.
  62. **
  63. ** This array looks large, but in a typical installation actually uses
  64. ** only a handful of compile-time options, so most times this array is usually
  65. ** rather short and uses little memory space.
  66. */
  67. static const char * const sqlite3azCompileOpt[] = {
  68. /*
  69. ** BEGIN CODE GENERATED BY tool/mkctime.tcl
  70. */
  71. #if SQLITE_32BIT_ROWID
  72. "32BIT_ROWID",
  73. #endif
  74. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  75. "4_BYTE_ALIGNED_MALLOC",
  76. #endif
  77. #if SQLITE_64BIT_STATS
  78. "64BIT_STATS",
  79. #endif
  80. #if SQLITE_ALLOW_COVERING_INDEX_SCAN
  81. "ALLOW_COVERING_INDEX_SCAN",
  82. #endif
  83. #if SQLITE_ALLOW_URI_AUTHORITY
  84. "ALLOW_URI_AUTHORITY",
  85. #endif
  86. #ifdef SQLITE_BITMASK_TYPE
  87. "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
  88. #endif
  89. #if SQLITE_BUG_COMPATIBLE_20160819
  90. "BUG_COMPATIBLE_20160819",
  91. #endif
  92. #if SQLITE_CASE_SENSITIVE_LIKE
  93. "CASE_SENSITIVE_LIKE",
  94. #endif
  95. #if SQLITE_CHECK_PAGES
  96. "CHECK_PAGES",
  97. #endif
  98. #if defined(__clang__) && defined(__clang_major__)
  99. "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
  100. CTIMEOPT_VAL(__clang_minor__) "."
  101. CTIMEOPT_VAL(__clang_patchlevel__),
  102. #elif defined(_MSC_VER)
  103. "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
  104. #elif defined(__GNUC__) && defined(__VERSION__)
  105. "COMPILER=gcc-" __VERSION__,
  106. #endif
  107. #if SQLITE_COVERAGE_TEST
  108. "COVERAGE_TEST",
  109. #endif
  110. #if SQLITE_DEBUG
  111. "DEBUG",
  112. #endif
  113. #if SQLITE_DEFAULT_AUTOMATIC_INDEX
  114. "DEFAULT_AUTOMATIC_INDEX",
  115. #endif
  116. #if SQLITE_DEFAULT_AUTOVACUUM
  117. "DEFAULT_AUTOVACUUM",
  118. #endif
  119. #ifdef SQLITE_DEFAULT_CACHE_SIZE
  120. "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
  121. #endif
  122. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  123. "DEFAULT_CKPTFULLFSYNC",
  124. #endif
  125. #ifdef SQLITE_DEFAULT_FILE_FORMAT
  126. "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
  127. #endif
  128. #ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
  129. "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
  130. #endif
  131. #if SQLITE_DEFAULT_FOREIGN_KEYS
  132. "DEFAULT_FOREIGN_KEYS",
  133. #endif
  134. #ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  135. "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
  136. #endif
  137. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  138. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  139. #endif
  140. #ifdef SQLITE_DEFAULT_LOOKASIDE
  141. "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL2(SQLITE_DEFAULT_LOOKASIDE),
  142. #endif
  143. #if SQLITE_DEFAULT_MEMSTATUS
  144. "DEFAULT_MEMSTATUS",
  145. #endif
  146. #ifdef SQLITE_DEFAULT_MMAP_SIZE
  147. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  148. #endif
  149. #ifdef SQLITE_DEFAULT_PAGE_SIZE
  150. "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
  151. #endif
  152. #ifdef SQLITE_DEFAULT_PCACHE_INITSZ
  153. "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
  154. #endif
  155. #ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  156. "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
  157. #endif
  158. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  159. "DEFAULT_RECURSIVE_TRIGGERS",
  160. #endif
  161. #ifdef SQLITE_DEFAULT_ROWEST
  162. "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
  163. #endif
  164. #ifdef SQLITE_DEFAULT_SECTOR_SIZE
  165. "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
  166. #endif
  167. #ifdef SQLITE_DEFAULT_SYNCHRONOUS
  168. "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
  169. #endif
  170. #ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  171. "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
  172. #endif
  173. #ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  174. "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
  175. #endif
  176. #ifdef SQLITE_DEFAULT_WORKER_THREADS
  177. "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
  178. #endif
  179. #if SQLITE_DIRECT_OVERFLOW_READ
  180. "DIRECT_OVERFLOW_READ",
  181. #endif
  182. #if SQLITE_DISABLE_DIRSYNC
  183. "DISABLE_DIRSYNC",
  184. #endif
  185. #if SQLITE_DISABLE_FTS3_UNICODE
  186. "DISABLE_FTS3_UNICODE",
  187. #endif
  188. #if SQLITE_DISABLE_FTS4_DEFERRED
  189. "DISABLE_FTS4_DEFERRED",
  190. #endif
  191. #if SQLITE_DISABLE_INTRINSIC
  192. "DISABLE_INTRINSIC",
  193. #endif
  194. #if SQLITE_DISABLE_LFS
  195. "DISABLE_LFS",
  196. #endif
  197. #if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  198. "DISABLE_PAGECACHE_OVERFLOW_STATS",
  199. #endif
  200. #if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  201. "DISABLE_SKIPAHEAD_DISTINCT",
  202. #endif
  203. #ifdef SQLITE_ENABLE_8_3_NAMES
  204. "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
  205. #endif
  206. #if SQLITE_ENABLE_API_ARMOR
  207. "ENABLE_API_ARMOR",
  208. #endif
  209. #if SQLITE_ENABLE_ATOMIC_WRITE
  210. "ENABLE_ATOMIC_WRITE",
  211. #endif
  212. #if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  213. "ENABLE_BATCH_ATOMIC_WRITE",
  214. #endif
  215. #if SQLITE_ENABLE_CEROD
  216. "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
  217. #endif
  218. #if SQLITE_ENABLE_COLUMN_METADATA
  219. "ENABLE_COLUMN_METADATA",
  220. #endif
  221. #if SQLITE_ENABLE_COLUMN_USED_MASK
  222. "ENABLE_COLUMN_USED_MASK",
  223. #endif
  224. #if SQLITE_ENABLE_COSTMULT
  225. "ENABLE_COSTMULT",
  226. #endif
  227. #if SQLITE_ENABLE_CURSOR_HINTS
  228. "ENABLE_CURSOR_HINTS",
  229. #endif
  230. #if SQLITE_ENABLE_DBSTAT_VTAB
  231. "ENABLE_DBSTAT_VTAB",
  232. #endif
  233. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  234. "ENABLE_EXPENSIVE_ASSERT",
  235. #endif
  236. #if SQLITE_ENABLE_FTS1
  237. "ENABLE_FTS1",
  238. #endif
  239. #if SQLITE_ENABLE_FTS2
  240. "ENABLE_FTS2",
  241. #endif
  242. #if SQLITE_ENABLE_FTS3
  243. "ENABLE_FTS3",
  244. #endif
  245. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  246. "ENABLE_FTS3_PARENTHESIS",
  247. #endif
  248. #if SQLITE_ENABLE_FTS3_TOKENIZER
  249. "ENABLE_FTS3_TOKENIZER",
  250. #endif
  251. #if SQLITE_ENABLE_FTS4
  252. "ENABLE_FTS4",
  253. #endif
  254. #if SQLITE_ENABLE_FTS5
  255. "ENABLE_FTS5",
  256. #endif
  257. #if SQLITE_ENABLE_GEOPOLY
  258. "ENABLE_GEOPOLY",
  259. #endif
  260. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  261. "ENABLE_HIDDEN_COLUMNS",
  262. #endif
  263. #if SQLITE_ENABLE_ICU
  264. "ENABLE_ICU",
  265. #endif
  266. #if SQLITE_ENABLE_IOTRACE
  267. "ENABLE_IOTRACE",
  268. #endif
  269. #if SQLITE_ENABLE_JSON1
  270. "ENABLE_JSON1",
  271. #endif
  272. #if SQLITE_ENABLE_LOAD_EXTENSION
  273. "ENABLE_LOAD_EXTENSION",
  274. #endif
  275. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  276. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  277. #endif
  278. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  279. "ENABLE_MEMORY_MANAGEMENT",
  280. #endif
  281. #if SQLITE_ENABLE_MEMSYS3
  282. "ENABLE_MEMSYS3",
  283. #endif
  284. #if SQLITE_ENABLE_MEMSYS5
  285. "ENABLE_MEMSYS5",
  286. #endif
  287. #if SQLITE_ENABLE_MULTIPLEX
  288. "ENABLE_MULTIPLEX",
  289. #endif
  290. #if SQLITE_ENABLE_NORMALIZE
  291. "ENABLE_NORMALIZE",
  292. #endif
  293. #if SQLITE_ENABLE_NULL_TRIM
  294. "ENABLE_NULL_TRIM",
  295. #endif
  296. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  297. "ENABLE_OVERSIZE_CELL_CHECK",
  298. #endif
  299. #if SQLITE_ENABLE_PREUPDATE_HOOK
  300. "ENABLE_PREUPDATE_HOOK",
  301. #endif
  302. #if SQLITE_ENABLE_QPSG
  303. "ENABLE_QPSG",
  304. #endif
  305. #if SQLITE_ENABLE_RBU
  306. "ENABLE_RBU",
  307. #endif
  308. #if SQLITE_ENABLE_RTREE
  309. "ENABLE_RTREE",
  310. #endif
  311. #if SQLITE_ENABLE_SELECTTRACE
  312. "ENABLE_SELECTTRACE",
  313. #endif
  314. #if SQLITE_ENABLE_SESSION
  315. "ENABLE_SESSION",
  316. #endif
  317. #if SQLITE_ENABLE_SNAPSHOT
  318. "ENABLE_SNAPSHOT",
  319. #endif
  320. #if SQLITE_ENABLE_SORTER_REFERENCES
  321. "ENABLE_SORTER_REFERENCES",
  322. #endif
  323. #if SQLITE_ENABLE_SQLLOG
  324. "ENABLE_SQLLOG",
  325. #endif
  326. #if defined(SQLITE_ENABLE_STAT4)
  327. "ENABLE_STAT4",
  328. #elif defined(SQLITE_ENABLE_STAT3)
  329. "ENABLE_STAT3",
  330. #endif
  331. #if SQLITE_ENABLE_STMTVTAB
  332. "ENABLE_STMTVTAB",
  333. #endif
  334. #if SQLITE_ENABLE_STMT_SCANSTATUS
  335. "ENABLE_STMT_SCANSTATUS",
  336. #endif
  337. #if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  338. "ENABLE_UNKNOWN_SQL_FUNCTION",
  339. #endif
  340. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  341. "ENABLE_UNLOCK_NOTIFY",
  342. #endif
  343. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  344. "ENABLE_UPDATE_DELETE_LIMIT",
  345. #endif
  346. #if SQLITE_ENABLE_URI_00_ERROR
  347. "ENABLE_URI_00_ERROR",
  348. #endif
  349. #if SQLITE_ENABLE_VFSTRACE
  350. "ENABLE_VFSTRACE",
  351. #endif
  352. #if SQLITE_ENABLE_WHERETRACE
  353. "ENABLE_WHERETRACE",
  354. #endif
  355. #if SQLITE_ENABLE_ZIPVFS
  356. "ENABLE_ZIPVFS",
  357. #endif
  358. #if SQLITE_EXPLAIN_ESTIMATED_ROWS
  359. "EXPLAIN_ESTIMATED_ROWS",
  360. #endif
  361. #if SQLITE_EXTRA_IFNULLROW
  362. "EXTRA_IFNULLROW",
  363. #endif
  364. #ifdef SQLITE_EXTRA_INIT
  365. "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
  366. #endif
  367. #ifdef SQLITE_EXTRA_SHUTDOWN
  368. "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
  369. #endif
  370. #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
  371. "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
  372. #endif
  373. #if SQLITE_FTS5_ENABLE_TEST_MI
  374. "FTS5_ENABLE_TEST_MI",
  375. #endif
  376. #if SQLITE_FTS5_NO_WITHOUT_ROWID
  377. "FTS5_NO_WITHOUT_ROWID",
  378. #endif
  379. #if SQLITE_HAS_CODEC
  380. "HAS_CODEC",
  381. #endif
  382. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  383. "HAVE_ISNAN",
  384. #endif
  385. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  386. "HOMEGROWN_RECURSIVE_MUTEX",
  387. #endif
  388. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  389. "IGNORE_AFP_LOCK_ERRORS",
  390. #endif
  391. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  392. "IGNORE_FLOCK_LOCK_ERRORS",
  393. #endif
  394. #if SQLITE_INLINE_MEMCPY
  395. "INLINE_MEMCPY",
  396. #endif
  397. #if SQLITE_INT64_TYPE
  398. "INT64_TYPE",
  399. #endif
  400. #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  401. "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
  402. #endif
  403. #if SQLITE_LIKE_DOESNT_MATCH_BLOBS
  404. "LIKE_DOESNT_MATCH_BLOBS",
  405. #endif
  406. #if SQLITE_LOCK_TRACE
  407. "LOCK_TRACE",
  408. #endif
  409. #if SQLITE_LOG_CACHE_SPILL
  410. "LOG_CACHE_SPILL",
  411. #endif
  412. #ifdef SQLITE_MALLOC_SOFT_LIMIT
  413. "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
  414. #endif
  415. #ifdef SQLITE_MAX_ATTACHED
  416. "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
  417. #endif
  418. #ifdef SQLITE_MAX_COLUMN
  419. "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
  420. #endif
  421. #ifdef SQLITE_MAX_COMPOUND_SELECT
  422. "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
  423. #endif
  424. #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
  425. "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
  426. #endif
  427. #ifdef SQLITE_MAX_EXPR_DEPTH
  428. "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
  429. #endif
  430. #ifdef SQLITE_MAX_FUNCTION_ARG
  431. "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
  432. #endif
  433. #ifdef SQLITE_MAX_LENGTH
  434. "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
  435. #endif
  436. #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
  437. "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
  438. #endif
  439. #ifdef SQLITE_MAX_MEMORY
  440. "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
  441. #endif
  442. #ifdef SQLITE_MAX_MMAP_SIZE
  443. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  444. #endif
  445. #ifdef SQLITE_MAX_MMAP_SIZE_
  446. "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
  447. #endif
  448. #ifdef SQLITE_MAX_PAGE_COUNT
  449. "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
  450. #endif
  451. #ifdef SQLITE_MAX_PAGE_SIZE
  452. "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
  453. #endif
  454. #ifdef SQLITE_MAX_SCHEMA_RETRY
  455. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  456. #endif
  457. #ifdef SQLITE_MAX_SQL_LENGTH
  458. "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
  459. #endif
  460. #ifdef SQLITE_MAX_TRIGGER_DEPTH
  461. "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
  462. #endif
  463. #ifdef SQLITE_MAX_VARIABLE_NUMBER
  464. "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
  465. #endif
  466. #ifdef SQLITE_MAX_VDBE_OP
  467. "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
  468. #endif
  469. #ifdef SQLITE_MAX_WORKER_THREADS
  470. "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
  471. #endif
  472. #if SQLITE_MEMDEBUG
  473. "MEMDEBUG",
  474. #endif
  475. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  476. "MIXED_ENDIAN_64BIT_FLOAT",
  477. #endif
  478. #if SQLITE_MMAP_READWRITE
  479. "MMAP_READWRITE",
  480. #endif
  481. #if SQLITE_MUTEX_NOOP
  482. "MUTEX_NOOP",
  483. #endif
  484. #if SQLITE_MUTEX_NREF
  485. "MUTEX_NREF",
  486. #endif
  487. #if SQLITE_MUTEX_OMIT
  488. "MUTEX_OMIT",
  489. #endif
  490. #if SQLITE_MUTEX_PTHREADS
  491. "MUTEX_PTHREADS",
  492. #endif
  493. #if SQLITE_MUTEX_W32
  494. "MUTEX_W32",
  495. #endif
  496. #if SQLITE_NEED_ERR_NAME
  497. "NEED_ERR_NAME",
  498. #endif
  499. #if SQLITE_NOINLINE
  500. "NOINLINE",
  501. #endif
  502. #if SQLITE_NO_SYNC
  503. "NO_SYNC",
  504. #endif
  505. #if SQLITE_OMIT_ALTERTABLE
  506. "OMIT_ALTERTABLE",
  507. #endif
  508. #if SQLITE_OMIT_ANALYZE
  509. "OMIT_ANALYZE",
  510. #endif
  511. #if SQLITE_OMIT_ATTACH
  512. "OMIT_ATTACH",
  513. #endif
  514. #if SQLITE_OMIT_AUTHORIZATION
  515. "OMIT_AUTHORIZATION",
  516. #endif
  517. #if SQLITE_OMIT_AUTOINCREMENT
  518. "OMIT_AUTOINCREMENT",
  519. #endif
  520. #if SQLITE_OMIT_AUTOINIT
  521. "OMIT_AUTOINIT",
  522. #endif
  523. #if SQLITE_OMIT_AUTOMATIC_INDEX
  524. "OMIT_AUTOMATIC_INDEX",
  525. #endif
  526. #if SQLITE_OMIT_AUTORESET
  527. "OMIT_AUTORESET",
  528. #endif
  529. #if SQLITE_OMIT_AUTOVACUUM
  530. "OMIT_AUTOVACUUM",
  531. #endif
  532. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  533. "OMIT_BETWEEN_OPTIMIZATION",
  534. #endif
  535. #if SQLITE_OMIT_BLOB_LITERAL
  536. "OMIT_BLOB_LITERAL",
  537. #endif
  538. #if SQLITE_OMIT_BTREECOUNT
  539. "OMIT_BTREECOUNT",
  540. #endif
  541. #if SQLITE_OMIT_CAST
  542. "OMIT_CAST",
  543. #endif
  544. #if SQLITE_OMIT_CHECK
  545. "OMIT_CHECK",
  546. #endif
  547. #if SQLITE_OMIT_COMPLETE
  548. "OMIT_COMPLETE",
  549. #endif
  550. #if SQLITE_OMIT_COMPOUND_SELECT
  551. "OMIT_COMPOUND_SELECT",
  552. #endif
  553. #if SQLITE_OMIT_CONFLICT_CLAUSE
  554. "OMIT_CONFLICT_CLAUSE",
  555. #endif
  556. #if SQLITE_OMIT_CTE
  557. "OMIT_CTE",
  558. #endif
  559. #if SQLITE_OMIT_DATETIME_FUNCS
  560. "OMIT_DATETIME_FUNCS",
  561. #endif
  562. #if SQLITE_OMIT_DECLTYPE
  563. "OMIT_DECLTYPE",
  564. #endif
  565. #if SQLITE_OMIT_DEPRECATED
  566. "OMIT_DEPRECATED",
  567. #endif
  568. #if SQLITE_OMIT_DISKIO
  569. "OMIT_DISKIO",
  570. #endif
  571. #if SQLITE_OMIT_EXPLAIN
  572. "OMIT_EXPLAIN",
  573. #endif
  574. #if SQLITE_OMIT_FLAG_PRAGMAS
  575. "OMIT_FLAG_PRAGMAS",
  576. #endif
  577. #if SQLITE_OMIT_FLOATING_POINT
  578. "OMIT_FLOATING_POINT",
  579. #endif
  580. #if SQLITE_OMIT_FOREIGN_KEY
  581. "OMIT_FOREIGN_KEY",
  582. #endif
  583. #if SQLITE_OMIT_GET_TABLE
  584. "OMIT_GET_TABLE",
  585. #endif
  586. #if SQLITE_OMIT_HEX_INTEGER
  587. "OMIT_HEX_INTEGER",
  588. #endif
  589. #if SQLITE_OMIT_INCRBLOB
  590. "OMIT_INCRBLOB",
  591. #endif
  592. #if SQLITE_OMIT_INTEGRITY_CHECK
  593. "OMIT_INTEGRITY_CHECK",
  594. #endif
  595. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  596. "OMIT_LIKE_OPTIMIZATION",
  597. #endif
  598. #if SQLITE_OMIT_LOAD_EXTENSION
  599. "OMIT_LOAD_EXTENSION",
  600. #endif
  601. #if SQLITE_OMIT_LOCALTIME
  602. "OMIT_LOCALTIME",
  603. #endif
  604. #if SQLITE_OMIT_LOOKASIDE
  605. "OMIT_LOOKASIDE",
  606. #endif
  607. #if SQLITE_OMIT_MEMORYDB
  608. "OMIT_MEMORYDB",
  609. #endif
  610. #if SQLITE_OMIT_OR_OPTIMIZATION
  611. "OMIT_OR_OPTIMIZATION",
  612. #endif
  613. #if SQLITE_OMIT_PAGER_PRAGMAS
  614. "OMIT_PAGER_PRAGMAS",
  615. #endif
  616. #if SQLITE_OMIT_PARSER_TRACE
  617. "OMIT_PARSER_TRACE",
  618. #endif
  619. #if SQLITE_OMIT_POPEN
  620. "OMIT_POPEN",
  621. #endif
  622. #if SQLITE_OMIT_PRAGMA
  623. "OMIT_PRAGMA",
  624. #endif
  625. #if SQLITE_OMIT_PROGRESS_CALLBACK
  626. "OMIT_PROGRESS_CALLBACK",
  627. #endif
  628. #if SQLITE_OMIT_QUICKBALANCE
  629. "OMIT_QUICKBALANCE",
  630. #endif
  631. #if SQLITE_OMIT_REINDEX
  632. "OMIT_REINDEX",
  633. #endif
  634. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  635. "OMIT_SCHEMA_PRAGMAS",
  636. #endif
  637. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  638. "OMIT_SCHEMA_VERSION_PRAGMAS",
  639. #endif
  640. #if SQLITE_OMIT_SHARED_CACHE
  641. "OMIT_SHARED_CACHE",
  642. #endif
  643. #if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  644. "OMIT_SHUTDOWN_DIRECTORIES",
  645. #endif
  646. #if SQLITE_OMIT_SUBQUERY
  647. "OMIT_SUBQUERY",
  648. #endif
  649. #if SQLITE_OMIT_TCL_VARIABLE
  650. "OMIT_TCL_VARIABLE",
  651. #endif
  652. #if SQLITE_OMIT_TEMPDB
  653. "OMIT_TEMPDB",
  654. #endif
  655. #if SQLITE_OMIT_TEST_CONTROL
  656. "OMIT_TEST_CONTROL",
  657. #endif
  658. #if SQLITE_OMIT_TRACE
  659. "OMIT_TRACE",
  660. #endif
  661. #if SQLITE_OMIT_TRIGGER
  662. "OMIT_TRIGGER",
  663. #endif
  664. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  665. "OMIT_TRUNCATE_OPTIMIZATION",
  666. #endif
  667. #if SQLITE_OMIT_UTF16
  668. "OMIT_UTF16",
  669. #endif
  670. #if SQLITE_OMIT_VACUUM
  671. "OMIT_VACUUM",
  672. #endif
  673. #if SQLITE_OMIT_VIEW
  674. "OMIT_VIEW",
  675. #endif
  676. #if SQLITE_OMIT_VIRTUALTABLE
  677. "OMIT_VIRTUALTABLE",
  678. #endif
  679. #if SQLITE_OMIT_WAL
  680. "OMIT_WAL",
  681. #endif
  682. #if SQLITE_OMIT_WSD
  683. "OMIT_WSD",
  684. #endif
  685. #if SQLITE_OMIT_XFER_OPT
  686. "OMIT_XFER_OPT",
  687. #endif
  688. #if SQLITE_PCACHE_SEPARATE_HEADER
  689. "PCACHE_SEPARATE_HEADER",
  690. #endif
  691. #if SQLITE_PERFORMANCE_TRACE
  692. "PERFORMANCE_TRACE",
  693. #endif
  694. #if SQLITE_POWERSAFE_OVERWRITE
  695. "POWERSAFE_OVERWRITE",
  696. #endif
  697. #if SQLITE_PREFER_PROXY_LOCKING
  698. "PREFER_PROXY_LOCKING",
  699. #endif
  700. #if SQLITE_PROXY_DEBUG
  701. "PROXY_DEBUG",
  702. #endif
  703. #if SQLITE_REVERSE_UNORDERED_SELECTS
  704. "REVERSE_UNORDERED_SELECTS",
  705. #endif
  706. #if SQLITE_RTREE_INT_ONLY
  707. "RTREE_INT_ONLY",
  708. #endif
  709. #if SQLITE_SECURE_DELETE
  710. "SECURE_DELETE",
  711. #endif
  712. #if SQLITE_SMALL_STACK
  713. "SMALL_STACK",
  714. #endif
  715. #ifdef SQLITE_SORTER_PMASZ
  716. "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
  717. #endif
  718. #if SQLITE_SOUNDEX
  719. "SOUNDEX",
  720. #endif
  721. #ifdef SQLITE_STAT4_SAMPLES
  722. "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
  723. #endif
  724. #ifdef SQLITE_STMTJRNL_SPILL
  725. "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
  726. #endif
  727. #if SQLITE_SUBSTR_COMPATIBILITY
  728. "SUBSTR_COMPATIBILITY",
  729. #endif
  730. #if SQLITE_SYSTEM_MALLOC
  731. "SYSTEM_MALLOC",
  732. #endif
  733. #if SQLITE_TCL
  734. "TCL",
  735. #endif
  736. #ifdef SQLITE_TEMP_STORE
  737. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  738. #endif
  739. #if SQLITE_TEST
  740. "TEST",
  741. #endif
  742. #if defined(SQLITE_THREADSAFE)
  743. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  744. #elif defined(THREADSAFE)
  745. "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
  746. #else
  747. "THREADSAFE=1",
  748. #endif
  749. #if SQLITE_UNLINK_AFTER_CLOSE
  750. "UNLINK_AFTER_CLOSE",
  751. #endif
  752. #if SQLITE_UNTESTABLE
  753. "UNTESTABLE",
  754. #endif
  755. #if SQLITE_USER_AUTHENTICATION
  756. "USER_AUTHENTICATION",
  757. #endif
  758. #if SQLITE_USE_ALLOCA
  759. "USE_ALLOCA",
  760. #endif
  761. #if SQLITE_USE_FCNTL_TRACE
  762. "USE_FCNTL_TRACE",
  763. #endif
  764. #if SQLITE_USE_URI
  765. "USE_URI",
  766. #endif
  767. #if SQLITE_VDBE_COVERAGE
  768. "VDBE_COVERAGE",
  769. #endif
  770. #if SQLITE_WIN32_MALLOC
  771. "WIN32_MALLOC",
  772. #endif
  773. #if SQLITE_ZERO_MALLOC
  774. "ZERO_MALLOC",
  775. #endif
  776. /*
  777. ** END CODE GENERATED BY tool/mkctime.tcl
  778. */
  779. };
  780. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
  781. *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
  782. return (const char**)sqlite3azCompileOpt;
  783. }
  784. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  785. /************** End of ctime.c ***********************************************/
  786. /************** Begin file sqliteInt.h ***************************************/
  787. /*
  788. ** 2001 September 15
  789. **
  790. ** The author disclaims copyright to this source code. In place of
  791. ** a legal notice, here is a blessing:
  792. **
  793. ** May you do good and not evil.
  794. ** May you find forgiveness for yourself and forgive others.
  795. ** May you share freely, never taking more than you give.
  796. **
  797. *************************************************************************
  798. ** Internal interface definitions for SQLite.
  799. **
  800. */
  801. #ifndef SQLITEINT_H
  802. #define SQLITEINT_H
  803. /* Special Comments:
  804. **
  805. ** Some comments have special meaning to the tools that measure test
  806. ** coverage:
  807. **
  808. ** NO_TEST - The branches on this line are not
  809. ** measured by branch coverage. This is
  810. ** used on lines of code that actually
  811. ** implement parts of coverage testing.
  812. **
  813. ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
  814. ** and the correct answer is still obtained,
  815. ** though perhaps more slowly.
  816. **
  817. ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
  818. ** and the correct answer is still obtained,
  819. ** though perhaps more slowly.
  820. **
  821. ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
  822. ** that would be harmless and undetectable
  823. ** if it did occur.
  824. **
  825. ** In all cases, the special comment must be enclosed in the usual
  826. ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
  827. ** asterisks and the comment text.
  828. */
  829. /*
  830. ** Make sure the Tcl calling convention macro is defined. This macro is
  831. ** only used by test code and Tcl integration code.
  832. */
  833. #ifndef SQLITE_TCLAPI
  834. # define SQLITE_TCLAPI
  835. #endif
  836. /*
  837. ** Include the header file used to customize the compiler options for MSVC.
  838. ** This should be done first so that it can successfully prevent spurious
  839. ** compiler warnings due to subsequent content in this file and other files
  840. ** that are included by this file.
  841. */
  842. /************** Include msvc.h in the middle of sqliteInt.h ******************/
  843. /************** Begin file msvc.h ********************************************/
  844. /*
  845. ** 2015 January 12
  846. **
  847. ** The author disclaims copyright to this source code. In place of
  848. ** a legal notice, here is a blessing:
  849. **
  850. ** May you do good and not evil.
  851. ** May you find forgiveness for yourself and forgive others.
  852. ** May you share freely, never taking more than you give.
  853. **
  854. ******************************************************************************
  855. **
  856. ** This file contains code that is specific to MSVC.
  857. */
  858. #ifndef SQLITE_MSVC_H
  859. #define SQLITE_MSVC_H
  860. #if defined(_MSC_VER)
  861. #pragma warning(disable : 4054)
  862. #pragma warning(disable : 4055)
  863. #pragma warning(disable : 4100)
  864. #pragma warning(disable : 4127)
  865. #pragma warning(disable : 4130)
  866. #pragma warning(disable : 4152)
  867. #pragma warning(disable : 4189)
  868. #pragma warning(disable : 4206)
  869. #pragma warning(disable : 4210)
  870. #pragma warning(disable : 4232)
  871. #pragma warning(disable : 4244)
  872. #pragma warning(disable : 4305)
  873. #pragma warning(disable : 4306)
  874. #pragma warning(disable : 4702)
  875. #pragma warning(disable : 4706)
  876. #endif /* defined(_MSC_VER) */
  877. #endif /* SQLITE_MSVC_H */
  878. /************** End of msvc.h ************************************************/
  879. /************** Continuing where we left off in sqliteInt.h ******************/
  880. /*
  881. ** Special setup for VxWorks
  882. */
  883. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  884. /************** Begin file vxworks.h *****************************************/
  885. /*
  886. ** 2015-03-02
  887. **
  888. ** The author disclaims copyright to this source code. In place of
  889. ** a legal notice, here is a blessing:
  890. **
  891. ** May you do good and not evil.
  892. ** May you find forgiveness for yourself and forgive others.
  893. ** May you share freely, never taking more than you give.
  894. **
  895. ******************************************************************************
  896. **
  897. ** This file contains code that is specific to Wind River's VxWorks
  898. */
  899. #if defined(__RTP__) || defined(_WRS_KERNEL)
  900. /* This is VxWorks. Set up things specially for that OS
  901. */
  902. #include <vxWorks.h>
  903. #include <pthread.h> /* amalgamator: dontcache */
  904. #define OS_VXWORKS 1
  905. #define SQLITE_OS_OTHER 0
  906. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  907. #define SQLITE_OMIT_LOAD_EXTENSION 1
  908. #define SQLITE_ENABLE_LOCKING_STYLE 0
  909. #define HAVE_UTIME 1
  910. #else
  911. /* This is not VxWorks. */
  912. #define OS_VXWORKS 0
  913. #define HAVE_FCHOWN 1
  914. #define HAVE_READLINK 1
  915. #define HAVE_LSTAT 1
  916. #endif /* defined(_WRS_KERNEL) */
  917. /************** End of vxworks.h *********************************************/
  918. /************** Continuing where we left off in sqliteInt.h ******************/
  919. /*
  920. ** These #defines should enable >2GB file support on POSIX if the
  921. ** underlying operating system supports it. If the OS lacks
  922. ** large file support, or if the OS is windows, these should be no-ops.
  923. **
  924. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  925. ** system #includes. Hence, this block of code must be the very first
  926. ** code in all source files.
  927. **
  928. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  929. ** on the compiler command line. This is necessary if you are compiling
  930. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  931. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  932. ** without this option, LFS is enable. But LFS does not exist in the kernel
  933. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  934. ** portability you should omit LFS.
  935. **
  936. ** The previous paragraph was written in 2005. (This paragraph is written
  937. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  938. ** you should probably leave LFS enabled. But some embedded platforms might
  939. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  940. **
  941. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  942. */
  943. #ifndef SQLITE_DISABLE_LFS
  944. # define _LARGE_FILE 1
  945. # ifndef _FILE_OFFSET_BITS
  946. # define _FILE_OFFSET_BITS 64
  947. # endif
  948. # define _LARGEFILE_SOURCE 1
  949. #endif
  950. /* The GCC_VERSION and MSVC_VERSION macros are used to
  951. ** conditionally include optimizations for each of these compilers. A
  952. ** value of 0 means that compiler is not being used. The
  953. ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
  954. ** optimizations, and hence set all compiler macros to 0
  955. **
  956. ** There was once also a CLANG_VERSION macro. However, we learn that the
  957. ** version numbers in clang are for "marketing" only and are inconsistent
  958. ** and unreliable. Fortunately, all versions of clang also recognize the
  959. ** gcc version numbers and have reasonable settings for gcc version numbers,
  960. ** so the GCC_VERSION macro will be set to a correct non-zero value even
  961. ** when compiling with clang.
  962. */
  963. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  964. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  965. #else
  966. # define GCC_VERSION 0
  967. #endif
  968. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  969. # define MSVC_VERSION _MSC_VER
  970. #else
  971. # define MSVC_VERSION 0
  972. #endif
  973. /* Needed for various definitions... */
  974. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  975. # define _GNU_SOURCE
  976. #endif
  977. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  978. # define _BSD_SOURCE
  979. #endif
  980. /*
  981. ** For MinGW, check to see if we can include the header file containing its
  982. ** version information, among other things. Normally, this internal MinGW
  983. ** header file would [only] be included automatically by other MinGW header
  984. ** files; however, the contained version information is now required by this
  985. ** header file to work around binary compatibility issues (see below) and
  986. ** this is the only known way to reliably obtain it. This entire #if block
  987. ** would be completely unnecessary if there was any other way of detecting
  988. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  989. ** some MinGW-specific macros). When compiling for MinGW, either the
  990. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  991. ** defined; otherwise, detection of conditions specific to MinGW will be
  992. ** disabled.
  993. */
  994. #if defined(_HAVE_MINGW_H)
  995. # include "mingw.h"
  996. #elif defined(_HAVE__MINGW_H)
  997. # include "_mingw.h"
  998. #endif
  999. /*
  1000. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  1001. ** define is required to maintain binary compatibility with the MSVC runtime
  1002. ** library in use (e.g. for Windows XP).
  1003. */
  1004. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  1005. defined(_WIN32) && !defined(_WIN64) && \
  1006. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  1007. defined(__MSVCRT__)
  1008. # define _USE_32BIT_TIME_T
  1009. #endif
  1010. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  1011. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  1012. ** MinGW.
  1013. */
  1014. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  1015. /************** Begin file sqlite3.h *****************************************/
  1016. /*
  1017. ** 2001-09-15
  1018. **
  1019. ** The author disclaims copyright to this source code. In place of
  1020. ** a legal notice, here is a blessing:
  1021. **
  1022. ** May you do good and not evil.
  1023. ** May you find forgiveness for yourself and forgive others.
  1024. ** May you share freely, never taking more than you give.
  1025. **
  1026. *************************************************************************
  1027. ** This header file defines the interface that the SQLite library
  1028. ** presents to client programs. If a C-function, structure, datatype,
  1029. ** or constant definition does not appear in this file, then it is
  1030. ** not a published API of SQLite, is subject to change without
  1031. ** notice, and should not be referenced by programs that use SQLite.
  1032. **
  1033. ** Some of the definitions that are in this file are marked as
  1034. ** "experimental". Experimental interfaces are normally new
  1035. ** features recently added to SQLite. We do not anticipate changes
  1036. ** to experimental interfaces but reserve the right to make minor changes
  1037. ** if experience from use "in the wild" suggest such changes are prudent.
  1038. **
  1039. ** The official C-language API documentation for SQLite is derived
  1040. ** from comments in this file. This file is the authoritative source
  1041. ** on how SQLite interfaces are supposed to operate.
  1042. **
  1043. ** The name of this file under configuration management is "sqlite.h.in".
  1044. ** The makefile makes some minor changes to this file (such as inserting
  1045. ** the version number) and changes its name to "sqlite3.h" as
  1046. ** part of the build process.
  1047. */
  1048. #ifndef SQLITE3_H
  1049. #define SQLITE3_H
  1050. #include <stdarg.h> /* Needed for the definition of va_list */
  1051. /*
  1052. ** Make sure we can call this stuff from C++.
  1053. */
  1054. #if 0
  1055. extern "C" {
  1056. #endif
  1057. /*
  1058. ** Provide the ability to override linkage features of the interface.
  1059. */
  1060. #ifndef SQLITE_EXTERN
  1061. # define SQLITE_EXTERN extern
  1062. #endif
  1063. #ifndef SQLITE_API
  1064. # define SQLITE_API
  1065. #endif
  1066. #ifndef SQLITE_CDECL
  1067. # define SQLITE_CDECL
  1068. #endif
  1069. #ifndef SQLITE_APICALL
  1070. # define SQLITE_APICALL
  1071. #endif
  1072. #ifndef SQLITE_STDCALL
  1073. # define SQLITE_STDCALL SQLITE_APICALL
  1074. #endif
  1075. #ifndef SQLITE_CALLBACK
  1076. # define SQLITE_CALLBACK
  1077. #endif
  1078. #ifndef SQLITE_SYSAPI
  1079. # define SQLITE_SYSAPI
  1080. #endif
  1081. /*
  1082. ** These no-op macros are used in front of interfaces to mark those
  1083. ** interfaces as either deprecated or experimental. New applications
  1084. ** should not use deprecated interfaces - they are supported for backwards
  1085. ** compatibility only. Application writers should be aware that
  1086. ** experimental interfaces are subject to change in point releases.
  1087. **
  1088. ** These macros used to resolve to various kinds of compiler magic that
  1089. ** would generate warning messages when they were used. But that
  1090. ** compiler magic ended up generating such a flurry of bug reports
  1091. ** that we have taken it all out and gone back to using simple
  1092. ** noop macros.
  1093. */
  1094. #define SQLITE_DEPRECATED
  1095. #define SQLITE_EXPERIMENTAL
  1096. /*
  1097. ** Ensure these symbols were not defined by some previous header file.
  1098. */
  1099. #ifdef SQLITE_VERSION
  1100. # undef SQLITE_VERSION
  1101. #endif
  1102. #ifdef SQLITE_VERSION_NUMBER
  1103. # undef SQLITE_VERSION_NUMBER
  1104. #endif
  1105. /*
  1106. ** CAPI3REF: Compile-Time Library Version Numbers
  1107. **
  1108. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  1109. ** evaluates to a string literal that is the SQLite version in the
  1110. ** format "X.Y.Z" where X is the major version number (always 3 for
  1111. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  1112. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  1113. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  1114. ** numbers used in [SQLITE_VERSION].)^
  1115. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  1116. ** be larger than the release from which it is derived. Either Y will
  1117. ** be held constant and Z will be incremented or else Y will be incremented
  1118. ** and Z will be reset to zero.
  1119. **
  1120. ** Since [version 3.6.18] ([dateof:3.6.18]),
  1121. ** SQLite source code has been stored in the
  1122. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  1123. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  1124. ** a string which identifies a particular check-in of SQLite
  1125. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  1126. ** string contains the date and time of the check-in (UTC) and a SHA1
  1127. ** or SHA3-256 hash of the entire source tree. If the source code has
  1128. ** been edited in any way since it was last checked in, then the last
  1129. ** four hexadecimal digits of the hash may be modified.
  1130. **
  1131. ** See also: [sqlite3_libversion()],
  1132. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  1133. ** [sqlite_version()] and [sqlite_source_id()].
  1134. */
  1135. #define SQLITE_VERSION "3.28.0"
  1136. #define SQLITE_VERSION_NUMBER 3028000
  1137. #define SQLITE_SOURCE_ID "2019-04-16 19:49:53 884b4b7e502b4e991677b53971277adfaf0a04a284f8e483e2553d0f83156b50"
  1138. /*
  1139. ** CAPI3REF: Run-Time Library Version Numbers
  1140. ** KEYWORDS: sqlite3_version sqlite3_sourceid
  1141. **
  1142. ** These interfaces provide the same information as the [SQLITE_VERSION],
  1143. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  1144. ** but are associated with the library instead of the header file. ^(Cautious
  1145. ** programmers might include assert() statements in their application to
  1146. ** verify that values returned by these interfaces match the macros in
  1147. ** the header, and thus ensure that the application is
  1148. ** compiled with matching library and header files.
  1149. **
  1150. ** <blockquote><pre>
  1151. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  1152. ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
  1153. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  1154. ** </pre></blockquote>)^
  1155. **
  1156. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  1157. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  1158. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  1159. ** function is provided for use in DLLs since DLL users usually do not have
  1160. ** direct access to string constants within the DLL. ^The
  1161. ** sqlite3_libversion_number() function returns an integer equal to
  1162. ** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
  1163. ** a pointer to a string constant whose value is the same as the
  1164. ** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
  1165. ** using an edited copy of [the amalgamation], then the last four characters
  1166. ** of the hash might be different from [SQLITE_SOURCE_ID].)^
  1167. **
  1168. ** See also: [sqlite_version()] and [sqlite_source_id()].
  1169. */
  1170. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  1171. SQLITE_API const char *sqlite3_libversion(void);
  1172. SQLITE_API const char *sqlite3_sourceid(void);
  1173. SQLITE_API int sqlite3_libversion_number(void);
  1174. /*
  1175. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  1176. **
  1177. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  1178. ** indicating whether the specified option was defined at
  1179. ** compile time. ^The SQLITE_ prefix may be omitted from the
  1180. ** option name passed to sqlite3_compileoption_used().
  1181. **
  1182. ** ^The sqlite3_compileoption_get() function allows iterating
  1183. ** over the list of options that were defined at compile time by
  1184. ** returning the N-th compile time option string. ^If N is out of range,
  1185. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  1186. ** prefix is omitted from any strings returned by
  1187. ** sqlite3_compileoption_get().
  1188. **
  1189. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  1190. ** and sqlite3_compileoption_get() may be omitted by specifying the
  1191. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  1192. **
  1193. ** See also: SQL functions [sqlite_compileoption_used()] and
  1194. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  1195. */
  1196. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  1197. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  1198. SQLITE_API const char *sqlite3_compileoption_get(int N);
  1199. #else
  1200. # define sqlite3_compileoption_used(X) 0
  1201. # define sqlite3_compileoption_get(X) ((void*)0)
  1202. #endif
  1203. /*
  1204. ** CAPI3REF: Test To See If The Library Is Threadsafe
  1205. **
  1206. ** ^The sqlite3_threadsafe() function returns zero if and only if
  1207. ** SQLite was compiled with mutexing code omitted due to the
  1208. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  1209. **
  1210. ** SQLite can be compiled with or without mutexes. When
  1211. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  1212. ** are enabled and SQLite is threadsafe. When the
  1213. ** [SQLITE_THREADSAFE] macro is 0,
  1214. ** the mutexes are omitted. Without the mutexes, it is not safe
  1215. ** to use SQLite concurrently from more than one thread.
  1216. **
  1217. ** Enabling mutexes incurs a measurable performance penalty.
  1218. ** So if speed is of utmost importance, it makes sense to disable
  1219. ** the mutexes. But for maximum safety, mutexes should be enabled.
  1220. ** ^The default behavior is for mutexes to be enabled.
  1221. **
  1222. ** This interface can be used by an application to make sure that the
  1223. ** version of SQLite that it is linking against was compiled with
  1224. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  1225. **
  1226. ** This interface only reports on the compile-time mutex setting
  1227. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  1228. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  1229. ** can be fully or partially disabled using a call to [sqlite3_config()]
  1230. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  1231. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  1232. ** sqlite3_threadsafe() function shows only the compile-time setting of
  1233. ** thread safety, not any run-time changes to that setting made by
  1234. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  1235. ** is unchanged by calls to sqlite3_config().)^
  1236. **
  1237. ** See the [threading mode] documentation for additional information.
  1238. */
  1239. SQLITE_API int sqlite3_threadsafe(void);
  1240. /*
  1241. ** CAPI3REF: Database Connection Handle
  1242. ** KEYWORDS: {database connection} {database connections}
  1243. **
  1244. ** Each open SQLite database is represented by a pointer to an instance of
  1245. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  1246. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  1247. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  1248. ** and [sqlite3_close_v2()] are its destructors. There are many other
  1249. ** interfaces (such as
  1250. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  1251. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  1252. ** sqlite3 object.
  1253. */
  1254. typedef struct sqlite3 sqlite3;
  1255. /*
  1256. ** CAPI3REF: 64-Bit Integer Types
  1257. ** KEYWORDS: sqlite_int64 sqlite_uint64
  1258. **
  1259. ** Because there is no cross-platform way to specify 64-bit integer types
  1260. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  1261. **
  1262. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  1263. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  1264. ** compatibility only.
  1265. **
  1266. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  1267. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  1268. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  1269. ** between 0 and +18446744073709551615 inclusive.
  1270. */
  1271. #ifdef SQLITE_INT64_TYPE
  1272. typedef SQLITE_INT64_TYPE sqlite_int64;
  1273. # ifdef SQLITE_UINT64_TYPE
  1274. typedef SQLITE_UINT64_TYPE sqlite_uint64;
  1275. # else
  1276. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  1277. # endif
  1278. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  1279. typedef __int64 sqlite_int64;
  1280. typedef unsigned __int64 sqlite_uint64;
  1281. #else
  1282. typedef long long int sqlite_int64;
  1283. typedef unsigned long long int sqlite_uint64;
  1284. #endif
  1285. typedef sqlite_int64 sqlite3_int64;
  1286. typedef sqlite_uint64 sqlite3_uint64;
  1287. /*
  1288. ** If compiling for a processor that lacks floating point support,
  1289. ** substitute integer for floating-point.
  1290. */
  1291. #ifdef SQLITE_OMIT_FLOATING_POINT
  1292. # define double sqlite3_int64
  1293. #endif
  1294. /*
  1295. ** CAPI3REF: Closing A Database Connection
  1296. ** DESTRUCTOR: sqlite3
  1297. **
  1298. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  1299. ** for the [sqlite3] object.
  1300. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  1301. ** the [sqlite3] object is successfully destroyed and all associated
  1302. ** resources are deallocated.
  1303. **
  1304. ** ^If the database connection is associated with unfinalized prepared
  1305. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  1306. ** will leave the database connection open and return [SQLITE_BUSY].
  1307. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  1308. ** and/or unfinished sqlite3_backups, then the database connection becomes
  1309. ** an unusable "zombie" which will automatically be deallocated when the
  1310. ** last prepared statement is finalized or the last sqlite3_backup is
  1311. ** finished. The sqlite3_close_v2() interface is intended for use with
  1312. ** host languages that are garbage collected, and where the order in which
  1313. ** destructors are called is arbitrary.
  1314. **
  1315. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  1316. ** [sqlite3_blob_close | close] all [BLOB handles], and
  1317. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  1318. ** with the [sqlite3] object prior to attempting to close the object. ^If
  1319. ** sqlite3_close_v2() is called on a [database connection] that still has
  1320. ** outstanding [prepared statements], [BLOB handles], and/or
  1321. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  1322. ** of resources is deferred until all [prepared statements], [BLOB handles],
  1323. ** and [sqlite3_backup] objects are also destroyed.
  1324. **
  1325. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  1326. ** the transaction is automatically rolled back.
  1327. **
  1328. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  1329. ** must be either a NULL
  1330. ** pointer or an [sqlite3] object pointer obtained
  1331. ** from [sqlite3_open()], [sqlite3_open16()], or
  1332. ** [sqlite3_open_v2()], and not previously closed.
  1333. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  1334. ** argument is a harmless no-op.
  1335. */
  1336. SQLITE_API int sqlite3_close(sqlite3*);
  1337. SQLITE_API int sqlite3_close_v2(sqlite3*);
  1338. /*
  1339. ** The type for a callback function.
  1340. ** This is legacy and deprecated. It is included for historical
  1341. ** compatibility and is not documented.
  1342. */
  1343. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  1344. /*
  1345. ** CAPI3REF: One-Step Query Execution Interface
  1346. ** METHOD: sqlite3
  1347. **
  1348. ** The sqlite3_exec() interface is a convenience wrapper around
  1349. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  1350. ** that allows an application to run multiple statements of SQL
  1351. ** without having to use a lot of C code.
  1352. **
  1353. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  1354. ** semicolon-separate SQL statements passed into its 2nd argument,
  1355. ** in the context of the [database connection] passed in as its 1st
  1356. ** argument. ^If the callback function of the 3rd argument to
  1357. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  1358. ** coming out of the evaluated SQL statements. ^The 4th argument to
  1359. ** sqlite3_exec() is relayed through to the 1st argument of each
  1360. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  1361. ** is NULL, then no callback is ever invoked and result rows are
  1362. ** ignored.
  1363. **
  1364. ** ^If an error occurs while evaluating the SQL statements passed into
  1365. ** sqlite3_exec(), then execution of the current statement stops and
  1366. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  1367. ** is not NULL then any error message is written into memory obtained
  1368. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  1369. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  1370. ** on error message strings returned through the 5th parameter of
  1371. ** sqlite3_exec() after the error message string is no longer needed.
  1372. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  1373. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  1374. ** NULL before returning.
  1375. **
  1376. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  1377. ** routine returns SQLITE_ABORT without invoking the callback again and
  1378. ** without running any subsequent SQL statements.
  1379. **
  1380. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  1381. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  1382. ** callback is an array of pointers to strings obtained as if from
  1383. ** [sqlite3_column_text()], one for each column. ^If an element of a
  1384. ** result row is NULL then the corresponding string pointer for the
  1385. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  1386. ** sqlite3_exec() callback is an array of pointers to strings where each
  1387. ** entry represents the name of corresponding result column as obtained
  1388. ** from [sqlite3_column_name()].
  1389. **
  1390. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  1391. ** to an empty string, or a pointer that contains only whitespace and/or
  1392. ** SQL comments, then no SQL statements are evaluated and the database
  1393. ** is not changed.
  1394. **
  1395. ** Restrictions:
  1396. **
  1397. ** <ul>
  1398. ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  1399. ** is a valid and open [database connection].
  1400. ** <li> The application must not close the [database connection] specified by
  1401. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  1402. ** <li> The application must not modify the SQL statement text passed into
  1403. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  1404. ** </ul>
  1405. */
  1406. SQLITE_API int sqlite3_exec(
  1407. sqlite3*, /* An open database */
  1408. const char *sql, /* SQL to be evaluated */
  1409. int (*callback)(void*,int,char**,char**), /* Callback function */
  1410. void *, /* 1st argument to callback */
  1411. char **errmsg /* Error msg written here */
  1412. );
  1413. /*
  1414. ** CAPI3REF: Result Codes
  1415. ** KEYWORDS: {result code definitions}
  1416. **
  1417. ** Many SQLite functions return an integer result code from the set shown
  1418. ** here in order to indicate success or failure.
  1419. **
  1420. ** New error codes may be added in future versions of SQLite.
  1421. **
  1422. ** See also: [extended result code definitions]
  1423. */
  1424. #define SQLITE_OK 0 /* Successful result */
  1425. /* beginning-of-error-codes */
  1426. #define SQLITE_ERROR 1 /* Generic error */
  1427. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  1428. #define SQLITE_PERM 3 /* Access permission denied */
  1429. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  1430. #define SQLITE_BUSY 5 /* The database file is locked */
  1431. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  1432. #define SQLITE_NOMEM 7 /* A malloc() failed */
  1433. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  1434. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  1435. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  1436. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  1437. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  1438. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  1439. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  1440. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  1441. #define SQLITE_EMPTY 16 /* Internal use only */
  1442. #define SQLITE_SCHEMA 17 /* The database schema changed */
  1443. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  1444. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  1445. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  1446. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  1447. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  1448. #define SQLITE_AUTH 23 /* Authorization denied */
  1449. #define SQLITE_FORMAT 24 /* Not used */
  1450. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  1451. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  1452. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  1453. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  1454. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  1455. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  1456. /* end-of-error-codes */
  1457. /*
  1458. ** CAPI3REF: Extended Result Codes
  1459. ** KEYWORDS: {extended result code definitions}
  1460. **
  1461. ** In its default configuration, SQLite API routines return one of 30 integer
  1462. ** [result codes]. However, experience has shown that many of
  1463. ** these result codes are too coarse-grained. They do not provide as
  1464. ** much information about problems as programmers might like. In an effort to
  1465. ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
  1466. ** and later) include
  1467. ** support for additional result codes that provide more detailed information
  1468. ** about errors. These [extended result codes] are enabled or disabled
  1469. ** on a per database connection basis using the
  1470. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  1471. ** the most recent error can be obtained using
  1472. ** [sqlite3_extended_errcode()].
  1473. */
  1474. #define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
  1475. #define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
  1476. #define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))
  1477. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  1478. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  1479. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  1480. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  1481. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  1482. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  1483. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  1484. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  1485. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  1486. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  1487. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  1488. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  1489. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  1490. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  1491. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  1492. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  1493. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  1494. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  1495. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  1496. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  1497. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  1498. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  1499. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  1500. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  1501. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  1502. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  1503. #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
  1504. #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
  1505. #define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
  1506. #define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
  1507. #define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
  1508. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  1509. #define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))
  1510. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  1511. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  1512. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  1513. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  1514. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  1515. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  1516. #define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
  1517. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  1518. #define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8))
  1519. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  1520. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  1521. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  1522. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  1523. #define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
  1524. #define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
  1525. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  1526. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  1527. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  1528. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  1529. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  1530. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  1531. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  1532. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  1533. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  1534. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  1535. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<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. /*
  1542. ** CAPI3REF: Flags For File Open Operations
  1543. **
  1544. ** These bit values are intended for use in the
  1545. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  1546. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  1547. */
  1548. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  1549. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  1550. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  1551. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  1552. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  1553. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  1554. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  1555. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  1556. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  1557. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  1558. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  1559. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  1560. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  1561. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  1562. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  1563. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  1564. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  1565. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  1566. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  1567. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  1568. /* Reserved: 0x00F00000 */
  1569. /*
  1570. ** CAPI3REF: Device Characteristics
  1571. **
  1572. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  1573. ** object returns an integer which is a vector of these
  1574. ** bit values expressing I/O characteristics of the mass storage
  1575. ** device that holds the file that the [sqlite3_io_methods]
  1576. ** refers to.
  1577. **
  1578. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1579. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1580. ** mean that writes of blocks that are nnn bytes in size and
  1581. ** are aligned to an address which is an integer multiple of
  1582. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1583. ** that when data is appended to a file, the data is appended
  1584. ** first then the size of the file is extended, never the other
  1585. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1586. ** information is written to disk in the same order as calls
  1587. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  1588. ** after reboot following a crash or power loss, the only bytes in a
  1589. ** file that were written at the application level might have changed
  1590. ** and that adjacent bytes, even bytes within the same sector are
  1591. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  1592. ** flag indicates that a file cannot be deleted when open. The
  1593. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  1594. ** read-only media and cannot be changed even by processes with
  1595. ** elevated privileges.
  1596. **
  1597. ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
  1598. ** filesystem supports doing multiple write operations atomically when those
  1599. ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
  1600. ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
  1601. */
  1602. #define SQLITE_IOCAP_ATOMIC 0x00000001
  1603. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  1604. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  1605. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  1606. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  1607. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  1608. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  1609. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  1610. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  1611. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  1612. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  1613. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  1614. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  1615. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  1616. #define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
  1617. /*
  1618. ** CAPI3REF: File Locking Levels
  1619. **
  1620. ** SQLite uses one of these integer values as the second
  1621. ** argument to calls it makes to the xLock() and xUnlock() methods
  1622. ** of an [sqlite3_io_methods] object.
  1623. */
  1624. #define SQLITE_LOCK_NONE 0
  1625. #define SQLITE_LOCK_SHARED 1
  1626. #define SQLITE_LOCK_RESERVED 2
  1627. #define SQLITE_LOCK_PENDING 3
  1628. #define SQLITE_LOCK_EXCLUSIVE 4
  1629. /*
  1630. ** CAPI3REF: Synchronization Type Flags
  1631. **
  1632. ** When SQLite invokes the xSync() method of an
  1633. ** [sqlite3_io_methods] object it uses a combination of
  1634. ** these integer values as the second argument.
  1635. **
  1636. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1637. ** sync operation only needs to flush data to mass storage. Inode
  1638. ** information need not be flushed. If the lower four bits of the flag
  1639. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1640. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1641. ** to use Mac OS X style fullsync instead of fsync().
  1642. **
  1643. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1644. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1645. ** settings. The [synchronous pragma] determines when calls to the
  1646. ** xSync VFS method occur and applies uniformly across all platforms.
  1647. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1648. ** energetic or rigorous or forceful the sync operations are and
  1649. ** only make a difference on Mac OSX for the default SQLite code.
  1650. ** (Third-party VFS implementations might also make the distinction
  1651. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1652. ** operating systems natively supported by SQLite, only Mac OSX
  1653. ** cares about the difference.)
  1654. */
  1655. #define SQLITE_SYNC_NORMAL 0x00002
  1656. #define SQLITE_SYNC_FULL 0x00003
  1657. #define SQLITE_SYNC_DATAONLY 0x00010
  1658. /*
  1659. ** CAPI3REF: OS Interface Open File Handle
  1660. **
  1661. ** An [sqlite3_file] object represents an open file in the
  1662. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  1663. ** implementations will
  1664. ** want to subclass this object by appending additional fields
  1665. ** for their own use. The pMethods entry is a pointer to an
  1666. ** [sqlite3_io_methods] object that defines methods for performing
  1667. ** I/O operations on the open file.
  1668. */
  1669. typedef struct sqlite3_file sqlite3_file;
  1670. struct sqlite3_file {
  1671. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1672. };
  1673. /*
  1674. ** CAPI3REF: OS Interface File Virtual Methods Object
  1675. **
  1676. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1677. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1678. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1679. ** This object defines the methods used to perform various operations
  1680. ** against the open file represented by the [sqlite3_file] object.
  1681. **
  1682. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  1683. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1684. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  1685. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1686. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1687. ** to NULL.
  1688. **
  1689. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1690. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1691. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1692. ** flag may be ORed in to indicate that only the data of the file
  1693. ** and not its inode needs to be synced.
  1694. **
  1695. ** The integer values to xLock() and xUnlock() are one of
  1696. ** <ul>
  1697. ** <li> [SQLITE_LOCK_NONE],
  1698. ** <li> [SQLITE_LOCK_SHARED],
  1699. ** <li> [SQLITE_LOCK_RESERVED],
  1700. ** <li> [SQLITE_LOCK_PENDING], or
  1701. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1702. ** </ul>
  1703. ** xLock() increases the lock. xUnlock() decreases the lock.
  1704. ** The xCheckReservedLock() method checks whether any database connection,
  1705. ** either in this process or in some other process, is holding a RESERVED,
  1706. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1707. ** if such a lock exists and false otherwise.
  1708. **
  1709. ** The xFileControl() method is a generic interface that allows custom
  1710. ** VFS implementations to directly control an open file using the
  1711. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1712. ** integer opcode. The third argument is a generic pointer intended to
  1713. ** point to a structure that may contain arguments or space in which to
  1714. ** write return values. Potential uses for xFileControl() might be
  1715. ** functions to enable blocking locks with timeouts, to change the
  1716. ** locking strategy (for example to use dot-file locks), to inquire
  1717. ** about the status of a lock, or to break stale locks. The SQLite
  1718. ** core reserves all opcodes less than 100 for its own use.
  1719. ** A [file control opcodes | list of opcodes] less than 100 is available.
  1720. ** Applications that define a custom xFileControl method should use opcodes
  1721. ** greater than 100 to avoid conflicts. VFS implementations should
  1722. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1723. ** recognize.
  1724. **
  1725. ** The xSectorSize() method returns the sector size of the
  1726. ** device that underlies the file. The sector size is the
  1727. ** minimum write that can be performed without disturbing
  1728. ** other bytes in the file. The xDeviceCharacteristics()
  1729. ** method returns a bit vector describing behaviors of the
  1730. ** underlying device:
  1731. **
  1732. ** <ul>
  1733. ** <li> [SQLITE_IOCAP_ATOMIC]
  1734. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1735. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1736. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1737. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1738. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1739. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1740. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1741. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1742. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1743. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1744. ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
  1745. ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
  1746. ** <li> [SQLITE_IOCAP_IMMUTABLE]
  1747. ** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
  1748. ** </ul>
  1749. **
  1750. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1751. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1752. ** mean that writes of blocks that are nnn bytes in size and
  1753. ** are aligned to an address which is an integer multiple of
  1754. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1755. ** that when data is appended to a file, the data is appended
  1756. ** first then the size of the file is extended, never the other
  1757. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1758. ** information is written to disk in the same order as calls
  1759. ** to xWrite().
  1760. **
  1761. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1762. ** in the unread portions of the buffer with zeros. A VFS that
  1763. ** fails to zero-fill short reads might seem to work. However,
  1764. ** failure to zero-fill short reads will eventually lead to
  1765. ** database corruption.
  1766. */
  1767. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1768. struct sqlite3_io_methods {
  1769. int iVersion;
  1770. int (*xClose)(sqlite3_file*);
  1771. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1772. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1773. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1774. int (*xSync)(sqlite3_file*, int flags);
  1775. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1776. int (*xLock)(sqlite3_file*, int);
  1777. int (*xUnlock)(sqlite3_file*, int);
  1778. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1779. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1780. int (*xSectorSize)(sqlite3_file*);
  1781. int (*xDeviceCharacteristics)(sqlite3_file*);
  1782. /* Methods above are valid for version 1 */
  1783. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1784. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1785. void (*xShmBarrier)(sqlite3_file*);
  1786. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1787. /* Methods above are valid for version 2 */
  1788. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1789. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1790. /* Methods above are valid for version 3 */
  1791. /* Additional methods may be added in future releases */
  1792. };
  1793. /*
  1794. ** CAPI3REF: Standard File Control Opcodes
  1795. ** KEYWORDS: {file control opcodes} {file control opcode}
  1796. **
  1797. ** These integer constants are opcodes for the xFileControl method
  1798. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1799. ** interface.
  1800. **
  1801. ** <ul>
  1802. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  1803. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1804. ** opcode causes the xFileControl method to write the current state of
  1805. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1806. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1807. ** into an integer that the pArg argument points to. This capability
  1808. ** is used during testing and is only available when the SQLITE_TEST
  1809. ** compile-time option is used.
  1810. **
  1811. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1812. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1813. ** layer a hint of how large the database file will grow to be during the
  1814. ** current transaction. This hint is not guaranteed to be accurate but it
  1815. ** is often close. The underlying VFS might choose to preallocate database
  1816. ** file space based on this hint in order to help writes to the database
  1817. ** file run faster.
  1818. **
  1819. ** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]
  1820. ** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
  1821. ** implements [sqlite3_deserialize()] to set an upper bound on the size
  1822. ** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
  1823. ** If the integer pointed to is negative, then it is filled in with the
  1824. ** current limit. Otherwise the limit is set to the larger of the value
  1825. ** of the integer pointed to and the current database size. The integer
  1826. ** pointed to is set to the new limit.
  1827. **
  1828. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1829. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1830. ** extends and truncates the database file in chunks of a size specified
  1831. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1832. ** point to an integer (type int) containing the new chunk-size to use
  1833. ** for the nominated database. Allocating database file space in large
  1834. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1835. ** improve performance on some systems.
  1836. **
  1837. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1838. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1839. ** to the [sqlite3_file] object associated with a particular database
  1840. ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
  1841. **
  1842. ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  1843. ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  1844. ** to the [sqlite3_file] object associated with the journal file (either
  1845. ** the [rollback journal] or the [write-ahead log]) for a particular database
  1846. ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
  1847. **
  1848. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1849. ** No longer in use.
  1850. **
  1851. ** <li>[[SQLITE_FCNTL_SYNC]]
  1852. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  1853. ** sent to the VFS immediately before the xSync method is invoked on a
  1854. ** database file descriptor. Or, if the xSync method is not invoked
  1855. ** because the user has configured SQLite with
  1856. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  1857. ** of the xSync method. In most cases, the pointer argument passed with
  1858. ** this file-control is NULL. However, if the database file is being synced
  1859. ** as part of a multi-database commit, the argument points to a nul-terminated
  1860. ** string containing the transactions master-journal file name. VFSes that
  1861. ** do not need this signal should silently ignore this opcode. Applications
  1862. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  1863. ** disrupt the operation of the specialized VFSes that do require it.
  1864. **
  1865. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1866. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1867. ** and sent to the VFS after a transaction has been committed immediately
  1868. ** but before the database is unlocked. VFSes that do not need this signal
  1869. ** should silently ignore this opcode. Applications should not call
  1870. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  1871. ** operation of the specialized VFSes that do require it.
  1872. **
  1873. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1874. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1875. ** retry counts and intervals for certain disk I/O operations for the
  1876. ** windows [VFS] in order to provide robustness in the presence of
  1877. ** anti-virus programs. By default, the windows VFS will retry file read,
  1878. ** file write, and file delete operations up to 10 times, with a delay
  1879. ** of 25 milliseconds before the first retry and with the delay increasing
  1880. ** by an additional 25 milliseconds with each subsequent retry. This
  1881. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1882. ** to be adjusted. The values are changed for all database connections
  1883. ** within the same process. The argument is a pointer to an array of two
  1884. ** integers where the first integer is the new retry count and the second
  1885. ** integer is the delay. If either integer is negative, then the setting
  1886. ** is not changed but instead the prior value of that setting is written
  1887. ** into the array entry, allowing the current retry settings to be
  1888. ** interrogated. The zDbName parameter is ignored.
  1889. **
  1890. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1891. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1892. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1893. ** write ahead log ([WAL file]) and shared memory
  1894. ** files used for transaction control
  1895. ** are automatically deleted when the latest connection to the database
  1896. ** closes. Setting persistent WAL mode causes those files to persist after
  1897. ** close. Persisting the files is useful when other processes that do not
  1898. ** have write permission on the directory containing the database file want
  1899. ** to read the database file, as the WAL and shared memory files must exist
  1900. ** in order for the database to be readable. The fourth parameter to
  1901. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1902. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1903. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1904. ** WAL persistence setting.
  1905. **
  1906. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1907. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1908. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1909. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1910. ** xDeviceCharacteristics methods. The fourth parameter to
  1911. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1912. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1913. ** mode. If the integer is -1, then it is overwritten with the current
  1914. ** zero-damage mode setting.
  1915. **
  1916. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1917. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1918. ** a write transaction to indicate that, unless it is rolled back for some
  1919. ** reason, the entire database file will be overwritten by the current
  1920. ** transaction. This is used by VACUUM operations.
  1921. **
  1922. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1923. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1924. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1925. ** final bottom-level VFS are written into memory obtained from
  1926. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1927. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1928. ** The caller is responsible for freeing the memory when done. As with
  1929. ** all file-control actions, there is no guarantee that this will actually
  1930. ** do anything. Callers should initialize the char* variable to a NULL
  1931. ** pointer in case this file-control is not implemented. This file-control
  1932. ** is intended for diagnostic use only.
  1933. **
  1934. ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1935. ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1936. ** [VFSes] currently in use. ^(The argument X in
  1937. ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1938. ** of type "[sqlite3_vfs] **". This opcodes will set *X
  1939. ** to a pointer to the top-level VFS.)^
  1940. ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1941. ** upper-most shim only.
  1942. **
  1943. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1944. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1945. ** file control is sent to the open [sqlite3_file] object corresponding
  1946. ** to the database file to which the pragma statement refers. ^The argument
  1947. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1948. ** pointers to strings (char**) in which the second element of the array
  1949. ** is the name of the pragma and the third element is the argument to the
  1950. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1951. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1952. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1953. ** or the equivalent and that string will become the result of the pragma or
  1954. ** the error message if the pragma fails. ^If the
  1955. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1956. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1957. ** file control returns [SQLITE_OK], then the parser assumes that the
  1958. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1959. ** prepared statement if result string is NULL, or that returns a copy
  1960. ** of the result string if the string is non-NULL.
  1961. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1962. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1963. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1964. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1965. ** file control occurs at the beginning of pragma statement analysis and so
  1966. ** it is able to override built-in [PRAGMA] statements.
  1967. **
  1968. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1969. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1970. ** file-control may be invoked by SQLite on the database file handle
  1971. ** shortly after it is opened in order to provide a custom VFS with access
  1972. ** to the connections busy-handler callback. The argument is of type (void **)
  1973. ** - an array of two (void *) values. The first (void *) actually points
  1974. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1975. ** busy-handler, this function should be invoked with the second (void *) in
  1976. ** the array as the only argument. If it returns non-zero, then the operation
  1977. ** should be retried. If it returns zero, the custom VFS should abandon the
  1978. ** current operation.
  1979. **
  1980. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1981. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1982. ** to have SQLite generate a
  1983. ** temporary filename using the same algorithm that is followed to generate
  1984. ** temporary filenames for TEMP tables and other internal uses. The
  1985. ** argument should be a char** which will be filled with the filename
  1986. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1987. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1988. **
  1989. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1990. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1991. ** maximum number of bytes that will be used for memory-mapped I/O.
  1992. ** The argument is a pointer to a value of type sqlite3_int64 that
  1993. ** is an advisory maximum number of bytes in the file to memory map. The
  1994. ** pointer is overwritten with the old value. The limit is not changed if
  1995. ** the value originally pointed to is negative, and so the current limit
  1996. ** can be queried by passing in a pointer to a negative number. This
  1997. ** file-control is used internally to implement [PRAGMA mmap_size].
  1998. **
  1999. ** <li>[[SQLITE_FCNTL_TRACE]]
  2000. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  2001. ** to the VFS about what the higher layers of the SQLite stack are doing.
  2002. ** This file control is used by some VFS activity tracing [shims].
  2003. ** The argument is a zero-terminated string. Higher layers in the
  2004. ** SQLite stack may generate instances of this file control if
  2005. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  2006. **
  2007. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  2008. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  2009. ** pointer to an integer and it writes a boolean into that integer depending
  2010. ** on whether or not the file has been renamed, moved, or deleted since it
  2011. ** was first opened.
  2012. **
  2013. ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
  2014. ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
  2015. ** underlying native file handle associated with a file handle. This file
  2016. ** control interprets its argument as a pointer to a native file handle and
  2017. ** writes the resulting value there.
  2018. **
  2019. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  2020. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  2021. ** opcode causes the xFileControl method to swap the file handle with the one
  2022. ** pointed to by the pArg argument. This capability is used during testing
  2023. ** and only needs to be supported when SQLITE_TEST is defined.
  2024. **
  2025. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  2026. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  2027. ** be advantageous to block on the next WAL lock if the lock is not immediately
  2028. ** available. The WAL subsystem issues this signal during rare
  2029. ** circumstances in order to fix a problem with priority inversion.
  2030. ** Applications should <em>not</em> use this file-control.
  2031. **
  2032. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  2033. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  2034. ** VFS should return SQLITE_NOTFOUND for this opcode.
  2035. **
  2036. ** <li>[[SQLITE_FCNTL_RBU]]
  2037. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  2038. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  2039. ** this opcode.
  2040. **
  2041. ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
  2042. ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
  2043. ** the file descriptor is placed in "batch write mode", which
  2044. ** means all subsequent write operations will be deferred and done
  2045. ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
  2046. ** that do not support batch atomic writes will return SQLITE_NOTFOUND.
  2047. ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
  2048. ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
  2049. ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
  2050. ** no VFS interface calls on the same [sqlite3_file] file descriptor
  2051. ** except for calls to the xWrite method and the xFileControl method
  2052. ** with [SQLITE_FCNTL_SIZE_HINT].
  2053. **
  2054. ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
  2055. ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
  2056. ** operations since the previous successful call to
  2057. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
  2058. ** This file control returns [SQLITE_OK] if and only if the writes were
  2059. ** all performed successfully and have been committed to persistent storage.
  2060. ** ^Regardless of whether or not it is successful, this file control takes
  2061. ** the file descriptor out of batch write mode so that all subsequent
  2062. ** write operations are independent.
  2063. ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
  2064. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2065. **
  2066. ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
  2067. ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
  2068. ** operations since the previous successful call to
  2069. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
  2070. ** ^This file control takes the file descriptor out of batch write mode
  2071. ** so that all subsequent write operations are independent.
  2072. ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
  2073. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2074. **
  2075. ** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
  2076. ** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode causes attempts to obtain
  2077. ** a file lock using the xLock or xShmLock methods of the VFS to wait
  2078. ** for up to M milliseconds before failing, where M is the single
  2079. ** unsigned integer parameter.
  2080. **
  2081. ** <li>[[SQLITE_FCNTL_DATA_VERSION]]
  2082. ** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
  2083. ** a database file. The argument is a pointer to a 32-bit unsigned integer.
  2084. ** The "data version" for the pager is written into the pointer. The
  2085. ** "data version" changes whenever any change occurs to the corresponding
  2086. ** database file, either through SQL statements on the same database
  2087. ** connection or through transactions committed by separate database
  2088. ** connections possibly in other processes. The [sqlite3_total_changes()]
  2089. ** interface can be used to find if any database on the connection has changed,
  2090. ** but that interface responds to changes on TEMP as well as MAIN and does
  2091. ** not provide a mechanism to detect changes to MAIN only. Also, the
  2092. ** [sqlite3_total_changes()] interface responds to internal changes only and
  2093. ** omits changes made by other database connections. The
  2094. ** [PRAGMA data_version] command provide a mechanism to detect changes to
  2095. ** a single attached database that occur due to other database connections,
  2096. ** but omits changes implemented by the database connection on which it is
  2097. ** called. This file control is the only mechanism to detect changes that
  2098. ** happen either internally or externally and that are associated with
  2099. ** a particular attached database.
  2100. ** </ul>
  2101. */
  2102. #define SQLITE_FCNTL_LOCKSTATE 1
  2103. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  2104. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  2105. #define SQLITE_FCNTL_LAST_ERRNO 4
  2106. #define SQLITE_FCNTL_SIZE_HINT 5
  2107. #define SQLITE_FCNTL_CHUNK_SIZE 6
  2108. #define SQLITE_FCNTL_FILE_POINTER 7
  2109. #define SQLITE_FCNTL_SYNC_OMITTED 8
  2110. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  2111. #define SQLITE_FCNTL_PERSIST_WAL 10
  2112. #define SQLITE_FCNTL_OVERWRITE 11
  2113. #define SQLITE_FCNTL_VFSNAME 12
  2114. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  2115. #define SQLITE_FCNTL_PRAGMA 14
  2116. #define SQLITE_FCNTL_BUSYHANDLER 15
  2117. #define SQLITE_FCNTL_TEMPFILENAME 16
  2118. #define SQLITE_FCNTL_MMAP_SIZE 18
  2119. #define SQLITE_FCNTL_TRACE 19
  2120. #define SQLITE_FCNTL_HAS_MOVED 20
  2121. #define SQLITE_FCNTL_SYNC 21
  2122. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  2123. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  2124. #define SQLITE_FCNTL_WAL_BLOCK 24
  2125. #define SQLITE_FCNTL_ZIPVFS 25
  2126. #define SQLITE_FCNTL_RBU 26
  2127. #define SQLITE_FCNTL_VFS_POINTER 27
  2128. #define SQLITE_FCNTL_JOURNAL_POINTER 28
  2129. #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
  2130. #define SQLITE_FCNTL_PDB 30
  2131. #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
  2132. #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
  2133. #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
  2134. #define SQLITE_FCNTL_LOCK_TIMEOUT 34
  2135. #define SQLITE_FCNTL_DATA_VERSION 35
  2136. #define SQLITE_FCNTL_SIZE_LIMIT 36
  2137. /* deprecated names */
  2138. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  2139. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  2140. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  2141. /*
  2142. ** CAPI3REF: Mutex Handle
  2143. **
  2144. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  2145. ** abstract type for a mutex object. The SQLite core never looks
  2146. ** at the internal representation of an [sqlite3_mutex]. It only
  2147. ** deals with pointers to the [sqlite3_mutex] object.
  2148. **
  2149. ** Mutexes are created using [sqlite3_mutex_alloc()].
  2150. */
  2151. typedef struct sqlite3_mutex sqlite3_mutex;
  2152. /*
  2153. ** CAPI3REF: Loadable Extension Thunk
  2154. **
  2155. ** A pointer to the opaque sqlite3_api_routines structure is passed as
  2156. ** the third parameter to entry points of [loadable extensions]. This
  2157. ** structure must be typedefed in order to work around compiler warnings
  2158. ** on some platforms.
  2159. */
  2160. typedef struct sqlite3_api_routines sqlite3_api_routines;
  2161. /*
  2162. ** CAPI3REF: OS Interface Object
  2163. **
  2164. ** An instance of the sqlite3_vfs object defines the interface between
  2165. ** the SQLite core and the underlying operating system. The "vfs"
  2166. ** in the name of the object stands for "virtual file system". See
  2167. ** the [VFS | VFS documentation] for further information.
  2168. **
  2169. ** The VFS interface is sometimes extended by adding new methods onto
  2170. ** the end. Each time such an extension occurs, the iVersion field
  2171. ** is incremented. The iVersion value started out as 1 in
  2172. ** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
  2173. ** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
  2174. ** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields
  2175. ** may be appended to the sqlite3_vfs object and the iVersion value
  2176. ** may increase again in future versions of SQLite.
  2177. ** Note that the structure
  2178. ** of the sqlite3_vfs object changes in the transition from
  2179. ** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
  2180. ** and yet the iVersion field was not modified.
  2181. **
  2182. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  2183. ** structure used by this VFS. mxPathname is the maximum length of
  2184. ** a pathname in this VFS.
  2185. **
  2186. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  2187. ** the pNext pointer. The [sqlite3_vfs_register()]
  2188. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  2189. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  2190. ** searches the list. Neither the application code nor the VFS
  2191. ** implementation should use the pNext pointer.
  2192. **
  2193. ** The pNext field is the only field in the sqlite3_vfs
  2194. ** structure that SQLite will ever modify. SQLite will only access
  2195. ** or modify this field while holding a particular static mutex.
  2196. ** The application should never modify anything within the sqlite3_vfs
  2197. ** object once the object has been registered.
  2198. **
  2199. ** The zName field holds the name of the VFS module. The name must
  2200. ** be unique across all VFS modules.
  2201. **
  2202. ** [[sqlite3_vfs.xOpen]]
  2203. ** ^SQLite guarantees that the zFilename parameter to xOpen
  2204. ** is either a NULL pointer or string obtained
  2205. ** from xFullPathname() with an optional suffix added.
  2206. ** ^If a suffix is added to the zFilename parameter, it will
  2207. ** consist of a single "-" character followed by no more than
  2208. ** 11 alphanumeric and/or "-" characters.
  2209. ** ^SQLite further guarantees that
  2210. ** the string will be valid and unchanged until xClose() is
  2211. ** called. Because of the previous sentence,
  2212. ** the [sqlite3_file] can safely store a pointer to the
  2213. ** filename if it needs to remember the filename for some reason.
  2214. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  2215. ** must invent its own temporary name for the file. ^Whenever the
  2216. ** xFilename parameter is NULL it will also be the case that the
  2217. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  2218. **
  2219. ** The flags argument to xOpen() includes all bits set in
  2220. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  2221. ** or [sqlite3_open16()] is used, then flags includes at least
  2222. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  2223. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  2224. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  2225. **
  2226. ** ^(SQLite will also add one of the following flags to the xOpen()
  2227. ** call, depending on the object being opened:
  2228. **
  2229. ** <ul>
  2230. ** <li> [SQLITE_OPEN_MAIN_DB]
  2231. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  2232. ** <li> [SQLITE_OPEN_TEMP_DB]
  2233. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  2234. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  2235. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  2236. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  2237. ** <li> [SQLITE_OPEN_WAL]
  2238. ** </ul>)^
  2239. **
  2240. ** The file I/O implementation can use the object type flags to
  2241. ** change the way it deals with files. For example, an application
  2242. ** that does not care about crash recovery or rollback might make
  2243. ** the open of a journal file a no-op. Writes to this journal would
  2244. ** also be no-ops, and any attempt to read the journal would return
  2245. ** SQLITE_IOERR. Or the implementation might recognize that a database
  2246. ** file will be doing page-aligned sector reads and writes in a random
  2247. ** order and set up its I/O subsystem accordingly.
  2248. **
  2249. ** SQLite might also add one of the following flags to the xOpen method:
  2250. **
  2251. ** <ul>
  2252. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  2253. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  2254. ** </ul>
  2255. **
  2256. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  2257. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  2258. ** will be set for TEMP databases and their journals, transient
  2259. ** databases, and subjournals.
  2260. **
  2261. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  2262. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  2263. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  2264. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  2265. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  2266. ** be created, and that it is an error if it already exists.
  2267. ** It is <i>not</i> used to indicate the file should be opened
  2268. ** for exclusive access.
  2269. **
  2270. ** ^At least szOsFile bytes of memory are allocated by SQLite
  2271. ** to hold the [sqlite3_file] structure passed as the third
  2272. ** argument to xOpen. The xOpen method does not have to
  2273. ** allocate the structure; it should just fill it in. Note that
  2274. ** the xOpen method must set the sqlite3_file.pMethods to either
  2275. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  2276. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  2277. ** element will be valid after xOpen returns regardless of the success
  2278. ** or failure of the xOpen call.
  2279. **
  2280. ** [[sqlite3_vfs.xAccess]]
  2281. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  2282. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  2283. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  2284. ** to test whether a file is at least readable. The file can be a
  2285. ** directory.
  2286. **
  2287. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  2288. ** output buffer xFullPathname. The exact size of the output buffer
  2289. ** is also passed as a parameter to both methods. If the output buffer
  2290. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  2291. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  2292. ** to prevent this by setting mxPathname to a sufficiently large value.
  2293. **
  2294. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  2295. ** interfaces are not strictly a part of the filesystem, but they are
  2296. ** included in the VFS structure for completeness.
  2297. ** The xRandomness() function attempts to return nBytes bytes
  2298. ** of good-quality randomness into zOut. The return value is
  2299. ** the actual number of bytes of randomness obtained.
  2300. ** The xSleep() method causes the calling thread to sleep for at
  2301. ** least the number of microseconds given. ^The xCurrentTime()
  2302. ** method returns a Julian Day Number for the current date and time as
  2303. ** a floating point value.
  2304. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  2305. ** Day Number multiplied by 86400000 (the number of milliseconds in
  2306. ** a 24-hour day).
  2307. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  2308. ** date and time if that method is available (if iVersion is 2 or
  2309. ** greater and the function pointer is not NULL) and will fall back
  2310. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  2311. **
  2312. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  2313. ** are not used by the SQLite core. These optional interfaces are provided
  2314. ** by some VFSes to facilitate testing of the VFS code. By overriding
  2315. ** system calls with functions under its control, a test program can
  2316. ** simulate faults and error conditions that would otherwise be difficult
  2317. ** or impossible to induce. The set of system calls that can be overridden
  2318. ** varies from one VFS to another, and from one version of the same VFS to the
  2319. ** next. Applications that use these interfaces must be prepared for any
  2320. ** or all of these interfaces to be NULL or for their behavior to change
  2321. ** from one release to the next. Applications must not attempt to access
  2322. ** any of these methods if the iVersion of the VFS is less than 3.
  2323. */
  2324. typedef struct sqlite3_vfs sqlite3_vfs;
  2325. typedef void (*sqlite3_syscall_ptr)(void);
  2326. struct sqlite3_vfs {
  2327. int iVersion; /* Structure version number (currently 3) */
  2328. int szOsFile; /* Size of subclassed sqlite3_file */
  2329. int mxPathname; /* Maximum file pathname length */
  2330. sqlite3_vfs *pNext; /* Next registered VFS */
  2331. const char *zName; /* Name of this virtual file system */
  2332. void *pAppData; /* Pointer to application-specific data */
  2333. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  2334. int flags, int *pOutFlags);
  2335. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  2336. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  2337. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  2338. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  2339. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  2340. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  2341. void (*xDlClose)(sqlite3_vfs*, void*);
  2342. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  2343. int (*xSleep)(sqlite3_vfs*, int microseconds);
  2344. int (*xCurrentTime)(sqlite3_vfs*, double*);
  2345. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  2346. /*
  2347. ** The methods above are in version 1 of the sqlite_vfs object
  2348. ** definition. Those that follow are added in version 2 or later
  2349. */
  2350. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  2351. /*
  2352. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  2353. ** Those below are for version 3 and greater.
  2354. */
  2355. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  2356. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  2357. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  2358. /*
  2359. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  2360. ** New fields may be appended in future versions. The iVersion
  2361. ** value will increment whenever this happens.
  2362. */
  2363. };
  2364. /*
  2365. ** CAPI3REF: Flags for the xAccess VFS method
  2366. **
  2367. ** These integer constants can be used as the third parameter to
  2368. ** the xAccess method of an [sqlite3_vfs] object. They determine
  2369. ** what kind of permissions the xAccess method is looking for.
  2370. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  2371. ** simply checks whether the file exists.
  2372. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  2373. ** checks whether the named directory is both readable and writable
  2374. ** (in other words, if files can be added, removed, and renamed within
  2375. ** the directory).
  2376. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  2377. ** [temp_store_directory pragma], though this could change in a future
  2378. ** release of SQLite.
  2379. ** With SQLITE_ACCESS_READ, the xAccess method
  2380. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  2381. ** currently unused, though it might be used in a future release of
  2382. ** SQLite.
  2383. */
  2384. #define SQLITE_ACCESS_EXISTS 0
  2385. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  2386. #define SQLITE_ACCESS_READ 2 /* Unused */
  2387. /*
  2388. ** CAPI3REF: Flags for the xShmLock VFS method
  2389. **
  2390. ** These integer constants define the various locking operations
  2391. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  2392. ** following are the only legal combinations of flags to the
  2393. ** xShmLock method:
  2394. **
  2395. ** <ul>
  2396. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  2397. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  2398. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  2399. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  2400. ** </ul>
  2401. **
  2402. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  2403. ** was given on the corresponding lock.
  2404. **
  2405. ** The xShmLock method can transition between unlocked and SHARED or
  2406. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  2407. ** and EXCLUSIVE.
  2408. */
  2409. #define SQLITE_SHM_UNLOCK 1
  2410. #define SQLITE_SHM_LOCK 2
  2411. #define SQLITE_SHM_SHARED 4
  2412. #define SQLITE_SHM_EXCLUSIVE 8
  2413. /*
  2414. ** CAPI3REF: Maximum xShmLock index
  2415. **
  2416. ** The xShmLock method on [sqlite3_io_methods] may use values
  2417. ** between 0 and this upper bound as its "offset" argument.
  2418. ** The SQLite core will never attempt to acquire or release a
  2419. ** lock outside of this range
  2420. */
  2421. #define SQLITE_SHM_NLOCK 8
  2422. /*
  2423. ** CAPI3REF: Initialize The SQLite Library
  2424. **
  2425. ** ^The sqlite3_initialize() routine initializes the
  2426. ** SQLite library. ^The sqlite3_shutdown() routine
  2427. ** deallocates any resources that were allocated by sqlite3_initialize().
  2428. ** These routines are designed to aid in process initialization and
  2429. ** shutdown on embedded systems. Workstation applications using
  2430. ** SQLite normally do not need to invoke either of these routines.
  2431. **
  2432. ** A call to sqlite3_initialize() is an "effective" call if it is
  2433. ** the first time sqlite3_initialize() is invoked during the lifetime of
  2434. ** the process, or if it is the first time sqlite3_initialize() is invoked
  2435. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  2436. ** of sqlite3_initialize() does any initialization. All other calls
  2437. ** are harmless no-ops.)^
  2438. **
  2439. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  2440. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  2441. ** an effective call to sqlite3_shutdown() does any deinitialization.
  2442. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  2443. **
  2444. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  2445. ** is not. The sqlite3_shutdown() interface must only be called from a
  2446. ** single thread. All open [database connections] must be closed and all
  2447. ** other SQLite resources must be deallocated prior to invoking
  2448. ** sqlite3_shutdown().
  2449. **
  2450. ** Among other things, ^sqlite3_initialize() will invoke
  2451. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  2452. ** will invoke sqlite3_os_end().
  2453. **
  2454. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  2455. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  2456. ** the library (perhaps it is unable to allocate a needed resource such
  2457. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  2458. **
  2459. ** ^The sqlite3_initialize() routine is called internally by many other
  2460. ** SQLite interfaces so that an application usually does not need to
  2461. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  2462. ** calls sqlite3_initialize() so the SQLite library will be automatically
  2463. ** initialized when [sqlite3_open()] is called if it has not be initialized
  2464. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  2465. ** compile-time option, then the automatic calls to sqlite3_initialize()
  2466. ** are omitted and the application must call sqlite3_initialize() directly
  2467. ** prior to using any other SQLite interface. For maximum portability,
  2468. ** it is recommended that applications always invoke sqlite3_initialize()
  2469. ** directly prior to using any other SQLite interface. Future releases
  2470. ** of SQLite may require this. In other words, the behavior exhibited
  2471. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  2472. ** default behavior in some future release of SQLite.
  2473. **
  2474. ** The sqlite3_os_init() routine does operating-system specific
  2475. ** initialization of the SQLite library. The sqlite3_os_end()
  2476. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  2477. ** performed by these routines include allocation or deallocation
  2478. ** of static resources, initialization of global variables,
  2479. ** setting up a default [sqlite3_vfs] module, or setting up
  2480. ** a default configuration using [sqlite3_config()].
  2481. **
  2482. ** The application should never invoke either sqlite3_os_init()
  2483. ** or sqlite3_os_end() directly. The application should only invoke
  2484. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  2485. ** interface is called automatically by sqlite3_initialize() and
  2486. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  2487. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  2488. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  2489. ** When [custom builds | built for other platforms]
  2490. ** (using the [SQLITE_OS_OTHER=1] compile-time
  2491. ** option) the application must supply a suitable implementation for
  2492. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  2493. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  2494. ** must return [SQLITE_OK] on success and some other [error code] upon
  2495. ** failure.
  2496. */
  2497. SQLITE_API int sqlite3_initialize(void);
  2498. SQLITE_API int sqlite3_shutdown(void);
  2499. SQLITE_API int sqlite3_os_init(void);
  2500. SQLITE_API int sqlite3_os_end(void);
  2501. /*
  2502. ** CAPI3REF: Configuring The SQLite Library
  2503. **
  2504. ** The sqlite3_config() interface is used to make global configuration
  2505. ** changes to SQLite in order to tune SQLite to the specific needs of
  2506. ** the application. The default configuration is recommended for most
  2507. ** applications and so this routine is usually not necessary. It is
  2508. ** provided to support rare applications with unusual needs.
  2509. **
  2510. ** <b>The sqlite3_config() interface is not threadsafe. The application
  2511. ** must ensure that no other SQLite interfaces are invoked by other
  2512. ** threads while sqlite3_config() is running.</b>
  2513. **
  2514. ** The sqlite3_config() interface
  2515. ** may only be invoked prior to library initialization using
  2516. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  2517. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  2518. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  2519. ** Note, however, that ^sqlite3_config() can be called as part of the
  2520. ** implementation of an application-defined [sqlite3_os_init()].
  2521. **
  2522. ** The first argument to sqlite3_config() is an integer
  2523. ** [configuration option] that determines
  2524. ** what property of SQLite is to be configured. Subsequent arguments
  2525. ** vary depending on the [configuration option]
  2526. ** in the first argument.
  2527. **
  2528. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  2529. ** ^If the option is unknown or SQLite is unable to set the option
  2530. ** then this routine returns a non-zero [error code].
  2531. */
  2532. SQLITE_API int sqlite3_config(int, ...);
  2533. /*
  2534. ** CAPI3REF: Configure database connections
  2535. ** METHOD: sqlite3
  2536. **
  2537. ** The sqlite3_db_config() interface is used to make configuration
  2538. ** changes to a [database connection]. The interface is similar to
  2539. ** [sqlite3_config()] except that the changes apply to a single
  2540. ** [database connection] (specified in the first argument).
  2541. **
  2542. ** The second argument to sqlite3_db_config(D,V,...) is the
  2543. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  2544. ** that indicates what aspect of the [database connection] is being configured.
  2545. ** Subsequent arguments vary depending on the configuration verb.
  2546. **
  2547. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  2548. ** the call is considered successful.
  2549. */
  2550. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  2551. /*
  2552. ** CAPI3REF: Memory Allocation Routines
  2553. **
  2554. ** An instance of this object defines the interface between SQLite
  2555. ** and low-level memory allocation routines.
  2556. **
  2557. ** This object is used in only one place in the SQLite interface.
  2558. ** A pointer to an instance of this object is the argument to
  2559. ** [sqlite3_config()] when the configuration option is
  2560. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  2561. ** By creating an instance of this object
  2562. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  2563. ** during configuration, an application can specify an alternative
  2564. ** memory allocation subsystem for SQLite to use for all of its
  2565. ** dynamic memory needs.
  2566. **
  2567. ** Note that SQLite comes with several [built-in memory allocators]
  2568. ** that are perfectly adequate for the overwhelming majority of applications
  2569. ** and that this object is only useful to a tiny minority of applications
  2570. ** with specialized memory allocation requirements. This object is
  2571. ** also used during testing of SQLite in order to specify an alternative
  2572. ** memory allocator that simulates memory out-of-memory conditions in
  2573. ** order to verify that SQLite recovers gracefully from such
  2574. ** conditions.
  2575. **
  2576. ** The xMalloc, xRealloc, and xFree methods must work like the
  2577. ** malloc(), realloc() and free() functions from the standard C library.
  2578. ** ^SQLite guarantees that the second argument to
  2579. ** xRealloc is always a value returned by a prior call to xRoundup.
  2580. **
  2581. ** xSize should return the allocated size of a memory allocation
  2582. ** previously obtained from xMalloc or xRealloc. The allocated size
  2583. ** is always at least as big as the requested size but may be larger.
  2584. **
  2585. ** The xRoundup method returns what would be the allocated size of
  2586. ** a memory allocation given a particular requested size. Most memory
  2587. ** allocators round up memory allocations at least to the next multiple
  2588. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  2589. ** Every memory allocation request coming in through [sqlite3_malloc()]
  2590. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  2591. ** that causes the corresponding memory allocation to fail.
  2592. **
  2593. ** The xInit method initializes the memory allocator. For example,
  2594. ** it might allocate any require mutexes or initialize internal data
  2595. ** structures. The xShutdown method is invoked (indirectly) by
  2596. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  2597. ** by xInit. The pAppData pointer is used as the only parameter to
  2598. ** xInit and xShutdown.
  2599. **
  2600. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  2601. ** the xInit method, so the xInit method need not be threadsafe. The
  2602. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  2603. ** not need to be threadsafe either. For all other methods, SQLite
  2604. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  2605. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  2606. ** it is by default) and so the methods are automatically serialized.
  2607. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  2608. ** methods must be threadsafe or else make their own arrangements for
  2609. ** serialization.
  2610. **
  2611. ** SQLite will never invoke xInit() more than once without an intervening
  2612. ** call to xShutdown().
  2613. */
  2614. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  2615. struct sqlite3_mem_methods {
  2616. void *(*xMalloc)(int); /* Memory allocation function */
  2617. void (*xFree)(void*); /* Free a prior allocation */
  2618. void *(*xRealloc)(void*,int); /* Resize an allocation */
  2619. int (*xSize)(void*); /* Return the size of an allocation */
  2620. int (*xRoundup)(int); /* Round up request size to allocation size */
  2621. int (*xInit)(void*); /* Initialize the memory allocator */
  2622. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  2623. void *pAppData; /* Argument to xInit() and xShutdown() */
  2624. };
  2625. /*
  2626. ** CAPI3REF: Configuration Options
  2627. ** KEYWORDS: {configuration option}
  2628. **
  2629. ** These constants are the available integer configuration options that
  2630. ** can be passed as the first argument to the [sqlite3_config()] interface.
  2631. **
  2632. ** New configuration options may be added in future releases of SQLite.
  2633. ** Existing configuration options might be discontinued. Applications
  2634. ** should check the return code from [sqlite3_config()] to make sure that
  2635. ** the call worked. The [sqlite3_config()] interface will return a
  2636. ** non-zero [error code] if a discontinued or unsupported configuration option
  2637. ** is invoked.
  2638. **
  2639. ** <dl>
  2640. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  2641. ** <dd>There are no arguments to this option. ^This option sets the
  2642. ** [threading mode] to Single-thread. In other words, it disables
  2643. ** all mutexing and puts SQLite into a mode where it can only be used
  2644. ** by a single thread. ^If SQLite is compiled with
  2645. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2646. ** it is not possible to change the [threading mode] from its default
  2647. ** value of Single-thread and so [sqlite3_config()] will return
  2648. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  2649. ** configuration option.</dd>
  2650. **
  2651. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  2652. ** <dd>There are no arguments to this option. ^This option sets the
  2653. ** [threading mode] to Multi-thread. In other words, it disables
  2654. ** mutexing on [database connection] and [prepared statement] objects.
  2655. ** The application is responsible for serializing access to
  2656. ** [database connections] and [prepared statements]. But other mutexes
  2657. ** are enabled so that SQLite will be safe to use in a multi-threaded
  2658. ** environment as long as no two threads attempt to use the same
  2659. ** [database connection] at the same time. ^If SQLite is compiled with
  2660. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2661. ** it is not possible to set the Multi-thread [threading mode] and
  2662. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2663. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  2664. **
  2665. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  2666. ** <dd>There are no arguments to this option. ^This option sets the
  2667. ** [threading mode] to Serialized. In other words, this option enables
  2668. ** all mutexes including the recursive
  2669. ** mutexes on [database connection] and [prepared statement] objects.
  2670. ** In this mode (which is the default when SQLite is compiled with
  2671. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  2672. ** to [database connections] and [prepared statements] so that the
  2673. ** application is free to use the same [database connection] or the
  2674. ** same [prepared statement] in different threads at the same time.
  2675. ** ^If SQLite is compiled with
  2676. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2677. ** it is not possible to set the Serialized [threading mode] and
  2678. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2679. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  2680. **
  2681. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  2682. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  2683. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  2684. ** The argument specifies
  2685. ** alternative low-level memory allocation routines to be used in place of
  2686. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  2687. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  2688. ** before the [sqlite3_config()] call returns.</dd>
  2689. **
  2690. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  2691. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  2692. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  2693. ** The [sqlite3_mem_methods]
  2694. ** structure is filled with the currently defined memory allocation routines.)^
  2695. ** This option can be used to overload the default memory allocation
  2696. ** routines with a wrapper that simulations memory allocation failure or
  2697. ** tracks memory usage, for example. </dd>
  2698. **
  2699. ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
  2700. ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
  2701. ** type int, interpreted as a boolean, which if true provides a hint to
  2702. ** SQLite that it should avoid large memory allocations if possible.
  2703. ** SQLite will run faster if it is free to make large memory allocations,
  2704. ** but some application might prefer to run slower in exchange for
  2705. ** guarantees about memory fragmentation that are possible if large
  2706. ** allocations are avoided. This hint is normally off.
  2707. ** </dd>
  2708. **
  2709. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  2710. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  2711. ** interpreted as a boolean, which enables or disables the collection of
  2712. ** memory allocation statistics. ^(When memory allocation statistics are
  2713. ** disabled, the following SQLite interfaces become non-operational:
  2714. ** <ul>
  2715. ** <li> [sqlite3_memory_used()]
  2716. ** <li> [sqlite3_memory_highwater()]
  2717. ** <li> [sqlite3_soft_heap_limit64()]
  2718. ** <li> [sqlite3_status64()]
  2719. ** </ul>)^
  2720. ** ^Memory allocation statistics are enabled by default unless SQLite is
  2721. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  2722. ** allocation statistics are disabled by default.
  2723. ** </dd>
  2724. **
  2725. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  2726. ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
  2727. ** </dd>
  2728. **
  2729. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  2730. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  2731. ** that SQLite can use for the database page cache with the default page
  2732. ** cache implementation.
  2733. ** This configuration option is a no-op if an application-define page
  2734. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  2735. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  2736. ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  2737. ** and the number of cache lines (N).
  2738. ** The sz argument should be the size of the largest database page
  2739. ** (a power of two between 512 and 65536) plus some extra bytes for each
  2740. ** page header. ^The number of extra bytes needed by the page header
  2741. ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  2742. ** ^It is harmless, apart from the wasted memory,
  2743. ** for the sz parameter to be larger than necessary. The pMem
  2744. ** argument must be either a NULL pointer or a pointer to an 8-byte
  2745. ** aligned block of memory of at least sz*N bytes, otherwise
  2746. ** subsequent behavior is undefined.
  2747. ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  2748. ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  2749. ** a page cache line is larger than sz bytes or if all of the pMem buffer
  2750. ** is exhausted.
  2751. ** ^If pMem is NULL and N is non-zero, then each database connection
  2752. ** does an initial bulk allocation for page cache memory
  2753. ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  2754. ** of -1024*N bytes if N is negative, . ^If additional
  2755. ** page cache memory is needed beyond what is provided by the initial
  2756. ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  2757. ** additional cache line. </dd>
  2758. **
  2759. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  2760. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  2761. ** that SQLite will use for all of its dynamic memory allocation needs
  2762. ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
  2763. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  2764. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  2765. ** [SQLITE_ERROR] if invoked otherwise.
  2766. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  2767. ** An 8-byte aligned pointer to the memory,
  2768. ** the number of bytes in the memory buffer, and the minimum allocation size.
  2769. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  2770. ** to using its default memory allocator (the system malloc() implementation),
  2771. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  2772. ** memory pointer is not NULL then the alternative memory
  2773. ** allocator is engaged to handle all of SQLites memory allocation needs.
  2774. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  2775. ** boundary or subsequent behavior of SQLite will be undefined.
  2776. ** The minimum allocation size is capped at 2**12. Reasonable values
  2777. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  2778. **
  2779. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  2780. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  2781. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  2782. ** The argument specifies alternative low-level mutex routines to be used
  2783. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  2784. ** the content of the [sqlite3_mutex_methods] structure before the call to
  2785. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  2786. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2787. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2788. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  2789. ** return [SQLITE_ERROR].</dd>
  2790. **
  2791. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  2792. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  2793. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  2794. ** [sqlite3_mutex_methods]
  2795. ** structure is filled with the currently defined mutex routines.)^
  2796. ** This option can be used to overload the default mutex allocation
  2797. ** routines with a wrapper used to track mutex usage for performance
  2798. ** profiling or testing, for example. ^If SQLite is compiled with
  2799. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2800. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2801. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  2802. ** return [SQLITE_ERROR].</dd>
  2803. **
  2804. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  2805. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  2806. ** the default size of lookaside memory on each [database connection].
  2807. ** The first argument is the
  2808. ** size of each lookaside buffer slot and the second is the number of
  2809. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  2810. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  2811. ** option to [sqlite3_db_config()] can be used to change the lookaside
  2812. ** configuration on individual connections.)^ </dd>
  2813. **
  2814. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  2815. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  2816. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  2817. ** the interface to a custom page cache implementation.)^
  2818. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  2819. **
  2820. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  2821. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  2822. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  2823. ** the current page cache implementation into that object.)^ </dd>
  2824. **
  2825. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  2826. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  2827. ** global [error log].
  2828. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  2829. ** function with a call signature of void(*)(void*,int,const char*),
  2830. ** and a pointer to void. ^If the function pointer is not NULL, it is
  2831. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  2832. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  2833. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  2834. ** passed through as the first parameter to the application-defined logger
  2835. ** function whenever that function is invoked. ^The second parameter to
  2836. ** the logger function is a copy of the first parameter to the corresponding
  2837. ** [sqlite3_log()] call and is intended to be a [result code] or an
  2838. ** [extended result code]. ^The third parameter passed to the logger is
  2839. ** log message after formatting via [sqlite3_snprintf()].
  2840. ** The SQLite logging interface is not reentrant; the logger function
  2841. ** supplied by the application must not invoke any SQLite interface.
  2842. ** In a multi-threaded application, the application-defined logger
  2843. ** function must be threadsafe. </dd>
  2844. **
  2845. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2846. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  2847. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  2848. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  2849. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  2850. ** [sqlite3_open16()] or
  2851. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2852. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2853. ** connection is opened. ^If it is globally disabled, filenames are
  2854. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2855. ** database connection is opened. ^(By default, URI handling is globally
  2856. ** disabled. The default value may be changed by compiling with the
  2857. ** [SQLITE_USE_URI] symbol defined.)^
  2858. **
  2859. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2860. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  2861. ** argument which is interpreted as a boolean in order to enable or disable
  2862. ** the use of covering indices for full table scans in the query optimizer.
  2863. ** ^The default setting is determined
  2864. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2865. ** if that compile-time option is omitted.
  2866. ** The ability to disable the use of covering indices for full table scans
  2867. ** is because some incorrectly coded legacy applications might malfunction
  2868. ** when the optimization is enabled. Providing the ability to
  2869. ** disable the optimization allows the older, buggy application code to work
  2870. ** without change even with newer versions of SQLite.
  2871. **
  2872. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2873. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2874. ** <dd> These options are obsolete and should not be used by new code.
  2875. ** They are retained for backwards compatibility but are now no-ops.
  2876. ** </dd>
  2877. **
  2878. ** [[SQLITE_CONFIG_SQLLOG]]
  2879. ** <dt>SQLITE_CONFIG_SQLLOG
  2880. ** <dd>This option is only available if sqlite is compiled with the
  2881. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2882. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2883. ** The second should be of type (void*). The callback is invoked by the library
  2884. ** in three separate circumstances, identified by the value passed as the
  2885. ** fourth parameter. If the fourth parameter is 0, then the database connection
  2886. ** passed as the second argument has just been opened. The third argument
  2887. ** points to a buffer containing the name of the main database file. If the
  2888. ** fourth parameter is 1, then the SQL statement that the third parameter
  2889. ** points to has just been executed. Or, if the fourth parameter is 2, then
  2890. ** the connection being passed as the second parameter is being closed. The
  2891. ** third parameter is passed NULL In this case. An example of using this
  2892. ** configuration option can be seen in the "test_sqllog.c" source file in
  2893. ** the canonical SQLite source tree.</dd>
  2894. **
  2895. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2896. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2897. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2898. ** that are the default mmap size limit (the default setting for
  2899. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2900. ** ^The default setting can be overridden by each database connection using
  2901. ** either the [PRAGMA mmap_size] command, or by using the
  2902. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  2903. ** will be silently truncated if necessary so that it does not exceed the
  2904. ** compile-time maximum mmap size set by the
  2905. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  2906. ** ^If either argument to this option is negative, then that argument is
  2907. ** changed to its compile-time default.
  2908. **
  2909. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  2910. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  2911. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  2912. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  2913. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  2914. ** that specifies the maximum size of the created heap.
  2915. **
  2916. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  2917. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  2918. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  2919. ** is a pointer to an integer and writes into that integer the number of extra
  2920. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  2921. ** The amount of extra space required can change depending on the compiler,
  2922. ** target platform, and SQLite version.
  2923. **
  2924. ** [[SQLITE_CONFIG_PMASZ]]
  2925. ** <dt>SQLITE_CONFIG_PMASZ
  2926. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  2927. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  2928. ** sorter to that integer. The default minimum PMA Size is set by the
  2929. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  2930. ** to help with sort operations when multithreaded sorting
  2931. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  2932. ** to be sorted exceeds the page size times the minimum of the
  2933. ** [PRAGMA cache_size] setting and this value.
  2934. **
  2935. ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  2936. ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  2937. ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  2938. ** becomes the [statement journal] spill-to-disk threshold.
  2939. ** [Statement journals] are held in memory until their size (in bytes)
  2940. ** exceeds this threshold, at which point they are written to disk.
  2941. ** Or if the threshold is -1, statement journals are always held
  2942. ** exclusively in memory.
  2943. ** Since many statement journals never become large, setting the spill
  2944. ** threshold to a value such as 64KiB can greatly reduce the amount of
  2945. ** I/O required to support statement rollback.
  2946. ** The default value for this setting is controlled by the
  2947. ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2948. **
  2949. ** [[SQLITE_CONFIG_SORTERREF_SIZE]]
  2950. ** <dt>SQLITE_CONFIG_SORTERREF_SIZE
  2951. ** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
  2952. ** of type (int) - the new value of the sorter-reference size threshold.
  2953. ** Usually, when SQLite uses an external sort to order records according
  2954. ** to an ORDER BY clause, all fields required by the caller are present in the
  2955. ** sorted records. However, if SQLite determines based on the declared type
  2956. ** of a table column that its values are likely to be very large - larger
  2957. ** than the configured sorter-reference size threshold - then a reference
  2958. ** is stored in each sorted record and the required column values loaded
  2959. ** from the database as records are returned in sorted order. The default
  2960. ** value for this option is to never use this optimization. Specifying a
  2961. ** negative value for this option restores the default behaviour.
  2962. ** This option is only available if SQLite is compiled with the
  2963. ** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
  2964. **
  2965. ** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]
  2966. ** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE
  2967. ** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter
  2968. ** [sqlite3_int64] parameter which is the default maximum size for an in-memory
  2969. ** database created using [sqlite3_deserialize()]. This default maximum
  2970. ** size can be adjusted up or down for individual databases using the
  2971. ** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this
  2972. ** configuration setting is never used, then the default maximum is determined
  2973. ** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that
  2974. ** compile-time option is not set, then the default maximum is 1073741824.
  2975. ** </dl>
  2976. */
  2977. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  2978. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  2979. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  2980. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  2981. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  2982. #define SQLITE_CONFIG_SCRATCH 6 /* No longer used */
  2983. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  2984. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  2985. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  2986. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  2987. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2988. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2989. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2990. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2991. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2992. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2993. #define SQLITE_CONFIG_URI 17 /* int */
  2994. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2995. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2996. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  2997. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  2998. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  2999. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  3000. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  3001. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  3002. #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
  3003. #define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
  3004. #define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */
  3005. #define SQLITE_CONFIG_MEMDB_MAXSIZE 29 /* sqlite3_int64 */
  3006. /*
  3007. ** CAPI3REF: Database Connection Configuration Options
  3008. **
  3009. ** These constants are the available integer configuration options that
  3010. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  3011. **
  3012. ** New configuration options may be added in future releases of SQLite.
  3013. ** Existing configuration options might be discontinued. Applications
  3014. ** should check the return code from [sqlite3_db_config()] to make sure that
  3015. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  3016. ** non-zero [error code] if a discontinued or unsupported configuration option
  3017. ** is invoked.
  3018. **
  3019. ** <dl>
  3020. ** [[SQLITE_DBCONFIG_LOOKASIDE]]
  3021. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  3022. ** <dd> ^This option takes three additional arguments that determine the
  3023. ** [lookaside memory allocator] configuration for the [database connection].
  3024. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  3025. ** pointer to a memory buffer to use for lookaside memory.
  3026. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  3027. ** may be NULL in which case SQLite will allocate the
  3028. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  3029. ** size of each lookaside buffer slot. ^The third argument is the number of
  3030. ** slots. The size of the buffer in the first argument must be greater than
  3031. ** or equal to the product of the second and third arguments. The buffer
  3032. ** must be aligned to an 8-byte boundary. ^If the second argument to
  3033. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  3034. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  3035. ** configuration for a database connection can only be changed when that
  3036. ** connection is not currently using lookaside memory, or in other words
  3037. ** when the "current value" returned by
  3038. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  3039. ** Any attempt to change the lookaside memory configuration when lookaside
  3040. ** memory is in use leaves the configuration unchanged and returns
  3041. ** [SQLITE_BUSY].)^</dd>
  3042. **
  3043. ** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
  3044. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  3045. ** <dd> ^This option is used to enable or disable the enforcement of
  3046. ** [foreign key constraints]. There should be two additional arguments.
  3047. ** The first argument is an integer which is 0 to disable FK enforcement,
  3048. ** positive to enable FK enforcement or negative to leave FK enforcement
  3049. ** unchanged. The second parameter is a pointer to an integer into which
  3050. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  3051. ** following this call. The second parameter may be a NULL pointer, in
  3052. ** which case the FK enforcement setting is not reported back. </dd>
  3053. **
  3054. ** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]
  3055. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  3056. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  3057. ** There should be two additional arguments.
  3058. ** The first argument is an integer which is 0 to disable triggers,
  3059. ** positive to enable triggers or negative to leave the setting unchanged.
  3060. ** The second parameter is a pointer to an integer into which
  3061. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  3062. ** following this call. The second parameter may be a NULL pointer, in
  3063. ** which case the trigger setting is not reported back. </dd>
  3064. **
  3065. ** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
  3066. ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  3067. ** <dd> ^This option is used to enable or disable the
  3068. ** [fts3_tokenizer()] function which is part of the
  3069. ** [FTS3] full-text search engine extension.
  3070. ** There should be two additional arguments.
  3071. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  3072. ** positive to enable fts3_tokenizer() or negative to leave the setting
  3073. ** unchanged.
  3074. ** The second parameter is a pointer to an integer into which
  3075. ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  3076. ** following this call. The second parameter may be a NULL pointer, in
  3077. ** which case the new setting is not reported back. </dd>
  3078. **
  3079. ** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
  3080. ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  3081. ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  3082. ** interface independently of the [load_extension()] SQL function.
  3083. ** The [sqlite3_enable_load_extension()] API enables or disables both the
  3084. ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  3085. ** There should be two additional arguments.
  3086. ** When the first argument to this interface is 1, then only the C-API is
  3087. ** enabled and the SQL function remains disabled. If the first argument to
  3088. ** this interface is 0, then both the C-API and the SQL function are disabled.
  3089. ** If the first argument is -1, then no changes are made to state of either the
  3090. ** C-API or the SQL function.
  3091. ** The second parameter is a pointer to an integer into which
  3092. ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  3093. ** is disabled or enabled following this call. The second parameter may
  3094. ** be a NULL pointer, in which case the new setting is not reported back.
  3095. ** </dd>
  3096. **
  3097. ** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  3098. ** <dd> ^This option is used to change the name of the "main" database
  3099. ** schema. ^The sole argument is a pointer to a constant UTF8 string
  3100. ** which will become the new schema name in place of "main". ^SQLite
  3101. ** does not make a copy of the new main schema name string, so the application
  3102. ** must ensure that the argument passed into this DBCONFIG option is unchanged
  3103. ** until after the database connection closes.
  3104. ** </dd>
  3105. **
  3106. ** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
  3107. ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  3108. ** <dd> Usually, when a database in wal mode is closed or detached from a
  3109. ** database handle, SQLite checks if this will mean that there are now no
  3110. ** connections at all to the database. If so, it performs a checkpoint
  3111. ** operation before closing the connection. This option may be used to
  3112. ** override this behaviour. The first parameter passed to this operation
  3113. ** is an integer - positive to disable checkpoints-on-close, or zero (the
  3114. ** default) to enable them, and negative to leave the setting unchanged.
  3115. ** The second parameter is a pointer to an integer
  3116. ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  3117. ** have been disabled - 0 if they are not disabled, 1 if they are.
  3118. ** </dd>
  3119. **
  3120. ** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
  3121. ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
  3122. ** the [query planner stability guarantee] (QPSG). When the QPSG is active,
  3123. ** a single SQL query statement will always use the same algorithm regardless
  3124. ** of values of [bound parameters].)^ The QPSG disables some query optimizations
  3125. ** that look at the values of bound parameters, which can make some queries
  3126. ** slower. But the QPSG has the advantage of more predictable behavior. With
  3127. ** the QPSG active, SQLite will always use the same query plan in the field as
  3128. ** was used during testing in the lab.
  3129. ** The first argument to this setting is an integer which is 0 to disable
  3130. ** the QPSG, positive to enable QPSG, or negative to leave the setting
  3131. ** unchanged. The second parameter is a pointer to an integer into which
  3132. ** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
  3133. ** following this call.
  3134. ** </dd>
  3135. **
  3136. ** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
  3137. ** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
  3138. ** include output for any operations performed by trigger programs. This
  3139. ** option is used to set or clear (the default) a flag that governs this
  3140. ** behavior. The first parameter passed to this operation is an integer -
  3141. ** positive to enable output for trigger programs, or zero to disable it,
  3142. ** or negative to leave the setting unchanged.
  3143. ** The second parameter is a pointer to an integer into which is written
  3144. ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
  3145. ** it is not disabled, 1 if it is.
  3146. ** </dd>
  3147. **
  3148. ** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
  3149. ** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
  3150. ** [VACUUM] in order to reset a database back to an empty database
  3151. ** with no schema and no content. The following process works even for
  3152. ** a badly corrupted database file:
  3153. ** <ol>
  3154. ** <li> If the database connection is newly opened, make sure it has read the
  3155. ** database schema by preparing then discarding some query against the
  3156. ** database, or calling sqlite3_table_column_metadata(), ignoring any
  3157. ** errors. This step is only necessary if the application desires to keep
  3158. ** the database in WAL mode after the reset if it was in WAL mode before
  3159. ** the reset.
  3160. ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
  3161. ** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
  3162. ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
  3163. ** </ol>
  3164. ** Because resetting a database is destructive and irreversible, the
  3165. ** process requires the use of this obscure API and multiple steps to help
  3166. ** ensure that it does not happen by accident.
  3167. **
  3168. ** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
  3169. ** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
  3170. ** "defensive" flag for a database connection. When the defensive
  3171. ** flag is enabled, language features that allow ordinary SQL to
  3172. ** deliberately corrupt the database file are disabled. The disabled
  3173. ** features include but are not limited to the following:
  3174. ** <ul>
  3175. ** <li> The [PRAGMA writable_schema=ON] statement.
  3176. ** <li> Writes to the [sqlite_dbpage] virtual table.
  3177. ** <li> Direct writes to [shadow tables].
  3178. ** </ul>
  3179. ** </dd>
  3180. **
  3181. ** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt>
  3182. ** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
  3183. ** "writable_schema" flag. This has the same effect and is logically equivalent
  3184. ** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].
  3185. ** The first argument to this setting is an integer which is 0 to disable
  3186. ** the writable_schema, positive to enable writable_schema, or negative to
  3187. ** leave the setting unchanged. The second parameter is a pointer to an
  3188. ** integer into which is written 0 or 1 to indicate whether the writable_schema
  3189. ** is enabled or disabled following this call.
  3190. ** </dd>
  3191. ** </dl>
  3192. */
  3193. #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
  3194. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  3195. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  3196. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  3197. #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  3198. #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  3199. #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
  3200. #define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
  3201. #define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */
  3202. #define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */
  3203. #define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */
  3204. #define SQLITE_DBCONFIG_WRITABLE_SCHEMA 1011 /* int int* */
  3205. #define SQLITE_DBCONFIG_MAX 1011 /* Largest DBCONFIG */
  3206. /*
  3207. ** CAPI3REF: Enable Or Disable Extended Result Codes
  3208. ** METHOD: sqlite3
  3209. **
  3210. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  3211. ** [extended result codes] feature of SQLite. ^The extended result
  3212. ** codes are disabled by default for historical compatibility.
  3213. */
  3214. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  3215. /*
  3216. ** CAPI3REF: Last Insert Rowid
  3217. ** METHOD: sqlite3
  3218. **
  3219. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  3220. ** has a unique 64-bit signed
  3221. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  3222. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  3223. ** names are not also used by explicitly declared columns. ^If
  3224. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  3225. ** is another alias for the rowid.
  3226. **
  3227. ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
  3228. ** the most recent successful [INSERT] into a rowid table or [virtual table]
  3229. ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
  3230. ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
  3231. ** on the database connection D, then sqlite3_last_insert_rowid(D) returns
  3232. ** zero.
  3233. **
  3234. ** As well as being set automatically as rows are inserted into database
  3235. ** tables, the value returned by this function may be set explicitly by
  3236. ** [sqlite3_set_last_insert_rowid()]
  3237. **
  3238. ** Some virtual table implementations may INSERT rows into rowid tables as
  3239. ** part of committing a transaction (e.g. to flush data accumulated in memory
  3240. ** to disk). In this case subsequent calls to this function return the rowid
  3241. ** associated with these internal INSERT operations, which leads to
  3242. ** unintuitive results. Virtual table implementations that do write to rowid
  3243. ** tables in this way can avoid this problem by restoring the original
  3244. ** rowid value using [sqlite3_set_last_insert_rowid()] before returning
  3245. ** control to the user.
  3246. **
  3247. ** ^(If an [INSERT] occurs within a trigger then this routine will
  3248. ** return the [rowid] of the inserted row as long as the trigger is
  3249. ** running. Once the trigger program ends, the value returned
  3250. ** by this routine reverts to what it was before the trigger was fired.)^
  3251. **
  3252. ** ^An [INSERT] that fails due to a constraint violation is not a
  3253. ** successful [INSERT] and does not change the value returned by this
  3254. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  3255. ** and INSERT OR ABORT make no changes to the return value of this
  3256. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  3257. ** encounters a constraint violation, it does not fail. The
  3258. ** INSERT continues to completion after deleting rows that caused
  3259. ** the constraint problem so INSERT OR REPLACE will always change
  3260. ** the return value of this interface.)^
  3261. **
  3262. ** ^For the purposes of this routine, an [INSERT] is considered to
  3263. ** be successful even if it is subsequently rolled back.
  3264. **
  3265. ** This function is accessible to SQL statements via the
  3266. ** [last_insert_rowid() SQL function].
  3267. **
  3268. ** If a separate thread performs a new [INSERT] on the same
  3269. ** database connection while the [sqlite3_last_insert_rowid()]
  3270. ** function is running and thus changes the last insert [rowid],
  3271. ** then the value returned by [sqlite3_last_insert_rowid()] is
  3272. ** unpredictable and might not equal either the old or the new
  3273. ** last insert [rowid].
  3274. */
  3275. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  3276. /*
  3277. ** CAPI3REF: Set the Last Insert Rowid value.
  3278. ** METHOD: sqlite3
  3279. **
  3280. ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
  3281. ** set the value returned by calling sqlite3_last_insert_rowid(D) to R
  3282. ** without inserting a row into the database.
  3283. */
  3284. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
  3285. /*
  3286. ** CAPI3REF: Count The Number Of Rows Modified
  3287. ** METHOD: sqlite3
  3288. **
  3289. ** ^This function returns the number of rows modified, inserted or
  3290. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  3291. ** statement on the database connection specified by the only parameter.
  3292. ** ^Executing any other type of SQL statement does not modify the value
  3293. ** returned by this function.
  3294. **
  3295. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  3296. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  3297. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  3298. **
  3299. ** Changes to a view that are intercepted by
  3300. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  3301. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  3302. ** DELETE statement run on a view is always zero. Only changes made to real
  3303. ** tables are counted.
  3304. **
  3305. ** Things are more complicated if the sqlite3_changes() function is
  3306. ** executed while a trigger program is running. This may happen if the
  3307. ** program uses the [changes() SQL function], or if some other callback
  3308. ** function invokes sqlite3_changes() directly. Essentially:
  3309. **
  3310. ** <ul>
  3311. ** <li> ^(Before entering a trigger program the value returned by
  3312. ** sqlite3_changes() function is saved. After the trigger program
  3313. ** has finished, the original value is restored.)^
  3314. **
  3315. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  3316. ** statement sets the value returned by sqlite3_changes()
  3317. ** upon completion as normal. Of course, this value will not include
  3318. ** any changes performed by sub-triggers, as the sqlite3_changes()
  3319. ** value will be saved and restored after each sub-trigger has run.)^
  3320. ** </ul>
  3321. **
  3322. ** ^This means that if the changes() SQL function (or similar) is used
  3323. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  3324. ** returns the value as set when the calling statement began executing.
  3325. ** ^If it is used by the second or subsequent such statement within a trigger
  3326. ** program, the value returned reflects the number of rows modified by the
  3327. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  3328. **
  3329. ** If a separate thread makes changes on the same database connection
  3330. ** while [sqlite3_changes()] is running then the value returned
  3331. ** is unpredictable and not meaningful.
  3332. **
  3333. ** See also:
  3334. ** <ul>
  3335. ** <li> the [sqlite3_total_changes()] interface
  3336. ** <li> the [count_changes pragma]
  3337. ** <li> the [changes() SQL function]
  3338. ** <li> the [data_version pragma]
  3339. ** </ul>
  3340. */
  3341. SQLITE_API int sqlite3_changes(sqlite3*);
  3342. /*
  3343. ** CAPI3REF: Total Number Of Rows Modified
  3344. ** METHOD: sqlite3
  3345. **
  3346. ** ^This function returns the total number of rows inserted, modified or
  3347. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  3348. ** since the database connection was opened, including those executed as
  3349. ** part of trigger programs. ^Executing any other type of SQL statement
  3350. ** does not affect the value returned by sqlite3_total_changes().
  3351. **
  3352. ** ^Changes made as part of [foreign key actions] are included in the
  3353. ** count, but those made as part of REPLACE constraint resolution are
  3354. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  3355. ** are not counted.
  3356. **
  3357. ** The [sqlite3_total_changes(D)] interface only reports the number
  3358. ** of rows that changed due to SQL statement run against database
  3359. ** connection D. Any changes by other database connections are ignored.
  3360. ** To detect changes against a database file from other database
  3361. ** connections use the [PRAGMA data_version] command or the
  3362. ** [SQLITE_FCNTL_DATA_VERSION] [file control].
  3363. **
  3364. ** If a separate thread makes changes on the same database connection
  3365. ** while [sqlite3_total_changes()] is running then the value
  3366. ** returned is unpredictable and not meaningful.
  3367. **
  3368. ** See also:
  3369. ** <ul>
  3370. ** <li> the [sqlite3_changes()] interface
  3371. ** <li> the [count_changes pragma]
  3372. ** <li> the [changes() SQL function]
  3373. ** <li> the [data_version pragma]
  3374. ** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]
  3375. ** </ul>
  3376. */
  3377. SQLITE_API int sqlite3_total_changes(sqlite3*);
  3378. /*
  3379. ** CAPI3REF: Interrupt A Long-Running Query
  3380. ** METHOD: sqlite3
  3381. **
  3382. ** ^This function causes any pending database operation to abort and
  3383. ** return at its earliest opportunity. This routine is typically
  3384. ** called in response to a user action such as pressing "Cancel"
  3385. ** or Ctrl-C where the user wants a long query operation to halt
  3386. ** immediately.
  3387. **
  3388. ** ^It is safe to call this routine from a thread different from the
  3389. ** thread that is currently running the database operation. But it
  3390. ** is not safe to call this routine with a [database connection] that
  3391. ** is closed or might close before sqlite3_interrupt() returns.
  3392. **
  3393. ** ^If an SQL operation is very nearly finished at the time when
  3394. ** sqlite3_interrupt() is called, then it might not have an opportunity
  3395. ** to be interrupted and might continue to completion.
  3396. **
  3397. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  3398. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  3399. ** that is inside an explicit transaction, then the entire transaction
  3400. ** will be rolled back automatically.
  3401. **
  3402. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  3403. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  3404. ** that are started after the sqlite3_interrupt() call and before the
  3405. ** running statements reaches zero are interrupted as if they had been
  3406. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  3407. ** that are started after the running statement count reaches zero are
  3408. ** not effected by the sqlite3_interrupt().
  3409. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  3410. ** SQL statements is a no-op and has no effect on SQL statements
  3411. ** that are started after the sqlite3_interrupt() call returns.
  3412. */
  3413. SQLITE_API void sqlite3_interrupt(sqlite3*);
  3414. /*
  3415. ** CAPI3REF: Determine If An SQL Statement Is Complete
  3416. **
  3417. ** These routines are useful during command-line input to determine if the
  3418. ** currently entered text seems to form a complete SQL statement or
  3419. ** if additional input is needed before sending the text into
  3420. ** SQLite for parsing. ^These routines return 1 if the input string
  3421. ** appears to be a complete SQL statement. ^A statement is judged to be
  3422. ** complete if it ends with a semicolon token and is not a prefix of a
  3423. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  3424. ** string literals or quoted identifier names or comments are not
  3425. ** independent tokens (they are part of the token in which they are
  3426. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  3427. ** and comments that follow the final semicolon are ignored.
  3428. **
  3429. ** ^These routines return 0 if the statement is incomplete. ^If a
  3430. ** memory allocation fails, then SQLITE_NOMEM is returned.
  3431. **
  3432. ** ^These routines do not parse the SQL statements thus
  3433. ** will not detect syntactically incorrect SQL.
  3434. **
  3435. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  3436. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  3437. ** automatically by sqlite3_complete16(). If that initialization fails,
  3438. ** then the return value from sqlite3_complete16() will be non-zero
  3439. ** regardless of whether or not the input SQL is complete.)^
  3440. **
  3441. ** The input to [sqlite3_complete()] must be a zero-terminated
  3442. ** UTF-8 string.
  3443. **
  3444. ** The input to [sqlite3_complete16()] must be a zero-terminated
  3445. ** UTF-16 string in native byte order.
  3446. */
  3447. SQLITE_API int sqlite3_complete(const char *sql);
  3448. SQLITE_API int sqlite3_complete16(const void *sql);
  3449. /*
  3450. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  3451. ** KEYWORDS: {busy-handler callback} {busy handler}
  3452. ** METHOD: sqlite3
  3453. **
  3454. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  3455. ** that might be invoked with argument P whenever
  3456. ** an attempt is made to access a database table associated with
  3457. ** [database connection] D when another thread
  3458. ** or process has the table locked.
  3459. ** The sqlite3_busy_handler() interface is used to implement
  3460. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  3461. **
  3462. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  3463. ** is returned immediately upon encountering the lock. ^If the busy callback
  3464. ** is not NULL, then the callback might be invoked with two arguments.
  3465. **
  3466. ** ^The first argument to the busy handler is a copy of the void* pointer which
  3467. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  3468. ** the busy handler callback is the number of times that the busy handler has
  3469. ** been invoked previously for the same locking event. ^If the
  3470. ** busy callback returns 0, then no additional attempts are made to
  3471. ** access the database and [SQLITE_BUSY] is returned
  3472. ** to the application.
  3473. ** ^If the callback returns non-zero, then another attempt
  3474. ** is made to access the database and the cycle repeats.
  3475. **
  3476. ** The presence of a busy handler does not guarantee that it will be invoked
  3477. ** when there is lock contention. ^If SQLite determines that invoking the busy
  3478. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  3479. ** to the application instead of invoking the
  3480. ** busy handler.
  3481. ** Consider a scenario where one process is holding a read lock that
  3482. ** it is trying to promote to a reserved lock and
  3483. ** a second process is holding a reserved lock that it is trying
  3484. ** to promote to an exclusive lock. The first process cannot proceed
  3485. ** because it is blocked by the second and the second process cannot
  3486. ** proceed because it is blocked by the first. If both processes
  3487. ** invoke the busy handlers, neither will make any progress. Therefore,
  3488. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  3489. ** will induce the first process to release its read lock and allow
  3490. ** the second process to proceed.
  3491. **
  3492. ** ^The default busy callback is NULL.
  3493. **
  3494. ** ^(There can only be a single busy handler defined for each
  3495. ** [database connection]. Setting a new busy handler clears any
  3496. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  3497. ** or evaluating [PRAGMA busy_timeout=N] will change the
  3498. ** busy handler and thus clear any previously set busy handler.
  3499. **
  3500. ** The busy callback should not take any actions which modify the
  3501. ** database connection that invoked the busy handler. In other words,
  3502. ** the busy handler is not reentrant. Any such actions
  3503. ** result in undefined behavior.
  3504. **
  3505. ** A busy handler must not close the database connection
  3506. ** or [prepared statement] that invoked the busy handler.
  3507. */
  3508. SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
  3509. /*
  3510. ** CAPI3REF: Set A Busy Timeout
  3511. ** METHOD: sqlite3
  3512. **
  3513. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  3514. ** for a specified amount of time when a table is locked. ^The handler
  3515. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  3516. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  3517. ** the handler returns 0 which causes [sqlite3_step()] to return
  3518. ** [SQLITE_BUSY].
  3519. **
  3520. ** ^Calling this routine with an argument less than or equal to zero
  3521. ** turns off all busy handlers.
  3522. **
  3523. ** ^(There can only be a single busy handler for a particular
  3524. ** [database connection] at any given moment. If another busy handler
  3525. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  3526. ** this routine, that other busy handler is cleared.)^
  3527. **
  3528. ** See also: [PRAGMA busy_timeout]
  3529. */
  3530. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  3531. /*
  3532. ** CAPI3REF: Convenience Routines For Running Queries
  3533. ** METHOD: sqlite3
  3534. **
  3535. ** This is a legacy interface that is preserved for backwards compatibility.
  3536. ** Use of this interface is not recommended.
  3537. **
  3538. ** Definition: A <b>result table</b> is memory data structure created by the
  3539. ** [sqlite3_get_table()] interface. A result table records the
  3540. ** complete query results from one or more queries.
  3541. **
  3542. ** The table conceptually has a number of rows and columns. But
  3543. ** these numbers are not part of the result table itself. These
  3544. ** numbers are obtained separately. Let N be the number of rows
  3545. ** and M be the number of columns.
  3546. **
  3547. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  3548. ** There are (N+1)*M elements in the array. The first M pointers point
  3549. ** to zero-terminated strings that contain the names of the columns.
  3550. ** The remaining entries all point to query results. NULL values result
  3551. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  3552. ** string representation as returned by [sqlite3_column_text()].
  3553. **
  3554. ** A result table might consist of one or more memory allocations.
  3555. ** It is not safe to pass a result table directly to [sqlite3_free()].
  3556. ** A result table should be deallocated using [sqlite3_free_table()].
  3557. **
  3558. ** ^(As an example of the result table format, suppose a query result
  3559. ** is as follows:
  3560. **
  3561. ** <blockquote><pre>
  3562. ** Name | Age
  3563. ** -----------------------
  3564. ** Alice | 43
  3565. ** Bob | 28
  3566. ** Cindy | 21
  3567. ** </pre></blockquote>
  3568. **
  3569. ** There are two column (M==2) and three rows (N==3). Thus the
  3570. ** result table has 8 entries. Suppose the result table is stored
  3571. ** in an array names azResult. Then azResult holds this content:
  3572. **
  3573. ** <blockquote><pre>
  3574. ** azResult&#91;0] = "Name";
  3575. ** azResult&#91;1] = "Age";
  3576. ** azResult&#91;2] = "Alice";
  3577. ** azResult&#91;3] = "43";
  3578. ** azResult&#91;4] = "Bob";
  3579. ** azResult&#91;5] = "28";
  3580. ** azResult&#91;6] = "Cindy";
  3581. ** azResult&#91;7] = "21";
  3582. ** </pre></blockquote>)^
  3583. **
  3584. ** ^The sqlite3_get_table() function evaluates one or more
  3585. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  3586. ** string of its 2nd parameter and returns a result table to the
  3587. ** pointer given in its 3rd parameter.
  3588. **
  3589. ** After the application has finished with the result from sqlite3_get_table(),
  3590. ** it must pass the result table pointer to sqlite3_free_table() in order to
  3591. ** release the memory that was malloced. Because of the way the
  3592. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  3593. ** function must not try to call [sqlite3_free()] directly. Only
  3594. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  3595. **
  3596. ** The sqlite3_get_table() interface is implemented as a wrapper around
  3597. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  3598. ** to any internal data structures of SQLite. It uses only the public
  3599. ** interface defined here. As a consequence, errors that occur in the
  3600. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  3601. ** reflected in subsequent calls to [sqlite3_errcode()] or
  3602. ** [sqlite3_errmsg()].
  3603. */
  3604. SQLITE_API int sqlite3_get_table(
  3605. sqlite3 *db, /* An open database */
  3606. const char *zSql, /* SQL to be evaluated */
  3607. char ***pazResult, /* Results of the query */
  3608. int *pnRow, /* Number of result rows written here */
  3609. int *pnColumn, /* Number of result columns written here */
  3610. char **pzErrmsg /* Error msg written here */
  3611. );
  3612. SQLITE_API void sqlite3_free_table(char **result);
  3613. /*
  3614. ** CAPI3REF: Formatted String Printing Functions
  3615. **
  3616. ** These routines are work-alikes of the "printf()" family of functions
  3617. ** from the standard C library.
  3618. ** These routines understand most of the common formatting options from
  3619. ** the standard library printf()
  3620. ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
  3621. ** See the [built-in printf()] documentation for details.
  3622. **
  3623. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  3624. ** results into memory obtained from [sqlite3_malloc64()].
  3625. ** The strings returned by these two routines should be
  3626. ** released by [sqlite3_free()]. ^Both routines return a
  3627. ** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
  3628. ** memory to hold the resulting string.
  3629. **
  3630. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  3631. ** the standard C library. The result is written into the
  3632. ** buffer supplied as the second parameter whose size is given by
  3633. ** the first parameter. Note that the order of the
  3634. ** first two parameters is reversed from snprintf().)^ This is an
  3635. ** historical accident that cannot be fixed without breaking
  3636. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  3637. ** returns a pointer to its buffer instead of the number of
  3638. ** characters actually written into the buffer.)^ We admit that
  3639. ** the number of characters written would be a more useful return
  3640. ** value but we cannot change the implementation of sqlite3_snprintf()
  3641. ** now without breaking compatibility.
  3642. **
  3643. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  3644. ** guarantees that the buffer is always zero-terminated. ^The first
  3645. ** parameter "n" is the total size of the buffer, including space for
  3646. ** the zero terminator. So the longest string that can be completely
  3647. ** written will be n-1 characters.
  3648. **
  3649. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  3650. **
  3651. ** See also: [built-in printf()], [printf() SQL function]
  3652. */
  3653. SQLITE_API char *sqlite3_mprintf(const char*,...);
  3654. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  3655. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  3656. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  3657. /*
  3658. ** CAPI3REF: Memory Allocation Subsystem
  3659. **
  3660. ** The SQLite core uses these three routines for all of its own
  3661. ** internal memory allocation needs. "Core" in the previous sentence
  3662. ** does not include operating-system specific VFS implementation. The
  3663. ** Windows VFS uses native malloc() and free() for some operations.
  3664. **
  3665. ** ^The sqlite3_malloc() routine returns a pointer to a block
  3666. ** of memory at least N bytes in length, where N is the parameter.
  3667. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  3668. ** memory, it returns a NULL pointer. ^If the parameter N to
  3669. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  3670. ** a NULL pointer.
  3671. **
  3672. ** ^The sqlite3_malloc64(N) routine works just like
  3673. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  3674. ** of a signed 32-bit integer.
  3675. **
  3676. ** ^Calling sqlite3_free() with a pointer previously returned
  3677. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  3678. ** that it might be reused. ^The sqlite3_free() routine is
  3679. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  3680. ** to sqlite3_free() is harmless. After being freed, memory
  3681. ** should neither be read nor written. Even reading previously freed
  3682. ** memory might result in a segmentation fault or other severe error.
  3683. ** Memory corruption, a segmentation fault, or other severe error
  3684. ** might result if sqlite3_free() is called with a non-NULL pointer that
  3685. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  3686. **
  3687. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  3688. ** prior memory allocation X to be at least N bytes.
  3689. ** ^If the X parameter to sqlite3_realloc(X,N)
  3690. ** is a NULL pointer then its behavior is identical to calling
  3691. ** sqlite3_malloc(N).
  3692. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  3693. ** negative then the behavior is exactly the same as calling
  3694. ** sqlite3_free(X).
  3695. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  3696. ** of at least N bytes in size or NULL if insufficient memory is available.
  3697. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  3698. ** of the prior allocation are copied into the beginning of buffer returned
  3699. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  3700. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  3701. ** prior allocation is not freed.
  3702. **
  3703. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  3704. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  3705. ** of a 32-bit signed integer.
  3706. **
  3707. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  3708. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  3709. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  3710. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  3711. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  3712. ** sqlite3_msize(X) returns zero. If X points to something that is not
  3713. ** the beginning of memory allocation, or if it points to a formerly
  3714. ** valid memory allocation that has now been freed, then the behavior
  3715. ** of sqlite3_msize(X) is undefined and possibly harmful.
  3716. **
  3717. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  3718. ** sqlite3_malloc64(), and sqlite3_realloc64()
  3719. ** is always aligned to at least an 8 byte boundary, or to a
  3720. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  3721. ** option is used.
  3722. **
  3723. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  3724. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  3725. ** implementation of these routines to be omitted. That capability
  3726. ** is no longer provided. Only built-in memory allocators can be used.
  3727. **
  3728. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  3729. ** the system malloc() and free() directly when converting
  3730. ** filenames between the UTF-8 encoding used by SQLite
  3731. ** and whatever filename encoding is used by the particular Windows
  3732. ** installation. Memory allocation errors were detected, but
  3733. ** they were reported back as [SQLITE_CANTOPEN] or
  3734. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  3735. **
  3736. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  3737. ** must be either NULL or else pointers obtained from a prior
  3738. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  3739. ** not yet been released.
  3740. **
  3741. ** The application must not read or write any part of
  3742. ** a block of memory after it has been released using
  3743. ** [sqlite3_free()] or [sqlite3_realloc()].
  3744. */
  3745. SQLITE_API void *sqlite3_malloc(int);
  3746. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  3747. SQLITE_API void *sqlite3_realloc(void*, int);
  3748. SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  3749. SQLITE_API void sqlite3_free(void*);
  3750. SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  3751. /*
  3752. ** CAPI3REF: Memory Allocator Statistics
  3753. **
  3754. ** SQLite provides these two interfaces for reporting on the status
  3755. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  3756. ** routines, which form the built-in memory allocation subsystem.
  3757. **
  3758. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  3759. ** of memory currently outstanding (malloced but not freed).
  3760. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  3761. ** value of [sqlite3_memory_used()] since the high-water mark
  3762. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  3763. ** [sqlite3_memory_highwater()] include any overhead
  3764. ** added by SQLite in its implementation of [sqlite3_malloc()],
  3765. ** but not overhead added by the any underlying system library
  3766. ** routines that [sqlite3_malloc()] may call.
  3767. **
  3768. ** ^The memory high-water mark is reset to the current value of
  3769. ** [sqlite3_memory_used()] if and only if the parameter to
  3770. ** [sqlite3_memory_highwater()] is true. ^The value returned
  3771. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  3772. ** prior to the reset.
  3773. */
  3774. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  3775. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  3776. /*
  3777. ** CAPI3REF: Pseudo-Random Number Generator
  3778. **
  3779. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  3780. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  3781. ** already uses the largest possible [ROWID]. The PRNG is also used for
  3782. ** the build-in random() and randomblob() SQL functions. This interface allows
  3783. ** applications to access the same PRNG for other purposes.
  3784. **
  3785. ** ^A call to this routine stores N bytes of randomness into buffer P.
  3786. ** ^The P parameter can be a NULL pointer.
  3787. **
  3788. ** ^If this routine has not been previously called or if the previous
  3789. ** call had N less than one or a NULL pointer for P, then the PRNG is
  3790. ** seeded using randomness obtained from the xRandomness method of
  3791. ** the default [sqlite3_vfs] object.
  3792. ** ^If the previous call to this routine had an N of 1 or more and a
  3793. ** non-NULL P then the pseudo-randomness is generated
  3794. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  3795. ** method.
  3796. */
  3797. SQLITE_API void sqlite3_randomness(int N, void *P);
  3798. /*
  3799. ** CAPI3REF: Compile-Time Authorization Callbacks
  3800. ** METHOD: sqlite3
  3801. ** KEYWORDS: {authorizer callback}
  3802. **
  3803. ** ^This routine registers an authorizer callback with a particular
  3804. ** [database connection], supplied in the first argument.
  3805. ** ^The authorizer callback is invoked as SQL statements are being compiled
  3806. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  3807. ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
  3808. ** and [sqlite3_prepare16_v3()]. ^At various
  3809. ** points during the compilation process, as logic is being created
  3810. ** to perform various actions, the authorizer callback is invoked to
  3811. ** see if those actions are allowed. ^The authorizer callback should
  3812. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  3813. ** specific action but allow the SQL statement to continue to be
  3814. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  3815. ** rejected with an error. ^If the authorizer callback returns
  3816. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  3817. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  3818. ** the authorizer will fail with an error message.
  3819. **
  3820. ** When the callback returns [SQLITE_OK], that means the operation
  3821. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  3822. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  3823. ** authorizer will fail with an error message explaining that
  3824. ** access is denied.
  3825. **
  3826. ** ^The first parameter to the authorizer callback is a copy of the third
  3827. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  3828. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  3829. ** the particular action to be authorized. ^The third through sixth parameters
  3830. ** to the callback are either NULL pointers or zero-terminated strings
  3831. ** that contain additional details about the action to be authorized.
  3832. ** Applications must always be prepared to encounter a NULL pointer in any
  3833. ** of the third through the sixth parameters of the authorization callback.
  3834. **
  3835. ** ^If the action code is [SQLITE_READ]
  3836. ** and the callback returns [SQLITE_IGNORE] then the
  3837. ** [prepared statement] statement is constructed to substitute
  3838. ** a NULL value in place of the table column that would have
  3839. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  3840. ** return can be used to deny an untrusted user access to individual
  3841. ** columns of a table.
  3842. ** ^When a table is referenced by a [SELECT] but no column values are
  3843. ** extracted from that table (for example in a query like
  3844. ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
  3845. ** is invoked once for that table with a column name that is an empty string.
  3846. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  3847. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  3848. ** [truncate optimization] is disabled and all rows are deleted individually.
  3849. **
  3850. ** An authorizer is used when [sqlite3_prepare | preparing]
  3851. ** SQL statements from an untrusted source, to ensure that the SQL statements
  3852. ** do not try to access data they are not allowed to see, or that they do not
  3853. ** try to execute malicious statements that damage the database. For
  3854. ** example, an application may allow a user to enter arbitrary
  3855. ** SQL queries for evaluation by a database. But the application does
  3856. ** not want the user to be able to make arbitrary changes to the
  3857. ** database. An authorizer could then be put in place while the
  3858. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  3859. ** disallows everything except [SELECT] statements.
  3860. **
  3861. ** Applications that need to process SQL from untrusted sources
  3862. ** might also consider lowering resource limits using [sqlite3_limit()]
  3863. ** and limiting database size using the [max_page_count] [PRAGMA]
  3864. ** in addition to using an authorizer.
  3865. **
  3866. ** ^(Only a single authorizer can be in place on a database connection
  3867. ** at a time. Each call to sqlite3_set_authorizer overrides the
  3868. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  3869. ** The authorizer is disabled by default.
  3870. **
  3871. ** The authorizer callback must not do anything that will modify
  3872. ** the database connection that invoked the authorizer callback.
  3873. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3874. ** database connections for the meaning of "modify" in this paragraph.
  3875. **
  3876. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  3877. ** statement might be re-prepared during [sqlite3_step()] due to a
  3878. ** schema change. Hence, the application should ensure that the
  3879. ** correct authorizer callback remains in place during the [sqlite3_step()].
  3880. **
  3881. ** ^Note that the authorizer callback is invoked only during
  3882. ** [sqlite3_prepare()] or its variants. Authorization is not
  3883. ** performed during statement evaluation in [sqlite3_step()], unless
  3884. ** as stated in the previous paragraph, sqlite3_step() invokes
  3885. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  3886. */
  3887. SQLITE_API int sqlite3_set_authorizer(
  3888. sqlite3*,
  3889. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  3890. void *pUserData
  3891. );
  3892. /*
  3893. ** CAPI3REF: Authorizer Return Codes
  3894. **
  3895. ** The [sqlite3_set_authorizer | authorizer callback function] must
  3896. ** return either [SQLITE_OK] or one of these two constants in order
  3897. ** to signal SQLite whether or not the action is permitted. See the
  3898. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  3899. ** information.
  3900. **
  3901. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  3902. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  3903. */
  3904. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  3905. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  3906. /*
  3907. ** CAPI3REF: Authorizer Action Codes
  3908. **
  3909. ** The [sqlite3_set_authorizer()] interface registers a callback function
  3910. ** that is invoked to authorize certain SQL statement actions. The
  3911. ** second parameter to the callback is an integer code that specifies
  3912. ** what action is being authorized. These are the integer action codes that
  3913. ** the authorizer callback may be passed.
  3914. **
  3915. ** These action code values signify what kind of operation is to be
  3916. ** authorized. The 3rd and 4th parameters to the authorization
  3917. ** callback function will be parameters or NULL depending on which of these
  3918. ** codes is used as the second parameter. ^(The 5th parameter to the
  3919. ** authorizer callback is the name of the database ("main", "temp",
  3920. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  3921. ** is the name of the inner-most trigger or view that is responsible for
  3922. ** the access attempt or NULL if this access attempt is directly from
  3923. ** top-level SQL code.
  3924. */
  3925. /******************************************* 3rd ************ 4th ***********/
  3926. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  3927. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  3928. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  3929. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  3930. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  3931. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  3932. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  3933. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  3934. #define SQLITE_DELETE 9 /* Table Name NULL */
  3935. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  3936. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  3937. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  3938. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  3939. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  3940. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  3941. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  3942. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  3943. #define SQLITE_INSERT 18 /* Table Name NULL */
  3944. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  3945. #define SQLITE_READ 20 /* Table Name Column Name */
  3946. #define SQLITE_SELECT 21 /* NULL NULL */
  3947. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  3948. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  3949. #define SQLITE_ATTACH 24 /* Filename NULL */
  3950. #define SQLITE_DETACH 25 /* Database Name NULL */
  3951. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  3952. #define SQLITE_REINDEX 27 /* Index Name NULL */
  3953. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  3954. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  3955. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  3956. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  3957. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  3958. #define SQLITE_COPY 0 /* No longer used */
  3959. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  3960. /*
  3961. ** CAPI3REF: Tracing And Profiling Functions
  3962. ** METHOD: sqlite3
  3963. **
  3964. ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
  3965. ** instead of the routines described here.
  3966. **
  3967. ** These routines register callback functions that can be used for
  3968. ** tracing and profiling the execution of SQL statements.
  3969. **
  3970. ** ^The callback function registered by sqlite3_trace() is invoked at
  3971. ** various times when an SQL statement is being run by [sqlite3_step()].
  3972. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  3973. ** SQL statement text as the statement first begins executing.
  3974. ** ^(Additional sqlite3_trace() callbacks might occur
  3975. ** as each triggered subprogram is entered. The callbacks for triggers
  3976. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  3977. **
  3978. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  3979. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  3980. **
  3981. ** ^The callback function registered by sqlite3_profile() is invoked
  3982. ** as each SQL statement finishes. ^The profile callback contains
  3983. ** the original statement text and an estimate of wall-clock time
  3984. ** of how long that statement took to run. ^The profile callback
  3985. ** time is in units of nanoseconds, however the current implementation
  3986. ** is only capable of millisecond resolution so the six least significant
  3987. ** digits in the time are meaningless. Future versions of SQLite
  3988. ** might provide greater resolution on the profiler callback. Invoking
  3989. ** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the
  3990. ** profile callback.
  3991. */
  3992. SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
  3993. void(*xTrace)(void*,const char*), void*);
  3994. SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
  3995. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  3996. /*
  3997. ** CAPI3REF: SQL Trace Event Codes
  3998. ** KEYWORDS: SQLITE_TRACE
  3999. **
  4000. ** These constants identify classes of events that can be monitored
  4001. ** using the [sqlite3_trace_v2()] tracing logic. The M argument
  4002. ** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
  4003. ** the following constants. ^The first argument to the trace callback
  4004. ** is one of the following constants.
  4005. **
  4006. ** New tracing constants may be added in future releases.
  4007. **
  4008. ** ^A trace callback has four arguments: xCallback(T,C,P,X).
  4009. ** ^The T argument is one of the integer type codes above.
  4010. ** ^The C argument is a copy of the context pointer passed in as the
  4011. ** fourth argument to [sqlite3_trace_v2()].
  4012. ** The P and X arguments are pointers whose meanings depend on T.
  4013. **
  4014. ** <dl>
  4015. ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
  4016. ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
  4017. ** first begins running and possibly at other times during the
  4018. ** execution of the prepared statement, such as at the start of each
  4019. ** trigger subprogram. ^The P argument is a pointer to the
  4020. ** [prepared statement]. ^The X argument is a pointer to a string which
  4021. ** is the unexpanded SQL text of the prepared statement or an SQL comment
  4022. ** that indicates the invocation of a trigger. ^The callback can compute
  4023. ** the same text that would have been returned by the legacy [sqlite3_trace()]
  4024. ** interface by using the X argument when X begins with "--" and invoking
  4025. ** [sqlite3_expanded_sql(P)] otherwise.
  4026. **
  4027. ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
  4028. ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
  4029. ** information as is provided by the [sqlite3_profile()] callback.
  4030. ** ^The P argument is a pointer to the [prepared statement] and the
  4031. ** X argument points to a 64-bit integer which is the estimated of
  4032. ** the number of nanosecond that the prepared statement took to run.
  4033. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
  4034. **
  4035. ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
  4036. ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
  4037. ** statement generates a single row of result.
  4038. ** ^The P argument is a pointer to the [prepared statement] and the
  4039. ** X argument is unused.
  4040. **
  4041. ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
  4042. ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
  4043. ** connection closes.
  4044. ** ^The P argument is a pointer to the [database connection] object
  4045. ** and the X argument is unused.
  4046. ** </dl>
  4047. */
  4048. #define SQLITE_TRACE_STMT 0x01
  4049. #define SQLITE_TRACE_PROFILE 0x02
  4050. #define SQLITE_TRACE_ROW 0x04
  4051. #define SQLITE_TRACE_CLOSE 0x08
  4052. /*
  4053. ** CAPI3REF: SQL Trace Hook
  4054. ** METHOD: sqlite3
  4055. **
  4056. ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
  4057. ** function X against [database connection] D, using property mask M
  4058. ** and context pointer P. ^If the X callback is
  4059. ** NULL or if the M mask is zero, then tracing is disabled. The
  4060. ** M argument should be the bitwise OR-ed combination of
  4061. ** zero or more [SQLITE_TRACE] constants.
  4062. **
  4063. ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
  4064. ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
  4065. **
  4066. ** ^The X callback is invoked whenever any of the events identified by
  4067. ** mask M occur. ^The integer return value from the callback is currently
  4068. ** ignored, though this may change in future releases. Callback
  4069. ** implementations should return zero to ensure future compatibility.
  4070. **
  4071. ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
  4072. ** ^The T argument is one of the [SQLITE_TRACE]
  4073. ** constants to indicate why the callback was invoked.
  4074. ** ^The C argument is a copy of the context pointer.
  4075. ** The P and X arguments are pointers whose meanings depend on T.
  4076. **
  4077. ** The sqlite3_trace_v2() interface is intended to replace the legacy
  4078. ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
  4079. ** are deprecated.
  4080. */
  4081. SQLITE_API int sqlite3_trace_v2(
  4082. sqlite3*,
  4083. unsigned uMask,
  4084. int(*xCallback)(unsigned,void*,void*,void*),
  4085. void *pCtx
  4086. );
  4087. /*
  4088. ** CAPI3REF: Query Progress Callbacks
  4089. ** METHOD: sqlite3
  4090. **
  4091. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  4092. ** function X to be invoked periodically during long running calls to
  4093. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  4094. ** database connection D. An example use for this
  4095. ** interface is to keep a GUI updated during a large query.
  4096. **
  4097. ** ^The parameter P is passed through as the only parameter to the
  4098. ** callback function X. ^The parameter N is the approximate number of
  4099. ** [virtual machine instructions] that are evaluated between successive
  4100. ** invocations of the callback X. ^If N is less than one then the progress
  4101. ** handler is disabled.
  4102. **
  4103. ** ^Only a single progress handler may be defined at one time per
  4104. ** [database connection]; setting a new progress handler cancels the
  4105. ** old one. ^Setting parameter X to NULL disables the progress handler.
  4106. ** ^The progress handler is also disabled by setting N to a value less
  4107. ** than 1.
  4108. **
  4109. ** ^If the progress callback returns non-zero, the operation is
  4110. ** interrupted. This feature can be used to implement a
  4111. ** "Cancel" button on a GUI progress dialog box.
  4112. **
  4113. ** The progress handler callback must not do anything that will modify
  4114. ** the database connection that invoked the progress handler.
  4115. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4116. ** database connections for the meaning of "modify" in this paragraph.
  4117. **
  4118. */
  4119. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  4120. /*
  4121. ** CAPI3REF: Opening A New Database Connection
  4122. ** CONSTRUCTOR: sqlite3
  4123. **
  4124. ** ^These routines open an SQLite database file as specified by the
  4125. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  4126. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  4127. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  4128. ** returned in *ppDb, even if an error occurs. The only exception is that
  4129. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  4130. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  4131. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  4132. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  4133. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  4134. ** an English language description of the error following a failure of any
  4135. ** of the sqlite3_open() routines.
  4136. **
  4137. ** ^The default encoding will be UTF-8 for databases created using
  4138. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  4139. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  4140. **
  4141. ** Whether or not an error occurs when it is opened, resources
  4142. ** associated with the [database connection] handle should be released by
  4143. ** passing it to [sqlite3_close()] when it is no longer required.
  4144. **
  4145. ** The sqlite3_open_v2() interface works like sqlite3_open()
  4146. ** except that it accepts two additional parameters for additional control
  4147. ** over the new database connection. ^(The flags parameter to
  4148. ** sqlite3_open_v2() can take one of
  4149. ** the following three values, optionally combined with the
  4150. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  4151. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  4152. **
  4153. ** <dl>
  4154. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  4155. ** <dd>The database is opened in read-only mode. If the database does not
  4156. ** already exist, an error is returned.</dd>)^
  4157. **
  4158. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  4159. ** <dd>The database is opened for reading and writing if possible, or reading
  4160. ** only if the file is write protected by the operating system. In either
  4161. ** case the database must already exist, otherwise an error is returned.</dd>)^
  4162. **
  4163. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  4164. ** <dd>The database is opened for reading and writing, and is created if
  4165. ** it does not already exist. This is the behavior that is always used for
  4166. ** sqlite3_open() and sqlite3_open16().</dd>)^
  4167. ** </dl>
  4168. **
  4169. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  4170. ** combinations shown above optionally combined with other
  4171. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  4172. ** then the behavior is undefined.
  4173. **
  4174. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  4175. ** opens in the multi-thread [threading mode] as long as the single-thread
  4176. ** mode has not been set at compile-time or start-time. ^If the
  4177. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  4178. ** in the serialized [threading mode] unless single-thread was
  4179. ** previously selected at compile-time or start-time.
  4180. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  4181. ** eligible to use [shared cache mode], regardless of whether or not shared
  4182. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  4183. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  4184. ** participate in [shared cache mode] even if it is enabled.
  4185. **
  4186. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  4187. ** [sqlite3_vfs] object that defines the operating system interface that
  4188. ** the new database connection should use. ^If the fourth parameter is
  4189. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  4190. **
  4191. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  4192. ** is created for the connection. ^This in-memory database will vanish when
  4193. ** the database connection is closed. Future versions of SQLite might
  4194. ** make use of additional special filenames that begin with the ":" character.
  4195. ** It is recommended that when a database filename actually does begin with
  4196. ** a ":" character you should prefix the filename with a pathname such as
  4197. ** "./" to avoid ambiguity.
  4198. **
  4199. ** ^If the filename is an empty string, then a private, temporary
  4200. ** on-disk database will be created. ^This private database will be
  4201. ** automatically deleted as soon as the database connection is closed.
  4202. **
  4203. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  4204. **
  4205. ** ^If [URI filename] interpretation is enabled, and the filename argument
  4206. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  4207. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  4208. ** set in the third argument to sqlite3_open_v2(), or if it has
  4209. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  4210. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  4211. ** URI filename interpretation is turned off
  4212. ** by default, but future releases of SQLite might enable URI filename
  4213. ** interpretation by default. See "[URI filenames]" for additional
  4214. ** information.
  4215. **
  4216. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  4217. ** authority, then it must be either an empty string or the string
  4218. ** "localhost". ^If the authority is not an empty string or "localhost", an
  4219. ** error is returned to the caller. ^The fragment component of a URI, if
  4220. ** present, is ignored.
  4221. **
  4222. ** ^SQLite uses the path component of the URI as the name of the disk file
  4223. ** which contains the database. ^If the path begins with a '/' character,
  4224. ** then it is interpreted as an absolute path. ^If the path does not begin
  4225. ** with a '/' (meaning that the authority section is omitted from the URI)
  4226. ** then the path is interpreted as a relative path.
  4227. ** ^(On windows, the first component of an absolute path
  4228. ** is a drive specification (e.g. "C:").)^
  4229. **
  4230. ** [[core URI query parameters]]
  4231. ** The query component of a URI may contain parameters that are interpreted
  4232. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  4233. ** SQLite and its built-in [VFSes] interpret the
  4234. ** following query parameters:
  4235. **
  4236. ** <ul>
  4237. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  4238. ** a VFS object that provides the operating system interface that should
  4239. ** be used to access the database file on disk. ^If this option is set to
  4240. ** an empty string the default VFS object is used. ^Specifying an unknown
  4241. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  4242. ** present, then the VFS specified by the option takes precedence over
  4243. ** the value passed as the fourth parameter to sqlite3_open_v2().
  4244. **
  4245. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  4246. ** "rwc", or "memory". Attempting to set it to any other value is
  4247. ** an error)^.
  4248. ** ^If "ro" is specified, then the database is opened for read-only
  4249. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  4250. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  4251. ** "rw", then the database is opened for read-write (but not create)
  4252. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  4253. ** been set. ^Value "rwc" is equivalent to setting both
  4254. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  4255. ** set to "memory" then a pure [in-memory database] that never reads
  4256. ** or writes from disk is used. ^It is an error to specify a value for
  4257. ** the mode parameter that is less restrictive than that specified by
  4258. ** the flags passed in the third parameter to sqlite3_open_v2().
  4259. **
  4260. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  4261. ** "private". ^Setting it to "shared" is equivalent to setting the
  4262. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  4263. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  4264. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  4265. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  4266. ** a URI filename, its value overrides any behavior requested by setting
  4267. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  4268. **
  4269. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  4270. ** [powersafe overwrite] property does or does not apply to the
  4271. ** storage media on which the database file resides.
  4272. **
  4273. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  4274. ** which if set disables file locking in rollback journal modes. This
  4275. ** is useful for accessing a database on a filesystem that does not
  4276. ** support locking. Caution: Database corruption might result if two
  4277. ** or more processes write to the same database and any one of those
  4278. ** processes uses nolock=1.
  4279. **
  4280. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  4281. ** parameter that indicates that the database file is stored on
  4282. ** read-only media. ^When immutable is set, SQLite assumes that the
  4283. ** database file cannot be changed, even by a process with higher
  4284. ** privilege, and so the database is opened read-only and all locking
  4285. ** and change detection is disabled. Caution: Setting the immutable
  4286. ** property on a database file that does in fact change can result
  4287. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  4288. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  4289. **
  4290. ** </ul>
  4291. **
  4292. ** ^Specifying an unknown parameter in the query component of a URI is not an
  4293. ** error. Future versions of SQLite might understand additional query
  4294. ** parameters. See "[query parameters with special meaning to SQLite]" for
  4295. ** additional information.
  4296. **
  4297. ** [[URI filename examples]] <h3>URI filename examples</h3>
  4298. **
  4299. ** <table border="1" align=center cellpadding=5>
  4300. ** <tr><th> URI filenames <th> Results
  4301. ** <tr><td> file:data.db <td>
  4302. ** Open the file "data.db" in the current directory.
  4303. ** <tr><td> file:/home/fred/data.db<br>
  4304. ** file:///home/fred/data.db <br>
  4305. ** file://localhost/home/fred/data.db <br> <td>
  4306. ** Open the database file "/home/fred/data.db".
  4307. ** <tr><td> file://darkstar/home/fred/data.db <td>
  4308. ** An error. "darkstar" is not a recognized authority.
  4309. ** <tr><td style="white-space:nowrap">
  4310. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  4311. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  4312. ** C:. Note that the %20 escaping in this example is not strictly
  4313. ** necessary - space characters can be used literally
  4314. ** in URI filenames.
  4315. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  4316. ** Open file "data.db" in the current directory for read-only access.
  4317. ** Regardless of whether or not shared-cache mode is enabled by
  4318. ** default, use a private cache.
  4319. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  4320. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  4321. ** that uses dot-files in place of posix advisory locking.
  4322. ** <tr><td> file:data.db?mode=readonly <td>
  4323. ** An error. "readonly" is not a valid option for the "mode" parameter.
  4324. ** </table>
  4325. **
  4326. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  4327. ** query components of a URI. A hexadecimal escape sequence consists of a
  4328. ** percent sign - "%" - followed by exactly two hexadecimal digits
  4329. ** specifying an octet value. ^Before the path or query components of a
  4330. ** URI filename are interpreted, they are encoded using UTF-8 and all
  4331. ** hexadecimal escape sequences replaced by a single byte containing the
  4332. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  4333. ** the results are undefined.
  4334. **
  4335. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  4336. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  4337. ** codepage is currently defined. Filenames containing international
  4338. ** characters must be converted to UTF-8 prior to passing them into
  4339. ** sqlite3_open() or sqlite3_open_v2().
  4340. **
  4341. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4342. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  4343. ** features that require the use of temporary files may fail.
  4344. **
  4345. ** See also: [sqlite3_temp_directory]
  4346. */
  4347. SQLITE_API int sqlite3_open(
  4348. const char *filename, /* Database filename (UTF-8) */
  4349. sqlite3 **ppDb /* OUT: SQLite db handle */
  4350. );
  4351. SQLITE_API int sqlite3_open16(
  4352. const void *filename, /* Database filename (UTF-16) */
  4353. sqlite3 **ppDb /* OUT: SQLite db handle */
  4354. );
  4355. SQLITE_API int sqlite3_open_v2(
  4356. const char *filename, /* Database filename (UTF-8) */
  4357. sqlite3 **ppDb, /* OUT: SQLite db handle */
  4358. int flags, /* Flags */
  4359. const char *zVfs /* Name of VFS module to use */
  4360. );
  4361. /*
  4362. ** CAPI3REF: Obtain Values For URI Parameters
  4363. **
  4364. ** These are utility routines, useful to VFS implementations, that check
  4365. ** to see if a database file was a URI that contained a specific query
  4366. ** parameter, and if so obtains the value of that query parameter.
  4367. **
  4368. ** If F is the database filename pointer passed into the xOpen() method of
  4369. ** a VFS implementation when the flags parameter to xOpen() has one or
  4370. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  4371. ** P is the name of the query parameter, then
  4372. ** sqlite3_uri_parameter(F,P) returns the value of the P
  4373. ** parameter if it exists or a NULL pointer if P does not appear as a
  4374. ** query parameter on F. If P is a query parameter of F
  4375. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  4376. ** a pointer to an empty string.
  4377. **
  4378. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  4379. ** parameter and returns true (1) or false (0) according to the value
  4380. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  4381. ** value of query parameter P is one of "yes", "true", or "on" in any
  4382. ** case or if the value begins with a non-zero number. The
  4383. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  4384. ** query parameter P is one of "no", "false", or "off" in any case or
  4385. ** if the value begins with a numeric zero. If P is not a query
  4386. ** parameter on F or if the value of P is does not match any of the
  4387. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  4388. **
  4389. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  4390. ** 64-bit signed integer and returns that integer, or D if P does not
  4391. ** exist. If the value of P is something other than an integer, then
  4392. ** zero is returned.
  4393. **
  4394. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  4395. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  4396. ** is not a database file pathname pointer that SQLite passed into the xOpen
  4397. ** VFS method, then the behavior of this routine is undefined and probably
  4398. ** undesirable.
  4399. **
  4400. ** See the [URI filename] documentation for additional information.
  4401. */
  4402. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  4403. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  4404. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  4405. /*
  4406. ** CAPI3REF: Error Codes And Messages
  4407. ** METHOD: sqlite3
  4408. **
  4409. ** ^If the most recent sqlite3_* API call associated with
  4410. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  4411. ** returns the numeric [result code] or [extended result code] for that
  4412. ** API call.
  4413. ** ^The sqlite3_extended_errcode()
  4414. ** interface is the same except that it always returns the
  4415. ** [extended result code] even when extended result codes are
  4416. ** disabled.
  4417. **
  4418. ** The values returned by sqlite3_errcode() and/or
  4419. ** sqlite3_extended_errcode() might change with each API call.
  4420. ** Except, there are some interfaces that are guaranteed to never
  4421. ** change the value of the error code. The error-code preserving
  4422. ** interfaces are:
  4423. **
  4424. ** <ul>
  4425. ** <li> sqlite3_errcode()
  4426. ** <li> sqlite3_extended_errcode()
  4427. ** <li> sqlite3_errmsg()
  4428. ** <li> sqlite3_errmsg16()
  4429. ** </ul>
  4430. **
  4431. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  4432. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  4433. ** ^(Memory to hold the error message string is managed internally.
  4434. ** The application does not need to worry about freeing the result.
  4435. ** However, the error string might be overwritten or deallocated by
  4436. ** subsequent calls to other SQLite interface functions.)^
  4437. **
  4438. ** ^The sqlite3_errstr() interface returns the English-language text
  4439. ** that describes the [result code], as UTF-8.
  4440. ** ^(Memory to hold the error message string is managed internally
  4441. ** and must not be freed by the application)^.
  4442. **
  4443. ** When the serialized [threading mode] is in use, it might be the
  4444. ** case that a second error occurs on a separate thread in between
  4445. ** the time of the first error and the call to these interfaces.
  4446. ** When that happens, the second error will be reported since these
  4447. ** interfaces always report the most recent result. To avoid
  4448. ** this, each thread can obtain exclusive use of the [database connection] D
  4449. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  4450. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  4451. ** all calls to the interfaces listed here are completed.
  4452. **
  4453. ** If an interface fails with SQLITE_MISUSE, that means the interface
  4454. ** was invoked incorrectly by the application. In that case, the
  4455. ** error code and message may or may not be set.
  4456. */
  4457. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  4458. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  4459. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  4460. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  4461. SQLITE_API const char *sqlite3_errstr(int);
  4462. /*
  4463. ** CAPI3REF: Prepared Statement Object
  4464. ** KEYWORDS: {prepared statement} {prepared statements}
  4465. **
  4466. ** An instance of this object represents a single SQL statement that
  4467. ** has been compiled into binary form and is ready to be evaluated.
  4468. **
  4469. ** Think of each SQL statement as a separate computer program. The
  4470. ** original SQL text is source code. A prepared statement object
  4471. ** is the compiled object code. All SQL must be converted into a
  4472. ** prepared statement before it can be run.
  4473. **
  4474. ** The life-cycle of a prepared statement object usually goes like this:
  4475. **
  4476. ** <ol>
  4477. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  4478. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  4479. ** interfaces.
  4480. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  4481. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  4482. ** to step 2. Do this zero or more times.
  4483. ** <li> Destroy the object using [sqlite3_finalize()].
  4484. ** </ol>
  4485. */
  4486. typedef struct sqlite3_stmt sqlite3_stmt;
  4487. /*
  4488. ** CAPI3REF: Run-time Limits
  4489. ** METHOD: sqlite3
  4490. **
  4491. ** ^(This interface allows the size of various constructs to be limited
  4492. ** on a connection by connection basis. The first parameter is the
  4493. ** [database connection] whose limit is to be set or queried. The
  4494. ** second parameter is one of the [limit categories] that define a
  4495. ** class of constructs to be size limited. The third parameter is the
  4496. ** new limit for that construct.)^
  4497. **
  4498. ** ^If the new limit is a negative number, the limit is unchanged.
  4499. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  4500. ** [limits | hard upper bound]
  4501. ** set at compile-time by a C preprocessor macro called
  4502. ** [limits | SQLITE_MAX_<i>NAME</i>].
  4503. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  4504. ** ^Attempts to increase a limit above its hard upper bound are
  4505. ** silently truncated to the hard upper bound.
  4506. **
  4507. ** ^Regardless of whether or not the limit was changed, the
  4508. ** [sqlite3_limit()] interface returns the prior value of the limit.
  4509. ** ^Hence, to find the current value of a limit without changing it,
  4510. ** simply invoke this interface with the third parameter set to -1.
  4511. **
  4512. ** Run-time limits are intended for use in applications that manage
  4513. ** both their own internal database and also databases that are controlled
  4514. ** by untrusted external sources. An example application might be a
  4515. ** web browser that has its own databases for storing history and
  4516. ** separate databases controlled by JavaScript applications downloaded
  4517. ** off the Internet. The internal databases can be given the
  4518. ** large, default limits. Databases managed by external sources can
  4519. ** be given much smaller limits designed to prevent a denial of service
  4520. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  4521. ** interface to further control untrusted SQL. The size of the database
  4522. ** created by an untrusted script can be contained using the
  4523. ** [max_page_count] [PRAGMA].
  4524. **
  4525. ** New run-time limit categories may be added in future releases.
  4526. */
  4527. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  4528. /*
  4529. ** CAPI3REF: Run-Time Limit Categories
  4530. ** KEYWORDS: {limit category} {*limit categories}
  4531. **
  4532. ** These constants define various performance limits
  4533. ** that can be lowered at run-time using [sqlite3_limit()].
  4534. ** The synopsis of the meanings of the various limits is shown below.
  4535. ** Additional information is available at [limits | Limits in SQLite].
  4536. **
  4537. ** <dl>
  4538. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  4539. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  4540. **
  4541. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  4542. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  4543. **
  4544. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  4545. ** <dd>The maximum number of columns in a table definition or in the
  4546. ** result set of a [SELECT] or the maximum number of columns in an index
  4547. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  4548. **
  4549. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  4550. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  4551. **
  4552. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  4553. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  4554. **
  4555. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  4556. ** <dd>The maximum number of instructions in a virtual machine program
  4557. ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
  4558. ** the equivalent tries to allocate space for more than this many opcodes
  4559. ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
  4560. **
  4561. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  4562. ** <dd>The maximum number of arguments on a function.</dd>)^
  4563. **
  4564. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  4565. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  4566. **
  4567. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  4568. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  4569. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  4570. ** [GLOB] operators.</dd>)^
  4571. **
  4572. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  4573. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  4574. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  4575. **
  4576. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  4577. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  4578. **
  4579. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  4580. ** <dd>The maximum number of auxiliary worker threads that a single
  4581. ** [prepared statement] may start.</dd>)^
  4582. ** </dl>
  4583. */
  4584. #define SQLITE_LIMIT_LENGTH 0
  4585. #define SQLITE_LIMIT_SQL_LENGTH 1
  4586. #define SQLITE_LIMIT_COLUMN 2
  4587. #define SQLITE_LIMIT_EXPR_DEPTH 3
  4588. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  4589. #define SQLITE_LIMIT_VDBE_OP 5
  4590. #define SQLITE_LIMIT_FUNCTION_ARG 6
  4591. #define SQLITE_LIMIT_ATTACHED 7
  4592. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  4593. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  4594. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  4595. #define SQLITE_LIMIT_WORKER_THREADS 11
  4596. /*
  4597. ** CAPI3REF: Prepare Flags
  4598. **
  4599. ** These constants define various flags that can be passed into
  4600. ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
  4601. ** [sqlite3_prepare16_v3()] interfaces.
  4602. **
  4603. ** New flags may be added in future releases of SQLite.
  4604. **
  4605. ** <dl>
  4606. ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
  4607. ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
  4608. ** that the prepared statement will be retained for a long time and
  4609. ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
  4610. ** and [sqlite3_prepare16_v3()] assume that the prepared statement will
  4611. ** be used just once or at most a few times and then destroyed using
  4612. ** [sqlite3_finalize()] relatively soon. The current implementation acts
  4613. ** on this hint by avoiding the use of [lookaside memory] so as not to
  4614. ** deplete the limited store of lookaside memory. Future versions of
  4615. ** SQLite may act on this hint differently.
  4616. **
  4617. ** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>
  4618. ** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
  4619. ** to be required for any prepared statement that wanted to use the
  4620. ** [sqlite3_normalized_sql()] interface. However, the
  4621. ** [sqlite3_normalized_sql()] interface is now available to all
  4622. ** prepared statements, regardless of whether or not they use this
  4623. ** flag.
  4624. **
  4625. ** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>
  4626. ** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler
  4627. ** to return an error (error code SQLITE_ERROR) if the statement uses
  4628. ** any virtual tables.
  4629. ** </dl>
  4630. */
  4631. #define SQLITE_PREPARE_PERSISTENT 0x01
  4632. #define SQLITE_PREPARE_NORMALIZE 0x02
  4633. #define SQLITE_PREPARE_NO_VTAB 0x04
  4634. /*
  4635. ** CAPI3REF: Compiling An SQL Statement
  4636. ** KEYWORDS: {SQL statement compiler}
  4637. ** METHOD: sqlite3
  4638. ** CONSTRUCTOR: sqlite3_stmt
  4639. **
  4640. ** To execute an SQL statement, it must first be compiled into a byte-code
  4641. ** program using one of these routines. Or, in other words, these routines
  4642. ** are constructors for the [prepared statement] object.
  4643. **
  4644. ** The preferred routine to use is [sqlite3_prepare_v2()]. The
  4645. ** [sqlite3_prepare()] interface is legacy and should be avoided.
  4646. ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
  4647. ** for special purposes.
  4648. **
  4649. ** The use of the UTF-8 interfaces is preferred, as SQLite currently
  4650. ** does all parsing using UTF-8. The UTF-16 interfaces are provided
  4651. ** as a convenience. The UTF-16 interfaces work by converting the
  4652. ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
  4653. **
  4654. ** The first argument, "db", is a [database connection] obtained from a
  4655. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  4656. ** [sqlite3_open16()]. The database connection must not have been closed.
  4657. **
  4658. ** The second argument, "zSql", is the statement to be compiled, encoded
  4659. ** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
  4660. ** and sqlite3_prepare_v3()
  4661. ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
  4662. ** and sqlite3_prepare16_v3() use UTF-16.
  4663. **
  4664. ** ^If the nByte argument is negative, then zSql is read up to the
  4665. ** first zero terminator. ^If nByte is positive, then it is the
  4666. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  4667. ** statement is generated.
  4668. ** If the caller knows that the supplied string is nul-terminated, then
  4669. ** there is a small performance advantage to passing an nByte parameter that
  4670. ** is the number of bytes in the input string <i>including</i>
  4671. ** the nul-terminator.
  4672. **
  4673. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  4674. ** past the end of the first SQL statement in zSql. These routines only
  4675. ** compile the first statement in zSql, so *pzTail is left pointing to
  4676. ** what remains uncompiled.
  4677. **
  4678. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  4679. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  4680. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  4681. ** string or a comment) then *ppStmt is set to NULL.
  4682. ** The calling procedure is responsible for deleting the compiled
  4683. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  4684. ** ppStmt may not be NULL.
  4685. **
  4686. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  4687. ** otherwise an [error code] is returned.
  4688. **
  4689. ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
  4690. ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
  4691. ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
  4692. ** are retained for backwards compatibility, but their use is discouraged.
  4693. ** ^In the "vX" interfaces, the prepared statement
  4694. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  4695. ** original SQL text. This causes the [sqlite3_step()] interface to
  4696. ** behave differently in three ways:
  4697. **
  4698. ** <ol>
  4699. ** <li>
  4700. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  4701. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  4702. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  4703. ** retries will occur before sqlite3_step() gives up and returns an error.
  4704. ** </li>
  4705. **
  4706. ** <li>
  4707. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  4708. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  4709. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  4710. ** and the application would have to make a second call to [sqlite3_reset()]
  4711. ** in order to find the underlying cause of the problem. With the "v2" prepare
  4712. ** interfaces, the underlying reason for the error is returned immediately.
  4713. ** </li>
  4714. **
  4715. ** <li>
  4716. ** ^If the specific value bound to [parameter | host parameter] in the
  4717. ** WHERE clause might influence the choice of query plan for a statement,
  4718. ** then the statement will be automatically recompiled, as if there had been
  4719. ** a schema change, on the first [sqlite3_step()] call following any change
  4720. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  4721. ** ^The specific value of WHERE-clause [parameter] might influence the
  4722. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  4723. ** or [GLOB] operator or if the parameter is compared to an indexed column
  4724. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  4725. ** </li>
  4726. ** </ol>
  4727. **
  4728. ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
  4729. ** the extra prepFlags parameter, which is a bit array consisting of zero or
  4730. ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
  4731. ** sqlite3_prepare_v2() interface works exactly the same as
  4732. ** sqlite3_prepare_v3() with a zero prepFlags parameter.
  4733. */
  4734. SQLITE_API int sqlite3_prepare(
  4735. sqlite3 *db, /* Database handle */
  4736. const char *zSql, /* SQL statement, UTF-8 encoded */
  4737. int nByte, /* Maximum length of zSql in bytes. */
  4738. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4739. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4740. );
  4741. SQLITE_API int sqlite3_prepare_v2(
  4742. sqlite3 *db, /* Database handle */
  4743. const char *zSql, /* SQL statement, UTF-8 encoded */
  4744. int nByte, /* Maximum length of zSql in bytes. */
  4745. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4746. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4747. );
  4748. SQLITE_API int sqlite3_prepare_v3(
  4749. sqlite3 *db, /* Database handle */
  4750. const char *zSql, /* SQL statement, UTF-8 encoded */
  4751. int nByte, /* Maximum length of zSql in bytes. */
  4752. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4753. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4754. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4755. );
  4756. SQLITE_API int sqlite3_prepare16(
  4757. sqlite3 *db, /* Database handle */
  4758. const void *zSql, /* SQL statement, UTF-16 encoded */
  4759. int nByte, /* Maximum length of zSql in bytes. */
  4760. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4761. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4762. );
  4763. SQLITE_API int sqlite3_prepare16_v2(
  4764. sqlite3 *db, /* Database handle */
  4765. const void *zSql, /* SQL statement, UTF-16 encoded */
  4766. int nByte, /* Maximum length of zSql in bytes. */
  4767. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4768. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4769. );
  4770. SQLITE_API int sqlite3_prepare16_v3(
  4771. sqlite3 *db, /* Database handle */
  4772. const void *zSql, /* SQL statement, UTF-16 encoded */
  4773. int nByte, /* Maximum length of zSql in bytes. */
  4774. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4775. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4776. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4777. );
  4778. /*
  4779. ** CAPI3REF: Retrieving Statement SQL
  4780. ** METHOD: sqlite3_stmt
  4781. **
  4782. ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  4783. ** SQL text used to create [prepared statement] P if P was
  4784. ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
  4785. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4786. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  4787. ** string containing the SQL text of prepared statement P with
  4788. ** [bound parameters] expanded.
  4789. ** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
  4790. ** string containing the normalized SQL text of prepared statement P. The
  4791. ** semantics used to normalize a SQL statement are unspecified and subject
  4792. ** to change. At a minimum, literal values will be replaced with suitable
  4793. ** placeholders.
  4794. **
  4795. ** ^(For example, if a prepared statement is created using the SQL
  4796. ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  4797. ** and parameter :xyz is unbound, then sqlite3_sql() will return
  4798. ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  4799. ** will return "SELECT 2345,NULL".)^
  4800. **
  4801. ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
  4802. ** is available to hold the result, or if the result would exceed the
  4803. ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  4804. **
  4805. ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  4806. ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
  4807. ** option causes sqlite3_expanded_sql() to always return NULL.
  4808. **
  4809. ** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
  4810. ** are managed by SQLite and are automatically freed when the prepared
  4811. ** statement is finalized.
  4812. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  4813. ** is obtained from [sqlite3_malloc()] and must be free by the application
  4814. ** by passing it to [sqlite3_free()].
  4815. */
  4816. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  4817. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  4818. SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
  4819. /*
  4820. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  4821. ** METHOD: sqlite3_stmt
  4822. **
  4823. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  4824. ** and only if the [prepared statement] X makes no direct changes to
  4825. ** the content of the database file.
  4826. **
  4827. ** Note that [application-defined SQL functions] or
  4828. ** [virtual tables] might change the database indirectly as a side effect.
  4829. ** ^(For example, if an application defines a function "eval()" that
  4830. ** calls [sqlite3_exec()], then the following SQL statement would
  4831. ** change the database file through side-effects:
  4832. **
  4833. ** <blockquote><pre>
  4834. ** SELECT eval('DELETE FROM t1') FROM t2;
  4835. ** </pre></blockquote>
  4836. **
  4837. ** But because the [SELECT] statement does not change the database file
  4838. ** directly, sqlite3_stmt_readonly() would still return true.)^
  4839. **
  4840. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  4841. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  4842. ** since the statements themselves do not actually modify the database but
  4843. ** rather they control the timing of when other statements modify the
  4844. ** database. ^The [ATTACH] and [DETACH] statements also cause
  4845. ** sqlite3_stmt_readonly() to return true since, while those statements
  4846. ** change the configuration of a database connection, they do not make
  4847. ** changes to the content of the database files on disk.
  4848. ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
  4849. ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
  4850. ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
  4851. ** sqlite3_stmt_readonly() returns false for those commands.
  4852. */
  4853. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  4854. /*
  4855. ** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
  4856. ** METHOD: sqlite3_stmt
  4857. **
  4858. ** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the
  4859. ** prepared statement S is an EXPLAIN statement, or 2 if the
  4860. ** statement S is an EXPLAIN QUERY PLAN.
  4861. ** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is
  4862. ** an ordinary statement or a NULL pointer.
  4863. */
  4864. SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);
  4865. /*
  4866. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  4867. ** METHOD: sqlite3_stmt
  4868. **
  4869. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  4870. ** [prepared statement] S has been stepped at least once using
  4871. ** [sqlite3_step(S)] but has neither run to completion (returned
  4872. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  4873. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  4874. ** interface returns false if S is a NULL pointer. If S is not a
  4875. ** NULL pointer and is not a pointer to a valid [prepared statement]
  4876. ** object, then the behavior is undefined and probably undesirable.
  4877. **
  4878. ** This interface can be used in combination [sqlite3_next_stmt()]
  4879. ** to locate all prepared statements associated with a database
  4880. ** connection that are in need of being reset. This can be used,
  4881. ** for example, in diagnostic routines to search for prepared
  4882. ** statements that are holding a transaction open.
  4883. */
  4884. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  4885. /*
  4886. ** CAPI3REF: Dynamically Typed Value Object
  4887. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  4888. **
  4889. ** SQLite uses the sqlite3_value object to represent all values
  4890. ** that can be stored in a database table. SQLite uses dynamic typing
  4891. ** for the values it stores. ^Values stored in sqlite3_value objects
  4892. ** can be integers, floating point values, strings, BLOBs, or NULL.
  4893. **
  4894. ** An sqlite3_value object may be either "protected" or "unprotected".
  4895. ** Some interfaces require a protected sqlite3_value. Other interfaces
  4896. ** will accept either a protected or an unprotected sqlite3_value.
  4897. ** Every interface that accepts sqlite3_value arguments specifies
  4898. ** whether or not it requires a protected sqlite3_value. The
  4899. ** [sqlite3_value_dup()] interface can be used to construct a new
  4900. ** protected sqlite3_value from an unprotected sqlite3_value.
  4901. **
  4902. ** The terms "protected" and "unprotected" refer to whether or not
  4903. ** a mutex is held. An internal mutex is held for a protected
  4904. ** sqlite3_value object but no mutex is held for an unprotected
  4905. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  4906. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  4907. ** or if SQLite is run in one of reduced mutex modes
  4908. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  4909. ** then there is no distinction between protected and unprotected
  4910. ** sqlite3_value objects and they can be used interchangeably. However,
  4911. ** for maximum code portability it is recommended that applications
  4912. ** still make the distinction between protected and unprotected
  4913. ** sqlite3_value objects even when not strictly required.
  4914. **
  4915. ** ^The sqlite3_value objects that are passed as parameters into the
  4916. ** implementation of [application-defined SQL functions] are protected.
  4917. ** ^The sqlite3_value object returned by
  4918. ** [sqlite3_column_value()] is unprotected.
  4919. ** Unprotected sqlite3_value objects may only be used as arguments
  4920. ** to [sqlite3_result_value()], [sqlite3_bind_value()], and
  4921. ** [sqlite3_value_dup()].
  4922. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  4923. ** interfaces require protected sqlite3_value objects.
  4924. */
  4925. typedef struct sqlite3_value sqlite3_value;
  4926. /*
  4927. ** CAPI3REF: SQL Function Context Object
  4928. **
  4929. ** The context in which an SQL function executes is stored in an
  4930. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  4931. ** is always first parameter to [application-defined SQL functions].
  4932. ** The application-defined SQL function implementation will pass this
  4933. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  4934. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  4935. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  4936. ** and/or [sqlite3_set_auxdata()].
  4937. */
  4938. typedef struct sqlite3_context sqlite3_context;
  4939. /*
  4940. ** CAPI3REF: Binding Values To Prepared Statements
  4941. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  4942. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  4943. ** METHOD: sqlite3_stmt
  4944. **
  4945. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  4946. ** literals may be replaced by a [parameter] that matches one of following
  4947. ** templates:
  4948. **
  4949. ** <ul>
  4950. ** <li> ?
  4951. ** <li> ?NNN
  4952. ** <li> :VVV
  4953. ** <li> @VVV
  4954. ** <li> $VVV
  4955. ** </ul>
  4956. **
  4957. ** In the templates above, NNN represents an integer literal,
  4958. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  4959. ** parameters (also called "host parameter names" or "SQL parameters")
  4960. ** can be set using the sqlite3_bind_*() routines defined here.
  4961. **
  4962. ** ^The first argument to the sqlite3_bind_*() routines is always
  4963. ** a pointer to the [sqlite3_stmt] object returned from
  4964. ** [sqlite3_prepare_v2()] or its variants.
  4965. **
  4966. ** ^The second argument is the index of the SQL parameter to be set.
  4967. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  4968. ** SQL parameter is used more than once, second and subsequent
  4969. ** occurrences have the same index as the first occurrence.
  4970. ** ^The index for named parameters can be looked up using the
  4971. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  4972. ** for "?NNN" parameters is the value of NNN.
  4973. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  4974. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  4975. **
  4976. ** ^The third argument is the value to bind to the parameter.
  4977. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4978. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  4979. ** is ignored and the end result is the same as sqlite3_bind_null().
  4980. **
  4981. ** ^(In those routines that have a fourth argument, its value is the
  4982. ** number of bytes in the parameter. To be clear: the value is the
  4983. ** number of <u>bytes</u> in the value, not the number of characters.)^
  4984. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4985. ** is negative, then the length of the string is
  4986. ** the number of bytes up to the first zero terminator.
  4987. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  4988. ** the behavior is undefined.
  4989. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  4990. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  4991. ** that parameter must be the byte offset
  4992. ** where the NUL terminator would occur assuming the string were NUL
  4993. ** terminated. If any NUL characters occur at byte offsets less than
  4994. ** the value of the fourth parameter then the resulting string value will
  4995. ** contain embedded NULs. The result of expressions involving strings
  4996. ** with embedded NULs is undefined.
  4997. **
  4998. ** ^The fifth argument to the BLOB and string binding interfaces
  4999. ** is a destructor used to dispose of the BLOB or
  5000. ** string after SQLite has finished with it. ^The destructor is called
  5001. ** to dispose of the BLOB or string even if the call to the bind API fails,
  5002. ** except the destructor is not called if the third parameter is a NULL
  5003. ** pointer or the fourth parameter is negative.
  5004. ** ^If the fifth argument is
  5005. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  5006. ** information is in static, unmanaged space and does not need to be freed.
  5007. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  5008. ** SQLite makes its own private copy of the data immediately, before
  5009. ** the sqlite3_bind_*() routine returns.
  5010. **
  5011. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  5012. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  5013. ** to specify the encoding of the text in the third parameter. If
  5014. ** the sixth argument to sqlite3_bind_text64() is not one of the
  5015. ** allowed values shown above, or if the text encoding is different
  5016. ** from the encoding specified by the sixth parameter, then the behavior
  5017. ** is undefined.
  5018. **
  5019. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  5020. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  5021. ** (just an integer to hold its size) while it is being processed.
  5022. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  5023. ** content is later written using
  5024. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  5025. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  5026. **
  5027. ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
  5028. ** [prepared statement] S to have an SQL value of NULL, but to also be
  5029. ** associated with the pointer P of type T. ^D is either a NULL pointer or
  5030. ** a pointer to a destructor function for P. ^SQLite will invoke the
  5031. ** destructor D with a single argument of P when it is finished using
  5032. ** P. The T parameter should be a static string, preferably a string
  5033. ** literal. The sqlite3_bind_pointer() routine is part of the
  5034. ** [pointer passing interface] added for SQLite 3.20.0.
  5035. **
  5036. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  5037. ** for the [prepared statement] or with a prepared statement for which
  5038. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  5039. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  5040. ** routine is passed a [prepared statement] that has been finalized, the
  5041. ** result is undefined and probably harmful.
  5042. **
  5043. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  5044. ** ^Unbound parameters are interpreted as NULL.
  5045. **
  5046. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  5047. ** [error code] if anything goes wrong.
  5048. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  5049. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  5050. ** [SQLITE_MAX_LENGTH].
  5051. ** ^[SQLITE_RANGE] is returned if the parameter
  5052. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  5053. **
  5054. ** See also: [sqlite3_bind_parameter_count()],
  5055. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  5056. */
  5057. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  5058. SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  5059. void(*)(void*));
  5060. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  5061. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  5062. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  5063. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  5064. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  5065. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  5066. SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  5067. void(*)(void*), unsigned char encoding);
  5068. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  5069. SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
  5070. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  5071. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  5072. /*
  5073. ** CAPI3REF: Number Of SQL Parameters
  5074. ** METHOD: sqlite3_stmt
  5075. **
  5076. ** ^This routine can be used to find the number of [SQL parameters]
  5077. ** in a [prepared statement]. SQL parameters are tokens of the
  5078. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  5079. ** placeholders for values that are [sqlite3_bind_blob | bound]
  5080. ** to the parameters at a later time.
  5081. **
  5082. ** ^(This routine actually returns the index of the largest (rightmost)
  5083. ** parameter. For all forms except ?NNN, this will correspond to the
  5084. ** number of unique parameters. If parameters of the ?NNN form are used,
  5085. ** there may be gaps in the list.)^
  5086. **
  5087. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5088. ** [sqlite3_bind_parameter_name()], and
  5089. ** [sqlite3_bind_parameter_index()].
  5090. */
  5091. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  5092. /*
  5093. ** CAPI3REF: Name Of A Host Parameter
  5094. ** METHOD: sqlite3_stmt
  5095. **
  5096. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  5097. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  5098. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5099. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5100. ** respectively.
  5101. ** In other words, the initial ":" or "$" or "@" or "?"
  5102. ** is included as part of the name.)^
  5103. ** ^Parameters of the form "?" without a following integer have no name
  5104. ** and are referred to as "nameless" or "anonymous parameters".
  5105. **
  5106. ** ^The first host parameter has an index of 1, not 0.
  5107. **
  5108. ** ^If the value N is out of range or if the N-th parameter is
  5109. ** nameless, then NULL is returned. ^The returned string is
  5110. ** always in UTF-8 encoding even if the named parameter was
  5111. ** originally specified as UTF-16 in [sqlite3_prepare16()],
  5112. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  5113. **
  5114. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5115. ** [sqlite3_bind_parameter_count()], and
  5116. ** [sqlite3_bind_parameter_index()].
  5117. */
  5118. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  5119. /*
  5120. ** CAPI3REF: Index Of A Parameter With A Given Name
  5121. ** METHOD: sqlite3_stmt
  5122. **
  5123. ** ^Return the index of an SQL parameter given its name. ^The
  5124. ** index value returned is suitable for use as the second
  5125. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  5126. ** is returned if no matching parameter is found. ^The parameter
  5127. ** name must be given in UTF-8 even if the original statement
  5128. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
  5129. ** [sqlite3_prepare16_v3()].
  5130. **
  5131. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5132. ** [sqlite3_bind_parameter_count()], and
  5133. ** [sqlite3_bind_parameter_name()].
  5134. */
  5135. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  5136. /*
  5137. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  5138. ** METHOD: sqlite3_stmt
  5139. **
  5140. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  5141. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  5142. ** ^Use this routine to reset all host parameters to NULL.
  5143. */
  5144. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  5145. /*
  5146. ** CAPI3REF: Number Of Columns In A Result Set
  5147. ** METHOD: sqlite3_stmt
  5148. **
  5149. ** ^Return the number of columns in the result set returned by the
  5150. ** [prepared statement]. ^If this routine returns 0, that means the
  5151. ** [prepared statement] returns no data (for example an [UPDATE]).
  5152. ** ^However, just because this routine returns a positive number does not
  5153. ** mean that one or more rows of data will be returned. ^A SELECT statement
  5154. ** will always have a positive sqlite3_column_count() but depending on the
  5155. ** WHERE clause constraints and the table content, it might return no rows.
  5156. **
  5157. ** See also: [sqlite3_data_count()]
  5158. */
  5159. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  5160. /*
  5161. ** CAPI3REF: Column Names In A Result Set
  5162. ** METHOD: sqlite3_stmt
  5163. **
  5164. ** ^These routines return the name assigned to a particular column
  5165. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  5166. ** interface returns a pointer to a zero-terminated UTF-8 string
  5167. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  5168. ** UTF-16 string. ^The first parameter is the [prepared statement]
  5169. ** that implements the [SELECT] statement. ^The second parameter is the
  5170. ** column number. ^The leftmost column is number 0.
  5171. **
  5172. ** ^The returned string pointer is valid until either the [prepared statement]
  5173. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  5174. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5175. ** or until the next call to
  5176. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  5177. **
  5178. ** ^If sqlite3_malloc() fails during the processing of either routine
  5179. ** (for example during a conversion from UTF-8 to UTF-16) then a
  5180. ** NULL pointer is returned.
  5181. **
  5182. ** ^The name of a result column is the value of the "AS" clause for
  5183. ** that column, if there is an AS clause. If there is no AS clause
  5184. ** then the name of the column is unspecified and may change from
  5185. ** one release of SQLite to the next.
  5186. */
  5187. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  5188. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  5189. /*
  5190. ** CAPI3REF: Source Of Data In A Query Result
  5191. ** METHOD: sqlite3_stmt
  5192. **
  5193. ** ^These routines provide a means to determine the database, table, and
  5194. ** table column that is the origin of a particular result column in
  5195. ** [SELECT] statement.
  5196. ** ^The name of the database or table or column can be returned as
  5197. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  5198. ** the database name, the _table_ routines return the table name, and
  5199. ** the origin_ routines return the column name.
  5200. ** ^The returned string is valid until the [prepared statement] is destroyed
  5201. ** using [sqlite3_finalize()] or until the statement is automatically
  5202. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5203. ** or until the same information is requested
  5204. ** again in a different encoding.
  5205. **
  5206. ** ^The names returned are the original un-aliased names of the
  5207. ** database, table, and column.
  5208. **
  5209. ** ^The first argument to these interfaces is a [prepared statement].
  5210. ** ^These functions return information about the Nth result column returned by
  5211. ** the statement, where N is the second function argument.
  5212. ** ^The left-most column is column 0 for these routines.
  5213. **
  5214. ** ^If the Nth column returned by the statement is an expression or
  5215. ** subquery and is not a column value, then all of these functions return
  5216. ** NULL. ^These routine might also return NULL if a memory allocation error
  5217. ** occurs. ^Otherwise, they return the name of the attached database, table,
  5218. ** or column that query result column was extracted from.
  5219. **
  5220. ** ^As with all other SQLite APIs, those whose names end with "16" return
  5221. ** UTF-16 encoded strings and the other functions return UTF-8.
  5222. **
  5223. ** ^These APIs are only available if the library was compiled with the
  5224. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  5225. **
  5226. ** If two or more threads call one or more of these routines against the same
  5227. ** prepared statement and column at the same time then the results are
  5228. ** undefined.
  5229. **
  5230. ** If two or more threads call one or more
  5231. ** [sqlite3_column_database_name | column metadata interfaces]
  5232. ** for the same [prepared statement] and result column
  5233. ** at the same time then the results are undefined.
  5234. */
  5235. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  5236. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  5237. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  5238. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  5239. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  5240. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  5241. /*
  5242. ** CAPI3REF: Declared Datatype Of A Query Result
  5243. ** METHOD: sqlite3_stmt
  5244. **
  5245. ** ^(The first parameter is a [prepared statement].
  5246. ** If this statement is a [SELECT] statement and the Nth column of the
  5247. ** returned result set of that [SELECT] is a table column (not an
  5248. ** expression or subquery) then the declared type of the table
  5249. ** column is returned.)^ ^If the Nth column of the result set is an
  5250. ** expression or subquery, then a NULL pointer is returned.
  5251. ** ^The returned string is always UTF-8 encoded.
  5252. **
  5253. ** ^(For example, given the database schema:
  5254. **
  5255. ** CREATE TABLE t1(c1 VARIANT);
  5256. **
  5257. ** and the following statement to be compiled:
  5258. **
  5259. ** SELECT c1 + 1, c1 FROM t1;
  5260. **
  5261. ** this routine would return the string "VARIANT" for the second result
  5262. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  5263. **
  5264. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  5265. ** is declared to contain a particular type does not mean that the
  5266. ** data stored in that column is of the declared type. SQLite is
  5267. ** strongly typed, but the typing is dynamic not static. ^Type
  5268. ** is associated with individual values, not with the containers
  5269. ** used to hold those values.
  5270. */
  5271. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  5272. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  5273. /*
  5274. ** CAPI3REF: Evaluate An SQL Statement
  5275. ** METHOD: sqlite3_stmt
  5276. **
  5277. ** After a [prepared statement] has been prepared using any of
  5278. ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
  5279. ** or [sqlite3_prepare16_v3()] or one of the legacy
  5280. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  5281. ** must be called one or more times to evaluate the statement.
  5282. **
  5283. ** The details of the behavior of the sqlite3_step() interface depend
  5284. ** on whether the statement was prepared using the newer "vX" interfaces
  5285. ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
  5286. ** [sqlite3_prepare16_v2()] or the older legacy
  5287. ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  5288. ** new "vX" interface is recommended for new applications but the legacy
  5289. ** interface will continue to be supported.
  5290. **
  5291. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  5292. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  5293. ** ^With the "v2" interface, any of the other [result codes] or
  5294. ** [extended result codes] might be returned as well.
  5295. **
  5296. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  5297. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  5298. ** or occurs outside of an explicit transaction, then you can retry the
  5299. ** statement. If the statement is not a [COMMIT] and occurs within an
  5300. ** explicit transaction then you should rollback the transaction before
  5301. ** continuing.
  5302. **
  5303. ** ^[SQLITE_DONE] means that the statement has finished executing
  5304. ** successfully. sqlite3_step() should not be called again on this virtual
  5305. ** machine without first calling [sqlite3_reset()] to reset the virtual
  5306. ** machine back to its initial state.
  5307. **
  5308. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  5309. ** is returned each time a new row of data is ready for processing by the
  5310. ** caller. The values may be accessed using the [column access functions].
  5311. ** sqlite3_step() is called again to retrieve the next row of data.
  5312. **
  5313. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  5314. ** violation) has occurred. sqlite3_step() should not be called again on
  5315. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  5316. ** ^With the legacy interface, a more specific error code (for example,
  5317. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  5318. ** can be obtained by calling [sqlite3_reset()] on the
  5319. ** [prepared statement]. ^In the "v2" interface,
  5320. ** the more specific error code is returned directly by sqlite3_step().
  5321. **
  5322. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  5323. ** Perhaps it was called on a [prepared statement] that has
  5324. ** already been [sqlite3_finalize | finalized] or on one that had
  5325. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  5326. ** be the case that the same database connection is being used by two or
  5327. ** more threads at the same moment in time.
  5328. **
  5329. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  5330. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  5331. ** other than [SQLITE_ROW] before any subsequent invocation of
  5332. ** sqlite3_step(). Failure to reset the prepared statement using
  5333. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  5334. ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
  5335. ** sqlite3_step() began
  5336. ** calling [sqlite3_reset()] automatically in this circumstance rather
  5337. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  5338. ** break because any application that ever receives an SQLITE_MISUSE error
  5339. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  5340. ** can be used to restore the legacy behavior.
  5341. **
  5342. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  5343. ** API always returns a generic error code, [SQLITE_ERROR], following any
  5344. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  5345. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  5346. ** specific [error codes] that better describes the error.
  5347. ** We admit that this is a goofy design. The problem has been fixed
  5348. ** with the "v2" interface. If you prepare all of your SQL statements
  5349. ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
  5350. ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
  5351. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  5352. ** then the more specific [error codes] are returned directly
  5353. ** by sqlite3_step(). The use of the "vX" interfaces is recommended.
  5354. */
  5355. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  5356. /*
  5357. ** CAPI3REF: Number of columns in a result set
  5358. ** METHOD: sqlite3_stmt
  5359. **
  5360. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  5361. ** current row of the result set of [prepared statement] P.
  5362. ** ^If prepared statement P does not have results ready to return
  5363. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  5364. ** interfaces) then sqlite3_data_count(P) returns 0.
  5365. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  5366. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  5367. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  5368. ** will return non-zero if previous call to [sqlite3_step](P) returned
  5369. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  5370. ** where it always returns zero since each step of that multi-step
  5371. ** pragma returns 0 columns of data.
  5372. **
  5373. ** See also: [sqlite3_column_count()]
  5374. */
  5375. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  5376. /*
  5377. ** CAPI3REF: Fundamental Datatypes
  5378. ** KEYWORDS: SQLITE_TEXT
  5379. **
  5380. ** ^(Every value in SQLite has one of five fundamental datatypes:
  5381. **
  5382. ** <ul>
  5383. ** <li> 64-bit signed integer
  5384. ** <li> 64-bit IEEE floating point number
  5385. ** <li> string
  5386. ** <li> BLOB
  5387. ** <li> NULL
  5388. ** </ul>)^
  5389. **
  5390. ** These constants are codes for each of those types.
  5391. **
  5392. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  5393. ** for a completely different meaning. Software that links against both
  5394. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  5395. ** SQLITE_TEXT.
  5396. */
  5397. #define SQLITE_INTEGER 1
  5398. #define SQLITE_FLOAT 2
  5399. #define SQLITE_BLOB 4
  5400. #define SQLITE_NULL 5
  5401. #ifdef SQLITE_TEXT
  5402. # undef SQLITE_TEXT
  5403. #else
  5404. # define SQLITE_TEXT 3
  5405. #endif
  5406. #define SQLITE3_TEXT 3
  5407. /*
  5408. ** CAPI3REF: Result Values From A Query
  5409. ** KEYWORDS: {column access functions}
  5410. ** METHOD: sqlite3_stmt
  5411. **
  5412. ** <b>Summary:</b>
  5413. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5414. ** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
  5415. ** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
  5416. ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
  5417. ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
  5418. ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
  5419. ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
  5420. ** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
  5421. ** [sqlite3_value|unprotected sqlite3_value] object.
  5422. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5423. ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
  5424. ** or a UTF-8 TEXT result in bytes
  5425. ** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
  5426. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5427. ** TEXT in bytes
  5428. ** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
  5429. ** datatype of the result
  5430. ** </table></blockquote>
  5431. **
  5432. ** <b>Details:</b>
  5433. **
  5434. ** ^These routines return information about a single column of the current
  5435. ** result row of a query. ^In every case the first argument is a pointer
  5436. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  5437. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  5438. ** and the second argument is the index of the column for which information
  5439. ** should be returned. ^The leftmost column of the result set has the index 0.
  5440. ** ^The number of columns in the result can be determined using
  5441. ** [sqlite3_column_count()].
  5442. **
  5443. ** If the SQL statement does not currently point to a valid row, or if the
  5444. ** column index is out of range, the result is undefined.
  5445. ** These routines may only be called when the most recent call to
  5446. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  5447. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  5448. ** If any of these routines are called after [sqlite3_reset()] or
  5449. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  5450. ** something other than [SQLITE_ROW], the results are undefined.
  5451. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  5452. ** are called from a different thread while any of these routines
  5453. ** are pending, then the results are undefined.
  5454. **
  5455. ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
  5456. ** each return the value of a result column in a specific data format. If
  5457. ** the result column is not initially in the requested format (for example,
  5458. ** if the query returns an integer but the sqlite3_column_text() interface
  5459. ** is used to extract the value) then an automatic type conversion is performed.
  5460. **
  5461. ** ^The sqlite3_column_type() routine returns the
  5462. ** [SQLITE_INTEGER | datatype code] for the initial data type
  5463. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  5464. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
  5465. ** The return value of sqlite3_column_type() can be used to decide which
  5466. ** of the first six interface should be used to extract the column value.
  5467. ** The value returned by sqlite3_column_type() is only meaningful if no
  5468. ** automatic type conversions have occurred for the value in question.
  5469. ** After a type conversion, the result of calling sqlite3_column_type()
  5470. ** is undefined, though harmless. Future
  5471. ** versions of SQLite may change the behavior of sqlite3_column_type()
  5472. ** following a type conversion.
  5473. **
  5474. ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
  5475. ** or sqlite3_column_bytes16() interfaces can be used to determine the size
  5476. ** of that BLOB or string.
  5477. **
  5478. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  5479. ** routine returns the number of bytes in that BLOB or string.
  5480. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  5481. ** the string to UTF-8 and then returns the number of bytes.
  5482. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  5483. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  5484. ** the number of bytes in that string.
  5485. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  5486. **
  5487. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  5488. ** routine returns the number of bytes in that BLOB or string.
  5489. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  5490. ** the string to UTF-16 and then returns the number of bytes.
  5491. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  5492. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  5493. ** the number of bytes in that string.
  5494. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  5495. **
  5496. ** ^The values returned by [sqlite3_column_bytes()] and
  5497. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  5498. ** of the string. ^For clarity: the values returned by
  5499. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  5500. ** bytes in the string, not the number of characters.
  5501. **
  5502. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  5503. ** even empty strings, are always zero-terminated. ^The return
  5504. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  5505. **
  5506. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  5507. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  5508. ** an unprotected sqlite3_value object may only be used safely with
  5509. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  5510. ** If the [unprotected sqlite3_value] object returned by
  5511. ** [sqlite3_column_value()] is used in any other way, including calls
  5512. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  5513. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  5514. ** Hence, the sqlite3_column_value() interface
  5515. ** is normally only useful within the implementation of
  5516. ** [application-defined SQL functions] or [virtual tables], not within
  5517. ** top-level application code.
  5518. **
  5519. ** The these routines may attempt to convert the datatype of the result.
  5520. ** ^For example, if the internal representation is FLOAT and a text result
  5521. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  5522. ** conversion automatically. ^(The following table details the conversions
  5523. ** that are applied:
  5524. **
  5525. ** <blockquote>
  5526. ** <table border="1">
  5527. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  5528. **
  5529. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  5530. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  5531. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  5532. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  5533. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  5534. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  5535. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  5536. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  5537. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  5538. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  5539. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  5540. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  5541. ** <tr><td> TEXT <td> BLOB <td> No change
  5542. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  5543. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  5544. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  5545. ** </table>
  5546. ** </blockquote>)^
  5547. **
  5548. ** Note that when type conversions occur, pointers returned by prior
  5549. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  5550. ** sqlite3_column_text16() may be invalidated.
  5551. ** Type conversions and pointer invalidations might occur
  5552. ** in the following cases:
  5553. **
  5554. ** <ul>
  5555. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  5556. ** sqlite3_column_text16() is called. A zero-terminator might
  5557. ** need to be added to the string.</li>
  5558. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  5559. ** sqlite3_column_text16() is called. The content must be converted
  5560. ** to UTF-16.</li>
  5561. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  5562. ** sqlite3_column_text() is called. The content must be converted
  5563. ** to UTF-8.</li>
  5564. ** </ul>
  5565. **
  5566. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  5567. ** not invalidate a prior pointer, though of course the content of the buffer
  5568. ** that the prior pointer references will have been modified. Other kinds
  5569. ** of conversion are done in place when it is possible, but sometimes they
  5570. ** are not possible and in those cases prior pointers are invalidated.
  5571. **
  5572. ** The safest policy is to invoke these routines
  5573. ** in one of the following ways:
  5574. **
  5575. ** <ul>
  5576. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  5577. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  5578. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  5579. ** </ul>
  5580. **
  5581. ** In other words, you should call sqlite3_column_text(),
  5582. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  5583. ** into the desired format, then invoke sqlite3_column_bytes() or
  5584. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  5585. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  5586. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  5587. ** with calls to sqlite3_column_bytes().
  5588. **
  5589. ** ^The pointers returned are valid until a type conversion occurs as
  5590. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  5591. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  5592. ** and BLOBs is freed automatically. Do not pass the pointers returned
  5593. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  5594. ** [sqlite3_free()].
  5595. **
  5596. ** As long as the input parameters are correct, these routines will only
  5597. ** fail if an out-of-memory error occurs during a format conversion.
  5598. ** Only the following subset of interfaces are subject to out-of-memory
  5599. ** errors:
  5600. **
  5601. ** <ul>
  5602. ** <li> sqlite3_column_blob()
  5603. ** <li> sqlite3_column_text()
  5604. ** <li> sqlite3_column_text16()
  5605. ** <li> sqlite3_column_bytes()
  5606. ** <li> sqlite3_column_bytes16()
  5607. ** </ul>
  5608. **
  5609. ** If an out-of-memory error occurs, then the return value from these
  5610. ** routines is the same as if the column had contained an SQL NULL value.
  5611. ** Valid SQL NULL returns can be distinguished from out-of-memory errors
  5612. ** by invoking the [sqlite3_errcode()] immediately after the suspect
  5613. ** return value is obtained and before any
  5614. ** other SQLite interface is called on the same [database connection].
  5615. */
  5616. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  5617. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  5618. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  5619. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  5620. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  5621. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  5622. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  5623. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  5624. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  5625. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  5626. /*
  5627. ** CAPI3REF: Destroy A Prepared Statement Object
  5628. ** DESTRUCTOR: sqlite3_stmt
  5629. **
  5630. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  5631. ** ^If the most recent evaluation of the statement encountered no errors
  5632. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  5633. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  5634. ** sqlite3_finalize(S) returns the appropriate [error code] or
  5635. ** [extended error code].
  5636. **
  5637. ** ^The sqlite3_finalize(S) routine can be called at any point during
  5638. ** the life cycle of [prepared statement] S:
  5639. ** before statement S is ever evaluated, after
  5640. ** one or more calls to [sqlite3_reset()], or after any call
  5641. ** to [sqlite3_step()] regardless of whether or not the statement has
  5642. ** completed execution.
  5643. **
  5644. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  5645. **
  5646. ** The application must finalize every [prepared statement] in order to avoid
  5647. ** resource leaks. It is a grievous error for the application to try to use
  5648. ** a prepared statement after it has been finalized. Any use of a prepared
  5649. ** statement after it has been finalized can result in undefined and
  5650. ** undesirable behavior such as segfaults and heap corruption.
  5651. */
  5652. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  5653. /*
  5654. ** CAPI3REF: Reset A Prepared Statement Object
  5655. ** METHOD: sqlite3_stmt
  5656. **
  5657. ** The sqlite3_reset() function is called to reset a [prepared statement]
  5658. ** object back to its initial state, ready to be re-executed.
  5659. ** ^Any SQL statement variables that had values bound to them using
  5660. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  5661. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  5662. **
  5663. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  5664. ** back to the beginning of its program.
  5665. **
  5666. ** ^If the most recent call to [sqlite3_step(S)] for the
  5667. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  5668. ** or if [sqlite3_step(S)] has never before been called on S,
  5669. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  5670. **
  5671. ** ^If the most recent call to [sqlite3_step(S)] for the
  5672. ** [prepared statement] S indicated an error, then
  5673. ** [sqlite3_reset(S)] returns an appropriate [error code].
  5674. **
  5675. ** ^The [sqlite3_reset(S)] interface does not change the values
  5676. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  5677. */
  5678. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  5679. /*
  5680. ** CAPI3REF: Create Or Redefine SQL Functions
  5681. ** KEYWORDS: {function creation routines}
  5682. ** KEYWORDS: {application-defined SQL function}
  5683. ** KEYWORDS: {application-defined SQL functions}
  5684. ** METHOD: sqlite3
  5685. **
  5686. ** ^These functions (collectively known as "function creation routines")
  5687. ** are used to add SQL functions or aggregates or to redefine the behavior
  5688. ** of existing SQL functions or aggregates. The only differences between
  5689. ** the three "sqlite3_create_function*" routines are the text encoding
  5690. ** expected for the second parameter (the name of the function being
  5691. ** created) and the presence or absence of a destructor callback for
  5692. ** the application data pointer. Function sqlite3_create_window_function()
  5693. ** is similar, but allows the user to supply the extra callback functions
  5694. ** needed by [aggregate window functions].
  5695. **
  5696. ** ^The first parameter is the [database connection] to which the SQL
  5697. ** function is to be added. ^If an application uses more than one database
  5698. ** connection then application-defined SQL functions must be added
  5699. ** to each database connection separately.
  5700. **
  5701. ** ^The second parameter is the name of the SQL function to be created or
  5702. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  5703. ** representation, exclusive of the zero-terminator. ^Note that the name
  5704. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  5705. ** ^Any attempt to create a function with a longer name
  5706. ** will result in [SQLITE_MISUSE] being returned.
  5707. **
  5708. ** ^The third parameter (nArg)
  5709. ** is the number of arguments that the SQL function or
  5710. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  5711. ** aggregate may take any number of arguments between 0 and the limit
  5712. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  5713. ** parameter is less than -1 or greater than 127 then the behavior is
  5714. ** undefined.
  5715. **
  5716. ** ^The fourth parameter, eTextRep, specifies what
  5717. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  5718. ** its parameters. The application should set this parameter to
  5719. ** [SQLITE_UTF16LE] if the function implementation invokes
  5720. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  5721. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  5722. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  5723. ** otherwise. ^The same SQL function may be registered multiple times using
  5724. ** different preferred text encodings, with different implementations for
  5725. ** each encoding.
  5726. ** ^When multiple implementations of the same function are available, SQLite
  5727. ** will pick the one that involves the least amount of data conversion.
  5728. **
  5729. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  5730. ** to signal that the function will always return the same result given
  5731. ** the same inputs within a single SQL statement. Most SQL functions are
  5732. ** deterministic. The built-in [random()] SQL function is an example of a
  5733. ** function that is not deterministic. The SQLite query planner is able to
  5734. ** perform additional optimizations on deterministic functions, so use
  5735. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  5736. **
  5737. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  5738. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  5739. **
  5740. ** ^The sixth, seventh and eighth parameters passed to the three
  5741. ** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
  5742. ** pointers to C-language functions that implement the SQL function or
  5743. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  5744. ** callback only; NULL pointers must be passed as the xStep and xFinal
  5745. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  5746. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  5747. ** SQL function or aggregate, pass NULL pointers for all three function
  5748. ** callbacks.
  5749. **
  5750. ** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
  5751. ** and xInverse) passed to sqlite3_create_window_function are pointers to
  5752. ** C-language callbacks that implement the new function. xStep and xFinal
  5753. ** must both be non-NULL. xValue and xInverse may either both be NULL, in
  5754. ** which case a regular aggregate function is created, or must both be
  5755. ** non-NULL, in which case the new function may be used as either an aggregate
  5756. ** or aggregate window function. More details regarding the implementation
  5757. ** of aggregate window functions are
  5758. ** [user-defined window functions|available here].
  5759. **
  5760. ** ^(If the final parameter to sqlite3_create_function_v2() or
  5761. ** sqlite3_create_window_function() is not NULL, then it is destructor for
  5762. ** the application data pointer. The destructor is invoked when the function
  5763. ** is deleted, either by being overloaded or when the database connection
  5764. ** closes.)^ ^The destructor is also invoked if the call to
  5765. ** sqlite3_create_function_v2() fails. ^When the destructor callback is
  5766. ** invoked, it is passed a single argument which is a copy of the application
  5767. ** data pointer which was the fifth parameter to sqlite3_create_function_v2().
  5768. **
  5769. ** ^It is permitted to register multiple implementations of the same
  5770. ** functions with the same name but with either differing numbers of
  5771. ** arguments or differing preferred text encodings. ^SQLite will use
  5772. ** the implementation that most closely matches the way in which the
  5773. ** SQL function is used. ^A function implementation with a non-negative
  5774. ** nArg parameter is a better match than a function implementation with
  5775. ** a negative nArg. ^A function where the preferred text encoding
  5776. ** matches the database encoding is a better
  5777. ** match than a function where the encoding is different.
  5778. ** ^A function where the encoding difference is between UTF16le and UTF16be
  5779. ** is a closer match than a function where the encoding difference is
  5780. ** between UTF8 and UTF16.
  5781. **
  5782. ** ^Built-in functions may be overloaded by new application-defined functions.
  5783. **
  5784. ** ^An application-defined function is permitted to call other
  5785. ** SQLite interfaces. However, such calls must not
  5786. ** close the database connection nor finalize or reset the prepared
  5787. ** statement in which the function is running.
  5788. */
  5789. SQLITE_API int sqlite3_create_function(
  5790. sqlite3 *db,
  5791. const char *zFunctionName,
  5792. int nArg,
  5793. int eTextRep,
  5794. void *pApp,
  5795. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5796. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5797. void (*xFinal)(sqlite3_context*)
  5798. );
  5799. SQLITE_API int sqlite3_create_function16(
  5800. sqlite3 *db,
  5801. const void *zFunctionName,
  5802. int nArg,
  5803. int eTextRep,
  5804. void *pApp,
  5805. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5806. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5807. void (*xFinal)(sqlite3_context*)
  5808. );
  5809. SQLITE_API int sqlite3_create_function_v2(
  5810. sqlite3 *db,
  5811. const char *zFunctionName,
  5812. int nArg,
  5813. int eTextRep,
  5814. void *pApp,
  5815. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5816. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5817. void (*xFinal)(sqlite3_context*),
  5818. void(*xDestroy)(void*)
  5819. );
  5820. SQLITE_API int sqlite3_create_window_function(
  5821. sqlite3 *db,
  5822. const char *zFunctionName,
  5823. int nArg,
  5824. int eTextRep,
  5825. void *pApp,
  5826. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5827. void (*xFinal)(sqlite3_context*),
  5828. void (*xValue)(sqlite3_context*),
  5829. void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
  5830. void(*xDestroy)(void*)
  5831. );
  5832. /*
  5833. ** CAPI3REF: Text Encodings
  5834. **
  5835. ** These constant define integer codes that represent the various
  5836. ** text encodings supported by SQLite.
  5837. */
  5838. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  5839. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  5840. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  5841. #define SQLITE_UTF16 4 /* Use native byte order */
  5842. #define SQLITE_ANY 5 /* Deprecated */
  5843. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  5844. /*
  5845. ** CAPI3REF: Function Flags
  5846. **
  5847. ** These constants may be ORed together with the
  5848. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  5849. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  5850. ** [sqlite3_create_function_v2()].
  5851. */
  5852. #define SQLITE_DETERMINISTIC 0x800
  5853. /*
  5854. ** CAPI3REF: Deprecated Functions
  5855. ** DEPRECATED
  5856. **
  5857. ** These functions are [deprecated]. In order to maintain
  5858. ** backwards compatibility with older code, these functions continue
  5859. ** to be supported. However, new applications should avoid
  5860. ** the use of these functions. To encourage programmers to avoid
  5861. ** these functions, we will not explain what they do.
  5862. */
  5863. #ifndef SQLITE_OMIT_DEPRECATED
  5864. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  5865. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  5866. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  5867. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  5868. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  5869. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  5870. void*,sqlite3_int64);
  5871. #endif
  5872. /*
  5873. ** CAPI3REF: Obtaining SQL Values
  5874. ** METHOD: sqlite3_value
  5875. **
  5876. ** <b>Summary:</b>
  5877. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5878. ** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
  5879. ** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
  5880. ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
  5881. ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
  5882. ** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
  5883. ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
  5884. ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
  5885. ** the native byteorder
  5886. ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
  5887. ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
  5888. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5889. ** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
  5890. ** or a UTF-8 TEXT in bytes
  5891. ** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
  5892. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5893. ** TEXT in bytes
  5894. ** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
  5895. ** datatype of the value
  5896. ** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
  5897. ** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
  5898. ** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
  5899. ** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
  5900. ** against a virtual table.
  5901. ** <tr><td><b>sqlite3_value_frombind&nbsp;&nbsp;</b>
  5902. ** <td>&rarr;&nbsp;&nbsp;<td>True if value originated from a [bound parameter]
  5903. ** </table></blockquote>
  5904. **
  5905. ** <b>Details:</b>
  5906. **
  5907. ** These routines extract type, size, and content information from
  5908. ** [protected sqlite3_value] objects. Protected sqlite3_value objects
  5909. ** are used to pass parameter information into implementation of
  5910. ** [application-defined SQL functions] and [virtual tables].
  5911. **
  5912. ** These routines work only with [protected sqlite3_value] objects.
  5913. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  5914. ** is not threadsafe.
  5915. **
  5916. ** ^These routines work just like the corresponding [column access functions]
  5917. ** except that these routines take a single [protected sqlite3_value] object
  5918. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  5919. **
  5920. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  5921. ** in the native byte-order of the host machine. ^The
  5922. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  5923. ** extract UTF-16 strings as big-endian and little-endian respectively.
  5924. **
  5925. ** ^If [sqlite3_value] object V was initialized
  5926. ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
  5927. ** and if X and Y are strings that compare equal according to strcmp(X,Y),
  5928. ** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
  5929. ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
  5930. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  5931. **
  5932. ** ^(The sqlite3_value_type(V) interface returns the
  5933. ** [SQLITE_INTEGER | datatype code] for the initial datatype of the
  5934. ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
  5935. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
  5936. ** Other interfaces might change the datatype for an sqlite3_value object.
  5937. ** For example, if the datatype is initially SQLITE_INTEGER and
  5938. ** sqlite3_value_text(V) is called to extract a text value for that
  5939. ** integer, then subsequent calls to sqlite3_value_type(V) might return
  5940. ** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
  5941. ** occurs is undefined and may change from one release of SQLite to the next.
  5942. **
  5943. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  5944. ** numeric affinity to the value. This means that an attempt is
  5945. ** made to convert the value to an integer or floating point. If
  5946. ** such a conversion is possible without loss of information (in other
  5947. ** words, if the value is a string that looks like a number)
  5948. ** then the conversion is performed. Otherwise no conversion occurs.
  5949. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  5950. **
  5951. ** ^Within the [xUpdate] method of a [virtual table], the
  5952. ** sqlite3_value_nochange(X) interface returns true if and only if
  5953. ** the column corresponding to X is unchanged by the UPDATE operation
  5954. ** that the xUpdate method call was invoked to implement and if
  5955. ** and the prior [xColumn] method call that was invoked to extracted
  5956. ** the value for that column returned without setting a result (probably
  5957. ** because it queried [sqlite3_vtab_nochange()] and found that the column
  5958. ** was unchanging). ^Within an [xUpdate] method, any value for which
  5959. ** sqlite3_value_nochange(X) is true will in all other respects appear
  5960. ** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other
  5961. ** than within an [xUpdate] method call for an UPDATE statement, then
  5962. ** the return value is arbitrary and meaningless.
  5963. **
  5964. ** ^The sqlite3_value_frombind(X) interface returns non-zero if the
  5965. ** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]
  5966. ** interfaces. ^If X comes from an SQL literal value, or a table column,
  5967. ** and expression, then sqlite3_value_frombind(X) returns zero.
  5968. **
  5969. ** Please pay particular attention to the fact that the pointer returned
  5970. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  5971. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  5972. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  5973. ** or [sqlite3_value_text16()].
  5974. **
  5975. ** These routines must be called from the same thread as
  5976. ** the SQL function that supplied the [sqlite3_value*] parameters.
  5977. **
  5978. ** As long as the input parameter is correct, these routines can only
  5979. ** fail if an out-of-memory error occurs during a format conversion.
  5980. ** Only the following subset of interfaces are subject to out-of-memory
  5981. ** errors:
  5982. **
  5983. ** <ul>
  5984. ** <li> sqlite3_value_blob()
  5985. ** <li> sqlite3_value_text()
  5986. ** <li> sqlite3_value_text16()
  5987. ** <li> sqlite3_value_text16le()
  5988. ** <li> sqlite3_value_text16be()
  5989. ** <li> sqlite3_value_bytes()
  5990. ** <li> sqlite3_value_bytes16()
  5991. ** </ul>
  5992. **
  5993. ** If an out-of-memory error occurs, then the return value from these
  5994. ** routines is the same as if the column had contained an SQL NULL value.
  5995. ** Valid SQL NULL returns can be distinguished from out-of-memory errors
  5996. ** by invoking the [sqlite3_errcode()] immediately after the suspect
  5997. ** return value is obtained and before any
  5998. ** other SQLite interface is called on the same [database connection].
  5999. */
  6000. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  6001. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  6002. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  6003. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  6004. SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
  6005. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  6006. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  6007. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  6008. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  6009. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  6010. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  6011. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  6012. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  6013. SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
  6014. SQLITE_API int sqlite3_value_frombind(sqlite3_value*);
  6015. /*
  6016. ** CAPI3REF: Finding The Subtype Of SQL Values
  6017. ** METHOD: sqlite3_value
  6018. **
  6019. ** The sqlite3_value_subtype(V) function returns the subtype for
  6020. ** an [application-defined SQL function] argument V. The subtype
  6021. ** information can be used to pass a limited amount of context from
  6022. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  6023. ** routine to set the subtype for the return value of an SQL function.
  6024. */
  6025. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
  6026. /*
  6027. ** CAPI3REF: Copy And Free SQL Values
  6028. ** METHOD: sqlite3_value
  6029. **
  6030. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  6031. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  6032. ** is a [protected sqlite3_value] object even if the input is not.
  6033. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  6034. ** memory allocation fails.
  6035. **
  6036. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  6037. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  6038. ** then sqlite3_value_free(V) is a harmless no-op.
  6039. */
  6040. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
  6041. SQLITE_API void sqlite3_value_free(sqlite3_value*);
  6042. /*
  6043. ** CAPI3REF: Obtain Aggregate Function Context
  6044. ** METHOD: sqlite3_context
  6045. **
  6046. ** Implementations of aggregate SQL functions use this
  6047. ** routine to allocate memory for storing their state.
  6048. **
  6049. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  6050. ** for a particular aggregate function, SQLite
  6051. ** allocates N of memory, zeroes out that memory, and returns a pointer
  6052. ** to the new memory. ^On second and subsequent calls to
  6053. ** sqlite3_aggregate_context() for the same aggregate function instance,
  6054. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  6055. ** called once for each invocation of the xStep callback and then one
  6056. ** last time when the xFinal callback is invoked. ^(When no rows match
  6057. ** an aggregate query, the xStep() callback of the aggregate function
  6058. ** implementation is never called and xFinal() is called exactly once.
  6059. ** In those cases, sqlite3_aggregate_context() might be called for the
  6060. ** first time from within xFinal().)^
  6061. **
  6062. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  6063. ** when first called if N is less than or equal to zero or if a memory
  6064. ** allocate error occurs.
  6065. **
  6066. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  6067. ** determined by the N parameter on first successful call. Changing the
  6068. ** value of N in subsequent call to sqlite3_aggregate_context() within
  6069. ** the same aggregate function instance will not resize the memory
  6070. ** allocation.)^ Within the xFinal callback, it is customary to set
  6071. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  6072. ** pointless memory allocations occur.
  6073. **
  6074. ** ^SQLite automatically frees the memory allocated by
  6075. ** sqlite3_aggregate_context() when the aggregate query concludes.
  6076. **
  6077. ** The first parameter must be a copy of the
  6078. ** [sqlite3_context | SQL function context] that is the first parameter
  6079. ** to the xStep or xFinal callback routine that implements the aggregate
  6080. ** function.
  6081. **
  6082. ** This routine must be called from the same thread in which
  6083. ** the aggregate SQL function is running.
  6084. */
  6085. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  6086. /*
  6087. ** CAPI3REF: User Data For Functions
  6088. ** METHOD: sqlite3_context
  6089. **
  6090. ** ^The sqlite3_user_data() interface returns a copy of
  6091. ** the pointer that was the pUserData parameter (the 5th parameter)
  6092. ** of the [sqlite3_create_function()]
  6093. ** and [sqlite3_create_function16()] routines that originally
  6094. ** registered the application defined function.
  6095. **
  6096. ** This routine must be called from the same thread in which
  6097. ** the application-defined function is running.
  6098. */
  6099. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  6100. /*
  6101. ** CAPI3REF: Database Connection For Functions
  6102. ** METHOD: sqlite3_context
  6103. **
  6104. ** ^The sqlite3_context_db_handle() interface returns a copy of
  6105. ** the pointer to the [database connection] (the 1st parameter)
  6106. ** of the [sqlite3_create_function()]
  6107. ** and [sqlite3_create_function16()] routines that originally
  6108. ** registered the application defined function.
  6109. */
  6110. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  6111. /*
  6112. ** CAPI3REF: Function Auxiliary Data
  6113. ** METHOD: sqlite3_context
  6114. **
  6115. ** These functions may be used by (non-aggregate) SQL functions to
  6116. ** associate metadata with argument values. If the same value is passed to
  6117. ** multiple invocations of the same SQL function during query execution, under
  6118. ** some circumstances the associated metadata may be preserved. An example
  6119. ** of where this might be useful is in a regular-expression matching
  6120. ** function. The compiled version of the regular expression can be stored as
  6121. ** metadata associated with the pattern string.
  6122. ** Then as long as the pattern string remains the same,
  6123. ** the compiled regular expression can be reused on multiple
  6124. ** invocations of the same function.
  6125. **
  6126. ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
  6127. ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
  6128. ** value to the application-defined function. ^N is zero for the left-most
  6129. ** function argument. ^If there is no metadata
  6130. ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
  6131. ** returns a NULL pointer.
  6132. **
  6133. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  6134. ** argument of the application-defined function. ^Subsequent
  6135. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  6136. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  6137. ** NULL if the metadata has been discarded.
  6138. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  6139. ** SQLite will invoke the destructor function X with parameter P exactly
  6140. ** once, when the metadata is discarded.
  6141. ** SQLite is free to discard the metadata at any time, including: <ul>
  6142. ** <li> ^(when the corresponding function parameter changes)^, or
  6143. ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  6144. ** SQL statement)^, or
  6145. ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
  6146. ** parameter)^, or
  6147. ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
  6148. ** allocation error occurs.)^ </ul>
  6149. **
  6150. ** Note the last bullet in particular. The destructor X in
  6151. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  6152. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  6153. ** should be called near the end of the function implementation and the
  6154. ** function implementation should not make any use of P after
  6155. ** sqlite3_set_auxdata() has been called.
  6156. **
  6157. ** ^(In practice, metadata is preserved between function calls for
  6158. ** function parameters that are compile-time constants, including literal
  6159. ** values and [parameters] and expressions composed from the same.)^
  6160. **
  6161. ** The value of the N parameter to these interfaces should be non-negative.
  6162. ** Future enhancements may make use of negative N values to define new
  6163. ** kinds of function caching behavior.
  6164. **
  6165. ** These routines must be called from the same thread in which
  6166. ** the SQL function is running.
  6167. */
  6168. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  6169. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  6170. /*
  6171. ** CAPI3REF: Constants Defining Special Destructor Behavior
  6172. **
  6173. ** These are special values for the destructor that is passed in as the
  6174. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  6175. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  6176. ** and will never change. It does not need to be destroyed. ^The
  6177. ** SQLITE_TRANSIENT value means that the content will likely change in
  6178. ** the near future and that SQLite should make its own private copy of
  6179. ** the content before returning.
  6180. **
  6181. ** The typedef is necessary to work around problems in certain
  6182. ** C++ compilers.
  6183. */
  6184. typedef void (*sqlite3_destructor_type)(void*);
  6185. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  6186. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  6187. /*
  6188. ** CAPI3REF: Setting The Result Of An SQL Function
  6189. ** METHOD: sqlite3_context
  6190. **
  6191. ** These routines are used by the xFunc or xFinal callbacks that
  6192. ** implement SQL functions and aggregates. See
  6193. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  6194. ** for additional information.
  6195. **
  6196. ** These functions work very much like the [parameter binding] family of
  6197. ** functions used to bind values to host parameters in prepared statements.
  6198. ** Refer to the [SQL parameter] documentation for additional information.
  6199. **
  6200. ** ^The sqlite3_result_blob() interface sets the result from
  6201. ** an application-defined function to be the BLOB whose content is pointed
  6202. ** to by the second parameter and which is N bytes long where N is the
  6203. ** third parameter.
  6204. **
  6205. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  6206. ** interfaces set the result of the application-defined function to be
  6207. ** a BLOB containing all zero bytes and N bytes in size.
  6208. **
  6209. ** ^The sqlite3_result_double() interface sets the result from
  6210. ** an application-defined function to be a floating point value specified
  6211. ** by its 2nd argument.
  6212. **
  6213. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  6214. ** cause the implemented SQL function to throw an exception.
  6215. ** ^SQLite uses the string pointed to by the
  6216. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  6217. ** as the text of an error message. ^SQLite interprets the error
  6218. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  6219. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  6220. ** byte order. ^If the third parameter to sqlite3_result_error()
  6221. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  6222. ** message all text up through the first zero character.
  6223. ** ^If the third parameter to sqlite3_result_error() or
  6224. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  6225. ** bytes (not characters) from the 2nd parameter as the error message.
  6226. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  6227. ** routines make a private copy of the error message text before
  6228. ** they return. Hence, the calling function can deallocate or
  6229. ** modify the text after they return without harm.
  6230. ** ^The sqlite3_result_error_code() function changes the error code
  6231. ** returned by SQLite as a result of an error in a function. ^By default,
  6232. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  6233. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  6234. **
  6235. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  6236. ** error indicating that a string or BLOB is too long to represent.
  6237. **
  6238. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  6239. ** error indicating that a memory allocation failed.
  6240. **
  6241. ** ^The sqlite3_result_int() interface sets the return value
  6242. ** of the application-defined function to be the 32-bit signed integer
  6243. ** value given in the 2nd argument.
  6244. ** ^The sqlite3_result_int64() interface sets the return value
  6245. ** of the application-defined function to be the 64-bit signed integer
  6246. ** value given in the 2nd argument.
  6247. **
  6248. ** ^The sqlite3_result_null() interface sets the return value
  6249. ** of the application-defined function to be NULL.
  6250. **
  6251. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  6252. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  6253. ** set the return value of the application-defined function to be
  6254. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  6255. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  6256. ** ^The sqlite3_result_text64() interface sets the return value of an
  6257. ** application-defined function to be a text string in an encoding
  6258. ** specified by the fifth (and last) parameter, which must be one
  6259. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  6260. ** ^SQLite takes the text result from the application from
  6261. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  6262. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6263. ** is negative, then SQLite takes result text from the 2nd parameter
  6264. ** through the first zero character.
  6265. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6266. ** is non-negative, then as many bytes (not characters) of the text
  6267. ** pointed to by the 2nd parameter are taken as the application-defined
  6268. ** function result. If the 3rd parameter is non-negative, then it
  6269. ** must be the byte offset into the string where the NUL terminator would
  6270. ** appear if the string where NUL terminated. If any NUL characters occur
  6271. ** in the string at a byte offset that is less than the value of the 3rd
  6272. ** parameter, then the resulting string will contain embedded NULs and the
  6273. ** result of expressions operating on strings with embedded NULs is undefined.
  6274. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6275. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  6276. ** function as the destructor on the text or BLOB result when it has
  6277. ** finished using that result.
  6278. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  6279. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  6280. ** assumes that the text or BLOB result is in constant space and does not
  6281. ** copy the content of the parameter nor call a destructor on the content
  6282. ** when it has finished using that result.
  6283. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6284. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  6285. ** then SQLite makes a copy of the result into space obtained
  6286. ** from [sqlite3_malloc()] before it returns.
  6287. **
  6288. ** ^The sqlite3_result_value() interface sets the result of
  6289. ** the application-defined function to be a copy of the
  6290. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  6291. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  6292. ** so that the [sqlite3_value] specified in the parameter may change or
  6293. ** be deallocated after sqlite3_result_value() returns without harm.
  6294. ** ^A [protected sqlite3_value] object may always be used where an
  6295. ** [unprotected sqlite3_value] object is required, so either
  6296. ** kind of [sqlite3_value] object can be used with this interface.
  6297. **
  6298. ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
  6299. ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
  6300. ** also associates the host-language pointer P or type T with that
  6301. ** NULL value such that the pointer can be retrieved within an
  6302. ** [application-defined SQL function] using [sqlite3_value_pointer()].
  6303. ** ^If the D parameter is not NULL, then it is a pointer to a destructor
  6304. ** for the P parameter. ^SQLite invokes D with P as its only argument
  6305. ** when SQLite is finished with P. The T parameter should be a static
  6306. ** string and preferably a string literal. The sqlite3_result_pointer()
  6307. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  6308. **
  6309. ** If these routines are called from within the different thread
  6310. ** than the one containing the application-defined function that received
  6311. ** the [sqlite3_context] pointer, the results are undefined.
  6312. */
  6313. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  6314. SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
  6315. sqlite3_uint64,void(*)(void*));
  6316. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  6317. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  6318. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  6319. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  6320. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  6321. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  6322. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  6323. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  6324. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  6325. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  6326. SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  6327. void(*)(void*), unsigned char encoding);
  6328. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  6329. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  6330. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  6331. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  6332. SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
  6333. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  6334. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  6335. /*
  6336. ** CAPI3REF: Setting The Subtype Of An SQL Function
  6337. ** METHOD: sqlite3_context
  6338. **
  6339. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  6340. ** the result from the [application-defined SQL function] with
  6341. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  6342. ** of the subtype T are preserved in current versions of SQLite;
  6343. ** higher order bits are discarded.
  6344. ** The number of subtype bytes preserved by SQLite might increase
  6345. ** in future releases of SQLite.
  6346. */
  6347. SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
  6348. /*
  6349. ** CAPI3REF: Define New Collating Sequences
  6350. ** METHOD: sqlite3
  6351. **
  6352. ** ^These functions add, remove, or modify a [collation] associated
  6353. ** with the [database connection] specified as the first argument.
  6354. **
  6355. ** ^The name of the collation is a UTF-8 string
  6356. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  6357. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  6358. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  6359. ** considered to be the same name.
  6360. **
  6361. ** ^(The third argument (eTextRep) must be one of the constants:
  6362. ** <ul>
  6363. ** <li> [SQLITE_UTF8],
  6364. ** <li> [SQLITE_UTF16LE],
  6365. ** <li> [SQLITE_UTF16BE],
  6366. ** <li> [SQLITE_UTF16], or
  6367. ** <li> [SQLITE_UTF16_ALIGNED].
  6368. ** </ul>)^
  6369. ** ^The eTextRep argument determines the encoding of strings passed
  6370. ** to the collating function callback, xCallback.
  6371. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  6372. ** force strings to be UTF16 with native byte order.
  6373. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  6374. ** on an even byte address.
  6375. **
  6376. ** ^The fourth argument, pArg, is an application data pointer that is passed
  6377. ** through as the first argument to the collating function callback.
  6378. **
  6379. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  6380. ** ^Multiple collating functions can be registered using the same name but
  6381. ** with different eTextRep parameters and SQLite will use whichever
  6382. ** function requires the least amount of data transformation.
  6383. ** ^If the xCallback argument is NULL then the collating function is
  6384. ** deleted. ^When all collating functions having the same name are deleted,
  6385. ** that collation is no longer usable.
  6386. **
  6387. ** ^The collating function callback is invoked with a copy of the pArg
  6388. ** application data pointer and with two strings in the encoding specified
  6389. ** by the eTextRep argument. The collating function must return an
  6390. ** integer that is negative, zero, or positive
  6391. ** if the first string is less than, equal to, or greater than the second,
  6392. ** respectively. A collating function must always return the same answer
  6393. ** given the same inputs. If two or more collating functions are registered
  6394. ** to the same collation name (using different eTextRep values) then all
  6395. ** must give an equivalent answer when invoked with equivalent strings.
  6396. ** The collating function must obey the following properties for all
  6397. ** strings A, B, and C:
  6398. **
  6399. ** <ol>
  6400. ** <li> If A==B then B==A.
  6401. ** <li> If A==B and B==C then A==C.
  6402. ** <li> If A&lt;B THEN B&gt;A.
  6403. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  6404. ** </ol>
  6405. **
  6406. ** If a collating function fails any of the above constraints and that
  6407. ** collating function is registered and used, then the behavior of SQLite
  6408. ** is undefined.
  6409. **
  6410. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  6411. ** with the addition that the xDestroy callback is invoked on pArg when
  6412. ** the collating function is deleted.
  6413. ** ^Collating functions are deleted when they are overridden by later
  6414. ** calls to the collation creation functions or when the
  6415. ** [database connection] is closed using [sqlite3_close()].
  6416. **
  6417. ** ^The xDestroy callback is <u>not</u> called if the
  6418. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  6419. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  6420. ** check the return code and dispose of the application data pointer
  6421. ** themselves rather than expecting SQLite to deal with it for them.
  6422. ** This is different from every other SQLite interface. The inconsistency
  6423. ** is unfortunate but cannot be changed without breaking backwards
  6424. ** compatibility.
  6425. **
  6426. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  6427. */
  6428. SQLITE_API int sqlite3_create_collation(
  6429. sqlite3*,
  6430. const char *zName,
  6431. int eTextRep,
  6432. void *pArg,
  6433. int(*xCompare)(void*,int,const void*,int,const void*)
  6434. );
  6435. SQLITE_API int sqlite3_create_collation_v2(
  6436. sqlite3*,
  6437. const char *zName,
  6438. int eTextRep,
  6439. void *pArg,
  6440. int(*xCompare)(void*,int,const void*,int,const void*),
  6441. void(*xDestroy)(void*)
  6442. );
  6443. SQLITE_API int sqlite3_create_collation16(
  6444. sqlite3*,
  6445. const void *zName,
  6446. int eTextRep,
  6447. void *pArg,
  6448. int(*xCompare)(void*,int,const void*,int,const void*)
  6449. );
  6450. /*
  6451. ** CAPI3REF: Collation Needed Callbacks
  6452. ** METHOD: sqlite3
  6453. **
  6454. ** ^To avoid having to register all collation sequences before a database
  6455. ** can be used, a single callback function may be registered with the
  6456. ** [database connection] to be invoked whenever an undefined collation
  6457. ** sequence is required.
  6458. **
  6459. ** ^If the function is registered using the sqlite3_collation_needed() API,
  6460. ** then it is passed the names of undefined collation sequences as strings
  6461. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  6462. ** the names are passed as UTF-16 in machine native byte order.
  6463. ** ^A call to either function replaces the existing collation-needed callback.
  6464. **
  6465. ** ^(When the callback is invoked, the first argument passed is a copy
  6466. ** of the second argument to sqlite3_collation_needed() or
  6467. ** sqlite3_collation_needed16(). The second argument is the database
  6468. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  6469. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  6470. ** sequence function required. The fourth parameter is the name of the
  6471. ** required collation sequence.)^
  6472. **
  6473. ** The callback function should register the desired collation using
  6474. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  6475. ** [sqlite3_create_collation_v2()].
  6476. */
  6477. SQLITE_API int sqlite3_collation_needed(
  6478. sqlite3*,
  6479. void*,
  6480. void(*)(void*,sqlite3*,int eTextRep,const char*)
  6481. );
  6482. SQLITE_API int sqlite3_collation_needed16(
  6483. sqlite3*,
  6484. void*,
  6485. void(*)(void*,sqlite3*,int eTextRep,const void*)
  6486. );
  6487. #ifdef SQLITE_HAS_CODEC
  6488. /*
  6489. ** Specify the key for an encrypted database. This routine should be
  6490. ** called right after sqlite3_open().
  6491. **
  6492. ** The code to implement this API is not available in the public release
  6493. ** of SQLite.
  6494. */
  6495. SQLITE_API int sqlite3_key(
  6496. sqlite3 *db, /* Database to be rekeyed */
  6497. const void *pKey, int nKey /* The key */
  6498. );
  6499. SQLITE_API int sqlite3_key_v2(
  6500. sqlite3 *db, /* Database to be rekeyed */
  6501. const char *zDbName, /* Name of the database */
  6502. const void *pKey, int nKey /* The key */
  6503. );
  6504. /*
  6505. ** Change the key on an open database. If the current database is not
  6506. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  6507. ** database is decrypted.
  6508. **
  6509. ** The code to implement this API is not available in the public release
  6510. ** of SQLite.
  6511. */
  6512. SQLITE_API int sqlite3_rekey(
  6513. sqlite3 *db, /* Database to be rekeyed */
  6514. const void *pKey, int nKey /* The new key */
  6515. );
  6516. SQLITE_API int sqlite3_rekey_v2(
  6517. sqlite3 *db, /* Database to be rekeyed */
  6518. const char *zDbName, /* Name of the database */
  6519. const void *pKey, int nKey /* The new key */
  6520. );
  6521. /*
  6522. ** Specify the activation key for a SEE database. Unless
  6523. ** activated, none of the SEE routines will work.
  6524. */
  6525. SQLITE_API void sqlite3_activate_see(
  6526. const char *zPassPhrase /* Activation phrase */
  6527. );
  6528. #endif
  6529. #ifdef SQLITE_ENABLE_CEROD
  6530. /*
  6531. ** Specify the activation key for a CEROD database. Unless
  6532. ** activated, none of the CEROD routines will work.
  6533. */
  6534. SQLITE_API void sqlite3_activate_cerod(
  6535. const char *zPassPhrase /* Activation phrase */
  6536. );
  6537. #endif
  6538. /*
  6539. ** CAPI3REF: Suspend Execution For A Short Time
  6540. **
  6541. ** The sqlite3_sleep() function causes the current thread to suspend execution
  6542. ** for at least a number of milliseconds specified in its parameter.
  6543. **
  6544. ** If the operating system does not support sleep requests with
  6545. ** millisecond time resolution, then the time will be rounded up to
  6546. ** the nearest second. The number of milliseconds of sleep actually
  6547. ** requested from the operating system is returned.
  6548. **
  6549. ** ^SQLite implements this interface by calling the xSleep()
  6550. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  6551. ** of the default VFS is not implemented correctly, or not implemented at
  6552. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  6553. ** in the previous paragraphs.
  6554. */
  6555. SQLITE_API int sqlite3_sleep(int);
  6556. /*
  6557. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  6558. **
  6559. ** ^(If this global variable is made to point to a string which is
  6560. ** the name of a folder (a.k.a. directory), then all temporary files
  6561. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  6562. ** will be placed in that directory.)^ ^If this variable
  6563. ** is a NULL pointer, then SQLite performs a search for an appropriate
  6564. ** temporary file directory.
  6565. **
  6566. ** Applications are strongly discouraged from using this global variable.
  6567. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  6568. ** But for all other platforms, it is highly recommended that applications
  6569. ** neither read nor write this variable. This global variable is a relic
  6570. ** that exists for backwards compatibility of legacy applications and should
  6571. ** be avoided in new projects.
  6572. **
  6573. ** It is not safe to read or modify this variable in more than one
  6574. ** thread at a time. It is not safe to read or modify this variable
  6575. ** if a [database connection] is being used at the same time in a separate
  6576. ** thread.
  6577. ** It is intended that this variable be set once
  6578. ** as part of process initialization and before any SQLite interface
  6579. ** routines have been called and that this variable remain unchanged
  6580. ** thereafter.
  6581. **
  6582. ** ^The [temp_store_directory pragma] may modify this variable and cause
  6583. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6584. ** the [temp_store_directory pragma] always assumes that any string
  6585. ** that this variable points to is held in memory obtained from
  6586. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6587. ** using [sqlite3_free].
  6588. ** Hence, if this variable is modified directly, either it should be
  6589. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6590. ** or else the use of the [temp_store_directory pragma] should be avoided.
  6591. ** Except when requested by the [temp_store_directory pragma], SQLite
  6592. ** does not free the memory that sqlite3_temp_directory points to. If
  6593. ** the application wants that memory to be freed, it must do
  6594. ** so itself, taking care to only do so after all [database connection]
  6595. ** objects have been destroyed.
  6596. **
  6597. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  6598. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  6599. ** features that require the use of temporary files may fail. Here is an
  6600. ** example of how to do this using C++ with the Windows Runtime:
  6601. **
  6602. ** <blockquote><pre>
  6603. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  6604. ** &nbsp; TemporaryFolder->Path->Data();
  6605. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  6606. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  6607. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  6608. ** &nbsp; NULL, NULL);
  6609. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  6610. ** </pre></blockquote>
  6611. */
  6612. SQLITE_API char *sqlite3_temp_directory;
  6613. /*
  6614. ** CAPI3REF: Name Of The Folder Holding Database Files
  6615. **
  6616. ** ^(If this global variable is made to point to a string which is
  6617. ** the name of a folder (a.k.a. directory), then all database files
  6618. ** specified with a relative pathname and created or accessed by
  6619. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  6620. ** to be relative to that directory.)^ ^If this variable is a NULL
  6621. ** pointer, then SQLite assumes that all database files specified
  6622. ** with a relative pathname are relative to the current directory
  6623. ** for the process. Only the windows VFS makes use of this global
  6624. ** variable; it is ignored by the unix VFS.
  6625. **
  6626. ** Changing the value of this variable while a database connection is
  6627. ** open can result in a corrupt database.
  6628. **
  6629. ** It is not safe to read or modify this variable in more than one
  6630. ** thread at a time. It is not safe to read or modify this variable
  6631. ** if a [database connection] is being used at the same time in a separate
  6632. ** thread.
  6633. ** It is intended that this variable be set once
  6634. ** as part of process initialization and before any SQLite interface
  6635. ** routines have been called and that this variable remain unchanged
  6636. ** thereafter.
  6637. **
  6638. ** ^The [data_store_directory pragma] may modify this variable and cause
  6639. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6640. ** the [data_store_directory pragma] always assumes that any string
  6641. ** that this variable points to is held in memory obtained from
  6642. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6643. ** using [sqlite3_free].
  6644. ** Hence, if this variable is modified directly, either it should be
  6645. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6646. ** or else the use of the [data_store_directory pragma] should be avoided.
  6647. */
  6648. SQLITE_API char *sqlite3_data_directory;
  6649. /*
  6650. ** CAPI3REF: Win32 Specific Interface
  6651. **
  6652. ** These interfaces are available only on Windows. The
  6653. ** [sqlite3_win32_set_directory] interface is used to set the value associated
  6654. ** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
  6655. ** zValue, depending on the value of the type parameter. The zValue parameter
  6656. ** should be NULL to cause the previous value to be freed via [sqlite3_free];
  6657. ** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
  6658. ** prior to being used. The [sqlite3_win32_set_directory] interface returns
  6659. ** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
  6660. ** or [SQLITE_NOMEM] if memory could not be allocated. The value of the
  6661. ** [sqlite3_data_directory] variable is intended to act as a replacement for
  6662. ** the current directory on the sub-platforms of Win32 where that concept is
  6663. ** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and
  6664. ** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
  6665. ** sqlite3_win32_set_directory interface except the string parameter must be
  6666. ** UTF-8 or UTF-16, respectively.
  6667. */
  6668. SQLITE_API int sqlite3_win32_set_directory(
  6669. unsigned long type, /* Identifier for directory being set or reset */
  6670. void *zValue /* New value for directory being set or reset */
  6671. );
  6672. SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
  6673. SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
  6674. /*
  6675. ** CAPI3REF: Win32 Directory Types
  6676. **
  6677. ** These macros are only available on Windows. They define the allowed values
  6678. ** for the type argument to the [sqlite3_win32_set_directory] interface.
  6679. */
  6680. #define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1
  6681. #define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2
  6682. /*
  6683. ** CAPI3REF: Test For Auto-Commit Mode
  6684. ** KEYWORDS: {autocommit mode}
  6685. ** METHOD: sqlite3
  6686. **
  6687. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  6688. ** zero if the given database connection is or is not in autocommit mode,
  6689. ** respectively. ^Autocommit mode is on by default.
  6690. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  6691. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  6692. **
  6693. ** If certain kinds of errors occur on a statement within a multi-statement
  6694. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  6695. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  6696. ** transaction might be rolled back automatically. The only way to
  6697. ** find out whether SQLite automatically rolled back the transaction after
  6698. ** an error is to use this function.
  6699. **
  6700. ** If another thread changes the autocommit status of the database
  6701. ** connection while this routine is running, then the return value
  6702. ** is undefined.
  6703. */
  6704. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  6705. /*
  6706. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  6707. ** METHOD: sqlite3_stmt
  6708. **
  6709. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  6710. ** to which a [prepared statement] belongs. ^The [database connection]
  6711. ** returned by sqlite3_db_handle is the same [database connection]
  6712. ** that was the first argument
  6713. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  6714. ** create the statement in the first place.
  6715. */
  6716. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  6717. /*
  6718. ** CAPI3REF: Return The Filename For A Database Connection
  6719. ** METHOD: sqlite3
  6720. **
  6721. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  6722. ** associated with database N of connection D. ^The main database file
  6723. ** has the name "main". If there is no attached database N on the database
  6724. ** connection D, or if database N is a temporary or in-memory database, then
  6725. ** this function will return either a NULL pointer or an empty string.
  6726. **
  6727. ** ^The filename returned by this function is the output of the
  6728. ** xFullPathname method of the [VFS]. ^In other words, the filename
  6729. ** will be an absolute pathname, even if the filename used
  6730. ** to open the database originally was a URI or relative pathname.
  6731. */
  6732. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  6733. /*
  6734. ** CAPI3REF: Determine if a database is read-only
  6735. ** METHOD: sqlite3
  6736. **
  6737. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  6738. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  6739. ** the name of a database on connection D.
  6740. */
  6741. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  6742. /*
  6743. ** CAPI3REF: Find the next prepared statement
  6744. ** METHOD: sqlite3
  6745. **
  6746. ** ^This interface returns a pointer to the next [prepared statement] after
  6747. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  6748. ** then this interface returns a pointer to the first prepared statement
  6749. ** associated with the database connection pDb. ^If no prepared statement
  6750. ** satisfies the conditions of this routine, it returns NULL.
  6751. **
  6752. ** The [database connection] pointer D in a call to
  6753. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  6754. ** connection and in particular must not be a NULL pointer.
  6755. */
  6756. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  6757. /*
  6758. ** CAPI3REF: Commit And Rollback Notification Callbacks
  6759. ** METHOD: sqlite3
  6760. **
  6761. ** ^The sqlite3_commit_hook() interface registers a callback
  6762. ** function to be invoked whenever a transaction is [COMMIT | committed].
  6763. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  6764. ** for the same database connection is overridden.
  6765. ** ^The sqlite3_rollback_hook() interface registers a callback
  6766. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  6767. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  6768. ** for the same database connection is overridden.
  6769. ** ^The pArg argument is passed through to the callback.
  6770. ** ^If the callback on a commit hook function returns non-zero,
  6771. ** then the commit is converted into a rollback.
  6772. **
  6773. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  6774. ** return the P argument from the previous call of the same function
  6775. ** on the same [database connection] D, or NULL for
  6776. ** the first call for each function on D.
  6777. **
  6778. ** The commit and rollback hook callbacks are not reentrant.
  6779. ** The callback implementation must not do anything that will modify
  6780. ** the database connection that invoked the callback. Any actions
  6781. ** to modify the database connection must be deferred until after the
  6782. ** completion of the [sqlite3_step()] call that triggered the commit
  6783. ** or rollback hook in the first place.
  6784. ** Note that running any other SQL statements, including SELECT statements,
  6785. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  6786. ** the database connections for the meaning of "modify" in this paragraph.
  6787. **
  6788. ** ^Registering a NULL function disables the callback.
  6789. **
  6790. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  6791. ** operation is allowed to continue normally. ^If the commit hook
  6792. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  6793. ** ^The rollback hook is invoked on a rollback that results from a commit
  6794. ** hook returning non-zero, just as it would be with any other rollback.
  6795. **
  6796. ** ^For the purposes of this API, a transaction is said to have been
  6797. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  6798. ** an error or constraint causes an implicit rollback to occur.
  6799. ** ^The rollback callback is not invoked if a transaction is
  6800. ** automatically rolled back because the database connection is closed.
  6801. **
  6802. ** See also the [sqlite3_update_hook()] interface.
  6803. */
  6804. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  6805. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  6806. /*
  6807. ** CAPI3REF: Data Change Notification Callbacks
  6808. ** METHOD: sqlite3
  6809. **
  6810. ** ^The sqlite3_update_hook() interface registers a callback function
  6811. ** with the [database connection] identified by the first argument
  6812. ** to be invoked whenever a row is updated, inserted or deleted in
  6813. ** a [rowid table].
  6814. ** ^Any callback set by a previous call to this function
  6815. ** for the same database connection is overridden.
  6816. **
  6817. ** ^The second argument is a pointer to the function to invoke when a
  6818. ** row is updated, inserted or deleted in a rowid table.
  6819. ** ^The first argument to the callback is a copy of the third argument
  6820. ** to sqlite3_update_hook().
  6821. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  6822. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  6823. ** to be invoked.
  6824. ** ^The third and fourth arguments to the callback contain pointers to the
  6825. ** database and table name containing the affected row.
  6826. ** ^The final callback parameter is the [rowid] of the row.
  6827. ** ^In the case of an update, this is the [rowid] after the update takes place.
  6828. **
  6829. ** ^(The update hook is not invoked when internal system tables are
  6830. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  6831. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  6832. **
  6833. ** ^In the current implementation, the update hook
  6834. ** is not invoked when conflicting rows are deleted because of an
  6835. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  6836. ** invoked when rows are deleted using the [truncate optimization].
  6837. ** The exceptions defined in this paragraph might change in a future
  6838. ** release of SQLite.
  6839. **
  6840. ** The update hook implementation must not do anything that will modify
  6841. ** the database connection that invoked the update hook. Any actions
  6842. ** to modify the database connection must be deferred until after the
  6843. ** completion of the [sqlite3_step()] call that triggered the update hook.
  6844. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  6845. ** database connections for the meaning of "modify" in this paragraph.
  6846. **
  6847. ** ^The sqlite3_update_hook(D,C,P) function
  6848. ** returns the P argument from the previous call
  6849. ** on the same [database connection] D, or NULL for
  6850. ** the first call on D.
  6851. **
  6852. ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
  6853. ** and [sqlite3_preupdate_hook()] interfaces.
  6854. */
  6855. SQLITE_API void *sqlite3_update_hook(
  6856. sqlite3*,
  6857. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  6858. void*
  6859. );
  6860. /*
  6861. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  6862. **
  6863. ** ^(This routine enables or disables the sharing of the database cache
  6864. ** and schema data structures between [database connection | connections]
  6865. ** to the same database. Sharing is enabled if the argument is true
  6866. ** and disabled if the argument is false.)^
  6867. **
  6868. ** ^Cache sharing is enabled and disabled for an entire process.
  6869. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
  6870. ** In prior versions of SQLite,
  6871. ** sharing was enabled or disabled for each thread separately.
  6872. **
  6873. ** ^(The cache sharing mode set by this interface effects all subsequent
  6874. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  6875. ** Existing database connections continue use the sharing mode
  6876. ** that was in effect at the time they were opened.)^
  6877. **
  6878. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  6879. ** successfully. An [error code] is returned otherwise.)^
  6880. **
  6881. ** ^Shared cache is disabled by default. But this might change in
  6882. ** future releases of SQLite. Applications that care about shared
  6883. ** cache setting should set it explicitly.
  6884. **
  6885. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  6886. ** and will always return SQLITE_MISUSE. On those systems,
  6887. ** shared cache mode should be enabled per-database connection via
  6888. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  6889. **
  6890. ** This interface is threadsafe on processors where writing a
  6891. ** 32-bit integer is atomic.
  6892. **
  6893. ** See Also: [SQLite Shared-Cache Mode]
  6894. */
  6895. SQLITE_API int sqlite3_enable_shared_cache(int);
  6896. /*
  6897. ** CAPI3REF: Attempt To Free Heap Memory
  6898. **
  6899. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  6900. ** of heap memory by deallocating non-essential memory allocations
  6901. ** held by the database library. Memory used to cache database
  6902. ** pages to improve performance is an example of non-essential memory.
  6903. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  6904. ** which might be more or less than the amount requested.
  6905. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  6906. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6907. **
  6908. ** See also: [sqlite3_db_release_memory()]
  6909. */
  6910. SQLITE_API int sqlite3_release_memory(int);
  6911. /*
  6912. ** CAPI3REF: Free Memory Used By A Database Connection
  6913. ** METHOD: sqlite3
  6914. **
  6915. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  6916. ** memory as possible from database connection D. Unlike the
  6917. ** [sqlite3_release_memory()] interface, this interface is in effect even
  6918. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  6919. ** omitted.
  6920. **
  6921. ** See also: [sqlite3_release_memory()]
  6922. */
  6923. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  6924. /*
  6925. ** CAPI3REF: Impose A Limit On Heap Size
  6926. **
  6927. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  6928. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  6929. ** ^SQLite strives to keep heap memory utilization below the soft heap
  6930. ** limit by reducing the number of pages held in the page cache
  6931. ** as heap memory usages approaches the limit.
  6932. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  6933. ** below the limit, it will exceed the limit rather than generate
  6934. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  6935. ** is advisory only.
  6936. **
  6937. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  6938. ** the soft heap limit prior to the call, or negative in the case of an
  6939. ** error. ^If the argument N is negative
  6940. ** then no change is made to the soft heap limit. Hence, the current
  6941. ** size of the soft heap limit can be determined by invoking
  6942. ** sqlite3_soft_heap_limit64() with a negative argument.
  6943. **
  6944. ** ^If the argument N is zero then the soft heap limit is disabled.
  6945. **
  6946. ** ^(The soft heap limit is not enforced in the current implementation
  6947. ** if one or more of following conditions are true:
  6948. **
  6949. ** <ul>
  6950. ** <li> The soft heap limit is set to zero.
  6951. ** <li> Memory accounting is disabled using a combination of the
  6952. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  6953. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  6954. ** <li> An alternative page cache implementation is specified using
  6955. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  6956. ** <li> The page cache allocates from its own memory pool supplied
  6957. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  6958. ** from the heap.
  6959. ** </ul>)^
  6960. **
  6961. ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
  6962. ** the soft heap limit is enforced
  6963. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  6964. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  6965. ** the soft heap limit is enforced on every memory allocation. Without
  6966. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  6967. ** when memory is allocated by the page cache. Testing suggests that because
  6968. ** the page cache is the predominate memory user in SQLite, most
  6969. ** applications will achieve adequate soft heap limit enforcement without
  6970. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6971. **
  6972. ** The circumstances under which SQLite will enforce the soft heap limit may
  6973. ** changes in future releases of SQLite.
  6974. */
  6975. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  6976. /*
  6977. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  6978. ** DEPRECATED
  6979. **
  6980. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  6981. ** interface. This routine is provided for historical compatibility
  6982. ** only. All new applications should use the
  6983. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  6984. */
  6985. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  6986. /*
  6987. ** CAPI3REF: Extract Metadata About A Column Of A Table
  6988. ** METHOD: sqlite3
  6989. **
  6990. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  6991. ** information about column C of table T in database D
  6992. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  6993. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  6994. ** the final five arguments with appropriate values if the specified
  6995. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  6996. ** SQLITE_ERROR and if the specified column does not exist.
  6997. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  6998. ** NULL pointer, then this routine simply checks for the existence of the
  6999. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  7000. ** does not. If the table name parameter T in a call to
  7001. ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
  7002. ** undefined behavior.
  7003. **
  7004. ** ^The column is identified by the second, third and fourth parameters to
  7005. ** this function. ^(The second parameter is either the name of the database
  7006. ** (i.e. "main", "temp", or an attached database) containing the specified
  7007. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  7008. ** for the table using the same algorithm used by the database engine to
  7009. ** resolve unqualified table references.
  7010. **
  7011. ** ^The third and fourth parameters to this function are the table and column
  7012. ** name of the desired column, respectively.
  7013. **
  7014. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  7015. ** and subsequent parameters to this function. ^Any of these arguments may be
  7016. ** NULL, in which case the corresponding element of metadata is omitted.
  7017. **
  7018. ** ^(<blockquote>
  7019. ** <table border="1">
  7020. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  7021. **
  7022. ** <tr><td> 5th <td> const char* <td> Data type
  7023. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  7024. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  7025. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  7026. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  7027. ** </table>
  7028. ** </blockquote>)^
  7029. **
  7030. ** ^The memory pointed to by the character pointers returned for the
  7031. ** declaration type and collation sequence is valid until the next
  7032. ** call to any SQLite API function.
  7033. **
  7034. ** ^If the specified table is actually a view, an [error code] is returned.
  7035. **
  7036. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  7037. ** is not a [WITHOUT ROWID] table and an
  7038. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  7039. ** parameters are set for the explicitly declared column. ^(If there is no
  7040. ** [INTEGER PRIMARY KEY] column, then the outputs
  7041. ** for the [rowid] are set as follows:
  7042. **
  7043. ** <pre>
  7044. ** data type: "INTEGER"
  7045. ** collation sequence: "BINARY"
  7046. ** not null: 0
  7047. ** primary key: 1
  7048. ** auto increment: 0
  7049. ** </pre>)^
  7050. **
  7051. ** ^This function causes all database schemas to be read from disk and
  7052. ** parsed, if that has not already been done, and returns an error if
  7053. ** any errors are encountered while loading the schema.
  7054. */
  7055. SQLITE_API int sqlite3_table_column_metadata(
  7056. sqlite3 *db, /* Connection handle */
  7057. const char *zDbName, /* Database name or NULL */
  7058. const char *zTableName, /* Table name */
  7059. const char *zColumnName, /* Column name */
  7060. char const **pzDataType, /* OUTPUT: Declared data type */
  7061. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  7062. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  7063. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  7064. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  7065. );
  7066. /*
  7067. ** CAPI3REF: Load An Extension
  7068. ** METHOD: sqlite3
  7069. **
  7070. ** ^This interface loads an SQLite extension library from the named file.
  7071. **
  7072. ** ^The sqlite3_load_extension() interface attempts to load an
  7073. ** [SQLite extension] library contained in the file zFile. If
  7074. ** the file cannot be loaded directly, attempts are made to load
  7075. ** with various operating-system specific extensions added.
  7076. ** So for example, if "samplelib" cannot be loaded, then names like
  7077. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  7078. ** be tried also.
  7079. **
  7080. ** ^The entry point is zProc.
  7081. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  7082. ** entry point name on its own. It first tries "sqlite3_extension_init".
  7083. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  7084. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  7085. ** characters in the filename from the last "/" to the first following
  7086. ** "." and omitting any initial "lib".)^
  7087. ** ^The sqlite3_load_extension() interface returns
  7088. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  7089. ** ^If an error occurs and pzErrMsg is not 0, then the
  7090. ** [sqlite3_load_extension()] interface shall attempt to
  7091. ** fill *pzErrMsg with error message text stored in memory
  7092. ** obtained from [sqlite3_malloc()]. The calling function
  7093. ** should free this memory by calling [sqlite3_free()].
  7094. **
  7095. ** ^Extension loading must be enabled using
  7096. ** [sqlite3_enable_load_extension()] or
  7097. ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
  7098. ** prior to calling this API,
  7099. ** otherwise an error will be returned.
  7100. **
  7101. ** <b>Security warning:</b> It is recommended that the
  7102. ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
  7103. ** interface. The use of the [sqlite3_enable_load_extension()] interface
  7104. ** should be avoided. This will keep the SQL function [load_extension()]
  7105. ** disabled and prevent SQL injections from giving attackers
  7106. ** access to extension loading capabilities.
  7107. **
  7108. ** See also the [load_extension() SQL function].
  7109. */
  7110. SQLITE_API int sqlite3_load_extension(
  7111. sqlite3 *db, /* Load the extension into this database connection */
  7112. const char *zFile, /* Name of the shared library containing extension */
  7113. const char *zProc, /* Entry point. Derived from zFile if 0 */
  7114. char **pzErrMsg /* Put error message here if not 0 */
  7115. );
  7116. /*
  7117. ** CAPI3REF: Enable Or Disable Extension Loading
  7118. ** METHOD: sqlite3
  7119. **
  7120. ** ^So as not to open security holes in older applications that are
  7121. ** unprepared to deal with [extension loading], and as a means of disabling
  7122. ** [extension loading] while evaluating user-entered SQL, the following API
  7123. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  7124. **
  7125. ** ^Extension loading is off by default.
  7126. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  7127. ** to turn extension loading on and call it with onoff==0 to turn
  7128. ** it back off again.
  7129. **
  7130. ** ^This interface enables or disables both the C-API
  7131. ** [sqlite3_load_extension()] and the SQL function [load_extension()].
  7132. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
  7133. ** to enable or disable only the C-API.)^
  7134. **
  7135. ** <b>Security warning:</b> It is recommended that extension loading
  7136. ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
  7137. ** rather than this interface, so the [load_extension()] SQL function
  7138. ** remains disabled. This will prevent SQL injections from giving attackers
  7139. ** access to extension loading capabilities.
  7140. */
  7141. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  7142. /*
  7143. ** CAPI3REF: Automatically Load Statically Linked Extensions
  7144. **
  7145. ** ^This interface causes the xEntryPoint() function to be invoked for
  7146. ** each new [database connection] that is created. The idea here is that
  7147. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  7148. ** that is to be automatically loaded into all new database connections.
  7149. **
  7150. ** ^(Even though the function prototype shows that xEntryPoint() takes
  7151. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  7152. ** arguments and expects an integer result as if the signature of the
  7153. ** entry point where as follows:
  7154. **
  7155. ** <blockquote><pre>
  7156. ** &nbsp; int xEntryPoint(
  7157. ** &nbsp; sqlite3 *db,
  7158. ** &nbsp; const char **pzErrMsg,
  7159. ** &nbsp; const struct sqlite3_api_routines *pThunk
  7160. ** &nbsp; );
  7161. ** </pre></blockquote>)^
  7162. **
  7163. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  7164. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  7165. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  7166. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  7167. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  7168. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  7169. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  7170. **
  7171. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  7172. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  7173. ** will be called more than once for each database connection that is opened.
  7174. **
  7175. ** See also: [sqlite3_reset_auto_extension()]
  7176. ** and [sqlite3_cancel_auto_extension()]
  7177. */
  7178. SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
  7179. /*
  7180. ** CAPI3REF: Cancel Automatic Extension Loading
  7181. **
  7182. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  7183. ** initialization routine X that was registered using a prior call to
  7184. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  7185. ** routine returns 1 if initialization routine X was successfully
  7186. ** unregistered and it returns 0 if X was not on the list of initialization
  7187. ** routines.
  7188. */
  7189. SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
  7190. /*
  7191. ** CAPI3REF: Reset Automatic Extension Loading
  7192. **
  7193. ** ^This interface disables all automatic extensions previously
  7194. ** registered using [sqlite3_auto_extension()].
  7195. */
  7196. SQLITE_API void sqlite3_reset_auto_extension(void);
  7197. /*
  7198. ** The interface to the virtual-table mechanism is currently considered
  7199. ** to be experimental. The interface might change in incompatible ways.
  7200. ** If this is a problem for you, do not use the interface at this time.
  7201. **
  7202. ** When the virtual-table mechanism stabilizes, we will declare the
  7203. ** interface fixed, support it indefinitely, and remove this comment.
  7204. */
  7205. /*
  7206. ** Structures used by the virtual table interface
  7207. */
  7208. typedef struct sqlite3_vtab sqlite3_vtab;
  7209. typedef struct sqlite3_index_info sqlite3_index_info;
  7210. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  7211. typedef struct sqlite3_module sqlite3_module;
  7212. /*
  7213. ** CAPI3REF: Virtual Table Object
  7214. ** KEYWORDS: sqlite3_module {virtual table module}
  7215. **
  7216. ** This structure, sometimes called a "virtual table module",
  7217. ** defines the implementation of a [virtual tables].
  7218. ** This structure consists mostly of methods for the module.
  7219. **
  7220. ** ^A virtual table module is created by filling in a persistent
  7221. ** instance of this structure and passing a pointer to that instance
  7222. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  7223. ** ^The registration remains valid until it is replaced by a different
  7224. ** module or until the [database connection] closes. The content
  7225. ** of this structure must not change while it is registered with
  7226. ** any database connection.
  7227. */
  7228. struct sqlite3_module {
  7229. int iVersion;
  7230. int (*xCreate)(sqlite3*, void *pAux,
  7231. int argc, const char *const*argv,
  7232. sqlite3_vtab **ppVTab, char**);
  7233. int (*xConnect)(sqlite3*, void *pAux,
  7234. int argc, const char *const*argv,
  7235. sqlite3_vtab **ppVTab, char**);
  7236. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  7237. int (*xDisconnect)(sqlite3_vtab *pVTab);
  7238. int (*xDestroy)(sqlite3_vtab *pVTab);
  7239. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  7240. int (*xClose)(sqlite3_vtab_cursor*);
  7241. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  7242. int argc, sqlite3_value **argv);
  7243. int (*xNext)(sqlite3_vtab_cursor*);
  7244. int (*xEof)(sqlite3_vtab_cursor*);
  7245. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  7246. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  7247. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  7248. int (*xBegin)(sqlite3_vtab *pVTab);
  7249. int (*xSync)(sqlite3_vtab *pVTab);
  7250. int (*xCommit)(sqlite3_vtab *pVTab);
  7251. int (*xRollback)(sqlite3_vtab *pVTab);
  7252. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  7253. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  7254. void **ppArg);
  7255. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  7256. /* The methods above are in version 1 of the sqlite_module object. Those
  7257. ** below are for version 2 and greater. */
  7258. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  7259. int (*xRelease)(sqlite3_vtab *pVTab, int);
  7260. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  7261. /* The methods above are in versions 1 and 2 of the sqlite_module object.
  7262. ** Those below are for version 3 and greater. */
  7263. int (*xShadowName)(const char*);
  7264. };
  7265. /*
  7266. ** CAPI3REF: Virtual Table Indexing Information
  7267. ** KEYWORDS: sqlite3_index_info
  7268. **
  7269. ** The sqlite3_index_info structure and its substructures is used as part
  7270. ** of the [virtual table] interface to
  7271. ** pass information into and receive the reply from the [xBestIndex]
  7272. ** method of a [virtual table module]. The fields under **Inputs** are the
  7273. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  7274. ** results into the **Outputs** fields.
  7275. **
  7276. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  7277. **
  7278. ** <blockquote>column OP expr</blockquote>
  7279. **
  7280. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  7281. ** stored in aConstraint[].op using one of the
  7282. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  7283. ** ^(The index of the column is stored in
  7284. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  7285. ** expr on the right-hand side can be evaluated (and thus the constraint
  7286. ** is usable) and false if it cannot.)^
  7287. **
  7288. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  7289. ** and makes other simplifications to the WHERE clause in an attempt to
  7290. ** get as many WHERE clause terms into the form shown above as possible.
  7291. ** ^The aConstraint[] array only reports WHERE clause terms that are
  7292. ** relevant to the particular virtual table being queried.
  7293. **
  7294. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  7295. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  7296. **
  7297. ** The colUsed field indicates which columns of the virtual table may be
  7298. ** required by the current scan. Virtual table columns are numbered from
  7299. ** zero in the order in which they appear within the CREATE TABLE statement
  7300. ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  7301. ** the corresponding bit is set within the colUsed mask if the column may be
  7302. ** required by SQLite. If the table has at least 64 columns and any column
  7303. ** to the right of the first 63 is required, then bit 63 of colUsed is also
  7304. ** set. In other words, column iCol may be required if the expression
  7305. ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
  7306. ** non-zero.
  7307. **
  7308. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  7309. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  7310. ** the right-hand side of the corresponding aConstraint[] is evaluated
  7311. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  7312. ** is true, then the constraint is assumed to be fully handled by the
  7313. ** virtual table and is not checked again by SQLite.)^
  7314. **
  7315. ** ^The idxNum and idxPtr values are recorded and passed into the
  7316. ** [xFilter] method.
  7317. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  7318. ** needToFreeIdxPtr is true.
  7319. **
  7320. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  7321. ** the correct order to satisfy the ORDER BY clause so that no separate
  7322. ** sorting step is required.
  7323. **
  7324. ** ^The estimatedCost value is an estimate of the cost of a particular
  7325. ** strategy. A cost of N indicates that the cost of the strategy is similar
  7326. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  7327. ** indicates that the expense of the operation is similar to that of a
  7328. ** binary search on a unique indexed field of an SQLite table with N rows.
  7329. **
  7330. ** ^The estimatedRows value is an estimate of the number of rows that
  7331. ** will be returned by the strategy.
  7332. **
  7333. ** The xBestIndex method may optionally populate the idxFlags field with a
  7334. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  7335. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  7336. ** assumes that the strategy may visit at most one row.
  7337. **
  7338. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  7339. ** SQLite also assumes that if a call to the xUpdate() method is made as
  7340. ** part of the same statement to delete or update a virtual table row and the
  7341. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  7342. ** any database changes. In other words, if the xUpdate() returns
  7343. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  7344. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  7345. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  7346. ** the xUpdate method are automatically rolled back by SQLite.
  7347. **
  7348. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  7349. ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
  7350. ** If a virtual table extension is
  7351. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  7352. ** to read or write the estimatedRows field are undefined (but are likely
  7353. ** to included crashing the application). The estimatedRows field should
  7354. ** therefore only be used if [sqlite3_libversion_number()] returns a
  7355. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  7356. ** was added for [version 3.9.0] ([dateof:3.9.0]).
  7357. ** It may therefore only be used if
  7358. ** sqlite3_libversion_number() returns a value greater than or equal to
  7359. ** 3009000.
  7360. */
  7361. struct sqlite3_index_info {
  7362. /* Inputs */
  7363. int nConstraint; /* Number of entries in aConstraint */
  7364. struct sqlite3_index_constraint {
  7365. int iColumn; /* Column constrained. -1 for ROWID */
  7366. unsigned char op; /* Constraint operator */
  7367. unsigned char usable; /* True if this constraint is usable */
  7368. int iTermOffset; /* Used internally - xBestIndex should ignore */
  7369. } *aConstraint; /* Table of WHERE clause constraints */
  7370. int nOrderBy; /* Number of terms in the ORDER BY clause */
  7371. struct sqlite3_index_orderby {
  7372. int iColumn; /* Column number */
  7373. unsigned char desc; /* True for DESC. False for ASC. */
  7374. } *aOrderBy; /* The ORDER BY clause */
  7375. /* Outputs */
  7376. struct sqlite3_index_constraint_usage {
  7377. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  7378. unsigned char omit; /* Do not code a test for this constraint */
  7379. } *aConstraintUsage;
  7380. int idxNum; /* Number used to identify the index */
  7381. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  7382. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  7383. int orderByConsumed; /* True if output is already ordered */
  7384. double estimatedCost; /* Estimated cost of using this index */
  7385. /* Fields below are only available in SQLite 3.8.2 and later */
  7386. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  7387. /* Fields below are only available in SQLite 3.9.0 and later */
  7388. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  7389. /* Fields below are only available in SQLite 3.10.0 and later */
  7390. sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
  7391. };
  7392. /*
  7393. ** CAPI3REF: Virtual Table Scan Flags
  7394. **
  7395. ** Virtual table implementations are allowed to set the
  7396. ** [sqlite3_index_info].idxFlags field to some combination of
  7397. ** these bits.
  7398. */
  7399. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  7400. /*
  7401. ** CAPI3REF: Virtual Table Constraint Operator Codes
  7402. **
  7403. ** These macros defined the allowed values for the
  7404. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  7405. ** an operator that is part of a constraint term in the wHERE clause of
  7406. ** a query that uses a [virtual table].
  7407. */
  7408. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  7409. #define SQLITE_INDEX_CONSTRAINT_GT 4
  7410. #define SQLITE_INDEX_CONSTRAINT_LE 8
  7411. #define SQLITE_INDEX_CONSTRAINT_LT 16
  7412. #define SQLITE_INDEX_CONSTRAINT_GE 32
  7413. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  7414. #define SQLITE_INDEX_CONSTRAINT_LIKE 65
  7415. #define SQLITE_INDEX_CONSTRAINT_GLOB 66
  7416. #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
  7417. #define SQLITE_INDEX_CONSTRAINT_NE 68
  7418. #define SQLITE_INDEX_CONSTRAINT_ISNOT 69
  7419. #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
  7420. #define SQLITE_INDEX_CONSTRAINT_ISNULL 71
  7421. #define SQLITE_INDEX_CONSTRAINT_IS 72
  7422. #define SQLITE_INDEX_CONSTRAINT_FUNCTION 150
  7423. /*
  7424. ** CAPI3REF: Register A Virtual Table Implementation
  7425. ** METHOD: sqlite3
  7426. **
  7427. ** ^These routines are used to register a new [virtual table module] name.
  7428. ** ^Module names must be registered before
  7429. ** creating a new [virtual table] using the module and before using a
  7430. ** preexisting [virtual table] for the module.
  7431. **
  7432. ** ^The module name is registered on the [database connection] specified
  7433. ** by the first parameter. ^The name of the module is given by the
  7434. ** second parameter. ^The third parameter is a pointer to
  7435. ** the implementation of the [virtual table module]. ^The fourth
  7436. ** parameter is an arbitrary client data pointer that is passed through
  7437. ** into the [xCreate] and [xConnect] methods of the virtual table module
  7438. ** when a new virtual table is be being created or reinitialized.
  7439. **
  7440. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  7441. ** is a pointer to a destructor for the pClientData. ^SQLite will
  7442. ** invoke the destructor function (if it is not NULL) when SQLite
  7443. ** no longer needs the pClientData pointer. ^The destructor will also
  7444. ** be invoked if the call to sqlite3_create_module_v2() fails.
  7445. ** ^The sqlite3_create_module()
  7446. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  7447. ** destructor.
  7448. */
  7449. SQLITE_API int sqlite3_create_module(
  7450. sqlite3 *db, /* SQLite connection to register module with */
  7451. const char *zName, /* Name of the module */
  7452. const sqlite3_module *p, /* Methods for the module */
  7453. void *pClientData /* Client data for xCreate/xConnect */
  7454. );
  7455. SQLITE_API int sqlite3_create_module_v2(
  7456. sqlite3 *db, /* SQLite connection to register module with */
  7457. const char *zName, /* Name of the module */
  7458. const sqlite3_module *p, /* Methods for the module */
  7459. void *pClientData, /* Client data for xCreate/xConnect */
  7460. void(*xDestroy)(void*) /* Module destructor function */
  7461. );
  7462. /*
  7463. ** CAPI3REF: Virtual Table Instance Object
  7464. ** KEYWORDS: sqlite3_vtab
  7465. **
  7466. ** Every [virtual table module] implementation uses a subclass
  7467. ** of this object to describe a particular instance
  7468. ** of the [virtual table]. Each subclass will
  7469. ** be tailored to the specific needs of the module implementation.
  7470. ** The purpose of this superclass is to define certain fields that are
  7471. ** common to all module implementations.
  7472. **
  7473. ** ^Virtual tables methods can set an error message by assigning a
  7474. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  7475. ** take care that any prior string is freed by a call to [sqlite3_free()]
  7476. ** prior to assigning a new string to zErrMsg. ^After the error message
  7477. ** is delivered up to the client application, the string will be automatically
  7478. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  7479. */
  7480. struct sqlite3_vtab {
  7481. const sqlite3_module *pModule; /* The module for this virtual table */
  7482. int nRef; /* Number of open cursors */
  7483. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  7484. /* Virtual table implementations will typically add additional fields */
  7485. };
  7486. /*
  7487. ** CAPI3REF: Virtual Table Cursor Object
  7488. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  7489. **
  7490. ** Every [virtual table module] implementation uses a subclass of the
  7491. ** following structure to describe cursors that point into the
  7492. ** [virtual table] and are used
  7493. ** to loop through the virtual table. Cursors are created using the
  7494. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  7495. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  7496. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  7497. ** of the module. Each module implementation will define
  7498. ** the content of a cursor structure to suit its own needs.
  7499. **
  7500. ** This superclass exists in order to define fields of the cursor that
  7501. ** are common to all implementations.
  7502. */
  7503. struct sqlite3_vtab_cursor {
  7504. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  7505. /* Virtual table implementations will typically add additional fields */
  7506. };
  7507. /*
  7508. ** CAPI3REF: Declare The Schema Of A Virtual Table
  7509. **
  7510. ** ^The [xCreate] and [xConnect] methods of a
  7511. ** [virtual table module] call this interface
  7512. ** to declare the format (the names and datatypes of the columns) of
  7513. ** the virtual tables they implement.
  7514. */
  7515. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  7516. /*
  7517. ** CAPI3REF: Overload A Function For A Virtual Table
  7518. ** METHOD: sqlite3
  7519. **
  7520. ** ^(Virtual tables can provide alternative implementations of functions
  7521. ** using the [xFindFunction] method of the [virtual table module].
  7522. ** But global versions of those functions
  7523. ** must exist in order to be overloaded.)^
  7524. **
  7525. ** ^(This API makes sure a global version of a function with a particular
  7526. ** name and number of parameters exists. If no such function exists
  7527. ** before this API is called, a new function is created.)^ ^The implementation
  7528. ** of the new function always causes an exception to be thrown. So
  7529. ** the new function is not good for anything by itself. Its only
  7530. ** purpose is to be a placeholder function that can be overloaded
  7531. ** by a [virtual table].
  7532. */
  7533. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  7534. /*
  7535. ** The interface to the virtual-table mechanism defined above (back up
  7536. ** to a comment remarkably similar to this one) is currently considered
  7537. ** to be experimental. The interface might change in incompatible ways.
  7538. ** If this is a problem for you, do not use the interface at this time.
  7539. **
  7540. ** When the virtual-table mechanism stabilizes, we will declare the
  7541. ** interface fixed, support it indefinitely, and remove this comment.
  7542. */
  7543. /*
  7544. ** CAPI3REF: A Handle To An Open BLOB
  7545. ** KEYWORDS: {BLOB handle} {BLOB handles}
  7546. **
  7547. ** An instance of this object represents an open BLOB on which
  7548. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  7549. ** ^Objects of this type are created by [sqlite3_blob_open()]
  7550. ** and destroyed by [sqlite3_blob_close()].
  7551. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  7552. ** can be used to read or write small subsections of the BLOB.
  7553. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  7554. */
  7555. typedef struct sqlite3_blob sqlite3_blob;
  7556. /*
  7557. ** CAPI3REF: Open A BLOB For Incremental I/O
  7558. ** METHOD: sqlite3
  7559. ** CONSTRUCTOR: sqlite3_blob
  7560. **
  7561. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  7562. ** in row iRow, column zColumn, table zTable in database zDb;
  7563. ** in other words, the same BLOB that would be selected by:
  7564. **
  7565. ** <pre>
  7566. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  7567. ** </pre>)^
  7568. **
  7569. ** ^(Parameter zDb is not the filename that contains the database, but
  7570. ** rather the symbolic name of the database. For attached databases, this is
  7571. ** the name that appears after the AS keyword in the [ATTACH] statement.
  7572. ** For the main database file, the database name is "main". For TEMP
  7573. ** tables, the database name is "temp".)^
  7574. **
  7575. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  7576. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  7577. ** read-only access.
  7578. **
  7579. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  7580. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  7581. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  7582. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  7583. ** on *ppBlob after this function it returns.
  7584. **
  7585. ** This function fails with SQLITE_ERROR if any of the following are true:
  7586. ** <ul>
  7587. ** <li> ^(Database zDb does not exist)^,
  7588. ** <li> ^(Table zTable does not exist within database zDb)^,
  7589. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  7590. ** <li> ^(Column zColumn does not exist)^,
  7591. ** <li> ^(Row iRow is not present in the table)^,
  7592. ** <li> ^(The specified column of row iRow contains a value that is not
  7593. ** a TEXT or BLOB value)^,
  7594. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  7595. ** constraint and the blob is being opened for read/write access)^,
  7596. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  7597. ** column zColumn is part of a [child key] definition and the blob is
  7598. ** being opened for read/write access)^.
  7599. ** </ul>
  7600. **
  7601. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  7602. ** [database connection] error code and message accessible via
  7603. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7604. **
  7605. ** A BLOB referenced by sqlite3_blob_open() may be read using the
  7606. ** [sqlite3_blob_read()] interface and modified by using
  7607. ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
  7608. ** different row of the same table using the [sqlite3_blob_reopen()]
  7609. ** interface. However, the column, table, or database of a [BLOB handle]
  7610. ** cannot be changed after the [BLOB handle] is opened.
  7611. **
  7612. ** ^(If the row that a BLOB handle points to is modified by an
  7613. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  7614. ** then the BLOB handle is marked as "expired".
  7615. ** This is true if any column of the row is changed, even a column
  7616. ** other than the one the BLOB handle is open on.)^
  7617. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  7618. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  7619. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  7620. ** rolled back by the expiration of the BLOB. Such changes will eventually
  7621. ** commit if the transaction continues to completion.)^
  7622. **
  7623. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  7624. ** the opened blob. ^The size of a blob may not be changed by this
  7625. ** interface. Use the [UPDATE] SQL command to change the size of a
  7626. ** blob.
  7627. **
  7628. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  7629. ** and the built-in [zeroblob] SQL function may be used to create a
  7630. ** zero-filled blob to read or write using the incremental-blob interface.
  7631. **
  7632. ** To avoid a resource leak, every open [BLOB handle] should eventually
  7633. ** be released by a call to [sqlite3_blob_close()].
  7634. **
  7635. ** See also: [sqlite3_blob_close()],
  7636. ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
  7637. ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
  7638. */
  7639. SQLITE_API int sqlite3_blob_open(
  7640. sqlite3*,
  7641. const char *zDb,
  7642. const char *zTable,
  7643. const char *zColumn,
  7644. sqlite3_int64 iRow,
  7645. int flags,
  7646. sqlite3_blob **ppBlob
  7647. );
  7648. /*
  7649. ** CAPI3REF: Move a BLOB Handle to a New Row
  7650. ** METHOD: sqlite3_blob
  7651. **
  7652. ** ^This function is used to move an existing [BLOB handle] so that it points
  7653. ** to a different row of the same database table. ^The new row is identified
  7654. ** by the rowid value passed as the second argument. Only the row can be
  7655. ** changed. ^The database, table and column on which the blob handle is open
  7656. ** remain the same. Moving an existing [BLOB handle] to a new row is
  7657. ** faster than closing the existing handle and opening a new one.
  7658. **
  7659. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  7660. ** it must exist and there must be either a blob or text value stored in
  7661. ** the nominated column.)^ ^If the new row is not present in the table, or if
  7662. ** it does not contain a blob or text value, or if another error occurs, an
  7663. ** SQLite error code is returned and the blob handle is considered aborted.
  7664. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  7665. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  7666. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  7667. ** always returns zero.
  7668. **
  7669. ** ^This function sets the database handle error code and message.
  7670. */
  7671. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  7672. /*
  7673. ** CAPI3REF: Close A BLOB Handle
  7674. ** DESTRUCTOR: sqlite3_blob
  7675. **
  7676. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  7677. ** unconditionally. Even if this routine returns an error code, the
  7678. ** handle is still closed.)^
  7679. **
  7680. ** ^If the blob handle being closed was opened for read-write access, and if
  7681. ** the database is in auto-commit mode and there are no other open read-write
  7682. ** blob handles or active write statements, the current transaction is
  7683. ** committed. ^If an error occurs while committing the transaction, an error
  7684. ** code is returned and the transaction rolled back.
  7685. **
  7686. ** Calling this function with an argument that is not a NULL pointer or an
  7687. ** open blob handle results in undefined behaviour. ^Calling this routine
  7688. ** with a null pointer (such as would be returned by a failed call to
  7689. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  7690. ** is passed a valid open blob handle, the values returned by the
  7691. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  7692. */
  7693. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  7694. /*
  7695. ** CAPI3REF: Return The Size Of An Open BLOB
  7696. ** METHOD: sqlite3_blob
  7697. **
  7698. ** ^Returns the size in bytes of the BLOB accessible via the
  7699. ** successfully opened [BLOB handle] in its only argument. ^The
  7700. ** incremental blob I/O routines can only read or overwriting existing
  7701. ** blob content; they cannot change the size of a blob.
  7702. **
  7703. ** This routine only works on a [BLOB handle] which has been created
  7704. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7705. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7706. ** to this routine results in undefined and probably undesirable behavior.
  7707. */
  7708. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  7709. /*
  7710. ** CAPI3REF: Read Data From A BLOB Incrementally
  7711. ** METHOD: sqlite3_blob
  7712. **
  7713. ** ^(This function is used to read data from an open [BLOB handle] into a
  7714. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  7715. ** from the open BLOB, starting at offset iOffset.)^
  7716. **
  7717. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7718. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  7719. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  7720. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  7721. ** can be determined using the [sqlite3_blob_bytes()] interface.
  7722. **
  7723. ** ^An attempt to read from an expired [BLOB handle] fails with an
  7724. ** error code of [SQLITE_ABORT].
  7725. **
  7726. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  7727. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7728. **
  7729. ** This routine only works on a [BLOB handle] which has been created
  7730. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7731. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7732. ** to this routine results in undefined and probably undesirable behavior.
  7733. **
  7734. ** See also: [sqlite3_blob_write()].
  7735. */
  7736. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  7737. /*
  7738. ** CAPI3REF: Write Data Into A BLOB Incrementally
  7739. ** METHOD: sqlite3_blob
  7740. **
  7741. ** ^(This function is used to write data into an open [BLOB handle] from a
  7742. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  7743. ** into the open BLOB, starting at offset iOffset.)^
  7744. **
  7745. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  7746. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7747. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  7748. ** [database connection] error code and message accessible via
  7749. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7750. **
  7751. ** ^If the [BLOB handle] passed as the first argument was not opened for
  7752. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  7753. ** this function returns [SQLITE_READONLY].
  7754. **
  7755. ** This function may only modify the contents of the BLOB; it is
  7756. ** not possible to increase the size of a BLOB using this API.
  7757. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7758. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  7759. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  7760. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  7761. ** than zero [SQLITE_ERROR] is returned and no data is written.
  7762. **
  7763. ** ^An attempt to write to an expired [BLOB handle] fails with an
  7764. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  7765. ** before the [BLOB handle] expired are not rolled back by the
  7766. ** expiration of the handle, though of course those changes might
  7767. ** have been overwritten by the statement that expired the BLOB handle
  7768. ** or by other independent statements.
  7769. **
  7770. ** This routine only works on a [BLOB handle] which has been created
  7771. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7772. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7773. ** to this routine results in undefined and probably undesirable behavior.
  7774. **
  7775. ** See also: [sqlite3_blob_read()].
  7776. */
  7777. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  7778. /*
  7779. ** CAPI3REF: Virtual File System Objects
  7780. **
  7781. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  7782. ** that SQLite uses to interact
  7783. ** with the underlying operating system. Most SQLite builds come with a
  7784. ** single default VFS that is appropriate for the host computer.
  7785. ** New VFSes can be registered and existing VFSes can be unregistered.
  7786. ** The following interfaces are provided.
  7787. **
  7788. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  7789. ** ^Names are case sensitive.
  7790. ** ^Names are zero-terminated UTF-8 strings.
  7791. ** ^If there is no match, a NULL pointer is returned.
  7792. ** ^If zVfsName is NULL then the default VFS is returned.
  7793. **
  7794. ** ^New VFSes are registered with sqlite3_vfs_register().
  7795. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  7796. ** ^The same VFS can be registered multiple times without injury.
  7797. ** ^To make an existing VFS into the default VFS, register it again
  7798. ** with the makeDflt flag set. If two different VFSes with the
  7799. ** same name are registered, the behavior is undefined. If a
  7800. ** VFS is registered with a name that is NULL or an empty string,
  7801. ** then the behavior is undefined.
  7802. **
  7803. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  7804. ** ^(If the default VFS is unregistered, another VFS is chosen as
  7805. ** the default. The choice for the new VFS is arbitrary.)^
  7806. */
  7807. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  7808. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  7809. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  7810. /*
  7811. ** CAPI3REF: Mutexes
  7812. **
  7813. ** The SQLite core uses these routines for thread
  7814. ** synchronization. Though they are intended for internal
  7815. ** use by SQLite, code that links against SQLite is
  7816. ** permitted to use any of these routines.
  7817. **
  7818. ** The SQLite source code contains multiple implementations
  7819. ** of these mutex routines. An appropriate implementation
  7820. ** is selected automatically at compile-time. The following
  7821. ** implementations are available in the SQLite core:
  7822. **
  7823. ** <ul>
  7824. ** <li> SQLITE_MUTEX_PTHREADS
  7825. ** <li> SQLITE_MUTEX_W32
  7826. ** <li> SQLITE_MUTEX_NOOP
  7827. ** </ul>
  7828. **
  7829. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  7830. ** that does no real locking and is appropriate for use in
  7831. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  7832. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  7833. ** and Windows.
  7834. **
  7835. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  7836. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  7837. ** implementation is included with the library. In this case the
  7838. ** application must supply a custom mutex implementation using the
  7839. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  7840. ** before calling sqlite3_initialize() or any other public sqlite3_
  7841. ** function that calls sqlite3_initialize().
  7842. **
  7843. ** ^The sqlite3_mutex_alloc() routine allocates a new
  7844. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  7845. ** routine returns NULL if it is unable to allocate the requested
  7846. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  7847. ** integer constants:
  7848. **
  7849. ** <ul>
  7850. ** <li> SQLITE_MUTEX_FAST
  7851. ** <li> SQLITE_MUTEX_RECURSIVE
  7852. ** <li> SQLITE_MUTEX_STATIC_MASTER
  7853. ** <li> SQLITE_MUTEX_STATIC_MEM
  7854. ** <li> SQLITE_MUTEX_STATIC_OPEN
  7855. ** <li> SQLITE_MUTEX_STATIC_PRNG
  7856. ** <li> SQLITE_MUTEX_STATIC_LRU
  7857. ** <li> SQLITE_MUTEX_STATIC_PMEM
  7858. ** <li> SQLITE_MUTEX_STATIC_APP1
  7859. ** <li> SQLITE_MUTEX_STATIC_APP2
  7860. ** <li> SQLITE_MUTEX_STATIC_APP3
  7861. ** <li> SQLITE_MUTEX_STATIC_VFS1
  7862. ** <li> SQLITE_MUTEX_STATIC_VFS2
  7863. ** <li> SQLITE_MUTEX_STATIC_VFS3
  7864. ** </ul>
  7865. **
  7866. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  7867. ** cause sqlite3_mutex_alloc() to create
  7868. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  7869. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  7870. ** The mutex implementation does not need to make a distinction
  7871. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  7872. ** not want to. SQLite will only request a recursive mutex in
  7873. ** cases where it really needs one. If a faster non-recursive mutex
  7874. ** implementation is available on the host platform, the mutex subsystem
  7875. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  7876. **
  7877. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  7878. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  7879. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  7880. ** used by the current version of SQLite. Future versions of SQLite
  7881. ** may add additional static mutexes. Static mutexes are for internal
  7882. ** use by SQLite only. Applications that use SQLite mutexes should
  7883. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  7884. ** SQLITE_MUTEX_RECURSIVE.
  7885. **
  7886. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  7887. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  7888. ** returns a different mutex on every call. ^For the static
  7889. ** mutex types, the same mutex is returned on every call that has
  7890. ** the same type number.
  7891. **
  7892. ** ^The sqlite3_mutex_free() routine deallocates a previously
  7893. ** allocated dynamic mutex. Attempting to deallocate a static
  7894. ** mutex results in undefined behavior.
  7895. **
  7896. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  7897. ** to enter a mutex. ^If another thread is already within the mutex,
  7898. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  7899. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  7900. ** upon successful entry. ^(Mutexes created using
  7901. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  7902. ** In such cases, the
  7903. ** mutex must be exited an equal number of times before another thread
  7904. ** can enter.)^ If the same thread tries to enter any mutex other
  7905. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  7906. **
  7907. ** ^(Some systems (for example, Windows 95) do not support the operation
  7908. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  7909. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  7910. ** sqlite3_mutex_try() as an optimization so this is acceptable
  7911. ** behavior.)^
  7912. **
  7913. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  7914. ** previously entered by the same thread. The behavior
  7915. ** is undefined if the mutex is not currently entered by the
  7916. ** calling thread or is not currently allocated.
  7917. **
  7918. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  7919. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  7920. ** behave as no-ops.
  7921. **
  7922. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  7923. */
  7924. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  7925. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  7926. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  7927. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  7928. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  7929. /*
  7930. ** CAPI3REF: Mutex Methods Object
  7931. **
  7932. ** An instance of this structure defines the low-level routines
  7933. ** used to allocate and use mutexes.
  7934. **
  7935. ** Usually, the default mutex implementations provided by SQLite are
  7936. ** sufficient, however the application has the option of substituting a custom
  7937. ** implementation for specialized deployments or systems for which SQLite
  7938. ** does not provide a suitable implementation. In this case, the application
  7939. ** creates and populates an instance of this structure to pass
  7940. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  7941. ** Additionally, an instance of this structure can be used as an
  7942. ** output variable when querying the system for the current mutex
  7943. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  7944. **
  7945. ** ^The xMutexInit method defined by this structure is invoked as
  7946. ** part of system initialization by the sqlite3_initialize() function.
  7947. ** ^The xMutexInit routine is called by SQLite exactly once for each
  7948. ** effective call to [sqlite3_initialize()].
  7949. **
  7950. ** ^The xMutexEnd method defined by this structure is invoked as
  7951. ** part of system shutdown by the sqlite3_shutdown() function. The
  7952. ** implementation of this method is expected to release all outstanding
  7953. ** resources obtained by the mutex methods implementation, especially
  7954. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  7955. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  7956. **
  7957. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  7958. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  7959. ** xMutexNotheld) implement the following interfaces (respectively):
  7960. **
  7961. ** <ul>
  7962. ** <li> [sqlite3_mutex_alloc()] </li>
  7963. ** <li> [sqlite3_mutex_free()] </li>
  7964. ** <li> [sqlite3_mutex_enter()] </li>
  7965. ** <li> [sqlite3_mutex_try()] </li>
  7966. ** <li> [sqlite3_mutex_leave()] </li>
  7967. ** <li> [sqlite3_mutex_held()] </li>
  7968. ** <li> [sqlite3_mutex_notheld()] </li>
  7969. ** </ul>)^
  7970. **
  7971. ** The only difference is that the public sqlite3_XXX functions enumerated
  7972. ** above silently ignore any invocations that pass a NULL pointer instead
  7973. ** of a valid mutex handle. The implementations of the methods defined
  7974. ** by this structure are not required to handle this case, the results
  7975. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  7976. ** (i.e. it is acceptable to provide an implementation that segfaults if
  7977. ** it is passed a NULL pointer).
  7978. **
  7979. ** The xMutexInit() method must be threadsafe. It must be harmless to
  7980. ** invoke xMutexInit() multiple times within the same process and without
  7981. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  7982. ** xMutexInit() must be no-ops.
  7983. **
  7984. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  7985. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  7986. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  7987. ** memory allocation for a fast or recursive mutex.
  7988. **
  7989. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  7990. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  7991. ** If xMutexInit fails in any way, it is expected to clean up after itself
  7992. ** prior to returning.
  7993. */
  7994. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  7995. struct sqlite3_mutex_methods {
  7996. int (*xMutexInit)(void);
  7997. int (*xMutexEnd)(void);
  7998. sqlite3_mutex *(*xMutexAlloc)(int);
  7999. void (*xMutexFree)(sqlite3_mutex *);
  8000. void (*xMutexEnter)(sqlite3_mutex *);
  8001. int (*xMutexTry)(sqlite3_mutex *);
  8002. void (*xMutexLeave)(sqlite3_mutex *);
  8003. int (*xMutexHeld)(sqlite3_mutex *);
  8004. int (*xMutexNotheld)(sqlite3_mutex *);
  8005. };
  8006. /*
  8007. ** CAPI3REF: Mutex Verification Routines
  8008. **
  8009. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  8010. ** are intended for use inside assert() statements. The SQLite core
  8011. ** never uses these routines except inside an assert() and applications
  8012. ** are advised to follow the lead of the core. The SQLite core only
  8013. ** provides implementations for these routines when it is compiled
  8014. ** with the SQLITE_DEBUG flag. External mutex implementations
  8015. ** are only required to provide these routines if SQLITE_DEBUG is
  8016. ** defined and if NDEBUG is not defined.
  8017. **
  8018. ** These routines should return true if the mutex in their argument
  8019. ** is held or not held, respectively, by the calling thread.
  8020. **
  8021. ** The implementation is not required to provide versions of these
  8022. ** routines that actually work. If the implementation does not provide working
  8023. ** versions of these routines, it should at least provide stubs that always
  8024. ** return true so that one does not get spurious assertion failures.
  8025. **
  8026. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  8027. ** the routine should return 1. This seems counter-intuitive since
  8028. ** clearly the mutex cannot be held if it does not exist. But
  8029. ** the reason the mutex does not exist is because the build is not
  8030. ** using mutexes. And we do not want the assert() containing the
  8031. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  8032. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  8033. ** interface should also return 1 when given a NULL pointer.
  8034. */
  8035. #ifndef NDEBUG
  8036. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  8037. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  8038. #endif
  8039. /*
  8040. ** CAPI3REF: Mutex Types
  8041. **
  8042. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  8043. ** which is one of these integer constants.
  8044. **
  8045. ** The set of static mutexes may change from one SQLite release to the
  8046. ** next. Applications that override the built-in mutex logic must be
  8047. ** prepared to accommodate additional static mutexes.
  8048. */
  8049. #define SQLITE_MUTEX_FAST 0
  8050. #define SQLITE_MUTEX_RECURSIVE 1
  8051. #define SQLITE_MUTEX_STATIC_MASTER 2
  8052. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  8053. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  8054. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  8055. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
  8056. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  8057. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  8058. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  8059. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  8060. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  8061. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  8062. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  8063. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  8064. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  8065. /*
  8066. ** CAPI3REF: Retrieve the mutex for a database connection
  8067. ** METHOD: sqlite3
  8068. **
  8069. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  8070. ** serializes access to the [database connection] given in the argument
  8071. ** when the [threading mode] is Serialized.
  8072. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  8073. ** routine returns a NULL pointer.
  8074. */
  8075. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  8076. /*
  8077. ** CAPI3REF: Low-Level Control Of Database Files
  8078. ** METHOD: sqlite3
  8079. ** KEYWORDS: {file control}
  8080. **
  8081. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  8082. ** xFileControl method for the [sqlite3_io_methods] object associated
  8083. ** with a particular database identified by the second argument. ^The
  8084. ** name of the database is "main" for the main database or "temp" for the
  8085. ** TEMP database, or the name that appears after the AS keyword for
  8086. ** databases that are added using the [ATTACH] SQL command.
  8087. ** ^A NULL pointer can be used in place of "main" to refer to the
  8088. ** main database file.
  8089. ** ^The third and fourth parameters to this routine
  8090. ** are passed directly through to the second and third parameters of
  8091. ** the xFileControl method. ^The return value of the xFileControl
  8092. ** method becomes the return value of this routine.
  8093. **
  8094. ** A few opcodes for [sqlite3_file_control()] are handled directly
  8095. ** by the SQLite core and never invoke the
  8096. ** sqlite3_io_methods.xFileControl method.
  8097. ** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
  8098. ** a pointer to the underlying [sqlite3_file] object to be written into
  8099. ** the space pointed to by the 4th parameter. The
  8100. ** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns
  8101. ** the [sqlite3_file] object associated with the journal file instead of
  8102. ** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns
  8103. ** a pointer to the underlying [sqlite3_vfs] object for the file.
  8104. ** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter
  8105. ** from the pager.
  8106. **
  8107. ** ^If the second parameter (zDbName) does not match the name of any
  8108. ** open database file, then SQLITE_ERROR is returned. ^This error
  8109. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  8110. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  8111. ** also return SQLITE_ERROR. There is no way to distinguish between
  8112. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  8113. ** xFileControl method.
  8114. **
  8115. ** See also: [file control opcodes]
  8116. */
  8117. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  8118. /*
  8119. ** CAPI3REF: Testing Interface
  8120. **
  8121. ** ^The sqlite3_test_control() interface is used to read out internal
  8122. ** state of SQLite and to inject faults into SQLite for testing
  8123. ** purposes. ^The first parameter is an operation code that determines
  8124. ** the number, meaning, and operation of all subsequent parameters.
  8125. **
  8126. ** This interface is not for use by applications. It exists solely
  8127. ** for verifying the correct operation of the SQLite library. Depending
  8128. ** on how the SQLite library is compiled, this interface might not exist.
  8129. **
  8130. ** The details of the operation codes, their meanings, the parameters
  8131. ** they take, and what they do are all subject to change without notice.
  8132. ** Unlike most of the SQLite API, this function is not guaranteed to
  8133. ** operate consistently from one release to the next.
  8134. */
  8135. SQLITE_API int sqlite3_test_control(int op, ...);
  8136. /*
  8137. ** CAPI3REF: Testing Interface Operation Codes
  8138. **
  8139. ** These constants are the valid operation code parameters used
  8140. ** as the first argument to [sqlite3_test_control()].
  8141. **
  8142. ** These parameters and their meanings are subject to change
  8143. ** without notice. These values are for testing purposes only.
  8144. ** Applications should not use any of these parameters or the
  8145. ** [sqlite3_test_control()] interface.
  8146. */
  8147. #define SQLITE_TESTCTRL_FIRST 5
  8148. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  8149. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  8150. #define SQLITE_TESTCTRL_PRNG_RESET 7
  8151. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  8152. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  8153. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  8154. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  8155. #define SQLITE_TESTCTRL_ASSERT 12
  8156. #define SQLITE_TESTCTRL_ALWAYS 13
  8157. #define SQLITE_TESTCTRL_RESERVE 14
  8158. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  8159. #define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */
  8160. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
  8161. #define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17
  8162. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  8163. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  8164. #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
  8165. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  8166. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  8167. #define SQLITE_TESTCTRL_BYTEORDER 22
  8168. #define SQLITE_TESTCTRL_ISINIT 23
  8169. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  8170. #define SQLITE_TESTCTRL_IMPOSTER 25
  8171. #define SQLITE_TESTCTRL_PARSER_COVERAGE 26
  8172. #define SQLITE_TESTCTRL_LAST 26 /* Largest TESTCTRL */
  8173. /*
  8174. ** CAPI3REF: SQL Keyword Checking
  8175. **
  8176. ** These routines provide access to the set of SQL language keywords
  8177. ** recognized by SQLite. Applications can uses these routines to determine
  8178. ** whether or not a specific identifier needs to be escaped (for example,
  8179. ** by enclosing in double-quotes) so as not to confuse the parser.
  8180. **
  8181. ** The sqlite3_keyword_count() interface returns the number of distinct
  8182. ** keywords understood by SQLite.
  8183. **
  8184. ** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
  8185. ** makes *Z point to that keyword expressed as UTF8 and writes the number
  8186. ** of bytes in the keyword into *L. The string that *Z points to is not
  8187. ** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
  8188. ** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
  8189. ** or L are NULL or invalid pointers then calls to
  8190. ** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
  8191. **
  8192. ** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
  8193. ** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
  8194. ** if it is and zero if not.
  8195. **
  8196. ** The parser used by SQLite is forgiving. It is often possible to use
  8197. ** a keyword as an identifier as long as such use does not result in a
  8198. ** parsing ambiguity. For example, the statement
  8199. ** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
  8200. ** creates a new table named "BEGIN" with three columns named
  8201. ** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid
  8202. ** using keywords as identifiers. Common techniques used to avoid keyword
  8203. ** name collisions include:
  8204. ** <ul>
  8205. ** <li> Put all identifier names inside double-quotes. This is the official
  8206. ** SQL way to escape identifier names.
  8207. ** <li> Put identifier names inside &#91;...&#93;. This is not standard SQL,
  8208. ** but it is what SQL Server does and so lots of programmers use this
  8209. ** technique.
  8210. ** <li> Begin every identifier with the letter "Z" as no SQL keywords start
  8211. ** with "Z".
  8212. ** <li> Include a digit somewhere in every identifier name.
  8213. ** </ul>
  8214. **
  8215. ** Note that the number of keywords understood by SQLite can depend on
  8216. ** compile-time options. For example, "VACUUM" is not a keyword if
  8217. ** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
  8218. ** new keywords may be added to future releases of SQLite.
  8219. */
  8220. SQLITE_API int sqlite3_keyword_count(void);
  8221. SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
  8222. SQLITE_API int sqlite3_keyword_check(const char*,int);
  8223. /*
  8224. ** CAPI3REF: Dynamic String Object
  8225. ** KEYWORDS: {dynamic string}
  8226. **
  8227. ** An instance of the sqlite3_str object contains a dynamically-sized
  8228. ** string under construction.
  8229. **
  8230. ** The lifecycle of an sqlite3_str object is as follows:
  8231. ** <ol>
  8232. ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
  8233. ** <li> ^Text is appended to the sqlite3_str object using various
  8234. ** methods, such as [sqlite3_str_appendf()].
  8235. ** <li> ^The sqlite3_str object is destroyed and the string it created
  8236. ** is returned using the [sqlite3_str_finish()] interface.
  8237. ** </ol>
  8238. */
  8239. typedef struct sqlite3_str sqlite3_str;
  8240. /*
  8241. ** CAPI3REF: Create A New Dynamic String Object
  8242. ** CONSTRUCTOR: sqlite3_str
  8243. **
  8244. ** ^The [sqlite3_str_new(D)] interface allocates and initializes
  8245. ** a new [sqlite3_str] object. To avoid memory leaks, the object returned by
  8246. ** [sqlite3_str_new()] must be freed by a subsequent call to
  8247. ** [sqlite3_str_finish(X)].
  8248. **
  8249. ** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
  8250. ** valid [sqlite3_str] object, though in the event of an out-of-memory
  8251. ** error the returned object might be a special singleton that will
  8252. ** silently reject new text, always return SQLITE_NOMEM from
  8253. ** [sqlite3_str_errcode()], always return 0 for
  8254. ** [sqlite3_str_length()], and always return NULL from
  8255. ** [sqlite3_str_finish(X)]. It is always safe to use the value
  8256. ** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
  8257. ** to any of the other [sqlite3_str] methods.
  8258. **
  8259. ** The D parameter to [sqlite3_str_new(D)] may be NULL. If the
  8260. ** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
  8261. ** length of the string contained in the [sqlite3_str] object will be
  8262. ** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
  8263. ** of [SQLITE_MAX_LENGTH].
  8264. */
  8265. SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
  8266. /*
  8267. ** CAPI3REF: Finalize A Dynamic String
  8268. ** DESTRUCTOR: sqlite3_str
  8269. **
  8270. ** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
  8271. ** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
  8272. ** that contains the constructed string. The calling application should
  8273. ** pass the returned value to [sqlite3_free()] to avoid a memory leak.
  8274. ** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
  8275. ** errors were encountered during construction of the string. ^The
  8276. ** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
  8277. ** string in [sqlite3_str] object X is zero bytes long.
  8278. */
  8279. SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
  8280. /*
  8281. ** CAPI3REF: Add Content To A Dynamic String
  8282. ** METHOD: sqlite3_str
  8283. **
  8284. ** These interfaces add content to an sqlite3_str object previously obtained
  8285. ** from [sqlite3_str_new()].
  8286. **
  8287. ** ^The [sqlite3_str_appendf(X,F,...)] and
  8288. ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
  8289. ** functionality of SQLite to append formatted text onto the end of
  8290. ** [sqlite3_str] object X.
  8291. **
  8292. ** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
  8293. ** onto the end of the [sqlite3_str] object X. N must be non-negative.
  8294. ** S must contain at least N non-zero bytes of content. To append a
  8295. ** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
  8296. ** method instead.
  8297. **
  8298. ** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
  8299. ** zero-terminated string S onto the end of [sqlite3_str] object X.
  8300. **
  8301. ** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
  8302. ** single-byte character C onto the end of [sqlite3_str] object X.
  8303. ** ^This method can be used, for example, to add whitespace indentation.
  8304. **
  8305. ** ^The [sqlite3_str_reset(X)] method resets the string under construction
  8306. ** inside [sqlite3_str] object X back to zero bytes in length.
  8307. **
  8308. ** These methods do not return a result code. ^If an error occurs, that fact
  8309. ** is recorded in the [sqlite3_str] object and can be recovered by a
  8310. ** subsequent call to [sqlite3_str_errcode(X)].
  8311. */
  8312. SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
  8313. SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
  8314. SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
  8315. SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
  8316. SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
  8317. SQLITE_API void sqlite3_str_reset(sqlite3_str*);
  8318. /*
  8319. ** CAPI3REF: Status Of A Dynamic String
  8320. ** METHOD: sqlite3_str
  8321. **
  8322. ** These interfaces return the current status of an [sqlite3_str] object.
  8323. **
  8324. ** ^If any prior errors have occurred while constructing the dynamic string
  8325. ** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
  8326. ** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns
  8327. ** [SQLITE_NOMEM] following any out-of-memory error, or
  8328. ** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
  8329. ** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
  8330. **
  8331. ** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
  8332. ** of the dynamic string under construction in [sqlite3_str] object X.
  8333. ** ^The length returned by [sqlite3_str_length(X)] does not include the
  8334. ** zero-termination byte.
  8335. **
  8336. ** ^The [sqlite3_str_value(X)] method returns a pointer to the current
  8337. ** content of the dynamic string under construction in X. The value
  8338. ** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
  8339. ** and might be freed or altered by any subsequent method on the same
  8340. ** [sqlite3_str] object. Applications must not used the pointer returned
  8341. ** [sqlite3_str_value(X)] after any subsequent method call on the same
  8342. ** object. ^Applications may change the content of the string returned
  8343. ** by [sqlite3_str_value(X)] as long as they do not write into any bytes
  8344. ** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
  8345. ** write any byte after any subsequent sqlite3_str method call.
  8346. */
  8347. SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
  8348. SQLITE_API int sqlite3_str_length(sqlite3_str*);
  8349. SQLITE_API char *sqlite3_str_value(sqlite3_str*);
  8350. /*
  8351. ** CAPI3REF: SQLite Runtime Status
  8352. **
  8353. ** ^These interfaces are used to retrieve runtime status information
  8354. ** about the performance of SQLite, and optionally to reset various
  8355. ** highwater marks. ^The first argument is an integer code for
  8356. ** the specific parameter to measure. ^(Recognized integer codes
  8357. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  8358. ** ^The current value of the parameter is returned into *pCurrent.
  8359. ** ^The highest recorded value is returned in *pHighwater. ^If the
  8360. ** resetFlag is true, then the highest record value is reset after
  8361. ** *pHighwater is written. ^(Some parameters do not record the highest
  8362. ** value. For those parameters
  8363. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  8364. ** ^(Other parameters record only the highwater mark and not the current
  8365. ** value. For these latter parameters nothing is written into *pCurrent.)^
  8366. **
  8367. ** ^The sqlite3_status() and sqlite3_status64() routines return
  8368. ** SQLITE_OK on success and a non-zero [error code] on failure.
  8369. **
  8370. ** If either the current value or the highwater mark is too large to
  8371. ** be represented by a 32-bit integer, then the values returned by
  8372. ** sqlite3_status() are undefined.
  8373. **
  8374. ** See also: [sqlite3_db_status()]
  8375. */
  8376. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  8377. SQLITE_API int sqlite3_status64(
  8378. int op,
  8379. sqlite3_int64 *pCurrent,
  8380. sqlite3_int64 *pHighwater,
  8381. int resetFlag
  8382. );
  8383. /*
  8384. ** CAPI3REF: Status Parameters
  8385. ** KEYWORDS: {status parameters}
  8386. **
  8387. ** These integer constants designate various run-time status parameters
  8388. ** that can be returned by [sqlite3_status()].
  8389. **
  8390. ** <dl>
  8391. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  8392. ** <dd>This parameter is the current amount of memory checked out
  8393. ** using [sqlite3_malloc()], either directly or indirectly. The
  8394. ** figure includes calls made to [sqlite3_malloc()] by the application
  8395. ** and internal memory usage by the SQLite library. Auxiliary page-cache
  8396. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  8397. ** this parameter. The amount returned is the sum of the allocation
  8398. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  8399. **
  8400. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  8401. ** <dd>This parameter records the largest memory allocation request
  8402. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  8403. ** internal equivalents). Only the value returned in the
  8404. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  8405. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8406. **
  8407. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  8408. ** <dd>This parameter records the number of separate memory allocations
  8409. ** currently checked out.</dd>)^
  8410. **
  8411. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  8412. ** <dd>This parameter returns the number of pages used out of the
  8413. ** [pagecache memory allocator] that was configured using
  8414. ** [SQLITE_CONFIG_PAGECACHE]. The
  8415. ** value returned is in pages, not in bytes.</dd>)^
  8416. **
  8417. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  8418. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  8419. ** <dd>This parameter returns the number of bytes of page cache
  8420. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  8421. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  8422. ** returned value includes allocations that overflowed because they
  8423. ** where too large (they were larger than the "sz" parameter to
  8424. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  8425. ** no space was left in the page cache.</dd>)^
  8426. **
  8427. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  8428. ** <dd>This parameter records the largest memory allocation request
  8429. ** handed to [pagecache memory allocator]. Only the value returned in the
  8430. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  8431. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8432. **
  8433. ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
  8434. ** <dd>No longer used.</dd>
  8435. **
  8436. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  8437. ** <dd>No longer used.</dd>
  8438. **
  8439. ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  8440. ** <dd>No longer used.</dd>
  8441. **
  8442. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  8443. ** <dd>The *pHighwater parameter records the deepest parser stack.
  8444. ** The *pCurrent value is undefined. The *pHighwater value is only
  8445. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  8446. ** </dl>
  8447. **
  8448. ** New status parameters may be added from time to time.
  8449. */
  8450. #define SQLITE_STATUS_MEMORY_USED 0
  8451. #define SQLITE_STATUS_PAGECACHE_USED 1
  8452. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  8453. #define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */
  8454. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
  8455. #define SQLITE_STATUS_MALLOC_SIZE 5
  8456. #define SQLITE_STATUS_PARSER_STACK 6
  8457. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  8458. #define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
  8459. #define SQLITE_STATUS_MALLOC_COUNT 9
  8460. /*
  8461. ** CAPI3REF: Database Connection Status
  8462. ** METHOD: sqlite3
  8463. **
  8464. ** ^This interface is used to retrieve runtime status information
  8465. ** about a single [database connection]. ^The first argument is the
  8466. ** database connection object to be interrogated. ^The second argument
  8467. ** is an integer constant, taken from the set of
  8468. ** [SQLITE_DBSTATUS options], that
  8469. ** determines the parameter to interrogate. The set of
  8470. ** [SQLITE_DBSTATUS options] is likely
  8471. ** to grow in future releases of SQLite.
  8472. **
  8473. ** ^The current value of the requested parameter is written into *pCur
  8474. ** and the highest instantaneous value is written into *pHiwtr. ^If
  8475. ** the resetFlg is true, then the highest instantaneous value is
  8476. ** reset back down to the current value.
  8477. **
  8478. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  8479. ** non-zero [error code] on failure.
  8480. **
  8481. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  8482. */
  8483. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  8484. /*
  8485. ** CAPI3REF: Status Parameters for database connections
  8486. ** KEYWORDS: {SQLITE_DBSTATUS options}
  8487. **
  8488. ** These constants are the available integer "verbs" that can be passed as
  8489. ** the second argument to the [sqlite3_db_status()] interface.
  8490. **
  8491. ** New verbs may be added in future releases of SQLite. Existing verbs
  8492. ** might be discontinued. Applications should check the return code from
  8493. ** [sqlite3_db_status()] to make sure that the call worked.
  8494. ** The [sqlite3_db_status()] interface will return a non-zero error code
  8495. ** if a discontinued or unsupported verb is invoked.
  8496. **
  8497. ** <dl>
  8498. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  8499. ** <dd>This parameter returns the number of lookaside memory slots currently
  8500. ** checked out.</dd>)^
  8501. **
  8502. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  8503. ** <dd>This parameter returns the number malloc attempts that were
  8504. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  8505. ** the current value is always zero.)^
  8506. **
  8507. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  8508. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  8509. ** <dd>This parameter returns the number malloc attempts that might have
  8510. ** been satisfied using lookaside memory but failed due to the amount of
  8511. ** memory requested being larger than the lookaside slot size.
  8512. ** Only the high-water value is meaningful;
  8513. ** the current value is always zero.)^
  8514. **
  8515. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  8516. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  8517. ** <dd>This parameter returns the number malloc attempts that might have
  8518. ** been satisfied using lookaside memory but failed due to all lookaside
  8519. ** memory already being in use.
  8520. ** Only the high-water value is meaningful;
  8521. ** the current value is always zero.)^
  8522. **
  8523. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  8524. ** <dd>This parameter returns the approximate number of bytes of heap
  8525. ** memory used by all pager caches associated with the database connection.)^
  8526. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  8527. **
  8528. ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
  8529. ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
  8530. ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
  8531. ** pager cache is shared between two or more connections the bytes of heap
  8532. ** memory used by that pager cache is divided evenly between the attached
  8533. ** connections.)^ In other words, if none of the pager caches associated
  8534. ** with the database connection are shared, this request returns the same
  8535. ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
  8536. ** shared, the value returned by this call will be smaller than that returned
  8537. ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
  8538. ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
  8539. **
  8540. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  8541. ** <dd>This parameter returns the approximate number of bytes of heap
  8542. ** memory used to store the schema for all databases associated
  8543. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  8544. ** ^The full amount of memory used by the schemas is reported, even if the
  8545. ** schema memory is shared with other database connections due to
  8546. ** [shared cache mode] being enabled.
  8547. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  8548. **
  8549. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  8550. ** <dd>This parameter returns the approximate number of bytes of heap
  8551. ** and lookaside memory used by all prepared statements associated with
  8552. ** the database connection.)^
  8553. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  8554. ** </dd>
  8555. **
  8556. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  8557. ** <dd>This parameter returns the number of pager cache hits that have
  8558. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  8559. ** is always 0.
  8560. ** </dd>
  8561. **
  8562. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  8563. ** <dd>This parameter returns the number of pager cache misses that have
  8564. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  8565. ** is always 0.
  8566. ** </dd>
  8567. **
  8568. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  8569. ** <dd>This parameter returns the number of dirty cache entries that have
  8570. ** been written to disk. Specifically, the number of pages written to the
  8571. ** wal file in wal mode databases, or the number of pages written to the
  8572. ** database file in rollback mode databases. Any pages written as part of
  8573. ** transaction rollback or database recovery operations are not included.
  8574. ** If an IO or other error occurs while writing a page to disk, the effect
  8575. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  8576. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  8577. ** </dd>
  8578. **
  8579. ** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
  8580. ** <dd>This parameter returns the number of dirty cache entries that have
  8581. ** been written to disk in the middle of a transaction due to the page
  8582. ** cache overflowing. Transactions are more efficient if they are written
  8583. ** to disk all at once. When pages spill mid-transaction, that introduces
  8584. ** additional overhead. This parameter can be used help identify
  8585. ** inefficiencies that can be resolve by increasing the cache size.
  8586. ** </dd>
  8587. **
  8588. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  8589. ** <dd>This parameter returns zero for the current value if and only if
  8590. ** all foreign key constraints (deferred or immediate) have been
  8591. ** resolved.)^ ^The highwater mark is always 0.
  8592. ** </dd>
  8593. ** </dl>
  8594. */
  8595. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  8596. #define SQLITE_DBSTATUS_CACHE_USED 1
  8597. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  8598. #define SQLITE_DBSTATUS_STMT_USED 3
  8599. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  8600. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  8601. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  8602. #define SQLITE_DBSTATUS_CACHE_HIT 7
  8603. #define SQLITE_DBSTATUS_CACHE_MISS 8
  8604. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  8605. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  8606. #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
  8607. #define SQLITE_DBSTATUS_CACHE_SPILL 12
  8608. #define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */
  8609. /*
  8610. ** CAPI3REF: Prepared Statement Status
  8611. ** METHOD: sqlite3_stmt
  8612. **
  8613. ** ^(Each prepared statement maintains various
  8614. ** [SQLITE_STMTSTATUS counters] that measure the number
  8615. ** of times it has performed specific operations.)^ These counters can
  8616. ** be used to monitor the performance characteristics of the prepared
  8617. ** statements. For example, if the number of table steps greatly exceeds
  8618. ** the number of table searches or result rows, that would tend to indicate
  8619. ** that the prepared statement is using a full table scan rather than
  8620. ** an index.
  8621. **
  8622. ** ^(This interface is used to retrieve and reset counter values from
  8623. ** a [prepared statement]. The first argument is the prepared statement
  8624. ** object to be interrogated. The second argument
  8625. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  8626. ** to be interrogated.)^
  8627. ** ^The current value of the requested counter is returned.
  8628. ** ^If the resetFlg is true, then the counter is reset to zero after this
  8629. ** interface call returns.
  8630. **
  8631. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  8632. */
  8633. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  8634. /*
  8635. ** CAPI3REF: Status Parameters for prepared statements
  8636. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  8637. **
  8638. ** These preprocessor macros define integer codes that name counter
  8639. ** values associated with the [sqlite3_stmt_status()] interface.
  8640. ** The meanings of the various counters are as follows:
  8641. **
  8642. ** <dl>
  8643. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  8644. ** <dd>^This is the number of times that SQLite has stepped forward in
  8645. ** a table as part of a full table scan. Large numbers for this counter
  8646. ** may indicate opportunities for performance improvement through
  8647. ** careful use of indices.</dd>
  8648. **
  8649. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  8650. ** <dd>^This is the number of sort operations that have occurred.
  8651. ** A non-zero value in this counter may indicate an opportunity to
  8652. ** improvement performance through careful use of indices.</dd>
  8653. **
  8654. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  8655. ** <dd>^This is the number of rows inserted into transient indices that
  8656. ** were created automatically in order to help joins run faster.
  8657. ** A non-zero value in this counter may indicate an opportunity to
  8658. ** improvement performance by adding permanent indices that do not
  8659. ** need to be reinitialized each time the statement is run.</dd>
  8660. **
  8661. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  8662. ** <dd>^This is the number of virtual machine operations executed
  8663. ** by the prepared statement if that number is less than or equal
  8664. ** to 2147483647. The number of virtual machine operations can be
  8665. ** used as a proxy for the total work done by the prepared statement.
  8666. ** If the number of virtual machine operations exceeds 2147483647
  8667. ** then the value returned by this statement status code is undefined.
  8668. **
  8669. ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
  8670. ** <dd>^This is the number of times that the prepare statement has been
  8671. ** automatically regenerated due to schema changes or change to
  8672. ** [bound parameters] that might affect the query plan.
  8673. **
  8674. ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
  8675. ** <dd>^This is the number of times that the prepared statement has
  8676. ** been run. A single "run" for the purposes of this counter is one
  8677. ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
  8678. ** The counter is incremented on the first [sqlite3_step()] call of each
  8679. ** cycle.
  8680. **
  8681. ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
  8682. ** <dd>^This is the approximate number of bytes of heap memory
  8683. ** used to store the prepared statement. ^This value is not actually
  8684. ** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
  8685. ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
  8686. ** </dd>
  8687. ** </dl>
  8688. */
  8689. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  8690. #define SQLITE_STMTSTATUS_SORT 2
  8691. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  8692. #define SQLITE_STMTSTATUS_VM_STEP 4
  8693. #define SQLITE_STMTSTATUS_REPREPARE 5
  8694. #define SQLITE_STMTSTATUS_RUN 6
  8695. #define SQLITE_STMTSTATUS_MEMUSED 99
  8696. /*
  8697. ** CAPI3REF: Custom Page Cache Object
  8698. **
  8699. ** The sqlite3_pcache type is opaque. It is implemented by
  8700. ** the pluggable module. The SQLite core has no knowledge of
  8701. ** its size or internal structure and never deals with the
  8702. ** sqlite3_pcache object except by holding and passing pointers
  8703. ** to the object.
  8704. **
  8705. ** See [sqlite3_pcache_methods2] for additional information.
  8706. */
  8707. typedef struct sqlite3_pcache sqlite3_pcache;
  8708. /*
  8709. ** CAPI3REF: Custom Page Cache Object
  8710. **
  8711. ** The sqlite3_pcache_page object represents a single page in the
  8712. ** page cache. The page cache will allocate instances of this
  8713. ** object. Various methods of the page cache use pointers to instances
  8714. ** of this object as parameters or as their return value.
  8715. **
  8716. ** See [sqlite3_pcache_methods2] for additional information.
  8717. */
  8718. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  8719. struct sqlite3_pcache_page {
  8720. void *pBuf; /* The content of the page */
  8721. void *pExtra; /* Extra information associated with the page */
  8722. };
  8723. /*
  8724. ** CAPI3REF: Application Defined Page Cache.
  8725. ** KEYWORDS: {page cache}
  8726. **
  8727. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  8728. ** register an alternative page cache implementation by passing in an
  8729. ** instance of the sqlite3_pcache_methods2 structure.)^
  8730. ** In many applications, most of the heap memory allocated by
  8731. ** SQLite is used for the page cache.
  8732. ** By implementing a
  8733. ** custom page cache using this API, an application can better control
  8734. ** the amount of memory consumed by SQLite, the way in which
  8735. ** that memory is allocated and released, and the policies used to
  8736. ** determine exactly which parts of a database file are cached and for
  8737. ** how long.
  8738. **
  8739. ** The alternative page cache mechanism is an
  8740. ** extreme measure that is only needed by the most demanding applications.
  8741. ** The built-in page cache is recommended for most uses.
  8742. **
  8743. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  8744. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  8745. ** the application may discard the parameter after the call to
  8746. ** [sqlite3_config()] returns.)^
  8747. **
  8748. ** [[the xInit() page cache method]]
  8749. ** ^(The xInit() method is called once for each effective
  8750. ** call to [sqlite3_initialize()])^
  8751. ** (usually only once during the lifetime of the process). ^(The xInit()
  8752. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  8753. ** The intent of the xInit() method is to set up global data structures
  8754. ** required by the custom page cache implementation.
  8755. ** ^(If the xInit() method is NULL, then the
  8756. ** built-in default page cache is used instead of the application defined
  8757. ** page cache.)^
  8758. **
  8759. ** [[the xShutdown() page cache method]]
  8760. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  8761. ** It can be used to clean up
  8762. ** any outstanding resources before process shutdown, if required.
  8763. ** ^The xShutdown() method may be NULL.
  8764. **
  8765. ** ^SQLite automatically serializes calls to the xInit method,
  8766. ** so the xInit method need not be threadsafe. ^The
  8767. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  8768. ** not need to be threadsafe either. All other methods must be threadsafe
  8769. ** in multithreaded applications.
  8770. **
  8771. ** ^SQLite will never invoke xInit() more than once without an intervening
  8772. ** call to xShutdown().
  8773. **
  8774. ** [[the xCreate() page cache methods]]
  8775. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  8776. ** SQLite will typically create one cache instance for each open database file,
  8777. ** though this is not guaranteed. ^The
  8778. ** first parameter, szPage, is the size in bytes of the pages that must
  8779. ** be allocated by the cache. ^szPage will always a power of two. ^The
  8780. ** second parameter szExtra is a number of bytes of extra storage
  8781. ** associated with each page cache entry. ^The szExtra parameter will
  8782. ** a number less than 250. SQLite will use the
  8783. ** extra szExtra bytes on each page to store metadata about the underlying
  8784. ** database page on disk. The value passed into szExtra depends
  8785. ** on the SQLite version, the target platform, and how SQLite was compiled.
  8786. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  8787. ** created will be used to cache database pages of a file stored on disk, or
  8788. ** false if it is used for an in-memory database. The cache implementation
  8789. ** does not have to do anything special based with the value of bPurgeable;
  8790. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  8791. ** never invoke xUnpin() except to deliberately delete a page.
  8792. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  8793. ** false will always have the "discard" flag set to true.
  8794. ** ^Hence, a cache created with bPurgeable false will
  8795. ** never contain any unpinned pages.
  8796. **
  8797. ** [[the xCachesize() page cache method]]
  8798. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  8799. ** suggested maximum cache-size (number of pages stored by) the cache
  8800. ** instance passed as the first argument. This is the value configured using
  8801. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  8802. ** parameter, the implementation is not required to do anything with this
  8803. ** value; it is advisory only.
  8804. **
  8805. ** [[the xPagecount() page cache methods]]
  8806. ** The xPagecount() method must return the number of pages currently
  8807. ** stored in the cache, both pinned and unpinned.
  8808. **
  8809. ** [[the xFetch() page cache methods]]
  8810. ** The xFetch() method locates a page in the cache and returns a pointer to
  8811. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  8812. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  8813. ** pointer to a buffer of szPage bytes used to store the content of a
  8814. ** single database page. The pExtra element of sqlite3_pcache_page will be
  8815. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  8816. ** for each entry in the page cache.
  8817. **
  8818. ** The page to be fetched is determined by the key. ^The minimum key value
  8819. ** is 1. After it has been retrieved using xFetch, the page is considered
  8820. ** to be "pinned".
  8821. **
  8822. ** If the requested page is already in the page cache, then the page cache
  8823. ** implementation must return a pointer to the page buffer with its content
  8824. ** intact. If the requested page is not already in the cache, then the
  8825. ** cache implementation should use the value of the createFlag
  8826. ** parameter to help it determined what action to take:
  8827. **
  8828. ** <table border=1 width=85% align=center>
  8829. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  8830. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  8831. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  8832. ** Otherwise return NULL.
  8833. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  8834. ** NULL if allocating a new page is effectively impossible.
  8835. ** </table>
  8836. **
  8837. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  8838. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  8839. ** failed.)^ In between the to xFetch() calls, SQLite may
  8840. ** attempt to unpin one or more cache pages by spilling the content of
  8841. ** pinned pages to disk and synching the operating system disk cache.
  8842. **
  8843. ** [[the xUnpin() page cache method]]
  8844. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  8845. ** as its second argument. If the third parameter, discard, is non-zero,
  8846. ** then the page must be evicted from the cache.
  8847. ** ^If the discard parameter is
  8848. ** zero, then the page may be discarded or retained at the discretion of
  8849. ** page cache implementation. ^The page cache implementation
  8850. ** may choose to evict unpinned pages at any time.
  8851. **
  8852. ** The cache must not perform any reference counting. A single
  8853. ** call to xUnpin() unpins the page regardless of the number of prior calls
  8854. ** to xFetch().
  8855. **
  8856. ** [[the xRekey() page cache methods]]
  8857. ** The xRekey() method is used to change the key value associated with the
  8858. ** page passed as the second argument. If the cache
  8859. ** previously contains an entry associated with newKey, it must be
  8860. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  8861. ** to be pinned.
  8862. **
  8863. ** When SQLite calls the xTruncate() method, the cache must discard all
  8864. ** existing cache entries with page numbers (keys) greater than or equal
  8865. ** to the value of the iLimit parameter passed to xTruncate(). If any
  8866. ** of these pages are pinned, they are implicitly unpinned, meaning that
  8867. ** they can be safely discarded.
  8868. **
  8869. ** [[the xDestroy() page cache method]]
  8870. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  8871. ** All resources associated with the specified cache should be freed. ^After
  8872. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  8873. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  8874. ** functions.
  8875. **
  8876. ** [[the xShrink() page cache method]]
  8877. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  8878. ** free up as much of heap memory as possible. The page cache implementation
  8879. ** is not obligated to free any memory, but well-behaved implementations should
  8880. ** do their best.
  8881. */
  8882. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  8883. struct sqlite3_pcache_methods2 {
  8884. int iVersion;
  8885. void *pArg;
  8886. int (*xInit)(void*);
  8887. void (*xShutdown)(void*);
  8888. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  8889. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8890. int (*xPagecount)(sqlite3_pcache*);
  8891. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8892. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  8893. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  8894. unsigned oldKey, unsigned newKey);
  8895. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8896. void (*xDestroy)(sqlite3_pcache*);
  8897. void (*xShrink)(sqlite3_pcache*);
  8898. };
  8899. /*
  8900. ** This is the obsolete pcache_methods object that has now been replaced
  8901. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  8902. ** retained in the header file for backwards compatibility only.
  8903. */
  8904. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  8905. struct sqlite3_pcache_methods {
  8906. void *pArg;
  8907. int (*xInit)(void*);
  8908. void (*xShutdown)(void*);
  8909. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  8910. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8911. int (*xPagecount)(sqlite3_pcache*);
  8912. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8913. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  8914. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  8915. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8916. void (*xDestroy)(sqlite3_pcache*);
  8917. };
  8918. /*
  8919. ** CAPI3REF: Online Backup Object
  8920. **
  8921. ** The sqlite3_backup object records state information about an ongoing
  8922. ** online backup operation. ^The sqlite3_backup object is created by
  8923. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  8924. ** [sqlite3_backup_finish()].
  8925. **
  8926. ** See Also: [Using the SQLite Online Backup API]
  8927. */
  8928. typedef struct sqlite3_backup sqlite3_backup;
  8929. /*
  8930. ** CAPI3REF: Online Backup API.
  8931. **
  8932. ** The backup API copies the content of one database into another.
  8933. ** It is useful either for creating backups of databases or
  8934. ** for copying in-memory databases to or from persistent files.
  8935. **
  8936. ** See Also: [Using the SQLite Online Backup API]
  8937. **
  8938. ** ^SQLite holds a write transaction open on the destination database file
  8939. ** for the duration of the backup operation.
  8940. ** ^The source database is read-locked only while it is being read;
  8941. ** it is not locked continuously for the entire backup operation.
  8942. ** ^Thus, the backup may be performed on a live source database without
  8943. ** preventing other database connections from
  8944. ** reading or writing to the source database while the backup is underway.
  8945. **
  8946. ** ^(To perform a backup operation:
  8947. ** <ol>
  8948. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  8949. ** backup,
  8950. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  8951. ** the data between the two databases, and finally
  8952. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  8953. ** associated with the backup operation.
  8954. ** </ol>)^
  8955. ** There should be exactly one call to sqlite3_backup_finish() for each
  8956. ** successful call to sqlite3_backup_init().
  8957. **
  8958. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  8959. **
  8960. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  8961. ** [database connection] associated with the destination database
  8962. ** and the database name, respectively.
  8963. ** ^The database name is "main" for the main database, "temp" for the
  8964. ** temporary database, or the name specified after the AS keyword in
  8965. ** an [ATTACH] statement for an attached database.
  8966. ** ^The S and M arguments passed to
  8967. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  8968. ** and database name of the source database, respectively.
  8969. ** ^The source and destination [database connections] (parameters S and D)
  8970. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  8971. ** an error.
  8972. **
  8973. ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
  8974. ** there is already a read or read-write transaction open on the
  8975. ** destination database.
  8976. **
  8977. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  8978. ** returned and an error code and error message are stored in the
  8979. ** destination [database connection] D.
  8980. ** ^The error code and message for the failed call to sqlite3_backup_init()
  8981. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  8982. ** [sqlite3_errmsg16()] functions.
  8983. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  8984. ** [sqlite3_backup] object.
  8985. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  8986. ** sqlite3_backup_finish() functions to perform the specified backup
  8987. ** operation.
  8988. **
  8989. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  8990. **
  8991. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  8992. ** the source and destination databases specified by [sqlite3_backup] object B.
  8993. ** ^If N is negative, all remaining source pages are copied.
  8994. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  8995. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  8996. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  8997. ** from source to destination, then it returns [SQLITE_DONE].
  8998. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  8999. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  9000. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  9001. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  9002. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  9003. **
  9004. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  9005. ** <ol>
  9006. ** <li> the destination database was opened read-only, or
  9007. ** <li> the destination database is using write-ahead-log journaling
  9008. ** and the destination and source page sizes differ, or
  9009. ** <li> the destination database is an in-memory database and the
  9010. ** destination and source page sizes differ.
  9011. ** </ol>)^
  9012. **
  9013. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  9014. ** the [sqlite3_busy_handler | busy-handler function]
  9015. ** is invoked (if one is specified). ^If the
  9016. ** busy-handler returns non-zero before the lock is available, then
  9017. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  9018. ** sqlite3_backup_step() can be retried later. ^If the source
  9019. ** [database connection]
  9020. ** is being used to write to the source database when sqlite3_backup_step()
  9021. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  9022. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  9023. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  9024. ** [SQLITE_READONLY] is returned, then
  9025. ** there is no point in retrying the call to sqlite3_backup_step(). These
  9026. ** errors are considered fatal.)^ The application must accept
  9027. ** that the backup operation has failed and pass the backup operation handle
  9028. ** to the sqlite3_backup_finish() to release associated resources.
  9029. **
  9030. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  9031. ** on the destination file. ^The exclusive lock is not released until either
  9032. ** sqlite3_backup_finish() is called or the backup operation is complete
  9033. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  9034. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  9035. ** lasts for the duration of the sqlite3_backup_step() call.
  9036. ** ^Because the source database is not locked between calls to
  9037. ** sqlite3_backup_step(), the source database may be modified mid-way
  9038. ** through the backup process. ^If the source database is modified by an
  9039. ** external process or via a database connection other than the one being
  9040. ** used by the backup operation, then the backup will be automatically
  9041. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  9042. ** database is modified by the using the same database connection as is used
  9043. ** by the backup operation, then the backup database is automatically
  9044. ** updated at the same time.
  9045. **
  9046. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  9047. **
  9048. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  9049. ** application wishes to abandon the backup operation, the application
  9050. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  9051. ** ^The sqlite3_backup_finish() interfaces releases all
  9052. ** resources associated with the [sqlite3_backup] object.
  9053. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  9054. ** active write-transaction on the destination database is rolled back.
  9055. ** The [sqlite3_backup] object is invalid
  9056. ** and may not be used following a call to sqlite3_backup_finish().
  9057. **
  9058. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  9059. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  9060. ** sqlite3_backup_step() completed.
  9061. ** ^If an out-of-memory condition or IO error occurred during any prior
  9062. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  9063. ** sqlite3_backup_finish() returns the corresponding [error code].
  9064. **
  9065. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  9066. ** is not a permanent error and does not affect the return value of
  9067. ** sqlite3_backup_finish().
  9068. **
  9069. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  9070. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  9071. **
  9072. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  9073. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  9074. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  9075. ** in the source database at the conclusion of the most recent
  9076. ** sqlite3_backup_step().
  9077. ** ^(The values returned by these functions are only updated by
  9078. ** sqlite3_backup_step(). If the source database is modified in a way that
  9079. ** changes the size of the source database or the number of pages remaining,
  9080. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  9081. ** and sqlite3_backup_remaining() until after the next
  9082. ** sqlite3_backup_step().)^
  9083. **
  9084. ** <b>Concurrent Usage of Database Handles</b>
  9085. **
  9086. ** ^The source [database connection] may be used by the application for other
  9087. ** purposes while a backup operation is underway or being initialized.
  9088. ** ^If SQLite is compiled and configured to support threadsafe database
  9089. ** connections, then the source database connection may be used concurrently
  9090. ** from within other threads.
  9091. **
  9092. ** However, the application must guarantee that the destination
  9093. ** [database connection] is not passed to any other API (by any thread) after
  9094. ** sqlite3_backup_init() is called and before the corresponding call to
  9095. ** sqlite3_backup_finish(). SQLite does not currently check to see
  9096. ** if the application incorrectly accesses the destination [database connection]
  9097. ** and so no error code is reported, but the operations may malfunction
  9098. ** nevertheless. Use of the destination database connection while a
  9099. ** backup is in progress might also also cause a mutex deadlock.
  9100. **
  9101. ** If running in [shared cache mode], the application must
  9102. ** guarantee that the shared cache used by the destination database
  9103. ** is not accessed while the backup is running. In practice this means
  9104. ** that the application must guarantee that the disk file being
  9105. ** backed up to is not accessed by any connection within the process,
  9106. ** not just the specific connection that was passed to sqlite3_backup_init().
  9107. **
  9108. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  9109. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  9110. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  9111. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  9112. ** same time as another thread is invoking sqlite3_backup_step() it is
  9113. ** possible that they return invalid values.
  9114. */
  9115. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  9116. sqlite3 *pDest, /* Destination database handle */
  9117. const char *zDestName, /* Destination database name */
  9118. sqlite3 *pSource, /* Source database handle */
  9119. const char *zSourceName /* Source database name */
  9120. );
  9121. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  9122. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  9123. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  9124. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  9125. /*
  9126. ** CAPI3REF: Unlock Notification
  9127. ** METHOD: sqlite3
  9128. **
  9129. ** ^When running in shared-cache mode, a database operation may fail with
  9130. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  9131. ** individual tables within the shared-cache cannot be obtained. See
  9132. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  9133. ** ^This API may be used to register a callback that SQLite will invoke
  9134. ** when the connection currently holding the required lock relinquishes it.
  9135. ** ^This API is only available if the library was compiled with the
  9136. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  9137. **
  9138. ** See Also: [Using the SQLite Unlock Notification Feature].
  9139. **
  9140. ** ^Shared-cache locks are released when a database connection concludes
  9141. ** its current transaction, either by committing it or rolling it back.
  9142. **
  9143. ** ^When a connection (known as the blocked connection) fails to obtain a
  9144. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  9145. ** identity of the database connection (the blocking connection) that
  9146. ** has locked the required resource is stored internally. ^After an
  9147. ** application receives an SQLITE_LOCKED error, it may call the
  9148. ** sqlite3_unlock_notify() method with the blocked connection handle as
  9149. ** the first argument to register for a callback that will be invoked
  9150. ** when the blocking connections current transaction is concluded. ^The
  9151. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  9152. ** call that concludes the blocking connections transaction.
  9153. **
  9154. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  9155. ** there is a chance that the blocking connection will have already
  9156. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  9157. ** If this happens, then the specified callback is invoked immediately,
  9158. ** from within the call to sqlite3_unlock_notify().)^
  9159. **
  9160. ** ^If the blocked connection is attempting to obtain a write-lock on a
  9161. ** shared-cache table, and more than one other connection currently holds
  9162. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  9163. ** the other connections to use as the blocking connection.
  9164. **
  9165. ** ^(There may be at most one unlock-notify callback registered by a
  9166. ** blocked connection. If sqlite3_unlock_notify() is called when the
  9167. ** blocked connection already has a registered unlock-notify callback,
  9168. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  9169. ** called with a NULL pointer as its second argument, then any existing
  9170. ** unlock-notify callback is canceled. ^The blocked connections
  9171. ** unlock-notify callback may also be canceled by closing the blocked
  9172. ** connection using [sqlite3_close()].
  9173. **
  9174. ** The unlock-notify callback is not reentrant. If an application invokes
  9175. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  9176. ** crash or deadlock may be the result.
  9177. **
  9178. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  9179. ** returns SQLITE_OK.
  9180. **
  9181. ** <b>Callback Invocation Details</b>
  9182. **
  9183. ** When an unlock-notify callback is registered, the application provides a
  9184. ** single void* pointer that is passed to the callback when it is invoked.
  9185. ** However, the signature of the callback function allows SQLite to pass
  9186. ** it an array of void* context pointers. The first argument passed to
  9187. ** an unlock-notify callback is a pointer to an array of void* pointers,
  9188. ** and the second is the number of entries in the array.
  9189. **
  9190. ** When a blocking connections transaction is concluded, there may be
  9191. ** more than one blocked connection that has registered for an unlock-notify
  9192. ** callback. ^If two or more such blocked connections have specified the
  9193. ** same callback function, then instead of invoking the callback function
  9194. ** multiple times, it is invoked once with the set of void* context pointers
  9195. ** specified by the blocked connections bundled together into an array.
  9196. ** This gives the application an opportunity to prioritize any actions
  9197. ** related to the set of unblocked database connections.
  9198. **
  9199. ** <b>Deadlock Detection</b>
  9200. **
  9201. ** Assuming that after registering for an unlock-notify callback a
  9202. ** database waits for the callback to be issued before taking any further
  9203. ** action (a reasonable assumption), then using this API may cause the
  9204. ** application to deadlock. For example, if connection X is waiting for
  9205. ** connection Y's transaction to be concluded, and similarly connection
  9206. ** Y is waiting on connection X's transaction, then neither connection
  9207. ** will proceed and the system may remain deadlocked indefinitely.
  9208. **
  9209. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  9210. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  9211. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  9212. ** unlock-notify callback is registered. The system is said to be in
  9213. ** a deadlocked state if connection A has registered for an unlock-notify
  9214. ** callback on the conclusion of connection B's transaction, and connection
  9215. ** B has itself registered for an unlock-notify callback when connection
  9216. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  9217. ** the system is also considered to be deadlocked if connection B has
  9218. ** registered for an unlock-notify callback on the conclusion of connection
  9219. ** C's transaction, where connection C is waiting on connection A. ^Any
  9220. ** number of levels of indirection are allowed.
  9221. **
  9222. ** <b>The "DROP TABLE" Exception</b>
  9223. **
  9224. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  9225. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  9226. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  9227. ** SQLite checks if there are any currently executing SELECT statements
  9228. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  9229. ** returned. In this case there is no "blocking connection", so invoking
  9230. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  9231. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  9232. ** or "DROP INDEX" query, an infinite loop might be the result.
  9233. **
  9234. ** One way around this problem is to check the extended error code returned
  9235. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  9236. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  9237. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  9238. ** SQLITE_LOCKED.)^
  9239. */
  9240. SQLITE_API int sqlite3_unlock_notify(
  9241. sqlite3 *pBlocked, /* Waiting connection */
  9242. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  9243. void *pNotifyArg /* Argument to pass to xNotify */
  9244. );
  9245. /*
  9246. ** CAPI3REF: String Comparison
  9247. **
  9248. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  9249. ** and extensions to compare the contents of two buffers containing UTF-8
  9250. ** strings in a case-independent fashion, using the same definition of "case
  9251. ** independence" that SQLite uses internally when comparing identifiers.
  9252. */
  9253. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  9254. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  9255. /*
  9256. ** CAPI3REF: String Globbing
  9257. *
  9258. ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  9259. ** string X matches the [GLOB] pattern P.
  9260. ** ^The definition of [GLOB] pattern matching used in
  9261. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  9262. ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
  9263. ** is case sensitive.
  9264. **
  9265. ** Note that this routine returns zero on a match and non-zero if the strings
  9266. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9267. **
  9268. ** See also: [sqlite3_strlike()].
  9269. */
  9270. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  9271. /*
  9272. ** CAPI3REF: String LIKE Matching
  9273. *
  9274. ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  9275. ** string X matches the [LIKE] pattern P with escape character E.
  9276. ** ^The definition of [LIKE] pattern matching used in
  9277. ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  9278. ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
  9279. ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  9280. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  9281. ** insensitive - equivalent upper and lower case ASCII characters match
  9282. ** one another.
  9283. **
  9284. ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  9285. ** only ASCII characters are case folded.
  9286. **
  9287. ** Note that this routine returns zero on a match and non-zero if the strings
  9288. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9289. **
  9290. ** See also: [sqlite3_strglob()].
  9291. */
  9292. SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  9293. /*
  9294. ** CAPI3REF: Error Logging Interface
  9295. **
  9296. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  9297. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  9298. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  9299. ** used with [sqlite3_snprintf()] to generate the final output string.
  9300. **
  9301. ** The sqlite3_log() interface is intended for use by extensions such as
  9302. ** virtual tables, collating functions, and SQL functions. While there is
  9303. ** nothing to prevent an application from calling sqlite3_log(), doing so
  9304. ** is considered bad form.
  9305. **
  9306. ** The zFormat string must not be NULL.
  9307. **
  9308. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  9309. ** will not use dynamically allocated memory. The log message is stored in
  9310. ** a fixed-length buffer on the stack. If the log message is longer than
  9311. ** a few hundred characters, it will be truncated to the length of the
  9312. ** buffer.
  9313. */
  9314. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  9315. /*
  9316. ** CAPI3REF: Write-Ahead Log Commit Hook
  9317. ** METHOD: sqlite3
  9318. **
  9319. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  9320. ** is invoked each time data is committed to a database in wal mode.
  9321. **
  9322. ** ^(The callback is invoked by SQLite after the commit has taken place and
  9323. ** the associated write-lock on the database released)^, so the implementation
  9324. ** may read, write or [checkpoint] the database as required.
  9325. **
  9326. ** ^The first parameter passed to the callback function when it is invoked
  9327. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  9328. ** registering the callback. ^The second is a copy of the database handle.
  9329. ** ^The third parameter is the name of the database that was written to -
  9330. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  9331. ** is the number of pages currently in the write-ahead log file,
  9332. ** including those that were just committed.
  9333. **
  9334. ** The callback function should normally return [SQLITE_OK]. ^If an error
  9335. ** code is returned, that error will propagate back up through the
  9336. ** SQLite code base to cause the statement that provoked the callback
  9337. ** to report an error, though the commit will have still occurred. If the
  9338. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  9339. ** that does not correspond to any valid SQLite error code, the results
  9340. ** are undefined.
  9341. **
  9342. ** A single database handle may have at most a single write-ahead log callback
  9343. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  9344. ** previously registered write-ahead log callback. ^Note that the
  9345. ** [sqlite3_wal_autocheckpoint()] interface and the
  9346. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  9347. ** overwrite any prior [sqlite3_wal_hook()] settings.
  9348. */
  9349. SQLITE_API void *sqlite3_wal_hook(
  9350. sqlite3*,
  9351. int(*)(void *,sqlite3*,const char*,int),
  9352. void*
  9353. );
  9354. /*
  9355. ** CAPI3REF: Configure an auto-checkpoint
  9356. ** METHOD: sqlite3
  9357. **
  9358. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  9359. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  9360. ** to automatically [checkpoint]
  9361. ** after committing a transaction if there are N or
  9362. ** more frames in the [write-ahead log] file. ^Passing zero or
  9363. ** a negative value as the nFrame parameter disables automatic
  9364. ** checkpoints entirely.
  9365. **
  9366. ** ^The callback registered by this function replaces any existing callback
  9367. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  9368. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  9369. ** configured by this function.
  9370. **
  9371. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  9372. ** from SQL.
  9373. **
  9374. ** ^Checkpoints initiated by this mechanism are
  9375. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  9376. **
  9377. ** ^Every new [database connection] defaults to having the auto-checkpoint
  9378. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  9379. ** pages. The use of this interface
  9380. ** is only necessary if the default setting is found to be suboptimal
  9381. ** for a particular application.
  9382. */
  9383. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  9384. /*
  9385. ** CAPI3REF: Checkpoint a database
  9386. ** METHOD: sqlite3
  9387. **
  9388. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  9389. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  9390. **
  9391. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  9392. ** [write-ahead log] for database X on [database connection] D to be
  9393. ** transferred into the database file and for the write-ahead log to
  9394. ** be reset. See the [checkpointing] documentation for addition
  9395. ** information.
  9396. **
  9397. ** This interface used to be the only way to cause a checkpoint to
  9398. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  9399. ** interface was added. This interface is retained for backwards
  9400. ** compatibility and as a convenience for applications that need to manually
  9401. ** start a callback but which do not need the full power (and corresponding
  9402. ** complication) of [sqlite3_wal_checkpoint_v2()].
  9403. */
  9404. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  9405. /*
  9406. ** CAPI3REF: Checkpoint a database
  9407. ** METHOD: sqlite3
  9408. **
  9409. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  9410. ** operation on database X of [database connection] D in mode M. Status
  9411. ** information is written back into integers pointed to by L and C.)^
  9412. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  9413. **
  9414. ** <dl>
  9415. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  9416. ** ^Checkpoint as many frames as possible without waiting for any database
  9417. ** readers or writers to finish, then sync the database file if all frames
  9418. ** in the log were checkpointed. ^The [busy-handler callback]
  9419. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  9420. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  9421. ** if there are concurrent readers or writers.
  9422. **
  9423. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  9424. ** ^This mode blocks (it invokes the
  9425. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  9426. ** database writer and all readers are reading from the most recent database
  9427. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  9428. ** database file. ^This mode blocks new database writers while it is pending,
  9429. ** but new database readers are allowed to continue unimpeded.
  9430. **
  9431. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  9432. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  9433. ** that after checkpointing the log file it blocks (calls the
  9434. ** [busy-handler callback])
  9435. ** until all readers are reading from the database file only. ^This ensures
  9436. ** that the next writer will restart the log file from the beginning.
  9437. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  9438. ** database writer attempts while it is pending, but does not impede readers.
  9439. **
  9440. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  9441. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  9442. ** addition that it also truncates the log file to zero bytes just prior
  9443. ** to a successful return.
  9444. ** </dl>
  9445. **
  9446. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  9447. ** the log file or to -1 if the checkpoint could not run because
  9448. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  9449. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  9450. ** log file (including any that were already checkpointed before the function
  9451. ** was called) or to -1 if the checkpoint could not run due to an error or
  9452. ** because the database is not in WAL mode. ^Note that upon successful
  9453. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  9454. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  9455. **
  9456. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  9457. ** any other process is running a checkpoint operation at the same time, the
  9458. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  9459. ** busy-handler configured, it will not be invoked in this case.
  9460. **
  9461. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  9462. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  9463. ** obtained immediately, and a busy-handler is configured, it is invoked and
  9464. ** the writer lock retried until either the busy-handler returns 0 or the lock
  9465. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  9466. ** database readers as described above. ^If the busy-handler returns 0 before
  9467. ** the writer lock is obtained or while waiting for database readers, the
  9468. ** checkpoint operation proceeds from that point in the same way as
  9469. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  9470. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  9471. **
  9472. ** ^If parameter zDb is NULL or points to a zero length string, then the
  9473. ** specified operation is attempted on all WAL databases [attached] to
  9474. ** [database connection] db. In this case the
  9475. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  9476. ** an SQLITE_BUSY error is encountered when processing one or more of the
  9477. ** attached WAL databases, the operation is still attempted on any remaining
  9478. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  9479. ** error occurs while processing an attached database, processing is abandoned
  9480. ** and the error code is returned to the caller immediately. ^If no error
  9481. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  9482. ** databases, SQLITE_OK is returned.
  9483. **
  9484. ** ^If database zDb is the name of an attached database that is not in WAL
  9485. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  9486. ** zDb is not NULL (or a zero length string) and is not the name of any
  9487. ** attached database, SQLITE_ERROR is returned to the caller.
  9488. **
  9489. ** ^Unless it returns SQLITE_MISUSE,
  9490. ** the sqlite3_wal_checkpoint_v2() interface
  9491. ** sets the error information that is queried by
  9492. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  9493. **
  9494. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  9495. ** from SQL.
  9496. */
  9497. SQLITE_API int sqlite3_wal_checkpoint_v2(
  9498. sqlite3 *db, /* Database handle */
  9499. const char *zDb, /* Name of attached database (or NULL) */
  9500. int eMode, /* SQLITE_CHECKPOINT_* value */
  9501. int *pnLog, /* OUT: Size of WAL log in frames */
  9502. int *pnCkpt /* OUT: Total number of frames checkpointed */
  9503. );
  9504. /*
  9505. ** CAPI3REF: Checkpoint Mode Values
  9506. ** KEYWORDS: {checkpoint mode}
  9507. **
  9508. ** These constants define all valid values for the "checkpoint mode" passed
  9509. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  9510. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  9511. ** meaning of each of these checkpoint modes.
  9512. */
  9513. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  9514. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  9515. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  9516. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  9517. /*
  9518. ** CAPI3REF: Virtual Table Interface Configuration
  9519. **
  9520. ** This function may be called by either the [xConnect] or [xCreate] method
  9521. ** of a [virtual table] implementation to configure
  9522. ** various facets of the virtual table interface.
  9523. **
  9524. ** If this interface is invoked outside the context of an xConnect or
  9525. ** xCreate virtual table method then the behavior is undefined.
  9526. **
  9527. ** At present, there is only one option that may be configured using
  9528. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  9529. ** may be added in the future.
  9530. */
  9531. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  9532. /*
  9533. ** CAPI3REF: Virtual Table Configuration Options
  9534. **
  9535. ** These macros define the various options to the
  9536. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  9537. ** can use to customize and optimize their behavior.
  9538. **
  9539. ** <dl>
  9540. ** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
  9541. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  9542. ** <dd>Calls of the form
  9543. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  9544. ** where X is an integer. If X is zero, then the [virtual table] whose
  9545. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  9546. ** support constraints. In this configuration (which is the default) if
  9547. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  9548. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  9549. ** specified as part of the users SQL statement, regardless of the actual
  9550. ** ON CONFLICT mode specified.
  9551. **
  9552. ** If X is non-zero, then the virtual table implementation guarantees
  9553. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  9554. ** any modifications to internal or persistent data structures have been made.
  9555. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  9556. ** is able to roll back a statement or database transaction, and abandon
  9557. ** or continue processing the current SQL statement as appropriate.
  9558. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  9559. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  9560. ** had been ABORT.
  9561. **
  9562. ** Virtual table implementations that are required to handle OR REPLACE
  9563. ** must do so within the [xUpdate] method. If a call to the
  9564. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  9565. ** CONFLICT policy is REPLACE, the virtual table implementation should
  9566. ** silently replace the appropriate rows within the xUpdate callback and
  9567. ** return SQLITE_OK. Or, if this is not possible, it may return
  9568. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  9569. ** constraint handling.
  9570. ** </dl>
  9571. */
  9572. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  9573. /*
  9574. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  9575. **
  9576. ** This function may only be called from within a call to the [xUpdate] method
  9577. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  9578. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  9579. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  9580. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  9581. ** [virtual table].
  9582. */
  9583. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  9584. /*
  9585. ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
  9586. **
  9587. ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
  9588. ** method of a [virtual table], then it returns true if and only if the
  9589. ** column is being fetched as part of an UPDATE operation during which the
  9590. ** column value will not change. Applications might use this to substitute
  9591. ** a return value that is less expensive to compute and that the corresponding
  9592. ** [xUpdate] method understands as a "no-change" value.
  9593. **
  9594. ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
  9595. ** the column is not changed by the UPDATE statement, then the xColumn
  9596. ** method can optionally return without setting a result, without calling
  9597. ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
  9598. ** In that case, [sqlite3_value_nochange(X)] will return true for the
  9599. ** same column in the [xUpdate] method.
  9600. */
  9601. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
  9602. /*
  9603. ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
  9604. **
  9605. ** This function may only be called from within a call to the [xBestIndex]
  9606. ** method of a [virtual table].
  9607. **
  9608. ** The first argument must be the sqlite3_index_info object that is the
  9609. ** first parameter to the xBestIndex() method. The second argument must be
  9610. ** an index into the aConstraint[] array belonging to the sqlite3_index_info
  9611. ** structure passed to xBestIndex. This function returns a pointer to a buffer
  9612. ** containing the name of the collation sequence for the corresponding
  9613. ** constraint.
  9614. */
  9615. SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
  9616. /*
  9617. ** CAPI3REF: Conflict resolution modes
  9618. ** KEYWORDS: {conflict resolution mode}
  9619. **
  9620. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  9621. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  9622. ** is for the SQL statement being evaluated.
  9623. **
  9624. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  9625. ** return value from the [sqlite3_set_authorizer()] callback and that
  9626. ** [SQLITE_ABORT] is also a [result code].
  9627. */
  9628. #define SQLITE_ROLLBACK 1
  9629. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  9630. #define SQLITE_FAIL 3
  9631. /* #define SQLITE_ABORT 4 // Also an error code */
  9632. #define SQLITE_REPLACE 5
  9633. /*
  9634. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  9635. ** KEYWORDS: {scanstatus options}
  9636. **
  9637. ** The following constants can be used for the T parameter to the
  9638. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  9639. ** different metric for sqlite3_stmt_scanstatus() to return.
  9640. **
  9641. ** When the value returned to V is a string, space to hold that string is
  9642. ** managed by the prepared statement S and will be automatically freed when
  9643. ** S is finalized.
  9644. **
  9645. ** <dl>
  9646. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  9647. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  9648. ** set to the total number of times that the X-th loop has run.</dd>
  9649. **
  9650. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  9651. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  9652. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  9653. **
  9654. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  9655. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  9656. ** query planner's estimate for the average number of rows output from each
  9657. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  9658. ** then this value will approximate the quotient NVISIT/NLOOP and the
  9659. ** product of this value for all prior loops with the same SELECTID will
  9660. ** be the NLOOP value for the current loop.
  9661. **
  9662. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  9663. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9664. ** to a zero-terminated UTF-8 string containing the name of the index or table
  9665. ** used for the X-th loop.
  9666. **
  9667. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  9668. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9669. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  9670. ** description for the X-th loop.
  9671. **
  9672. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  9673. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  9674. ** "select-id" for the X-th loop. The select-id identifies which query or
  9675. ** subquery the loop is part of. The main query has a select-id of zero.
  9676. ** The select-id is the same value as is output in the first column
  9677. ** of an [EXPLAIN QUERY PLAN] query.
  9678. ** </dl>
  9679. */
  9680. #define SQLITE_SCANSTAT_NLOOP 0
  9681. #define SQLITE_SCANSTAT_NVISIT 1
  9682. #define SQLITE_SCANSTAT_EST 2
  9683. #define SQLITE_SCANSTAT_NAME 3
  9684. #define SQLITE_SCANSTAT_EXPLAIN 4
  9685. #define SQLITE_SCANSTAT_SELECTID 5
  9686. /*
  9687. ** CAPI3REF: Prepared Statement Scan Status
  9688. ** METHOD: sqlite3_stmt
  9689. **
  9690. ** This interface returns information about the predicted and measured
  9691. ** performance for pStmt. Advanced applications can use this
  9692. ** interface to compare the predicted and the measured performance and
  9693. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  9694. **
  9695. ** Since this interface is expected to be rarely used, it is only
  9696. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  9697. ** compile-time option.
  9698. **
  9699. ** The "iScanStatusOp" parameter determines which status information to return.
  9700. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  9701. ** of this interface is undefined.
  9702. ** ^The requested measurement is written into a variable pointed to by
  9703. ** the "pOut" parameter.
  9704. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  9705. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  9706. ** zero or greater than or equal to the total number of loops used to implement
  9707. ** the statement - a non-zero value is returned and the variable that pOut
  9708. ** points to is unchanged.
  9709. **
  9710. ** ^Statistics might not be available for all loops in all statements. ^In cases
  9711. ** where there exist loops with no available statistics, this function behaves
  9712. ** as if the loop did not exist - it returns non-zero and leave the variable
  9713. ** that pOut points to unchanged.
  9714. **
  9715. ** See also: [sqlite3_stmt_scanstatus_reset()]
  9716. */
  9717. SQLITE_API int sqlite3_stmt_scanstatus(
  9718. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  9719. int idx, /* Index of loop to report on */
  9720. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  9721. void *pOut /* Result written here */
  9722. );
  9723. /*
  9724. ** CAPI3REF: Zero Scan-Status Counters
  9725. ** METHOD: sqlite3_stmt
  9726. **
  9727. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  9728. **
  9729. ** This API is only available if the library is built with pre-processor
  9730. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  9731. */
  9732. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  9733. /*
  9734. ** CAPI3REF: Flush caches to disk mid-transaction
  9735. **
  9736. ** ^If a write-transaction is open on [database connection] D when the
  9737. ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  9738. ** pages in the pager-cache that are not currently in use are written out
  9739. ** to disk. A dirty page may be in use if a database cursor created by an
  9740. ** active SQL statement is reading from it, or if it is page 1 of a database
  9741. ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
  9742. ** interface flushes caches for all schemas - "main", "temp", and
  9743. ** any [attached] databases.
  9744. **
  9745. ** ^If this function needs to obtain extra database locks before dirty pages
  9746. ** can be flushed to disk, it does so. ^If those locks cannot be obtained
  9747. ** immediately and there is a busy-handler callback configured, it is invoked
  9748. ** in the usual manner. ^If the required lock still cannot be obtained, then
  9749. ** the database is skipped and an attempt made to flush any dirty pages
  9750. ** belonging to the next (if any) database. ^If any databases are skipped
  9751. ** because locks cannot be obtained, but no other error occurs, this
  9752. ** function returns SQLITE_BUSY.
  9753. **
  9754. ** ^If any other error occurs while flushing dirty pages to disk (for
  9755. ** example an IO error or out-of-memory condition), then processing is
  9756. ** abandoned and an SQLite [error code] is returned to the caller immediately.
  9757. **
  9758. ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  9759. **
  9760. ** ^This function does not set the database handle error code or message
  9761. ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  9762. */
  9763. SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
  9764. /*
  9765. ** CAPI3REF: The pre-update hook.
  9766. **
  9767. ** ^These interfaces are only available if SQLite is compiled using the
  9768. ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
  9769. **
  9770. ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
  9771. ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
  9772. ** on a database table.
  9773. ** ^At most one preupdate hook may be registered at a time on a single
  9774. ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
  9775. ** the previous setting.
  9776. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
  9777. ** with a NULL pointer as the second parameter.
  9778. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
  9779. ** the first parameter to callbacks.
  9780. **
  9781. ** ^The preupdate hook only fires for changes to real database tables; the
  9782. ** preupdate hook is not invoked for changes to [virtual tables] or to
  9783. ** system tables like sqlite_master or sqlite_stat1.
  9784. **
  9785. ** ^The second parameter to the preupdate callback is a pointer to
  9786. ** the [database connection] that registered the preupdate hook.
  9787. ** ^The third parameter to the preupdate callback is one of the constants
  9788. ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
  9789. ** kind of update operation that is about to occur.
  9790. ** ^(The fourth parameter to the preupdate callback is the name of the
  9791. ** database within the database connection that is being modified. This
  9792. ** will be "main" for the main database or "temp" for TEMP tables or
  9793. ** the name given after the AS keyword in the [ATTACH] statement for attached
  9794. ** databases.)^
  9795. ** ^The fifth parameter to the preupdate callback is the name of the
  9796. ** table that is being modified.
  9797. **
  9798. ** For an UPDATE or DELETE operation on a [rowid table], the sixth
  9799. ** parameter passed to the preupdate callback is the initial [rowid] of the
  9800. ** row being modified or deleted. For an INSERT operation on a rowid table,
  9801. ** or any operation on a WITHOUT ROWID table, the value of the sixth
  9802. ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
  9803. ** seventh parameter is the final rowid value of the row being inserted
  9804. ** or updated. The value of the seventh parameter passed to the callback
  9805. ** function is not defined for operations on WITHOUT ROWID tables, or for
  9806. ** INSERT operations on rowid tables.
  9807. **
  9808. ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
  9809. ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
  9810. ** provide additional information about a preupdate event. These routines
  9811. ** may only be called from within a preupdate callback. Invoking any of
  9812. ** these routines from outside of a preupdate callback or with a
  9813. ** [database connection] pointer that is different from the one supplied
  9814. ** to the preupdate callback results in undefined and probably undesirable
  9815. ** behavior.
  9816. **
  9817. ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
  9818. ** in the row that is being inserted, updated, or deleted.
  9819. **
  9820. ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
  9821. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9822. ** the table row before it is updated. The N parameter must be between 0
  9823. ** and one less than the number of columns or the behavior will be
  9824. ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
  9825. ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
  9826. ** behavior is undefined. The [sqlite3_value] that P points to
  9827. ** will be destroyed when the preupdate callback returns.
  9828. **
  9829. ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
  9830. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9831. ** the table row after it is updated. The N parameter must be between 0
  9832. ** and one less than the number of columns or the behavior will be
  9833. ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
  9834. ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
  9835. ** behavior is undefined. The [sqlite3_value] that P points to
  9836. ** will be destroyed when the preupdate callback returns.
  9837. **
  9838. ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
  9839. ** callback was invoked as a result of a direct insert, update, or delete
  9840. ** operation; or 1 for inserts, updates, or deletes invoked by top-level
  9841. ** triggers; or 2 for changes resulting from triggers called by top-level
  9842. ** triggers; and so forth.
  9843. **
  9844. ** See also: [sqlite3_update_hook()]
  9845. */
  9846. #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  9847. SQLITE_API void *sqlite3_preupdate_hook(
  9848. sqlite3 *db,
  9849. void(*xPreUpdate)(
  9850. void *pCtx, /* Copy of third arg to preupdate_hook() */
  9851. sqlite3 *db, /* Database handle */
  9852. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  9853. char const *zDb, /* Database name */
  9854. char const *zName, /* Table name */
  9855. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  9856. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  9857. ),
  9858. void*
  9859. );
  9860. SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
  9861. SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
  9862. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
  9863. SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
  9864. #endif
  9865. /*
  9866. ** CAPI3REF: Low-level system error code
  9867. **
  9868. ** ^Attempt to return the underlying operating system error code or error
  9869. ** number that caused the most recent I/O error or failure to open a file.
  9870. ** The return value is OS-dependent. For example, on unix systems, after
  9871. ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
  9872. ** called to get back the underlying "errno" that caused the problem, such
  9873. ** as ENOSPC, EAUTH, EISDIR, and so forth.
  9874. */
  9875. SQLITE_API int sqlite3_system_errno(sqlite3*);
  9876. /*
  9877. ** CAPI3REF: Database Snapshot
  9878. ** KEYWORDS: {snapshot} {sqlite3_snapshot}
  9879. **
  9880. ** An instance of the snapshot object records the state of a [WAL mode]
  9881. ** database for some specific point in history.
  9882. **
  9883. ** In [WAL mode], multiple [database connections] that are open on the
  9884. ** same database file can each be reading a different historical version
  9885. ** of the database file. When a [database connection] begins a read
  9886. ** transaction, that connection sees an unchanging copy of the database
  9887. ** as it existed for the point in time when the transaction first started.
  9888. ** Subsequent changes to the database from other connections are not seen
  9889. ** by the reader until a new read transaction is started.
  9890. **
  9891. ** The sqlite3_snapshot object records state information about an historical
  9892. ** version of the database file so that it is possible to later open a new read
  9893. ** transaction that sees that historical version of the database rather than
  9894. ** the most recent version.
  9895. */
  9896. typedef struct sqlite3_snapshot {
  9897. unsigned char hidden[48];
  9898. } sqlite3_snapshot;
  9899. /*
  9900. ** CAPI3REF: Record A Database Snapshot
  9901. ** CONSTRUCTOR: sqlite3_snapshot
  9902. **
  9903. ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  9904. ** new [sqlite3_snapshot] object that records the current state of
  9905. ** schema S in database connection D. ^On success, the
  9906. ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  9907. ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  9908. ** If there is not already a read-transaction open on schema S when
  9909. ** this function is called, one is opened automatically.
  9910. **
  9911. ** The following must be true for this function to succeed. If any of
  9912. ** the following statements are false when sqlite3_snapshot_get() is
  9913. ** called, SQLITE_ERROR is returned. The final value of *P is undefined
  9914. ** in this case.
  9915. **
  9916. ** <ul>
  9917. ** <li> The database handle must not be in [autocommit mode].
  9918. **
  9919. ** <li> Schema S of [database connection] D must be a [WAL mode] database.
  9920. **
  9921. ** <li> There must not be a write transaction open on schema S of database
  9922. ** connection D.
  9923. **
  9924. ** <li> One or more transactions must have been written to the current wal
  9925. ** file since it was created on disk (by any connection). This means
  9926. ** that a snapshot cannot be taken on a wal mode database with no wal
  9927. ** file immediately after it is first opened. At least one transaction
  9928. ** must be written to it first.
  9929. ** </ul>
  9930. **
  9931. ** This function may also return SQLITE_NOMEM. If it is called with the
  9932. ** database handle in autocommit mode but fails for some other reason,
  9933. ** whether or not a read transaction is opened on schema S is undefined.
  9934. **
  9935. ** The [sqlite3_snapshot] object returned from a successful call to
  9936. ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  9937. ** to avoid a memory leak.
  9938. **
  9939. ** The [sqlite3_snapshot_get()] interface is only available when the
  9940. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  9941. */
  9942. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
  9943. sqlite3 *db,
  9944. const char *zSchema,
  9945. sqlite3_snapshot **ppSnapshot
  9946. );
  9947. /*
  9948. ** CAPI3REF: Start a read transaction on an historical snapshot
  9949. ** METHOD: sqlite3_snapshot
  9950. **
  9951. ** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
  9952. ** transaction or upgrades an existing one for schema S of
  9953. ** [database connection] D such that the read transaction refers to
  9954. ** historical [snapshot] P, rather than the most recent change to the
  9955. ** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
  9956. ** on success or an appropriate [error code] if it fails.
  9957. **
  9958. ** ^In order to succeed, the database connection must not be in
  9959. ** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
  9960. ** is already a read transaction open on schema S, then the database handle
  9961. ** must have no active statements (SELECT statements that have been passed
  9962. ** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
  9963. ** SQLITE_ERROR is returned if either of these conditions is violated, or
  9964. ** if schema S does not exist, or if the snapshot object is invalid.
  9965. **
  9966. ** ^A call to sqlite3_snapshot_open() will fail to open if the specified
  9967. ** snapshot has been overwritten by a [checkpoint]. In this case
  9968. ** SQLITE_ERROR_SNAPSHOT is returned.
  9969. **
  9970. ** If there is already a read transaction open when this function is
  9971. ** invoked, then the same read transaction remains open (on the same
  9972. ** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
  9973. ** is returned. If another error code - for example SQLITE_PROTOCOL or an
  9974. ** SQLITE_IOERR error code - is returned, then the final state of the
  9975. ** read transaction is undefined. If SQLITE_OK is returned, then the
  9976. ** read transaction is now open on database snapshot P.
  9977. **
  9978. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
  9979. ** database connection D does not know that the database file for
  9980. ** schema S is in [WAL mode]. A database connection might not know
  9981. ** that the database file is in [WAL mode] if there has been no prior
  9982. ** I/O on that database connection, or if the database entered [WAL mode]
  9983. ** after the most recent I/O on the database connection.)^
  9984. ** (Hint: Run "[PRAGMA application_id]" against a newly opened
  9985. ** database connection in order to make it ready to use snapshots.)
  9986. **
  9987. ** The [sqlite3_snapshot_open()] interface is only available when the
  9988. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  9989. */
  9990. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
  9991. sqlite3 *db,
  9992. const char *zSchema,
  9993. sqlite3_snapshot *pSnapshot
  9994. );
  9995. /*
  9996. ** CAPI3REF: Destroy a snapshot
  9997. ** DESTRUCTOR: sqlite3_snapshot
  9998. **
  9999. ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  10000. ** The application must eventually free every [sqlite3_snapshot] object
  10001. ** using this routine to avoid a memory leak.
  10002. **
  10003. ** The [sqlite3_snapshot_free()] interface is only available when the
  10004. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  10005. */
  10006. SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
  10007. /*
  10008. ** CAPI3REF: Compare the ages of two snapshot handles.
  10009. ** METHOD: sqlite3_snapshot
  10010. **
  10011. ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
  10012. ** of two valid snapshot handles.
  10013. **
  10014. ** If the two snapshot handles are not associated with the same database
  10015. ** file, the result of the comparison is undefined.
  10016. **
  10017. ** Additionally, the result of the comparison is only valid if both of the
  10018. ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
  10019. ** last time the wal file was deleted. The wal file is deleted when the
  10020. ** database is changed back to rollback mode or when the number of database
  10021. ** clients drops to zero. If either snapshot handle was obtained before the
  10022. ** wal file was last deleted, the value returned by this function
  10023. ** is undefined.
  10024. **
  10025. ** Otherwise, this API returns a negative value if P1 refers to an older
  10026. ** snapshot than P2, zero if the two handles refer to the same database
  10027. ** snapshot, and a positive value if P1 is a newer snapshot than P2.
  10028. **
  10029. ** This interface is only available if SQLite is compiled with the
  10030. ** [SQLITE_ENABLE_SNAPSHOT] option.
  10031. */
  10032. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
  10033. sqlite3_snapshot *p1,
  10034. sqlite3_snapshot *p2
  10035. );
  10036. /*
  10037. ** CAPI3REF: Recover snapshots from a wal file
  10038. ** METHOD: sqlite3_snapshot
  10039. **
  10040. ** If a [WAL file] remains on disk after all database connections close
  10041. ** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]
  10042. ** or because the last process to have the database opened exited without
  10043. ** calling [sqlite3_close()]) and a new connection is subsequently opened
  10044. ** on that database and [WAL file], the [sqlite3_snapshot_open()] interface
  10045. ** will only be able to open the last transaction added to the WAL file
  10046. ** even though the WAL file contains other valid transactions.
  10047. **
  10048. ** This function attempts to scan the WAL file associated with database zDb
  10049. ** of database handle db and make all valid snapshots available to
  10050. ** sqlite3_snapshot_open(). It is an error if there is already a read
  10051. ** transaction open on the database, or if the database is not a WAL mode
  10052. ** database.
  10053. **
  10054. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  10055. **
  10056. ** This interface is only available if SQLite is compiled with the
  10057. ** [SQLITE_ENABLE_SNAPSHOT] option.
  10058. */
  10059. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
  10060. /*
  10061. ** CAPI3REF: Serialize a database
  10062. **
  10063. ** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
  10064. ** that is a serialization of the S database on [database connection] D.
  10065. ** If P is not a NULL pointer, then the size of the database in bytes
  10066. ** is written into *P.
  10067. **
  10068. ** For an ordinary on-disk database file, the serialization is just a
  10069. ** copy of the disk file. For an in-memory database or a "TEMP" database,
  10070. ** the serialization is the same sequence of bytes which would be written
  10071. ** to disk if that database where backed up to disk.
  10072. **
  10073. ** The usual case is that sqlite3_serialize() copies the serialization of
  10074. ** the database into memory obtained from [sqlite3_malloc64()] and returns
  10075. ** a pointer to that memory. The caller is responsible for freeing the
  10076. ** returned value to avoid a memory leak. However, if the F argument
  10077. ** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
  10078. ** are made, and the sqlite3_serialize() function will return a pointer
  10079. ** to the contiguous memory representation of the database that SQLite
  10080. ** is currently using for that database, or NULL if the no such contiguous
  10081. ** memory representation of the database exists. A contiguous memory
  10082. ** representation of the database will usually only exist if there has
  10083. ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
  10084. ** values of D and S.
  10085. ** The size of the database is written into *P even if the
  10086. ** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
  10087. ** of the database exists.
  10088. **
  10089. ** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
  10090. ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
  10091. ** allocation error occurs.
  10092. **
  10093. ** This interface is only available if SQLite is compiled with the
  10094. ** [SQLITE_ENABLE_DESERIALIZE] option.
  10095. */
  10096. SQLITE_API unsigned char *sqlite3_serialize(
  10097. sqlite3 *db, /* The database connection */
  10098. const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */
  10099. sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
  10100. unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */
  10101. );
  10102. /*
  10103. ** CAPI3REF: Flags for sqlite3_serialize
  10104. **
  10105. ** Zero or more of the following constants can be OR-ed together for
  10106. ** the F argument to [sqlite3_serialize(D,S,P,F)].
  10107. **
  10108. ** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
  10109. ** a pointer to contiguous in-memory database that it is currently using,
  10110. ** without making a copy of the database. If SQLite is not currently using
  10111. ** a contiguous in-memory database, then this option causes
  10112. ** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be
  10113. ** using a contiguous in-memory database if it has been initialized by a
  10114. ** prior call to [sqlite3_deserialize()].
  10115. */
  10116. #define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */
  10117. /*
  10118. ** CAPI3REF: Deserialize a database
  10119. **
  10120. ** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
  10121. ** [database connection] D to disconnect from database S and then
  10122. ** reopen S as an in-memory database based on the serialization contained
  10123. ** in P. The serialized database P is N bytes in size. M is the size of
  10124. ** the buffer P, which might be larger than N. If M is larger than N, and
  10125. ** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
  10126. ** permitted to add content to the in-memory database as long as the total
  10127. ** size does not exceed M bytes.
  10128. **
  10129. ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
  10130. ** invoke sqlite3_free() on the serialization buffer when the database
  10131. ** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
  10132. ** SQLite will try to increase the buffer size using sqlite3_realloc64()
  10133. ** if writes on the database cause it to grow larger than M bytes.
  10134. **
  10135. ** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
  10136. ** database is currently in a read transaction or is involved in a backup
  10137. ** operation.
  10138. **
  10139. ** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
  10140. ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
  10141. ** [sqlite3_free()] is invoked on argument P prior to returning.
  10142. **
  10143. ** This interface is only available if SQLite is compiled with the
  10144. ** [SQLITE_ENABLE_DESERIALIZE] option.
  10145. */
  10146. SQLITE_API int sqlite3_deserialize(
  10147. sqlite3 *db, /* The database connection */
  10148. const char *zSchema, /* Which DB to reopen with the deserialization */
  10149. unsigned char *pData, /* The serialized database content */
  10150. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  10151. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  10152. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  10153. );
  10154. /*
  10155. ** CAPI3REF: Flags for sqlite3_deserialize()
  10156. **
  10157. ** The following are allowed values for 6th argument (the F argument) to
  10158. ** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
  10159. **
  10160. ** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
  10161. ** in the P argument is held in memory obtained from [sqlite3_malloc64()]
  10162. ** and that SQLite should take ownership of this memory and automatically
  10163. ** free it when it has finished using it. Without this flag, the caller
  10164. ** is responsible for freeing any dynamically allocated memory.
  10165. **
  10166. ** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
  10167. ** grow the size of the database using calls to [sqlite3_realloc64()]. This
  10168. ** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
  10169. ** Without this flag, the deserialized database cannot increase in size beyond
  10170. ** the number of bytes specified by the M parameter.
  10171. **
  10172. ** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
  10173. ** should be treated as read-only.
  10174. */
  10175. #define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
  10176. #define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */
  10177. #define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
  10178. /*
  10179. ** Undo the hack that converts floating point types to integer for
  10180. ** builds on processors without floating point support.
  10181. */
  10182. #ifdef SQLITE_OMIT_FLOATING_POINT
  10183. # undef double
  10184. #endif
  10185. #if 0
  10186. } /* End of the 'extern "C"' block */
  10187. #endif
  10188. #endif /* SQLITE3_H */
  10189. /******** Begin file sqlite3rtree.h *********/
  10190. /*
  10191. ** 2010 August 30
  10192. **
  10193. ** The author disclaims copyright to this source code. In place of
  10194. ** a legal notice, here is a blessing:
  10195. **
  10196. ** May you do good and not evil.
  10197. ** May you find forgiveness for yourself and forgive others.
  10198. ** May you share freely, never taking more than you give.
  10199. **
  10200. *************************************************************************
  10201. */
  10202. #ifndef _SQLITE3RTREE_H_
  10203. #define _SQLITE3RTREE_H_
  10204. #if 0
  10205. extern "C" {
  10206. #endif
  10207. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  10208. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  10209. /* The double-precision datatype used by RTree depends on the
  10210. ** SQLITE_RTREE_INT_ONLY compile-time option.
  10211. */
  10212. #ifdef SQLITE_RTREE_INT_ONLY
  10213. typedef sqlite3_int64 sqlite3_rtree_dbl;
  10214. #else
  10215. typedef double sqlite3_rtree_dbl;
  10216. #endif
  10217. /*
  10218. ** Register a geometry callback named zGeom that can be used as part of an
  10219. ** R-Tree geometry query as follows:
  10220. **
  10221. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  10222. */
  10223. SQLITE_API int sqlite3_rtree_geometry_callback(
  10224. sqlite3 *db,
  10225. const char *zGeom,
  10226. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  10227. void *pContext
  10228. );
  10229. /*
  10230. ** A pointer to a structure of the following type is passed as the first
  10231. ** argument to callbacks registered using rtree_geometry_callback().
  10232. */
  10233. struct sqlite3_rtree_geometry {
  10234. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  10235. int nParam; /* Size of array aParam[] */
  10236. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  10237. void *pUser; /* Callback implementation user data */
  10238. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  10239. };
  10240. /*
  10241. ** Register a 2nd-generation geometry callback named zScore that can be
  10242. ** used as part of an R-Tree geometry query as follows:
  10243. **
  10244. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  10245. */
  10246. SQLITE_API int sqlite3_rtree_query_callback(
  10247. sqlite3 *db,
  10248. const char *zQueryFunc,
  10249. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  10250. void *pContext,
  10251. void (*xDestructor)(void*)
  10252. );
  10253. /*
  10254. ** A pointer to a structure of the following type is passed as the
  10255. ** argument to scored geometry callback registered using
  10256. ** sqlite3_rtree_query_callback().
  10257. **
  10258. ** Note that the first 5 fields of this structure are identical to
  10259. ** sqlite3_rtree_geometry. This structure is a subclass of
  10260. ** sqlite3_rtree_geometry.
  10261. */
  10262. struct sqlite3_rtree_query_info {
  10263. void *pContext; /* pContext from when function registered */
  10264. int nParam; /* Number of function parameters */
  10265. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  10266. void *pUser; /* callback can use this, if desired */
  10267. void (*xDelUser)(void*); /* function to free pUser */
  10268. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  10269. unsigned int *anQueue; /* Number of pending entries in the queue */
  10270. int nCoord; /* Number of coordinates */
  10271. int iLevel; /* Level of current node or entry */
  10272. int mxLevel; /* The largest iLevel value in the tree */
  10273. sqlite3_int64 iRowid; /* Rowid for current entry */
  10274. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  10275. int eParentWithin; /* Visibility of parent node */
  10276. int eWithin; /* OUT: Visibility */
  10277. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  10278. /* The following fields are only available in 3.8.11 and later */
  10279. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  10280. };
  10281. /*
  10282. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  10283. */
  10284. #define NOT_WITHIN 0 /* Object completely outside of query region */
  10285. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  10286. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  10287. #if 0
  10288. } /* end of the 'extern "C"' block */
  10289. #endif
  10290. #endif /* ifndef _SQLITE3RTREE_H_ */
  10291. /******** End of sqlite3rtree.h *********/
  10292. /******** Begin file sqlite3session.h *********/
  10293. #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
  10294. #define __SQLITESESSION_H_ 1
  10295. /*
  10296. ** Make sure we can call this stuff from C++.
  10297. */
  10298. #if 0
  10299. extern "C" {
  10300. #endif
  10301. /*
  10302. ** CAPI3REF: Session Object Handle
  10303. **
  10304. ** An instance of this object is a [session] that can be used to
  10305. ** record changes to a database.
  10306. */
  10307. typedef struct sqlite3_session sqlite3_session;
  10308. /*
  10309. ** CAPI3REF: Changeset Iterator Handle
  10310. **
  10311. ** An instance of this object acts as a cursor for iterating
  10312. ** over the elements of a [changeset] or [patchset].
  10313. */
  10314. typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
  10315. /*
  10316. ** CAPI3REF: Create A New Session Object
  10317. ** CONSTRUCTOR: sqlite3_session
  10318. **
  10319. ** Create a new session object attached to database handle db. If successful,
  10320. ** a pointer to the new object is written to *ppSession and SQLITE_OK is
  10321. ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
  10322. ** error code (e.g. SQLITE_NOMEM) is returned.
  10323. **
  10324. ** It is possible to create multiple session objects attached to a single
  10325. ** database handle.
  10326. **
  10327. ** Session objects created using this function should be deleted using the
  10328. ** [sqlite3session_delete()] function before the database handle that they
  10329. ** are attached to is itself closed. If the database handle is closed before
  10330. ** the session object is deleted, then the results of calling any session
  10331. ** module function, including [sqlite3session_delete()] on the session object
  10332. ** are undefined.
  10333. **
  10334. ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
  10335. ** is not possible for an application to register a pre-update hook on a
  10336. ** database handle that has one or more session objects attached. Nor is
  10337. ** it possible to create a session object attached to a database handle for
  10338. ** which a pre-update hook is already defined. The results of attempting
  10339. ** either of these things are undefined.
  10340. **
  10341. ** The session object will be used to create changesets for tables in
  10342. ** database zDb, where zDb is either "main", or "temp", or the name of an
  10343. ** attached database. It is not an error if database zDb is not attached
  10344. ** to the database when the session object is created.
  10345. */
  10346. SQLITE_API int sqlite3session_create(
  10347. sqlite3 *db, /* Database handle */
  10348. const char *zDb, /* Name of db (e.g. "main") */
  10349. sqlite3_session **ppSession /* OUT: New session object */
  10350. );
  10351. /*
  10352. ** CAPI3REF: Delete A Session Object
  10353. ** DESTRUCTOR: sqlite3_session
  10354. **
  10355. ** Delete a session object previously allocated using
  10356. ** [sqlite3session_create()]. Once a session object has been deleted, the
  10357. ** results of attempting to use pSession with any other session module
  10358. ** function are undefined.
  10359. **
  10360. ** Session objects must be deleted before the database handle to which they
  10361. ** are attached is closed. Refer to the documentation for
  10362. ** [sqlite3session_create()] for details.
  10363. */
  10364. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
  10365. /*
  10366. ** CAPI3REF: Enable Or Disable A Session Object
  10367. ** METHOD: sqlite3_session
  10368. **
  10369. ** Enable or disable the recording of changes by a session object. When
  10370. ** enabled, a session object records changes made to the database. When
  10371. ** disabled - it does not. A newly created session object is enabled.
  10372. ** Refer to the documentation for [sqlite3session_changeset()] for further
  10373. ** details regarding how enabling and disabling a session object affects
  10374. ** the eventual changesets.
  10375. **
  10376. ** Passing zero to this function disables the session. Passing a value
  10377. ** greater than zero enables it. Passing a value less than zero is a
  10378. ** no-op, and may be used to query the current state of the session.
  10379. **
  10380. ** The return value indicates the final state of the session object: 0 if
  10381. ** the session is disabled, or 1 if it is enabled.
  10382. */
  10383. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
  10384. /*
  10385. ** CAPI3REF: Set Or Clear the Indirect Change Flag
  10386. ** METHOD: sqlite3_session
  10387. **
  10388. ** Each change recorded by a session object is marked as either direct or
  10389. ** indirect. A change is marked as indirect if either:
  10390. **
  10391. ** <ul>
  10392. ** <li> The session object "indirect" flag is set when the change is
  10393. ** made, or
  10394. ** <li> The change is made by an SQL trigger or foreign key action
  10395. ** instead of directly as a result of a users SQL statement.
  10396. ** </ul>
  10397. **
  10398. ** If a single row is affected by more than one operation within a session,
  10399. ** then the change is considered indirect if all operations meet the criteria
  10400. ** for an indirect change above, or direct otherwise.
  10401. **
  10402. ** This function is used to set, clear or query the session object indirect
  10403. ** flag. If the second argument passed to this function is zero, then the
  10404. ** indirect flag is cleared. If it is greater than zero, the indirect flag
  10405. ** is set. Passing a value less than zero does not modify the current value
  10406. ** of the indirect flag, and may be used to query the current state of the
  10407. ** indirect flag for the specified session object.
  10408. **
  10409. ** The return value indicates the final state of the indirect flag: 0 if
  10410. ** it is clear, or 1 if it is set.
  10411. */
  10412. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
  10413. /*
  10414. ** CAPI3REF: Attach A Table To A Session Object
  10415. ** METHOD: sqlite3_session
  10416. **
  10417. ** If argument zTab is not NULL, then it is the name of a table to attach
  10418. ** to the session object passed as the first argument. All subsequent changes
  10419. ** made to the table while the session object is enabled will be recorded. See
  10420. ** documentation for [sqlite3session_changeset()] for further details.
  10421. **
  10422. ** Or, if argument zTab is NULL, then changes are recorded for all tables
  10423. ** in the database. If additional tables are added to the database (by
  10424. ** executing "CREATE TABLE" statements) after this call is made, changes for
  10425. ** the new tables are also recorded.
  10426. **
  10427. ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
  10428. ** defined as part of their CREATE TABLE statement. It does not matter if the
  10429. ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
  10430. ** KEY may consist of a single column, or may be a composite key.
  10431. **
  10432. ** It is not an error if the named table does not exist in the database. Nor
  10433. ** is it an error if the named table does not have a PRIMARY KEY. However,
  10434. ** no changes will be recorded in either of these scenarios.
  10435. **
  10436. ** Changes are not recorded for individual rows that have NULL values stored
  10437. ** in one or more of their PRIMARY KEY columns.
  10438. **
  10439. ** SQLITE_OK is returned if the call completes without error. Or, if an error
  10440. ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  10441. **
  10442. ** <h3>Special sqlite_stat1 Handling</h3>
  10443. **
  10444. ** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
  10445. ** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
  10446. ** <pre>
  10447. ** &nbsp; CREATE TABLE sqlite_stat1(tbl,idx,stat)
  10448. ** </pre>
  10449. **
  10450. ** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
  10451. ** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
  10452. ** are recorded for rows for which (idx IS NULL) is true. However, for such
  10453. ** rows a zero-length blob (SQL value X'') is stored in the changeset or
  10454. ** patchset instead of a NULL value. This allows such changesets to be
  10455. ** manipulated by legacy implementations of sqlite3changeset_invert(),
  10456. ** concat() and similar.
  10457. **
  10458. ** The sqlite3changeset_apply() function automatically converts the
  10459. ** zero-length blob back to a NULL value when updating the sqlite_stat1
  10460. ** table. However, if the application calls sqlite3changeset_new(),
  10461. ** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
  10462. ** iterator directly (including on a changeset iterator passed to a
  10463. ** conflict-handler callback) then the X'' value is returned. The application
  10464. ** must translate X'' to NULL itself if required.
  10465. **
  10466. ** Legacy (older than 3.22.0) versions of the sessions module cannot capture
  10467. ** changes made to the sqlite_stat1 table. Legacy versions of the
  10468. ** sqlite3changeset_apply() function silently ignore any modifications to the
  10469. ** sqlite_stat1 table that are part of a changeset or patchset.
  10470. */
  10471. SQLITE_API int sqlite3session_attach(
  10472. sqlite3_session *pSession, /* Session object */
  10473. const char *zTab /* Table name */
  10474. );
  10475. /*
  10476. ** CAPI3REF: Set a table filter on a Session Object.
  10477. ** METHOD: sqlite3_session
  10478. **
  10479. ** The second argument (xFilter) is the "filter callback". For changes to rows
  10480. ** in tables that are not attached to the Session object, the filter is called
  10481. ** to determine whether changes to the table's rows should be tracked or not.
  10482. ** If xFilter returns 0, changes is not tracked. Note that once a table is
  10483. ** attached, xFilter will not be called again.
  10484. */
  10485. SQLITE_API void sqlite3session_table_filter(
  10486. sqlite3_session *pSession, /* Session object */
  10487. int(*xFilter)(
  10488. void *pCtx, /* Copy of third arg to _filter_table() */
  10489. const char *zTab /* Table name */
  10490. ),
  10491. void *pCtx /* First argument passed to xFilter */
  10492. );
  10493. /*
  10494. ** CAPI3REF: Generate A Changeset From A Session Object
  10495. ** METHOD: sqlite3_session
  10496. **
  10497. ** Obtain a changeset containing changes to the tables attached to the
  10498. ** session object passed as the first argument. If successful,
  10499. ** set *ppChangeset to point to a buffer containing the changeset
  10500. ** and *pnChangeset to the size of the changeset in bytes before returning
  10501. ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
  10502. ** zero and return an SQLite error code.
  10503. **
  10504. ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
  10505. ** each representing a change to a single row of an attached table. An INSERT
  10506. ** change contains the values of each field of a new database row. A DELETE
  10507. ** contains the original values of each field of a deleted database row. An
  10508. ** UPDATE change contains the original values of each field of an updated
  10509. ** database row along with the updated values for each updated non-primary-key
  10510. ** column. It is not possible for an UPDATE change to represent a change that
  10511. ** modifies the values of primary key columns. If such a change is made, it
  10512. ** is represented in a changeset as a DELETE followed by an INSERT.
  10513. **
  10514. ** Changes are not recorded for rows that have NULL values stored in one or
  10515. ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
  10516. ** no corresponding change is present in the changesets returned by this
  10517. ** function. If an existing row with one or more NULL values stored in
  10518. ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
  10519. ** only an INSERT is appears in the changeset. Similarly, if an existing row
  10520. ** with non-NULL PRIMARY KEY values is updated so that one or more of its
  10521. ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
  10522. ** DELETE change only.
  10523. **
  10524. ** The contents of a changeset may be traversed using an iterator created
  10525. ** using the [sqlite3changeset_start()] API. A changeset may be applied to
  10526. ** a database with a compatible schema using the [sqlite3changeset_apply()]
  10527. ** API.
  10528. **
  10529. ** Within a changeset generated by this function, all changes related to a
  10530. ** single table are grouped together. In other words, when iterating through
  10531. ** a changeset or when applying a changeset to a database, all changes related
  10532. ** to a single table are processed before moving on to the next table. Tables
  10533. ** are sorted in the same order in which they were attached (or auto-attached)
  10534. ** to the sqlite3_session object. The order in which the changes related to
  10535. ** a single table are stored is undefined.
  10536. **
  10537. ** Following a successful call to this function, it is the responsibility of
  10538. ** the caller to eventually free the buffer that *ppChangeset points to using
  10539. ** [sqlite3_free()].
  10540. **
  10541. ** <h3>Changeset Generation</h3>
  10542. **
  10543. ** Once a table has been attached to a session object, the session object
  10544. ** records the primary key values of all new rows inserted into the table.
  10545. ** It also records the original primary key and other column values of any
  10546. ** deleted or updated rows. For each unique primary key value, data is only
  10547. ** recorded once - the first time a row with said primary key is inserted,
  10548. ** updated or deleted in the lifetime of the session.
  10549. **
  10550. ** There is one exception to the previous paragraph: when a row is inserted,
  10551. ** updated or deleted, if one or more of its primary key columns contain a
  10552. ** NULL value, no record of the change is made.
  10553. **
  10554. ** The session object therefore accumulates two types of records - those
  10555. ** that consist of primary key values only (created when the user inserts
  10556. ** a new record) and those that consist of the primary key values and the
  10557. ** original values of other table columns (created when the users deletes
  10558. ** or updates a record).
  10559. **
  10560. ** When this function is called, the requested changeset is created using
  10561. ** both the accumulated records and the current contents of the database
  10562. ** file. Specifically:
  10563. **
  10564. ** <ul>
  10565. ** <li> For each record generated by an insert, the database is queried
  10566. ** for a row with a matching primary key. If one is found, an INSERT
  10567. ** change is added to the changeset. If no such row is found, no change
  10568. ** is added to the changeset.
  10569. **
  10570. ** <li> For each record generated by an update or delete, the database is
  10571. ** queried for a row with a matching primary key. If such a row is
  10572. ** found and one or more of the non-primary key fields have been
  10573. ** modified from their original values, an UPDATE change is added to
  10574. ** the changeset. Or, if no such row is found in the table, a DELETE
  10575. ** change is added to the changeset. If there is a row with a matching
  10576. ** primary key in the database, but all fields contain their original
  10577. ** values, no change is added to the changeset.
  10578. ** </ul>
  10579. **
  10580. ** This means, amongst other things, that if a row is inserted and then later
  10581. ** deleted while a session object is active, neither the insert nor the delete
  10582. ** will be present in the changeset. Or if a row is deleted and then later a
  10583. ** row with the same primary key values inserted while a session object is
  10584. ** active, the resulting changeset will contain an UPDATE change instead of
  10585. ** a DELETE and an INSERT.
  10586. **
  10587. ** When a session object is disabled (see the [sqlite3session_enable()] API),
  10588. ** it does not accumulate records when rows are inserted, updated or deleted.
  10589. ** This may appear to have some counter-intuitive effects if a single row
  10590. ** is written to more than once during a session. For example, if a row
  10591. ** is inserted while a session object is enabled, then later deleted while
  10592. ** the same session object is disabled, no INSERT record will appear in the
  10593. ** changeset, even though the delete took place while the session was disabled.
  10594. ** Or, if one field of a row is updated while a session is disabled, and
  10595. ** another field of the same row is updated while the session is enabled, the
  10596. ** resulting changeset will contain an UPDATE change that updates both fields.
  10597. */
  10598. SQLITE_API int sqlite3session_changeset(
  10599. sqlite3_session *pSession, /* Session object */
  10600. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  10601. void **ppChangeset /* OUT: Buffer containing changeset */
  10602. );
  10603. /*
  10604. ** CAPI3REF: Load The Difference Between Tables Into A Session
  10605. ** METHOD: sqlite3_session
  10606. **
  10607. ** If it is not already attached to the session object passed as the first
  10608. ** argument, this function attaches table zTbl in the same manner as the
  10609. ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
  10610. ** does not have a primary key, this function is a no-op (but does not return
  10611. ** an error).
  10612. **
  10613. ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
  10614. ** attached to the same database handle as the session object that contains
  10615. ** a table compatible with the table attached to the session by this function.
  10616. ** A table is considered compatible if it:
  10617. **
  10618. ** <ul>
  10619. ** <li> Has the same name,
  10620. ** <li> Has the same set of columns declared in the same order, and
  10621. ** <li> Has the same PRIMARY KEY definition.
  10622. ** </ul>
  10623. **
  10624. ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
  10625. ** are compatible but do not have any PRIMARY KEY columns, it is not an error
  10626. ** but no changes are added to the session object. As with other session
  10627. ** APIs, tables without PRIMARY KEYs are simply ignored.
  10628. **
  10629. ** This function adds a set of changes to the session object that could be
  10630. ** used to update the table in database zFrom (call this the "from-table")
  10631. ** so that its content is the same as the table attached to the session
  10632. ** object (call this the "to-table"). Specifically:
  10633. **
  10634. ** <ul>
  10635. ** <li> For each row (primary key) that exists in the to-table but not in
  10636. ** the from-table, an INSERT record is added to the session object.
  10637. **
  10638. ** <li> For each row (primary key) that exists in the to-table but not in
  10639. ** the from-table, a DELETE record is added to the session object.
  10640. **
  10641. ** <li> For each row (primary key) that exists in both tables, but features
  10642. ** different non-PK values in each, an UPDATE record is added to the
  10643. ** session.
  10644. ** </ul>
  10645. **
  10646. ** To clarify, if this function is called and then a changeset constructed
  10647. ** using [sqlite3session_changeset()], then after applying that changeset to
  10648. ** database zFrom the contents of the two compatible tables would be
  10649. ** identical.
  10650. **
  10651. ** It an error if database zFrom does not exist or does not contain the
  10652. ** required compatible table.
  10653. **
  10654. ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
  10655. ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
  10656. ** may be set to point to a buffer containing an English language error
  10657. ** message. It is the responsibility of the caller to free this buffer using
  10658. ** sqlite3_free().
  10659. */
  10660. SQLITE_API int sqlite3session_diff(
  10661. sqlite3_session *pSession,
  10662. const char *zFromDb,
  10663. const char *zTbl,
  10664. char **pzErrMsg
  10665. );
  10666. /*
  10667. ** CAPI3REF: Generate A Patchset From A Session Object
  10668. ** METHOD: sqlite3_session
  10669. **
  10670. ** The differences between a patchset and a changeset are that:
  10671. **
  10672. ** <ul>
  10673. ** <li> DELETE records consist of the primary key fields only. The
  10674. ** original values of other fields are omitted.
  10675. ** <li> The original values of any modified fields are omitted from
  10676. ** UPDATE records.
  10677. ** </ul>
  10678. **
  10679. ** A patchset blob may be used with up to date versions of all
  10680. ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
  10681. ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
  10682. ** attempting to use a patchset blob with old versions of the
  10683. ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
  10684. **
  10685. ** Because the non-primary key "old.*" fields are omitted, no
  10686. ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
  10687. ** is passed to the sqlite3changeset_apply() API. Other conflict types work
  10688. ** in the same way as for changesets.
  10689. **
  10690. ** Changes within a patchset are ordered in the same way as for changesets
  10691. ** generated by the sqlite3session_changeset() function (i.e. all changes for
  10692. ** a single table are grouped together, tables appear in the order in which
  10693. ** they were attached to the session object).
  10694. */
  10695. SQLITE_API int sqlite3session_patchset(
  10696. sqlite3_session *pSession, /* Session object */
  10697. int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
  10698. void **ppPatchset /* OUT: Buffer containing patchset */
  10699. );
  10700. /*
  10701. ** CAPI3REF: Test if a changeset has recorded any changes.
  10702. **
  10703. ** Return non-zero if no changes to attached tables have been recorded by
  10704. ** the session object passed as the first argument. Otherwise, if one or
  10705. ** more changes have been recorded, return zero.
  10706. **
  10707. ** Even if this function returns zero, it is possible that calling
  10708. ** [sqlite3session_changeset()] on the session handle may still return a
  10709. ** changeset that contains no changes. This can happen when a row in
  10710. ** an attached table is modified and then later on the original values
  10711. ** are restored. However, if this function returns non-zero, then it is
  10712. ** guaranteed that a call to sqlite3session_changeset() will return a
  10713. ** changeset containing zero changes.
  10714. */
  10715. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
  10716. /*
  10717. ** CAPI3REF: Create An Iterator To Traverse A Changeset
  10718. ** CONSTRUCTOR: sqlite3_changeset_iter
  10719. **
  10720. ** Create an iterator used to iterate through the contents of a changeset.
  10721. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
  10722. ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
  10723. ** SQLite error code is returned.
  10724. **
  10725. ** The following functions can be used to advance and query a changeset
  10726. ** iterator created by this function:
  10727. **
  10728. ** <ul>
  10729. ** <li> [sqlite3changeset_next()]
  10730. ** <li> [sqlite3changeset_op()]
  10731. ** <li> [sqlite3changeset_new()]
  10732. ** <li> [sqlite3changeset_old()]
  10733. ** </ul>
  10734. **
  10735. ** It is the responsibility of the caller to eventually destroy the iterator
  10736. ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
  10737. ** changeset (pChangeset) must remain valid until after the iterator is
  10738. ** destroyed.
  10739. **
  10740. ** Assuming the changeset blob was created by one of the
  10741. ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
  10742. ** [sqlite3changeset_invert()] functions, all changes within the changeset
  10743. ** that apply to a single table are grouped together. This means that when
  10744. ** an application iterates through a changeset using an iterator created by
  10745. ** this function, all changes that relate to a single table are visited
  10746. ** consecutively. There is no chance that the iterator will visit a change
  10747. ** the applies to table X, then one for table Y, and then later on visit
  10748. ** another change for table X.
  10749. **
  10750. ** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
  10751. ** may be modified by passing a combination of
  10752. ** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
  10753. **
  10754. ** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>
  10755. ** and therefore subject to change.
  10756. */
  10757. SQLITE_API int sqlite3changeset_start(
  10758. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  10759. int nChangeset, /* Size of changeset blob in bytes */
  10760. void *pChangeset /* Pointer to blob containing changeset */
  10761. );
  10762. SQLITE_API int sqlite3changeset_start_v2(
  10763. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  10764. int nChangeset, /* Size of changeset blob in bytes */
  10765. void *pChangeset, /* Pointer to blob containing changeset */
  10766. int flags /* SESSION_CHANGESETSTART_* flags */
  10767. );
  10768. /*
  10769. ** CAPI3REF: Flags for sqlite3changeset_start_v2
  10770. **
  10771. ** The following flags may passed via the 4th parameter to
  10772. ** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
  10773. **
  10774. ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
  10775. ** Invert the changeset while iterating through it. This is equivalent to
  10776. ** inverting a changeset using sqlite3changeset_invert() before applying it.
  10777. ** It is an error to specify this flag with a patchset.
  10778. */
  10779. #define SQLITE_CHANGESETSTART_INVERT 0x0002
  10780. /*
  10781. ** CAPI3REF: Advance A Changeset Iterator
  10782. ** METHOD: sqlite3_changeset_iter
  10783. **
  10784. ** This function may only be used with iterators created by function
  10785. ** [sqlite3changeset_start()]. If it is called on an iterator passed to
  10786. ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
  10787. ** is returned and the call has no effect.
  10788. **
  10789. ** Immediately after an iterator is created by sqlite3changeset_start(), it
  10790. ** does not point to any change in the changeset. Assuming the changeset
  10791. ** is not empty, the first call to this function advances the iterator to
  10792. ** point to the first change in the changeset. Each subsequent call advances
  10793. ** the iterator to point to the next change in the changeset (if any). If
  10794. ** no error occurs and the iterator points to a valid change after a call
  10795. ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
  10796. ** Otherwise, if all changes in the changeset have already been visited,
  10797. ** SQLITE_DONE is returned.
  10798. **
  10799. ** If an error occurs, an SQLite error code is returned. Possible error
  10800. ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
  10801. ** SQLITE_NOMEM.
  10802. */
  10803. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
  10804. /*
  10805. ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
  10806. ** METHOD: sqlite3_changeset_iter
  10807. **
  10808. ** The pIter argument passed to this function may either be an iterator
  10809. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10810. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10811. ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
  10812. ** is not the case, this function returns [SQLITE_MISUSE].
  10813. **
  10814. ** If argument pzTab is not NULL, then *pzTab is set to point to a
  10815. ** nul-terminated utf-8 encoded string containing the name of the table
  10816. ** affected by the current change. The buffer remains valid until either
  10817. ** sqlite3changeset_next() is called on the iterator or until the
  10818. ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
  10819. ** set to the number of columns in the table affected by the change. If
  10820. ** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
  10821. ** is an indirect change, or false (0) otherwise. See the documentation for
  10822. ** [sqlite3session_indirect()] for a description of direct and indirect
  10823. ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
  10824. ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
  10825. ** type of change that the iterator currently points to.
  10826. **
  10827. ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
  10828. ** SQLite error code is returned. The values of the output variables may not
  10829. ** be trusted in this case.
  10830. */
  10831. SQLITE_API int sqlite3changeset_op(
  10832. sqlite3_changeset_iter *pIter, /* Iterator object */
  10833. const char **pzTab, /* OUT: Pointer to table name */
  10834. int *pnCol, /* OUT: Number of columns in table */
  10835. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  10836. int *pbIndirect /* OUT: True for an 'indirect' change */
  10837. );
  10838. /*
  10839. ** CAPI3REF: Obtain The Primary Key Definition Of A Table
  10840. ** METHOD: sqlite3_changeset_iter
  10841. **
  10842. ** For each modified table, a changeset includes the following:
  10843. **
  10844. ** <ul>
  10845. ** <li> The number of columns in the table, and
  10846. ** <li> Which of those columns make up the tables PRIMARY KEY.
  10847. ** </ul>
  10848. **
  10849. ** This function is used to find which columns comprise the PRIMARY KEY of
  10850. ** the table modified by the change that iterator pIter currently points to.
  10851. ** If successful, *pabPK is set to point to an array of nCol entries, where
  10852. ** nCol is the number of columns in the table. Elements of *pabPK are set to
  10853. ** 0x01 if the corresponding column is part of the tables primary key, or
  10854. ** 0x00 if it is not.
  10855. **
  10856. ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
  10857. ** in the table.
  10858. **
  10859. ** If this function is called when the iterator does not point to a valid
  10860. ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
  10861. ** SQLITE_OK is returned and the output variables populated as described
  10862. ** above.
  10863. */
  10864. SQLITE_API int sqlite3changeset_pk(
  10865. sqlite3_changeset_iter *pIter, /* Iterator object */
  10866. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  10867. int *pnCol /* OUT: Number of entries in output array */
  10868. );
  10869. /*
  10870. ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
  10871. ** METHOD: sqlite3_changeset_iter
  10872. **
  10873. ** The pIter argument passed to this function may either be an iterator
  10874. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10875. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10876. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10877. ** Furthermore, it may only be called if the type of change that the iterator
  10878. ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
  10879. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10880. **
  10881. ** Argument iVal must be greater than or equal to 0, and less than the number
  10882. ** of columns in the table affected by the current change. Otherwise,
  10883. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10884. **
  10885. ** If successful, this function sets *ppValue to point to a protected
  10886. ** sqlite3_value object containing the iVal'th value from the vector of
  10887. ** original row values stored as part of the UPDATE or DELETE change and
  10888. ** returns SQLITE_OK. The name of the function comes from the fact that this
  10889. ** is similar to the "old.*" columns available to update or delete triggers.
  10890. **
  10891. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10892. ** is returned and *ppValue is set to NULL.
  10893. */
  10894. SQLITE_API int sqlite3changeset_old(
  10895. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10896. int iVal, /* Column number */
  10897. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  10898. );
  10899. /*
  10900. ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
  10901. ** METHOD: sqlite3_changeset_iter
  10902. **
  10903. ** The pIter argument passed to this function may either be an iterator
  10904. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10905. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10906. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10907. ** Furthermore, it may only be called if the type of change that the iterator
  10908. ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
  10909. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10910. **
  10911. ** Argument iVal must be greater than or equal to 0, and less than the number
  10912. ** of columns in the table affected by the current change. Otherwise,
  10913. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10914. **
  10915. ** If successful, this function sets *ppValue to point to a protected
  10916. ** sqlite3_value object containing the iVal'th value from the vector of
  10917. ** new row values stored as part of the UPDATE or INSERT change and
  10918. ** returns SQLITE_OK. If the change is an UPDATE and does not include
  10919. ** a new value for the requested column, *ppValue is set to NULL and
  10920. ** SQLITE_OK returned. The name of the function comes from the fact that
  10921. ** this is similar to the "new.*" columns available to update or delete
  10922. ** triggers.
  10923. **
  10924. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10925. ** is returned and *ppValue is set to NULL.
  10926. */
  10927. SQLITE_API int sqlite3changeset_new(
  10928. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10929. int iVal, /* Column number */
  10930. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  10931. );
  10932. /*
  10933. ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
  10934. ** METHOD: sqlite3_changeset_iter
  10935. **
  10936. ** This function should only be used with iterator objects passed to a
  10937. ** conflict-handler callback by [sqlite3changeset_apply()] with either
  10938. ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
  10939. ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
  10940. ** is set to NULL.
  10941. **
  10942. ** Argument iVal must be greater than or equal to 0, and less than the number
  10943. ** of columns in the table affected by the current change. Otherwise,
  10944. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10945. **
  10946. ** If successful, this function sets *ppValue to point to a protected
  10947. ** sqlite3_value object containing the iVal'th value from the
  10948. ** "conflicting row" associated with the current conflict-handler callback
  10949. ** and returns SQLITE_OK.
  10950. **
  10951. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10952. ** is returned and *ppValue is set to NULL.
  10953. */
  10954. SQLITE_API int sqlite3changeset_conflict(
  10955. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10956. int iVal, /* Column number */
  10957. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  10958. );
  10959. /*
  10960. ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
  10961. ** METHOD: sqlite3_changeset_iter
  10962. **
  10963. ** This function may only be called with an iterator passed to an
  10964. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  10965. ** it sets the output variable to the total number of known foreign key
  10966. ** violations in the destination database and returns SQLITE_OK.
  10967. **
  10968. ** In all other cases this function returns SQLITE_MISUSE.
  10969. */
  10970. SQLITE_API int sqlite3changeset_fk_conflicts(
  10971. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10972. int *pnOut /* OUT: Number of FK violations */
  10973. );
  10974. /*
  10975. ** CAPI3REF: Finalize A Changeset Iterator
  10976. ** METHOD: sqlite3_changeset_iter
  10977. **
  10978. ** This function is used to finalize an iterator allocated with
  10979. ** [sqlite3changeset_start()].
  10980. **
  10981. ** This function should only be called on iterators created using the
  10982. ** [sqlite3changeset_start()] function. If an application calls this
  10983. ** function with an iterator passed to a conflict-handler by
  10984. ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
  10985. ** call has no effect.
  10986. **
  10987. ** If an error was encountered within a call to an sqlite3changeset_xxx()
  10988. ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
  10989. ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
  10990. ** to that error is returned by this function. Otherwise, SQLITE_OK is
  10991. ** returned. This is to allow the following pattern (pseudo-code):
  10992. **
  10993. ** <pre>
  10994. ** sqlite3changeset_start();
  10995. ** while( SQLITE_ROW==sqlite3changeset_next() ){
  10996. ** // Do something with change.
  10997. ** }
  10998. ** rc = sqlite3changeset_finalize();
  10999. ** if( rc!=SQLITE_OK ){
  11000. ** // An error has occurred
  11001. ** }
  11002. ** </pre>
  11003. */
  11004. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
  11005. /*
  11006. ** CAPI3REF: Invert A Changeset
  11007. **
  11008. ** This function is used to "invert" a changeset object. Applying an inverted
  11009. ** changeset to a database reverses the effects of applying the uninverted
  11010. ** changeset. Specifically:
  11011. **
  11012. ** <ul>
  11013. ** <li> Each DELETE change is changed to an INSERT, and
  11014. ** <li> Each INSERT change is changed to a DELETE, and
  11015. ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
  11016. ** </ul>
  11017. **
  11018. ** This function does not change the order in which changes appear within
  11019. ** the changeset. It merely reverses the sense of each individual change.
  11020. **
  11021. ** If successful, a pointer to a buffer containing the inverted changeset
  11022. ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
  11023. ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
  11024. ** zeroed and an SQLite error code returned.
  11025. **
  11026. ** It is the responsibility of the caller to eventually call sqlite3_free()
  11027. ** on the *ppOut pointer to free the buffer allocation following a successful
  11028. ** call to this function.
  11029. **
  11030. ** WARNING/TODO: This function currently assumes that the input is a valid
  11031. ** changeset. If it is not, the results are undefined.
  11032. */
  11033. SQLITE_API int sqlite3changeset_invert(
  11034. int nIn, const void *pIn, /* Input changeset */
  11035. int *pnOut, void **ppOut /* OUT: Inverse of input */
  11036. );
  11037. /*
  11038. ** CAPI3REF: Concatenate Two Changeset Objects
  11039. **
  11040. ** This function is used to concatenate two changesets, A and B, into a
  11041. ** single changeset. The result is a changeset equivalent to applying
  11042. ** changeset A followed by changeset B.
  11043. **
  11044. ** This function combines the two input changesets using an
  11045. ** sqlite3_changegroup object. Calling it produces similar results as the
  11046. ** following code fragment:
  11047. **
  11048. ** <pre>
  11049. ** sqlite3_changegroup *pGrp;
  11050. ** rc = sqlite3_changegroup_new(&pGrp);
  11051. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
  11052. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
  11053. ** if( rc==SQLITE_OK ){
  11054. ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  11055. ** }else{
  11056. ** *ppOut = 0;
  11057. ** *pnOut = 0;
  11058. ** }
  11059. ** </pre>
  11060. **
  11061. ** Refer to the sqlite3_changegroup documentation below for details.
  11062. */
  11063. SQLITE_API int sqlite3changeset_concat(
  11064. int nA, /* Number of bytes in buffer pA */
  11065. void *pA, /* Pointer to buffer containing changeset A */
  11066. int nB, /* Number of bytes in buffer pB */
  11067. void *pB, /* Pointer to buffer containing changeset B */
  11068. int *pnOut, /* OUT: Number of bytes in output changeset */
  11069. void **ppOut /* OUT: Buffer containing output changeset */
  11070. );
  11071. /*
  11072. ** CAPI3REF: Changegroup Handle
  11073. **
  11074. ** A changegroup is an object used to combine two or more
  11075. ** [changesets] or [patchsets]
  11076. */
  11077. typedef struct sqlite3_changegroup sqlite3_changegroup;
  11078. /*
  11079. ** CAPI3REF: Create A New Changegroup Object
  11080. ** CONSTRUCTOR: sqlite3_changegroup
  11081. **
  11082. ** An sqlite3_changegroup object is used to combine two or more changesets
  11083. ** (or patchsets) into a single changeset (or patchset). A single changegroup
  11084. ** object may combine changesets or patchsets, but not both. The output is
  11085. ** always in the same format as the input.
  11086. **
  11087. ** If successful, this function returns SQLITE_OK and populates (*pp) with
  11088. ** a pointer to a new sqlite3_changegroup object before returning. The caller
  11089. ** should eventually free the returned object using a call to
  11090. ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
  11091. ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
  11092. **
  11093. ** The usual usage pattern for an sqlite3_changegroup object is as follows:
  11094. **
  11095. ** <ul>
  11096. ** <li> It is created using a call to sqlite3changegroup_new().
  11097. **
  11098. ** <li> Zero or more changesets (or patchsets) are added to the object
  11099. ** by calling sqlite3changegroup_add().
  11100. **
  11101. ** <li> The result of combining all input changesets together is obtained
  11102. ** by the application via a call to sqlite3changegroup_output().
  11103. **
  11104. ** <li> The object is deleted using a call to sqlite3changegroup_delete().
  11105. ** </ul>
  11106. **
  11107. ** Any number of calls to add() and output() may be made between the calls to
  11108. ** new() and delete(), and in any order.
  11109. **
  11110. ** As well as the regular sqlite3changegroup_add() and
  11111. ** sqlite3changegroup_output() functions, also available are the streaming
  11112. ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
  11113. */
  11114. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
  11115. /*
  11116. ** CAPI3REF: Add A Changeset To A Changegroup
  11117. ** METHOD: sqlite3_changegroup
  11118. **
  11119. ** Add all changes within the changeset (or patchset) in buffer pData (size
  11120. ** nData bytes) to the changegroup.
  11121. **
  11122. ** If the buffer contains a patchset, then all prior calls to this function
  11123. ** on the same changegroup object must also have specified patchsets. Or, if
  11124. ** the buffer contains a changeset, so must have the earlier calls to this
  11125. ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
  11126. ** to the changegroup.
  11127. **
  11128. ** Rows within the changeset and changegroup are identified by the values in
  11129. ** their PRIMARY KEY columns. A change in the changeset is considered to
  11130. ** apply to the same row as a change already present in the changegroup if
  11131. ** the two rows have the same primary key.
  11132. **
  11133. ** Changes to rows that do not already appear in the changegroup are
  11134. ** simply copied into it. Or, if both the new changeset and the changegroup
  11135. ** contain changes that apply to a single row, the final contents of the
  11136. ** changegroup depends on the type of each change, as follows:
  11137. **
  11138. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  11139. ** <tr><th style="white-space:pre">Existing Change </th>
  11140. ** <th style="white-space:pre">New Change </th>
  11141. ** <th>Output Change
  11142. ** <tr><td>INSERT <td>INSERT <td>
  11143. ** The new change is ignored. This case does not occur if the new
  11144. ** changeset was recorded immediately after the changesets already
  11145. ** added to the changegroup.
  11146. ** <tr><td>INSERT <td>UPDATE <td>
  11147. ** The INSERT change remains in the changegroup. The values in the
  11148. ** INSERT change are modified as if the row was inserted by the
  11149. ** existing change and then updated according to the new change.
  11150. ** <tr><td>INSERT <td>DELETE <td>
  11151. ** The existing INSERT is removed from the changegroup. The DELETE is
  11152. ** not added.
  11153. ** <tr><td>UPDATE <td>INSERT <td>
  11154. ** The new change is ignored. This case does not occur if the new
  11155. ** changeset was recorded immediately after the changesets already
  11156. ** added to the changegroup.
  11157. ** <tr><td>UPDATE <td>UPDATE <td>
  11158. ** The existing UPDATE remains within the changegroup. It is amended
  11159. ** so that the accompanying values are as if the row was updated once
  11160. ** by the existing change and then again by the new change.
  11161. ** <tr><td>UPDATE <td>DELETE <td>
  11162. ** The existing UPDATE is replaced by the new DELETE within the
  11163. ** changegroup.
  11164. ** <tr><td>DELETE <td>INSERT <td>
  11165. ** If one or more of the column values in the row inserted by the
  11166. ** new change differ from those in the row deleted by the existing
  11167. ** change, the existing DELETE is replaced by an UPDATE within the
  11168. ** changegroup. Otherwise, if the inserted row is exactly the same
  11169. ** as the deleted row, the existing DELETE is simply discarded.
  11170. ** <tr><td>DELETE <td>UPDATE <td>
  11171. ** The new change is ignored. This case does not occur if the new
  11172. ** changeset was recorded immediately after the changesets already
  11173. ** added to the changegroup.
  11174. ** <tr><td>DELETE <td>DELETE <td>
  11175. ** The new change is ignored. This case does not occur if the new
  11176. ** changeset was recorded immediately after the changesets already
  11177. ** added to the changegroup.
  11178. ** </table>
  11179. **
  11180. ** If the new changeset contains changes to a table that is already present
  11181. ** in the changegroup, then the number of columns and the position of the
  11182. ** primary key columns for the table must be consistent. If this is not the
  11183. ** case, this function fails with SQLITE_SCHEMA. If the input changeset
  11184. ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
  11185. ** returned. Or, if an out-of-memory condition occurs during processing, this
  11186. ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
  11187. ** final contents of the changegroup is undefined.
  11188. **
  11189. ** If no error occurs, SQLITE_OK is returned.
  11190. */
  11191. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
  11192. /*
  11193. ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
  11194. ** METHOD: sqlite3_changegroup
  11195. **
  11196. ** Obtain a buffer containing a changeset (or patchset) representing the
  11197. ** current contents of the changegroup. If the inputs to the changegroup
  11198. ** were themselves changesets, the output is a changeset. Or, if the
  11199. ** inputs were patchsets, the output is also a patchset.
  11200. **
  11201. ** As with the output of the sqlite3session_changeset() and
  11202. ** sqlite3session_patchset() functions, all changes related to a single
  11203. ** table are grouped together in the output of this function. Tables appear
  11204. ** in the same order as for the very first changeset added to the changegroup.
  11205. ** If the second or subsequent changesets added to the changegroup contain
  11206. ** changes for tables that do not appear in the first changeset, they are
  11207. ** appended onto the end of the output changeset, again in the order in
  11208. ** which they are first encountered.
  11209. **
  11210. ** If an error occurs, an SQLite error code is returned and the output
  11211. ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
  11212. ** is returned and the output variables are set to the size of and a
  11213. ** pointer to the output buffer, respectively. In this case it is the
  11214. ** responsibility of the caller to eventually free the buffer using a
  11215. ** call to sqlite3_free().
  11216. */
  11217. SQLITE_API int sqlite3changegroup_output(
  11218. sqlite3_changegroup*,
  11219. int *pnData, /* OUT: Size of output buffer in bytes */
  11220. void **ppData /* OUT: Pointer to output buffer */
  11221. );
  11222. /*
  11223. ** CAPI3REF: Delete A Changegroup Object
  11224. ** DESTRUCTOR: sqlite3_changegroup
  11225. */
  11226. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
  11227. /*
  11228. ** CAPI3REF: Apply A Changeset To A Database
  11229. **
  11230. ** Apply a changeset or patchset to a database. These functions attempt to
  11231. ** update the "main" database attached to handle db with the changes found in
  11232. ** the changeset passed via the second and third arguments.
  11233. **
  11234. ** The fourth argument (xFilter) passed to these functions is the "filter
  11235. ** callback". If it is not NULL, then for each table affected by at least one
  11236. ** change in the changeset, the filter callback is invoked with
  11237. ** the table name as the second argument, and a copy of the context pointer
  11238. ** passed as the sixth argument as the first. If the "filter callback"
  11239. ** returns zero, then no attempt is made to apply any changes to the table.
  11240. ** Otherwise, if the return value is non-zero or the xFilter argument to
  11241. ** is NULL, all changes related to the table are attempted.
  11242. **
  11243. ** For each table that is not excluded by the filter callback, this function
  11244. ** tests that the target database contains a compatible table. A table is
  11245. ** considered compatible if all of the following are true:
  11246. **
  11247. ** <ul>
  11248. ** <li> The table has the same name as the name recorded in the
  11249. ** changeset, and
  11250. ** <li> The table has at least as many columns as recorded in the
  11251. ** changeset, and
  11252. ** <li> The table has primary key columns in the same position as
  11253. ** recorded in the changeset.
  11254. ** </ul>
  11255. **
  11256. ** If there is no compatible table, it is not an error, but none of the
  11257. ** changes associated with the table are applied. A warning message is issued
  11258. ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
  11259. ** one such warning is issued for each table in the changeset.
  11260. **
  11261. ** For each change for which there is a compatible table, an attempt is made
  11262. ** to modify the table contents according to the UPDATE, INSERT or DELETE
  11263. ** change. If a change cannot be applied cleanly, the conflict handler
  11264. ** function passed as the fifth argument to sqlite3changeset_apply() may be
  11265. ** invoked. A description of exactly when the conflict handler is invoked for
  11266. ** each type of change is below.
  11267. **
  11268. ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
  11269. ** of passing anything other than a valid function pointer as the xConflict
  11270. ** argument are undefined.
  11271. **
  11272. ** Each time the conflict handler function is invoked, it must return one
  11273. ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
  11274. ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
  11275. ** if the second argument passed to the conflict handler is either
  11276. ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
  11277. ** returns an illegal value, any changes already made are rolled back and
  11278. ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
  11279. ** actions are taken by sqlite3changeset_apply() depending on the value
  11280. ** returned by each invocation of the conflict-handler function. Refer to
  11281. ** the documentation for the three
  11282. ** [SQLITE_CHANGESET_OMIT|available return values] for details.
  11283. **
  11284. ** <dl>
  11285. ** <dt>DELETE Changes<dd>
  11286. ** For each DELETE change, the function checks if the target database
  11287. ** contains a row with the same primary key value (or values) as the
  11288. ** original row values stored in the changeset. If it does, and the values
  11289. ** stored in all non-primary key columns also match the values stored in
  11290. ** the changeset the row is deleted from the target database.
  11291. **
  11292. ** If a row with matching primary key values is found, but one or more of
  11293. ** the non-primary key fields contains a value different from the original
  11294. ** row value stored in the changeset, the conflict-handler function is
  11295. ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
  11296. ** database table has more columns than are recorded in the changeset,
  11297. ** only the values of those non-primary key fields are compared against
  11298. ** the current database contents - any trailing database table columns
  11299. ** are ignored.
  11300. **
  11301. ** If no row with matching primary key values is found in the database,
  11302. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  11303. ** passed as the second argument.
  11304. **
  11305. ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
  11306. ** (which can only happen if a foreign key constraint is violated), the
  11307. ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
  11308. ** passed as the second argument. This includes the case where the DELETE
  11309. ** operation is attempted because an earlier call to the conflict handler
  11310. ** function returned [SQLITE_CHANGESET_REPLACE].
  11311. **
  11312. ** <dt>INSERT Changes<dd>
  11313. ** For each INSERT change, an attempt is made to insert the new row into
  11314. ** the database. If the changeset row contains fewer fields than the
  11315. ** database table, the trailing fields are populated with their default
  11316. ** values.
  11317. **
  11318. ** If the attempt to insert the row fails because the database already
  11319. ** contains a row with the same primary key values, the conflict handler
  11320. ** function is invoked with the second argument set to
  11321. ** [SQLITE_CHANGESET_CONFLICT].
  11322. **
  11323. ** If the attempt to insert the row fails because of some other constraint
  11324. ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
  11325. ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
  11326. ** This includes the case where the INSERT operation is re-attempted because
  11327. ** an earlier call to the conflict handler function returned
  11328. ** [SQLITE_CHANGESET_REPLACE].
  11329. **
  11330. ** <dt>UPDATE Changes<dd>
  11331. ** For each UPDATE change, the function checks if the target database
  11332. ** contains a row with the same primary key value (or values) as the
  11333. ** original row values stored in the changeset. If it does, and the values
  11334. ** stored in all modified non-primary key columns also match the values
  11335. ** stored in the changeset the row is updated within the target database.
  11336. **
  11337. ** If a row with matching primary key values is found, but one or more of
  11338. ** the modified non-primary key fields contains a value different from an
  11339. ** original row value stored in the changeset, the conflict-handler function
  11340. ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
  11341. ** UPDATE changes only contain values for non-primary key fields that are
  11342. ** to be modified, only those fields need to match the original values to
  11343. ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
  11344. **
  11345. ** If no row with matching primary key values is found in the database,
  11346. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  11347. ** passed as the second argument.
  11348. **
  11349. ** If the UPDATE operation is attempted, but SQLite returns
  11350. ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
  11351. ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
  11352. ** This includes the case where the UPDATE operation is attempted after
  11353. ** an earlier call to the conflict handler function returned
  11354. ** [SQLITE_CHANGESET_REPLACE].
  11355. ** </dl>
  11356. **
  11357. ** It is safe to execute SQL statements, including those that write to the
  11358. ** table that the callback related to, from within the xConflict callback.
  11359. ** This can be used to further customize the applications conflict
  11360. ** resolution strategy.
  11361. **
  11362. ** All changes made by these functions are enclosed in a savepoint transaction.
  11363. ** If any other error (aside from a constraint failure when attempting to
  11364. ** write to the target database) occurs, then the savepoint transaction is
  11365. ** rolled back, restoring the target database to its original state, and an
  11366. ** SQLite error code returned.
  11367. **
  11368. ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
  11369. ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
  11370. ** may set (*ppRebase) to point to a "rebase" that may be used with the
  11371. ** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
  11372. ** is set to the size of the buffer in bytes. It is the responsibility of the
  11373. ** caller to eventually free any such buffer using sqlite3_free(). The buffer
  11374. ** is only allocated and populated if one or more conflicts were encountered
  11375. ** while applying the patchset. See comments surrounding the sqlite3_rebaser
  11376. ** APIs for further details.
  11377. **
  11378. ** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
  11379. ** may be modified by passing a combination of
  11380. ** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
  11381. **
  11382. ** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
  11383. ** and therefore subject to change.
  11384. */
  11385. SQLITE_API int sqlite3changeset_apply(
  11386. sqlite3 *db, /* Apply change to "main" db of this handle */
  11387. int nChangeset, /* Size of changeset in bytes */
  11388. void *pChangeset, /* Changeset blob */
  11389. int(*xFilter)(
  11390. void *pCtx, /* Copy of sixth arg to _apply() */
  11391. const char *zTab /* Table name */
  11392. ),
  11393. int(*xConflict)(
  11394. void *pCtx, /* Copy of sixth arg to _apply() */
  11395. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11396. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11397. ),
  11398. void *pCtx /* First argument passed to xConflict */
  11399. );
  11400. SQLITE_API int sqlite3changeset_apply_v2(
  11401. sqlite3 *db, /* Apply change to "main" db of this handle */
  11402. int nChangeset, /* Size of changeset in bytes */
  11403. void *pChangeset, /* Changeset blob */
  11404. int(*xFilter)(
  11405. void *pCtx, /* Copy of sixth arg to _apply() */
  11406. const char *zTab /* Table name */
  11407. ),
  11408. int(*xConflict)(
  11409. void *pCtx, /* Copy of sixth arg to _apply() */
  11410. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11411. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11412. ),
  11413. void *pCtx, /* First argument passed to xConflict */
  11414. void **ppRebase, int *pnRebase, /* OUT: Rebase data */
  11415. int flags /* SESSION_CHANGESETAPPLY_* flags */
  11416. );
  11417. /*
  11418. ** CAPI3REF: Flags for sqlite3changeset_apply_v2
  11419. **
  11420. ** The following flags may passed via the 9th parameter to
  11421. ** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
  11422. **
  11423. ** <dl>
  11424. ** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
  11425. ** Usually, the sessions module encloses all operations performed by
  11426. ** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
  11427. ** SAVEPOINT is committed if the changeset or patchset is successfully
  11428. ** applied, or rolled back if an error occurs. Specifying this flag
  11429. ** causes the sessions module to omit this savepoint. In this case, if the
  11430. ** caller has an open transaction or savepoint when apply_v2() is called,
  11431. ** it may revert the partially applied changeset by rolling it back.
  11432. **
  11433. ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
  11434. ** Invert the changeset before applying it. This is equivalent to inverting
  11435. ** a changeset using sqlite3changeset_invert() before applying it. It is
  11436. ** an error to specify this flag with a patchset.
  11437. */
  11438. #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001
  11439. #define SQLITE_CHANGESETAPPLY_INVERT 0x0002
  11440. /*
  11441. ** CAPI3REF: Constants Passed To The Conflict Handler
  11442. **
  11443. ** Values that may be passed as the second argument to a conflict-handler.
  11444. **
  11445. ** <dl>
  11446. ** <dt>SQLITE_CHANGESET_DATA<dd>
  11447. ** The conflict handler is invoked with CHANGESET_DATA as the second argument
  11448. ** when processing a DELETE or UPDATE change if a row with the required
  11449. ** PRIMARY KEY fields is present in the database, but one or more other
  11450. ** (non primary-key) fields modified by the update do not contain the
  11451. ** expected "before" values.
  11452. **
  11453. ** The conflicting row, in this case, is the database row with the matching
  11454. ** primary key.
  11455. **
  11456. ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
  11457. ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
  11458. ** argument when processing a DELETE or UPDATE change if a row with the
  11459. ** required PRIMARY KEY fields is not present in the database.
  11460. **
  11461. ** There is no conflicting row in this case. The results of invoking the
  11462. ** sqlite3changeset_conflict() API are undefined.
  11463. **
  11464. ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
  11465. ** CHANGESET_CONFLICT is passed as the second argument to the conflict
  11466. ** handler while processing an INSERT change if the operation would result
  11467. ** in duplicate primary key values.
  11468. **
  11469. ** The conflicting row in this case is the database row with the matching
  11470. ** primary key.
  11471. **
  11472. ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
  11473. ** If foreign key handling is enabled, and applying a changeset leaves the
  11474. ** database in a state containing foreign key violations, the conflict
  11475. ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
  11476. ** exactly once before the changeset is committed. If the conflict handler
  11477. ** returns CHANGESET_OMIT, the changes, including those that caused the
  11478. ** foreign key constraint violation, are committed. Or, if it returns
  11479. ** CHANGESET_ABORT, the changeset is rolled back.
  11480. **
  11481. ** No current or conflicting row information is provided. The only function
  11482. ** it is possible to call on the supplied sqlite3_changeset_iter handle
  11483. ** is sqlite3changeset_fk_conflicts().
  11484. **
  11485. ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
  11486. ** If any other constraint violation occurs while applying a change (i.e.
  11487. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
  11488. ** invoked with CHANGESET_CONSTRAINT as the second argument.
  11489. **
  11490. ** There is no conflicting row in this case. The results of invoking the
  11491. ** sqlite3changeset_conflict() API are undefined.
  11492. **
  11493. ** </dl>
  11494. */
  11495. #define SQLITE_CHANGESET_DATA 1
  11496. #define SQLITE_CHANGESET_NOTFOUND 2
  11497. #define SQLITE_CHANGESET_CONFLICT 3
  11498. #define SQLITE_CHANGESET_CONSTRAINT 4
  11499. #define SQLITE_CHANGESET_FOREIGN_KEY 5
  11500. /*
  11501. ** CAPI3REF: Constants Returned By The Conflict Handler
  11502. **
  11503. ** A conflict handler callback must return one of the following three values.
  11504. **
  11505. ** <dl>
  11506. ** <dt>SQLITE_CHANGESET_OMIT<dd>
  11507. ** If a conflict handler returns this value no special action is taken. The
  11508. ** change that caused the conflict is not applied. The session module
  11509. ** continues to the next change in the changeset.
  11510. **
  11511. ** <dt>SQLITE_CHANGESET_REPLACE<dd>
  11512. ** This value may only be returned if the second argument to the conflict
  11513. ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
  11514. ** is not the case, any changes applied so far are rolled back and the
  11515. ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
  11516. **
  11517. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
  11518. ** handler, then the conflicting row is either updated or deleted, depending
  11519. ** on the type of change.
  11520. **
  11521. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
  11522. ** handler, then the conflicting row is removed from the database and a
  11523. ** second attempt to apply the change is made. If this second attempt fails,
  11524. ** the original row is restored to the database before continuing.
  11525. **
  11526. ** <dt>SQLITE_CHANGESET_ABORT<dd>
  11527. ** If this value is returned, any changes applied so far are rolled back
  11528. ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
  11529. ** </dl>
  11530. */
  11531. #define SQLITE_CHANGESET_OMIT 0
  11532. #define SQLITE_CHANGESET_REPLACE 1
  11533. #define SQLITE_CHANGESET_ABORT 2
  11534. /*
  11535. ** CAPI3REF: Rebasing changesets
  11536. ** EXPERIMENTAL
  11537. **
  11538. ** Suppose there is a site hosting a database in state S0. And that
  11539. ** modifications are made that move that database to state S1 and a
  11540. ** changeset recorded (the "local" changeset). Then, a changeset based
  11541. ** on S0 is received from another site (the "remote" changeset) and
  11542. ** applied to the database. The database is then in state
  11543. ** (S1+"remote"), where the exact state depends on any conflict
  11544. ** resolution decisions (OMIT or REPLACE) made while applying "remote".
  11545. ** Rebasing a changeset is to update it to take those conflict
  11546. ** resolution decisions into account, so that the same conflicts
  11547. ** do not have to be resolved elsewhere in the network.
  11548. **
  11549. ** For example, if both the local and remote changesets contain an
  11550. ** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
  11551. **
  11552. ** local: INSERT INTO t1 VALUES(1, 'v1');
  11553. ** remote: INSERT INTO t1 VALUES(1, 'v2');
  11554. **
  11555. ** and the conflict resolution is REPLACE, then the INSERT change is
  11556. ** removed from the local changeset (it was overridden). Or, if the
  11557. ** conflict resolution was "OMIT", then the local changeset is modified
  11558. ** to instead contain:
  11559. **
  11560. ** UPDATE t1 SET b = 'v2' WHERE a=1;
  11561. **
  11562. ** Changes within the local changeset are rebased as follows:
  11563. **
  11564. ** <dl>
  11565. ** <dt>Local INSERT<dd>
  11566. ** This may only conflict with a remote INSERT. If the conflict
  11567. ** resolution was OMIT, then add an UPDATE change to the rebased
  11568. ** changeset. Or, if the conflict resolution was REPLACE, add
  11569. ** nothing to the rebased changeset.
  11570. **
  11571. ** <dt>Local DELETE<dd>
  11572. ** This may conflict with a remote UPDATE or DELETE. In both cases the
  11573. ** only possible resolution is OMIT. If the remote operation was a
  11574. ** DELETE, then add no change to the rebased changeset. If the remote
  11575. ** operation was an UPDATE, then the old.* fields of change are updated
  11576. ** to reflect the new.* values in the UPDATE.
  11577. **
  11578. ** <dt>Local UPDATE<dd>
  11579. ** This may conflict with a remote UPDATE or DELETE. If it conflicts
  11580. ** with a DELETE, and the conflict resolution was OMIT, then the update
  11581. ** is changed into an INSERT. Any undefined values in the new.* record
  11582. ** from the update change are filled in using the old.* values from
  11583. ** the conflicting DELETE. Or, if the conflict resolution was REPLACE,
  11584. ** the UPDATE change is simply omitted from the rebased changeset.
  11585. **
  11586. ** If conflict is with a remote UPDATE and the resolution is OMIT, then
  11587. ** the old.* values are rebased using the new.* values in the remote
  11588. ** change. Or, if the resolution is REPLACE, then the change is copied
  11589. ** into the rebased changeset with updates to columns also updated by
  11590. ** the conflicting remote UPDATE removed. If this means no columns would
  11591. ** be updated, the change is omitted.
  11592. ** </dl>
  11593. **
  11594. ** A local change may be rebased against multiple remote changes
  11595. ** simultaneously. If a single key is modified by multiple remote
  11596. ** changesets, they are combined as follows before the local changeset
  11597. ** is rebased:
  11598. **
  11599. ** <ul>
  11600. ** <li> If there has been one or more REPLACE resolutions on a
  11601. ** key, it is rebased according to a REPLACE.
  11602. **
  11603. ** <li> If there have been no REPLACE resolutions on a key, then
  11604. ** the local changeset is rebased according to the most recent
  11605. ** of the OMIT resolutions.
  11606. ** </ul>
  11607. **
  11608. ** Note that conflict resolutions from multiple remote changesets are
  11609. ** combined on a per-field basis, not per-row. This means that in the
  11610. ** case of multiple remote UPDATE operations, some fields of a single
  11611. ** local change may be rebased for REPLACE while others are rebased for
  11612. ** OMIT.
  11613. **
  11614. ** In order to rebase a local changeset, the remote changeset must first
  11615. ** be applied to the local database using sqlite3changeset_apply_v2() and
  11616. ** the buffer of rebase information captured. Then:
  11617. **
  11618. ** <ol>
  11619. ** <li> An sqlite3_rebaser object is created by calling
  11620. ** sqlite3rebaser_create().
  11621. ** <li> The new object is configured with the rebase buffer obtained from
  11622. ** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
  11623. ** If the local changeset is to be rebased against multiple remote
  11624. ** changesets, then sqlite3rebaser_configure() should be called
  11625. ** multiple times, in the same order that the multiple
  11626. ** sqlite3changeset_apply_v2() calls were made.
  11627. ** <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
  11628. ** <li> The sqlite3_rebaser object is deleted by calling
  11629. ** sqlite3rebaser_delete().
  11630. ** </ol>
  11631. */
  11632. typedef struct sqlite3_rebaser sqlite3_rebaser;
  11633. /*
  11634. ** CAPI3REF: Create a changeset rebaser object.
  11635. ** EXPERIMENTAL
  11636. **
  11637. ** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
  11638. ** point to the new object and return SQLITE_OK. Otherwise, if an error
  11639. ** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
  11640. ** to NULL.
  11641. */
  11642. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
  11643. /*
  11644. ** CAPI3REF: Configure a changeset rebaser object.
  11645. ** EXPERIMENTAL
  11646. **
  11647. ** Configure the changeset rebaser object to rebase changesets according
  11648. ** to the conflict resolutions described by buffer pRebase (size nRebase
  11649. ** bytes), which must have been obtained from a previous call to
  11650. ** sqlite3changeset_apply_v2().
  11651. */
  11652. SQLITE_API int sqlite3rebaser_configure(
  11653. sqlite3_rebaser*,
  11654. int nRebase, const void *pRebase
  11655. );
  11656. /*
  11657. ** CAPI3REF: Rebase a changeset
  11658. ** EXPERIMENTAL
  11659. **
  11660. ** Argument pIn must point to a buffer containing a changeset nIn bytes
  11661. ** in size. This function allocates and populates a buffer with a copy
  11662. ** of the changeset rebased rebased according to the configuration of the
  11663. ** rebaser object passed as the first argument. If successful, (*ppOut)
  11664. ** is set to point to the new buffer containing the rebased changeset and
  11665. ** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
  11666. ** responsibility of the caller to eventually free the new buffer using
  11667. ** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
  11668. ** are set to zero and an SQLite error code returned.
  11669. */
  11670. SQLITE_API int sqlite3rebaser_rebase(
  11671. sqlite3_rebaser*,
  11672. int nIn, const void *pIn,
  11673. int *pnOut, void **ppOut
  11674. );
  11675. /*
  11676. ** CAPI3REF: Delete a changeset rebaser object.
  11677. ** EXPERIMENTAL
  11678. **
  11679. ** Delete the changeset rebaser object and all associated resources. There
  11680. ** should be one call to this function for each successful invocation
  11681. ** of sqlite3rebaser_create().
  11682. */
  11683. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
  11684. /*
  11685. ** CAPI3REF: Streaming Versions of API functions.
  11686. **
  11687. ** The six streaming API xxx_strm() functions serve similar purposes to the
  11688. ** corresponding non-streaming API functions:
  11689. **
  11690. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  11691. ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
  11692. ** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
  11693. ** <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
  11694. ** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
  11695. ** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
  11696. ** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
  11697. ** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
  11698. ** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
  11699. ** </table>
  11700. **
  11701. ** Non-streaming functions that accept changesets (or patchsets) as input
  11702. ** require that the entire changeset be stored in a single buffer in memory.
  11703. ** Similarly, those that return a changeset or patchset do so by returning
  11704. ** a pointer to a single large buffer allocated using sqlite3_malloc().
  11705. ** Normally this is convenient. However, if an application running in a
  11706. ** low-memory environment is required to handle very large changesets, the
  11707. ** large contiguous memory allocations required can become onerous.
  11708. **
  11709. ** In order to avoid this problem, instead of a single large buffer, input
  11710. ** is passed to a streaming API functions by way of a callback function that
  11711. ** the sessions module invokes to incrementally request input data as it is
  11712. ** required. In all cases, a pair of API function parameters such as
  11713. **
  11714. ** <pre>
  11715. ** &nbsp; int nChangeset,
  11716. ** &nbsp; void *pChangeset,
  11717. ** </pre>
  11718. **
  11719. ** Is replaced by:
  11720. **
  11721. ** <pre>
  11722. ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
  11723. ** &nbsp; void *pIn,
  11724. ** </pre>
  11725. **
  11726. ** Each time the xInput callback is invoked by the sessions module, the first
  11727. ** argument passed is a copy of the supplied pIn context pointer. The second
  11728. ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
  11729. ** error occurs the xInput method should copy up to (*pnData) bytes of data
  11730. ** into the buffer and set (*pnData) to the actual number of bytes copied
  11731. ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
  11732. ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
  11733. ** error code should be returned. In all cases, if an xInput callback returns
  11734. ** an error, all processing is abandoned and the streaming API function
  11735. ** returns a copy of the error code to the caller.
  11736. **
  11737. ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
  11738. ** invoked by the sessions module at any point during the lifetime of the
  11739. ** iterator. If such an xInput callback returns an error, the iterator enters
  11740. ** an error state, whereby all subsequent calls to iterator functions
  11741. ** immediately fail with the same error code as returned by xInput.
  11742. **
  11743. ** Similarly, streaming API functions that return changesets (or patchsets)
  11744. ** return them in chunks by way of a callback function instead of via a
  11745. ** pointer to a single large buffer. In this case, a pair of parameters such
  11746. ** as:
  11747. **
  11748. ** <pre>
  11749. ** &nbsp; int *pnChangeset,
  11750. ** &nbsp; void **ppChangeset,
  11751. ** </pre>
  11752. **
  11753. ** Is replaced by:
  11754. **
  11755. ** <pre>
  11756. ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
  11757. ** &nbsp; void *pOut
  11758. ** </pre>
  11759. **
  11760. ** The xOutput callback is invoked zero or more times to return data to
  11761. ** the application. The first parameter passed to each call is a copy of the
  11762. ** pOut pointer supplied by the application. The second parameter, pData,
  11763. ** points to a buffer nData bytes in size containing the chunk of output
  11764. ** data being returned. If the xOutput callback successfully processes the
  11765. ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
  11766. ** it should return some other SQLite error code. In this case processing
  11767. ** is immediately abandoned and the streaming API function returns a copy
  11768. ** of the xOutput error code to the application.
  11769. **
  11770. ** The sessions module never invokes an xOutput callback with the third
  11771. ** parameter set to a value less than or equal to zero. Other than this,
  11772. ** no guarantees are made as to the size of the chunks of data returned.
  11773. */
  11774. SQLITE_API int sqlite3changeset_apply_strm(
  11775. sqlite3 *db, /* Apply change to "main" db of this handle */
  11776. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  11777. void *pIn, /* First arg for xInput */
  11778. int(*xFilter)(
  11779. void *pCtx, /* Copy of sixth arg to _apply() */
  11780. const char *zTab /* Table name */
  11781. ),
  11782. int(*xConflict)(
  11783. void *pCtx, /* Copy of sixth arg to _apply() */
  11784. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11785. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11786. ),
  11787. void *pCtx /* First argument passed to xConflict */
  11788. );
  11789. SQLITE_API int sqlite3changeset_apply_v2_strm(
  11790. sqlite3 *db, /* Apply change to "main" db of this handle */
  11791. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  11792. void *pIn, /* First arg for xInput */
  11793. int(*xFilter)(
  11794. void *pCtx, /* Copy of sixth arg to _apply() */
  11795. const char *zTab /* Table name */
  11796. ),
  11797. int(*xConflict)(
  11798. void *pCtx, /* Copy of sixth arg to _apply() */
  11799. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11800. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11801. ),
  11802. void *pCtx, /* First argument passed to xConflict */
  11803. void **ppRebase, int *pnRebase,
  11804. int flags
  11805. );
  11806. SQLITE_API int sqlite3changeset_concat_strm(
  11807. int (*xInputA)(void *pIn, void *pData, int *pnData),
  11808. void *pInA,
  11809. int (*xInputB)(void *pIn, void *pData, int *pnData),
  11810. void *pInB,
  11811. int (*xOutput)(void *pOut, const void *pData, int nData),
  11812. void *pOut
  11813. );
  11814. SQLITE_API int sqlite3changeset_invert_strm(
  11815. int (*xInput)(void *pIn, void *pData, int *pnData),
  11816. void *pIn,
  11817. int (*xOutput)(void *pOut, const void *pData, int nData),
  11818. void *pOut
  11819. );
  11820. SQLITE_API int sqlite3changeset_start_strm(
  11821. sqlite3_changeset_iter **pp,
  11822. int (*xInput)(void *pIn, void *pData, int *pnData),
  11823. void *pIn
  11824. );
  11825. SQLITE_API int sqlite3changeset_start_v2_strm(
  11826. sqlite3_changeset_iter **pp,
  11827. int (*xInput)(void *pIn, void *pData, int *pnData),
  11828. void *pIn,
  11829. int flags
  11830. );
  11831. SQLITE_API int sqlite3session_changeset_strm(
  11832. sqlite3_session *pSession,
  11833. int (*xOutput)(void *pOut, const void *pData, int nData),
  11834. void *pOut
  11835. );
  11836. SQLITE_API int sqlite3session_patchset_strm(
  11837. sqlite3_session *pSession,
  11838. int (*xOutput)(void *pOut, const void *pData, int nData),
  11839. void *pOut
  11840. );
  11841. SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
  11842. int (*xInput)(void *pIn, void *pData, int *pnData),
  11843. void *pIn
  11844. );
  11845. SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
  11846. int (*xOutput)(void *pOut, const void *pData, int nData),
  11847. void *pOut
  11848. );
  11849. SQLITE_API int sqlite3rebaser_rebase_strm(
  11850. sqlite3_rebaser *pRebaser,
  11851. int (*xInput)(void *pIn, void *pData, int *pnData),
  11852. void *pIn,
  11853. int (*xOutput)(void *pOut, const void *pData, int nData),
  11854. void *pOut
  11855. );
  11856. /*
  11857. ** CAPI3REF: Configure global parameters
  11858. **
  11859. ** The sqlite3session_config() interface is used to make global configuration
  11860. ** changes to the sessions module in order to tune it to the specific needs
  11861. ** of the application.
  11862. **
  11863. ** The sqlite3session_config() interface is not threadsafe. If it is invoked
  11864. ** while any other thread is inside any other sessions method then the
  11865. ** results are undefined. Furthermore, if it is invoked after any sessions
  11866. ** related objects have been created, the results are also undefined.
  11867. **
  11868. ** The first argument to the sqlite3session_config() function must be one
  11869. ** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
  11870. ** interpretation of the (void*) value passed as the second parameter and
  11871. ** the effect of calling this function depends on the value of the first
  11872. ** parameter.
  11873. **
  11874. ** <dl>
  11875. ** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>
  11876. ** By default, the sessions module streaming interfaces attempt to input
  11877. ** and output data in approximately 1 KiB chunks. This operand may be used
  11878. ** to set and query the value of this configuration setting. The pointer
  11879. ** passed as the second argument must point to a value of type (int).
  11880. ** If this value is greater than 0, it is used as the new streaming data
  11881. ** chunk size for both input and output. Before returning, the (int) value
  11882. ** pointed to by pArg is set to the final value of the streaming interface
  11883. ** chunk size.
  11884. ** </dl>
  11885. **
  11886. ** This function returns SQLITE_OK if successful, or an SQLite error code
  11887. ** otherwise.
  11888. */
  11889. SQLITE_API int sqlite3session_config(int op, void *pArg);
  11890. /*
  11891. ** CAPI3REF: Values for sqlite3session_config().
  11892. */
  11893. #define SQLITE_SESSION_CONFIG_STRMSIZE 1
  11894. /*
  11895. ** Make sure we can call this stuff from C++.
  11896. */
  11897. #if 0
  11898. }
  11899. #endif
  11900. #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
  11901. /******** End of sqlite3session.h *********/
  11902. /******** Begin file fts5.h *********/
  11903. /*
  11904. ** 2014 May 31
  11905. **
  11906. ** The author disclaims copyright to this source code. In place of
  11907. ** a legal notice, here is a blessing:
  11908. **
  11909. ** May you do good and not evil.
  11910. ** May you find forgiveness for yourself and forgive others.
  11911. ** May you share freely, never taking more than you give.
  11912. **
  11913. ******************************************************************************
  11914. **
  11915. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  11916. ** FTS5 may be extended with:
  11917. **
  11918. ** * custom tokenizers, and
  11919. ** * custom auxiliary functions.
  11920. */
  11921. #ifndef _FTS5_H
  11922. #define _FTS5_H
  11923. #if 0
  11924. extern "C" {
  11925. #endif
  11926. /*************************************************************************
  11927. ** CUSTOM AUXILIARY FUNCTIONS
  11928. **
  11929. ** Virtual table implementations may overload SQL functions by implementing
  11930. ** the sqlite3_module.xFindFunction() method.
  11931. */
  11932. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  11933. typedef struct Fts5Context Fts5Context;
  11934. typedef struct Fts5PhraseIter Fts5PhraseIter;
  11935. typedef void (*fts5_extension_function)(
  11936. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  11937. Fts5Context *pFts, /* First arg to pass to pApi functions */
  11938. sqlite3_context *pCtx, /* Context for returning result/error */
  11939. int nVal, /* Number of values in apVal[] array */
  11940. sqlite3_value **apVal /* Array of trailing arguments */
  11941. );
  11942. struct Fts5PhraseIter {
  11943. const unsigned char *a;
  11944. const unsigned char *b;
  11945. };
  11946. /*
  11947. ** EXTENSION API FUNCTIONS
  11948. **
  11949. ** xUserData(pFts):
  11950. ** Return a copy of the context pointer the extension function was
  11951. ** registered with.
  11952. **
  11953. ** xColumnTotalSize(pFts, iCol, pnToken):
  11954. ** If parameter iCol is less than zero, set output variable *pnToken
  11955. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  11956. ** non-negative but less than the number of columns in the table, return
  11957. ** the total number of tokens in column iCol, considering all rows in
  11958. ** the FTS5 table.
  11959. **
  11960. ** If parameter iCol is greater than or equal to the number of columns
  11961. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  11962. ** an OOM condition or IO error), an appropriate SQLite error code is
  11963. ** returned.
  11964. **
  11965. ** xColumnCount(pFts):
  11966. ** Return the number of columns in the table.
  11967. **
  11968. ** xColumnSize(pFts, iCol, pnToken):
  11969. ** If parameter iCol is less than zero, set output variable *pnToken
  11970. ** to the total number of tokens in the current row. Or, if iCol is
  11971. ** non-negative but less than the number of columns in the table, set
  11972. ** *pnToken to the number of tokens in column iCol of the current row.
  11973. **
  11974. ** If parameter iCol is greater than or equal to the number of columns
  11975. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  11976. ** an OOM condition or IO error), an appropriate SQLite error code is
  11977. ** returned.
  11978. **
  11979. ** This function may be quite inefficient if used with an FTS5 table
  11980. ** created with the "columnsize=0" option.
  11981. **
  11982. ** xColumnText:
  11983. ** This function attempts to retrieve the text of column iCol of the
  11984. ** current document. If successful, (*pz) is set to point to a buffer
  11985. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  11986. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  11987. ** if an error occurs, an SQLite error code is returned and the final values
  11988. ** of (*pz) and (*pn) are undefined.
  11989. **
  11990. ** xPhraseCount:
  11991. ** Returns the number of phrases in the current query expression.
  11992. **
  11993. ** xPhraseSize:
  11994. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  11995. ** are numbered starting from zero.
  11996. **
  11997. ** xInstCount:
  11998. ** Set *pnInst to the total number of occurrences of all phrases within
  11999. ** the query within the current row. Return SQLITE_OK if successful, or
  12000. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  12001. **
  12002. ** This API can be quite slow if used with an FTS5 table created with the
  12003. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  12004. ** with either "detail=none" or "detail=column" and "content=" option
  12005. ** (i.e. if it is a contentless table), then this API always returns 0.
  12006. **
  12007. ** xInst:
  12008. ** Query for the details of phrase match iIdx within the current row.
  12009. ** Phrase matches are numbered starting from zero, so the iIdx argument
  12010. ** should be greater than or equal to zero and smaller than the value
  12011. ** output by xInstCount().
  12012. **
  12013. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  12014. ** to the column in which it occurs and *piOff the token offset of the
  12015. ** first token of the phrase. Returns SQLITE_OK if successful, or an error
  12016. ** code (i.e. SQLITE_NOMEM) if an error occurs.
  12017. **
  12018. ** This API can be quite slow if used with an FTS5 table created with the
  12019. ** "detail=none" or "detail=column" option.
  12020. **
  12021. ** xRowid:
  12022. ** Returns the rowid of the current row.
  12023. **
  12024. ** xTokenize:
  12025. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  12026. **
  12027. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  12028. ** This API function is used to query the FTS table for phrase iPhrase
  12029. ** of the current query. Specifically, a query equivalent to:
  12030. **
  12031. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  12032. **
  12033. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  12034. ** current query is executed. Any column filter that applies to
  12035. ** phrase iPhrase of the current query is included in $p. For each
  12036. ** row visited, the callback function passed as the fourth argument
  12037. ** is invoked. The context and API objects passed to the callback
  12038. ** function may be used to access the properties of each matched row.
  12039. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  12040. ** the third argument to pUserData.
  12041. **
  12042. ** If the callback function returns any value other than SQLITE_OK, the
  12043. ** query is abandoned and the xQueryPhrase function returns immediately.
  12044. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  12045. ** Otherwise, the error code is propagated upwards.
  12046. **
  12047. ** If the query runs to completion without incident, SQLITE_OK is returned.
  12048. ** Or, if some error occurs before the query completes or is aborted by
  12049. ** the callback, an SQLite error code is returned.
  12050. **
  12051. **
  12052. ** xSetAuxdata(pFts5, pAux, xDelete)
  12053. **
  12054. ** Save the pointer passed as the second argument as the extension functions
  12055. ** "auxiliary data". The pointer may then be retrieved by the current or any
  12056. ** future invocation of the same fts5 extension function made as part of
  12057. ** the same MATCH query using the xGetAuxdata() API.
  12058. **
  12059. ** Each extension function is allocated a single auxiliary data slot for
  12060. ** each FTS query (MATCH expression). If the extension function is invoked
  12061. ** more than once for a single FTS query, then all invocations share a
  12062. ** single auxiliary data context.
  12063. **
  12064. ** If there is already an auxiliary data pointer when this function is
  12065. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  12066. ** was specified along with the original pointer, it is invoked at this
  12067. ** point.
  12068. **
  12069. ** The xDelete callback, if one is specified, is also invoked on the
  12070. ** auxiliary data pointer after the FTS5 query has finished.
  12071. **
  12072. ** If an error (e.g. an OOM condition) occurs within this function,
  12073. ** the auxiliary data is set to NULL and an error code returned. If the
  12074. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  12075. ** pointer before returning.
  12076. **
  12077. **
  12078. ** xGetAuxdata(pFts5, bClear)
  12079. **
  12080. ** Returns the current auxiliary data pointer for the fts5 extension
  12081. ** function. See the xSetAuxdata() method for details.
  12082. **
  12083. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  12084. ** (set to NULL) before this function returns. In this case the xDelete,
  12085. ** if any, is not invoked.
  12086. **
  12087. **
  12088. ** xRowCount(pFts5, pnRow)
  12089. **
  12090. ** This function is used to retrieve the total number of rows in the table.
  12091. ** In other words, the same value that would be returned by:
  12092. **
  12093. ** SELECT count(*) FROM ftstable;
  12094. **
  12095. ** xPhraseFirst()
  12096. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  12097. ** method, to iterate through all instances of a single query phrase within
  12098. ** the current row. This is the same information as is accessible via the
  12099. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  12100. ** to use, this API may be faster under some circumstances. To iterate
  12101. ** through instances of phrase iPhrase, use the following code:
  12102. **
  12103. ** Fts5PhraseIter iter;
  12104. ** int iCol, iOff;
  12105. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  12106. ** iCol>=0;
  12107. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  12108. ** ){
  12109. ** // An instance of phrase iPhrase at offset iOff of column iCol
  12110. ** }
  12111. **
  12112. ** The Fts5PhraseIter structure is defined above. Applications should not
  12113. ** modify this structure directly - it should only be used as shown above
  12114. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  12115. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  12116. **
  12117. ** This API can be quite slow if used with an FTS5 table created with the
  12118. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  12119. ** with either "detail=none" or "detail=column" and "content=" option
  12120. ** (i.e. if it is a contentless table), then this API always iterates
  12121. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  12122. **
  12123. ** xPhraseNext()
  12124. ** See xPhraseFirst above.
  12125. **
  12126. ** xPhraseFirstColumn()
  12127. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  12128. ** and xPhraseNext() APIs described above. The difference is that instead
  12129. ** of iterating through all instances of a phrase in the current row, these
  12130. ** APIs are used to iterate through the set of columns in the current row
  12131. ** that contain one or more instances of a specified phrase. For example:
  12132. **
  12133. ** Fts5PhraseIter iter;
  12134. ** int iCol;
  12135. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  12136. ** iCol>=0;
  12137. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  12138. ** ){
  12139. ** // Column iCol contains at least one instance of phrase iPhrase
  12140. ** }
  12141. **
  12142. ** This API can be quite slow if used with an FTS5 table created with the
  12143. ** "detail=none" option. If the FTS5 table is created with either
  12144. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  12145. ** then this API always iterates through an empty set (all calls to
  12146. ** xPhraseFirstColumn() set iCol to -1).
  12147. **
  12148. ** The information accessed using this API and its companion
  12149. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  12150. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  12151. ** significantly more efficient than those alternatives when used with
  12152. ** "detail=column" tables.
  12153. **
  12154. ** xPhraseNextColumn()
  12155. ** See xPhraseFirstColumn above.
  12156. */
  12157. struct Fts5ExtensionApi {
  12158. int iVersion; /* Currently always set to 3 */
  12159. void *(*xUserData)(Fts5Context*);
  12160. int (*xColumnCount)(Fts5Context*);
  12161. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  12162. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  12163. int (*xTokenize)(Fts5Context*,
  12164. const char *pText, int nText, /* Text to tokenize */
  12165. void *pCtx, /* Context passed to xToken() */
  12166. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  12167. );
  12168. int (*xPhraseCount)(Fts5Context*);
  12169. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  12170. int (*xInstCount)(Fts5Context*, int *pnInst);
  12171. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  12172. sqlite3_int64 (*xRowid)(Fts5Context*);
  12173. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  12174. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  12175. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  12176. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  12177. );
  12178. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  12179. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  12180. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  12181. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  12182. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  12183. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  12184. };
  12185. /*
  12186. ** CUSTOM AUXILIARY FUNCTIONS
  12187. *************************************************************************/
  12188. /*************************************************************************
  12189. ** CUSTOM TOKENIZERS
  12190. **
  12191. ** Applications may also register custom tokenizer types. A tokenizer
  12192. ** is registered by providing fts5 with a populated instance of the
  12193. ** following structure. All structure methods must be defined, setting
  12194. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  12195. ** behaviour. The structure methods are expected to function as follows:
  12196. **
  12197. ** xCreate:
  12198. ** This function is used to allocate and initialize a tokenizer instance.
  12199. ** A tokenizer instance is required to actually tokenize text.
  12200. **
  12201. ** The first argument passed to this function is a copy of the (void*)
  12202. ** pointer provided by the application when the fts5_tokenizer object
  12203. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  12204. ** The second and third arguments are an array of nul-terminated strings
  12205. ** containing the tokenizer arguments, if any, specified following the
  12206. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  12207. ** to create the FTS5 table.
  12208. **
  12209. ** The final argument is an output variable. If successful, (*ppOut)
  12210. ** should be set to point to the new tokenizer handle and SQLITE_OK
  12211. ** returned. If an error occurs, some value other than SQLITE_OK should
  12212. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  12213. ** is undefined.
  12214. **
  12215. ** xDelete:
  12216. ** This function is invoked to delete a tokenizer handle previously
  12217. ** allocated using xCreate(). Fts5 guarantees that this function will
  12218. ** be invoked exactly once for each successful call to xCreate().
  12219. **
  12220. ** xTokenize:
  12221. ** This function is expected to tokenize the nText byte string indicated
  12222. ** by argument pText. pText may or may not be nul-terminated. The first
  12223. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  12224. ** returned by an earlier call to xCreate().
  12225. **
  12226. ** The second argument indicates the reason that FTS5 is requesting
  12227. ** tokenization of the supplied text. This is always one of the following
  12228. ** four values:
  12229. **
  12230. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  12231. ** or removed from the FTS table. The tokenizer is being invoked to
  12232. ** determine the set of tokens to add to (or delete from) the
  12233. ** FTS index.
  12234. **
  12235. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  12236. ** against the FTS index. The tokenizer is being called to tokenize
  12237. ** a bareword or quoted string specified as part of the query.
  12238. **
  12239. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  12240. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  12241. ** followed by a "*" character, indicating that the last token
  12242. ** returned by the tokenizer will be treated as a token prefix.
  12243. **
  12244. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  12245. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  12246. ** function. Or an fts5_api.xColumnSize() request made by the same
  12247. ** on a columnsize=0 database.
  12248. ** </ul>
  12249. **
  12250. ** For each token in the input string, the supplied callback xToken() must
  12251. ** be invoked. The first argument to it should be a copy of the pointer
  12252. ** passed as the second argument to xTokenize(). The third and fourth
  12253. ** arguments are a pointer to a buffer containing the token text, and the
  12254. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  12255. ** of the first byte of and first byte immediately following the text from
  12256. ** which the token is derived within the input.
  12257. **
  12258. ** The second argument passed to the xToken() callback ("tflags") should
  12259. ** normally be set to 0. The exception is if the tokenizer supports
  12260. ** synonyms. In this case see the discussion below for details.
  12261. **
  12262. ** FTS5 assumes the xToken() callback is invoked for each token in the
  12263. ** order that they occur within the input text.
  12264. **
  12265. ** If an xToken() callback returns any value other than SQLITE_OK, then
  12266. ** the tokenization should be abandoned and the xTokenize() method should
  12267. ** immediately return a copy of the xToken() return value. Or, if the
  12268. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  12269. ** if an error occurs with the xTokenize() implementation itself, it
  12270. ** may abandon the tokenization and return any error code other than
  12271. ** SQLITE_OK or SQLITE_DONE.
  12272. **
  12273. ** SYNONYM SUPPORT
  12274. **
  12275. ** Custom tokenizers may also support synonyms. Consider a case in which a
  12276. ** user wishes to query for a phrase such as "first place". Using the
  12277. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  12278. ** of "first place" within the document set, but not alternative forms
  12279. ** such as "1st place". In some applications, it would be better to match
  12280. ** all instances of "first place" or "1st place" regardless of which form
  12281. ** the user specified in the MATCH query text.
  12282. **
  12283. ** There are several ways to approach this in FTS5:
  12284. **
  12285. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  12286. ** In the above example, this means that the tokenizer returns the
  12287. ** same token for inputs "first" and "1st". Say that token is in
  12288. ** fact "first", so that when the user inserts the document "I won
  12289. ** 1st place" entries are added to the index for tokens "i", "won",
  12290. ** "first" and "place". If the user then queries for '1st + place',
  12291. ** the tokenizer substitutes "first" for "1st" and the query works
  12292. ** as expected.
  12293. **
  12294. ** <li> By querying the index for all synonyms of each query term
  12295. ** separately. In this case, when tokenizing query text, the
  12296. ** tokenizer may provide multiple synonyms for a single term
  12297. ** within the document. FTS5 then queries the index for each
  12298. ** synonym individually. For example, faced with the query:
  12299. **
  12300. ** <codeblock>
  12301. ** ... MATCH 'first place'</codeblock>
  12302. **
  12303. ** the tokenizer offers both "1st" and "first" as synonyms for the
  12304. ** first token in the MATCH query and FTS5 effectively runs a query
  12305. ** similar to:
  12306. **
  12307. ** <codeblock>
  12308. ** ... MATCH '(first OR 1st) place'</codeblock>
  12309. **
  12310. ** except that, for the purposes of auxiliary functions, the query
  12311. ** still appears to contain just two phrases - "(first OR 1st)"
  12312. ** being treated as a single phrase.
  12313. **
  12314. ** <li> By adding multiple synonyms for a single term to the FTS index.
  12315. ** Using this method, when tokenizing document text, the tokenizer
  12316. ** provides multiple synonyms for each token. So that when a
  12317. ** document such as "I won first place" is tokenized, entries are
  12318. ** added to the FTS index for "i", "won", "first", "1st" and
  12319. ** "place".
  12320. **
  12321. ** This way, even if the tokenizer does not provide synonyms
  12322. ** when tokenizing query text (it should not - to do so would be
  12323. ** inefficient), it doesn't matter if the user queries for
  12324. ** 'first + place' or '1st + place', as there are entries in the
  12325. ** FTS index corresponding to both forms of the first token.
  12326. ** </ol>
  12327. **
  12328. ** Whether it is parsing document or query text, any call to xToken that
  12329. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  12330. ** is considered to supply a synonym for the previous token. For example,
  12331. ** when parsing the document "I won first place", a tokenizer that supports
  12332. ** synonyms would call xToken() 5 times, as follows:
  12333. **
  12334. ** <codeblock>
  12335. ** xToken(pCtx, 0, "i", 1, 0, 1);
  12336. ** xToken(pCtx, 0, "won", 3, 2, 5);
  12337. ** xToken(pCtx, 0, "first", 5, 6, 11);
  12338. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  12339. ** xToken(pCtx, 0, "place", 5, 12, 17);
  12340. **</codeblock>
  12341. **
  12342. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  12343. ** xToken() is called. Multiple synonyms may be specified for a single token
  12344. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  12345. ** There is no limit to the number of synonyms that may be provided for a
  12346. ** single token.
  12347. **
  12348. ** In many cases, method (1) above is the best approach. It does not add
  12349. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  12350. ** so it is efficient in terms of disk space and query speed. However, it
  12351. ** does not support prefix queries very well. If, as suggested above, the
  12352. ** token "first" is substituted for "1st" by the tokenizer, then the query:
  12353. **
  12354. ** <codeblock>
  12355. ** ... MATCH '1s*'</codeblock>
  12356. **
  12357. ** will not match documents that contain the token "1st" (as the tokenizer
  12358. ** will probably not map "1s" to any prefix of "first").
  12359. **
  12360. ** For full prefix support, method (3) may be preferred. In this case,
  12361. ** because the index contains entries for both "first" and "1st", prefix
  12362. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  12363. ** extra entries are added to the FTS index, this method uses more space
  12364. ** within the database.
  12365. **
  12366. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  12367. ** a query such as '1s*' will match documents that contain the literal
  12368. ** token "1st", but not "first" (assuming the tokenizer is not able to
  12369. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  12370. ** will match against "1st" and "first". This method does not require
  12371. ** extra disk space, as no extra entries are added to the FTS index.
  12372. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  12373. ** as separate queries of the FTS index are required for each synonym.
  12374. **
  12375. ** When using methods (2) or (3), it is important that the tokenizer only
  12376. ** provide synonyms when tokenizing document text (method (2)) or query
  12377. ** text (method (3)), not both. Doing so will not cause any errors, but is
  12378. ** inefficient.
  12379. */
  12380. typedef struct Fts5Tokenizer Fts5Tokenizer;
  12381. typedef struct fts5_tokenizer fts5_tokenizer;
  12382. struct fts5_tokenizer {
  12383. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  12384. void (*xDelete)(Fts5Tokenizer*);
  12385. int (*xTokenize)(Fts5Tokenizer*,
  12386. void *pCtx,
  12387. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  12388. const char *pText, int nText,
  12389. int (*xToken)(
  12390. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  12391. int tflags, /* Mask of FTS5_TOKEN_* flags */
  12392. const char *pToken, /* Pointer to buffer containing token */
  12393. int nToken, /* Size of token in bytes */
  12394. int iStart, /* Byte offset of token within input text */
  12395. int iEnd /* Byte offset of end of token within input text */
  12396. )
  12397. );
  12398. };
  12399. /* Flags that may be passed as the third argument to xTokenize() */
  12400. #define FTS5_TOKENIZE_QUERY 0x0001
  12401. #define FTS5_TOKENIZE_PREFIX 0x0002
  12402. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  12403. #define FTS5_TOKENIZE_AUX 0x0008
  12404. /* Flags that may be passed by the tokenizer implementation back to FTS5
  12405. ** as the third argument to the supplied xToken callback. */
  12406. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  12407. /*
  12408. ** END OF CUSTOM TOKENIZERS
  12409. *************************************************************************/
  12410. /*************************************************************************
  12411. ** FTS5 EXTENSION REGISTRATION API
  12412. */
  12413. typedef struct fts5_api fts5_api;
  12414. struct fts5_api {
  12415. int iVersion; /* Currently always set to 2 */
  12416. /* Create a new tokenizer */
  12417. int (*xCreateTokenizer)(
  12418. fts5_api *pApi,
  12419. const char *zName,
  12420. void *pContext,
  12421. fts5_tokenizer *pTokenizer,
  12422. void (*xDestroy)(void*)
  12423. );
  12424. /* Find an existing tokenizer */
  12425. int (*xFindTokenizer)(
  12426. fts5_api *pApi,
  12427. const char *zName,
  12428. void **ppContext,
  12429. fts5_tokenizer *pTokenizer
  12430. );
  12431. /* Create a new auxiliary function */
  12432. int (*xCreateFunction)(
  12433. fts5_api *pApi,
  12434. const char *zName,
  12435. void *pContext,
  12436. fts5_extension_function xFunction,
  12437. void (*xDestroy)(void*)
  12438. );
  12439. };
  12440. /*
  12441. ** END OF REGISTRATION API
  12442. *************************************************************************/
  12443. #if 0
  12444. } /* end of the 'extern "C"' block */
  12445. #endif
  12446. #endif /* _FTS5_H */
  12447. /******** End of fts5.h *********/
  12448. /************** End of sqlite3.h *********************************************/
  12449. /************** Continuing where we left off in sqliteInt.h ******************/
  12450. /*
  12451. ** Include the configuration header output by 'configure' if we're using the
  12452. ** autoconf-based build
  12453. */
  12454. #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
  12455. /* #include "config.h" */
  12456. #define SQLITECONFIG_H 1
  12457. #endif
  12458. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  12459. /************** Begin file sqliteLimit.h *************************************/
  12460. /*
  12461. ** 2007 May 7
  12462. **
  12463. ** The author disclaims copyright to this source code. In place of
  12464. ** a legal notice, here is a blessing:
  12465. **
  12466. ** May you do good and not evil.
  12467. ** May you find forgiveness for yourself and forgive others.
  12468. ** May you share freely, never taking more than you give.
  12469. **
  12470. *************************************************************************
  12471. **
  12472. ** This file defines various limits of what SQLite can process.
  12473. */
  12474. /*
  12475. ** The maximum length of a TEXT or BLOB in bytes. This also
  12476. ** limits the size of a row in a table or index.
  12477. **
  12478. ** The hard limit is the ability of a 32-bit signed integer
  12479. ** to count the size: 2^31-1 or 2147483647.
  12480. */
  12481. #ifndef SQLITE_MAX_LENGTH
  12482. # define SQLITE_MAX_LENGTH 1000000000
  12483. #endif
  12484. /*
  12485. ** This is the maximum number of
  12486. **
  12487. ** * Columns in a table
  12488. ** * Columns in an index
  12489. ** * Columns in a view
  12490. ** * Terms in the SET clause of an UPDATE statement
  12491. ** * Terms in the result set of a SELECT statement
  12492. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  12493. ** * Terms in the VALUES clause of an INSERT statement
  12494. **
  12495. ** The hard upper limit here is 32676. Most database people will
  12496. ** tell you that in a well-normalized database, you usually should
  12497. ** not have more than a dozen or so columns in any table. And if
  12498. ** that is the case, there is no point in having more than a few
  12499. ** dozen values in any of the other situations described above.
  12500. */
  12501. #ifndef SQLITE_MAX_COLUMN
  12502. # define SQLITE_MAX_COLUMN 2000
  12503. #endif
  12504. /*
  12505. ** The maximum length of a single SQL statement in bytes.
  12506. **
  12507. ** It used to be the case that setting this value to zero would
  12508. ** turn the limit off. That is no longer true. It is not possible
  12509. ** to turn this limit off.
  12510. */
  12511. #ifndef SQLITE_MAX_SQL_LENGTH
  12512. # define SQLITE_MAX_SQL_LENGTH 1000000000
  12513. #endif
  12514. /*
  12515. ** The maximum depth of an expression tree. This is limited to
  12516. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  12517. ** want to place more severe limits on the complexity of an
  12518. ** expression.
  12519. **
  12520. ** A value of 0 used to mean that the limit was not enforced.
  12521. ** But that is no longer true. The limit is now strictly enforced
  12522. ** at all times.
  12523. */
  12524. #ifndef SQLITE_MAX_EXPR_DEPTH
  12525. # define SQLITE_MAX_EXPR_DEPTH 1000
  12526. #endif
  12527. /*
  12528. ** The maximum number of terms in a compound SELECT statement.
  12529. ** The code generator for compound SELECT statements does one
  12530. ** level of recursion for each term. A stack overflow can result
  12531. ** if the number of terms is too large. In practice, most SQL
  12532. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  12533. ** any limit on the number of terms in a compount SELECT.
  12534. */
  12535. #ifndef SQLITE_MAX_COMPOUND_SELECT
  12536. # define SQLITE_MAX_COMPOUND_SELECT 500
  12537. #endif
  12538. /*
  12539. ** The maximum number of opcodes in a VDBE program.
  12540. ** Not currently enforced.
  12541. */
  12542. #ifndef SQLITE_MAX_VDBE_OP
  12543. # define SQLITE_MAX_VDBE_OP 250000000
  12544. #endif
  12545. /*
  12546. ** The maximum number of arguments to an SQL function.
  12547. */
  12548. #ifndef SQLITE_MAX_FUNCTION_ARG
  12549. # define SQLITE_MAX_FUNCTION_ARG 127
  12550. #endif
  12551. /*
  12552. ** The suggested maximum number of in-memory pages to use for
  12553. ** the main database table and for temporary tables.
  12554. **
  12555. ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
  12556. ** which means the cache size is limited to 2048000 bytes of memory.
  12557. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  12558. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  12559. */
  12560. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  12561. # define SQLITE_DEFAULT_CACHE_SIZE -2000
  12562. #endif
  12563. /*
  12564. ** The default number of frames to accumulate in the log file before
  12565. ** checkpointing the database in WAL mode.
  12566. */
  12567. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  12568. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  12569. #endif
  12570. /*
  12571. ** The maximum number of attached databases. This must be between 0
  12572. ** and 125. The upper bound of 125 is because the attached databases are
  12573. ** counted using a signed 8-bit integer which has a maximum value of 127
  12574. ** and we have to allow 2 extra counts for the "main" and "temp" databases.
  12575. */
  12576. #ifndef SQLITE_MAX_ATTACHED
  12577. # define SQLITE_MAX_ATTACHED 10
  12578. #endif
  12579. /*
  12580. ** The maximum value of a ?nnn wildcard that the parser will accept.
  12581. */
  12582. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  12583. # define SQLITE_MAX_VARIABLE_NUMBER 999
  12584. #endif
  12585. /* Maximum page size. The upper bound on this value is 65536. This a limit
  12586. ** imposed by the use of 16-bit offsets within each page.
  12587. **
  12588. ** Earlier versions of SQLite allowed the user to change this value at
  12589. ** compile time. This is no longer permitted, on the grounds that it creates
  12590. ** a library that is technically incompatible with an SQLite library
  12591. ** compiled with a different limit. If a process operating on a database
  12592. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  12593. ** compiled with the default page-size limit will not be able to rollback
  12594. ** the aborted transaction. This could lead to database corruption.
  12595. */
  12596. #ifdef SQLITE_MAX_PAGE_SIZE
  12597. # undef SQLITE_MAX_PAGE_SIZE
  12598. #endif
  12599. #define SQLITE_MAX_PAGE_SIZE 65536
  12600. /*
  12601. ** The default size of a database page.
  12602. */
  12603. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  12604. # define SQLITE_DEFAULT_PAGE_SIZE 4096
  12605. #endif
  12606. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  12607. # undef SQLITE_DEFAULT_PAGE_SIZE
  12608. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  12609. #endif
  12610. /*
  12611. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  12612. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  12613. ** device characteristics (sector-size and atomic write() support),
  12614. ** SQLite may choose a larger value. This constant is the maximum value
  12615. ** SQLite will choose on its own.
  12616. */
  12617. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  12618. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  12619. #endif
  12620. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  12621. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  12622. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  12623. #endif
  12624. /*
  12625. ** Maximum number of pages in one database file.
  12626. **
  12627. ** This is really just the default value for the max_page_count pragma.
  12628. ** This value can be lowered (or raised) at run-time using that the
  12629. ** max_page_count macro.
  12630. */
  12631. #ifndef SQLITE_MAX_PAGE_COUNT
  12632. # define SQLITE_MAX_PAGE_COUNT 1073741823
  12633. #endif
  12634. /*
  12635. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  12636. ** operator.
  12637. */
  12638. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  12639. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  12640. #endif
  12641. /*
  12642. ** Maximum depth of recursion for triggers.
  12643. **
  12644. ** A value of 1 means that a trigger program will not be able to itself
  12645. ** fire any triggers. A value of 0 means that no trigger programs at all
  12646. ** may be executed.
  12647. */
  12648. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  12649. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  12650. #endif
  12651. /************** End of sqliteLimit.h *****************************************/
  12652. /************** Continuing where we left off in sqliteInt.h ******************/
  12653. /* Disable nuisance warnings on Borland compilers */
  12654. #if defined(__BORLANDC__)
  12655. #pragma warn -rch /* unreachable code */
  12656. #pragma warn -ccc /* Condition is always true or false */
  12657. #pragma warn -aus /* Assigned value is never used */
  12658. #pragma warn -csu /* Comparing signed and unsigned */
  12659. #pragma warn -spa /* Suspicious pointer arithmetic */
  12660. #endif
  12661. /*
  12662. ** Include standard header files as necessary
  12663. */
  12664. #ifdef HAVE_STDINT_H
  12665. #include <stdint.h>
  12666. #endif
  12667. #ifdef HAVE_INTTYPES_H
  12668. #include <inttypes.h>
  12669. #endif
  12670. /*
  12671. ** The following macros are used to cast pointers to integers and
  12672. ** integers to pointers. The way you do this varies from one compiler
  12673. ** to the next, so we have developed the following set of #if statements
  12674. ** to generate appropriate macros for a wide range of compilers.
  12675. **
  12676. ** The correct "ANSI" way to do this is to use the intptr_t type.
  12677. ** Unfortunately, that typedef is not available on all compilers, or
  12678. ** if it is available, it requires an #include of specific headers
  12679. ** that vary from one machine to the next.
  12680. **
  12681. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  12682. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  12683. ** So we have to define the macros in different ways depending on the
  12684. ** compiler.
  12685. */
  12686. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  12687. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  12688. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  12689. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  12690. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  12691. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  12692. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  12693. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  12694. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  12695. #else /* Generates a warning - but it always works */
  12696. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  12697. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  12698. #endif
  12699. /*
  12700. ** A macro to hint to the compiler that a function should not be
  12701. ** inlined.
  12702. */
  12703. #if defined(__GNUC__)
  12704. # define SQLITE_NOINLINE __attribute__((noinline))
  12705. #elif defined(_MSC_VER) && _MSC_VER>=1310
  12706. # define SQLITE_NOINLINE __declspec(noinline)
  12707. #else
  12708. # define SQLITE_NOINLINE
  12709. #endif
  12710. /*
  12711. ** Make sure that the compiler intrinsics we desire are enabled when
  12712. ** compiling with an appropriate version of MSVC unless prevented by
  12713. ** the SQLITE_DISABLE_INTRINSIC define.
  12714. */
  12715. #if !defined(SQLITE_DISABLE_INTRINSIC)
  12716. # if defined(_MSC_VER) && _MSC_VER>=1400
  12717. # if !defined(_WIN32_WCE)
  12718. # include <intrin.h>
  12719. # pragma intrinsic(_byteswap_ushort)
  12720. # pragma intrinsic(_byteswap_ulong)
  12721. # pragma intrinsic(_byteswap_uint64)
  12722. # pragma intrinsic(_ReadWriteBarrier)
  12723. # else
  12724. # include <cmnintrin.h>
  12725. # endif
  12726. # endif
  12727. #endif
  12728. /*
  12729. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  12730. ** 0 means mutexes are permanently disable and the library is never
  12731. ** threadsafe. 1 means the library is serialized which is the highest
  12732. ** level of threadsafety. 2 means the library is multithreaded - multiple
  12733. ** threads can use SQLite as long as no two threads try to use the same
  12734. ** database connection at the same time.
  12735. **
  12736. ** Older versions of SQLite used an optional THREADSAFE macro.
  12737. ** We support that for legacy.
  12738. **
  12739. ** To ensure that the correct value of "THREADSAFE" is reported when querying
  12740. ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
  12741. ** logic is partially replicated in ctime.c. If it is updated here, it should
  12742. ** also be updated there.
  12743. */
  12744. #if !defined(SQLITE_THREADSAFE)
  12745. # if defined(THREADSAFE)
  12746. # define SQLITE_THREADSAFE THREADSAFE
  12747. # else
  12748. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  12749. # endif
  12750. #endif
  12751. /*
  12752. ** Powersafe overwrite is on by default. But can be turned off using
  12753. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  12754. */
  12755. #ifndef SQLITE_POWERSAFE_OVERWRITE
  12756. # define SQLITE_POWERSAFE_OVERWRITE 1
  12757. #endif
  12758. /*
  12759. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  12760. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  12761. ** which case memory allocation statistics are disabled by default.
  12762. */
  12763. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  12764. # define SQLITE_DEFAULT_MEMSTATUS 1
  12765. #endif
  12766. /*
  12767. ** Exactly one of the following macros must be defined in order to
  12768. ** specify which memory allocation subsystem to use.
  12769. **
  12770. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  12771. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  12772. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  12773. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  12774. **
  12775. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  12776. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  12777. ** will cause HeapValidate to be called. If heap validation should fail, an
  12778. ** assertion will be triggered.
  12779. **
  12780. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  12781. ** the default.
  12782. */
  12783. #if defined(SQLITE_SYSTEM_MALLOC) \
  12784. + defined(SQLITE_WIN32_MALLOC) \
  12785. + defined(SQLITE_ZERO_MALLOC) \
  12786. + defined(SQLITE_MEMDEBUG)>1
  12787. # error "Two or more of the following compile-time configuration options\
  12788. are defined but at most one is allowed:\
  12789. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  12790. SQLITE_ZERO_MALLOC"
  12791. #endif
  12792. #if defined(SQLITE_SYSTEM_MALLOC) \
  12793. + defined(SQLITE_WIN32_MALLOC) \
  12794. + defined(SQLITE_ZERO_MALLOC) \
  12795. + defined(SQLITE_MEMDEBUG)==0
  12796. # define SQLITE_SYSTEM_MALLOC 1
  12797. #endif
  12798. /*
  12799. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  12800. ** sizes of memory allocations below this value where possible.
  12801. */
  12802. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  12803. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  12804. #endif
  12805. /*
  12806. ** We need to define _XOPEN_SOURCE as follows in order to enable
  12807. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  12808. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  12809. ** it.
  12810. */
  12811. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  12812. # define _XOPEN_SOURCE 600
  12813. #endif
  12814. /*
  12815. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  12816. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  12817. ** make it true by defining or undefining NDEBUG.
  12818. **
  12819. ** Setting NDEBUG makes the code smaller and faster by disabling the
  12820. ** assert() statements in the code. So we want the default action
  12821. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  12822. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  12823. ** feature.
  12824. */
  12825. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  12826. # define NDEBUG 1
  12827. #endif
  12828. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  12829. # undef NDEBUG
  12830. #endif
  12831. /*
  12832. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  12833. */
  12834. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  12835. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  12836. #endif
  12837. /*
  12838. ** The testcase() macro is used to aid in coverage testing. When
  12839. ** doing coverage testing, the condition inside the argument to
  12840. ** testcase() must be evaluated both true and false in order to
  12841. ** get full branch coverage. The testcase() macro is inserted
  12842. ** to help ensure adequate test coverage in places where simple
  12843. ** condition/decision coverage is inadequate. For example, testcase()
  12844. ** can be used to make sure boundary values are tested. For
  12845. ** bitmask tests, testcase() can be used to make sure each bit
  12846. ** is significant and used at least once. On switch statements
  12847. ** where multiple cases go to the same block of code, testcase()
  12848. ** can insure that all cases are evaluated.
  12849. **
  12850. */
  12851. #ifdef SQLITE_COVERAGE_TEST
  12852. SQLITE_PRIVATE void sqlite3Coverage(int);
  12853. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  12854. #else
  12855. # define testcase(X)
  12856. #endif
  12857. /*
  12858. ** The TESTONLY macro is used to enclose variable declarations or
  12859. ** other bits of code that are needed to support the arguments
  12860. ** within testcase() and assert() macros.
  12861. */
  12862. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  12863. # define TESTONLY(X) X
  12864. #else
  12865. # define TESTONLY(X)
  12866. #endif
  12867. /*
  12868. ** Sometimes we need a small amount of code such as a variable initialization
  12869. ** to setup for a later assert() statement. We do not want this code to
  12870. ** appear when assert() is disabled. The following macro is therefore
  12871. ** used to contain that setup code. The "VVA" acronym stands for
  12872. ** "Verification, Validation, and Accreditation". In other words, the
  12873. ** code within VVA_ONLY() will only run during verification processes.
  12874. */
  12875. #ifndef NDEBUG
  12876. # define VVA_ONLY(X) X
  12877. #else
  12878. # define VVA_ONLY(X)
  12879. #endif
  12880. /*
  12881. ** The ALWAYS and NEVER macros surround boolean expressions which
  12882. ** are intended to always be true or false, respectively. Such
  12883. ** expressions could be omitted from the code completely. But they
  12884. ** are included in a few cases in order to enhance the resilience
  12885. ** of SQLite to unexpected behavior - to make the code "self-healing"
  12886. ** or "ductile" rather than being "brittle" and crashing at the first
  12887. ** hint of unplanned behavior.
  12888. **
  12889. ** In other words, ALWAYS and NEVER are added for defensive code.
  12890. **
  12891. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  12892. ** be true and false so that the unreachable code they specify will
  12893. ** not be counted as untested code.
  12894. */
  12895. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  12896. # define ALWAYS(X) (1)
  12897. # define NEVER(X) (0)
  12898. #elif !defined(NDEBUG)
  12899. # define ALWAYS(X) ((X)?1:(assert(0),0))
  12900. # define NEVER(X) ((X)?(assert(0),1):0)
  12901. #else
  12902. # define ALWAYS(X) (X)
  12903. # define NEVER(X) (X)
  12904. #endif
  12905. /*
  12906. ** Some conditionals are optimizations only. In other words, if the
  12907. ** conditionals are replaced with a constant 1 (true) or 0 (false) then
  12908. ** the correct answer is still obtained, though perhaps not as quickly.
  12909. **
  12910. ** The following macros mark these optimizations conditionals.
  12911. */
  12912. #if defined(SQLITE_MUTATION_TEST)
  12913. # define OK_IF_ALWAYS_TRUE(X) (1)
  12914. # define OK_IF_ALWAYS_FALSE(X) (0)
  12915. #else
  12916. # define OK_IF_ALWAYS_TRUE(X) (X)
  12917. # define OK_IF_ALWAYS_FALSE(X) (X)
  12918. #endif
  12919. /*
  12920. ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
  12921. ** defined. We need to defend against those failures when testing with
  12922. ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
  12923. ** during a normal build. The following macro can be used to disable tests
  12924. ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
  12925. */
  12926. #if defined(SQLITE_TEST_REALLOC_STRESS)
  12927. # define ONLY_IF_REALLOC_STRESS(X) (X)
  12928. #elif !defined(NDEBUG)
  12929. # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
  12930. #else
  12931. # define ONLY_IF_REALLOC_STRESS(X) (0)
  12932. #endif
  12933. /*
  12934. ** Declarations used for tracing the operating system interfaces.
  12935. */
  12936. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  12937. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  12938. extern int sqlite3OSTrace;
  12939. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  12940. # define SQLITE_HAVE_OS_TRACE
  12941. #else
  12942. # define OSTRACE(X)
  12943. # undef SQLITE_HAVE_OS_TRACE
  12944. #endif
  12945. /*
  12946. ** Is the sqlite3ErrName() function needed in the build? Currently,
  12947. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  12948. ** OSTRACE is enabled), and by several "test*.c" files (which are
  12949. ** compiled using SQLITE_TEST).
  12950. */
  12951. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  12952. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  12953. # define SQLITE_NEED_ERR_NAME
  12954. #else
  12955. # undef SQLITE_NEED_ERR_NAME
  12956. #endif
  12957. /*
  12958. ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
  12959. */
  12960. #ifdef SQLITE_OMIT_EXPLAIN
  12961. # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
  12962. #endif
  12963. /*
  12964. ** Return true (non-zero) if the input is an integer that is too large
  12965. ** to fit in 32-bits. This macro is used inside of various testcase()
  12966. ** macros to verify that we have tested SQLite for large-file support.
  12967. */
  12968. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  12969. /*
  12970. ** The macro unlikely() is a hint that surrounds a boolean
  12971. ** expression that is usually false. Macro likely() surrounds
  12972. ** a boolean expression that is usually true. These hints could,
  12973. ** in theory, be used by the compiler to generate better code, but
  12974. ** currently they are just comments for human readers.
  12975. */
  12976. #define likely(X) (X)
  12977. #define unlikely(X) (X)
  12978. /************** Include hash.h in the middle of sqliteInt.h ******************/
  12979. /************** Begin file hash.h ********************************************/
  12980. /*
  12981. ** 2001 September 22
  12982. **
  12983. ** The author disclaims copyright to this source code. In place of
  12984. ** a legal notice, here is a blessing:
  12985. **
  12986. ** May you do good and not evil.
  12987. ** May you find forgiveness for yourself and forgive others.
  12988. ** May you share freely, never taking more than you give.
  12989. **
  12990. *************************************************************************
  12991. ** This is the header file for the generic hash-table implementation
  12992. ** used in SQLite.
  12993. */
  12994. #ifndef SQLITE_HASH_H
  12995. #define SQLITE_HASH_H
  12996. /* Forward declarations of structures. */
  12997. typedef struct Hash Hash;
  12998. typedef struct HashElem HashElem;
  12999. /* A complete hash table is an instance of the following structure.
  13000. ** The internals of this structure are intended to be opaque -- client
  13001. ** code should not attempt to access or modify the fields of this structure
  13002. ** directly. Change this structure only by using the routines below.
  13003. ** However, some of the "procedures" and "functions" for modifying and
  13004. ** accessing this structure are really macros, so we can't really make
  13005. ** this structure opaque.
  13006. **
  13007. ** All elements of the hash table are on a single doubly-linked list.
  13008. ** Hash.first points to the head of this list.
  13009. **
  13010. ** There are Hash.htsize buckets. Each bucket points to a spot in
  13011. ** the global doubly-linked list. The contents of the bucket are the
  13012. ** element pointed to plus the next _ht.count-1 elements in the list.
  13013. **
  13014. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  13015. ** by a linear search of the global list. For small tables, the
  13016. ** Hash.ht table is never allocated because if there are few elements
  13017. ** in the table, it is faster to do a linear search than to manage
  13018. ** the hash table.
  13019. */
  13020. struct Hash {
  13021. unsigned int htsize; /* Number of buckets in the hash table */
  13022. unsigned int count; /* Number of entries in this table */
  13023. HashElem *first; /* The first element of the array */
  13024. struct _ht { /* the hash table */
  13025. unsigned int count; /* Number of entries with this hash */
  13026. HashElem *chain; /* Pointer to first entry with this hash */
  13027. } *ht;
  13028. };
  13029. /* Each element in the hash table is an instance of the following
  13030. ** structure. All elements are stored on a single doubly-linked list.
  13031. **
  13032. ** Again, this structure is intended to be opaque, but it can't really
  13033. ** be opaque because it is used by macros.
  13034. */
  13035. struct HashElem {
  13036. HashElem *next, *prev; /* Next and previous elements in the table */
  13037. void *data; /* Data associated with this element */
  13038. const char *pKey; /* Key associated with this element */
  13039. };
  13040. /*
  13041. ** Access routines. To delete, insert a NULL pointer.
  13042. */
  13043. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  13044. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  13045. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  13046. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  13047. /*
  13048. ** Macros for looping over all elements of a hash table. The idiom is
  13049. ** like this:
  13050. **
  13051. ** Hash h;
  13052. ** HashElem *p;
  13053. ** ...
  13054. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  13055. ** SomeStructure *pData = sqliteHashData(p);
  13056. ** // do something with pData
  13057. ** }
  13058. */
  13059. #define sqliteHashFirst(H) ((H)->first)
  13060. #define sqliteHashNext(E) ((E)->next)
  13061. #define sqliteHashData(E) ((E)->data)
  13062. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  13063. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  13064. /*
  13065. ** Number of entries in a hash table
  13066. */
  13067. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  13068. #endif /* SQLITE_HASH_H */
  13069. /************** End of hash.h ************************************************/
  13070. /************** Continuing where we left off in sqliteInt.h ******************/
  13071. /************** Include parse.h in the middle of sqliteInt.h *****************/
  13072. /************** Begin file parse.h *******************************************/
  13073. #define TK_SEMI 1
  13074. #define TK_EXPLAIN 2
  13075. #define TK_QUERY 3
  13076. #define TK_PLAN 4
  13077. #define TK_BEGIN 5
  13078. #define TK_TRANSACTION 6
  13079. #define TK_DEFERRED 7
  13080. #define TK_IMMEDIATE 8
  13081. #define TK_EXCLUSIVE 9
  13082. #define TK_COMMIT 10
  13083. #define TK_END 11
  13084. #define TK_ROLLBACK 12
  13085. #define TK_SAVEPOINT 13
  13086. #define TK_RELEASE 14
  13087. #define TK_TO 15
  13088. #define TK_TABLE 16
  13089. #define TK_CREATE 17
  13090. #define TK_IF 18
  13091. #define TK_NOT 19
  13092. #define TK_EXISTS 20
  13093. #define TK_TEMP 21
  13094. #define TK_LP 22
  13095. #define TK_RP 23
  13096. #define TK_AS 24
  13097. #define TK_WITHOUT 25
  13098. #define TK_COMMA 26
  13099. #define TK_ABORT 27
  13100. #define TK_ACTION 28
  13101. #define TK_AFTER 29
  13102. #define TK_ANALYZE 30
  13103. #define TK_ASC 31
  13104. #define TK_ATTACH 32
  13105. #define TK_BEFORE 33
  13106. #define TK_BY 34
  13107. #define TK_CASCADE 35
  13108. #define TK_CAST 36
  13109. #define TK_CONFLICT 37
  13110. #define TK_DATABASE 38
  13111. #define TK_DESC 39
  13112. #define TK_DETACH 40
  13113. #define TK_EACH 41
  13114. #define TK_FAIL 42
  13115. #define TK_OR 43
  13116. #define TK_AND 44
  13117. #define TK_IS 45
  13118. #define TK_MATCH 46
  13119. #define TK_LIKE_KW 47
  13120. #define TK_BETWEEN 48
  13121. #define TK_IN 49
  13122. #define TK_ISNULL 50
  13123. #define TK_NOTNULL 51
  13124. #define TK_NE 52
  13125. #define TK_EQ 53
  13126. #define TK_GT 54
  13127. #define TK_LE 55
  13128. #define TK_LT 56
  13129. #define TK_GE 57
  13130. #define TK_ESCAPE 58
  13131. #define TK_ID 59
  13132. #define TK_COLUMNKW 60
  13133. #define TK_DO 61
  13134. #define TK_FOR 62
  13135. #define TK_IGNORE 63
  13136. #define TK_INITIALLY 64
  13137. #define TK_INSTEAD 65
  13138. #define TK_NO 66
  13139. #define TK_KEY 67
  13140. #define TK_OF 68
  13141. #define TK_OFFSET 69
  13142. #define TK_PRAGMA 70
  13143. #define TK_RAISE 71
  13144. #define TK_RECURSIVE 72
  13145. #define TK_REPLACE 73
  13146. #define TK_RESTRICT 74
  13147. #define TK_ROW 75
  13148. #define TK_ROWS 76
  13149. #define TK_TRIGGER 77
  13150. #define TK_VACUUM 78
  13151. #define TK_VIEW 79
  13152. #define TK_VIRTUAL 80
  13153. #define TK_WITH 81
  13154. #define TK_CURRENT 82
  13155. #define TK_FOLLOWING 83
  13156. #define TK_PARTITION 84
  13157. #define TK_PRECEDING 85
  13158. #define TK_RANGE 86
  13159. #define TK_UNBOUNDED 87
  13160. #define TK_EXCLUDE 88
  13161. #define TK_GROUPS 89
  13162. #define TK_OTHERS 90
  13163. #define TK_TIES 91
  13164. #define TK_REINDEX 92
  13165. #define TK_RENAME 93
  13166. #define TK_CTIME_KW 94
  13167. #define TK_ANY 95
  13168. #define TK_BITAND 96
  13169. #define TK_BITOR 97
  13170. #define TK_LSHIFT 98
  13171. #define TK_RSHIFT 99
  13172. #define TK_PLUS 100
  13173. #define TK_MINUS 101
  13174. #define TK_STAR 102
  13175. #define TK_SLASH 103
  13176. #define TK_REM 104
  13177. #define TK_CONCAT 105
  13178. #define TK_COLLATE 106
  13179. #define TK_BITNOT 107
  13180. #define TK_ON 108
  13181. #define TK_INDEXED 109
  13182. #define TK_STRING 110
  13183. #define TK_JOIN_KW 111
  13184. #define TK_CONSTRAINT 112
  13185. #define TK_DEFAULT 113
  13186. #define TK_NULL 114
  13187. #define TK_PRIMARY 115
  13188. #define TK_UNIQUE 116
  13189. #define TK_CHECK 117
  13190. #define TK_REFERENCES 118
  13191. #define TK_AUTOINCR 119
  13192. #define TK_INSERT 120
  13193. #define TK_DELETE 121
  13194. #define TK_UPDATE 122
  13195. #define TK_SET 123
  13196. #define TK_DEFERRABLE 124
  13197. #define TK_FOREIGN 125
  13198. #define TK_DROP 126
  13199. #define TK_UNION 127
  13200. #define TK_ALL 128
  13201. #define TK_EXCEPT 129
  13202. #define TK_INTERSECT 130
  13203. #define TK_SELECT 131
  13204. #define TK_VALUES 132
  13205. #define TK_DISTINCT 133
  13206. #define TK_DOT 134
  13207. #define TK_FROM 135
  13208. #define TK_JOIN 136
  13209. #define TK_USING 137
  13210. #define TK_ORDER 138
  13211. #define TK_GROUP 139
  13212. #define TK_HAVING 140
  13213. #define TK_LIMIT 141
  13214. #define TK_WHERE 142
  13215. #define TK_INTO 143
  13216. #define TK_NOTHING 144
  13217. #define TK_FLOAT 145
  13218. #define TK_BLOB 146
  13219. #define TK_INTEGER 147
  13220. #define TK_VARIABLE 148
  13221. #define TK_CASE 149
  13222. #define TK_WHEN 150
  13223. #define TK_THEN 151
  13224. #define TK_ELSE 152
  13225. #define TK_INDEX 153
  13226. #define TK_ALTER 154
  13227. #define TK_ADD 155
  13228. #define TK_WINDOW 156
  13229. #define TK_OVER 157
  13230. #define TK_FILTER 158
  13231. #define TK_TRUEFALSE 159
  13232. #define TK_ISNOT 160
  13233. #define TK_FUNCTION 161
  13234. #define TK_COLUMN 162
  13235. #define TK_AGG_FUNCTION 163
  13236. #define TK_AGG_COLUMN 164
  13237. #define TK_UMINUS 165
  13238. #define TK_UPLUS 166
  13239. #define TK_TRUTH 167
  13240. #define TK_REGISTER 168
  13241. #define TK_VECTOR 169
  13242. #define TK_SELECT_COLUMN 170
  13243. #define TK_IF_NULL_ROW 171
  13244. #define TK_ASTERISK 172
  13245. #define TK_SPAN 173
  13246. #define TK_SPACE 174
  13247. #define TK_ILLEGAL 175
  13248. /************** End of parse.h ***********************************************/
  13249. /************** Continuing where we left off in sqliteInt.h ******************/
  13250. #include <stdio.h>
  13251. #include <stdlib.h>
  13252. #include <string.h>
  13253. #include <assert.h>
  13254. #include <stddef.h>
  13255. /*
  13256. ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
  13257. ** This allows better measurements of where memcpy() is used when running
  13258. ** cachegrind. But this macro version of memcpy() is very slow so it
  13259. ** should not be used in production. This is a performance measurement
  13260. ** hack only.
  13261. */
  13262. #ifdef SQLITE_INLINE_MEMCPY
  13263. # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
  13264. int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
  13265. #endif
  13266. /*
  13267. ** If compiling for a processor that lacks floating point support,
  13268. ** substitute integer for floating-point
  13269. */
  13270. #ifdef SQLITE_OMIT_FLOATING_POINT
  13271. # define double sqlite_int64
  13272. # define float sqlite_int64
  13273. # define LONGDOUBLE_TYPE sqlite_int64
  13274. # ifndef SQLITE_BIG_DBL
  13275. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  13276. # endif
  13277. # define SQLITE_OMIT_DATETIME_FUNCS 1
  13278. # define SQLITE_OMIT_TRACE 1
  13279. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  13280. # undef SQLITE_HAVE_ISNAN
  13281. #endif
  13282. #ifndef SQLITE_BIG_DBL
  13283. # define SQLITE_BIG_DBL (1e99)
  13284. #endif
  13285. /*
  13286. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  13287. ** afterward. Having this macro allows us to cause the C compiler
  13288. ** to omit code used by TEMP tables without messy #ifndef statements.
  13289. */
  13290. #ifdef SQLITE_OMIT_TEMPDB
  13291. #define OMIT_TEMPDB 1
  13292. #else
  13293. #define OMIT_TEMPDB 0
  13294. #endif
  13295. /*
  13296. ** The "file format" number is an integer that is incremented whenever
  13297. ** the VDBE-level file format changes. The following macros define the
  13298. ** the default file format for new databases and the maximum file format
  13299. ** that the library can read.
  13300. */
  13301. #define SQLITE_MAX_FILE_FORMAT 4
  13302. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  13303. # define SQLITE_DEFAULT_FILE_FORMAT 4
  13304. #endif
  13305. /*
  13306. ** Determine whether triggers are recursive by default. This can be
  13307. ** changed at run-time using a pragma.
  13308. */
  13309. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  13310. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  13311. #endif
  13312. /*
  13313. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  13314. ** on the command-line
  13315. */
  13316. #ifndef SQLITE_TEMP_STORE
  13317. # define SQLITE_TEMP_STORE 1
  13318. #endif
  13319. /*
  13320. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  13321. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  13322. ** to zero.
  13323. */
  13324. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  13325. # undef SQLITE_MAX_WORKER_THREADS
  13326. # define SQLITE_MAX_WORKER_THREADS 0
  13327. #endif
  13328. #ifndef SQLITE_MAX_WORKER_THREADS
  13329. # define SQLITE_MAX_WORKER_THREADS 8
  13330. #endif
  13331. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  13332. # define SQLITE_DEFAULT_WORKER_THREADS 0
  13333. #endif
  13334. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  13335. # undef SQLITE_MAX_WORKER_THREADS
  13336. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  13337. #endif
  13338. /*
  13339. ** The default initial allocation for the pagecache when using separate
  13340. ** pagecaches for each database connection. A positive number is the
  13341. ** number of pages. A negative number N translations means that a buffer
  13342. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  13343. **
  13344. ** The default value of "20" was choosen to minimize the run-time of the
  13345. ** speedtest1 test program with options: --shrink-memory --reprepare
  13346. */
  13347. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  13348. # define SQLITE_DEFAULT_PCACHE_INITSZ 20
  13349. #endif
  13350. /*
  13351. ** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
  13352. */
  13353. #ifndef SQLITE_DEFAULT_SORTERREF_SIZE
  13354. # define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
  13355. #endif
  13356. /*
  13357. ** The compile-time options SQLITE_MMAP_READWRITE and
  13358. ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
  13359. ** You must choose one or the other (or neither) but not both.
  13360. */
  13361. #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  13362. #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  13363. #endif
  13364. /*
  13365. ** GCC does not define the offsetof() macro so we'll have to do it
  13366. ** ourselves.
  13367. */
  13368. #ifndef offsetof
  13369. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  13370. #endif
  13371. /*
  13372. ** Macros to compute minimum and maximum of two numbers.
  13373. */
  13374. #ifndef MIN
  13375. # define MIN(A,B) ((A)<(B)?(A):(B))
  13376. #endif
  13377. #ifndef MAX
  13378. # define MAX(A,B) ((A)>(B)?(A):(B))
  13379. #endif
  13380. /*
  13381. ** Swap two objects of type TYPE.
  13382. */
  13383. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  13384. /*
  13385. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  13386. ** not, there are still machines out there that use EBCDIC.)
  13387. */
  13388. #if 'A' == '\301'
  13389. # define SQLITE_EBCDIC 1
  13390. #else
  13391. # define SQLITE_ASCII 1
  13392. #endif
  13393. /*
  13394. ** Integers of known sizes. These typedefs might change for architectures
  13395. ** where the sizes very. Preprocessor macros are available so that the
  13396. ** types can be conveniently redefined at compile-type. Like this:
  13397. **
  13398. ** cc '-DUINTPTR_TYPE=long long int' ...
  13399. */
  13400. #ifndef UINT32_TYPE
  13401. # ifdef HAVE_UINT32_T
  13402. # define UINT32_TYPE uint32_t
  13403. # else
  13404. # define UINT32_TYPE unsigned int
  13405. # endif
  13406. #endif
  13407. #ifndef UINT16_TYPE
  13408. # ifdef HAVE_UINT16_T
  13409. # define UINT16_TYPE uint16_t
  13410. # else
  13411. # define UINT16_TYPE unsigned short int
  13412. # endif
  13413. #endif
  13414. #ifndef INT16_TYPE
  13415. # ifdef HAVE_INT16_T
  13416. # define INT16_TYPE int16_t
  13417. # else
  13418. # define INT16_TYPE short int
  13419. # endif
  13420. #endif
  13421. #ifndef UINT8_TYPE
  13422. # ifdef HAVE_UINT8_T
  13423. # define UINT8_TYPE uint8_t
  13424. # else
  13425. # define UINT8_TYPE unsigned char
  13426. # endif
  13427. #endif
  13428. #ifndef INT8_TYPE
  13429. # ifdef HAVE_INT8_T
  13430. # define INT8_TYPE int8_t
  13431. # else
  13432. # define INT8_TYPE signed char
  13433. # endif
  13434. #endif
  13435. #ifndef LONGDOUBLE_TYPE
  13436. # define LONGDOUBLE_TYPE long double
  13437. #endif
  13438. typedef sqlite_int64 i64; /* 8-byte signed integer */
  13439. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  13440. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  13441. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  13442. typedef INT16_TYPE i16; /* 2-byte signed integer */
  13443. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  13444. typedef INT8_TYPE i8; /* 1-byte signed integer */
  13445. /*
  13446. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  13447. ** that can be stored in a u32 without loss of data. The value
  13448. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  13449. ** have to specify the value in the less intuitive manner shown:
  13450. */
  13451. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  13452. /*
  13453. ** The datatype used to store estimates of the number of rows in a
  13454. ** table or index. This is an unsigned integer type. For 99.9% of
  13455. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  13456. ** can be used at compile-time if desired.
  13457. */
  13458. #ifdef SQLITE_64BIT_STATS
  13459. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  13460. #else
  13461. typedef u32 tRowcnt; /* 32-bit is the default */
  13462. #endif
  13463. /*
  13464. ** Estimated quantities used for query planning are stored as 16-bit
  13465. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  13466. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  13467. ** But the allowed values are "grainy". Not every value is representable.
  13468. ** For example, quantities 16 and 17 are both represented by a LogEst
  13469. ** of 40. However, since LogEst quantities are suppose to be estimates,
  13470. ** not exact values, this imprecision is not a problem.
  13471. **
  13472. ** "LogEst" is short for "Logarithmic Estimate".
  13473. **
  13474. ** Examples:
  13475. ** 1 -> 0 20 -> 43 10000 -> 132
  13476. ** 2 -> 10 25 -> 46 25000 -> 146
  13477. ** 3 -> 16 100 -> 66 1000000 -> 199
  13478. ** 4 -> 20 1000 -> 99 1048576 -> 200
  13479. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  13480. **
  13481. ** The LogEst can be negative to indicate fractional values.
  13482. ** Examples:
  13483. **
  13484. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  13485. */
  13486. typedef INT16_TYPE LogEst;
  13487. /*
  13488. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  13489. */
  13490. #ifndef SQLITE_PTRSIZE
  13491. # if defined(__SIZEOF_POINTER__)
  13492. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  13493. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  13494. defined(_M_ARM) || defined(__arm__) || defined(__x86) || \
  13495. (defined(__TOS_AIX__) && !defined(__64BIT__))
  13496. # define SQLITE_PTRSIZE 4
  13497. # else
  13498. # define SQLITE_PTRSIZE 8
  13499. # endif
  13500. #endif
  13501. /* The uptr type is an unsigned integer large enough to hold a pointer
  13502. */
  13503. #if defined(HAVE_STDINT_H)
  13504. typedef uintptr_t uptr;
  13505. #elif SQLITE_PTRSIZE==4
  13506. typedef u32 uptr;
  13507. #else
  13508. typedef u64 uptr;
  13509. #endif
  13510. /*
  13511. ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  13512. ** something between S (inclusive) and E (exclusive).
  13513. **
  13514. ** In other words, S is a buffer and E is a pointer to the first byte after
  13515. ** the end of buffer S. This macro returns true if P points to something
  13516. ** contained within the buffer S.
  13517. */
  13518. #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
  13519. /*
  13520. ** Macros to determine whether the machine is big or little endian,
  13521. ** and whether or not that determination is run-time or compile-time.
  13522. **
  13523. ** For best performance, an attempt is made to guess at the byte-order
  13524. ** using C-preprocessor macros. If that is unsuccessful, or if
  13525. ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
  13526. ** at run-time.
  13527. */
  13528. #ifndef SQLITE_BYTEORDER
  13529. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  13530. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  13531. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  13532. defined(__arm__) || defined(_M_ARM64)
  13533. # define SQLITE_BYTEORDER 1234
  13534. # elif defined(sparc) || defined(__ppc__)
  13535. # define SQLITE_BYTEORDER 4321
  13536. # else
  13537. # define SQLITE_BYTEORDER 0
  13538. # endif
  13539. #endif
  13540. #if SQLITE_BYTEORDER==4321
  13541. # define SQLITE_BIGENDIAN 1
  13542. # define SQLITE_LITTLEENDIAN 0
  13543. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  13544. #elif SQLITE_BYTEORDER==1234
  13545. # define SQLITE_BIGENDIAN 0
  13546. # define SQLITE_LITTLEENDIAN 1
  13547. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  13548. #else
  13549. # ifdef SQLITE_AMALGAMATION
  13550. const int sqlite3one = 1;
  13551. # else
  13552. extern const int sqlite3one;
  13553. # endif
  13554. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  13555. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  13556. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  13557. #endif
  13558. /*
  13559. ** Constants for the largest and smallest possible 64-bit signed integers.
  13560. ** These macros are designed to work correctly on both 32-bit and 64-bit
  13561. ** compilers.
  13562. */
  13563. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  13564. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  13565. /*
  13566. ** Round up a number to the next larger multiple of 8. This is used
  13567. ** to force 8-byte alignment on 64-bit architectures.
  13568. */
  13569. #define ROUND8(x) (((x)+7)&~7)
  13570. /*
  13571. ** Round down to the nearest multiple of 8
  13572. */
  13573. #define ROUNDDOWN8(x) ((x)&~7)
  13574. /*
  13575. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  13576. ** macro is used only within assert() to verify that the code gets
  13577. ** all alignment restrictions correct.
  13578. **
  13579. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  13580. ** underlying malloc() implementation might return us 4-byte aligned
  13581. ** pointers. In that case, only verify 4-byte alignment.
  13582. */
  13583. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  13584. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  13585. #else
  13586. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  13587. #endif
  13588. /*
  13589. ** Disable MMAP on platforms where it is known to not work
  13590. */
  13591. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  13592. # undef SQLITE_MAX_MMAP_SIZE
  13593. # define SQLITE_MAX_MMAP_SIZE 0
  13594. #endif
  13595. /*
  13596. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  13597. */
  13598. #ifdef __APPLE__
  13599. # include <TargetConditionals.h>
  13600. #endif
  13601. #ifndef SQLITE_MAX_MMAP_SIZE
  13602. # if defined(__linux__) \
  13603. || defined(_WIN32) \
  13604. || (defined(__APPLE__) && defined(__MACH__)) \
  13605. || defined(__sun) \
  13606. || defined(__FreeBSD__) \
  13607. || defined(__DragonFly__)
  13608. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  13609. # else
  13610. # define SQLITE_MAX_MMAP_SIZE 0
  13611. # endif
  13612. #endif
  13613. /*
  13614. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  13615. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  13616. ** not exceed the maximum mmap size.
  13617. */
  13618. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  13619. # define SQLITE_DEFAULT_MMAP_SIZE 0
  13620. #endif
  13621. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  13622. # undef SQLITE_DEFAULT_MMAP_SIZE
  13623. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  13624. #endif
  13625. /*
  13626. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  13627. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  13628. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  13629. */
  13630. #ifdef SQLITE_ENABLE_STAT4
  13631. # undef SQLITE_ENABLE_STAT3
  13632. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  13633. #elif SQLITE_ENABLE_STAT3
  13634. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  13635. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  13636. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  13637. #endif
  13638. /*
  13639. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  13640. ** the Select query generator tracing logic is turned on.
  13641. */
  13642. #if defined(SQLITE_ENABLE_SELECTTRACE)
  13643. # define SELECTTRACE_ENABLED 1
  13644. #else
  13645. # define SELECTTRACE_ENABLED 0
  13646. #endif
  13647. /*
  13648. ** An instance of the following structure is used to store the busy-handler
  13649. ** callback for a given sqlite handle.
  13650. **
  13651. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  13652. ** callback for the database handle. Each pager opened via the sqlite
  13653. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  13654. ** callback is currently invoked only from within pager.c.
  13655. */
  13656. typedef struct BusyHandler BusyHandler;
  13657. struct BusyHandler {
  13658. int (*xBusyHandler)(void *,int); /* The busy callback */
  13659. void *pBusyArg; /* First arg to busy callback */
  13660. int nBusy; /* Incremented with each busy call */
  13661. u8 bExtraFileArg; /* Include sqlite3_file as callback arg */
  13662. };
  13663. /*
  13664. ** Name of the master database table. The master database table
  13665. ** is a special table that holds the names and attributes of all
  13666. ** user tables and indices.
  13667. */
  13668. #define MASTER_NAME "sqlite_master"
  13669. #define TEMP_MASTER_NAME "sqlite_temp_master"
  13670. /*
  13671. ** The root-page of the master database table.
  13672. */
  13673. #define MASTER_ROOT 1
  13674. /*
  13675. ** The name of the schema table.
  13676. */
  13677. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  13678. /*
  13679. ** A convenience macro that returns the number of elements in
  13680. ** an array.
  13681. */
  13682. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  13683. /*
  13684. ** Determine if the argument is a power of two
  13685. */
  13686. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  13687. /*
  13688. ** The following value as a destructor means to use sqlite3DbFree().
  13689. ** The sqlite3DbFree() routine requires two parameters instead of the
  13690. ** one parameter that destructors normally want. So we have to introduce
  13691. ** this magic value that the code knows to handle differently. Any
  13692. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  13693. ** and SQLITE_TRANSIENT.
  13694. */
  13695. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  13696. /*
  13697. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  13698. ** not support Writable Static Data (WSD) such as global and static variables.
  13699. ** All variables must either be on the stack or dynamically allocated from
  13700. ** the heap. When WSD is unsupported, the variable declarations scattered
  13701. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  13702. ** macro is used for this purpose. And instead of referencing the variable
  13703. ** directly, we use its constant as a key to lookup the run-time allocated
  13704. ** buffer that holds real variable. The constant is also the initializer
  13705. ** for the run-time allocated buffer.
  13706. **
  13707. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  13708. ** macros become no-ops and have zero performance impact.
  13709. */
  13710. #ifdef SQLITE_OMIT_WSD
  13711. #define SQLITE_WSD const
  13712. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  13713. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  13714. SQLITE_API int sqlite3_wsd_init(int N, int J);
  13715. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  13716. #else
  13717. #define SQLITE_WSD
  13718. #define GLOBAL(t,v) v
  13719. #define sqlite3GlobalConfig sqlite3Config
  13720. #endif
  13721. /*
  13722. ** The following macros are used to suppress compiler warnings and to
  13723. ** make it clear to human readers when a function parameter is deliberately
  13724. ** left unused within the body of a function. This usually happens when
  13725. ** a function is called via a function pointer. For example the
  13726. ** implementation of an SQL aggregate step callback may not use the
  13727. ** parameter indicating the number of arguments passed to the aggregate,
  13728. ** if it knows that this is enforced elsewhere.
  13729. **
  13730. ** When a function parameter is not used at all within the body of a function,
  13731. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  13732. ** However, these macros may also be used to suppress warnings related to
  13733. ** parameters that may or may not be used depending on compilation options.
  13734. ** For example those parameters only used in assert() statements. In these
  13735. ** cases the parameters are named as per the usual conventions.
  13736. */
  13737. #define UNUSED_PARAMETER(x) (void)(x)
  13738. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  13739. /*
  13740. ** Forward references to structures
  13741. */
  13742. typedef struct AggInfo AggInfo;
  13743. typedef struct AuthContext AuthContext;
  13744. typedef struct AutoincInfo AutoincInfo;
  13745. typedef struct Bitvec Bitvec;
  13746. typedef struct CollSeq CollSeq;
  13747. typedef struct Column Column;
  13748. typedef struct Db Db;
  13749. typedef struct Schema Schema;
  13750. typedef struct Expr Expr;
  13751. typedef struct ExprList ExprList;
  13752. typedef struct FKey FKey;
  13753. typedef struct FuncDestructor FuncDestructor;
  13754. typedef struct FuncDef FuncDef;
  13755. typedef struct FuncDefHash FuncDefHash;
  13756. typedef struct IdList IdList;
  13757. typedef struct Index Index;
  13758. typedef struct IndexSample IndexSample;
  13759. typedef struct KeyClass KeyClass;
  13760. typedef struct KeyInfo KeyInfo;
  13761. typedef struct Lookaside Lookaside;
  13762. typedef struct LookasideSlot LookasideSlot;
  13763. typedef struct Module Module;
  13764. typedef struct NameContext NameContext;
  13765. typedef struct Parse Parse;
  13766. typedef struct PreUpdate PreUpdate;
  13767. typedef struct PrintfArguments PrintfArguments;
  13768. typedef struct RenameToken RenameToken;
  13769. typedef struct RowSet RowSet;
  13770. typedef struct Savepoint Savepoint;
  13771. typedef struct Select Select;
  13772. typedef struct SQLiteThread SQLiteThread;
  13773. typedef struct SelectDest SelectDest;
  13774. typedef struct SrcList SrcList;
  13775. typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
  13776. typedef struct Table Table;
  13777. typedef struct TableLock TableLock;
  13778. typedef struct Token Token;
  13779. typedef struct TreeView TreeView;
  13780. typedef struct Trigger Trigger;
  13781. typedef struct TriggerPrg TriggerPrg;
  13782. typedef struct TriggerStep TriggerStep;
  13783. typedef struct UnpackedRecord UnpackedRecord;
  13784. typedef struct Upsert Upsert;
  13785. typedef struct VTable VTable;
  13786. typedef struct VtabCtx VtabCtx;
  13787. typedef struct Walker Walker;
  13788. typedef struct WhereInfo WhereInfo;
  13789. typedef struct Window Window;
  13790. typedef struct With With;
  13791. /*
  13792. ** The bitmask datatype defined below is used for various optimizations.
  13793. **
  13794. ** Changing this from a 64-bit to a 32-bit type limits the number of
  13795. ** tables in a join to 32 instead of 64. But it also reduces the size
  13796. ** of the library by 738 bytes on ix86.
  13797. */
  13798. #ifdef SQLITE_BITMASK_TYPE
  13799. typedef SQLITE_BITMASK_TYPE Bitmask;
  13800. #else
  13801. typedef u64 Bitmask;
  13802. #endif
  13803. /*
  13804. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  13805. */
  13806. #define BMS ((int)(sizeof(Bitmask)*8))
  13807. /*
  13808. ** A bit in a Bitmask
  13809. */
  13810. #define MASKBIT(n) (((Bitmask)1)<<(n))
  13811. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  13812. #define ALLBITS ((Bitmask)-1)
  13813. /* A VList object records a mapping between parameters/variables/wildcards
  13814. ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
  13815. ** variable number associated with that parameter. See the format description
  13816. ** on the sqlite3VListAdd() routine for more information. A VList is really
  13817. ** just an array of integers.
  13818. */
  13819. typedef int VList;
  13820. /*
  13821. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  13822. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  13823. ** pointer types (i.e. FuncDef) defined above.
  13824. */
  13825. /************** Include btree.h in the middle of sqliteInt.h *****************/
  13826. /************** Begin file btree.h *******************************************/
  13827. /*
  13828. ** 2001 September 15
  13829. **
  13830. ** The author disclaims copyright to this source code. In place of
  13831. ** a legal notice, here is a blessing:
  13832. **
  13833. ** May you do good and not evil.
  13834. ** May you find forgiveness for yourself and forgive others.
  13835. ** May you share freely, never taking more than you give.
  13836. **
  13837. *************************************************************************
  13838. ** This header file defines the interface that the sqlite B-Tree file
  13839. ** subsystem. See comments in the source code for a detailed description
  13840. ** of what each interface routine does.
  13841. */
  13842. #ifndef SQLITE_BTREE_H
  13843. #define SQLITE_BTREE_H
  13844. /* TODO: This definition is just included so other modules compile. It
  13845. ** needs to be revisited.
  13846. */
  13847. #define SQLITE_N_BTREE_META 16
  13848. /*
  13849. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  13850. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  13851. */
  13852. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  13853. #define SQLITE_DEFAULT_AUTOVACUUM 0
  13854. #endif
  13855. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  13856. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  13857. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  13858. /*
  13859. ** Forward declarations of structure
  13860. */
  13861. typedef struct Btree Btree;
  13862. typedef struct BtCursor BtCursor;
  13863. typedef struct BtShared BtShared;
  13864. typedef struct BtreePayload BtreePayload;
  13865. SQLITE_PRIVATE int sqlite3BtreeOpen(
  13866. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  13867. const char *zFilename, /* Name of database file to open */
  13868. sqlite3 *db, /* Associated database connection */
  13869. Btree **ppBtree, /* Return open Btree* here */
  13870. int flags, /* Flags */
  13871. int vfsFlags /* Flags passed through to VFS open */
  13872. );
  13873. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  13874. ** following values.
  13875. **
  13876. ** NOTE: These values must match the corresponding PAGER_ values in
  13877. ** pager.h.
  13878. */
  13879. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  13880. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  13881. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  13882. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  13883. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  13884. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  13885. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
  13886. #if SQLITE_MAX_MMAP_SIZE>0
  13887. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  13888. #endif
  13889. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  13890. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  13891. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  13892. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  13893. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  13894. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  13895. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  13896. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  13897. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  13898. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  13899. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);
  13900. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  13901. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  13902. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  13903. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  13904. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  13905. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  13906. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  13907. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  13908. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  13909. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  13910. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  13911. #ifndef SQLITE_OMIT_SHARED_CACHE
  13912. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  13913. #endif
  13914. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  13915. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  13916. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  13917. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  13918. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  13919. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  13920. ** of the flags shown below.
  13921. **
  13922. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  13923. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  13924. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  13925. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  13926. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  13927. ** indices.)
  13928. */
  13929. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  13930. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  13931. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  13932. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  13933. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  13934. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  13935. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  13936. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  13937. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  13938. /*
  13939. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  13940. ** should be one of the following values. The integer values are assigned
  13941. ** to constants so that the offset of the corresponding field in an
  13942. ** SQLite database header may be found using the following formula:
  13943. **
  13944. ** offset = 36 + (idx * 4)
  13945. **
  13946. ** For example, the free-page-count field is located at byte offset 36 of
  13947. ** the database file header. The incr-vacuum-flag field is located at
  13948. ** byte offset 64 (== 36+4*7).
  13949. **
  13950. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  13951. ** It is a read-only number computed by the pager. But we merge it with
  13952. ** the header value access routines since its access pattern is the same.
  13953. ** Call it a "virtual meta value".
  13954. */
  13955. #define BTREE_FREE_PAGE_COUNT 0
  13956. #define BTREE_SCHEMA_VERSION 1
  13957. #define BTREE_FILE_FORMAT 2
  13958. #define BTREE_DEFAULT_CACHE_SIZE 3
  13959. #define BTREE_LARGEST_ROOT_PAGE 4
  13960. #define BTREE_TEXT_ENCODING 5
  13961. #define BTREE_USER_VERSION 6
  13962. #define BTREE_INCR_VACUUM 7
  13963. #define BTREE_APPLICATION_ID 8
  13964. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  13965. /*
  13966. ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
  13967. ** interface.
  13968. **
  13969. ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
  13970. **
  13971. ** The first argument is an Expr* (which is guaranteed to be constant for
  13972. ** the lifetime of the cursor) that defines constraints on which rows
  13973. ** might be fetched with this cursor. The Expr* tree may contain
  13974. ** TK_REGISTER nodes that refer to values stored in the array of registers
  13975. ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
  13976. ** then the value of the node is the value in Mem[pExpr.iTable]. Any
  13977. ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
  13978. ** column of the b-tree of the cursor. The Expr tree will not contain
  13979. ** any function calls nor subqueries nor references to b-trees other than
  13980. ** the cursor being hinted.
  13981. **
  13982. ** The design of the _RANGE hint is aid b-tree implementations that try
  13983. ** to prefetch content from remote machines - to provide those
  13984. ** implementations with limits on what needs to be prefetched and thereby
  13985. ** reduce network bandwidth.
  13986. **
  13987. ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
  13988. ** standard SQLite. The other hints are provided for extentions that use
  13989. ** the SQLite parser and code generator but substitute their own storage
  13990. ** engine.
  13991. */
  13992. #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
  13993. /*
  13994. ** Values that may be OR'd together to form the argument to the
  13995. ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
  13996. **
  13997. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  13998. ** to be filled with content that is already in sorted order.
  13999. **
  14000. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  14001. ** OP_SeekLE opcodes for a range search, but where the range of entries
  14002. ** selected will all have the same key. In other words, the cursor will
  14003. ** be used only for equality key searches.
  14004. **
  14005. */
  14006. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  14007. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  14008. /*
  14009. ** Flags passed as the third argument to sqlite3BtreeCursor().
  14010. **
  14011. ** For read-only cursors the wrFlag argument is always zero. For read-write
  14012. ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
  14013. ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
  14014. ** only be used by SQLite for the following:
  14015. **
  14016. ** * to seek to and then delete specific entries, and/or
  14017. **
  14018. ** * to read values that will be used to create keys that other
  14019. ** BTREE_FORDELETE cursors will seek to and delete.
  14020. **
  14021. ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
  14022. ** by this, the native b-tree engine of SQLite, but it is available to
  14023. ** alternative storage engines that might be substituted in place of this
  14024. ** b-tree system. For alternative storage engines in which a delete of
  14025. ** the main table row automatically deletes corresponding index rows,
  14026. ** the FORDELETE flag hint allows those alternative storage engines to
  14027. ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
  14028. ** and DELETE operations as no-ops, and any READ operation against a
  14029. ** FORDELETE cursor may return a null row: 0x01 0x00.
  14030. */
  14031. #define BTREE_WRCSR 0x00000004 /* read-write cursor */
  14032. #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
  14033. SQLITE_PRIVATE int sqlite3BtreeCursor(
  14034. Btree*, /* BTree containing table to open */
  14035. int iTable, /* Index of root page */
  14036. int wrFlag, /* 1 for writing. 0 for read-only */
  14037. struct KeyInfo*, /* First argument to compare function */
  14038. BtCursor *pCursor /* Space to write cursor structure */
  14039. );
  14040. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
  14041. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  14042. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  14043. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
  14044. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  14045. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
  14046. #endif
  14047. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  14048. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  14049. BtCursor*,
  14050. UnpackedRecord *pUnKey,
  14051. i64 intKey,
  14052. int bias,
  14053. int *pRes
  14054. );
  14055. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  14056. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  14057. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
  14058. /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
  14059. #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
  14060. #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
  14061. #define BTREE_APPEND 0x08 /* Insert is likely an append */
  14062. /* An instance of the BtreePayload object describes the content of a single
  14063. ** entry in either an index or table btree.
  14064. **
  14065. ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
  14066. ** an arbitrary key and no data. These btrees have pKey,nKey set to the
  14067. ** key and the pData,nData,nZero fields are uninitialized. The aMem,nMem
  14068. ** fields give an array of Mem objects that are a decomposition of the key.
  14069. ** The nMem field might be zero, indicating that no decomposition is available.
  14070. **
  14071. ** Table btrees (used for rowid tables) contain an integer rowid used as
  14072. ** the key and passed in the nKey field. The pKey field is zero.
  14073. ** pData,nData hold the content of the new entry. nZero extra zero bytes
  14074. ** are appended to the end of the content when constructing the entry.
  14075. ** The aMem,nMem fields are uninitialized for table btrees.
  14076. **
  14077. ** Field usage summary:
  14078. **
  14079. ** Table BTrees Index Btrees
  14080. **
  14081. ** pKey always NULL encoded key
  14082. ** nKey the ROWID length of pKey
  14083. ** pData data not used
  14084. ** aMem not used decomposed key value
  14085. ** nMem not used entries in aMem
  14086. ** nData length of pData not used
  14087. ** nZero extra zeros after pData not used
  14088. **
  14089. ** This object is used to pass information into sqlite3BtreeInsert(). The
  14090. ** same information used to be passed as five separate parameters. But placing
  14091. ** the information into this object helps to keep the interface more
  14092. ** organized and understandable, and it also helps the resulting code to
  14093. ** run a little faster by using fewer registers for parameter passing.
  14094. */
  14095. struct BtreePayload {
  14096. const void *pKey; /* Key content for indexes. NULL for tables */
  14097. sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
  14098. const void *pData; /* Data for tables. */
  14099. sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
  14100. u16 nMem; /* Number of aMem[] value. Might be zero */
  14101. int nData; /* Size of pData. 0 if none. */
  14102. int nZero; /* Extra zero data appended after pData,nData */
  14103. };
  14104. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
  14105. int flags, int seekResult);
  14106. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  14107. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  14108. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
  14109. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  14110. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
  14111. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
  14112. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  14113. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
  14114. #endif
  14115. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
  14116. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
  14117. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
  14118. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);
  14119. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  14120. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  14121. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
  14122. #ifndef SQLITE_OMIT_INCRBLOB
  14123. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
  14124. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  14125. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  14126. #endif
  14127. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  14128. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  14129. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  14130. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  14131. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  14132. #ifndef NDEBUG
  14133. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  14134. #endif
  14135. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
  14136. #ifndef SQLITE_OMIT_BTREECOUNT
  14137. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  14138. #endif
  14139. #ifdef SQLITE_TEST
  14140. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  14141. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  14142. #endif
  14143. #ifndef SQLITE_OMIT_WAL
  14144. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  14145. #endif
  14146. /*
  14147. ** If we are not using shared cache, then there is no need to
  14148. ** use mutexes to access the BtShared structures. So make the
  14149. ** Enter and Leave procedures no-ops.
  14150. */
  14151. #ifndef SQLITE_OMIT_SHARED_CACHE
  14152. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  14153. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  14154. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  14155. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  14156. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
  14157. #else
  14158. # define sqlite3BtreeEnter(X)
  14159. # define sqlite3BtreeEnterAll(X)
  14160. # define sqlite3BtreeSharable(X) 0
  14161. # define sqlite3BtreeEnterCursor(X)
  14162. # define sqlite3BtreeConnectionCount(X) 1
  14163. #endif
  14164. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  14165. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  14166. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  14167. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  14168. #ifndef NDEBUG
  14169. /* These routines are used inside assert() statements only. */
  14170. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  14171. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  14172. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  14173. #endif
  14174. #else
  14175. # define sqlite3BtreeLeave(X)
  14176. # define sqlite3BtreeLeaveCursor(X)
  14177. # define sqlite3BtreeLeaveAll(X)
  14178. # define sqlite3BtreeHoldsMutex(X) 1
  14179. # define sqlite3BtreeHoldsAllMutexes(X) 1
  14180. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  14181. #endif
  14182. #endif /* SQLITE_BTREE_H */
  14183. /************** End of btree.h ***********************************************/
  14184. /************** Continuing where we left off in sqliteInt.h ******************/
  14185. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  14186. /************** Begin file vdbe.h ********************************************/
  14187. /*
  14188. ** 2001 September 15
  14189. **
  14190. ** The author disclaims copyright to this source code. In place of
  14191. ** a legal notice, here is a blessing:
  14192. **
  14193. ** May you do good and not evil.
  14194. ** May you find forgiveness for yourself and forgive others.
  14195. ** May you share freely, never taking more than you give.
  14196. **
  14197. *************************************************************************
  14198. ** Header file for the Virtual DataBase Engine (VDBE)
  14199. **
  14200. ** This header defines the interface to the virtual database engine
  14201. ** or VDBE. The VDBE implements an abstract machine that runs a
  14202. ** simple program to access and modify the underlying database.
  14203. */
  14204. #ifndef SQLITE_VDBE_H
  14205. #define SQLITE_VDBE_H
  14206. /* #include <stdio.h> */
  14207. /*
  14208. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  14209. ** in the source file sqliteVdbe.c are allowed to see the insides
  14210. ** of this structure.
  14211. */
  14212. typedef struct Vdbe Vdbe;
  14213. /*
  14214. ** The names of the following types declared in vdbeInt.h are required
  14215. ** for the VdbeOp definition.
  14216. */
  14217. typedef struct sqlite3_value Mem;
  14218. typedef struct SubProgram SubProgram;
  14219. /*
  14220. ** A single instruction of the virtual machine has an opcode
  14221. ** and as many as three operands. The instruction is recorded
  14222. ** as an instance of the following structure:
  14223. */
  14224. struct VdbeOp {
  14225. u8 opcode; /* What operation to perform */
  14226. signed char p4type; /* One of the P4_xxx constants for p4 */
  14227. u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
  14228. int p1; /* First operand */
  14229. int p2; /* Second parameter (often the jump destination) */
  14230. int p3; /* The third parameter */
  14231. union p4union { /* fourth parameter */
  14232. int i; /* Integer value if p4type==P4_INT32 */
  14233. void *p; /* Generic pointer */
  14234. char *z; /* Pointer to data for string (char array) types */
  14235. i64 *pI64; /* Used when p4type is P4_INT64 */
  14236. double *pReal; /* Used when p4type is P4_REAL */
  14237. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  14238. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  14239. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  14240. Mem *pMem; /* Used when p4type is P4_MEM */
  14241. VTable *pVtab; /* Used when p4type is P4_VTAB */
  14242. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  14243. int *ai; /* Used when p4type is P4_INTARRAY */
  14244. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  14245. Table *pTab; /* Used when p4type is P4_TABLE */
  14246. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  14247. Expr *pExpr; /* Used when p4type is P4_EXPR */
  14248. #endif
  14249. int (*xAdvance)(BtCursor *, int);
  14250. } p4;
  14251. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  14252. char *zComment; /* Comment to improve readability */
  14253. #endif
  14254. #ifdef VDBE_PROFILE
  14255. u32 cnt; /* Number of times this instruction was executed */
  14256. u64 cycles; /* Total time spent executing this instruction */
  14257. #endif
  14258. #ifdef SQLITE_VDBE_COVERAGE
  14259. u32 iSrcLine; /* Source-code line that generated this opcode
  14260. ** with flags in the upper 8 bits */
  14261. #endif
  14262. };
  14263. typedef struct VdbeOp VdbeOp;
  14264. /*
  14265. ** A sub-routine used to implement a trigger program.
  14266. */
  14267. struct SubProgram {
  14268. VdbeOp *aOp; /* Array of opcodes for sub-program */
  14269. int nOp; /* Elements in aOp[] */
  14270. int nMem; /* Number of memory cells required */
  14271. int nCsr; /* Number of cursors required */
  14272. u8 *aOnce; /* Array of OP_Once flags */
  14273. void *token; /* id that may be used to recursive triggers */
  14274. SubProgram *pNext; /* Next sub-program already visited */
  14275. };
  14276. /*
  14277. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  14278. ** it takes up less space.
  14279. */
  14280. struct VdbeOpList {
  14281. u8 opcode; /* What operation to perform */
  14282. signed char p1; /* First operand */
  14283. signed char p2; /* Second parameter (often the jump destination) */
  14284. signed char p3; /* Third parameter */
  14285. };
  14286. typedef struct VdbeOpList VdbeOpList;
  14287. /*
  14288. ** Allowed values of VdbeOp.p4type
  14289. */
  14290. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  14291. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  14292. #define P4_STATIC (-1) /* Pointer to a static string */
  14293. #define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
  14294. #define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
  14295. #define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
  14296. #define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  14297. #define P4_TABLE (-6) /* P4 is a pointer to a Table structure */
  14298. /* Above do not own any resources. Must free those below */
  14299. #define P4_FREE_IF_LE (-7)
  14300. #define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */
  14301. #define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */
  14302. #define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */
  14303. #define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */
  14304. #define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */
  14305. #define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */
  14306. #define P4_REAL (-13) /* P4 is a 64-bit floating point value */
  14307. #define P4_INT64 (-14) /* P4 is a 64-bit signed integer */
  14308. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  14309. #define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
  14310. #define P4_DYNBLOB (-17) /* Pointer to memory from sqliteMalloc() */
  14311. /* Error message codes for OP_Halt */
  14312. #define P5_ConstraintNotNull 1
  14313. #define P5_ConstraintUnique 2
  14314. #define P5_ConstraintCheck 3
  14315. #define P5_ConstraintFK 4
  14316. /*
  14317. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  14318. ** number of columns of data returned by the statement.
  14319. */
  14320. #define COLNAME_NAME 0
  14321. #define COLNAME_DECLTYPE 1
  14322. #define COLNAME_DATABASE 2
  14323. #define COLNAME_TABLE 3
  14324. #define COLNAME_COLUMN 4
  14325. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  14326. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  14327. #else
  14328. # ifdef SQLITE_OMIT_DECLTYPE
  14329. # define COLNAME_N 1 /* Store only the name */
  14330. # else
  14331. # define COLNAME_N 2 /* Store the name and decltype */
  14332. # endif
  14333. #endif
  14334. /*
  14335. ** The following macro converts a label returned by sqlite3VdbeMakeLabel()
  14336. ** into an index into the Parse.aLabel[] array that contains the resolved
  14337. ** address of that label.
  14338. */
  14339. #define ADDR(X) (~(X))
  14340. /*
  14341. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  14342. ** header file that defines a number for each opcode used by the VDBE.
  14343. */
  14344. /************** Include opcodes.h in the middle of vdbe.h ********************/
  14345. /************** Begin file opcodes.h *****************************************/
  14346. /* Automatically generated. Do not edit */
  14347. /* See the tool/mkopcodeh.tcl script for details */
  14348. #define OP_Savepoint 0
  14349. #define OP_AutoCommit 1
  14350. #define OP_Transaction 2
  14351. #define OP_SorterNext 3 /* jump */
  14352. #define OP_Prev 4 /* jump */
  14353. #define OP_Next 5 /* jump */
  14354. #define OP_Checkpoint 6
  14355. #define OP_JournalMode 7
  14356. #define OP_Vacuum 8
  14357. #define OP_VFilter 9 /* jump, synopsis: iplan=r[P3] zplan='P4' */
  14358. #define OP_VUpdate 10 /* synopsis: data=r[P3@P2] */
  14359. #define OP_Goto 11 /* jump */
  14360. #define OP_Gosub 12 /* jump */
  14361. #define OP_InitCoroutine 13 /* jump */
  14362. #define OP_Yield 14 /* jump */
  14363. #define OP_MustBeInt 15 /* jump */
  14364. #define OP_Jump 16 /* jump */
  14365. #define OP_Once 17 /* jump */
  14366. #define OP_If 18 /* jump */
  14367. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  14368. #define OP_IfNot 20 /* jump */
  14369. #define OP_IfNullRow 21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
  14370. #define OP_SeekLT 22 /* jump, synopsis: key=r[P3@P4] */
  14371. #define OP_SeekLE 23 /* jump, synopsis: key=r[P3@P4] */
  14372. #define OP_SeekGE 24 /* jump, synopsis: key=r[P3@P4] */
  14373. #define OP_SeekGT 25 /* jump, synopsis: key=r[P3@P4] */
  14374. #define OP_IfNoHope 26 /* jump, synopsis: key=r[P3@P4] */
  14375. #define OP_NoConflict 27 /* jump, synopsis: key=r[P3@P4] */
  14376. #define OP_NotFound 28 /* jump, synopsis: key=r[P3@P4] */
  14377. #define OP_Found 29 /* jump, synopsis: key=r[P3@P4] */
  14378. #define OP_SeekRowid 30 /* jump, synopsis: intkey=r[P3] */
  14379. #define OP_NotExists 31 /* jump, synopsis: intkey=r[P3] */
  14380. #define OP_Last 32 /* jump */
  14381. #define OP_IfSmaller 33 /* jump */
  14382. #define OP_SorterSort 34 /* jump */
  14383. #define OP_Sort 35 /* jump */
  14384. #define OP_Rewind 36 /* jump */
  14385. #define OP_IdxLE 37 /* jump, synopsis: key=r[P3@P4] */
  14386. #define OP_IdxGT 38 /* jump, synopsis: key=r[P3@P4] */
  14387. #define OP_IdxLT 39 /* jump, synopsis: key=r[P3@P4] */
  14388. #define OP_IdxGE 40 /* jump, synopsis: key=r[P3@P4] */
  14389. #define OP_RowSetRead 41 /* jump, synopsis: r[P3]=rowset(P1) */
  14390. #define OP_RowSetTest 42 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
  14391. #define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  14392. #define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  14393. #define OP_Program 45 /* jump */
  14394. #define OP_FkIfZero 46 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
  14395. #define OP_IfPos 47 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  14396. #define OP_IfNotZero 48 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
  14397. #define OP_DecrJumpZero 49 /* jump, synopsis: if (--r[P1])==0 goto P2 */
  14398. #define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  14399. #define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  14400. #define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
  14401. #define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
  14402. #define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
  14403. #define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
  14404. #define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
  14405. #define OP_Ge 57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
  14406. #define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */
  14407. #define OP_IncrVacuum 59 /* jump */
  14408. #define OP_VNext 60 /* jump */
  14409. #define OP_Init 61 /* jump, synopsis: Start at P2 */
  14410. #define OP_PureFunc0 62
  14411. #define OP_Function0 63 /* synopsis: r[P3]=func(r[P2@P5]) */
  14412. #define OP_PureFunc 64
  14413. #define OP_Function 65 /* synopsis: r[P3]=func(r[P2@P5]) */
  14414. #define OP_Return 66
  14415. #define OP_EndCoroutine 67
  14416. #define OP_HaltIfNull 68 /* synopsis: if r[P3]=null halt */
  14417. #define OP_Halt 69
  14418. #define OP_Integer 70 /* synopsis: r[P2]=P1 */
  14419. #define OP_Int64 71 /* synopsis: r[P2]=P4 */
  14420. #define OP_String 72 /* synopsis: r[P2]='P4' (len=P1) */
  14421. #define OP_Null 73 /* synopsis: r[P2..P3]=NULL */
  14422. #define OP_SoftNull 74 /* synopsis: r[P1]=NULL */
  14423. #define OP_Blob 75 /* synopsis: r[P2]=P4 (len=P1) */
  14424. #define OP_Variable 76 /* synopsis: r[P2]=parameter(P1,P4) */
  14425. #define OP_Move 77 /* synopsis: r[P2@P3]=r[P1@P3] */
  14426. #define OP_Copy 78 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  14427. #define OP_SCopy 79 /* synopsis: r[P2]=r[P1] */
  14428. #define OP_IntCopy 80 /* synopsis: r[P2]=r[P1] */
  14429. #define OP_ResultRow 81 /* synopsis: output=r[P1@P2] */
  14430. #define OP_CollSeq 82
  14431. #define OP_AddImm 83 /* synopsis: r[P1]=r[P1]+P2 */
  14432. #define OP_RealAffinity 84
  14433. #define OP_Cast 85 /* synopsis: affinity(r[P1]) */
  14434. #define OP_Permutation 86
  14435. #define OP_Compare 87 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  14436. #define OP_IsTrue 88 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
  14437. #define OP_Offset 89 /* synopsis: r[P3] = sqlite_offset(P1) */
  14438. #define OP_Column 90 /* synopsis: r[P3]=PX */
  14439. #define OP_Affinity 91 /* synopsis: affinity(r[P1@P2]) */
  14440. #define OP_MakeRecord 92 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  14441. #define OP_Count 93 /* synopsis: r[P2]=count() */
  14442. #define OP_ReadCookie 94
  14443. #define OP_SetCookie 95
  14444. #define OP_BitAnd 96 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  14445. #define OP_BitOr 97 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  14446. #define OP_ShiftLeft 98 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  14447. #define OP_ShiftRight 99 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  14448. #define OP_Add 100 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  14449. #define OP_Subtract 101 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  14450. #define OP_Multiply 102 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  14451. #define OP_Divide 103 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  14452. #define OP_Remainder 104 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  14453. #define OP_Concat 105 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  14454. #define OP_ReopenIdx 106 /* synopsis: root=P2 iDb=P3 */
  14455. #define OP_BitNot 107 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
  14456. #define OP_OpenRead 108 /* synopsis: root=P2 iDb=P3 */
  14457. #define OP_OpenWrite 109 /* synopsis: root=P2 iDb=P3 */
  14458. #define OP_String8 110 /* same as TK_STRING, synopsis: r[P2]='P4' */
  14459. #define OP_OpenDup 111
  14460. #define OP_OpenAutoindex 112 /* synopsis: nColumn=P2 */
  14461. #define OP_OpenEphemeral 113 /* synopsis: nColumn=P2 */
  14462. #define OP_SorterOpen 114
  14463. #define OP_SequenceTest 115 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  14464. #define OP_OpenPseudo 116 /* synopsis: P3 columns in r[P2] */
  14465. #define OP_Close 117
  14466. #define OP_ColumnsUsed 118
  14467. #define OP_SeekHit 119 /* synopsis: seekHit=P2 */
  14468. #define OP_Sequence 120 /* synopsis: r[P2]=cursor[P1].ctr++ */
  14469. #define OP_NewRowid 121 /* synopsis: r[P2]=rowid */
  14470. #define OP_Insert 122 /* synopsis: intkey=r[P3] data=r[P2] */
  14471. #define OP_Delete 123
  14472. #define OP_ResetCount 124
  14473. #define OP_SorterCompare 125 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  14474. #define OP_SorterData 126 /* synopsis: r[P2]=data */
  14475. #define OP_RowData 127 /* synopsis: r[P2]=data */
  14476. #define OP_Rowid 128 /* synopsis: r[P2]=rowid */
  14477. #define OP_NullRow 129
  14478. #define OP_SeekEnd 130
  14479. #define OP_SorterInsert 131 /* synopsis: key=r[P2] */
  14480. #define OP_IdxInsert 132 /* synopsis: key=r[P2] */
  14481. #define OP_IdxDelete 133 /* synopsis: key=r[P2@P3] */
  14482. #define OP_DeferredSeek 134 /* synopsis: Move P3 to P1.rowid if needed */
  14483. #define OP_IdxRowid 135 /* synopsis: r[P2]=rowid */
  14484. #define OP_Destroy 136
  14485. #define OP_Clear 137
  14486. #define OP_ResetSorter 138
  14487. #define OP_CreateBtree 139 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
  14488. #define OP_SqlExec 140
  14489. #define OP_ParseSchema 141
  14490. #define OP_LoadAnalysis 142
  14491. #define OP_DropTable 143
  14492. #define OP_DropIndex 144
  14493. #define OP_Real 145 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  14494. #define OP_DropTrigger 146
  14495. #define OP_IntegrityCk 147
  14496. #define OP_RowSetAdd 148 /* synopsis: rowset(P1)=r[P2] */
  14497. #define OP_Param 149
  14498. #define OP_FkCounter 150 /* synopsis: fkctr[P1]+=P2 */
  14499. #define OP_MemMax 151 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  14500. #define OP_OffsetLimit 152 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
  14501. #define OP_AggInverse 153 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
  14502. #define OP_AggStep 154 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  14503. #define OP_AggStep1 155 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  14504. #define OP_AggValue 156 /* synopsis: r[P3]=value N=P2 */
  14505. #define OP_AggFinal 157 /* synopsis: accum=r[P1] N=P2 */
  14506. #define OP_Expire 158
  14507. #define OP_TableLock 159 /* synopsis: iDb=P1 root=P2 write=P3 */
  14508. #define OP_VBegin 160
  14509. #define OP_VCreate 161
  14510. #define OP_VDestroy 162
  14511. #define OP_VOpen 163
  14512. #define OP_VColumn 164 /* synopsis: r[P3]=vcolumn(P2) */
  14513. #define OP_VRename 165
  14514. #define OP_Pagecount 166
  14515. #define OP_MaxPgcnt 167
  14516. #define OP_Trace 168
  14517. #define OP_CursorHint 169
  14518. #define OP_Noop 170
  14519. #define OP_Explain 171
  14520. #define OP_Abortable 172
  14521. /* Properties such as "out2" or "jump" that are specified in
  14522. ** comments following the "case" for each opcode in the vdbe.c
  14523. ** are encoded into bitvectors as follows:
  14524. */
  14525. #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
  14526. #define OPFLG_IN1 0x02 /* in1: P1 is an input */
  14527. #define OPFLG_IN2 0x04 /* in2: P2 is an input */
  14528. #define OPFLG_IN3 0x08 /* in3: P3 is an input */
  14529. #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
  14530. #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
  14531. #define OPFLG_INITIALIZER {\
  14532. /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\
  14533. /* 8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\
  14534. /* 16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x01, 0x09, 0x09,\
  14535. /* 24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
  14536. /* 32 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
  14537. /* 40 */ 0x01, 0x23, 0x0b, 0x26, 0x26, 0x01, 0x01, 0x03,\
  14538. /* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
  14539. /* 56 */ 0x0b, 0x0b, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,\
  14540. /* 64 */ 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10,\
  14541. /* 72 */ 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10,\
  14542. /* 80 */ 0x10, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\
  14543. /* 88 */ 0x12, 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
  14544. /* 96 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26,\
  14545. /* 104 */ 0x26, 0x26, 0x00, 0x12, 0x00, 0x00, 0x10, 0x00,\
  14546. /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14547. /* 120 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14548. /* 128 */ 0x10, 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10,\
  14549. /* 136 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
  14550. /* 144 */ 0x00, 0x10, 0x00, 0x00, 0x06, 0x10, 0x00, 0x04,\
  14551. /* 152 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14552. /* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\
  14553. /* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00,}
  14554. /* The sqlite3P2Values() routine is able to run faster if it knows
  14555. ** the value of the largest JUMP opcode. The smaller the maximum
  14556. ** JUMP opcode the better, so the mkopcodeh.tcl script that
  14557. ** generated this include file strives to group all JUMP opcodes
  14558. ** together near the beginning of the list.
  14559. */
  14560. #define SQLITE_MX_JUMP_OPCODE 61 /* Maximum JUMP opcode */
  14561. /************** End of opcodes.h *********************************************/
  14562. /************** Continuing where we left off in vdbe.h ***********************/
  14563. /*
  14564. ** Additional non-public SQLITE_PREPARE_* flags
  14565. */
  14566. #define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
  14567. #define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */
  14568. /*
  14569. ** Prototypes for the VDBE interface. See comments on the implementation
  14570. ** for a description of what each of these routines does.
  14571. */
  14572. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  14573. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  14574. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  14575. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  14576. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  14577. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  14578. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  14579. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  14580. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  14581. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  14582. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  14583. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
  14584. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  14585. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
  14586. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
  14587. #else
  14588. # define sqlite3VdbeVerifyNoMallocRequired(A,B)
  14589. # define sqlite3VdbeVerifyNoResultRow(A)
  14590. #endif
  14591. #if defined(SQLITE_DEBUG)
  14592. SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
  14593. #else
  14594. # define sqlite3VdbeVerifyAbortable(A,B)
  14595. #endif
  14596. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
  14597. #ifndef SQLITE_OMIT_EXPLAIN
  14598. SQLITE_PRIVATE void sqlite3VdbeExplain(Parse*,u8,const char*,...);
  14599. SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse*);
  14600. SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse*);
  14601. # define ExplainQueryPlan(P) sqlite3VdbeExplain P
  14602. # define ExplainQueryPlanPop(P) sqlite3VdbeExplainPop(P)
  14603. # define ExplainQueryPlanParent(P) sqlite3VdbeExplainParent(P)
  14604. #else
  14605. # define ExplainQueryPlan(P)
  14606. # define ExplainQueryPlanPop(P)
  14607. # define ExplainQueryPlanParent(P) 0
  14608. # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
  14609. #endif
  14610. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)
  14611. SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char*,const char*);
  14612. #else
  14613. # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
  14614. #endif
  14615. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  14616. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
  14617. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  14618. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  14619. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  14620. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
  14621. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  14622. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  14623. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  14624. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  14625. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
  14626. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  14627. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  14628. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  14629. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse*);
  14630. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  14631. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
  14632. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  14633. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  14634. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  14635. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  14636. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  14637. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  14638. #ifdef SQLITE_DEBUG
  14639. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  14640. #endif
  14641. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  14642. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  14643. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  14644. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  14645. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  14646. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  14647. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  14648. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
  14649. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
  14650. #ifdef SQLITE_ENABLE_NORMALIZE
  14651. SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*);
  14652. SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*);
  14653. #endif
  14654. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  14655. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  14656. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  14657. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  14658. #ifndef SQLITE_OMIT_TRACE
  14659. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  14660. #endif
  14661. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  14662. SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);
  14663. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  14664. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  14665. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  14666. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
  14667. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  14668. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  14669. #ifndef SQLITE_OMIT_TRIGGER
  14670. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  14671. #endif
  14672. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
  14673. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  14674. ** each VDBE opcode.
  14675. **
  14676. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  14677. ** comments in VDBE programs that show key decision points in the code
  14678. ** generator.
  14679. */
  14680. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  14681. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  14682. # define VdbeComment(X) sqlite3VdbeComment X
  14683. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  14684. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  14685. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  14686. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  14687. # else
  14688. # define VdbeModuleComment(X)
  14689. # endif
  14690. #else
  14691. # define VdbeComment(X)
  14692. # define VdbeNoopComment(X)
  14693. # define VdbeModuleComment(X)
  14694. #endif
  14695. /*
  14696. ** The VdbeCoverage macros are used to set a coverage testing point
  14697. ** for VDBE branch instructions. The coverage testing points are line
  14698. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  14699. ** only works with an amalagmation build. That's ok since a VDBE branch
  14700. ** coverage build designed for testing the test suite only. No application
  14701. ** should ever ship with VDBE branch coverage measuring turned on.
  14702. **
  14703. ** VdbeCoverage(v) // Mark the previously coded instruction
  14704. ** // as a branch
  14705. **
  14706. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  14707. **
  14708. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  14709. **
  14710. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  14711. **
  14712. ** VdbeCoverageNeverNull(v) // Previous three-way branch is only
  14713. ** // taken on the first two ways. The
  14714. ** // NULL option is not possible
  14715. **
  14716. ** VdbeCoverageEqNe(v) // Previous OP_Jump is only interested
  14717. ** // in distingishing equal and not-equal.
  14718. **
  14719. ** Every VDBE branch operation must be tagged with one of the macros above.
  14720. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  14721. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  14722. ** routine in vdbe.c, alerting the developer to the missed tag.
  14723. **
  14724. ** During testing, the test application will invoke
  14725. ** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback
  14726. ** routine that is invoked as each bytecode branch is taken. The callback
  14727. ** contains the sqlite3.c source line number ov the VdbeCoverage macro and
  14728. ** flags to indicate whether or not the branch was taken. The test application
  14729. ** is responsible for keeping track of this and reporting byte-code branches
  14730. ** that are never taken.
  14731. **
  14732. ** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the
  14733. ** vdbe.c source file for additional information.
  14734. */
  14735. #ifdef SQLITE_VDBE_COVERAGE
  14736. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  14737. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  14738. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  14739. # define VdbeCoverageAlwaysTaken(v) \
  14740. sqlite3VdbeSetLineNumber(v,__LINE__|0x5000000);
  14741. # define VdbeCoverageNeverTaken(v) \
  14742. sqlite3VdbeSetLineNumber(v,__LINE__|0x6000000);
  14743. # define VdbeCoverageNeverNull(v) \
  14744. sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
  14745. # define VdbeCoverageNeverNullIf(v,x) \
  14746. if(x)sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
  14747. # define VdbeCoverageEqNe(v) \
  14748. sqlite3VdbeSetLineNumber(v,__LINE__|0x8000000);
  14749. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  14750. #else
  14751. # define VdbeCoverage(v)
  14752. # define VdbeCoverageIf(v,x)
  14753. # define VdbeCoverageAlwaysTaken(v)
  14754. # define VdbeCoverageNeverTaken(v)
  14755. # define VdbeCoverageNeverNull(v)
  14756. # define VdbeCoverageNeverNullIf(v,x)
  14757. # define VdbeCoverageEqNe(v)
  14758. # define VDBE_OFFSET_LINENO(x) 0
  14759. #endif
  14760. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  14761. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  14762. #else
  14763. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  14764. #endif
  14765. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  14766. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
  14767. #endif
  14768. #endif /* SQLITE_VDBE_H */
  14769. /************** End of vdbe.h ************************************************/
  14770. /************** Continuing where we left off in sqliteInt.h ******************/
  14771. /************** Include pager.h in the middle of sqliteInt.h *****************/
  14772. /************** Begin file pager.h *******************************************/
  14773. /*
  14774. ** 2001 September 15
  14775. **
  14776. ** The author disclaims copyright to this source code. In place of
  14777. ** a legal notice, here is a blessing:
  14778. **
  14779. ** May you do good and not evil.
  14780. ** May you find forgiveness for yourself and forgive others.
  14781. ** May you share freely, never taking more than you give.
  14782. **
  14783. *************************************************************************
  14784. ** This header file defines the interface that the sqlite page cache
  14785. ** subsystem. The page cache subsystem reads and writes a file a page
  14786. ** at a time and provides a journal for rollback.
  14787. */
  14788. #ifndef SQLITE_PAGER_H
  14789. #define SQLITE_PAGER_H
  14790. /*
  14791. ** Default maximum size for persistent journal files. A negative
  14792. ** value means no limit. This value may be overridden using the
  14793. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  14794. */
  14795. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  14796. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  14797. #endif
  14798. /*
  14799. ** The type used to represent a page number. The first page in a file
  14800. ** is called page 1. 0 is used to represent "not a page".
  14801. */
  14802. typedef u32 Pgno;
  14803. /*
  14804. ** Each open file is managed by a separate instance of the "Pager" structure.
  14805. */
  14806. typedef struct Pager Pager;
  14807. /*
  14808. ** Handle type for pages.
  14809. */
  14810. typedef struct PgHdr DbPage;
  14811. /*
  14812. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  14813. ** reserved for working around a windows/posix incompatibility). It is
  14814. ** used in the journal to signify that the remainder of the journal file
  14815. ** is devoted to storing a master journal name - there are no more pages to
  14816. ** roll back. See comments for function writeMasterJournal() in pager.c
  14817. ** for details.
  14818. */
  14819. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  14820. /*
  14821. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  14822. **
  14823. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  14824. */
  14825. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  14826. #define PAGER_MEMORY 0x0002 /* In-memory database */
  14827. /*
  14828. ** Valid values for the second argument to sqlite3PagerLockingMode().
  14829. */
  14830. #define PAGER_LOCKINGMODE_QUERY -1
  14831. #define PAGER_LOCKINGMODE_NORMAL 0
  14832. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  14833. /*
  14834. ** Numeric constants that encode the journalmode.
  14835. **
  14836. ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
  14837. ** are exposed in the API via the "PRAGMA journal_mode" command and
  14838. ** therefore cannot be changed without a compatibility break.
  14839. */
  14840. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  14841. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  14842. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  14843. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  14844. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  14845. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  14846. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  14847. /*
  14848. ** Flags that make up the mask passed to sqlite3PagerGet().
  14849. */
  14850. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  14851. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  14852. /*
  14853. ** Flags for sqlite3PagerSetFlags()
  14854. **
  14855. ** Value constraints (enforced via assert()):
  14856. ** PAGER_FULLFSYNC == SQLITE_FullFSync
  14857. ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
  14858. ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
  14859. */
  14860. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  14861. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  14862. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  14863. #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
  14864. #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
  14865. #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
  14866. #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
  14867. #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
  14868. #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
  14869. /*
  14870. ** The remainder of this file contains the declarations of the functions
  14871. ** that make up the Pager sub-system API. See source code comments for
  14872. ** a detailed description of each routine.
  14873. */
  14874. /* Open and close a Pager connection. */
  14875. SQLITE_PRIVATE int sqlite3PagerOpen(
  14876. sqlite3_vfs*,
  14877. Pager **ppPager,
  14878. const char*,
  14879. int,
  14880. int,
  14881. int,
  14882. void(*)(DbPage*)
  14883. );
  14884. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
  14885. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  14886. /* Functions used to configure a Pager object. */
  14887. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
  14888. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  14889. #ifdef SQLITE_HAS_CODEC
  14890. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
  14891. #endif
  14892. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  14893. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  14894. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
  14895. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  14896. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  14897. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  14898. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  14899. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  14900. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  14901. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  14902. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  14903. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  14904. SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
  14905. /* Functions used to obtain and release page references. */
  14906. SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  14907. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  14908. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  14909. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  14910. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  14911. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
  14912. /* Operations on page references. */
  14913. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  14914. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  14915. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  14916. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  14917. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  14918. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  14919. /* Functions used to manage pager transactions and savepoints. */
  14920. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  14921. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  14922. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  14923. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  14924. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  14925. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  14926. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  14927. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  14928. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  14929. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  14930. #ifndef SQLITE_OMIT_WAL
  14931. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
  14932. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  14933. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  14934. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  14935. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
  14936. # ifdef SQLITE_ENABLE_SNAPSHOT
  14937. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
  14938. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
  14939. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
  14940. SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
  14941. SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager);
  14942. # endif
  14943. #endif
  14944. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  14945. SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
  14946. #endif
  14947. #ifdef SQLITE_ENABLE_ZIPVFS
  14948. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  14949. #endif
  14950. /* Functions used to query pager state and configuration. */
  14951. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  14952. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  14953. #ifdef SQLITE_DEBUG
  14954. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  14955. #endif
  14956. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  14957. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  14958. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
  14959. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  14960. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
  14961. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  14962. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  14963. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  14964. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  14965. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
  14966. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  14967. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  14968. SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager);
  14969. #else
  14970. # define sqlite3PagerResetLockTimeout(X)
  14971. #endif
  14972. /* Functions used to truncate the database file. */
  14973. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  14974. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  14975. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  14976. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  14977. #endif
  14978. /* Functions to support testing and debugging. */
  14979. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  14980. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  14981. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  14982. #endif
  14983. #ifdef SQLITE_TEST
  14984. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  14985. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  14986. void disable_simulated_io_errors(void);
  14987. void enable_simulated_io_errors(void);
  14988. #else
  14989. # define disable_simulated_io_errors()
  14990. # define enable_simulated_io_errors()
  14991. #endif
  14992. #endif /* SQLITE_PAGER_H */
  14993. /************** End of pager.h ***********************************************/
  14994. /************** Continuing where we left off in sqliteInt.h ******************/
  14995. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  14996. /************** Begin file pcache.h ******************************************/
  14997. /*
  14998. ** 2008 August 05
  14999. **
  15000. ** The author disclaims copyright to this source code. In place of
  15001. ** a legal notice, here is a blessing:
  15002. **
  15003. ** May you do good and not evil.
  15004. ** May you find forgiveness for yourself and forgive others.
  15005. ** May you share freely, never taking more than you give.
  15006. **
  15007. *************************************************************************
  15008. ** This header file defines the interface that the sqlite page cache
  15009. ** subsystem.
  15010. */
  15011. #ifndef _PCACHE_H_
  15012. typedef struct PgHdr PgHdr;
  15013. typedef struct PCache PCache;
  15014. /*
  15015. ** Every page in the cache is controlled by an instance of the following
  15016. ** structure.
  15017. */
  15018. struct PgHdr {
  15019. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  15020. void *pData; /* Page data */
  15021. void *pExtra; /* Extra content */
  15022. PCache *pCache; /* PRIVATE: Cache that owns this page */
  15023. PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
  15024. Pager *pPager; /* The pager this page is part of */
  15025. Pgno pgno; /* Page number for this page */
  15026. #ifdef SQLITE_CHECK_PAGES
  15027. u32 pageHash; /* Hash of page content */
  15028. #endif
  15029. u16 flags; /* PGHDR flags defined below */
  15030. /**********************************************************************
  15031. ** Elements above, except pCache, are public. All that follow are
  15032. ** private to pcache.c and should not be accessed by other modules.
  15033. ** pCache is grouped with the public elements for efficiency.
  15034. */
  15035. i16 nRef; /* Number of users of this page */
  15036. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  15037. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  15038. /* NB: pDirtyNext and pDirtyPrev are undefined if the
  15039. ** PgHdr object is not dirty */
  15040. };
  15041. /* Bit values for PgHdr.flags */
  15042. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  15043. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  15044. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  15045. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  15046. ** writing this page to the database */
  15047. #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
  15048. #define PGHDR_MMAP 0x020 /* This is an mmap page object */
  15049. #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
  15050. /* Initialize and shutdown the page cache subsystem */
  15051. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  15052. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  15053. /* Page cache buffer management:
  15054. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  15055. */
  15056. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  15057. /* Create a new pager cache.
  15058. ** Under memory stress, invoke xStress to try to make pages clean.
  15059. ** Only clean and unpinned pages can be reclaimed.
  15060. */
  15061. SQLITE_PRIVATE int sqlite3PcacheOpen(
  15062. int szPage, /* Size of every page */
  15063. int szExtra, /* Extra space associated with each page */
  15064. int bPurgeable, /* True if pages are on backing store */
  15065. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  15066. void *pStress, /* Argument to xStress */
  15067. PCache *pToInit /* Preallocated space for the PCache */
  15068. );
  15069. /* Modify the page-size after the cache has been created. */
  15070. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  15071. /* Return the size in bytes of a PCache object. Used to preallocate
  15072. ** storage space.
  15073. */
  15074. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  15075. /* One release per successful fetch. Page is pinned until released.
  15076. ** Reference counted.
  15077. */
  15078. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  15079. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  15080. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  15081. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  15082. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  15083. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  15084. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  15085. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  15086. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
  15087. /* Change a page number. Used by incr-vacuum. */
  15088. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  15089. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  15090. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  15091. /* Get a list of all dirty pages in the cache, sorted by page number */
  15092. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  15093. /* Reset and close the cache object */
  15094. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  15095. /* Clear flags from pages of the page cache */
  15096. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  15097. /* Discard the contents of the cache */
  15098. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  15099. /* Return the total number of outstanding page references */
  15100. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  15101. /* Increment the reference count of an existing page */
  15102. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  15103. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  15104. /* Return the total number of pages stored in the cache */
  15105. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  15106. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  15107. /* Iterate through all dirty pages currently stored in the cache. This
  15108. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  15109. ** library is built.
  15110. */
  15111. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  15112. #endif
  15113. #if defined(SQLITE_DEBUG)
  15114. /* Check invariants on a PgHdr object */
  15115. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
  15116. #endif
  15117. /* Set and get the suggested cache-size for the specified pager-cache.
  15118. **
  15119. ** If no global maximum is configured, then the system attempts to limit
  15120. ** the total number of pages cached by purgeable pager-caches to the sum
  15121. ** of the suggested cache-sizes.
  15122. */
  15123. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  15124. #ifdef SQLITE_TEST
  15125. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  15126. #endif
  15127. /* Set or get the suggested spill-size for the specified pager-cache.
  15128. **
  15129. ** The spill-size is the minimum number of pages in cache before the cache
  15130. ** will attempt to spill dirty pages by calling xStress.
  15131. */
  15132. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
  15133. /* Free up as much memory as possible from the page cache */
  15134. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  15135. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  15136. /* Try to return memory used by the pcache module to the main memory heap */
  15137. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  15138. #endif
  15139. #ifdef SQLITE_TEST
  15140. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  15141. #endif
  15142. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  15143. /* Return the header size */
  15144. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  15145. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  15146. /* Number of dirty pages as a percentage of the configured cache size */
  15147. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
  15148. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  15149. SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
  15150. #endif
  15151. #endif /* _PCACHE_H_ */
  15152. /************** End of pcache.h **********************************************/
  15153. /************** Continuing where we left off in sqliteInt.h ******************/
  15154. /************** Include os.h in the middle of sqliteInt.h ********************/
  15155. /************** Begin file os.h **********************************************/
  15156. /*
  15157. ** 2001 September 16
  15158. **
  15159. ** The author disclaims copyright to this source code. In place of
  15160. ** a legal notice, here is a blessing:
  15161. **
  15162. ** May you do good and not evil.
  15163. ** May you find forgiveness for yourself and forgive others.
  15164. ** May you share freely, never taking more than you give.
  15165. **
  15166. ******************************************************************************
  15167. **
  15168. ** This header file (together with is companion C source-code file
  15169. ** "os.c") attempt to abstract the underlying operating system so that
  15170. ** the SQLite library will work on both POSIX and windows systems.
  15171. **
  15172. ** This header file is #include-ed by sqliteInt.h and thus ends up
  15173. ** being included by every source file.
  15174. */
  15175. #ifndef _SQLITE_OS_H_
  15176. #define _SQLITE_OS_H_
  15177. /*
  15178. ** Attempt to automatically detect the operating system and setup the
  15179. ** necessary pre-processor macros for it.
  15180. */
  15181. /************** Include os_setup.h in the middle of os.h *********************/
  15182. /************** Begin file os_setup.h ****************************************/
  15183. /*
  15184. ** 2013 November 25
  15185. **
  15186. ** The author disclaims copyright to this source code. In place of
  15187. ** a legal notice, here is a blessing:
  15188. **
  15189. ** May you do good and not evil.
  15190. ** May you find forgiveness for yourself and forgive others.
  15191. ** May you share freely, never taking more than you give.
  15192. **
  15193. ******************************************************************************
  15194. **
  15195. ** This file contains pre-processor directives related to operating system
  15196. ** detection and/or setup.
  15197. */
  15198. #ifndef SQLITE_OS_SETUP_H
  15199. #define SQLITE_OS_SETUP_H
  15200. /*
  15201. ** Figure out if we are dealing with Unix, Windows, or some other operating
  15202. ** system.
  15203. **
  15204. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  15205. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  15206. ** the three will be 1. The other two will be 0.
  15207. */
  15208. #if defined(SQLITE_OS_OTHER)
  15209. # if SQLITE_OS_OTHER==1
  15210. # undef SQLITE_OS_UNIX
  15211. # define SQLITE_OS_UNIX 0
  15212. # undef SQLITE_OS_WIN
  15213. # define SQLITE_OS_WIN 0
  15214. # else
  15215. # undef SQLITE_OS_OTHER
  15216. # endif
  15217. #endif
  15218. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  15219. # define SQLITE_OS_OTHER 0
  15220. # ifndef SQLITE_OS_WIN
  15221. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  15222. defined(__MINGW32__) || defined(__BORLANDC__)
  15223. # define SQLITE_OS_WIN 1
  15224. # define SQLITE_OS_UNIX 0
  15225. # else
  15226. # define SQLITE_OS_WIN 0
  15227. # define SQLITE_OS_UNIX 1
  15228. # endif
  15229. # else
  15230. # define SQLITE_OS_UNIX 0
  15231. # endif
  15232. #else
  15233. # ifndef SQLITE_OS_WIN
  15234. # define SQLITE_OS_WIN 0
  15235. # endif
  15236. #endif
  15237. #endif /* SQLITE_OS_SETUP_H */
  15238. /************** End of os_setup.h ********************************************/
  15239. /************** Continuing where we left off in os.h *************************/
  15240. /* If the SET_FULLSYNC macro is not defined above, then make it
  15241. ** a no-op
  15242. */
  15243. #ifndef SET_FULLSYNC
  15244. # define SET_FULLSYNC(x,y)
  15245. #endif
  15246. /*
  15247. ** The default size of a disk sector
  15248. */
  15249. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  15250. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  15251. #endif
  15252. /*
  15253. ** Temporary files are named starting with this prefix followed by 16 random
  15254. ** alphanumeric characters, and no file extension. They are stored in the
  15255. ** OS's standard temporary file directory, and are deleted prior to exit.
  15256. ** If sqlite is being embedded in another program, you may wish to change the
  15257. ** prefix to reflect your program's name, so that if your program exits
  15258. ** prematurely, old temporary files can be easily identified. This can be done
  15259. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  15260. **
  15261. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  15262. ** Mcafee started using SQLite in their anti-virus product and it
  15263. ** started putting files with the "sqlite" name in the c:/temp folder.
  15264. ** This annoyed many windows users. Those users would then do a
  15265. ** Google search for "sqlite", find the telephone numbers of the
  15266. ** developers and call to wake them up at night and complain.
  15267. ** For this reason, the default name prefix is changed to be "sqlite"
  15268. ** spelled backwards. So the temp files are still identified, but
  15269. ** anybody smart enough to figure out the code is also likely smart
  15270. ** enough to know that calling the developer will not help get rid
  15271. ** of the file.
  15272. */
  15273. #ifndef SQLITE_TEMP_FILE_PREFIX
  15274. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  15275. #endif
  15276. /*
  15277. ** The following values may be passed as the second argument to
  15278. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  15279. **
  15280. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  15281. ** RESERVED: A single process may hold a RESERVED lock on a file at
  15282. ** any time. Other processes may hold and obtain new SHARED locks.
  15283. ** PENDING: A single process may hold a PENDING lock on a file at
  15284. ** any one time. Existing SHARED locks may persist, but no new
  15285. ** SHARED locks may be obtained by other processes.
  15286. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  15287. **
  15288. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  15289. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  15290. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  15291. ** sqlite3OsLock().
  15292. */
  15293. #define NO_LOCK 0
  15294. #define SHARED_LOCK 1
  15295. #define RESERVED_LOCK 2
  15296. #define PENDING_LOCK 3
  15297. #define EXCLUSIVE_LOCK 4
  15298. /*
  15299. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  15300. **
  15301. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  15302. ** those functions are not available. So we use only LockFile() and
  15303. ** UnlockFile().
  15304. **
  15305. ** LockFile() prevents not just writing but also reading by other processes.
  15306. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  15307. ** byte out of a specific range of bytes. The lock byte is obtained at
  15308. ** random so two separate readers can probably access the file at the
  15309. ** same time, unless they are unlucky and choose the same lock byte.
  15310. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  15311. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  15312. ** a single byte of the file that is designated as the reserved lock byte.
  15313. ** A PENDING_LOCK is obtained by locking a designated byte different from
  15314. ** the RESERVED_LOCK byte.
  15315. **
  15316. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  15317. ** which means we can use reader/writer locks. When reader/writer locks
  15318. ** are used, the lock is placed on the same range of bytes that is used
  15319. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  15320. ** will support two or more Win95 readers or two or more WinNT readers.
  15321. ** But a single Win95 reader will lock out all WinNT readers and a single
  15322. ** WinNT reader will lock out all other Win95 readers.
  15323. **
  15324. ** The following #defines specify the range of bytes used for locking.
  15325. ** SHARED_SIZE is the number of bytes available in the pool from which
  15326. ** a random byte is selected for a shared lock. The pool of bytes for
  15327. ** shared locks begins at SHARED_FIRST.
  15328. **
  15329. ** The same locking strategy and
  15330. ** byte ranges are used for Unix. This leaves open the possibility of having
  15331. ** clients on win95, winNT, and unix all talking to the same shared file
  15332. ** and all locking correctly. To do so would require that samba (or whatever
  15333. ** tool is being used for file sharing) implements locks correctly between
  15334. ** windows and unix. I'm guessing that isn't likely to happen, but by
  15335. ** using the same locking range we are at least open to the possibility.
  15336. **
  15337. ** Locking in windows is manditory. For this reason, we cannot store
  15338. ** actual data in the bytes used for locking. The pager never allocates
  15339. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  15340. ** that all locks will fit on a single page even at the minimum page size.
  15341. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  15342. ** is set high so that we don't have to allocate an unused page except
  15343. ** for very large databases. But one should test the page skipping logic
  15344. ** by setting PENDING_BYTE low and running the entire regression suite.
  15345. **
  15346. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  15347. ** file format. Depending on how it is changed, you might not notice
  15348. ** the incompatibility right away, even running a full regression test.
  15349. ** The default location of PENDING_BYTE is the first byte past the
  15350. ** 1GB boundary.
  15351. **
  15352. */
  15353. #ifdef SQLITE_OMIT_WSD
  15354. # define PENDING_BYTE (0x40000000)
  15355. #else
  15356. # define PENDING_BYTE sqlite3PendingByte
  15357. #endif
  15358. #define RESERVED_BYTE (PENDING_BYTE+1)
  15359. #define SHARED_FIRST (PENDING_BYTE+2)
  15360. #define SHARED_SIZE 510
  15361. /*
  15362. ** Wrapper around OS specific sqlite3_os_init() function.
  15363. */
  15364. SQLITE_PRIVATE int sqlite3OsInit(void);
  15365. /*
  15366. ** Functions for accessing sqlite3_file methods
  15367. */
  15368. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
  15369. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  15370. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  15371. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  15372. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  15373. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  15374. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  15375. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  15376. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  15377. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  15378. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  15379. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  15380. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  15381. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  15382. #ifndef SQLITE_OMIT_WAL
  15383. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  15384. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  15385. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  15386. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  15387. #endif /* SQLITE_OMIT_WAL */
  15388. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  15389. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  15390. /*
  15391. ** Functions for accessing sqlite3_vfs methods
  15392. */
  15393. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  15394. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  15395. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  15396. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  15397. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  15398. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  15399. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  15400. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  15401. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  15402. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  15403. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  15404. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  15405. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
  15406. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  15407. /*
  15408. ** Convenience functions for opening and closing files using
  15409. ** sqlite3_malloc() to obtain space for the file-handle structure.
  15410. */
  15411. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  15412. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
  15413. #endif /* _SQLITE_OS_H_ */
  15414. /************** End of os.h **************************************************/
  15415. /************** Continuing where we left off in sqliteInt.h ******************/
  15416. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  15417. /************** Begin file mutex.h *******************************************/
  15418. /*
  15419. ** 2007 August 28
  15420. **
  15421. ** The author disclaims copyright to this source code. In place of
  15422. ** a legal notice, here is a blessing:
  15423. **
  15424. ** May you do good and not evil.
  15425. ** May you find forgiveness for yourself and forgive others.
  15426. ** May you share freely, never taking more than you give.
  15427. **
  15428. *************************************************************************
  15429. **
  15430. ** This file contains the common header for all mutex implementations.
  15431. ** The sqliteInt.h header #includes this file so that it is available
  15432. ** to all source files. We break it out in an effort to keep the code
  15433. ** better organized.
  15434. **
  15435. ** NOTE: source files should *not* #include this header file directly.
  15436. ** Source files should #include the sqliteInt.h file and let that file
  15437. ** include this one indirectly.
  15438. */
  15439. /*
  15440. ** Figure out what version of the code to use. The choices are
  15441. **
  15442. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  15443. ** mutexes implementation cannot be overridden
  15444. ** at start-time.
  15445. **
  15446. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  15447. ** mutual exclusion is provided. But this
  15448. ** implementation can be overridden at
  15449. ** start-time.
  15450. **
  15451. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  15452. **
  15453. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  15454. */
  15455. #if !SQLITE_THREADSAFE
  15456. # define SQLITE_MUTEX_OMIT
  15457. #endif
  15458. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  15459. # if SQLITE_OS_UNIX
  15460. # define SQLITE_MUTEX_PTHREADS
  15461. # elif SQLITE_OS_WIN
  15462. # define SQLITE_MUTEX_W32
  15463. # else
  15464. # define SQLITE_MUTEX_NOOP
  15465. # endif
  15466. #endif
  15467. #ifdef SQLITE_MUTEX_OMIT
  15468. /*
  15469. ** If this is a no-op implementation, implement everything as macros.
  15470. */
  15471. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  15472. #define sqlite3_mutex_free(X)
  15473. #define sqlite3_mutex_enter(X)
  15474. #define sqlite3_mutex_try(X) SQLITE_OK
  15475. #define sqlite3_mutex_leave(X)
  15476. #define sqlite3_mutex_held(X) ((void)(X),1)
  15477. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  15478. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  15479. #define sqlite3MutexInit() SQLITE_OK
  15480. #define sqlite3MutexEnd()
  15481. #define MUTEX_LOGIC(X)
  15482. #else
  15483. #define MUTEX_LOGIC(X) X
  15484. #endif /* defined(SQLITE_MUTEX_OMIT) */
  15485. /************** End of mutex.h ***********************************************/
  15486. /************** Continuing where we left off in sqliteInt.h ******************/
  15487. /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
  15488. ** synchronous setting to EXTRA. It is no longer supported.
  15489. */
  15490. #ifdef SQLITE_EXTRA_DURABLE
  15491. # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
  15492. # define SQLITE_DEFAULT_SYNCHRONOUS 3
  15493. #endif
  15494. /*
  15495. ** Default synchronous levels.
  15496. **
  15497. ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
  15498. ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
  15499. **
  15500. ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
  15501. ** OFF 1 0
  15502. ** NORMAL 2 1
  15503. ** FULL 3 2
  15504. ** EXTRA 4 3
  15505. **
  15506. ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
  15507. ** In other words, the zero-based numbers are used for all external interfaces
  15508. ** and the one-based values are used internally.
  15509. */
  15510. #ifndef SQLITE_DEFAULT_SYNCHRONOUS
  15511. # define SQLITE_DEFAULT_SYNCHRONOUS 2
  15512. #endif
  15513. #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  15514. # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
  15515. #endif
  15516. /*
  15517. ** Each database file to be accessed by the system is an instance
  15518. ** of the following structure. There are normally two of these structures
  15519. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  15520. ** aDb[1] is the database file used to hold temporary tables. Additional
  15521. ** databases may be attached.
  15522. */
  15523. struct Db {
  15524. char *zDbSName; /* Name of this database. (schema name, not filename) */
  15525. Btree *pBt; /* The B*Tree structure for this database file */
  15526. u8 safety_level; /* How aggressive at syncing data to disk */
  15527. u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
  15528. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  15529. };
  15530. /*
  15531. ** An instance of the following structure stores a database schema.
  15532. **
  15533. ** Most Schema objects are associated with a Btree. The exception is
  15534. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  15535. ** In shared cache mode, a single Schema object can be shared by multiple
  15536. ** Btrees that refer to the same underlying BtShared object.
  15537. **
  15538. ** Schema objects are automatically deallocated when the last Btree that
  15539. ** references them is destroyed. The TEMP Schema is manually freed by
  15540. ** sqlite3_close().
  15541. *
  15542. ** A thread must be holding a mutex on the corresponding Btree in order
  15543. ** to access Schema content. This implies that the thread must also be
  15544. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  15545. ** For a TEMP Schema, only the connection mutex is required.
  15546. */
  15547. struct Schema {
  15548. int schema_cookie; /* Database schema version number for this file */
  15549. int iGeneration; /* Generation counter. Incremented with each change */
  15550. Hash tblHash; /* All tables indexed by name */
  15551. Hash idxHash; /* All (named) indices indexed by name */
  15552. Hash trigHash; /* All triggers indexed by name */
  15553. Hash fkeyHash; /* All foreign keys by referenced table name */
  15554. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  15555. u8 file_format; /* Schema format version for this file */
  15556. u8 enc; /* Text encoding used by this database */
  15557. u16 schemaFlags; /* Flags associated with this schema */
  15558. int cache_size; /* Number of pages to use in the cache */
  15559. };
  15560. /*
  15561. ** These macros can be used to test, set, or clear bits in the
  15562. ** Db.pSchema->flags field.
  15563. */
  15564. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  15565. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  15566. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  15567. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  15568. /*
  15569. ** Allowed values for the DB.pSchema->flags field.
  15570. **
  15571. ** The DB_SchemaLoaded flag is set after the database schema has been
  15572. ** read into internal hash tables.
  15573. **
  15574. ** DB_UnresetViews means that one or more views have column names that
  15575. ** have been filled out. If the schema changes, these column names might
  15576. ** changes and so the view will need to be reset.
  15577. */
  15578. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  15579. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  15580. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  15581. #define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
  15582. /*
  15583. ** The number of different kinds of things that can be limited
  15584. ** using the sqlite3_limit() interface.
  15585. */
  15586. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  15587. /*
  15588. ** Lookaside malloc is a set of fixed-size buffers that can be used
  15589. ** to satisfy small transient memory allocation requests for objects
  15590. ** associated with a particular database connection. The use of
  15591. ** lookaside malloc provides a significant performance enhancement
  15592. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  15593. ** SQL statements.
  15594. **
  15595. ** The Lookaside structure holds configuration information about the
  15596. ** lookaside malloc subsystem. Each available memory allocation in
  15597. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  15598. ** objects.
  15599. **
  15600. ** Lookaside allocations are only allowed for objects that are associated
  15601. ** with a particular database connection. Hence, schema information cannot
  15602. ** be stored in lookaside because in shared cache mode the schema information
  15603. ** is shared by multiple database connections. Therefore, while parsing
  15604. ** schema information, the Lookaside.bEnabled flag is cleared so that
  15605. ** lookaside allocations are not used to construct the schema objects.
  15606. */
  15607. struct Lookaside {
  15608. u32 bDisable; /* Only operate the lookaside when zero */
  15609. u16 sz; /* Size of each buffer in bytes */
  15610. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  15611. u32 nSlot; /* Number of lookaside slots allocated */
  15612. u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  15613. LookasideSlot *pInit; /* List of buffers not previously used */
  15614. LookasideSlot *pFree; /* List of available buffers */
  15615. void *pStart; /* First byte of available memory space */
  15616. void *pEnd; /* First byte past end of available space */
  15617. };
  15618. struct LookasideSlot {
  15619. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  15620. };
  15621. /*
  15622. ** A hash table for built-in function definitions. (Application-defined
  15623. ** functions use a regular table table from hash.h.)
  15624. **
  15625. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  15626. ** Collisions are on the FuncDef.u.pHash chain. Use the SQLITE_FUNC_HASH()
  15627. ** macro to compute a hash on the function name.
  15628. */
  15629. #define SQLITE_FUNC_HASH_SZ 23
  15630. struct FuncDefHash {
  15631. FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
  15632. };
  15633. #define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
  15634. #ifdef SQLITE_USER_AUTHENTICATION
  15635. /*
  15636. ** Information held in the "sqlite3" database connection object and used
  15637. ** to manage user authentication.
  15638. */
  15639. typedef struct sqlite3_userauth sqlite3_userauth;
  15640. struct sqlite3_userauth {
  15641. u8 authLevel; /* Current authentication level */
  15642. int nAuthPW; /* Size of the zAuthPW in bytes */
  15643. char *zAuthPW; /* Password used to authenticate */
  15644. char *zAuthUser; /* User name used to authenticate */
  15645. };
  15646. /* Allowed values for sqlite3_userauth.authLevel */
  15647. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  15648. #define UAUTH_Fail 1 /* User authentication failed */
  15649. #define UAUTH_User 2 /* Authenticated as a normal user */
  15650. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  15651. /* Functions used only by user authorization logic */
  15652. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  15653. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  15654. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  15655. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  15656. #endif /* SQLITE_USER_AUTHENTICATION */
  15657. /*
  15658. ** typedef for the authorization callback function.
  15659. */
  15660. #ifdef SQLITE_USER_AUTHENTICATION
  15661. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  15662. const char*, const char*);
  15663. #else
  15664. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  15665. const char*);
  15666. #endif
  15667. #ifndef SQLITE_OMIT_DEPRECATED
  15668. /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
  15669. ** in the style of sqlite3_trace()
  15670. */
  15671. #define SQLITE_TRACE_LEGACY 0x40 /* Use the legacy xTrace */
  15672. #define SQLITE_TRACE_XPROFILE 0x80 /* Use the legacy xProfile */
  15673. #else
  15674. #define SQLITE_TRACE_LEGACY 0
  15675. #define SQLITE_TRACE_XPROFILE 0
  15676. #endif /* SQLITE_OMIT_DEPRECATED */
  15677. #define SQLITE_TRACE_NONLEGACY_MASK 0x0f /* Normal flags */
  15678. /*
  15679. ** Each database connection is an instance of the following structure.
  15680. */
  15681. struct sqlite3 {
  15682. sqlite3_vfs *pVfs; /* OS Interface */
  15683. struct Vdbe *pVdbe; /* List of active virtual machines */
  15684. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  15685. sqlite3_mutex *mutex; /* Connection mutex */
  15686. Db *aDb; /* All backends */
  15687. int nDb; /* Number of backends currently in use */
  15688. u32 mDbFlags; /* flags recording internal state */
  15689. u64 flags; /* flags settable by pragmas. See below */
  15690. i64 lastRowid; /* ROWID of most recent insert (see above) */
  15691. i64 szMmap; /* Default mmap_size setting */
  15692. u32 nSchemaLock; /* Do not reset the schema when non-zero */
  15693. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  15694. int errCode; /* Most recent error code (SQLITE_*) */
  15695. int errMask; /* & result codes with this before returning */
  15696. int iSysErrno; /* Errno value from last system error */
  15697. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  15698. u8 enc; /* Text encoding */
  15699. u8 autoCommit; /* The auto-commit flag. */
  15700. u8 temp_store; /* 1: file 2: memory 0: default */
  15701. u8 mallocFailed; /* True if we have seen a malloc failure */
  15702. u8 bBenignMalloc; /* Do not require OOMs if true */
  15703. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  15704. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  15705. u8 suppressErr; /* Do not issue error messages if true */
  15706. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  15707. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  15708. u8 mTrace; /* zero or more SQLITE_TRACE flags */
  15709. u8 noSharedCache; /* True if no shared-cache backends */
  15710. u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
  15711. int nextPagesize; /* Pagesize after VACUUM if >0 */
  15712. u32 magic; /* Magic number for detect library misuse */
  15713. int nChange; /* Value returned by sqlite3_changes() */
  15714. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  15715. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  15716. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  15717. struct sqlite3InitInfo { /* Information used during initialization */
  15718. int newTnum; /* Rootpage of table being initialized */
  15719. u8 iDb; /* Which db file is being initialized */
  15720. u8 busy; /* TRUE if currently initializing */
  15721. unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
  15722. unsigned imposterTable : 1; /* Building an imposter table */
  15723. unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */
  15724. } init;
  15725. int nVdbeActive; /* Number of VDBEs currently running */
  15726. int nVdbeRead; /* Number of active VDBEs that read or write */
  15727. int nVdbeWrite; /* Number of active VDBEs that read and write */
  15728. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  15729. int nVDestroy; /* Number of active OP_VDestroy operations */
  15730. int nExtension; /* Number of loaded extensions */
  15731. void **aExtension; /* Array of shared library handles */
  15732. int (*xTrace)(u32,void*,void*,void*); /* Trace function */
  15733. void *pTraceArg; /* Argument to the trace function */
  15734. #ifndef SQLITE_OMIT_DEPRECATED
  15735. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  15736. void *pProfileArg; /* Argument to profile function */
  15737. #endif
  15738. void *pCommitArg; /* Argument to xCommitCallback() */
  15739. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  15740. void *pRollbackArg; /* Argument to xRollbackCallback() */
  15741. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  15742. void *pUpdateArg;
  15743. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  15744. Parse *pParse; /* Current parse */
  15745. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  15746. void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
  15747. void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
  15748. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
  15749. );
  15750. PreUpdate *pPreUpdate; /* Context for active pre-update callback */
  15751. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  15752. #ifndef SQLITE_OMIT_WAL
  15753. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  15754. void *pWalArg;
  15755. #endif
  15756. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  15757. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  15758. void *pCollNeededArg;
  15759. sqlite3_value *pErr; /* Most recent error message */
  15760. union {
  15761. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  15762. double notUsed1; /* Spacer */
  15763. } u1;
  15764. Lookaside lookaside; /* Lookaside malloc configuration */
  15765. #ifndef SQLITE_OMIT_AUTHORIZATION
  15766. sqlite3_xauth xAuth; /* Access authorization function */
  15767. void *pAuthArg; /* 1st argument to the access auth function */
  15768. #endif
  15769. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  15770. int (*xProgress)(void *); /* The progress callback */
  15771. void *pProgressArg; /* Argument to the progress callback */
  15772. unsigned nProgressOps; /* Number of opcodes for progress callback */
  15773. #endif
  15774. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15775. int nVTrans; /* Allocated size of aVTrans */
  15776. Hash aModule; /* populated by sqlite3_create_module() */
  15777. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  15778. VTable **aVTrans; /* Virtual tables with open transactions */
  15779. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  15780. #endif
  15781. Hash aFunc; /* Hash table of connection functions */
  15782. Hash aCollSeq; /* All collating sequences */
  15783. BusyHandler busyHandler; /* Busy callback */
  15784. Db aDbStatic[2]; /* Static space for the 2 default backends */
  15785. Savepoint *pSavepoint; /* List of active savepoints */
  15786. int busyTimeout; /* Busy handler timeout, in msec */
  15787. int nSavepoint; /* Number of non-transaction savepoints */
  15788. int nStatement; /* Number of nested statement-transactions */
  15789. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  15790. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  15791. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  15792. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  15793. /* The following variables are all protected by the STATIC_MASTER
  15794. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  15795. **
  15796. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  15797. ** unlock so that it can proceed.
  15798. **
  15799. ** When X.pBlockingConnection==Y, that means that something that X tried
  15800. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  15801. ** held by Y.
  15802. */
  15803. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  15804. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  15805. void *pUnlockArg; /* Argument to xUnlockNotify */
  15806. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  15807. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  15808. #endif
  15809. #ifdef SQLITE_USER_AUTHENTICATION
  15810. sqlite3_userauth auth; /* User authentication information */
  15811. #endif
  15812. };
  15813. /*
  15814. ** A macro to discover the encoding of a database.
  15815. */
  15816. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  15817. #define ENC(db) ((db)->enc)
  15818. /*
  15819. ** Possible values for the sqlite3.flags.
  15820. **
  15821. ** Value constraints (enforced via assert()):
  15822. ** SQLITE_FullFSync == PAGER_FULLFSYNC
  15823. ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
  15824. ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
  15825. */
  15826. #define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_MASTER */
  15827. #define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
  15828. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  15829. #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
  15830. #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
  15831. #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
  15832. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  15833. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  15834. /* DELETE, or UPDATE and return */
  15835. /* the count using a callback. */
  15836. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  15837. /* result set is empty */
  15838. #define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
  15839. #define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
  15840. #define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
  15841. #define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
  15842. #define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
  15843. #define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
  15844. #define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
  15845. #define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
  15846. #define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
  15847. #define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
  15848. #define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
  15849. #define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
  15850. #define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
  15851. #define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
  15852. #define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee*/
  15853. #define SQLITE_TriggerEQP 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */
  15854. #define SQLITE_ResetDatabase 0x02000000 /* Reset the database */
  15855. #define SQLITE_LegacyAlter 0x04000000 /* Legacy ALTER TABLE behaviour */
  15856. #define SQLITE_NoSchemaError 0x08000000 /* Do not report schema parse errors*/
  15857. #define SQLITE_Defensive 0x10000000 /* Input SQL is likely hostile */
  15858. /* Flags used only if debugging */
  15859. #define HI(X) ((u64)(X)<<32)
  15860. #ifdef SQLITE_DEBUG
  15861. #define SQLITE_SqlTrace HI(0x0001) /* Debug print SQL as it executes */
  15862. #define SQLITE_VdbeListing HI(0x0002) /* Debug listings of VDBE progs */
  15863. #define SQLITE_VdbeTrace HI(0x0004) /* True to trace VDBE execution */
  15864. #define SQLITE_VdbeAddopTrace HI(0x0008) /* Trace sqlite3VdbeAddOp() calls */
  15865. #define SQLITE_VdbeEQP HI(0x0010) /* Debug EXPLAIN QUERY PLAN */
  15866. #define SQLITE_ParserTrace HI(0x0020) /* PRAGMA parser_trace=ON */
  15867. #endif
  15868. /*
  15869. ** Allowed values for sqlite3.mDbFlags
  15870. */
  15871. #define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
  15872. #define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
  15873. #define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
  15874. #define DBFLAG_VacuumInto 0x0008 /* Currently running VACUUM INTO */
  15875. #define DBFLAG_SchemaKnownOk 0x0010 /* Schema is known to be valid */
  15876. /*
  15877. ** Bits of the sqlite3.dbOptFlags field that are used by the
  15878. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  15879. ** selectively disable various optimizations.
  15880. */
  15881. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  15882. #define SQLITE_WindowFunc 0x0002 /* Use xInverse for window functions */
  15883. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  15884. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  15885. #define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */
  15886. #define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */
  15887. #define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */
  15888. #define SQLITE_Transitive 0x0080 /* Transitive constraints */
  15889. #define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */
  15890. #define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */
  15891. #define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */
  15892. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  15893. /* TH3 expects the Stat34 ^^^^^^ value to be 0x0800. Don't change it */
  15894. #define SQLITE_PushDown 0x1000 /* The push-down optimization */
  15895. #define SQLITE_SimplifyJoin 0x2000 /* Convert LEFT JOIN to JOIN */
  15896. #define SQLITE_SkipScan 0x4000 /* Skip-scans */
  15897. #define SQLITE_PropagateConst 0x8000 /* The constant propagation opt */
  15898. #define SQLITE_AllOpts 0xffff /* All optimizations */
  15899. /*
  15900. ** Macros for testing whether or not optimizations are enabled or disabled.
  15901. */
  15902. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  15903. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  15904. /*
  15905. ** Return true if it OK to factor constant expressions into the initialization
  15906. ** code. The argument is a Parse object for the code generator.
  15907. */
  15908. #define ConstFactorOk(P) ((P)->okConstFactor)
  15909. /*
  15910. ** Possible values for the sqlite.magic field.
  15911. ** The numbers are obtained at random and have no special meaning, other
  15912. ** than being distinct from one another.
  15913. */
  15914. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  15915. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  15916. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  15917. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  15918. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  15919. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  15920. /*
  15921. ** Each SQL function is defined by an instance of the following
  15922. ** structure. For global built-in functions (ex: substr(), max(), count())
  15923. ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
  15924. ** For per-connection application-defined functions, a pointer to this
  15925. ** structure is held in the db->aHash hash table.
  15926. **
  15927. ** The u.pHash field is used by the global built-ins. The u.pDestructor
  15928. ** field is used by per-connection app-def functions.
  15929. */
  15930. struct FuncDef {
  15931. i8 nArg; /* Number of arguments. -1 means unlimited */
  15932. u32 funcFlags; /* Some combination of SQLITE_FUNC_* */
  15933. void *pUserData; /* User data parameter */
  15934. FuncDef *pNext; /* Next function with same name */
  15935. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
  15936. void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
  15937. void (*xValue)(sqlite3_context*); /* Current agg value */
  15938. void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
  15939. const char *zName; /* SQL name of the function. */
  15940. union {
  15941. FuncDef *pHash; /* Next with a different name but the same hash */
  15942. FuncDestructor *pDestructor; /* Reference counted destructor function */
  15943. } u;
  15944. };
  15945. /*
  15946. ** This structure encapsulates a user-function destructor callback (as
  15947. ** configured using create_function_v2()) and a reference counter. When
  15948. ** create_function_v2() is called to create a function with a destructor,
  15949. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  15950. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  15951. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  15952. ** member of each of the new FuncDef objects is set to point to the allocated
  15953. ** FuncDestructor.
  15954. **
  15955. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  15956. ** count on this object is decremented. When it reaches 0, the destructor
  15957. ** is invoked and the FuncDestructor structure freed.
  15958. */
  15959. struct FuncDestructor {
  15960. int nRef;
  15961. void (*xDestroy)(void *);
  15962. void *pUserData;
  15963. };
  15964. /*
  15965. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  15966. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
  15967. ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
  15968. ** are assert() statements in the code to verify this.
  15969. **
  15970. ** Value constraints (enforced via assert()):
  15971. ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
  15972. ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
  15973. ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
  15974. ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
  15975. ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
  15976. */
  15977. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  15978. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  15979. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  15980. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  15981. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  15982. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  15983. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  15984. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  15985. #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
  15986. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  15987. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  15988. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  15989. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  15990. ** single query - might change over time */
  15991. #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
  15992. #define SQLITE_FUNC_OFFSET 0x8000 /* Built-in sqlite_offset() function */
  15993. #define SQLITE_FUNC_WINDOW 0x00010000 /* Built-in window-only function */
  15994. #define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
  15995. /*
  15996. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  15997. ** used to create the initializers for the FuncDef structures.
  15998. **
  15999. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  16000. ** Used to create a scalar function definition of a function zName
  16001. ** implemented by C function xFunc that accepts nArg arguments. The
  16002. ** value passed as iArg is cast to a (void*) and made available
  16003. ** as the user-data (sqlite3_user_data()) for the function. If
  16004. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  16005. **
  16006. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  16007. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  16008. **
  16009. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  16010. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  16011. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  16012. ** and functions like sqlite_version() that can change, but not during
  16013. ** a single query. The iArg is ignored. The user-data is always set
  16014. ** to a NULL pointer. The bNC parameter is not used.
  16015. **
  16016. ** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
  16017. ** Used for "pure" date/time functions, this macro is like DFUNCTION
  16018. ** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
  16019. ** ignored and the user-data for these functions is set to an
  16020. ** arbitrary non-NULL pointer. The bNC parameter is not used.
  16021. **
  16022. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  16023. ** Used to create an aggregate function definition implemented by
  16024. ** the C functions xStep and xFinal. The first four parameters
  16025. ** are interpreted in the same way as the first 4 parameters to
  16026. ** FUNCTION().
  16027. **
  16028. ** WFUNCTION(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
  16029. ** Used to create an aggregate function definition implemented by
  16030. ** the C functions xStep and xFinal. The first four parameters
  16031. ** are interpreted in the same way as the first 4 parameters to
  16032. ** FUNCTION().
  16033. **
  16034. ** LIKEFUNC(zName, nArg, pArg, flags)
  16035. ** Used to create a scalar function definition of a function zName
  16036. ** that accepts nArg arguments and is implemented by a call to C
  16037. ** function likeFunc. Argument pArg is cast to a (void *) and made
  16038. ** available as the function user-data (sqlite3_user_data()). The
  16039. ** FuncDef.flags variable is set to the value passed as the flags
  16040. ** parameter.
  16041. */
  16042. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  16043. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  16044. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  16045. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  16046. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  16047. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  16048. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  16049. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
  16050. 0, 0, xFunc, 0, 0, 0, #zName, {0} }
  16051. #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
  16052. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
  16053. (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
  16054. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  16055. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  16056. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  16057. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  16058. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  16059. pArg, 0, xFunc, 0, 0, 0, #zName, }
  16060. #define LIKEFUNC(zName, nArg, arg, flags) \
  16061. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  16062. (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
  16063. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue) \
  16064. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  16065. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,0,#zName, {0}}
  16066. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  16067. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  16068. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xFinal,0,#zName, {0}}
  16069. #define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
  16070. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
  16071. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
  16072. #define INTERNAL_FUNCTION(zName, nArg, xFunc) \
  16073. {nArg, SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
  16074. 0, 0, xFunc, 0, 0, 0, #zName, {0} }
  16075. /*
  16076. ** All current savepoints are stored in a linked list starting at
  16077. ** sqlite3.pSavepoint. The first element in the list is the most recently
  16078. ** opened savepoint. Savepoints are added to the list by the vdbe
  16079. ** OP_Savepoint instruction.
  16080. */
  16081. struct Savepoint {
  16082. char *zName; /* Savepoint name (nul-terminated) */
  16083. i64 nDeferredCons; /* Number of deferred fk violations */
  16084. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  16085. Savepoint *pNext; /* Parent savepoint (if any) */
  16086. };
  16087. /*
  16088. ** The following are used as the second parameter to sqlite3Savepoint(),
  16089. ** and as the P1 argument to the OP_Savepoint instruction.
  16090. */
  16091. #define SAVEPOINT_BEGIN 0
  16092. #define SAVEPOINT_RELEASE 1
  16093. #define SAVEPOINT_ROLLBACK 2
  16094. /*
  16095. ** Each SQLite module (virtual table definition) is defined by an
  16096. ** instance of the following structure, stored in the sqlite3.aModule
  16097. ** hash table.
  16098. */
  16099. struct Module {
  16100. const sqlite3_module *pModule; /* Callback pointers */
  16101. const char *zName; /* Name passed to create_module() */
  16102. void *pAux; /* pAux passed to create_module() */
  16103. void (*xDestroy)(void *); /* Module destructor function */
  16104. Table *pEpoTab; /* Eponymous table for this module */
  16105. };
  16106. /*
  16107. ** information about each column of an SQL table is held in an instance
  16108. ** of this structure.
  16109. */
  16110. struct Column {
  16111. char *zName; /* Name of this column, \000, then the type */
  16112. Expr *pDflt; /* Default value of this column */
  16113. char *zColl; /* Collating sequence. If NULL, use the default */
  16114. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  16115. char affinity; /* One of the SQLITE_AFF_... values */
  16116. u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
  16117. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  16118. };
  16119. /* Allowed values for Column.colFlags:
  16120. */
  16121. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  16122. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  16123. #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
  16124. #define COLFLAG_UNIQUE 0x0008 /* Column def contains "UNIQUE" or "PK" */
  16125. #define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */
  16126. /*
  16127. ** A "Collating Sequence" is defined by an instance of the following
  16128. ** structure. Conceptually, a collating sequence consists of a name and
  16129. ** a comparison routine that defines the order of that sequence.
  16130. **
  16131. ** If CollSeq.xCmp is NULL, it means that the
  16132. ** collating sequence is undefined. Indices built on an undefined
  16133. ** collating sequence may not be read or written.
  16134. */
  16135. struct CollSeq {
  16136. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  16137. u8 enc; /* Text encoding handled by xCmp() */
  16138. void *pUser; /* First argument to xCmp() */
  16139. int (*xCmp)(void*,int, const void*, int, const void*);
  16140. void (*xDel)(void*); /* Destructor for pUser */
  16141. };
  16142. /*
  16143. ** A sort order can be either ASC or DESC.
  16144. */
  16145. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  16146. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  16147. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  16148. /*
  16149. ** Column affinity types.
  16150. **
  16151. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  16152. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  16153. ** the speed a little by numbering the values consecutively.
  16154. **
  16155. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  16156. ** when multiple affinity types are concatenated into a string and
  16157. ** used as the P4 operand, they will be more readable.
  16158. **
  16159. ** Note also that the numeric types are grouped together so that testing
  16160. ** for a numeric type is a single comparison. And the BLOB type is first.
  16161. */
  16162. #define SQLITE_AFF_BLOB 'A'
  16163. #define SQLITE_AFF_TEXT 'B'
  16164. #define SQLITE_AFF_NUMERIC 'C'
  16165. #define SQLITE_AFF_INTEGER 'D'
  16166. #define SQLITE_AFF_REAL 'E'
  16167. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  16168. /*
  16169. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  16170. ** affinity value.
  16171. */
  16172. #define SQLITE_AFF_MASK 0x47
  16173. /*
  16174. ** Additional bit values that can be ORed with an affinity without
  16175. ** changing the affinity.
  16176. **
  16177. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  16178. ** It causes an assert() to fire if either operand to a comparison
  16179. ** operator is NULL. It is added to certain comparison operators to
  16180. ** prove that the operands are always NOT NULL.
  16181. */
  16182. #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
  16183. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  16184. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  16185. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  16186. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  16187. /*
  16188. ** An object of this type is created for each virtual table present in
  16189. ** the database schema.
  16190. **
  16191. ** If the database schema is shared, then there is one instance of this
  16192. ** structure for each database connection (sqlite3*) that uses the shared
  16193. ** schema. This is because each database connection requires its own unique
  16194. ** instance of the sqlite3_vtab* handle used to access the virtual table
  16195. ** implementation. sqlite3_vtab* handles can not be shared between
  16196. ** database connections, even when the rest of the in-memory database
  16197. ** schema is shared, as the implementation often stores the database
  16198. ** connection handle passed to it via the xConnect() or xCreate() method
  16199. ** during initialization internally. This database connection handle may
  16200. ** then be used by the virtual table implementation to access real tables
  16201. ** within the database. So that they appear as part of the callers
  16202. ** transaction, these accesses need to be made via the same database
  16203. ** connection as that used to execute SQL operations on the virtual table.
  16204. **
  16205. ** All VTable objects that correspond to a single table in a shared
  16206. ** database schema are initially stored in a linked-list pointed to by
  16207. ** the Table.pVTable member variable of the corresponding Table object.
  16208. ** When an sqlite3_prepare() operation is required to access the virtual
  16209. ** table, it searches the list for the VTable that corresponds to the
  16210. ** database connection doing the preparing so as to use the correct
  16211. ** sqlite3_vtab* handle in the compiled query.
  16212. **
  16213. ** When an in-memory Table object is deleted (for example when the
  16214. ** schema is being reloaded for some reason), the VTable objects are not
  16215. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  16216. ** immediately. Instead, they are moved from the Table.pVTable list to
  16217. ** another linked list headed by the sqlite3.pDisconnect member of the
  16218. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  16219. ** next time a statement is prepared using said sqlite3*. This is done
  16220. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  16221. ** Refer to comments above function sqlite3VtabUnlockList() for an
  16222. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  16223. ** list without holding the corresponding sqlite3.mutex mutex.
  16224. **
  16225. ** The memory for objects of this type is always allocated by
  16226. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  16227. ** the first argument.
  16228. */
  16229. struct VTable {
  16230. sqlite3 *db; /* Database connection associated with this table */
  16231. Module *pMod; /* Pointer to module implementation */
  16232. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  16233. int nRef; /* Number of pointers to this structure */
  16234. u8 bConstraint; /* True if constraints are supported */
  16235. int iSavepoint; /* Depth of the SAVEPOINT stack */
  16236. VTable *pNext; /* Next in linked list (see above) */
  16237. };
  16238. /*
  16239. ** The schema for each SQL table and view is represented in memory
  16240. ** by an instance of the following structure.
  16241. */
  16242. struct Table {
  16243. char *zName; /* Name of the table or view */
  16244. Column *aCol; /* Information about each column */
  16245. Index *pIndex; /* List of SQL indexes on this table. */
  16246. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  16247. FKey *pFKey; /* Linked list of all foreign keys in this table */
  16248. char *zColAff; /* String defining the affinity of each column */
  16249. ExprList *pCheck; /* All CHECK constraints */
  16250. /* ... also used as column name list in a VIEW */
  16251. int tnum; /* Root BTree page for this table */
  16252. u32 nTabRef; /* Number of pointers to this Table */
  16253. u32 tabFlags; /* Mask of TF_* values */
  16254. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  16255. i16 nCol; /* Number of columns in this table */
  16256. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  16257. LogEst szTabRow; /* Estimated size of each table row in bytes */
  16258. #ifdef SQLITE_ENABLE_COSTMULT
  16259. LogEst costMult; /* Cost multiplier for using this table */
  16260. #endif
  16261. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  16262. #ifndef SQLITE_OMIT_ALTERTABLE
  16263. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  16264. #endif
  16265. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16266. int nModuleArg; /* Number of arguments to the module */
  16267. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  16268. VTable *pVTable; /* List of VTable objects. */
  16269. #endif
  16270. Trigger *pTrigger; /* List of triggers stored in pSchema */
  16271. Schema *pSchema; /* Schema that contains this table */
  16272. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  16273. };
  16274. /*
  16275. ** Allowed values for Table.tabFlags.
  16276. **
  16277. ** TF_OOOHidden applies to tables or view that have hidden columns that are
  16278. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  16279. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  16280. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  16281. ** special handling during INSERT processing.
  16282. */
  16283. #define TF_Readonly 0x0001 /* Read-only system table */
  16284. #define TF_Ephemeral 0x0002 /* An ephemeral table */
  16285. #define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
  16286. #define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
  16287. #define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
  16288. #define TF_WithoutRowid 0x0020 /* No rowid. PRIMARY KEY is the key */
  16289. #define TF_NoVisibleRowid 0x0040 /* No user-visible "rowid" column */
  16290. #define TF_OOOHidden 0x0080 /* Out-of-Order hidden columns */
  16291. #define TF_StatsUsed 0x0100 /* Query planner decisions affected by
  16292. ** Index.aiRowLogEst[] values */
  16293. #define TF_HasNotNull 0x0200 /* Contains NOT NULL constraints */
  16294. #define TF_Shadow 0x0400 /* True for a shadow table */
  16295. /*
  16296. ** Test to see whether or not a table is a virtual table. This is
  16297. ** done as a macro so that it will be optimized out when virtual
  16298. ** table support is omitted from the build.
  16299. */
  16300. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16301. # define IsVirtual(X) ((X)->nModuleArg)
  16302. #else
  16303. # define IsVirtual(X) 0
  16304. #endif
  16305. /*
  16306. ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
  16307. ** only works for non-virtual tables (ordinary tables and views) and is
  16308. ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
  16309. ** IsHiddenColumn() macro is general purpose.
  16310. */
  16311. #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
  16312. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16313. # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16314. #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
  16315. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16316. # define IsOrdinaryHiddenColumn(X) 0
  16317. #else
  16318. # define IsHiddenColumn(X) 0
  16319. # define IsOrdinaryHiddenColumn(X) 0
  16320. #endif
  16321. /* Does the table have a rowid */
  16322. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  16323. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  16324. /*
  16325. ** Each foreign key constraint is an instance of the following structure.
  16326. **
  16327. ** A foreign key is associated with two tables. The "from" table is
  16328. ** the table that contains the REFERENCES clause that creates the foreign
  16329. ** key. The "to" table is the table that is named in the REFERENCES clause.
  16330. ** Consider this example:
  16331. **
  16332. ** CREATE TABLE ex1(
  16333. ** a INTEGER PRIMARY KEY,
  16334. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  16335. ** );
  16336. **
  16337. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  16338. ** Equivalent names:
  16339. **
  16340. ** from-table == child-table
  16341. ** to-table == parent-table
  16342. **
  16343. ** Each REFERENCES clause generates an instance of the following structure
  16344. ** which is attached to the from-table. The to-table need not exist when
  16345. ** the from-table is created. The existence of the to-table is not checked.
  16346. **
  16347. ** The list of all parents for child Table X is held at X.pFKey.
  16348. **
  16349. ** A list of all children for a table named Z (which might not even exist)
  16350. ** is held in Schema.fkeyHash with a hash key of Z.
  16351. */
  16352. struct FKey {
  16353. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  16354. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  16355. char *zTo; /* Name of table that the key points to (aka: Parent) */
  16356. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  16357. FKey *pPrevTo; /* Previous with the same zTo */
  16358. int nCol; /* Number of columns in this key */
  16359. /* EV: R-30323-21917 */
  16360. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  16361. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  16362. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  16363. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  16364. int iFrom; /* Index of column in pFrom */
  16365. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  16366. } aCol[1]; /* One entry for each of nCol columns */
  16367. };
  16368. /*
  16369. ** SQLite supports many different ways to resolve a constraint
  16370. ** error. ROLLBACK processing means that a constraint violation
  16371. ** causes the operation in process to fail and for the current transaction
  16372. ** to be rolled back. ABORT processing means the operation in process
  16373. ** fails and any prior changes from that one operation are backed out,
  16374. ** but the transaction is not rolled back. FAIL processing means that
  16375. ** the operation in progress stops and returns an error code. But prior
  16376. ** changes due to the same operation are not backed out and no rollback
  16377. ** occurs. IGNORE means that the particular row that caused the constraint
  16378. ** error is not inserted or updated. Processing continues and no error
  16379. ** is returned. REPLACE means that preexisting database rows that caused
  16380. ** a UNIQUE constraint violation are removed so that the new insert or
  16381. ** update can proceed. Processing continues and no error is reported.
  16382. **
  16383. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  16384. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  16385. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  16386. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  16387. ** referenced table row is propagated into the row that holds the
  16388. ** foreign key.
  16389. **
  16390. ** The following symbolic values are used to record which type
  16391. ** of action to take.
  16392. */
  16393. #define OE_None 0 /* There is no constraint to check */
  16394. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  16395. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  16396. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  16397. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  16398. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  16399. #define OE_Update 6 /* Process as a DO UPDATE in an upsert */
  16400. #define OE_Restrict 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  16401. #define OE_SetNull 8 /* Set the foreign key value to NULL */
  16402. #define OE_SetDflt 9 /* Set the foreign key value to its default */
  16403. #define OE_Cascade 10 /* Cascade the changes */
  16404. #define OE_Default 11 /* Do whatever the default action is */
  16405. /*
  16406. ** An instance of the following structure is passed as the first
  16407. ** argument to sqlite3VdbeKeyCompare and is used to control the
  16408. ** comparison of the two index keys.
  16409. **
  16410. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  16411. ** are nField slots for the columns of an index then one extra slot
  16412. ** for the rowid at the end.
  16413. */
  16414. struct KeyInfo {
  16415. u32 nRef; /* Number of references to this KeyInfo object */
  16416. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  16417. u16 nKeyField; /* Number of key columns in the index */
  16418. u16 nAllField; /* Total columns, including key plus others */
  16419. sqlite3 *db; /* The database connection */
  16420. u8 *aSortOrder; /* Sort order for each column. */
  16421. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  16422. };
  16423. /*
  16424. ** This object holds a record which has been parsed out into individual
  16425. ** fields, for the purposes of doing a comparison.
  16426. **
  16427. ** A record is an object that contains one or more fields of data.
  16428. ** Records are used to store the content of a table row and to store
  16429. ** the key of an index. A blob encoding of a record is created by
  16430. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  16431. ** OP_Column opcode.
  16432. **
  16433. ** An instance of this object serves as a "key" for doing a search on
  16434. ** an index b+tree. The goal of the search is to find the entry that
  16435. ** is closed to the key described by this object. This object might hold
  16436. ** just a prefix of the key. The number of fields is given by
  16437. ** pKeyInfo->nField.
  16438. **
  16439. ** The r1 and r2 fields are the values to return if this key is less than
  16440. ** or greater than a key in the btree, respectively. These are normally
  16441. ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
  16442. ** is in DESC order.
  16443. **
  16444. ** The key comparison functions actually return default_rc when they find
  16445. ** an equals comparison. default_rc can be -1, 0, or +1. If there are
  16446. ** multiple entries in the b-tree with the same key (when only looking
  16447. ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
  16448. ** cause the search to find the last match, or +1 to cause the search to
  16449. ** find the first match.
  16450. **
  16451. ** The key comparison functions will set eqSeen to true if they ever
  16452. ** get and equal results when comparing this structure to a b-tree record.
  16453. ** When default_rc!=0, the search might end up on the record immediately
  16454. ** before the first match or immediately after the last match. The
  16455. ** eqSeen field will indicate whether or not an exact match exists in the
  16456. ** b-tree.
  16457. */
  16458. struct UnpackedRecord {
  16459. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  16460. Mem *aMem; /* Values */
  16461. u16 nField; /* Number of entries in apMem[] */
  16462. i8 default_rc; /* Comparison result if keys are equal */
  16463. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  16464. i8 r1; /* Value to return if (lhs < rhs) */
  16465. i8 r2; /* Value to return if (lhs > rhs) */
  16466. u8 eqSeen; /* True if an equality comparison has been seen */
  16467. };
  16468. /*
  16469. ** Each SQL index is represented in memory by an
  16470. ** instance of the following structure.
  16471. **
  16472. ** The columns of the table that are to be indexed are described
  16473. ** by the aiColumn[] field of this structure. For example, suppose
  16474. ** we have the following table and index:
  16475. **
  16476. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  16477. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  16478. **
  16479. ** In the Table structure describing Ex1, nCol==3 because there are
  16480. ** three columns in the table. In the Index structure describing
  16481. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  16482. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  16483. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  16484. ** The second column to be indexed (c1) has an index of 0 in
  16485. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  16486. **
  16487. ** The Index.onError field determines whether or not the indexed columns
  16488. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  16489. ** it means this is not a unique index. Otherwise it is a unique index
  16490. ** and the value of Index.onError indicate the which conflict resolution
  16491. ** algorithm to employ whenever an attempt is made to insert a non-unique
  16492. ** element.
  16493. **
  16494. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  16495. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  16496. ** table as part of parsing an existing database schema), transient instances
  16497. ** of this structure may be created. In this case the Index.tnum variable is
  16498. ** used to store the address of a VDBE instruction, not a database page
  16499. ** number (it cannot - the database page is not allocated until the VDBE
  16500. ** program is executed). See convertToWithoutRowidTable() for details.
  16501. */
  16502. struct Index {
  16503. char *zName; /* Name of this index */
  16504. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  16505. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  16506. Table *pTable; /* The SQL table being indexed */
  16507. char *zColAff; /* String defining the affinity of each column */
  16508. Index *pNext; /* The next index associated with the same table */
  16509. Schema *pSchema; /* Schema containing this index */
  16510. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  16511. const char **azColl; /* Array of collation sequence names for index */
  16512. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  16513. ExprList *aColExpr; /* Column expressions */
  16514. int tnum; /* DB Page containing root of this index */
  16515. LogEst szIdxRow; /* Estimated average row size in bytes */
  16516. u16 nKeyCol; /* Number of columns forming the key */
  16517. u16 nColumn; /* Number of columns stored in the index */
  16518. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  16519. unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */
  16520. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  16521. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  16522. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  16523. unsigned isCovering:1; /* True if this is a covering index */
  16524. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  16525. unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
  16526. unsigned bNoQuery:1; /* Do not use this index to optimize queries */
  16527. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  16528. int nSample; /* Number of elements in aSample[] */
  16529. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  16530. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  16531. IndexSample *aSample; /* Samples of the left-most key */
  16532. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  16533. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  16534. #endif
  16535. Bitmask colNotIdxed; /* 0 for unindexed columns in pTab */
  16536. };
  16537. /*
  16538. ** Allowed values for Index.idxType
  16539. */
  16540. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  16541. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  16542. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  16543. #define SQLITE_IDXTYPE_IPK 3 /* INTEGER PRIMARY KEY index */
  16544. /* Return true if index X is a PRIMARY KEY index */
  16545. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  16546. /* Return true if index X is a UNIQUE index */
  16547. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  16548. /* The Index.aiColumn[] values are normally positive integer. But
  16549. ** there are some negative values that have special meaning:
  16550. */
  16551. #define XN_ROWID (-1) /* Indexed column is the rowid */
  16552. #define XN_EXPR (-2) /* Indexed column is an expression */
  16553. /*
  16554. ** Each sample stored in the sqlite_stat3 table is represented in memory
  16555. ** using a structure of this type. See documentation at the top of the
  16556. ** analyze.c source file for additional information.
  16557. */
  16558. struct IndexSample {
  16559. void *p; /* Pointer to sampled record */
  16560. int n; /* Size of record in bytes */
  16561. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  16562. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  16563. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  16564. };
  16565. /*
  16566. ** Possible values to use within the flags argument to sqlite3GetToken().
  16567. */
  16568. #define SQLITE_TOKEN_QUOTED 0x1 /* Token is a quoted identifier. */
  16569. #define SQLITE_TOKEN_KEYWORD 0x2 /* Token is a keyword. */
  16570. /*
  16571. ** Each token coming out of the lexer is an instance of
  16572. ** this structure. Tokens are also used as part of an expression.
  16573. **
  16574. ** The memory that "z" points to is owned by other objects. Take care
  16575. ** that the owner of the "z" string does not deallocate the string before
  16576. ** the Token goes out of scope! Very often, the "z" points to some place
  16577. ** in the middle of the Parse.zSql text. But it might also point to a
  16578. ** static string.
  16579. */
  16580. struct Token {
  16581. const char *z; /* Text of the token. Not NULL-terminated! */
  16582. unsigned int n; /* Number of characters in this token */
  16583. };
  16584. /*
  16585. ** An instance of this structure contains information needed to generate
  16586. ** code for a SELECT that contains aggregate functions.
  16587. **
  16588. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  16589. ** pointer to this structure. The Expr.iColumn field is the index in
  16590. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  16591. ** code for that node.
  16592. **
  16593. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  16594. ** original Select structure that describes the SELECT statement. These
  16595. ** fields do not need to be freed when deallocating the AggInfo structure.
  16596. */
  16597. struct AggInfo {
  16598. u8 directMode; /* Direct rendering mode means take data directly
  16599. ** from source tables rather than from accumulators */
  16600. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  16601. ** than the source table */
  16602. int sortingIdx; /* Cursor number of the sorting index */
  16603. int sortingIdxPTab; /* Cursor number of pseudo-table */
  16604. int nSortingColumn; /* Number of columns in the sorting index */
  16605. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  16606. ExprList *pGroupBy; /* The group by clause */
  16607. struct AggInfo_col { /* For each column used in source tables */
  16608. Table *pTab; /* Source table */
  16609. int iTable; /* Cursor number of the source table */
  16610. int iColumn; /* Column number within the source table */
  16611. int iSorterColumn; /* Column number in the sorting index */
  16612. int iMem; /* Memory location that acts as accumulator */
  16613. Expr *pExpr; /* The original expression */
  16614. } *aCol;
  16615. int nColumn; /* Number of used entries in aCol[] */
  16616. int nAccumulator; /* Number of columns that show through to the output.
  16617. ** Additional columns are used only as parameters to
  16618. ** aggregate functions */
  16619. struct AggInfo_func { /* For each aggregate function */
  16620. Expr *pExpr; /* Expression encoding the function */
  16621. FuncDef *pFunc; /* The aggregate function implementation */
  16622. int iMem; /* Memory location that acts as accumulator */
  16623. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  16624. } *aFunc;
  16625. int nFunc; /* Number of entries in aFunc[] */
  16626. };
  16627. /*
  16628. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  16629. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  16630. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  16631. ** it uses less memory in the Expr object, which is a big memory user
  16632. ** in systems with lots of prepared statements. And few applications
  16633. ** need more than about 10 or 20 variables. But some extreme users want
  16634. ** to have prepared statements with over 32767 variables, and for them
  16635. ** the option is available (at compile-time).
  16636. */
  16637. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  16638. typedef i16 ynVar;
  16639. #else
  16640. typedef int ynVar;
  16641. #endif
  16642. /*
  16643. ** Each node of an expression in the parse tree is an instance
  16644. ** of this structure.
  16645. **
  16646. ** Expr.op is the opcode. The integer parser token codes are reused
  16647. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  16648. ** code representing the ">=" operator. This same integer code is reused
  16649. ** to represent the greater-than-or-equal-to operator in the expression
  16650. ** tree.
  16651. **
  16652. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  16653. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  16654. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  16655. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  16656. ** then Expr.token contains the name of the function.
  16657. **
  16658. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  16659. ** binary operator. Either or both may be NULL.
  16660. **
  16661. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  16662. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  16663. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  16664. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  16665. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  16666. ** valid.
  16667. **
  16668. ** An expression of the form ID or ID.ID refers to a column in a table.
  16669. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  16670. ** the integer cursor number of a VDBE cursor pointing to that table and
  16671. ** Expr.iColumn is the column number for the specific column. If the
  16672. ** expression is used as a result in an aggregate SELECT, then the
  16673. ** value is also stored in the Expr.iAgg column in the aggregate so that
  16674. ** it can be accessed after all aggregates are computed.
  16675. **
  16676. ** If the expression is an unbound variable marker (a question mark
  16677. ** character '?' in the original SQL) then the Expr.iTable holds the index
  16678. ** number for that variable.
  16679. **
  16680. ** If the expression is a subquery then Expr.iColumn holds an integer
  16681. ** register number containing the result of the subquery. If the
  16682. ** subquery gives a constant result, then iTable is -1. If the subquery
  16683. ** gives a different answer at different times during statement processing
  16684. ** then iTable is the address of a subroutine that computes the subquery.
  16685. **
  16686. ** If the Expr is of type OP_Column, and the table it is selecting from
  16687. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  16688. ** corresponding table definition.
  16689. **
  16690. ** ALLOCATION NOTES:
  16691. **
  16692. ** Expr objects can use a lot of memory space in database schema. To
  16693. ** help reduce memory requirements, sometimes an Expr object will be
  16694. ** truncated. And to reduce the number of memory allocations, sometimes
  16695. ** two or more Expr objects will be stored in a single memory allocation,
  16696. ** together with Expr.zToken strings.
  16697. **
  16698. ** If the EP_Reduced and EP_TokenOnly flags are set when
  16699. ** an Expr object is truncated. When EP_Reduced is set, then all
  16700. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  16701. ** are contained within the same memory allocation. Note, however, that
  16702. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  16703. ** allocated, regardless of whether or not EP_Reduced is set.
  16704. */
  16705. struct Expr {
  16706. u8 op; /* Operation performed by this node */
  16707. char affinity; /* The affinity of the column or 0 if not a column */
  16708. u32 flags; /* Various flags. EP_* See below */
  16709. union {
  16710. char *zToken; /* Token value. Zero terminated and dequoted */
  16711. int iValue; /* Non-negative integer value if EP_IntValue */
  16712. } u;
  16713. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  16714. ** space is allocated for the fields below this point. An attempt to
  16715. ** access them will result in a segfault or malfunction.
  16716. *********************************************************************/
  16717. Expr *pLeft; /* Left subnode */
  16718. Expr *pRight; /* Right subnode */
  16719. union {
  16720. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  16721. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  16722. } x;
  16723. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  16724. ** space is allocated for the fields below this point. An attempt to
  16725. ** access them will result in a segfault or malfunction.
  16726. *********************************************************************/
  16727. #if SQLITE_MAX_EXPR_DEPTH>0
  16728. int nHeight; /* Height of the tree headed by this node */
  16729. #endif
  16730. int iTable; /* TK_COLUMN: cursor number of table holding column
  16731. ** TK_REGISTER: register number
  16732. ** TK_TRIGGER: 1 -> new, 0 -> old
  16733. ** EP_Unlikely: 134217728 times likelihood
  16734. ** TK_SELECT: 1st register of result vector */
  16735. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  16736. ** TK_VARIABLE: variable number (always >= 1).
  16737. ** TK_SELECT_COLUMN: column of the result vector */
  16738. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  16739. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  16740. u8 op2; /* TK_REGISTER: original value of Expr.op
  16741. ** TK_COLUMN: the value of p5 for OP_Column
  16742. ** TK_AGG_FUNCTION: nesting depth */
  16743. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  16744. union {
  16745. Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL
  16746. ** for a column of an index on an expression */
  16747. Window *pWin; /* TK_FUNCTION: Window definition for the func */
  16748. struct { /* TK_IN, TK_SELECT, and TK_EXISTS */
  16749. int iAddr; /* Subroutine entry address */
  16750. int regReturn; /* Register used to hold return address */
  16751. } sub;
  16752. } y;
  16753. };
  16754. /*
  16755. ** The following are the meanings of bits in the Expr.flags field.
  16756. ** Value restrictions:
  16757. **
  16758. ** EP_Agg == NC_HasAgg == SF_HasAgg
  16759. ** EP_Win == NC_HasWin
  16760. */
  16761. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  16762. #define EP_Distinct 0x000002 /* Aggregate function with DISTINCT keyword */
  16763. #define EP_HasFunc 0x000004 /* Contains one or more functions of any kind */
  16764. #define EP_FixedCol 0x000008 /* TK_Column with a known fixed value */
  16765. #define EP_Agg 0x000010 /* Contains one or more aggregate functions */
  16766. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  16767. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  16768. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  16769. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  16770. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  16771. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  16772. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  16773. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  16774. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  16775. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  16776. #define EP_Win 0x008000 /* Contains window functions */
  16777. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  16778. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  16779. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  16780. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  16781. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  16782. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  16783. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  16784. #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
  16785. #define EP_WinFunc 0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
  16786. #define EP_Subrtn 0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
  16787. #define EP_Quoted 0x4000000 /* TK_ID was originally quoted */
  16788. #define EP_Static 0x8000000 /* Held in memory not obtained from malloc() */
  16789. /*
  16790. ** The EP_Propagate mask is a set of properties that automatically propagate
  16791. ** upwards into parent nodes.
  16792. */
  16793. #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
  16794. /*
  16795. ** These macros can be used to test, set, or clear bits in the
  16796. ** Expr.flags field.
  16797. */
  16798. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  16799. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  16800. #define ExprSetProperty(E,P) (E)->flags|=(P)
  16801. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  16802. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  16803. ** and Accreditation only. It works like ExprSetProperty() during VVA
  16804. ** processes but is a no-op for delivery.
  16805. */
  16806. #ifdef SQLITE_DEBUG
  16807. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  16808. #else
  16809. # define ExprSetVVAProperty(E,P)
  16810. #endif
  16811. /*
  16812. ** Macros to determine the number of bytes required by a normal Expr
  16813. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  16814. ** and an Expr struct with the EP_TokenOnly flag set.
  16815. */
  16816. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  16817. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  16818. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  16819. /*
  16820. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  16821. ** above sqlite3ExprDup() for details.
  16822. */
  16823. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  16824. /*
  16825. ** A list of expressions. Each expression may optionally have a
  16826. ** name. An expr/name combination can be used in several ways, such
  16827. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  16828. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  16829. ** also be used as the argument to a function, in which case the a.zName
  16830. ** field is not used.
  16831. **
  16832. ** By default the Expr.zSpan field holds a human-readable description of
  16833. ** the expression that is used in the generation of error messages and
  16834. ** column labels. In this case, Expr.zSpan is typically the text of a
  16835. ** column expression as it exists in a SELECT statement. However, if
  16836. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  16837. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  16838. ** form is used for name resolution with nested FROM clauses.
  16839. */
  16840. struct ExprList {
  16841. int nExpr; /* Number of expressions on the list */
  16842. struct ExprList_item { /* For each expression in the list */
  16843. Expr *pExpr; /* The parse tree for this expression */
  16844. char *zName; /* Token associated with this expression */
  16845. char *zSpan; /* Original text of the expression */
  16846. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  16847. unsigned done :1; /* A flag to indicate when processing is finished */
  16848. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  16849. unsigned reusable :1; /* Constant expression is reusable */
  16850. unsigned bSorterRef :1; /* Defer evaluation until after sorting */
  16851. union {
  16852. struct {
  16853. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  16854. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  16855. } x;
  16856. int iConstExprReg; /* Register in which Expr value is cached */
  16857. } u;
  16858. } a[1]; /* One slot for each expression in the list */
  16859. };
  16860. /*
  16861. ** An instance of this structure can hold a simple list of identifiers,
  16862. ** such as the list "a,b,c" in the following statements:
  16863. **
  16864. ** INSERT INTO t(a,b,c) VALUES ...;
  16865. ** CREATE INDEX idx ON t(a,b,c);
  16866. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  16867. **
  16868. ** The IdList.a.idx field is used when the IdList represents the list of
  16869. ** column names after a table name in an INSERT statement. In the statement
  16870. **
  16871. ** INSERT INTO t(a,b,c) ...
  16872. **
  16873. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  16874. */
  16875. struct IdList {
  16876. struct IdList_item {
  16877. char *zName; /* Name of the identifier */
  16878. int idx; /* Index in some Table.aCol[] of a column named zName */
  16879. } *a;
  16880. int nId; /* Number of identifiers on the list */
  16881. };
  16882. /*
  16883. ** The following structure describes the FROM clause of a SELECT statement.
  16884. ** Each table or subquery in the FROM clause is a separate element of
  16885. ** the SrcList.a[] array.
  16886. **
  16887. ** With the addition of multiple database support, the following structure
  16888. ** can also be used to describe a particular table such as the table that
  16889. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  16890. ** such a table must be a simple name: ID. But in SQLite, the table can
  16891. ** now be identified by a database name, a dot, then the table name: ID.ID.
  16892. **
  16893. ** The jointype starts out showing the join type between the current table
  16894. ** and the next table on the list. The parser builds the list this way.
  16895. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  16896. ** jointype expresses the join between the table and the previous table.
  16897. **
  16898. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  16899. ** contains more than 63 columns and the 64-th or later column is used.
  16900. */
  16901. struct SrcList {
  16902. int nSrc; /* Number of tables or subqueries in the FROM clause */
  16903. u32 nAlloc; /* Number of entries allocated in a[] below */
  16904. struct SrcList_item {
  16905. Schema *pSchema; /* Schema to which this item is fixed */
  16906. char *zDatabase; /* Name of database holding this table */
  16907. char *zName; /* Name of the table */
  16908. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  16909. Table *pTab; /* An SQL table corresponding to zName */
  16910. Select *pSelect; /* A SELECT statement used in place of a table name */
  16911. int addrFillSub; /* Address of subroutine to manifest a subquery */
  16912. int regReturn; /* Register holding return address of addrFillSub */
  16913. int regResult; /* Registers holding results of a co-routine */
  16914. struct {
  16915. u8 jointype; /* Type of join between this table and the previous */
  16916. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  16917. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  16918. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  16919. unsigned isCorrelated :1; /* True if sub-query is correlated */
  16920. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  16921. unsigned isRecursive :1; /* True for recursive reference in WITH */
  16922. } fg;
  16923. int iCursor; /* The VDBE cursor number used to access this table */
  16924. Expr *pOn; /* The ON clause of a join */
  16925. IdList *pUsing; /* The USING clause of a join */
  16926. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  16927. union {
  16928. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  16929. ExprList *pFuncArg; /* Arguments to table-valued-function */
  16930. } u1;
  16931. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  16932. } a[1]; /* One entry for each identifier on the list */
  16933. };
  16934. /*
  16935. ** Permitted values of the SrcList.a.jointype field
  16936. */
  16937. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  16938. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  16939. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  16940. #define JT_LEFT 0x0008 /* Left outer join */
  16941. #define JT_RIGHT 0x0010 /* Right outer join */
  16942. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  16943. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  16944. /*
  16945. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  16946. ** and the WhereInfo.wctrlFlags member.
  16947. **
  16948. ** Value constraints (enforced via assert()):
  16949. ** WHERE_USE_LIMIT == SF_FixedLimit
  16950. */
  16951. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  16952. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  16953. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  16954. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  16955. #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
  16956. #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
  16957. #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
  16958. ** the OR optimization */
  16959. #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
  16960. #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
  16961. #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
  16962. #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
  16963. #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
  16964. #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
  16965. #define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */
  16966. /* 0x2000 not currently used */
  16967. #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
  16968. /* 0x8000 not currently used */
  16969. /* Allowed return values from sqlite3WhereIsDistinct()
  16970. */
  16971. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  16972. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  16973. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  16974. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  16975. /*
  16976. ** A NameContext defines a context in which to resolve table and column
  16977. ** names. The context consists of a list of tables (the pSrcList) field and
  16978. ** a list of named expression (pEList). The named expression list may
  16979. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  16980. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  16981. ** pEList corresponds to the result set of a SELECT and is NULL for
  16982. ** other statements.
  16983. **
  16984. ** NameContexts can be nested. When resolving names, the inner-most
  16985. ** context is searched first. If no match is found, the next outer
  16986. ** context is checked. If there is still no match, the next context
  16987. ** is checked. This process continues until either a match is found
  16988. ** or all contexts are check. When a match is found, the nRef member of
  16989. ** the context containing the match is incremented.
  16990. **
  16991. ** Each subquery gets a new NameContext. The pNext field points to the
  16992. ** NameContext in the parent query. Thus the process of scanning the
  16993. ** NameContext list corresponds to searching through successively outer
  16994. ** subqueries looking for a match.
  16995. */
  16996. struct NameContext {
  16997. Parse *pParse; /* The parser */
  16998. SrcList *pSrcList; /* One or more tables used to resolve names */
  16999. union {
  17000. ExprList *pEList; /* Optional list of result-set columns */
  17001. AggInfo *pAggInfo; /* Information about aggregates at this level */
  17002. Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */
  17003. } uNC;
  17004. NameContext *pNext; /* Next outer name context. NULL for outermost */
  17005. int nRef; /* Number of names resolved by this context */
  17006. int nErr; /* Number of errors encountered while resolving names */
  17007. u16 ncFlags; /* Zero or more NC_* flags defined below */
  17008. Select *pWinSelect; /* SELECT statement for any window functions */
  17009. };
  17010. /*
  17011. ** Allowed values for the NameContext, ncFlags field.
  17012. **
  17013. ** Value constraints (all checked via assert()):
  17014. ** NC_HasAgg == SF_HasAgg == EP_Agg
  17015. ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
  17016. ** NC_HasWin == EP_Win
  17017. **
  17018. */
  17019. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  17020. #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
  17021. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  17022. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  17023. #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
  17024. #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
  17025. #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
  17026. #define NC_UEList 0x0080 /* True if uNC.pEList is used */
  17027. #define NC_UAggInfo 0x0100 /* True if uNC.pAggInfo is used */
  17028. #define NC_UUpsert 0x0200 /* True if uNC.pUpsert is used */
  17029. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  17030. #define NC_Complex 0x2000 /* True if a function or subquery seen */
  17031. #define NC_AllowWin 0x4000 /* Window functions are allowed here */
  17032. #define NC_HasWin 0x8000 /* One or more window functions seen */
  17033. /*
  17034. ** An instance of the following object describes a single ON CONFLICT
  17035. ** clause in an upsert.
  17036. **
  17037. ** The pUpsertTarget field is only set if the ON CONFLICT clause includes
  17038. ** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
  17039. ** conflict-target clause.) The pUpsertTargetWhere is the optional
  17040. ** WHERE clause used to identify partial unique indexes.
  17041. **
  17042. ** pUpsertSet is the list of column=expr terms of the UPDATE statement.
  17043. ** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The
  17044. ** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
  17045. ** WHERE clause is omitted.
  17046. */
  17047. struct Upsert {
  17048. ExprList *pUpsertTarget; /* Optional description of conflicting index */
  17049. Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
  17050. ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */
  17051. Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */
  17052. /* The fields above comprise the parse tree for the upsert clause.
  17053. ** The fields below are used to transfer information from the INSERT
  17054. ** processing down into the UPDATE processing while generating code.
  17055. ** Upsert owns the memory allocated above, but not the memory below. */
  17056. Index *pUpsertIdx; /* Constraint that pUpsertTarget identifies */
  17057. SrcList *pUpsertSrc; /* Table to be updated */
  17058. int regData; /* First register holding array of VALUES */
  17059. int iDataCur; /* Index of the data cursor */
  17060. int iIdxCur; /* Index of the first index cursor */
  17061. };
  17062. /*
  17063. ** An instance of the following structure contains all information
  17064. ** needed to generate code for a single SELECT statement.
  17065. **
  17066. ** See the header comment on the computeLimitRegisters() routine for a
  17067. ** detailed description of the meaning of the iLimit and iOffset fields.
  17068. **
  17069. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  17070. ** These addresses must be stored so that we can go back and fill in
  17071. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  17072. ** the number of columns in P2 can be computed at the same time
  17073. ** as the OP_OpenEphm instruction is coded because not
  17074. ** enough information about the compound query is known at that point.
  17075. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  17076. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  17077. ** sequences for the ORDER BY clause.
  17078. */
  17079. struct Select {
  17080. ExprList *pEList; /* The fields of the result */
  17081. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  17082. LogEst nSelectRow; /* Estimated number of result rows */
  17083. u32 selFlags; /* Various SF_* values */
  17084. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  17085. u32 selId; /* Unique identifier number for this SELECT */
  17086. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  17087. SrcList *pSrc; /* The FROM clause */
  17088. Expr *pWhere; /* The WHERE clause */
  17089. ExprList *pGroupBy; /* The GROUP BY clause */
  17090. Expr *pHaving; /* The HAVING clause */
  17091. ExprList *pOrderBy; /* The ORDER BY clause */
  17092. Select *pPrior; /* Prior select in a compound select statement */
  17093. Select *pNext; /* Next select to the left in a compound */
  17094. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  17095. With *pWith; /* WITH clause attached to this select. Or NULL. */
  17096. #ifndef SQLITE_OMIT_WINDOWFUNC
  17097. Window *pWin; /* List of window functions */
  17098. Window *pWinDefn; /* List of named window definitions */
  17099. #endif
  17100. };
  17101. /*
  17102. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  17103. ** "Select Flag".
  17104. **
  17105. ** Value constraints (all checked via assert())
  17106. ** SF_HasAgg == NC_HasAgg
  17107. ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
  17108. ** SF_FixedLimit == WHERE_USE_LIMIT
  17109. */
  17110. #define SF_Distinct 0x00001 /* Output should be DISTINCT */
  17111. #define SF_All 0x00002 /* Includes the ALL keyword */
  17112. #define SF_Resolved 0x00004 /* Identifiers have been resolved */
  17113. #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
  17114. #define SF_HasAgg 0x00010 /* Contains aggregate functions */
  17115. #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
  17116. #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
  17117. #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
  17118. #define SF_Compound 0x00100 /* Part of a compound query */
  17119. #define SF_Values 0x00200 /* Synthesized from VALUES clause */
  17120. #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
  17121. #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
  17122. #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
  17123. #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
  17124. #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
  17125. #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
  17126. #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
  17127. #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
  17128. #define SF_ComplexResult 0x40000 /* Result contains subquery or function */
  17129. /*
  17130. ** The results of a SELECT can be distributed in several ways, as defined
  17131. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  17132. ** Type".
  17133. **
  17134. ** SRT_Union Store results as a key in a temporary index
  17135. ** identified by pDest->iSDParm.
  17136. **
  17137. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  17138. **
  17139. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  17140. ** set is not empty.
  17141. **
  17142. ** SRT_Discard Throw the results away. This is used by SELECT
  17143. ** statements within triggers whose only purpose is
  17144. ** the side-effects of functions.
  17145. **
  17146. ** All of the above are free to ignore their ORDER BY clause. Those that
  17147. ** follow must honor the ORDER BY clause.
  17148. **
  17149. ** SRT_Output Generate a row of output (using the OP_ResultRow
  17150. ** opcode) for each row in the result set.
  17151. **
  17152. ** SRT_Mem Only valid if the result is a single column.
  17153. ** Store the first column of the first result row
  17154. ** in register pDest->iSDParm then abandon the rest
  17155. ** of the query. This destination implies "LIMIT 1".
  17156. **
  17157. ** SRT_Set The result must be a single column. Store each
  17158. ** row of result as the key in table pDest->iSDParm.
  17159. ** Apply the affinity pDest->affSdst before storing
  17160. ** results. Used to implement "IN (SELECT ...)".
  17161. **
  17162. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  17163. ** the result there. The cursor is left open after
  17164. ** returning. This is like SRT_Table except that
  17165. ** this destination uses OP_OpenEphemeral to create
  17166. ** the table first.
  17167. **
  17168. ** SRT_Coroutine Generate a co-routine that returns a new row of
  17169. ** results each time it is invoked. The entry point
  17170. ** of the co-routine is stored in register pDest->iSDParm
  17171. ** and the result row is stored in pDest->nDest registers
  17172. ** starting with pDest->iSdst.
  17173. **
  17174. ** SRT_Table Store results in temporary table pDest->iSDParm.
  17175. ** SRT_Fifo This is like SRT_EphemTab except that the table
  17176. ** is assumed to already be open. SRT_Fifo has
  17177. ** the additional property of being able to ignore
  17178. ** the ORDER BY clause.
  17179. **
  17180. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  17181. ** But also use temporary table pDest->iSDParm+1 as
  17182. ** a record of all prior results and ignore any duplicate
  17183. ** rows. Name means: "Distinct Fifo".
  17184. **
  17185. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  17186. ** an index). Append a sequence number so that all entries
  17187. ** are distinct.
  17188. **
  17189. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  17190. ** the same record has never been stored before. The
  17191. ** index at pDest->iSDParm+1 hold all prior stores.
  17192. */
  17193. #define SRT_Union 1 /* Store result as keys in an index */
  17194. #define SRT_Except 2 /* Remove result from a UNION index */
  17195. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  17196. #define SRT_Discard 4 /* Do not save the results anywhere */
  17197. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  17198. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  17199. #define SRT_Queue 7 /* Store result in an queue */
  17200. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  17201. /* The ORDER BY clause is ignored for all of the above */
  17202. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  17203. #define SRT_Output 9 /* Output each row of result */
  17204. #define SRT_Mem 10 /* Store result in a memory cell */
  17205. #define SRT_Set 11 /* Store results as keys in an index */
  17206. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  17207. #define SRT_Coroutine 13 /* Generate a single row of result */
  17208. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  17209. /*
  17210. ** An instance of this object describes where to put of the results of
  17211. ** a SELECT statement.
  17212. */
  17213. struct SelectDest {
  17214. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  17215. int iSDParm; /* A parameter used by the eDest disposal method */
  17216. int iSdst; /* Base register where results are written */
  17217. int nSdst; /* Number of registers allocated */
  17218. char *zAffSdst; /* Affinity used when eDest==SRT_Set */
  17219. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  17220. };
  17221. /*
  17222. ** During code generation of statements that do inserts into AUTOINCREMENT
  17223. ** tables, the following information is attached to the Table.u.autoInc.p
  17224. ** pointer of each autoincrement table to record some side information that
  17225. ** the code generator needs. We have to keep per-table autoincrement
  17226. ** information in case inserts are done within triggers. Triggers do not
  17227. ** normally coordinate their activities, but we do need to coordinate the
  17228. ** loading and saving of autoincrement information.
  17229. */
  17230. struct AutoincInfo {
  17231. AutoincInfo *pNext; /* Next info block in a list of them all */
  17232. Table *pTab; /* Table this info block refers to */
  17233. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  17234. int regCtr; /* Memory register holding the rowid counter */
  17235. };
  17236. /*
  17237. ** At least one instance of the following structure is created for each
  17238. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  17239. ** statement. All such objects are stored in the linked list headed at
  17240. ** Parse.pTriggerPrg and deleted once statement compilation has been
  17241. ** completed.
  17242. **
  17243. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  17244. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  17245. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  17246. ** The Parse.pTriggerPrg list never contains two entries with the same
  17247. ** values for both pTrigger and orconf.
  17248. **
  17249. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  17250. ** accessed (or set to 0 for triggers fired as a result of INSERT
  17251. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  17252. ** a mask of new.* columns used by the program.
  17253. */
  17254. struct TriggerPrg {
  17255. Trigger *pTrigger; /* Trigger this program was coded from */
  17256. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  17257. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  17258. int orconf; /* Default ON CONFLICT policy */
  17259. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  17260. };
  17261. /*
  17262. ** The yDbMask datatype for the bitmask of all attached databases.
  17263. */
  17264. #if SQLITE_MAX_ATTACHED>30
  17265. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  17266. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  17267. # define DbMaskZero(M) memset((M),0,sizeof(M))
  17268. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  17269. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  17270. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  17271. #else
  17272. typedef unsigned int yDbMask;
  17273. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  17274. # define DbMaskZero(M) (M)=0
  17275. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  17276. # define DbMaskAllZero(M) (M)==0
  17277. # define DbMaskNonZero(M) (M)!=0
  17278. #endif
  17279. /*
  17280. ** An SQL parser context. A copy of this structure is passed through
  17281. ** the parser and down into all the parser action routine in order to
  17282. ** carry around information that is global to the entire parse.
  17283. **
  17284. ** The structure is divided into two parts. When the parser and code
  17285. ** generate call themselves recursively, the first part of the structure
  17286. ** is constant but the second part is reset at the beginning and end of
  17287. ** each recursion.
  17288. **
  17289. ** The nTableLock and aTableLock variables are only used if the shared-cache
  17290. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  17291. ** used to store the set of table-locks required by the statement being
  17292. ** compiled. Function sqlite3TableLock() is used to add entries to the
  17293. ** list.
  17294. */
  17295. struct Parse {
  17296. sqlite3 *db; /* The main database structure */
  17297. char *zErrMsg; /* An error message */
  17298. Vdbe *pVdbe; /* An engine for executing database bytecode */
  17299. int rc; /* Return code from execution */
  17300. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  17301. u8 checkSchema; /* Causes schema cookie check after an error */
  17302. u8 nested; /* Number of nested calls to the parser/code generator */
  17303. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  17304. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  17305. u8 mayAbort; /* True if statement may throw an ABORT exception */
  17306. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  17307. u8 okConstFactor; /* OK to factor out constants */
  17308. u8 disableLookaside; /* Number of times lookaside has been disabled */
  17309. u8 disableVtab; /* Disable all virtual tables for this parse */
  17310. int nRangeReg; /* Size of the temporary register block */
  17311. int iRangeReg; /* First register in temporary register block */
  17312. int nErr; /* Number of errors seen */
  17313. int nTab; /* Number of previously allocated VDBE cursors */
  17314. int nMem; /* Number of memory cells used so far */
  17315. int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
  17316. int iSelfTab; /* Table associated with an index on expr, or negative
  17317. ** of the base register during check-constraint eval */
  17318. int nLabel; /* The *negative* of the number of labels used */
  17319. int nLabelAlloc; /* Number of slots in aLabel */
  17320. int *aLabel; /* Space to hold the labels */
  17321. ExprList *pConstExpr;/* Constant expressions */
  17322. Token constraintName;/* Name of the constraint currently being parsed */
  17323. yDbMask writeMask; /* Start a write transaction on these databases */
  17324. yDbMask cookieMask; /* Bitmask of schema verified databases */
  17325. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  17326. int regRoot; /* Register holding root page number for new objects */
  17327. int nMaxArg; /* Max args passed to user function by sub-program */
  17328. int nSelect; /* Number of SELECT stmts. Counter for Select.selId */
  17329. #ifndef SQLITE_OMIT_SHARED_CACHE
  17330. int nTableLock; /* Number of locks in aTableLock */
  17331. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  17332. #endif
  17333. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  17334. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  17335. Table *pTriggerTab; /* Table triggers are being coded for */
  17336. Parse *pParentParse; /* Parent parser if this parser is nested */
  17337. int addrCrTab; /* Address of OP_CreateBtree opcode on CREATE TABLE */
  17338. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  17339. u32 oldmask; /* Mask of old.* columns referenced */
  17340. u32 newmask; /* Mask of new.* columns referenced */
  17341. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  17342. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  17343. u8 disableTriggers; /* True to disable triggers */
  17344. /**************************************************************************
  17345. ** Fields above must be initialized to zero. The fields that follow,
  17346. ** down to the beginning of the recursive section, do not need to be
  17347. ** initialized as they will be set before being used. The boundary is
  17348. ** determined by offsetof(Parse,aTempReg).
  17349. **************************************************************************/
  17350. int aTempReg[8]; /* Holding area for temporary registers */
  17351. Token sNameToken; /* Token with unqualified schema object name */
  17352. /************************************************************************
  17353. ** Above is constant between recursions. Below is reset before and after
  17354. ** each recursion. The boundary between these two regions is determined
  17355. ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
  17356. ** first field in the recursive region.
  17357. ************************************************************************/
  17358. Token sLastToken; /* The last token parsed */
  17359. ynVar nVar; /* Number of '?' variables seen in the SQL so far */
  17360. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  17361. u8 explain; /* True if the EXPLAIN flag is found on the query */
  17362. #if !(defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE))
  17363. u8 eParseMode; /* PARSE_MODE_XXX constant */
  17364. #endif
  17365. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17366. int nVtabLock; /* Number of virtual tables to lock */
  17367. #endif
  17368. int nHeight; /* Expression tree height of current sub-select */
  17369. #ifndef SQLITE_OMIT_EXPLAIN
  17370. int addrExplain; /* Address of current OP_Explain opcode */
  17371. #endif
  17372. VList *pVList; /* Mapping between variable names and numbers */
  17373. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  17374. const char *zTail; /* All SQL text past the last semicolon parsed */
  17375. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  17376. Index *pNewIndex; /* An index being constructed by CREATE INDEX.
  17377. ** Also used to hold redundant UNIQUE constraints
  17378. ** during a RENAME COLUMN */
  17379. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  17380. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  17381. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17382. Token sArg; /* Complete text of a module argument */
  17383. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  17384. #endif
  17385. Table *pZombieTab; /* List of Table objects to delete after code gen */
  17386. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  17387. With *pWith; /* Current WITH clause, or NULL */
  17388. With *pWithToFree; /* Free this WITH object at the end of the parse */
  17389. #ifndef SQLITE_OMIT_ALTERTABLE
  17390. RenameToken *pRename; /* Tokens subject to renaming by ALTER TABLE */
  17391. #endif
  17392. };
  17393. #define PARSE_MODE_NORMAL 0
  17394. #define PARSE_MODE_DECLARE_VTAB 1
  17395. #define PARSE_MODE_RENAME_COLUMN 2
  17396. #define PARSE_MODE_RENAME_TABLE 3
  17397. /*
  17398. ** Sizes and pointers of various parts of the Parse object.
  17399. */
  17400. #define PARSE_HDR_SZ offsetof(Parse,aTempReg) /* Recursive part w/o aColCache*/
  17401. #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
  17402. #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
  17403. #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
  17404. /*
  17405. ** Return true if currently inside an sqlite3_declare_vtab() call.
  17406. */
  17407. #ifdef SQLITE_OMIT_VIRTUALTABLE
  17408. #define IN_DECLARE_VTAB 0
  17409. #else
  17410. #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
  17411. #endif
  17412. #if defined(SQLITE_OMIT_ALTERTABLE)
  17413. #define IN_RENAME_OBJECT 0
  17414. #else
  17415. #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME_COLUMN)
  17416. #endif
  17417. #if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
  17418. #define IN_SPECIAL_PARSE 0
  17419. #else
  17420. #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
  17421. #endif
  17422. /*
  17423. ** An instance of the following structure can be declared on a stack and used
  17424. ** to save the Parse.zAuthContext value so that it can be restored later.
  17425. */
  17426. struct AuthContext {
  17427. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  17428. Parse *pParse; /* The Parse structure */
  17429. };
  17430. /*
  17431. ** Bitfield flags for P5 value in various opcodes.
  17432. **
  17433. ** Value constraints (enforced via assert()):
  17434. ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
  17435. ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
  17436. ** OPFLAG_BULKCSR == BTREE_BULKLOAD
  17437. ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
  17438. ** OPFLAG_FORDELETE == BTREE_FORDELETE
  17439. ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
  17440. ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
  17441. */
  17442. #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
  17443. /* Also used in P2 (not P5) of OP_Delete */
  17444. #define OPFLAG_NOCHNG 0x01 /* OP_VColumn nochange for UPDATE */
  17445. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  17446. #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
  17447. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  17448. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  17449. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  17450. #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
  17451. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  17452. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  17453. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  17454. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  17455. #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
  17456. #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
  17457. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  17458. #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
  17459. #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
  17460. #define OPFLAG_NOCHNG_MAGIC 0x6d /* OP_MakeRecord: serialtype 10 is ok */
  17461. /*
  17462. * Each trigger present in the database schema is stored as an instance of
  17463. * struct Trigger.
  17464. *
  17465. * Pointers to instances of struct Trigger are stored in two ways.
  17466. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  17467. * database). This allows Trigger structures to be retrieved by name.
  17468. * 2. All triggers associated with a single table form a linked list, using the
  17469. * pNext member of struct Trigger. A pointer to the first element of the
  17470. * linked list is stored as the "pTrigger" member of the associated
  17471. * struct Table.
  17472. *
  17473. * The "step_list" member points to the first element of a linked list
  17474. * containing the SQL statements specified as the trigger program.
  17475. */
  17476. struct Trigger {
  17477. char *zName; /* The name of the trigger */
  17478. char *table; /* The table or view to which the trigger applies */
  17479. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  17480. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  17481. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  17482. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  17483. the <column-list> is stored here */
  17484. Schema *pSchema; /* Schema containing the trigger */
  17485. Schema *pTabSchema; /* Schema containing the table */
  17486. TriggerStep *step_list; /* Link list of trigger program steps */
  17487. Trigger *pNext; /* Next trigger associated with the table */
  17488. };
  17489. /*
  17490. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  17491. ** determine which.
  17492. **
  17493. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  17494. ** In that cases, the constants below can be ORed together.
  17495. */
  17496. #define TRIGGER_BEFORE 1
  17497. #define TRIGGER_AFTER 2
  17498. /*
  17499. * An instance of struct TriggerStep is used to store a single SQL statement
  17500. * that is a part of a trigger-program.
  17501. *
  17502. * Instances of struct TriggerStep are stored in a singly linked list (linked
  17503. * using the "pNext" member) referenced by the "step_list" member of the
  17504. * associated struct Trigger instance. The first element of the linked list is
  17505. * the first step of the trigger-program.
  17506. *
  17507. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  17508. * "SELECT" statement. The meanings of the other members is determined by the
  17509. * value of "op" as follows:
  17510. *
  17511. * (op == TK_INSERT)
  17512. * orconf -> stores the ON CONFLICT algorithm
  17513. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  17514. * this stores a pointer to the SELECT statement. Otherwise NULL.
  17515. * zTarget -> Dequoted name of the table to insert into.
  17516. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  17517. * this stores values to be inserted. Otherwise NULL.
  17518. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  17519. * statement, then this stores the column-names to be
  17520. * inserted into.
  17521. *
  17522. * (op == TK_DELETE)
  17523. * zTarget -> Dequoted name of the table to delete from.
  17524. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  17525. * Otherwise NULL.
  17526. *
  17527. * (op == TK_UPDATE)
  17528. * zTarget -> Dequoted name of the table to update.
  17529. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  17530. * Otherwise NULL.
  17531. * pExprList -> A list of the columns to update and the expressions to update
  17532. * them to. See sqlite3Update() documentation of "pChanges"
  17533. * argument.
  17534. *
  17535. */
  17536. struct TriggerStep {
  17537. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  17538. u8 orconf; /* OE_Rollback etc. */
  17539. Trigger *pTrig; /* The trigger that this step is a part of */
  17540. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  17541. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  17542. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  17543. ExprList *pExprList; /* SET clause for UPDATE */
  17544. IdList *pIdList; /* Column names for INSERT */
  17545. Upsert *pUpsert; /* Upsert clauses on an INSERT */
  17546. char *zSpan; /* Original SQL text of this command */
  17547. TriggerStep *pNext; /* Next in the link-list */
  17548. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  17549. };
  17550. /*
  17551. ** The following structure contains information used by the sqliteFix...
  17552. ** routines as they walk the parse tree to make database references
  17553. ** explicit.
  17554. */
  17555. typedef struct DbFixer DbFixer;
  17556. struct DbFixer {
  17557. Parse *pParse; /* The parsing context. Error messages written here */
  17558. Schema *pSchema; /* Fix items to this schema */
  17559. int bVarOnly; /* Check for variable references only */
  17560. const char *zDb; /* Make sure all objects are contained in this database */
  17561. const char *zType; /* Type of the container - used for error messages */
  17562. const Token *pName; /* Name of the container - used for error messages */
  17563. };
  17564. /*
  17565. ** An objected used to accumulate the text of a string where we
  17566. ** do not necessarily know how big the string will be in the end.
  17567. */
  17568. struct sqlite3_str {
  17569. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  17570. char *zText; /* The string collected so far */
  17571. u32 nAlloc; /* Amount of space allocated in zText */
  17572. u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  17573. u32 nChar; /* Length of the string so far */
  17574. u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */
  17575. u8 printfFlags; /* SQLITE_PRINTF flags below */
  17576. };
  17577. #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
  17578. #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
  17579. #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
  17580. #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
  17581. /*
  17582. ** A pointer to this structure is used to communicate information
  17583. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  17584. */
  17585. typedef struct {
  17586. sqlite3 *db; /* The database being initialized */
  17587. char **pzErrMsg; /* Error message stored here */
  17588. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  17589. int rc; /* Result code stored here */
  17590. u32 mInitFlags; /* Flags controlling error messages */
  17591. u32 nInitRow; /* Number of rows processed */
  17592. } InitData;
  17593. /*
  17594. ** Allowed values for mInitFlags
  17595. */
  17596. #define INITFLAG_AlterTable 0x0001 /* This is a reparse after ALTER TABLE */
  17597. /*
  17598. ** Structure containing global configuration data for the SQLite library.
  17599. **
  17600. ** This structure also contains some state information.
  17601. */
  17602. struct Sqlite3Config {
  17603. int bMemstat; /* True to enable memory status */
  17604. int bCoreMutex; /* True to enable core mutexing */
  17605. int bFullMutex; /* True to enable full mutexing */
  17606. int bOpenUri; /* True to interpret filenames as URIs */
  17607. int bUseCis; /* Use covering indices for full-scans */
  17608. int bSmallMalloc; /* Avoid large memory allocations if true */
  17609. int mxStrlen; /* Maximum string length */
  17610. int neverCorrupt; /* Database is always well-formed */
  17611. int szLookaside; /* Default lookaside buffer size */
  17612. int nLookaside; /* Default lookaside buffer count */
  17613. int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
  17614. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  17615. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  17616. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  17617. void *pHeap; /* Heap storage space */
  17618. int nHeap; /* Size of pHeap[] */
  17619. int mnReq, mxReq; /* Min and max heap requests sizes */
  17620. sqlite3_int64 szMmap; /* mmap() space per open file */
  17621. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  17622. void *pPage; /* Page cache memory */
  17623. int szPage; /* Size of each page in pPage[] */
  17624. int nPage; /* Number of pages in pPage[] */
  17625. int mxParserStack; /* maximum depth of the parser stack */
  17626. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  17627. u32 szPma; /* Maximum Sorter PMA size */
  17628. /* The above might be initialized to non-zero. The following need to always
  17629. ** initially be zero, however. */
  17630. int isInit; /* True after initialization has finished */
  17631. int inProgress; /* True while initialization in progress */
  17632. int isMutexInit; /* True after mutexes are initialized */
  17633. int isMallocInit; /* True after malloc is initialized */
  17634. int isPCacheInit; /* True after malloc is initialized */
  17635. int nRefInitMutex; /* Number of users of pInitMutex */
  17636. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  17637. void (*xLog)(void*,int,const char*); /* Function for logging */
  17638. void *pLogArg; /* First argument to xLog() */
  17639. #ifdef SQLITE_ENABLE_SQLLOG
  17640. void(*xSqllog)(void*,sqlite3*,const char*, int);
  17641. void *pSqllogArg;
  17642. #endif
  17643. #ifdef SQLITE_VDBE_COVERAGE
  17644. /* The following callback (if not NULL) is invoked on every VDBE branch
  17645. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  17646. */
  17647. void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx); /* Callback */
  17648. void *pVdbeBranchArg; /* 1st argument */
  17649. #endif
  17650. #ifdef SQLITE_ENABLE_DESERIALIZE
  17651. sqlite3_int64 mxMemdbSize; /* Default max memdb size */
  17652. #endif
  17653. #ifndef SQLITE_UNTESTABLE
  17654. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  17655. #endif
  17656. int bLocaltimeFault; /* True to fail localtime() calls */
  17657. int bInternalFunctions; /* Internal SQL functions are visible */
  17658. int iOnceResetThreshold; /* When to reset OP_Once counters */
  17659. u32 szSorterRef; /* Min size in bytes to use sorter-refs */
  17660. };
  17661. /*
  17662. ** This macro is used inside of assert() statements to indicate that
  17663. ** the assert is only valid on a well-formed database. Instead of:
  17664. **
  17665. ** assert( X );
  17666. **
  17667. ** One writes:
  17668. **
  17669. ** assert( X || CORRUPT_DB );
  17670. **
  17671. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  17672. ** that the database is definitely corrupt, only that it might be corrupt.
  17673. ** For most test cases, CORRUPT_DB is set to false using a special
  17674. ** sqlite3_test_control(). This enables assert() statements to prove
  17675. ** things that are always true for well-formed databases.
  17676. */
  17677. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  17678. /*
  17679. ** Context pointer passed down through the tree-walk.
  17680. */
  17681. struct Walker {
  17682. Parse *pParse; /* Parser context. */
  17683. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  17684. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  17685. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  17686. int walkerDepth; /* Number of subqueries */
  17687. u8 eCode; /* A small processing code */
  17688. union { /* Extra data for callback */
  17689. NameContext *pNC; /* Naming context */
  17690. int n; /* A counter */
  17691. int iCur; /* A cursor number */
  17692. SrcList *pSrcList; /* FROM clause */
  17693. struct SrcCount *pSrcCount; /* Counting column references */
  17694. struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
  17695. int *aiCol; /* array of column indexes */
  17696. struct IdxCover *pIdxCover; /* Check for index coverage */
  17697. struct IdxExprTrans *pIdxTrans; /* Convert idxed expr to column */
  17698. ExprList *pGroupBy; /* GROUP BY clause */
  17699. Select *pSelect; /* HAVING to WHERE clause ctx */
  17700. struct WindowRewrite *pRewrite; /* Window rewrite context */
  17701. struct WhereConst *pConst; /* WHERE clause constants */
  17702. struct RenameCtx *pRename; /* RENAME COLUMN context */
  17703. } u;
  17704. };
  17705. /* Forward declarations */
  17706. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  17707. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  17708. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  17709. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  17710. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  17711. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
  17712. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
  17713. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
  17714. #ifdef SQLITE_DEBUG
  17715. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
  17716. #endif
  17717. /*
  17718. ** Return code from the parse-tree walking primitives and their
  17719. ** callbacks.
  17720. */
  17721. #define WRC_Continue 0 /* Continue down into children */
  17722. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  17723. #define WRC_Abort 2 /* Abandon the tree walk */
  17724. /*
  17725. ** An instance of this structure represents a set of one or more CTEs
  17726. ** (common table expressions) created by a single WITH clause.
  17727. */
  17728. struct With {
  17729. int nCte; /* Number of CTEs in the WITH clause */
  17730. With *pOuter; /* Containing WITH clause, or NULL */
  17731. struct Cte { /* For each CTE in the WITH clause.... */
  17732. char *zName; /* Name of this CTE */
  17733. ExprList *pCols; /* List of explicit column names, or NULL */
  17734. Select *pSelect; /* The definition of this CTE */
  17735. const char *zCteErr; /* Error message for circular references */
  17736. } a[1];
  17737. };
  17738. #ifdef SQLITE_DEBUG
  17739. /*
  17740. ** An instance of the TreeView object is used for printing the content of
  17741. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  17742. */
  17743. struct TreeView {
  17744. int iLevel; /* Which level of the tree we are on */
  17745. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  17746. };
  17747. #endif /* SQLITE_DEBUG */
  17748. /*
  17749. ** This object is used in various ways, all related to window functions
  17750. **
  17751. ** (1) A single instance of this structure is attached to the
  17752. ** the Expr.pWin field for each window function in an expression tree.
  17753. ** This object holds the information contained in the OVER clause,
  17754. ** plus additional fields used during code generation.
  17755. **
  17756. ** (2) All window functions in a single SELECT form a linked-list
  17757. ** attached to Select.pWin. The Window.pFunc and Window.pExpr
  17758. ** fields point back to the expression that is the window function.
  17759. **
  17760. ** (3) The terms of the WINDOW clause of a SELECT are instances of this
  17761. ** object on a linked list attached to Select.pWinDefn.
  17762. **
  17763. ** The uses (1) and (2) are really the same Window object that just happens
  17764. ** to be accessible in two different ways. Use case (3) are separate objects.
  17765. */
  17766. struct Window {
  17767. char *zName; /* Name of window (may be NULL) */
  17768. char *zBase; /* Name of base window for chaining (may be NULL) */
  17769. ExprList *pPartition; /* PARTITION BY clause */
  17770. ExprList *pOrderBy; /* ORDER BY clause */
  17771. u8 eFrmType; /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */
  17772. u8 eStart; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
  17773. u8 eEnd; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
  17774. u8 bImplicitFrame; /* True if frame was implicitly specified */
  17775. u8 eExclude; /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */
  17776. Expr *pStart; /* Expression for "<expr> PRECEDING" */
  17777. Expr *pEnd; /* Expression for "<expr> FOLLOWING" */
  17778. Window *pNextWin; /* Next window function belonging to this SELECT */
  17779. Expr *pFilter; /* The FILTER expression */
  17780. FuncDef *pFunc; /* The function */
  17781. int iEphCsr; /* Partition buffer or Peer buffer */
  17782. int regAccum;
  17783. int regResult;
  17784. int csrApp; /* Function cursor (used by min/max) */
  17785. int regApp; /* Function register (also used by min/max) */
  17786. int regPart; /* Array of registers for PARTITION BY values */
  17787. Expr *pOwner; /* Expression object this window is attached to */
  17788. int nBufferCol; /* Number of columns in buffer table */
  17789. int iArgCol; /* Offset of first argument for this function */
  17790. int regOne; /* Register containing constant value 1 */
  17791. int regStartRowid;
  17792. int regEndRowid;
  17793. };
  17794. #ifndef SQLITE_OMIT_WINDOWFUNC
  17795. SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*);
  17796. SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);
  17797. SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);
  17798. SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);
  17799. SQLITE_PRIVATE int sqlite3WindowCompare(Parse*, Window*, Window*);
  17800. SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Window*);
  17801. SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
  17802. SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
  17803. SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, struct SrcList_item*);
  17804. SQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
  17805. SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
  17806. SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
  17807. SQLITE_PRIVATE void sqlite3WindowFunctions(void);
  17808. SQLITE_PRIVATE void sqlite3WindowChain(Parse*, Window*, Window*);
  17809. SQLITE_PRIVATE Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);
  17810. #else
  17811. # define sqlite3WindowDelete(a,b)
  17812. # define sqlite3WindowFunctions()
  17813. # define sqlite3WindowAttach(a,b,c)
  17814. #endif
  17815. /*
  17816. ** Assuming zIn points to the first byte of a UTF-8 character,
  17817. ** advance zIn to point to the first byte of the next UTF-8 character.
  17818. */
  17819. #define SQLITE_SKIP_UTF8(zIn) { \
  17820. if( (*(zIn++))>=0xc0 ){ \
  17821. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  17822. } \
  17823. }
  17824. /*
  17825. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  17826. ** the same name but without the _BKPT suffix. These macros invoke
  17827. ** routines that report the line-number on which the error originated
  17828. ** using sqlite3_log(). The routines also provide a convenient place
  17829. ** to set a debugger breakpoint.
  17830. */
  17831. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
  17832. SQLITE_PRIVATE int sqlite3CorruptError(int);
  17833. SQLITE_PRIVATE int sqlite3MisuseError(int);
  17834. SQLITE_PRIVATE int sqlite3CantopenError(int);
  17835. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  17836. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  17837. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  17838. #ifdef SQLITE_DEBUG
  17839. SQLITE_PRIVATE int sqlite3NomemError(int);
  17840. SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
  17841. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno);
  17842. # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
  17843. # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
  17844. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
  17845. #else
  17846. # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
  17847. # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
  17848. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
  17849. #endif
  17850. /*
  17851. ** FTS3 and FTS4 both require virtual table support
  17852. */
  17853. #if defined(SQLITE_OMIT_VIRTUALTABLE)
  17854. # undef SQLITE_ENABLE_FTS3
  17855. # undef SQLITE_ENABLE_FTS4
  17856. #endif
  17857. /*
  17858. ** FTS4 is really an extension for FTS3. It is enabled using the
  17859. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  17860. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  17861. */
  17862. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  17863. # define SQLITE_ENABLE_FTS3 1
  17864. #endif
  17865. /*
  17866. ** The ctype.h header is needed for non-ASCII systems. It is also
  17867. ** needed by FTS3 when FTS3 is included in the amalgamation.
  17868. */
  17869. #if !defined(SQLITE_ASCII) || \
  17870. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  17871. # include <ctype.h>
  17872. #endif
  17873. /*
  17874. ** The following macros mimic the standard library functions toupper(),
  17875. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  17876. ** sqlite versions only work for ASCII characters, regardless of locale.
  17877. */
  17878. #ifdef SQLITE_ASCII
  17879. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  17880. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  17881. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  17882. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  17883. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  17884. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  17885. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  17886. # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
  17887. #else
  17888. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  17889. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  17890. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  17891. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  17892. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  17893. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  17894. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  17895. # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
  17896. #endif
  17897. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  17898. /*
  17899. ** Internal function prototypes
  17900. */
  17901. SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
  17902. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  17903. #define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
  17904. SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
  17905. #define sqlite3StrNICmp sqlite3_strnicmp
  17906. SQLITE_PRIVATE int sqlite3MallocInit(void);
  17907. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  17908. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  17909. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  17910. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  17911. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  17912. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
  17913. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  17914. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  17915. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
  17916. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  17917. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  17918. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  17919. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  17920. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
  17921. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  17922. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  17923. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  17924. SQLITE_PRIVATE void sqlite3PageFree(void*);
  17925. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  17926. #ifndef SQLITE_UNTESTABLE
  17927. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  17928. #endif
  17929. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  17930. /*
  17931. ** On systems with ample stack space and that support alloca(), make
  17932. ** use of alloca() to obtain space for large automatic objects. By default,
  17933. ** obtain space from malloc().
  17934. **
  17935. ** The alloca() routine never returns NULL. This will cause code paths
  17936. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  17937. */
  17938. #ifdef SQLITE_USE_ALLOCA
  17939. # define sqlite3StackAllocRaw(D,N) alloca(N)
  17940. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  17941. # define sqlite3StackFree(D,P)
  17942. #else
  17943. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  17944. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  17945. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  17946. #endif
  17947. /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
  17948. ** are, disable MEMSYS3
  17949. */
  17950. #ifdef SQLITE_ENABLE_MEMSYS5
  17951. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  17952. #undef SQLITE_ENABLE_MEMSYS3
  17953. #endif
  17954. #ifdef SQLITE_ENABLE_MEMSYS3
  17955. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  17956. #endif
  17957. #ifndef SQLITE_MUTEX_OMIT
  17958. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  17959. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  17960. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  17961. SQLITE_PRIVATE int sqlite3MutexInit(void);
  17962. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  17963. #endif
  17964. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  17965. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  17966. #else
  17967. # define sqlite3MemoryBarrier()
  17968. #endif
  17969. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  17970. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  17971. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  17972. SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
  17973. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
  17974. /* Access to mutexes used by sqlite3_status() */
  17975. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  17976. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  17977. #if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
  17978. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
  17979. #else
  17980. # define sqlite3MutexWarnOnContention(x)
  17981. #endif
  17982. #ifndef SQLITE_OMIT_FLOATING_POINT
  17983. SQLITE_PRIVATE int sqlite3IsNaN(double);
  17984. #else
  17985. # define sqlite3IsNaN(X) 0
  17986. #endif
  17987. /*
  17988. ** An instance of the following structure holds information about SQL
  17989. ** functions arguments that are the parameters to the printf() function.
  17990. */
  17991. struct PrintfArguments {
  17992. int nArg; /* Total number of arguments */
  17993. int nUsed; /* Number of arguments used so far */
  17994. sqlite3_value **apArg; /* The argument values */
  17995. };
  17996. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  17997. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  17998. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  17999. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  18000. #endif
  18001. #if defined(SQLITE_TEST)
  18002. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  18003. #endif
  18004. #if defined(SQLITE_DEBUG)
  18005. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  18006. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
  18007. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  18008. SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
  18009. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  18010. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
  18011. #ifndef SQLITE_OMIT_WINDOWFUNC
  18012. SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
  18013. SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
  18014. #endif
  18015. #endif
  18016. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  18017. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  18018. SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3*,int);
  18019. SQLITE_PRIVATE void sqlite3Dequote(char*);
  18020. SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
  18021. SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
  18022. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  18023. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  18024. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  18025. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  18026. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  18027. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  18028. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  18029. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  18030. #ifdef SQLITE_DEBUG
  18031. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
  18032. #endif
  18033. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  18034. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  18035. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  18036. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
  18037. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
  18038. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  18039. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*, int);
  18040. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
  18041. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  18042. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  18043. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
  18044. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
  18045. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  18046. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
  18047. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  18048. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  18049. SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*);
  18050. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  18051. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  18052. SQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);
  18053. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  18054. #ifndef SQLITE_OMIT_VIRTUALTABLE
  18055. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
  18056. #endif
  18057. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  18058. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  18059. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  18060. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  18061. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  18062. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  18063. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
  18064. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  18065. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  18066. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  18067. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  18068. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  18069. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  18070. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
  18071. #else
  18072. # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
  18073. #endif
  18074. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
  18075. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  18076. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  18077. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  18078. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
  18079. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  18080. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  18081. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  18082. sqlite3_vfs**,char**,char **);
  18083. #ifdef SQLITE_HAS_CODEC
  18084. SQLITE_PRIVATE int sqlite3CodecQueryParameters(sqlite3*,const char*,const char*);
  18085. #else
  18086. # define sqlite3CodecQueryParameters(A,B,C) 0
  18087. #endif
  18088. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  18089. #ifdef SQLITE_UNTESTABLE
  18090. # define sqlite3FaultSim(X) SQLITE_OK
  18091. #else
  18092. SQLITE_PRIVATE int sqlite3FaultSim(int);
  18093. #endif
  18094. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  18095. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  18096. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  18097. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  18098. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  18099. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  18100. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  18101. #ifndef SQLITE_UNTESTABLE
  18102. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  18103. #endif
  18104. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*);
  18105. SQLITE_PRIVATE void sqlite3RowSetDelete(void*);
  18106. SQLITE_PRIVATE void sqlite3RowSetClear(void*);
  18107. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  18108. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  18109. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  18110. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  18111. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  18112. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  18113. #else
  18114. # define sqlite3ViewGetColumnNames(A,B) 0
  18115. #endif
  18116. #if SQLITE_MAX_ATTACHED>30
  18117. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  18118. #endif
  18119. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  18120. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  18121. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  18122. SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);
  18123. #ifndef SQLITE_OMIT_AUTOINCREMENT
  18124. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  18125. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  18126. #else
  18127. # define sqlite3AutoincrementBegin(X)
  18128. # define sqlite3AutoincrementEnd(X)
  18129. #endif
  18130. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
  18131. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  18132. SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
  18133. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  18134. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
  18135. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
  18136. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  18137. Token*, Select*, Expr*, IdList*);
  18138. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  18139. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  18140. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  18141. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  18142. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  18143. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  18144. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  18145. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  18146. SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  18147. Expr*, int, int, u8);
  18148. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  18149. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  18150. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  18151. Expr*,ExprList*,u32,Expr*);
  18152. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  18153. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  18154. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  18155. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  18156. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  18157. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
  18158. #endif
  18159. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
  18160. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
  18161. Upsert*);
  18162. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  18163. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  18164. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
  18165. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  18166. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  18167. SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
  18168. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  18169. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  18170. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  18171. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  18172. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  18173. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  18174. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  18175. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  18176. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  18177. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  18178. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  18179. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  18180. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
  18181. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  18182. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
  18183. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  18184. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  18185. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  18186. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  18187. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  18188. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  18189. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  18190. #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
  18191. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  18192. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  18193. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  18194. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  18195. #define LOCATE_VIEW 0x01
  18196. #define LOCATE_NOERR 0x02
  18197. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
  18198. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
  18199. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  18200. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  18201. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  18202. SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*,Expr*);
  18203. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
  18204. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  18205. SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
  18206. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
  18207. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  18208. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
  18209. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
  18210. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  18211. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  18212. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
  18213. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  18214. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  18215. #ifndef SQLITE_UNTESTABLE
  18216. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  18217. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  18218. #endif
  18219. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  18220. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  18221. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  18222. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  18223. SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
  18224. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  18225. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  18226. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  18227. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
  18228. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
  18229. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  18230. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  18231. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  18232. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
  18233. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  18234. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  18235. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
  18236. #endif
  18237. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  18238. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  18239. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  18240. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  18241. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  18242. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  18243. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  18244. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  18245. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  18246. SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
  18247. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  18248. u8,u8,int,int*,int*,Upsert*);
  18249. #ifdef SQLITE_ENABLE_NULL_TRIM
  18250. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
  18251. #else
  18252. # define sqlite3SetMakeRecordP5(A,B)
  18253. #endif
  18254. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  18255. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
  18256. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  18257. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  18258. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  18259. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  18260. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  18261. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  18262. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  18263. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  18264. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  18265. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  18266. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  18267. SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);
  18268. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
  18269. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
  18270. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
  18271. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  18272. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
  18273. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  18274. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  18275. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  18276. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  18277. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
  18278. #endif
  18279. #ifndef SQLITE_OMIT_TRIGGER
  18280. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  18281. Expr*,int, int);
  18282. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  18283. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  18284. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  18285. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  18286. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  18287. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  18288. int, int, int);
  18289. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  18290. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  18291. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  18292. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
  18293. const char*,const char*);
  18294. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
  18295. Select*,u8,Upsert*,
  18296. const char*,const char*);
  18297. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,ExprList*, Expr*, u8,
  18298. const char*,const char*);
  18299. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
  18300. const char*,const char*);
  18301. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  18302. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  18303. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  18304. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  18305. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  18306. #else
  18307. # define sqlite3TriggersExist(B,C,D,E,F) 0
  18308. # define sqlite3DeleteTrigger(A,B)
  18309. # define sqlite3DropTriggerPtr(A,B)
  18310. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  18311. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  18312. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  18313. # define sqlite3TriggerList(X, Y) 0
  18314. # define sqlite3ParseToplevel(p) p
  18315. # define sqlite3IsToplevel(p) 1
  18316. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  18317. #endif
  18318. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  18319. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  18320. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  18321. #ifndef SQLITE_OMIT_AUTHORIZATION
  18322. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  18323. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  18324. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  18325. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  18326. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  18327. #else
  18328. # define sqlite3AuthRead(a,b,c,d)
  18329. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  18330. # define sqlite3AuthContextPush(a,b,c)
  18331. # define sqlite3AuthContextPop(a) ((void)(a))
  18332. #endif
  18333. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  18334. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  18335. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  18336. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  18337. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  18338. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  18339. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  18340. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  18341. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  18342. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  18343. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  18344. #ifndef SQLITE_OMIT_UTF16
  18345. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  18346. #endif
  18347. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  18348. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  18349. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  18350. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  18351. #ifndef SQLITE_OMIT_VIRTUALTABLE
  18352. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  18353. #endif
  18354. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  18355. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  18356. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  18357. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  18358. #endif
  18359. SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
  18360. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
  18361. SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
  18362. /*
  18363. ** Routines to read and write variable-length integers. These used to
  18364. ** be defined locally, but now we use the varint routines in the util.c
  18365. ** file.
  18366. */
  18367. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  18368. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  18369. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  18370. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  18371. /*
  18372. ** The common case is for a varint to be a single byte. They following
  18373. ** macros handle the common case without a procedure call, but then call
  18374. ** the procedure for larger varints.
  18375. */
  18376. #define getVarint32(A,B) \
  18377. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  18378. #define putVarint32(A,B) \
  18379. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  18380. sqlite3PutVarint((A),(B)))
  18381. #define getVarint sqlite3GetVarint
  18382. #define putVarint sqlite3PutVarint
  18383. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  18384. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  18385. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  18386. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  18387. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
  18388. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  18389. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  18390. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  18391. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  18392. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  18393. SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
  18394. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  18395. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  18396. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  18397. #if defined(SQLITE_NEED_ERR_NAME)
  18398. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  18399. #endif
  18400. #ifdef SQLITE_ENABLE_DESERIALIZE
  18401. SQLITE_PRIVATE int sqlite3MemdbInit(void);
  18402. #endif
  18403. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  18404. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  18405. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  18406. SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);
  18407. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  18408. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  18409. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
  18410. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
  18411. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  18412. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  18413. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  18414. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  18415. SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
  18416. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  18417. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  18418. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  18419. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  18420. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  18421. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  18422. #ifdef SQLITE_ENABLE_8_3_NAMES
  18423. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  18424. #else
  18425. # define sqlite3FileSuffix3(X,Y)
  18426. #endif
  18427. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  18428. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  18429. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  18430. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  18431. void(*)(void*));
  18432. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  18433. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  18434. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  18435. #ifndef SQLITE_OMIT_UTF16
  18436. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  18437. #endif
  18438. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  18439. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  18440. #ifndef SQLITE_AMALGAMATION
  18441. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  18442. SQLITE_PRIVATE const char sqlite3StrBINARY[];
  18443. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  18444. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  18445. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  18446. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  18447. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  18448. #ifndef SQLITE_OMIT_WSD
  18449. SQLITE_PRIVATE int sqlite3PendingByte;
  18450. #endif
  18451. #endif
  18452. #ifdef VDBE_PROFILE
  18453. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
  18454. #endif
  18455. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  18456. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  18457. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  18458. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  18459. SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
  18460. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  18461. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  18462. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
  18463. SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
  18464. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
  18465. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  18466. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  18467. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  18468. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  18469. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  18470. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  18471. SQLITE_PRIVATE int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  18472. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  18473. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  18474. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  18475. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  18476. SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse*, void*, Token*);
  18477. SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, void *pTo, void *pFrom);
  18478. SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);
  18479. SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
  18480. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  18481. SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);
  18482. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  18483. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*, sqlite3_file*);
  18484. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  18485. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  18486. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  18487. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  18488. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  18489. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  18490. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  18491. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  18492. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  18493. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  18494. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  18495. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  18496. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  18497. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  18498. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
  18499. #ifdef SQLITE_DEBUG
  18500. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  18501. #endif
  18502. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  18503. void (*)(sqlite3_context*,int,sqlite3_value **),
  18504. void (*)(sqlite3_context*,int,sqlite3_value **),
  18505. void (*)(sqlite3_context*),
  18506. void (*)(sqlite3_context*),
  18507. void (*)(sqlite3_context*,int,sqlite3_value **),
  18508. FuncDestructor *pDestructor
  18509. );
  18510. SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
  18511. SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
  18512. SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
  18513. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  18514. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  18515. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  18516. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  18517. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  18518. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  18519. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  18520. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  18521. #ifndef SQLITE_OMIT_SUBQUERY
  18522. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
  18523. #else
  18524. # define sqlite3ExprCheckIN(x,y) SQLITE_OK
  18525. #endif
  18526. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  18527. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  18528. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  18529. Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
  18530. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  18531. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  18532. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  18533. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
  18534. #endif
  18535. /*
  18536. ** The interface to the LEMON-generated parser
  18537. */
  18538. #ifndef SQLITE_AMALGAMATION
  18539. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
  18540. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  18541. #endif
  18542. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token);
  18543. SQLITE_PRIVATE int sqlite3ParserFallback(int);
  18544. #ifdef YYTRACKMAXSTACKDEPTH
  18545. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  18546. #endif
  18547. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  18548. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  18549. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  18550. #else
  18551. # define sqlite3CloseExtensions(X)
  18552. #endif
  18553. #ifndef SQLITE_OMIT_SHARED_CACHE
  18554. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  18555. #else
  18556. #define sqlite3TableLock(v,w,x,y,z)
  18557. #endif
  18558. #ifdef SQLITE_TEST
  18559. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  18560. #endif
  18561. #ifdef SQLITE_OMIT_VIRTUALTABLE
  18562. # define sqlite3VtabClear(Y)
  18563. # define sqlite3VtabSync(X,Y) SQLITE_OK
  18564. # define sqlite3VtabRollback(X)
  18565. # define sqlite3VtabCommit(X)
  18566. # define sqlite3VtabInSync(db) 0
  18567. # define sqlite3VtabLock(X)
  18568. # define sqlite3VtabUnlock(X)
  18569. # define sqlite3VtabUnlockList(X)
  18570. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  18571. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  18572. #else
  18573. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  18574. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  18575. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  18576. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  18577. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  18578. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  18579. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  18580. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  18581. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  18582. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  18583. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  18584. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  18585. sqlite3*,
  18586. const char*,
  18587. const sqlite3_module*,
  18588. void*,
  18589. void(*)(void*)
  18590. );
  18591. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  18592. #endif
  18593. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  18594. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  18595. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  18596. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  18597. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  18598. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  18599. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  18600. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  18601. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  18602. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  18603. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  18604. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  18605. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  18606. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  18607. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  18608. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  18609. #ifdef SQLITE_ENABLE_NORMALIZE
  18610. SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);
  18611. #endif
  18612. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  18613. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  18614. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  18615. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  18616. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  18617. #ifndef SQLITE_OMIT_WAL
  18618. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  18619. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  18620. #endif
  18621. #ifndef SQLITE_OMIT_CTE
  18622. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  18623. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  18624. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  18625. #else
  18626. #define sqlite3WithPush(x,y,z)
  18627. #define sqlite3WithDelete(x,y)
  18628. #endif
  18629. #ifndef SQLITE_OMIT_UPSERT
  18630. SQLITE_PRIVATE Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*);
  18631. SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3*,Upsert*);
  18632. SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
  18633. SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
  18634. SQLITE_PRIVATE void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
  18635. #else
  18636. #define sqlite3UpsertNew(v,w,x,y,z) ((Upsert*)0)
  18637. #define sqlite3UpsertDelete(x,y)
  18638. #define sqlite3UpsertDup(x,y) ((Upsert*)0)
  18639. #endif
  18640. /* Declarations for functions in fkey.c. All of these are replaced by
  18641. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  18642. ** key functionality is available. If OMIT_TRIGGER is defined but
  18643. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  18644. ** this case foreign keys are parsed, but no other functionality is
  18645. ** provided (enforcement of FK constraints requires the triggers sub-system).
  18646. */
  18647. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  18648. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  18649. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  18650. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  18651. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  18652. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  18653. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  18654. #else
  18655. #define sqlite3FkActions(a,b,c,d,e,f)
  18656. #define sqlite3FkCheck(a,b,c,d,e,f)
  18657. #define sqlite3FkDropTable(a,b,c)
  18658. #define sqlite3FkOldmask(a,b) 0
  18659. #define sqlite3FkRequired(a,b,c,d) 0
  18660. #define sqlite3FkReferences(a) 0
  18661. #endif
  18662. #ifndef SQLITE_OMIT_FOREIGN_KEY
  18663. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  18664. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  18665. #else
  18666. #define sqlite3FkDelete(a,b)
  18667. #define sqlite3FkLocateIndex(a,b,c,d,e)
  18668. #endif
  18669. /*
  18670. ** Available fault injectors. Should be numbered beginning with 0.
  18671. */
  18672. #define SQLITE_FAULTINJECTOR_MALLOC 0
  18673. #define SQLITE_FAULTINJECTOR_COUNT 1
  18674. /*
  18675. ** The interface to the code in fault.c used for identifying "benign"
  18676. ** malloc failures. This is only present if SQLITE_UNTESTABLE
  18677. ** is not defined.
  18678. */
  18679. #ifndef SQLITE_UNTESTABLE
  18680. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  18681. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  18682. #else
  18683. #define sqlite3BeginBenignMalloc()
  18684. #define sqlite3EndBenignMalloc()
  18685. #endif
  18686. /*
  18687. ** Allowed return values from sqlite3FindInIndex()
  18688. */
  18689. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  18690. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  18691. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  18692. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  18693. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  18694. /*
  18695. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  18696. */
  18697. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  18698. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  18699. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  18700. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);
  18701. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  18702. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  18703. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  18704. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  18705. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  18706. #endif
  18707. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
  18708. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  18709. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  18710. #if SQLITE_MAX_EXPR_DEPTH>0
  18711. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  18712. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  18713. #else
  18714. #define sqlite3SelectExprHeight(x) 0
  18715. #define sqlite3ExprCheckHeight(x,y)
  18716. #endif
  18717. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  18718. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  18719. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  18720. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  18721. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  18722. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  18723. #else
  18724. #define sqlite3ConnectionBlocked(x,y)
  18725. #define sqlite3ConnectionUnlocked(x)
  18726. #define sqlite3ConnectionClosed(x)
  18727. #endif
  18728. #ifdef SQLITE_DEBUG
  18729. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  18730. #endif
  18731. #if defined(YYCOVERAGE)
  18732. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE*);
  18733. #endif
  18734. /*
  18735. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  18736. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  18737. ** print I/O tracing messages.
  18738. */
  18739. #ifdef SQLITE_ENABLE_IOTRACE
  18740. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  18741. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  18742. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  18743. #else
  18744. # define IOTRACE(A)
  18745. # define sqlite3VdbeIOTraceSql(X)
  18746. #endif
  18747. /*
  18748. ** These routines are available for the mem2.c debugging memory allocator
  18749. ** only. They are used to verify that different "types" of memory
  18750. ** allocations are properly tracked by the system.
  18751. **
  18752. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  18753. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  18754. ** a single bit set.
  18755. **
  18756. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  18757. ** argument match the type set by the previous sqlite3MemdebugSetType().
  18758. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  18759. **
  18760. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  18761. ** argument match the type set by the previous sqlite3MemdebugSetType().
  18762. **
  18763. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  18764. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  18765. ** it might have been allocated by lookaside, except the allocation was
  18766. ** too large or lookaside was already full. It is important to verify
  18767. ** that allocations that might have been satisfied by lookaside are not
  18768. ** passed back to non-lookaside free() routines. Asserts such as the
  18769. ** example above are placed on the non-lookaside free() routines to verify
  18770. ** this constraint.
  18771. **
  18772. ** All of this is no-op for a production build. It only comes into
  18773. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  18774. */
  18775. #ifdef SQLITE_MEMDEBUG
  18776. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  18777. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  18778. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  18779. #else
  18780. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  18781. # define sqlite3MemdebugHasType(X,Y) 1
  18782. # define sqlite3MemdebugNoType(X,Y) 1
  18783. #endif
  18784. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  18785. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  18786. #define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
  18787. /*
  18788. ** Threading interface
  18789. */
  18790. #if SQLITE_MAX_WORKER_THREADS>0
  18791. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  18792. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  18793. #endif
  18794. #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
  18795. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
  18796. #endif
  18797. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  18798. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  18799. #endif
  18800. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
  18801. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
  18802. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
  18803. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
  18804. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
  18805. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  18806. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
  18807. #endif
  18808. #endif /* SQLITEINT_H */
  18809. /************** End of sqliteInt.h *******************************************/
  18810. /************** Begin file global.c ******************************************/
  18811. /*
  18812. ** 2008 June 13
  18813. **
  18814. ** The author disclaims copyright to this source code. In place of
  18815. ** a legal notice, here is a blessing:
  18816. **
  18817. ** May you do good and not evil.
  18818. ** May you find forgiveness for yourself and forgive others.
  18819. ** May you share freely, never taking more than you give.
  18820. **
  18821. *************************************************************************
  18822. **
  18823. ** This file contains definitions of global variables and constants.
  18824. */
  18825. /* #include "sqliteInt.h" */
  18826. /* An array to map all upper-case characters into their corresponding
  18827. ** lower-case character.
  18828. **
  18829. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  18830. ** handle case conversions for the UTF character set since the tables
  18831. ** involved are nearly as big or bigger than SQLite itself.
  18832. */
  18833. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  18834. #ifdef SQLITE_ASCII
  18835. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  18836. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  18837. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  18838. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  18839. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  18840. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  18841. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  18842. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  18843. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  18844. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  18845. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  18846. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  18847. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  18848. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  18849. 252,253,254,255
  18850. #endif
  18851. #ifdef SQLITE_EBCDIC
  18852. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  18853. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  18854. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  18855. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  18856. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  18857. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  18858. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  18859. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  18860. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  18861. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  18862. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  18863. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  18864. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  18865. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  18866. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  18867. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  18868. #endif
  18869. };
  18870. /*
  18871. ** The following 256 byte lookup table is used to support SQLites built-in
  18872. ** equivalents to the following standard library functions:
  18873. **
  18874. ** isspace() 0x01
  18875. ** isalpha() 0x02
  18876. ** isdigit() 0x04
  18877. ** isalnum() 0x06
  18878. ** isxdigit() 0x08
  18879. ** toupper() 0x20
  18880. ** SQLite identifier character 0x40
  18881. ** Quote character 0x80
  18882. **
  18883. ** Bit 0x20 is set if the mapped character requires translation to upper
  18884. ** case. i.e. if the character is a lower-case ASCII character.
  18885. ** If x is a lower-case ASCII character, then its upper-case equivalent
  18886. ** is (x - 0x20). Therefore toupper() can be implemented as:
  18887. **
  18888. ** (x & ~(map[x]&0x20))
  18889. **
  18890. ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
  18891. ** array. tolower() is used more often than toupper() by SQLite.
  18892. **
  18893. ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
  18894. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  18895. ** non-ASCII UTF character. Hence the test for whether or not a character is
  18896. ** part of an identifier is 0x46.
  18897. */
  18898. #ifdef SQLITE_ASCII
  18899. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  18900. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  18901. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  18902. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  18903. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  18904. 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
  18905. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  18906. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  18907. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  18908. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  18909. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  18910. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  18911. 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  18912. 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  18913. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  18914. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  18915. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  18916. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  18917. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  18918. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  18919. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  18920. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  18921. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  18922. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  18923. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  18924. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  18925. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  18926. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  18927. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  18928. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  18929. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  18930. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  18931. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  18932. };
  18933. #endif
  18934. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  18935. ** compatibility for legacy applications, the URI filename capability is
  18936. ** disabled by default.
  18937. **
  18938. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  18939. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  18940. **
  18941. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  18942. ** disabled. The default value may be changed by compiling with the
  18943. ** SQLITE_USE_URI symbol defined.
  18944. **
  18945. ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
  18946. ** enabled.
  18947. */
  18948. #ifndef SQLITE_USE_URI
  18949. # ifdef SQLITE_HAS_CODEC
  18950. # define SQLITE_USE_URI 1
  18951. # else
  18952. # define SQLITE_USE_URI 0
  18953. # endif
  18954. #endif
  18955. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  18956. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  18957. ** that compile-time option is omitted.
  18958. */
  18959. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  18960. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  18961. #endif
  18962. /* The minimum PMA size is set to this value multiplied by the database
  18963. ** page size in bytes.
  18964. */
  18965. #ifndef SQLITE_SORTER_PMASZ
  18966. # define SQLITE_SORTER_PMASZ 250
  18967. #endif
  18968. /* Statement journals spill to disk when their size exceeds the following
  18969. ** threshold (in bytes). 0 means that statement journals are created and
  18970. ** written to disk immediately (the default behavior for SQLite versions
  18971. ** before 3.12.0). -1 means always keep the entire statement journal in
  18972. ** memory. (The statement journal is also always held entirely in memory
  18973. ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
  18974. ** setting.)
  18975. */
  18976. #ifndef SQLITE_STMTJRNL_SPILL
  18977. # define SQLITE_STMTJRNL_SPILL (64*1024)
  18978. #endif
  18979. /*
  18980. ** The default lookaside-configuration, the format "SZ,N". SZ is the
  18981. ** number of bytes in each lookaside slot (should be a multiple of 8)
  18982. ** and N is the number of slots. The lookaside-configuration can be
  18983. ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
  18984. ** or at run-time for an individual database connection using
  18985. ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
  18986. */
  18987. #ifndef SQLITE_DEFAULT_LOOKASIDE
  18988. # define SQLITE_DEFAULT_LOOKASIDE 1200,100
  18989. #endif
  18990. /* The default maximum size of an in-memory database created using
  18991. ** sqlite3_deserialize()
  18992. */
  18993. #ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE
  18994. # define SQLITE_MEMDB_DEFAULT_MAXSIZE 1073741824
  18995. #endif
  18996. /*
  18997. ** The following singleton contains the global configuration for
  18998. ** the SQLite library.
  18999. */
  19000. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  19001. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  19002. 1, /* bCoreMutex */
  19003. SQLITE_THREADSAFE==1, /* bFullMutex */
  19004. SQLITE_USE_URI, /* bOpenUri */
  19005. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  19006. 0, /* bSmallMalloc */
  19007. 0x7ffffffe, /* mxStrlen */
  19008. 0, /* neverCorrupt */
  19009. SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
  19010. SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
  19011. {0,0,0,0,0,0,0,0}, /* m */
  19012. {0,0,0,0,0,0,0,0,0}, /* mutex */
  19013. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  19014. (void*)0, /* pHeap */
  19015. 0, /* nHeap */
  19016. 0, 0, /* mnHeap, mxHeap */
  19017. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  19018. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  19019. (void*)0, /* pPage */
  19020. 0, /* szPage */
  19021. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  19022. 0, /* mxParserStack */
  19023. 0, /* sharedCacheEnabled */
  19024. SQLITE_SORTER_PMASZ, /* szPma */
  19025. /* All the rest should always be initialized to zero */
  19026. 0, /* isInit */
  19027. 0, /* inProgress */
  19028. 0, /* isMutexInit */
  19029. 0, /* isMallocInit */
  19030. 0, /* isPCacheInit */
  19031. 0, /* nRefInitMutex */
  19032. 0, /* pInitMutex */
  19033. 0, /* xLog */
  19034. 0, /* pLogArg */
  19035. #ifdef SQLITE_ENABLE_SQLLOG
  19036. 0, /* xSqllog */
  19037. 0, /* pSqllogArg */
  19038. #endif
  19039. #ifdef SQLITE_VDBE_COVERAGE
  19040. 0, /* xVdbeBranch */
  19041. 0, /* pVbeBranchArg */
  19042. #endif
  19043. #ifdef SQLITE_ENABLE_DESERIALIZE
  19044. SQLITE_MEMDB_DEFAULT_MAXSIZE, /* mxMemdbSize */
  19045. #endif
  19046. #ifndef SQLITE_UNTESTABLE
  19047. 0, /* xTestCallback */
  19048. #endif
  19049. 0, /* bLocaltimeFault */
  19050. 0, /* bInternalFunctions */
  19051. 0x7ffffffe, /* iOnceResetThreshold */
  19052. SQLITE_DEFAULT_SORTERREF_SIZE, /* szSorterRef */
  19053. };
  19054. /*
  19055. ** Hash table for global functions - functions common to all
  19056. ** database connections. After initialization, this table is
  19057. ** read-only.
  19058. */
  19059. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  19060. /*
  19061. ** Constant tokens for values 0 and 1.
  19062. */
  19063. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  19064. { "0", 1 },
  19065. { "1", 1 }
  19066. };
  19067. #ifdef VDBE_PROFILE
  19068. /*
  19069. ** The following performance counter can be used in place of
  19070. ** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
  19071. */
  19072. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
  19073. #endif
  19074. /*
  19075. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  19076. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  19077. ** the database page that contains the pending byte. It never attempts
  19078. ** to read or write that page. The pending byte page is set aside
  19079. ** for use by the VFS layers as space for managing file locks.
  19080. **
  19081. ** During testing, it is often desirable to move the pending byte to
  19082. ** a different position in the file. This allows code that has to
  19083. ** deal with the pending byte to run on files that are much smaller
  19084. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  19085. ** move the pending byte.
  19086. **
  19087. ** IMPORTANT: Changing the pending byte to any value other than
  19088. ** 0x40000000 results in an incompatible database file format!
  19089. ** Changing the pending byte during operation will result in undefined
  19090. ** and incorrect behavior.
  19091. */
  19092. #ifndef SQLITE_OMIT_WSD
  19093. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  19094. #endif
  19095. /* #include "opcodes.h" */
  19096. /*
  19097. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  19098. ** created by mkopcodeh.awk during compilation. Data is obtained
  19099. ** from the comments following the "case OP_xxxx:" statements in
  19100. ** the vdbe.c file.
  19101. */
  19102. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  19103. /*
  19104. ** Name of the default collating sequence
  19105. */
  19106. SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
  19107. /************** End of global.c **********************************************/
  19108. /************** Begin file status.c ******************************************/
  19109. /*
  19110. ** 2008 June 18
  19111. **
  19112. ** The author disclaims copyright to this source code. In place of
  19113. ** a legal notice, here is a blessing:
  19114. **
  19115. ** May you do good and not evil.
  19116. ** May you find forgiveness for yourself and forgive others.
  19117. ** May you share freely, never taking more than you give.
  19118. **
  19119. *************************************************************************
  19120. **
  19121. ** This module implements the sqlite3_status() interface and related
  19122. ** functionality.
  19123. */
  19124. /* #include "sqliteInt.h" */
  19125. /************** Include vdbeInt.h in the middle of status.c ******************/
  19126. /************** Begin file vdbeInt.h *****************************************/
  19127. /*
  19128. ** 2003 September 6
  19129. **
  19130. ** The author disclaims copyright to this source code. In place of
  19131. ** a legal notice, here is a blessing:
  19132. **
  19133. ** May you do good and not evil.
  19134. ** May you find forgiveness for yourself and forgive others.
  19135. ** May you share freely, never taking more than you give.
  19136. **
  19137. *************************************************************************
  19138. ** This is the header file for information that is private to the
  19139. ** VDBE. This information used to all be at the top of the single
  19140. ** source code file "vdbe.c". When that file became too big (over
  19141. ** 6000 lines long) it was split up into several smaller files and
  19142. ** this header information was factored out.
  19143. */
  19144. #ifndef SQLITE_VDBEINT_H
  19145. #define SQLITE_VDBEINT_H
  19146. /*
  19147. ** The maximum number of times that a statement will try to reparse
  19148. ** itself before giving up and returning SQLITE_SCHEMA.
  19149. */
  19150. #ifndef SQLITE_MAX_SCHEMA_RETRY
  19151. # define SQLITE_MAX_SCHEMA_RETRY 50
  19152. #endif
  19153. /*
  19154. ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
  19155. ** "explain" P4 display logic is enabled.
  19156. */
  19157. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  19158. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  19159. # define VDBE_DISPLAY_P4 1
  19160. #else
  19161. # define VDBE_DISPLAY_P4 0
  19162. #endif
  19163. /*
  19164. ** SQL is translated into a sequence of instructions to be
  19165. ** executed by a virtual machine. Each instruction is an instance
  19166. ** of the following structure.
  19167. */
  19168. typedef struct VdbeOp Op;
  19169. /*
  19170. ** Boolean values
  19171. */
  19172. typedef unsigned Bool;
  19173. /* Opaque type used by code in vdbesort.c */
  19174. typedef struct VdbeSorter VdbeSorter;
  19175. /* Elements of the linked list at Vdbe.pAuxData */
  19176. typedef struct AuxData AuxData;
  19177. /* Types of VDBE cursors */
  19178. #define CURTYPE_BTREE 0
  19179. #define CURTYPE_SORTER 1
  19180. #define CURTYPE_VTAB 2
  19181. #define CURTYPE_PSEUDO 3
  19182. /*
  19183. ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
  19184. **
  19185. ** * A b-tree cursor
  19186. ** - In the main database or in an ephemeral database
  19187. ** - On either an index or a table
  19188. ** * A sorter
  19189. ** * A virtual table
  19190. ** * A one-row "pseudotable" stored in a single register
  19191. */
  19192. typedef struct VdbeCursor VdbeCursor;
  19193. struct VdbeCursor {
  19194. u8 eCurType; /* One of the CURTYPE_* values above */
  19195. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  19196. u8 nullRow; /* True if pointing to a row with no data */
  19197. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  19198. u8 isTable; /* True for rowid tables. False for indexes */
  19199. #ifdef SQLITE_DEBUG
  19200. u8 seekOp; /* Most recent seek operation on this cursor */
  19201. u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
  19202. #endif
  19203. Bool isEphemeral:1; /* True for an ephemeral table */
  19204. Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
  19205. Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
  19206. Bool seekHit:1; /* See the OP_SeekHit and OP_IfNoHope opcodes */
  19207. Btree *pBtx; /* Separate file holding temporary table */
  19208. i64 seqCount; /* Sequence counter */
  19209. int *aAltMap; /* Mapping from table to index column numbers */
  19210. /* Cached OP_Column parse information is only valid if cacheStatus matches
  19211. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  19212. ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
  19213. ** the cache is out of date. */
  19214. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  19215. int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
  19216. ** if there have been no prior seeks on the cursor. */
  19217. /* seekResult does not distinguish between "no seeks have ever occurred
  19218. ** on this cursor" and "the most recent seek was an exact match".
  19219. ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
  19220. /* When a new VdbeCursor is allocated, only the fields above are zeroed.
  19221. ** The fields that follow are uninitialized, and must be individually
  19222. ** initialized prior to first use. */
  19223. VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
  19224. union {
  19225. BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
  19226. sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
  19227. VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
  19228. } uc;
  19229. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  19230. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  19231. Pgno pgnoRoot; /* Root page of the open btree cursor */
  19232. i16 nField; /* Number of fields in the header */
  19233. u16 nHdrParsed; /* Number of header fields parsed so far */
  19234. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  19235. u32 *aOffset; /* Pointer to aType[nField] */
  19236. const u8 *aRow; /* Data for the current row, if all on one page */
  19237. u32 payloadSize; /* Total number of bytes in the record */
  19238. u32 szRow; /* Byte available in aRow */
  19239. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  19240. u64 maskUsed; /* Mask of columns used by this cursor */
  19241. #endif
  19242. /* 2*nField extra array elements allocated for aType[], beyond the one
  19243. ** static element declared in the structure. nField total array slots for
  19244. ** aType[] and nField+1 array slots for aOffset[] */
  19245. u32 aType[1]; /* Type values record decode. MUST BE LAST */
  19246. };
  19247. /*
  19248. ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
  19249. */
  19250. #define CACHE_STALE 0
  19251. /*
  19252. ** When a sub-program is executed (OP_Program), a structure of this type
  19253. ** is allocated to store the current value of the program counter, as
  19254. ** well as the current memory cell array and various other frame specific
  19255. ** values stored in the Vdbe struct. When the sub-program is finished,
  19256. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  19257. ** restoring the state of the VM to as it was before the sub-program
  19258. ** began executing.
  19259. **
  19260. ** The memory for a VdbeFrame object is allocated and managed by a memory
  19261. ** cell in the parent (calling) frame. When the memory cell is deleted or
  19262. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  19263. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  19264. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  19265. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  19266. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  19267. ** child frame are released.
  19268. **
  19269. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  19270. ** set to NULL if the currently executing frame is the main program.
  19271. */
  19272. typedef struct VdbeFrame VdbeFrame;
  19273. struct VdbeFrame {
  19274. Vdbe *v; /* VM this frame belongs to */
  19275. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  19276. Op *aOp; /* Program instructions for parent frame */
  19277. i64 *anExec; /* Event counters from parent frame */
  19278. Mem *aMem; /* Array of memory cells for parent frame */
  19279. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  19280. u8 *aOnce; /* Bitmask used by OP_Once */
  19281. void *token; /* Copy of SubProgram.token */
  19282. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  19283. AuxData *pAuxData; /* Linked list of auxdata allocations */
  19284. #if SQLITE_DEBUG
  19285. u32 iFrameMagic; /* magic number for sanity checking */
  19286. #endif
  19287. int nCursor; /* Number of entries in apCsr */
  19288. int pc; /* Program Counter in parent (calling) frame */
  19289. int nOp; /* Size of aOp array */
  19290. int nMem; /* Number of entries in aMem */
  19291. int nChildMem; /* Number of memory cells for child frame */
  19292. int nChildCsr; /* Number of cursors for child frame */
  19293. int nChange; /* Statement changes (Vdbe.nChange) */
  19294. int nDbChange; /* Value of db->nChange */
  19295. };
  19296. /* Magic number for sanity checking on VdbeFrame objects */
  19297. #define SQLITE_FRAME_MAGIC 0x879fb71e
  19298. /*
  19299. ** Return a pointer to the array of registers allocated for use
  19300. ** by a VdbeFrame.
  19301. */
  19302. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  19303. /*
  19304. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  19305. ** structures. Each Mem struct may cache multiple representations (string,
  19306. ** integer etc.) of the same value.
  19307. */
  19308. struct sqlite3_value {
  19309. union MemValue {
  19310. double r; /* Real value used when MEM_Real is set in flags */
  19311. i64 i; /* Integer value used when MEM_Int is set in flags */
  19312. int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
  19313. const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
  19314. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  19315. } u;
  19316. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  19317. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  19318. u8 eSubtype; /* Subtype for this value */
  19319. int n; /* Number of characters in string value, excluding '\0' */
  19320. char *z; /* String or BLOB value */
  19321. /* ShallowCopy only needs to copy the information above */
  19322. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  19323. int szMalloc; /* Size of the zMalloc allocation */
  19324. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  19325. sqlite3 *db; /* The associated database connection */
  19326. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  19327. #ifdef SQLITE_DEBUG
  19328. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  19329. u16 mScopyFlags; /* flags value immediately after the shallow copy */
  19330. #endif
  19331. };
  19332. /*
  19333. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  19334. ** follows.
  19335. */
  19336. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  19337. /* One or more of the following flags are set to indicate the validOK
  19338. ** representations of the value stored in the Mem struct.
  19339. **
  19340. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  19341. ** For a pointer type created using sqlite3_bind_pointer() or
  19342. ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
  19343. **
  19344. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  19345. ** Usually this is encoded in the same unicode encoding as the main
  19346. ** database (see below for exceptions). If the MEM_Term flag is also
  19347. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  19348. ** flags may coexist with the MEM_Str flag.
  19349. */
  19350. #define MEM_Null 0x0001 /* Value is NULL (or a pointer) */
  19351. #define MEM_Str 0x0002 /* Value is a string */
  19352. #define MEM_Int 0x0004 /* Value is an integer */
  19353. #define MEM_Real 0x0008 /* Value is a real number */
  19354. #define MEM_Blob 0x0010 /* Value is a BLOB */
  19355. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  19356. #define MEM_FromBind 0x0020 /* Value originates from sqlite3_bind() */
  19357. /* Available 0x0040 */
  19358. #define MEM_Undefined 0x0080 /* Value is undefined */
  19359. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  19360. #define MEM_TypeMask 0xc1df /* Mask of type bits */
  19361. /* Whenever Mem contains a valid string or blob representation, one of
  19362. ** the following flags must be set to determine the memory management
  19363. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  19364. ** string is \000 or \u0000 terminated
  19365. */
  19366. #define MEM_Term 0x0200 /* String in Mem.z is zero terminated */
  19367. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  19368. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  19369. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  19370. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  19371. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  19372. #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
  19373. #ifdef SQLITE_OMIT_INCRBLOB
  19374. #undef MEM_Zero
  19375. #define MEM_Zero 0x0000
  19376. #endif
  19377. /* Return TRUE if Mem X contains dynamically allocated content - anything
  19378. ** that needs to be deallocated to avoid a leak.
  19379. */
  19380. #define VdbeMemDynamic(X) \
  19381. (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)
  19382. /*
  19383. ** Clear any existing type flags from a Mem and replace them with f
  19384. */
  19385. #define MemSetTypeFlag(p, f) \
  19386. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  19387. /*
  19388. ** True if Mem X is a NULL-nochng type.
  19389. */
  19390. #define MemNullNochng(X) \
  19391. ((X)->flags==(MEM_Null|MEM_Zero) && (X)->n==0 && (X)->u.nZero==0)
  19392. /*
  19393. ** Return true if a memory cell is not marked as invalid. This macro
  19394. ** is for use inside assert() statements only.
  19395. */
  19396. #ifdef SQLITE_DEBUG
  19397. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  19398. #endif
  19399. /*
  19400. ** Each auxiliary data pointer stored by a user defined function
  19401. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  19402. ** of this structure. All such structures associated with a single VM
  19403. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  19404. ** when the VM is halted (if not before).
  19405. */
  19406. struct AuxData {
  19407. int iAuxOp; /* Instruction number of OP_Function opcode */
  19408. int iAuxArg; /* Index of function argument. */
  19409. void *pAux; /* Aux data pointer */
  19410. void (*xDeleteAux)(void*); /* Destructor for the aux data */
  19411. AuxData *pNextAux; /* Next element in list */
  19412. };
  19413. /*
  19414. ** The "context" argument for an installable function. A pointer to an
  19415. ** instance of this structure is the first argument to the routines used
  19416. ** implement the SQL functions.
  19417. **
  19418. ** There is a typedef for this structure in sqlite.h. So all routines,
  19419. ** even the public interface to SQLite, can use a pointer to this structure.
  19420. ** But this file is the only place where the internal details of this
  19421. ** structure are known.
  19422. **
  19423. ** This structure is defined inside of vdbeInt.h because it uses substructures
  19424. ** (Mem) which are only defined there.
  19425. */
  19426. struct sqlite3_context {
  19427. Mem *pOut; /* The return value is stored here */
  19428. FuncDef *pFunc; /* Pointer to function information */
  19429. Mem *pMem; /* Memory cell used to store aggregate context */
  19430. Vdbe *pVdbe; /* The VM that owns this context */
  19431. int iOp; /* Instruction number of OP_Function */
  19432. int isError; /* Error code returned by the function. */
  19433. u8 skipFlag; /* Skip accumulator loading if true */
  19434. u8 argc; /* Number of arguments */
  19435. sqlite3_value *argv[1]; /* Argument set */
  19436. };
  19437. /* A bitfield type for use inside of structures. Always follow with :N where
  19438. ** N is the number of bits.
  19439. */
  19440. typedef unsigned bft; /* Bit Field Type */
  19441. /* The ScanStatus object holds a single value for the
  19442. ** sqlite3_stmt_scanstatus() interface.
  19443. */
  19444. typedef struct ScanStatus ScanStatus;
  19445. struct ScanStatus {
  19446. int addrExplain; /* OP_Explain for loop */
  19447. int addrLoop; /* Address of "loops" counter */
  19448. int addrVisit; /* Address of "rows visited" counter */
  19449. int iSelectID; /* The "Select-ID" for this loop */
  19450. LogEst nEst; /* Estimated output rows per loop */
  19451. char *zName; /* Name of table or index */
  19452. };
  19453. /* The DblquoteStr object holds the text of a double-quoted
  19454. ** string for a prepared statement. A linked list of these objects
  19455. ** is constructed during statement parsing and is held on Vdbe.pDblStr.
  19456. ** When computing a normalized SQL statement for an SQL statement, that
  19457. ** list is consulted for each double-quoted identifier to see if the
  19458. ** identifier should really be a string literal.
  19459. */
  19460. typedef struct DblquoteStr DblquoteStr;
  19461. struct DblquoteStr {
  19462. DblquoteStr *pNextStr; /* Next string literal in the list */
  19463. char z[8]; /* Dequoted value for the string */
  19464. };
  19465. /*
  19466. ** An instance of the virtual machine. This structure contains the complete
  19467. ** state of the virtual machine.
  19468. **
  19469. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  19470. ** is really a pointer to an instance of this structure.
  19471. */
  19472. struct Vdbe {
  19473. sqlite3 *db; /* The database connection that owns this statement */
  19474. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  19475. Parse *pParse; /* Parsing context used to create this Vdbe */
  19476. ynVar nVar; /* Number of entries in aVar[] */
  19477. u32 magic; /* Magic number for sanity checking */
  19478. int nMem; /* Number of memory locations currently allocated */
  19479. int nCursor; /* Number of slots in apCsr[] */
  19480. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  19481. int pc; /* The program counter */
  19482. int rc; /* Value to return */
  19483. int nChange; /* Number of db changes made since last reset */
  19484. int iStatement; /* Statement number (or 0 if has no opened stmt) */
  19485. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  19486. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  19487. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  19488. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  19489. Mem *aMem; /* The memory locations */
  19490. Mem **apArg; /* Arguments to currently executing user function */
  19491. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  19492. Mem *aVar; /* Values for the OP_Variable opcode. */
  19493. /* When allocating a new Vdbe object, all of the fields below should be
  19494. ** initialized to zero or NULL */
  19495. Op *aOp; /* Space to hold the virtual machine's program */
  19496. int nOp; /* Number of instructions in the program */
  19497. int nOpAlloc; /* Slots allocated for aOp[] */
  19498. Mem *aColName; /* Column names to return */
  19499. Mem *pResultSet; /* Pointer to an array of results */
  19500. char *zErrMsg; /* Error message written here */
  19501. VList *pVList; /* Name of variables */
  19502. #ifndef SQLITE_OMIT_TRACE
  19503. i64 startTime; /* Time when query started - used for profiling */
  19504. #endif
  19505. #ifdef SQLITE_DEBUG
  19506. int rcApp; /* errcode set by sqlite3_result_error_code() */
  19507. u32 nWrite; /* Number of write operations that have occurred */
  19508. #endif
  19509. u16 nResColumn; /* Number of columns in one row of the result set */
  19510. u8 errorAction; /* Recovery action to do in case of an error */
  19511. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  19512. u8 prepFlags; /* SQLITE_PREPARE_* flags */
  19513. bft expired:2; /* 1: recompile VM immediately 2: when convenient */
  19514. bft explain:2; /* True if EXPLAIN present on SQL command */
  19515. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  19516. bft changeCntOn:1; /* True to update the change-counter */
  19517. bft runOnlyOnce:1; /* Automatically expire on reset */
  19518. bft usesStmtJournal:1; /* True if uses a statement journal */
  19519. bft readOnly:1; /* True for statements that do not write */
  19520. bft bIsReader:1; /* True for statements that read */
  19521. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  19522. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  19523. u32 aCounter[7]; /* Counters used by sqlite3_stmt_status() */
  19524. char *zSql; /* Text of the SQL statement that generated this */
  19525. #ifdef SQLITE_ENABLE_NORMALIZE
  19526. char *zNormSql; /* Normalization of the associated SQL statement */
  19527. DblquoteStr *pDblStr; /* List of double-quoted string literals */
  19528. #endif
  19529. void *pFree; /* Free this when deleting the vdbe */
  19530. VdbeFrame *pFrame; /* Parent frame */
  19531. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  19532. int nFrame; /* Number of frames in pFrame list */
  19533. u32 expmask; /* Binding to these vars invalidates VM */
  19534. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  19535. AuxData *pAuxData; /* Linked list of auxdata allocations */
  19536. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  19537. i64 *anExec; /* Number of times each op has been executed */
  19538. int nScan; /* Entries in aScan[] */
  19539. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  19540. #endif
  19541. };
  19542. /*
  19543. ** The following are allowed values for Vdbe.magic
  19544. */
  19545. #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
  19546. #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
  19547. #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
  19548. #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
  19549. #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
  19550. /*
  19551. ** Structure used to store the context required by the
  19552. ** sqlite3_preupdate_*() API functions.
  19553. */
  19554. struct PreUpdate {
  19555. Vdbe *v;
  19556. VdbeCursor *pCsr; /* Cursor to read old values from */
  19557. int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
  19558. u8 *aRecord; /* old.* database record */
  19559. KeyInfo keyinfo;
  19560. UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
  19561. UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
  19562. int iNewReg; /* Register for new.* values */
  19563. i64 iKey1; /* First key value passed to hook */
  19564. i64 iKey2; /* Second key value passed to hook */
  19565. Mem *aNew; /* Array of new.* values */
  19566. Table *pTab; /* Schema object being upated */
  19567. Index *pPk; /* PK index if pTab is WITHOUT ROWID */
  19568. };
  19569. /*
  19570. ** Function prototypes
  19571. */
  19572. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  19573. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  19574. void sqliteVdbePopStack(Vdbe*,int);
  19575. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
  19576. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  19577. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  19578. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
  19579. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
  19580. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  19581. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  19582. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
  19583. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  19584. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  19585. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  19586. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  19587. #ifndef SQLITE_OMIT_EXPLAIN
  19588. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  19589. #endif
  19590. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  19591. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  19592. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  19593. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  19594. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  19595. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  19596. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  19597. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  19598. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  19599. #ifdef SQLITE_OMIT_FLOATING_POINT
  19600. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  19601. #else
  19602. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  19603. #endif
  19604. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
  19605. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  19606. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  19607. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  19608. #ifdef SQLITE_DEBUG
  19609. SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*);
  19610. #endif
  19611. SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*);
  19612. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  19613. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  19614. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  19615. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  19616. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  19617. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
  19618. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  19619. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  19620. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  19621. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  19622. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
  19623. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  19624. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  19625. #ifndef SQLITE_OMIT_WINDOWFUNC
  19626. SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
  19627. #endif
  19628. #ifndef SQLITE_OMIT_EXPLAIN
  19629. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  19630. #endif
  19631. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  19632. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  19633. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  19634. #ifdef SQLITE_DEBUG
  19635. SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame*);
  19636. #endif
  19637. SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*); /* Destructor on Mem */
  19638. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */
  19639. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  19640. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  19641. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
  19642. #endif
  19643. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  19644. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  19645. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  19646. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  19647. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  19648. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
  19649. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  19650. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  19651. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  19652. #ifdef SQLITE_DEBUG
  19653. SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
  19654. SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe*);
  19655. #else
  19656. # define sqlite3VdbeIncrWriteCounter(V,C)
  19657. # define sqlite3VdbeAssertAbortable(V)
  19658. #endif
  19659. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  19660. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  19661. #else
  19662. # define sqlite3VdbeEnter(X)
  19663. #endif
  19664. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  19665. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  19666. #else
  19667. # define sqlite3VdbeLeave(X)
  19668. #endif
  19669. #ifdef SQLITE_DEBUG
  19670. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  19671. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  19672. #endif
  19673. #ifndef SQLITE_OMIT_FOREIGN_KEY
  19674. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  19675. #else
  19676. # define sqlite3VdbeCheckFk(p,i) 0
  19677. #endif
  19678. #ifdef SQLITE_DEBUG
  19679. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  19680. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  19681. #endif
  19682. #ifndef SQLITE_OMIT_UTF16
  19683. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  19684. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  19685. #endif
  19686. #ifndef SQLITE_OMIT_INCRBLOB
  19687. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  19688. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  19689. #else
  19690. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  19691. #define ExpandBlob(P) SQLITE_OK
  19692. #endif
  19693. #endif /* !defined(SQLITE_VDBEINT_H) */
  19694. /************** End of vdbeInt.h *********************************************/
  19695. /************** Continuing where we left off in status.c *********************/
  19696. /*
  19697. ** Variables in which to record status information.
  19698. */
  19699. #if SQLITE_PTRSIZE>4
  19700. typedef sqlite3_int64 sqlite3StatValueType;
  19701. #else
  19702. typedef u32 sqlite3StatValueType;
  19703. #endif
  19704. typedef struct sqlite3StatType sqlite3StatType;
  19705. static SQLITE_WSD struct sqlite3StatType {
  19706. sqlite3StatValueType nowValue[10]; /* Current value */
  19707. sqlite3StatValueType mxValue[10]; /* Maximum value */
  19708. } sqlite3Stat = { {0,}, {0,} };
  19709. /*
  19710. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  19711. ** mutex, or by the pcache1 mutex. The following array determines which.
  19712. */
  19713. static const char statMutex[] = {
  19714. 0, /* SQLITE_STATUS_MEMORY_USED */
  19715. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  19716. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  19717. 0, /* SQLITE_STATUS_SCRATCH_USED */
  19718. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  19719. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  19720. 0, /* SQLITE_STATUS_PARSER_STACK */
  19721. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  19722. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  19723. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  19724. };
  19725. /* The "wsdStat" macro will resolve to the status information
  19726. ** state vector. If writable static data is unsupported on the target,
  19727. ** we have to locate the state vector at run-time. In the more common
  19728. ** case where writable static data is supported, wsdStat can refer directly
  19729. ** to the "sqlite3Stat" state vector declared above.
  19730. */
  19731. #ifdef SQLITE_OMIT_WSD
  19732. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  19733. # define wsdStat x[0]
  19734. #else
  19735. # define wsdStatInit
  19736. # define wsdStat sqlite3Stat
  19737. #endif
  19738. /*
  19739. ** Return the current value of a status parameter. The caller must
  19740. ** be holding the appropriate mutex.
  19741. */
  19742. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  19743. wsdStatInit;
  19744. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19745. assert( op>=0 && op<ArraySize(statMutex) );
  19746. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19747. : sqlite3MallocMutex()) );
  19748. return wsdStat.nowValue[op];
  19749. }
  19750. /*
  19751. ** Add N to the value of a status record. The caller must hold the
  19752. ** appropriate mutex. (Locking is checked by assert()).
  19753. **
  19754. ** The StatusUp() routine can accept positive or negative values for N.
  19755. ** The value of N is added to the current status value and the high-water
  19756. ** mark is adjusted if necessary.
  19757. **
  19758. ** The StatusDown() routine lowers the current value by N. The highwater
  19759. ** mark is unchanged. N must be non-negative for StatusDown().
  19760. */
  19761. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  19762. wsdStatInit;
  19763. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19764. assert( op>=0 && op<ArraySize(statMutex) );
  19765. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19766. : sqlite3MallocMutex()) );
  19767. wsdStat.nowValue[op] += N;
  19768. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  19769. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  19770. }
  19771. }
  19772. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  19773. wsdStatInit;
  19774. assert( N>=0 );
  19775. assert( op>=0 && op<ArraySize(statMutex) );
  19776. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19777. : sqlite3MallocMutex()) );
  19778. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19779. wsdStat.nowValue[op] -= N;
  19780. }
  19781. /*
  19782. ** Adjust the highwater mark if necessary.
  19783. ** The caller must hold the appropriate mutex.
  19784. */
  19785. SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
  19786. sqlite3StatValueType newValue;
  19787. wsdStatInit;
  19788. assert( X>=0 );
  19789. newValue = (sqlite3StatValueType)X;
  19790. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  19791. assert( op>=0 && op<ArraySize(statMutex) );
  19792. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  19793. : sqlite3MallocMutex()) );
  19794. assert( op==SQLITE_STATUS_MALLOC_SIZE
  19795. || op==SQLITE_STATUS_PAGECACHE_SIZE
  19796. || op==SQLITE_STATUS_PARSER_STACK );
  19797. if( newValue>wsdStat.mxValue[op] ){
  19798. wsdStat.mxValue[op] = newValue;
  19799. }
  19800. }
  19801. /*
  19802. ** Query status information.
  19803. */
  19804. SQLITE_API int sqlite3_status64(
  19805. int op,
  19806. sqlite3_int64 *pCurrent,
  19807. sqlite3_int64 *pHighwater,
  19808. int resetFlag
  19809. ){
  19810. sqlite3_mutex *pMutex;
  19811. wsdStatInit;
  19812. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  19813. return SQLITE_MISUSE_BKPT;
  19814. }
  19815. #ifdef SQLITE_ENABLE_API_ARMOR
  19816. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  19817. #endif
  19818. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  19819. sqlite3_mutex_enter(pMutex);
  19820. *pCurrent = wsdStat.nowValue[op];
  19821. *pHighwater = wsdStat.mxValue[op];
  19822. if( resetFlag ){
  19823. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  19824. }
  19825. sqlite3_mutex_leave(pMutex);
  19826. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  19827. return SQLITE_OK;
  19828. }
  19829. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  19830. sqlite3_int64 iCur = 0, iHwtr = 0;
  19831. int rc;
  19832. #ifdef SQLITE_ENABLE_API_ARMOR
  19833. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  19834. #endif
  19835. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  19836. if( rc==0 ){
  19837. *pCurrent = (int)iCur;
  19838. *pHighwater = (int)iHwtr;
  19839. }
  19840. return rc;
  19841. }
  19842. /*
  19843. ** Return the number of LookasideSlot elements on the linked list
  19844. */
  19845. static u32 countLookasideSlots(LookasideSlot *p){
  19846. u32 cnt = 0;
  19847. while( p ){
  19848. p = p->pNext;
  19849. cnt++;
  19850. }
  19851. return cnt;
  19852. }
  19853. /*
  19854. ** Count the number of slots of lookaside memory that are outstanding
  19855. */
  19856. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
  19857. u32 nInit = countLookasideSlots(db->lookaside.pInit);
  19858. u32 nFree = countLookasideSlots(db->lookaside.pFree);
  19859. if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
  19860. return db->lookaside.nSlot - (nInit+nFree);
  19861. }
  19862. /*
  19863. ** Query status information for a single database connection
  19864. */
  19865. SQLITE_API int sqlite3_db_status(
  19866. sqlite3 *db, /* The database connection whose status is desired */
  19867. int op, /* Status verb */
  19868. int *pCurrent, /* Write current value here */
  19869. int *pHighwater, /* Write high-water mark here */
  19870. int resetFlag /* Reset high-water mark if true */
  19871. ){
  19872. int rc = SQLITE_OK; /* Return code */
  19873. #ifdef SQLITE_ENABLE_API_ARMOR
  19874. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  19875. return SQLITE_MISUSE_BKPT;
  19876. }
  19877. #endif
  19878. sqlite3_mutex_enter(db->mutex);
  19879. switch( op ){
  19880. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  19881. *pCurrent = sqlite3LookasideUsed(db, pHighwater);
  19882. if( resetFlag ){
  19883. LookasideSlot *p = db->lookaside.pFree;
  19884. if( p ){
  19885. while( p->pNext ) p = p->pNext;
  19886. p->pNext = db->lookaside.pInit;
  19887. db->lookaside.pInit = db->lookaside.pFree;
  19888. db->lookaside.pFree = 0;
  19889. }
  19890. }
  19891. break;
  19892. }
  19893. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  19894. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  19895. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  19896. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  19897. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  19898. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  19899. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  19900. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  19901. *pCurrent = 0;
  19902. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  19903. if( resetFlag ){
  19904. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  19905. }
  19906. break;
  19907. }
  19908. /*
  19909. ** Return an approximation for the amount of memory currently used
  19910. ** by all pagers associated with the given database connection. The
  19911. ** highwater mark is meaningless and is returned as zero.
  19912. */
  19913. case SQLITE_DBSTATUS_CACHE_USED_SHARED:
  19914. case SQLITE_DBSTATUS_CACHE_USED: {
  19915. int totalUsed = 0;
  19916. int i;
  19917. sqlite3BtreeEnterAll(db);
  19918. for(i=0; i<db->nDb; i++){
  19919. Btree *pBt = db->aDb[i].pBt;
  19920. if( pBt ){
  19921. Pager *pPager = sqlite3BtreePager(pBt);
  19922. int nByte = sqlite3PagerMemUsed(pPager);
  19923. if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
  19924. nByte = nByte / sqlite3BtreeConnectionCount(pBt);
  19925. }
  19926. totalUsed += nByte;
  19927. }
  19928. }
  19929. sqlite3BtreeLeaveAll(db);
  19930. *pCurrent = totalUsed;
  19931. *pHighwater = 0;
  19932. break;
  19933. }
  19934. /*
  19935. ** *pCurrent gets an accurate estimate of the amount of memory used
  19936. ** to store the schema for all databases (main, temp, and any ATTACHed
  19937. ** databases. *pHighwater is set to zero.
  19938. */
  19939. case SQLITE_DBSTATUS_SCHEMA_USED: {
  19940. int i; /* Used to iterate through schemas */
  19941. int nByte = 0; /* Used to accumulate return value */
  19942. sqlite3BtreeEnterAll(db);
  19943. db->pnBytesFreed = &nByte;
  19944. for(i=0; i<db->nDb; i++){
  19945. Schema *pSchema = db->aDb[i].pSchema;
  19946. if( ALWAYS(pSchema!=0) ){
  19947. HashElem *p;
  19948. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  19949. pSchema->tblHash.count
  19950. + pSchema->trigHash.count
  19951. + pSchema->idxHash.count
  19952. + pSchema->fkeyHash.count
  19953. );
  19954. nByte += sqlite3_msize(pSchema->tblHash.ht);
  19955. nByte += sqlite3_msize(pSchema->trigHash.ht);
  19956. nByte += sqlite3_msize(pSchema->idxHash.ht);
  19957. nByte += sqlite3_msize(pSchema->fkeyHash.ht);
  19958. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  19959. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  19960. }
  19961. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  19962. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  19963. }
  19964. }
  19965. }
  19966. db->pnBytesFreed = 0;
  19967. sqlite3BtreeLeaveAll(db);
  19968. *pHighwater = 0;
  19969. *pCurrent = nByte;
  19970. break;
  19971. }
  19972. /*
  19973. ** *pCurrent gets an accurate estimate of the amount of memory used
  19974. ** to store all prepared statements.
  19975. ** *pHighwater is set to zero.
  19976. */
  19977. case SQLITE_DBSTATUS_STMT_USED: {
  19978. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  19979. int nByte = 0; /* Used to accumulate return value */
  19980. db->pnBytesFreed = &nByte;
  19981. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  19982. sqlite3VdbeClearObject(db, pVdbe);
  19983. sqlite3DbFree(db, pVdbe);
  19984. }
  19985. db->pnBytesFreed = 0;
  19986. *pHighwater = 0; /* IMP: R-64479-57858 */
  19987. *pCurrent = nByte;
  19988. break;
  19989. }
  19990. /*
  19991. ** Set *pCurrent to the total cache hits or misses encountered by all
  19992. ** pagers the database handle is connected to. *pHighwater is always set
  19993. ** to zero.
  19994. */
  19995. case SQLITE_DBSTATUS_CACHE_SPILL:
  19996. op = SQLITE_DBSTATUS_CACHE_WRITE+1;
  19997. /* Fall through into the next case */
  19998. case SQLITE_DBSTATUS_CACHE_HIT:
  19999. case SQLITE_DBSTATUS_CACHE_MISS:
  20000. case SQLITE_DBSTATUS_CACHE_WRITE:{
  20001. int i;
  20002. int nRet = 0;
  20003. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  20004. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  20005. for(i=0; i<db->nDb; i++){
  20006. if( db->aDb[i].pBt ){
  20007. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  20008. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  20009. }
  20010. }
  20011. *pHighwater = 0; /* IMP: R-42420-56072 */
  20012. /* IMP: R-54100-20147 */
  20013. /* IMP: R-29431-39229 */
  20014. *pCurrent = nRet;
  20015. break;
  20016. }
  20017. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  20018. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  20019. ** have been satisfied. The *pHighwater is always set to zero.
  20020. */
  20021. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  20022. *pHighwater = 0; /* IMP: R-11967-56545 */
  20023. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  20024. break;
  20025. }
  20026. default: {
  20027. rc = SQLITE_ERROR;
  20028. }
  20029. }
  20030. sqlite3_mutex_leave(db->mutex);
  20031. return rc;
  20032. }
  20033. /************** End of status.c **********************************************/
  20034. /************** Begin file date.c ********************************************/
  20035. /*
  20036. ** 2003 October 31
  20037. **
  20038. ** The author disclaims copyright to this source code. In place of
  20039. ** a legal notice, here is a blessing:
  20040. **
  20041. ** May you do good and not evil.
  20042. ** May you find forgiveness for yourself and forgive others.
  20043. ** May you share freely, never taking more than you give.
  20044. **
  20045. *************************************************************************
  20046. ** This file contains the C functions that implement date and time
  20047. ** functions for SQLite.
  20048. **
  20049. ** There is only one exported symbol in this file - the function
  20050. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  20051. ** All other code has file scope.
  20052. **
  20053. ** SQLite processes all times and dates as julian day numbers. The
  20054. ** dates and times are stored as the number of days since noon
  20055. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  20056. ** calendar system.
  20057. **
  20058. ** 1970-01-01 00:00:00 is JD 2440587.5
  20059. ** 2000-01-01 00:00:00 is JD 2451544.5
  20060. **
  20061. ** This implementation requires years to be expressed as a 4-digit number
  20062. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  20063. ** be represented, even though julian day numbers allow a much wider
  20064. ** range of dates.
  20065. **
  20066. ** The Gregorian calendar system is used for all dates and times,
  20067. ** even those that predate the Gregorian calendar. Historians usually
  20068. ** use the julian calendar for dates prior to 1582-10-15 and for some
  20069. ** dates afterwards, depending on locale. Beware of this difference.
  20070. **
  20071. ** The conversion algorithms are implemented based on descriptions
  20072. ** in the following text:
  20073. **
  20074. ** Jean Meeus
  20075. ** Astronomical Algorithms, 2nd Edition, 1998
  20076. ** ISBN 0-943396-61-1
  20077. ** Willmann-Bell, Inc
  20078. ** Richmond, Virginia (USA)
  20079. */
  20080. /* #include "sqliteInt.h" */
  20081. /* #include <stdlib.h> */
  20082. /* #include <assert.h> */
  20083. #include <time.h>
  20084. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  20085. /*
  20086. ** The MSVC CRT on Windows CE may not have a localtime() function.
  20087. ** So declare a substitute. The substitute function itself is
  20088. ** defined in "os_win.c".
  20089. */
  20090. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  20091. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  20092. struct tm *__cdecl localtime(const time_t *);
  20093. #endif
  20094. /*
  20095. ** A structure for holding a single date and time.
  20096. */
  20097. typedef struct DateTime DateTime;
  20098. struct DateTime {
  20099. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  20100. int Y, M, D; /* Year, month, and day */
  20101. int h, m; /* Hour and minutes */
  20102. int tz; /* Timezone offset in minutes */
  20103. double s; /* Seconds */
  20104. char validJD; /* True (1) if iJD is valid */
  20105. char rawS; /* Raw numeric value stored in s */
  20106. char validYMD; /* True (1) if Y,M,D are valid */
  20107. char validHMS; /* True (1) if h,m,s are valid */
  20108. char validTZ; /* True (1) if tz is valid */
  20109. char tzSet; /* Timezone was set explicitly */
  20110. char isError; /* An overflow has occurred */
  20111. };
  20112. /*
  20113. ** Convert zDate into one or more integers according to the conversion
  20114. ** specifier zFormat.
  20115. **
  20116. ** zFormat[] contains 4 characters for each integer converted, except for
  20117. ** the last integer which is specified by three characters. The meaning
  20118. ** of a four-character format specifiers ABCD is:
  20119. **
  20120. ** A: number of digits to convert. Always "2" or "4".
  20121. ** B: minimum value. Always "0" or "1".
  20122. ** C: maximum value, decoded as:
  20123. ** a: 12
  20124. ** b: 14
  20125. ** c: 24
  20126. ** d: 31
  20127. ** e: 59
  20128. ** f: 9999
  20129. ** D: the separator character, or \000 to indicate this is the
  20130. ** last number to convert.
  20131. **
  20132. ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
  20133. ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
  20134. ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
  20135. ** the 2-digit day which is the last integer in the set.
  20136. **
  20137. ** The function returns the number of successful conversions.
  20138. */
  20139. static int getDigits(const char *zDate, const char *zFormat, ...){
  20140. /* The aMx[] array translates the 3rd character of each format
  20141. ** spec into a max size: a b c d e f */
  20142. static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
  20143. va_list ap;
  20144. int cnt = 0;
  20145. char nextC;
  20146. va_start(ap, zFormat);
  20147. do{
  20148. char N = zFormat[0] - '0';
  20149. char min = zFormat[1] - '0';
  20150. int val = 0;
  20151. u16 max;
  20152. assert( zFormat[2]>='a' && zFormat[2]<='f' );
  20153. max = aMx[zFormat[2] - 'a'];
  20154. nextC = zFormat[3];
  20155. val = 0;
  20156. while( N-- ){
  20157. if( !sqlite3Isdigit(*zDate) ){
  20158. goto end_getDigits;
  20159. }
  20160. val = val*10 + *zDate - '0';
  20161. zDate++;
  20162. }
  20163. if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
  20164. goto end_getDigits;
  20165. }
  20166. *va_arg(ap,int*) = val;
  20167. zDate++;
  20168. cnt++;
  20169. zFormat += 4;
  20170. }while( nextC );
  20171. end_getDigits:
  20172. va_end(ap);
  20173. return cnt;
  20174. }
  20175. /*
  20176. ** Parse a timezone extension on the end of a date-time.
  20177. ** The extension is of the form:
  20178. **
  20179. ** (+/-)HH:MM
  20180. **
  20181. ** Or the "zulu" notation:
  20182. **
  20183. ** Z
  20184. **
  20185. ** If the parse is successful, write the number of minutes
  20186. ** of change in p->tz and return 0. If a parser error occurs,
  20187. ** return non-zero.
  20188. **
  20189. ** A missing specifier is not considered an error.
  20190. */
  20191. static int parseTimezone(const char *zDate, DateTime *p){
  20192. int sgn = 0;
  20193. int nHr, nMn;
  20194. int c;
  20195. while( sqlite3Isspace(*zDate) ){ zDate++; }
  20196. p->tz = 0;
  20197. c = *zDate;
  20198. if( c=='-' ){
  20199. sgn = -1;
  20200. }else if( c=='+' ){
  20201. sgn = +1;
  20202. }else if( c=='Z' || c=='z' ){
  20203. zDate++;
  20204. goto zulu_time;
  20205. }else{
  20206. return c!=0;
  20207. }
  20208. zDate++;
  20209. if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
  20210. return 1;
  20211. }
  20212. zDate += 5;
  20213. p->tz = sgn*(nMn + nHr*60);
  20214. zulu_time:
  20215. while( sqlite3Isspace(*zDate) ){ zDate++; }
  20216. p->tzSet = 1;
  20217. return *zDate!=0;
  20218. }
  20219. /*
  20220. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  20221. ** The HH, MM, and SS must each be exactly 2 digits. The
  20222. ** fractional seconds FFFF can be one or more digits.
  20223. **
  20224. ** Return 1 if there is a parsing error and 0 on success.
  20225. */
  20226. static int parseHhMmSs(const char *zDate, DateTime *p){
  20227. int h, m, s;
  20228. double ms = 0.0;
  20229. if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
  20230. return 1;
  20231. }
  20232. zDate += 5;
  20233. if( *zDate==':' ){
  20234. zDate++;
  20235. if( getDigits(zDate, "20e", &s)!=1 ){
  20236. return 1;
  20237. }
  20238. zDate += 2;
  20239. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  20240. double rScale = 1.0;
  20241. zDate++;
  20242. while( sqlite3Isdigit(*zDate) ){
  20243. ms = ms*10.0 + *zDate - '0';
  20244. rScale *= 10.0;
  20245. zDate++;
  20246. }
  20247. ms /= rScale;
  20248. }
  20249. }else{
  20250. s = 0;
  20251. }
  20252. p->validJD = 0;
  20253. p->rawS = 0;
  20254. p->validHMS = 1;
  20255. p->h = h;
  20256. p->m = m;
  20257. p->s = s + ms;
  20258. if( parseTimezone(zDate, p) ) return 1;
  20259. p->validTZ = (p->tz!=0)?1:0;
  20260. return 0;
  20261. }
  20262. /*
  20263. ** Put the DateTime object into its error state.
  20264. */
  20265. static void datetimeError(DateTime *p){
  20266. memset(p, 0, sizeof(*p));
  20267. p->isError = 1;
  20268. }
  20269. /*
  20270. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  20271. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  20272. **
  20273. ** Reference: Meeus page 61
  20274. */
  20275. static void computeJD(DateTime *p){
  20276. int Y, M, D, A, B, X1, X2;
  20277. if( p->validJD ) return;
  20278. if( p->validYMD ){
  20279. Y = p->Y;
  20280. M = p->M;
  20281. D = p->D;
  20282. }else{
  20283. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  20284. M = 1;
  20285. D = 1;
  20286. }
  20287. if( Y<-4713 || Y>9999 || p->rawS ){
  20288. datetimeError(p);
  20289. return;
  20290. }
  20291. if( M<=2 ){
  20292. Y--;
  20293. M += 12;
  20294. }
  20295. A = Y/100;
  20296. B = 2 - A + (A/4);
  20297. X1 = 36525*(Y+4716)/100;
  20298. X2 = 306001*(M+1)/10000;
  20299. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  20300. p->validJD = 1;
  20301. if( p->validHMS ){
  20302. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  20303. if( p->validTZ ){
  20304. p->iJD -= p->tz*60000;
  20305. p->validYMD = 0;
  20306. p->validHMS = 0;
  20307. p->validTZ = 0;
  20308. }
  20309. }
  20310. }
  20311. /*
  20312. ** Parse dates of the form
  20313. **
  20314. ** YYYY-MM-DD HH:MM:SS.FFF
  20315. ** YYYY-MM-DD HH:MM:SS
  20316. ** YYYY-MM-DD HH:MM
  20317. ** YYYY-MM-DD
  20318. **
  20319. ** Write the result into the DateTime structure and return 0
  20320. ** on success and 1 if the input string is not a well-formed
  20321. ** date.
  20322. */
  20323. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  20324. int Y, M, D, neg;
  20325. if( zDate[0]=='-' ){
  20326. zDate++;
  20327. neg = 1;
  20328. }else{
  20329. neg = 0;
  20330. }
  20331. if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
  20332. return 1;
  20333. }
  20334. zDate += 10;
  20335. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  20336. if( parseHhMmSs(zDate, p)==0 ){
  20337. /* We got the time */
  20338. }else if( *zDate==0 ){
  20339. p->validHMS = 0;
  20340. }else{
  20341. return 1;
  20342. }
  20343. p->validJD = 0;
  20344. p->validYMD = 1;
  20345. p->Y = neg ? -Y : Y;
  20346. p->M = M;
  20347. p->D = D;
  20348. if( p->validTZ ){
  20349. computeJD(p);
  20350. }
  20351. return 0;
  20352. }
  20353. /*
  20354. ** Set the time to the current time reported by the VFS.
  20355. **
  20356. ** Return the number of errors.
  20357. */
  20358. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  20359. p->iJD = sqlite3StmtCurrentTime(context);
  20360. if( p->iJD>0 ){
  20361. p->validJD = 1;
  20362. return 0;
  20363. }else{
  20364. return 1;
  20365. }
  20366. }
  20367. /*
  20368. ** Input "r" is a numeric quantity which might be a julian day number,
  20369. ** or the number of seconds since 1970. If the value if r is within
  20370. ** range of a julian day number, install it as such and set validJD.
  20371. ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
  20372. */
  20373. static void setRawDateNumber(DateTime *p, double r){
  20374. p->s = r;
  20375. p->rawS = 1;
  20376. if( r>=0.0 && r<5373484.5 ){
  20377. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  20378. p->validJD = 1;
  20379. }
  20380. }
  20381. /*
  20382. ** Attempt to parse the given string into a julian day number. Return
  20383. ** the number of errors.
  20384. **
  20385. ** The following are acceptable forms for the input string:
  20386. **
  20387. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  20388. ** DDDD.DD
  20389. ** now
  20390. **
  20391. ** In the first form, the +/-HH:MM is always optional. The fractional
  20392. ** seconds extension (the ".FFF") is optional. The seconds portion
  20393. ** (":SS.FFF") is option. The year and date can be omitted as long
  20394. ** as there is a time string. The time string can be omitted as long
  20395. ** as there is a year and date.
  20396. */
  20397. static int parseDateOrTime(
  20398. sqlite3_context *context,
  20399. const char *zDate,
  20400. DateTime *p
  20401. ){
  20402. double r;
  20403. if( parseYyyyMmDd(zDate,p)==0 ){
  20404. return 0;
  20405. }else if( parseHhMmSs(zDate, p)==0 ){
  20406. return 0;
  20407. }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
  20408. return setDateTimeToCurrent(context, p);
  20409. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  20410. setRawDateNumber(p, r);
  20411. return 0;
  20412. }
  20413. return 1;
  20414. }
  20415. /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
  20416. ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
  20417. ** for DateTime.iJD.
  20418. **
  20419. ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
  20420. ** such a large integer literal, so we have to encode it.
  20421. */
  20422. #define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
  20423. /*
  20424. ** Return TRUE if the given julian day number is within range.
  20425. **
  20426. ** The input is the JulianDay times 86400000.
  20427. */
  20428. static int validJulianDay(sqlite3_int64 iJD){
  20429. return iJD>=0 && iJD<=INT_464269060799999;
  20430. }
  20431. /*
  20432. ** Compute the Year, Month, and Day from the julian day number.
  20433. */
  20434. static void computeYMD(DateTime *p){
  20435. int Z, A, B, C, D, E, X1;
  20436. if( p->validYMD ) return;
  20437. if( !p->validJD ){
  20438. p->Y = 2000;
  20439. p->M = 1;
  20440. p->D = 1;
  20441. }else if( !validJulianDay(p->iJD) ){
  20442. datetimeError(p);
  20443. return;
  20444. }else{
  20445. Z = (int)((p->iJD + 43200000)/86400000);
  20446. A = (int)((Z - 1867216.25)/36524.25);
  20447. A = Z + 1 + A - (A/4);
  20448. B = A + 1524;
  20449. C = (int)((B - 122.1)/365.25);
  20450. D = (36525*(C&32767))/100;
  20451. E = (int)((B-D)/30.6001);
  20452. X1 = (int)(30.6001*E);
  20453. p->D = B - D - X1;
  20454. p->M = E<14 ? E-1 : E-13;
  20455. p->Y = p->M>2 ? C - 4716 : C - 4715;
  20456. }
  20457. p->validYMD = 1;
  20458. }
  20459. /*
  20460. ** Compute the Hour, Minute, and Seconds from the julian day number.
  20461. */
  20462. static void computeHMS(DateTime *p){
  20463. int s;
  20464. if( p->validHMS ) return;
  20465. computeJD(p);
  20466. s = (int)((p->iJD + 43200000) % 86400000);
  20467. p->s = s/1000.0;
  20468. s = (int)p->s;
  20469. p->s -= s;
  20470. p->h = s/3600;
  20471. s -= p->h*3600;
  20472. p->m = s/60;
  20473. p->s += s - p->m*60;
  20474. p->rawS = 0;
  20475. p->validHMS = 1;
  20476. }
  20477. /*
  20478. ** Compute both YMD and HMS
  20479. */
  20480. static void computeYMD_HMS(DateTime *p){
  20481. computeYMD(p);
  20482. computeHMS(p);
  20483. }
  20484. /*
  20485. ** Clear the YMD and HMS and the TZ
  20486. */
  20487. static void clearYMD_HMS_TZ(DateTime *p){
  20488. p->validYMD = 0;
  20489. p->validHMS = 0;
  20490. p->validTZ = 0;
  20491. }
  20492. #ifndef SQLITE_OMIT_LOCALTIME
  20493. /*
  20494. ** On recent Windows platforms, the localtime_s() function is available
  20495. ** as part of the "Secure CRT". It is essentially equivalent to
  20496. ** localtime_r() available under most POSIX platforms, except that the
  20497. ** order of the parameters is reversed.
  20498. **
  20499. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  20500. **
  20501. ** If the user has not indicated to use localtime_r() or localtime_s()
  20502. ** already, check for an MSVC build environment that provides
  20503. ** localtime_s().
  20504. */
  20505. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  20506. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  20507. #undef HAVE_LOCALTIME_S
  20508. #define HAVE_LOCALTIME_S 1
  20509. #endif
  20510. /*
  20511. ** The following routine implements the rough equivalent of localtime_r()
  20512. ** using whatever operating-system specific localtime facility that
  20513. ** is available. This routine returns 0 on success and
  20514. ** non-zero on any kind of error.
  20515. **
  20516. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  20517. ** routine will always fail.
  20518. **
  20519. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  20520. ** library function localtime_r() is used to assist in the calculation of
  20521. ** local time.
  20522. */
  20523. static int osLocaltime(time_t *t, struct tm *pTm){
  20524. int rc;
  20525. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  20526. struct tm *pX;
  20527. #if SQLITE_THREADSAFE>0
  20528. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  20529. #endif
  20530. sqlite3_mutex_enter(mutex);
  20531. pX = localtime(t);
  20532. #ifndef SQLITE_UNTESTABLE
  20533. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  20534. #endif
  20535. if( pX ) *pTm = *pX;
  20536. sqlite3_mutex_leave(mutex);
  20537. rc = pX==0;
  20538. #else
  20539. #ifndef SQLITE_UNTESTABLE
  20540. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  20541. #endif
  20542. #if HAVE_LOCALTIME_R
  20543. rc = localtime_r(t, pTm)==0;
  20544. #else
  20545. rc = localtime_s(pTm, t);
  20546. #endif /* HAVE_LOCALTIME_R */
  20547. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  20548. return rc;
  20549. }
  20550. #endif /* SQLITE_OMIT_LOCALTIME */
  20551. #ifndef SQLITE_OMIT_LOCALTIME
  20552. /*
  20553. ** Compute the difference (in milliseconds) between localtime and UTC
  20554. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  20555. ** return this value and set *pRc to SQLITE_OK.
  20556. **
  20557. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  20558. ** is undefined in this case.
  20559. */
  20560. static sqlite3_int64 localtimeOffset(
  20561. DateTime *p, /* Date at which to calculate offset */
  20562. sqlite3_context *pCtx, /* Write error here if one occurs */
  20563. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  20564. ){
  20565. DateTime x, y;
  20566. time_t t;
  20567. struct tm sLocal;
  20568. /* Initialize the contents of sLocal to avoid a compiler warning. */
  20569. memset(&sLocal, 0, sizeof(sLocal));
  20570. x = *p;
  20571. computeYMD_HMS(&x);
  20572. if( x.Y<1971 || x.Y>=2038 ){
  20573. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  20574. ** works for years between 1970 and 2037. For dates outside this range,
  20575. ** SQLite attempts to map the year into an equivalent year within this
  20576. ** range, do the calculation, then map the year back.
  20577. */
  20578. x.Y = 2000;
  20579. x.M = 1;
  20580. x.D = 1;
  20581. x.h = 0;
  20582. x.m = 0;
  20583. x.s = 0.0;
  20584. } else {
  20585. int s = (int)(x.s + 0.5);
  20586. x.s = s;
  20587. }
  20588. x.tz = 0;
  20589. x.validJD = 0;
  20590. computeJD(&x);
  20591. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  20592. if( osLocaltime(&t, &sLocal) ){
  20593. sqlite3_result_error(pCtx, "local time unavailable", -1);
  20594. *pRc = SQLITE_ERROR;
  20595. return 0;
  20596. }
  20597. y.Y = sLocal.tm_year + 1900;
  20598. y.M = sLocal.tm_mon + 1;
  20599. y.D = sLocal.tm_mday;
  20600. y.h = sLocal.tm_hour;
  20601. y.m = sLocal.tm_min;
  20602. y.s = sLocal.tm_sec;
  20603. y.validYMD = 1;
  20604. y.validHMS = 1;
  20605. y.validJD = 0;
  20606. y.rawS = 0;
  20607. y.validTZ = 0;
  20608. y.isError = 0;
  20609. computeJD(&y);
  20610. *pRc = SQLITE_OK;
  20611. return y.iJD - x.iJD;
  20612. }
  20613. #endif /* SQLITE_OMIT_LOCALTIME */
  20614. /*
  20615. ** The following table defines various date transformations of the form
  20616. **
  20617. ** 'NNN days'
  20618. **
  20619. ** Where NNN is an arbitrary floating-point number and "days" can be one
  20620. ** of several units of time.
  20621. */
  20622. static const struct {
  20623. u8 eType; /* Transformation type code */
  20624. u8 nName; /* Length of th name */
  20625. char *zName; /* Name of the transformation */
  20626. double rLimit; /* Maximum NNN value for this transform */
  20627. double rXform; /* Constant used for this transform */
  20628. } aXformType[] = {
  20629. { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
  20630. { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) },
  20631. { 0, 4, "hour", 128963628.0, 86400000.0/24.0 },
  20632. { 0, 3, "day", 5373485.0, 86400000.0 },
  20633. { 1, 5, "month", 176546.0, 30.0*86400000.0 },
  20634. { 2, 4, "year", 14713.0, 365.0*86400000.0 },
  20635. };
  20636. /*
  20637. ** Process a modifier to a date-time stamp. The modifiers are
  20638. ** as follows:
  20639. **
  20640. ** NNN days
  20641. ** NNN hours
  20642. ** NNN minutes
  20643. ** NNN.NNNN seconds
  20644. ** NNN months
  20645. ** NNN years
  20646. ** start of month
  20647. ** start of year
  20648. ** start of week
  20649. ** start of day
  20650. ** weekday N
  20651. ** unixepoch
  20652. ** localtime
  20653. ** utc
  20654. **
  20655. ** Return 0 on success and 1 if there is any kind of error. If the error
  20656. ** is in a system call (i.e. localtime()), then an error message is written
  20657. ** to context pCtx. If the error is an unrecognized modifier, no error is
  20658. ** written to pCtx.
  20659. */
  20660. static int parseModifier(
  20661. sqlite3_context *pCtx, /* Function context */
  20662. const char *z, /* The text of the modifier */
  20663. int n, /* Length of zMod in bytes */
  20664. DateTime *p /* The date/time value to be modified */
  20665. ){
  20666. int rc = 1;
  20667. double r;
  20668. switch(sqlite3UpperToLower[(u8)z[0]] ){
  20669. #ifndef SQLITE_OMIT_LOCALTIME
  20670. case 'l': {
  20671. /* localtime
  20672. **
  20673. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  20674. ** show local time.
  20675. */
  20676. if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
  20677. computeJD(p);
  20678. p->iJD += localtimeOffset(p, pCtx, &rc);
  20679. clearYMD_HMS_TZ(p);
  20680. }
  20681. break;
  20682. }
  20683. #endif
  20684. case 'u': {
  20685. /*
  20686. ** unixepoch
  20687. **
  20688. ** Treat the current value of p->s as the number of
  20689. ** seconds since 1970. Convert to a real julian day number.
  20690. */
  20691. if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
  20692. r = p->s*1000.0 + 210866760000000.0;
  20693. if( r>=0.0 && r<464269060800000.0 ){
  20694. clearYMD_HMS_TZ(p);
  20695. p->iJD = (sqlite3_int64)r;
  20696. p->validJD = 1;
  20697. p->rawS = 0;
  20698. rc = 0;
  20699. }
  20700. }
  20701. #ifndef SQLITE_OMIT_LOCALTIME
  20702. else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
  20703. if( p->tzSet==0 ){
  20704. sqlite3_int64 c1;
  20705. computeJD(p);
  20706. c1 = localtimeOffset(p, pCtx, &rc);
  20707. if( rc==SQLITE_OK ){
  20708. p->iJD -= c1;
  20709. clearYMD_HMS_TZ(p);
  20710. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  20711. }
  20712. p->tzSet = 1;
  20713. }else{
  20714. rc = SQLITE_OK;
  20715. }
  20716. }
  20717. #endif
  20718. break;
  20719. }
  20720. case 'w': {
  20721. /*
  20722. ** weekday N
  20723. **
  20724. ** Move the date to the same time on the next occurrence of
  20725. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  20726. ** date is already on the appropriate weekday, this is a no-op.
  20727. */
  20728. if( sqlite3_strnicmp(z, "weekday ", 8)==0
  20729. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  20730. && (n=(int)r)==r && n>=0 && r<7 ){
  20731. sqlite3_int64 Z;
  20732. computeYMD_HMS(p);
  20733. p->validTZ = 0;
  20734. p->validJD = 0;
  20735. computeJD(p);
  20736. Z = ((p->iJD + 129600000)/86400000) % 7;
  20737. if( Z>n ) Z -= 7;
  20738. p->iJD += (n - Z)*86400000;
  20739. clearYMD_HMS_TZ(p);
  20740. rc = 0;
  20741. }
  20742. break;
  20743. }
  20744. case 's': {
  20745. /*
  20746. ** start of TTTTT
  20747. **
  20748. ** Move the date backwards to the beginning of the current day,
  20749. ** or month or year.
  20750. */
  20751. if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
  20752. if( !p->validJD && !p->validYMD && !p->validHMS ) break;
  20753. z += 9;
  20754. computeYMD(p);
  20755. p->validHMS = 1;
  20756. p->h = p->m = 0;
  20757. p->s = 0.0;
  20758. p->rawS = 0;
  20759. p->validTZ = 0;
  20760. p->validJD = 0;
  20761. if( sqlite3_stricmp(z,"month")==0 ){
  20762. p->D = 1;
  20763. rc = 0;
  20764. }else if( sqlite3_stricmp(z,"year")==0 ){
  20765. p->M = 1;
  20766. p->D = 1;
  20767. rc = 0;
  20768. }else if( sqlite3_stricmp(z,"day")==0 ){
  20769. rc = 0;
  20770. }
  20771. break;
  20772. }
  20773. case '+':
  20774. case '-':
  20775. case '0':
  20776. case '1':
  20777. case '2':
  20778. case '3':
  20779. case '4':
  20780. case '5':
  20781. case '6':
  20782. case '7':
  20783. case '8':
  20784. case '9': {
  20785. double rRounder;
  20786. int i;
  20787. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  20788. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  20789. rc = 1;
  20790. break;
  20791. }
  20792. if( z[n]==':' ){
  20793. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  20794. ** specified number of hours, minutes, seconds, and fractional seconds
  20795. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  20796. ** omitted.
  20797. */
  20798. const char *z2 = z;
  20799. DateTime tx;
  20800. sqlite3_int64 day;
  20801. if( !sqlite3Isdigit(*z2) ) z2++;
  20802. memset(&tx, 0, sizeof(tx));
  20803. if( parseHhMmSs(z2, &tx) ) break;
  20804. computeJD(&tx);
  20805. tx.iJD -= 43200000;
  20806. day = tx.iJD/86400000;
  20807. tx.iJD -= day*86400000;
  20808. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  20809. computeJD(p);
  20810. clearYMD_HMS_TZ(p);
  20811. p->iJD += tx.iJD;
  20812. rc = 0;
  20813. break;
  20814. }
  20815. /* If control reaches this point, it means the transformation is
  20816. ** one of the forms like "+NNN days". */
  20817. z += n;
  20818. while( sqlite3Isspace(*z) ) z++;
  20819. n = sqlite3Strlen30(z);
  20820. if( n>10 || n<3 ) break;
  20821. if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
  20822. computeJD(p);
  20823. rc = 1;
  20824. rRounder = r<0 ? -0.5 : +0.5;
  20825. for(i=0; i<ArraySize(aXformType); i++){
  20826. if( aXformType[i].nName==n
  20827. && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
  20828. && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
  20829. ){
  20830. switch( aXformType[i].eType ){
  20831. case 1: { /* Special processing to add months */
  20832. int x;
  20833. computeYMD_HMS(p);
  20834. p->M += (int)r;
  20835. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  20836. p->Y += x;
  20837. p->M -= x*12;
  20838. p->validJD = 0;
  20839. r -= (int)r;
  20840. break;
  20841. }
  20842. case 2: { /* Special processing to add years */
  20843. int y = (int)r;
  20844. computeYMD_HMS(p);
  20845. p->Y += y;
  20846. p->validJD = 0;
  20847. r -= (int)r;
  20848. break;
  20849. }
  20850. }
  20851. computeJD(p);
  20852. p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
  20853. rc = 0;
  20854. break;
  20855. }
  20856. }
  20857. clearYMD_HMS_TZ(p);
  20858. break;
  20859. }
  20860. default: {
  20861. break;
  20862. }
  20863. }
  20864. return rc;
  20865. }
  20866. /*
  20867. ** Process time function arguments. argv[0] is a date-time stamp.
  20868. ** argv[1] and following are modifiers. Parse them all and write
  20869. ** the resulting time into the DateTime structure p. Return 0
  20870. ** on success and 1 if there are any errors.
  20871. **
  20872. ** If there are zero parameters (if even argv[0] is undefined)
  20873. ** then assume a default value of "now" for argv[0].
  20874. */
  20875. static int isDate(
  20876. sqlite3_context *context,
  20877. int argc,
  20878. sqlite3_value **argv,
  20879. DateTime *p
  20880. ){
  20881. int i, n;
  20882. const unsigned char *z;
  20883. int eType;
  20884. memset(p, 0, sizeof(*p));
  20885. if( argc==0 ){
  20886. return setDateTimeToCurrent(context, p);
  20887. }
  20888. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  20889. || eType==SQLITE_INTEGER ){
  20890. setRawDateNumber(p, sqlite3_value_double(argv[0]));
  20891. }else{
  20892. z = sqlite3_value_text(argv[0]);
  20893. if( !z || parseDateOrTime(context, (char*)z, p) ){
  20894. return 1;
  20895. }
  20896. }
  20897. for(i=1; i<argc; i++){
  20898. z = sqlite3_value_text(argv[i]);
  20899. n = sqlite3_value_bytes(argv[i]);
  20900. if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
  20901. }
  20902. computeJD(p);
  20903. if( p->isError || !validJulianDay(p->iJD) ) return 1;
  20904. return 0;
  20905. }
  20906. /*
  20907. ** The following routines implement the various date and time functions
  20908. ** of SQLite.
  20909. */
  20910. /*
  20911. ** julianday( TIMESTRING, MOD, MOD, ...)
  20912. **
  20913. ** Return the julian day number of the date specified in the arguments
  20914. */
  20915. static void juliandayFunc(
  20916. sqlite3_context *context,
  20917. int argc,
  20918. sqlite3_value **argv
  20919. ){
  20920. DateTime x;
  20921. if( isDate(context, argc, argv, &x)==0 ){
  20922. computeJD(&x);
  20923. sqlite3_result_double(context, x.iJD/86400000.0);
  20924. }
  20925. }
  20926. /*
  20927. ** datetime( TIMESTRING, MOD, MOD, ...)
  20928. **
  20929. ** Return YYYY-MM-DD HH:MM:SS
  20930. */
  20931. static void datetimeFunc(
  20932. sqlite3_context *context,
  20933. int argc,
  20934. sqlite3_value **argv
  20935. ){
  20936. DateTime x;
  20937. if( isDate(context, argc, argv, &x)==0 ){
  20938. char zBuf[100];
  20939. computeYMD_HMS(&x);
  20940. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  20941. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  20942. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20943. }
  20944. }
  20945. /*
  20946. ** time( TIMESTRING, MOD, MOD, ...)
  20947. **
  20948. ** Return HH:MM:SS
  20949. */
  20950. static void timeFunc(
  20951. sqlite3_context *context,
  20952. int argc,
  20953. sqlite3_value **argv
  20954. ){
  20955. DateTime x;
  20956. if( isDate(context, argc, argv, &x)==0 ){
  20957. char zBuf[100];
  20958. computeHMS(&x);
  20959. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  20960. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20961. }
  20962. }
  20963. /*
  20964. ** date( TIMESTRING, MOD, MOD, ...)
  20965. **
  20966. ** Return YYYY-MM-DD
  20967. */
  20968. static void dateFunc(
  20969. sqlite3_context *context,
  20970. int argc,
  20971. sqlite3_value **argv
  20972. ){
  20973. DateTime x;
  20974. if( isDate(context, argc, argv, &x)==0 ){
  20975. char zBuf[100];
  20976. computeYMD(&x);
  20977. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  20978. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20979. }
  20980. }
  20981. /*
  20982. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  20983. **
  20984. ** Return a string described by FORMAT. Conversions as follows:
  20985. **
  20986. ** %d day of month
  20987. ** %f ** fractional seconds SS.SSS
  20988. ** %H hour 00-24
  20989. ** %j day of year 000-366
  20990. ** %J ** julian day number
  20991. ** %m month 01-12
  20992. ** %M minute 00-59
  20993. ** %s seconds since 1970-01-01
  20994. ** %S seconds 00-59
  20995. ** %w day of week 0-6 sunday==0
  20996. ** %W week of year 00-53
  20997. ** %Y year 0000-9999
  20998. ** %% %
  20999. */
  21000. static void strftimeFunc(
  21001. sqlite3_context *context,
  21002. int argc,
  21003. sqlite3_value **argv
  21004. ){
  21005. DateTime x;
  21006. u64 n;
  21007. size_t i,j;
  21008. char *z;
  21009. sqlite3 *db;
  21010. const char *zFmt;
  21011. char zBuf[100];
  21012. if( argc==0 ) return;
  21013. zFmt = (const char*)sqlite3_value_text(argv[0]);
  21014. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  21015. db = sqlite3_context_db_handle(context);
  21016. for(i=0, n=1; zFmt[i]; i++, n++){
  21017. if( zFmt[i]=='%' ){
  21018. switch( zFmt[i+1] ){
  21019. case 'd':
  21020. case 'H':
  21021. case 'm':
  21022. case 'M':
  21023. case 'S':
  21024. case 'W':
  21025. n++;
  21026. /* fall thru */
  21027. case 'w':
  21028. case '%':
  21029. break;
  21030. case 'f':
  21031. n += 8;
  21032. break;
  21033. case 'j':
  21034. n += 3;
  21035. break;
  21036. case 'Y':
  21037. n += 8;
  21038. break;
  21039. case 's':
  21040. case 'J':
  21041. n += 50;
  21042. break;
  21043. default:
  21044. return; /* ERROR. return a NULL */
  21045. }
  21046. i++;
  21047. }
  21048. }
  21049. testcase( n==sizeof(zBuf)-1 );
  21050. testcase( n==sizeof(zBuf) );
  21051. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  21052. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  21053. if( n<sizeof(zBuf) ){
  21054. z = zBuf;
  21055. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  21056. sqlite3_result_error_toobig(context);
  21057. return;
  21058. }else{
  21059. z = sqlite3DbMallocRawNN(db, (int)n);
  21060. if( z==0 ){
  21061. sqlite3_result_error_nomem(context);
  21062. return;
  21063. }
  21064. }
  21065. computeJD(&x);
  21066. computeYMD_HMS(&x);
  21067. for(i=j=0; zFmt[i]; i++){
  21068. if( zFmt[i]!='%' ){
  21069. z[j++] = zFmt[i];
  21070. }else{
  21071. i++;
  21072. switch( zFmt[i] ){
  21073. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  21074. case 'f': {
  21075. double s = x.s;
  21076. if( s>59.999 ) s = 59.999;
  21077. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  21078. j += sqlite3Strlen30(&z[j]);
  21079. break;
  21080. }
  21081. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  21082. case 'W': /* Fall thru */
  21083. case 'j': {
  21084. int nDay; /* Number of days since 1st day of year */
  21085. DateTime y = x;
  21086. y.validJD = 0;
  21087. y.M = 1;
  21088. y.D = 1;
  21089. computeJD(&y);
  21090. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  21091. if( zFmt[i]=='W' ){
  21092. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  21093. wd = (int)(((x.iJD+43200000)/86400000)%7);
  21094. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  21095. j += 2;
  21096. }else{
  21097. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  21098. j += 3;
  21099. }
  21100. break;
  21101. }
  21102. case 'J': {
  21103. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  21104. j+=sqlite3Strlen30(&z[j]);
  21105. break;
  21106. }
  21107. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  21108. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  21109. case 's': {
  21110. sqlite3_snprintf(30,&z[j],"%lld",
  21111. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  21112. j += sqlite3Strlen30(&z[j]);
  21113. break;
  21114. }
  21115. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  21116. case 'w': {
  21117. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  21118. break;
  21119. }
  21120. case 'Y': {
  21121. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  21122. break;
  21123. }
  21124. default: z[j++] = '%'; break;
  21125. }
  21126. }
  21127. }
  21128. z[j] = 0;
  21129. sqlite3_result_text(context, z, -1,
  21130. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  21131. }
  21132. /*
  21133. ** current_time()
  21134. **
  21135. ** This function returns the same value as time('now').
  21136. */
  21137. static void ctimeFunc(
  21138. sqlite3_context *context,
  21139. int NotUsed,
  21140. sqlite3_value **NotUsed2
  21141. ){
  21142. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21143. timeFunc(context, 0, 0);
  21144. }
  21145. /*
  21146. ** current_date()
  21147. **
  21148. ** This function returns the same value as date('now').
  21149. */
  21150. static void cdateFunc(
  21151. sqlite3_context *context,
  21152. int NotUsed,
  21153. sqlite3_value **NotUsed2
  21154. ){
  21155. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21156. dateFunc(context, 0, 0);
  21157. }
  21158. /*
  21159. ** current_timestamp()
  21160. **
  21161. ** This function returns the same value as datetime('now').
  21162. */
  21163. static void ctimestampFunc(
  21164. sqlite3_context *context,
  21165. int NotUsed,
  21166. sqlite3_value **NotUsed2
  21167. ){
  21168. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21169. datetimeFunc(context, 0, 0);
  21170. }
  21171. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  21172. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  21173. /*
  21174. ** If the library is compiled to omit the full-scale date and time
  21175. ** handling (to get a smaller binary), the following minimal version
  21176. ** of the functions current_time(), current_date() and current_timestamp()
  21177. ** are included instead. This is to support column declarations that
  21178. ** include "DEFAULT CURRENT_TIME" etc.
  21179. **
  21180. ** This function uses the C-library functions time(), gmtime()
  21181. ** and strftime(). The format string to pass to strftime() is supplied
  21182. ** as the user-data for the function.
  21183. */
  21184. static void currentTimeFunc(
  21185. sqlite3_context *context,
  21186. int argc,
  21187. sqlite3_value **argv
  21188. ){
  21189. time_t t;
  21190. char *zFormat = (char *)sqlite3_user_data(context);
  21191. sqlite3_int64 iT;
  21192. struct tm *pTm;
  21193. struct tm sNow;
  21194. char zBuf[20];
  21195. UNUSED_PARAMETER(argc);
  21196. UNUSED_PARAMETER(argv);
  21197. iT = sqlite3StmtCurrentTime(context);
  21198. if( iT<=0 ) return;
  21199. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  21200. #if HAVE_GMTIME_R
  21201. pTm = gmtime_r(&t, &sNow);
  21202. #else
  21203. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  21204. pTm = gmtime(&t);
  21205. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  21206. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  21207. #endif
  21208. if( pTm ){
  21209. strftime(zBuf, 20, zFormat, &sNow);
  21210. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  21211. }
  21212. }
  21213. #endif
  21214. /*
  21215. ** This function registered all of the above C functions as SQL
  21216. ** functions. This should be the only routine in this file with
  21217. ** external linkage.
  21218. */
  21219. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  21220. static FuncDef aDateTimeFuncs[] = {
  21221. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  21222. PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
  21223. PURE_DATE(date, -1, 0, 0, dateFunc ),
  21224. PURE_DATE(time, -1, 0, 0, timeFunc ),
  21225. PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
  21226. PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
  21227. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  21228. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  21229. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  21230. #else
  21231. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  21232. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  21233. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  21234. #endif
  21235. };
  21236. sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
  21237. }
  21238. /************** End of date.c ************************************************/
  21239. /************** Begin file os.c **********************************************/
  21240. /*
  21241. ** 2005 November 29
  21242. **
  21243. ** The author disclaims copyright to this source code. In place of
  21244. ** a legal notice, here is a blessing:
  21245. **
  21246. ** May you do good and not evil.
  21247. ** May you find forgiveness for yourself and forgive others.
  21248. ** May you share freely, never taking more than you give.
  21249. **
  21250. ******************************************************************************
  21251. **
  21252. ** This file contains OS interface code that is common to all
  21253. ** architectures.
  21254. */
  21255. /* #include "sqliteInt.h" */
  21256. /*
  21257. ** If we compile with the SQLITE_TEST macro set, then the following block
  21258. ** of code will give us the ability to simulate a disk I/O error. This
  21259. ** is used for testing the I/O recovery logic.
  21260. */
  21261. #if defined(SQLITE_TEST)
  21262. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  21263. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  21264. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  21265. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  21266. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  21267. SQLITE_API int sqlite3_diskfull_pending = 0;
  21268. SQLITE_API int sqlite3_diskfull = 0;
  21269. #endif /* defined(SQLITE_TEST) */
  21270. /*
  21271. ** When testing, also keep a count of the number of open files.
  21272. */
  21273. #if defined(SQLITE_TEST)
  21274. SQLITE_API int sqlite3_open_file_count = 0;
  21275. #endif /* defined(SQLITE_TEST) */
  21276. /*
  21277. ** The default SQLite sqlite3_vfs implementations do not allocate
  21278. ** memory (actually, os_unix.c allocates a small amount of memory
  21279. ** from within OsOpen()), but some third-party implementations may.
  21280. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  21281. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  21282. **
  21283. ** The following functions are instrumented for malloc() failure
  21284. ** testing:
  21285. **
  21286. ** sqlite3OsRead()
  21287. ** sqlite3OsWrite()
  21288. ** sqlite3OsSync()
  21289. ** sqlite3OsFileSize()
  21290. ** sqlite3OsLock()
  21291. ** sqlite3OsCheckReservedLock()
  21292. ** sqlite3OsFileControl()
  21293. ** sqlite3OsShmMap()
  21294. ** sqlite3OsOpen()
  21295. ** sqlite3OsDelete()
  21296. ** sqlite3OsAccess()
  21297. ** sqlite3OsFullPathname()
  21298. **
  21299. */
  21300. #if defined(SQLITE_TEST)
  21301. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  21302. #define DO_OS_MALLOC_TEST(x) \
  21303. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
  21304. void *pTstAlloc = sqlite3Malloc(10); \
  21305. if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
  21306. sqlite3_free(pTstAlloc); \
  21307. }
  21308. #else
  21309. #define DO_OS_MALLOC_TEST(x)
  21310. #endif
  21311. /*
  21312. ** The following routines are convenience wrappers around methods
  21313. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  21314. ** of this would be completely automatic if SQLite were coded using
  21315. ** C++ instead of plain old C.
  21316. */
  21317. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
  21318. if( pId->pMethods ){
  21319. pId->pMethods->xClose(pId);
  21320. pId->pMethods = 0;
  21321. }
  21322. }
  21323. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  21324. DO_OS_MALLOC_TEST(id);
  21325. return id->pMethods->xRead(id, pBuf, amt, offset);
  21326. }
  21327. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  21328. DO_OS_MALLOC_TEST(id);
  21329. return id->pMethods->xWrite(id, pBuf, amt, offset);
  21330. }
  21331. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  21332. return id->pMethods->xTruncate(id, size);
  21333. }
  21334. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  21335. DO_OS_MALLOC_TEST(id);
  21336. return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
  21337. }
  21338. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  21339. DO_OS_MALLOC_TEST(id);
  21340. return id->pMethods->xFileSize(id, pSize);
  21341. }
  21342. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  21343. DO_OS_MALLOC_TEST(id);
  21344. return id->pMethods->xLock(id, lockType);
  21345. }
  21346. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  21347. return id->pMethods->xUnlock(id, lockType);
  21348. }
  21349. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  21350. DO_OS_MALLOC_TEST(id);
  21351. return id->pMethods->xCheckReservedLock(id, pResOut);
  21352. }
  21353. /*
  21354. ** Use sqlite3OsFileControl() when we are doing something that might fail
  21355. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  21356. ** when simply tossing information over the wall to the VFS and we do not
  21357. ** really care if the VFS receives and understands the information since it
  21358. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  21359. ** routine has no return value since the return value would be meaningless.
  21360. */
  21361. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  21362. if( id->pMethods==0 ) return SQLITE_NOTFOUND;
  21363. #ifdef SQLITE_TEST
  21364. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
  21365. && op!=SQLITE_FCNTL_LOCK_TIMEOUT
  21366. ){
  21367. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  21368. ** is using a regular VFS, it is called after the corresponding
  21369. ** transaction has been committed. Injecting a fault at this point
  21370. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  21371. ** but the transaction is committed anyway.
  21372. **
  21373. ** The core must call OsFileControl() though, not OsFileControlHint(),
  21374. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  21375. ** means the commit really has failed and an error should be returned
  21376. ** to the user. */
  21377. DO_OS_MALLOC_TEST(id);
  21378. }
  21379. #endif
  21380. return id->pMethods->xFileControl(id, op, pArg);
  21381. }
  21382. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  21383. if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
  21384. }
  21385. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  21386. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  21387. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  21388. }
  21389. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  21390. return id->pMethods->xDeviceCharacteristics(id);
  21391. }
  21392. #ifndef SQLITE_OMIT_WAL
  21393. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  21394. return id->pMethods->xShmLock(id, offset, n, flags);
  21395. }
  21396. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  21397. id->pMethods->xShmBarrier(id);
  21398. }
  21399. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  21400. return id->pMethods->xShmUnmap(id, deleteFlag);
  21401. }
  21402. SQLITE_PRIVATE int sqlite3OsShmMap(
  21403. sqlite3_file *id, /* Database file handle */
  21404. int iPage,
  21405. int pgsz,
  21406. int bExtend, /* True to extend file if necessary */
  21407. void volatile **pp /* OUT: Pointer to mapping */
  21408. ){
  21409. DO_OS_MALLOC_TEST(id);
  21410. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  21411. }
  21412. #endif /* SQLITE_OMIT_WAL */
  21413. #if SQLITE_MAX_MMAP_SIZE>0
  21414. /* The real implementation of xFetch and xUnfetch */
  21415. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  21416. DO_OS_MALLOC_TEST(id);
  21417. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  21418. }
  21419. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  21420. return id->pMethods->xUnfetch(id, iOff, p);
  21421. }
  21422. #else
  21423. /* No-op stubs to use when memory-mapped I/O is disabled */
  21424. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  21425. *pp = 0;
  21426. return SQLITE_OK;
  21427. }
  21428. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  21429. return SQLITE_OK;
  21430. }
  21431. #endif
  21432. /*
  21433. ** The next group of routines are convenience wrappers around the
  21434. ** VFS methods.
  21435. */
  21436. SQLITE_PRIVATE int sqlite3OsOpen(
  21437. sqlite3_vfs *pVfs,
  21438. const char *zPath,
  21439. sqlite3_file *pFile,
  21440. int flags,
  21441. int *pFlagsOut
  21442. ){
  21443. int rc;
  21444. DO_OS_MALLOC_TEST(0);
  21445. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  21446. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  21447. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  21448. ** reaching the VFS. */
  21449. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  21450. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  21451. return rc;
  21452. }
  21453. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  21454. DO_OS_MALLOC_TEST(0);
  21455. assert( dirSync==0 || dirSync==1 );
  21456. return pVfs->xDelete(pVfs, zPath, dirSync);
  21457. }
  21458. SQLITE_PRIVATE int sqlite3OsAccess(
  21459. sqlite3_vfs *pVfs,
  21460. const char *zPath,
  21461. int flags,
  21462. int *pResOut
  21463. ){
  21464. DO_OS_MALLOC_TEST(0);
  21465. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  21466. }
  21467. SQLITE_PRIVATE int sqlite3OsFullPathname(
  21468. sqlite3_vfs *pVfs,
  21469. const char *zPath,
  21470. int nPathOut,
  21471. char *zPathOut
  21472. ){
  21473. DO_OS_MALLOC_TEST(0);
  21474. zPathOut[0] = 0;
  21475. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  21476. }
  21477. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  21478. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  21479. return pVfs->xDlOpen(pVfs, zPath);
  21480. }
  21481. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  21482. pVfs->xDlError(pVfs, nByte, zBufOut);
  21483. }
  21484. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  21485. return pVfs->xDlSym(pVfs, pHdle, zSym);
  21486. }
  21487. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  21488. pVfs->xDlClose(pVfs, pHandle);
  21489. }
  21490. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  21491. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  21492. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  21493. }
  21494. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  21495. return pVfs->xSleep(pVfs, nMicro);
  21496. }
  21497. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
  21498. return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
  21499. }
  21500. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  21501. int rc;
  21502. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  21503. ** method to get the current date and time if that method is available
  21504. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  21505. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  21506. ** unavailable.
  21507. */
  21508. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  21509. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  21510. }else{
  21511. double r;
  21512. rc = pVfs->xCurrentTime(pVfs, &r);
  21513. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  21514. }
  21515. return rc;
  21516. }
  21517. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  21518. sqlite3_vfs *pVfs,
  21519. const char *zFile,
  21520. sqlite3_file **ppFile,
  21521. int flags,
  21522. int *pOutFlags
  21523. ){
  21524. int rc;
  21525. sqlite3_file *pFile;
  21526. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  21527. if( pFile ){
  21528. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  21529. if( rc!=SQLITE_OK ){
  21530. sqlite3_free(pFile);
  21531. }else{
  21532. *ppFile = pFile;
  21533. }
  21534. }else{
  21535. rc = SQLITE_NOMEM_BKPT;
  21536. }
  21537. return rc;
  21538. }
  21539. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
  21540. assert( pFile );
  21541. sqlite3OsClose(pFile);
  21542. sqlite3_free(pFile);
  21543. }
  21544. /*
  21545. ** This function is a wrapper around the OS specific implementation of
  21546. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  21547. ** ability to simulate a malloc failure, so that the handling of an
  21548. ** error in sqlite3_os_init() by the upper layers can be tested.
  21549. */
  21550. SQLITE_PRIVATE int sqlite3OsInit(void){
  21551. void *p = sqlite3_malloc(10);
  21552. if( p==0 ) return SQLITE_NOMEM_BKPT;
  21553. sqlite3_free(p);
  21554. return sqlite3_os_init();
  21555. }
  21556. /*
  21557. ** The list of all registered VFS implementations.
  21558. */
  21559. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  21560. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  21561. /*
  21562. ** Locate a VFS by name. If no name is given, simply return the
  21563. ** first VFS on the list.
  21564. */
  21565. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  21566. sqlite3_vfs *pVfs = 0;
  21567. #if SQLITE_THREADSAFE
  21568. sqlite3_mutex *mutex;
  21569. #endif
  21570. #ifndef SQLITE_OMIT_AUTOINIT
  21571. int rc = sqlite3_initialize();
  21572. if( rc ) return 0;
  21573. #endif
  21574. #if SQLITE_THREADSAFE
  21575. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  21576. #endif
  21577. sqlite3_mutex_enter(mutex);
  21578. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  21579. if( zVfs==0 ) break;
  21580. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  21581. }
  21582. sqlite3_mutex_leave(mutex);
  21583. return pVfs;
  21584. }
  21585. /*
  21586. ** Unlink a VFS from the linked list
  21587. */
  21588. static void vfsUnlink(sqlite3_vfs *pVfs){
  21589. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  21590. if( pVfs==0 ){
  21591. /* No-op */
  21592. }else if( vfsList==pVfs ){
  21593. vfsList = pVfs->pNext;
  21594. }else if( vfsList ){
  21595. sqlite3_vfs *p = vfsList;
  21596. while( p->pNext && p->pNext!=pVfs ){
  21597. p = p->pNext;
  21598. }
  21599. if( p->pNext==pVfs ){
  21600. p->pNext = pVfs->pNext;
  21601. }
  21602. }
  21603. }
  21604. /*
  21605. ** Register a VFS with the system. It is harmless to register the same
  21606. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  21607. ** true.
  21608. */
  21609. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  21610. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  21611. #ifndef SQLITE_OMIT_AUTOINIT
  21612. int rc = sqlite3_initialize();
  21613. if( rc ) return rc;
  21614. #endif
  21615. #ifdef SQLITE_ENABLE_API_ARMOR
  21616. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  21617. #endif
  21618. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  21619. sqlite3_mutex_enter(mutex);
  21620. vfsUnlink(pVfs);
  21621. if( makeDflt || vfsList==0 ){
  21622. pVfs->pNext = vfsList;
  21623. vfsList = pVfs;
  21624. }else{
  21625. pVfs->pNext = vfsList->pNext;
  21626. vfsList->pNext = pVfs;
  21627. }
  21628. assert(vfsList);
  21629. sqlite3_mutex_leave(mutex);
  21630. return SQLITE_OK;
  21631. }
  21632. /*
  21633. ** Unregister a VFS so that it is no longer accessible.
  21634. */
  21635. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  21636. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  21637. #ifndef SQLITE_OMIT_AUTOINIT
  21638. int rc = sqlite3_initialize();
  21639. if( rc ) return rc;
  21640. #endif
  21641. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  21642. sqlite3_mutex_enter(mutex);
  21643. vfsUnlink(pVfs);
  21644. sqlite3_mutex_leave(mutex);
  21645. return SQLITE_OK;
  21646. }
  21647. /************** End of os.c **************************************************/
  21648. /************** Begin file fault.c *******************************************/
  21649. /*
  21650. ** 2008 Jan 22
  21651. **
  21652. ** The author disclaims copyright to this source code. In place of
  21653. ** a legal notice, here is a blessing:
  21654. **
  21655. ** May you do good and not evil.
  21656. ** May you find forgiveness for yourself and forgive others.
  21657. ** May you share freely, never taking more than you give.
  21658. **
  21659. *************************************************************************
  21660. **
  21661. ** This file contains code to support the concept of "benign"
  21662. ** malloc failures (when the xMalloc() or xRealloc() method of the
  21663. ** sqlite3_mem_methods structure fails to allocate a block of memory
  21664. ** and returns 0).
  21665. **
  21666. ** Most malloc failures are non-benign. After they occur, SQLite
  21667. ** abandons the current operation and returns an error code (usually
  21668. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  21669. ** fatal. For example, if a malloc fails while resizing a hash table, this
  21670. ** is completely recoverable simply by not carrying out the resize. The
  21671. ** hash table will continue to function normally. So a malloc failure
  21672. ** during a hash table resize is a benign fault.
  21673. */
  21674. /* #include "sqliteInt.h" */
  21675. #ifndef SQLITE_UNTESTABLE
  21676. /*
  21677. ** Global variables.
  21678. */
  21679. typedef struct BenignMallocHooks BenignMallocHooks;
  21680. static SQLITE_WSD struct BenignMallocHooks {
  21681. void (*xBenignBegin)(void);
  21682. void (*xBenignEnd)(void);
  21683. } sqlite3Hooks = { 0, 0 };
  21684. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  21685. ** structure. If writable static data is unsupported on the target,
  21686. ** we have to locate the state vector at run-time. In the more common
  21687. ** case where writable static data is supported, wsdHooks can refer directly
  21688. ** to the "sqlite3Hooks" state vector declared above.
  21689. */
  21690. #ifdef SQLITE_OMIT_WSD
  21691. # define wsdHooksInit \
  21692. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  21693. # define wsdHooks x[0]
  21694. #else
  21695. # define wsdHooksInit
  21696. # define wsdHooks sqlite3Hooks
  21697. #endif
  21698. /*
  21699. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  21700. ** sqlite3EndBenignMalloc() are called, respectively.
  21701. */
  21702. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  21703. void (*xBenignBegin)(void),
  21704. void (*xBenignEnd)(void)
  21705. ){
  21706. wsdHooksInit;
  21707. wsdHooks.xBenignBegin = xBenignBegin;
  21708. wsdHooks.xBenignEnd = xBenignEnd;
  21709. }
  21710. /*
  21711. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  21712. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  21713. ** indicates that subsequent malloc failures are non-benign.
  21714. */
  21715. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  21716. wsdHooksInit;
  21717. if( wsdHooks.xBenignBegin ){
  21718. wsdHooks.xBenignBegin();
  21719. }
  21720. }
  21721. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  21722. wsdHooksInit;
  21723. if( wsdHooks.xBenignEnd ){
  21724. wsdHooks.xBenignEnd();
  21725. }
  21726. }
  21727. #endif /* #ifndef SQLITE_UNTESTABLE */
  21728. /************** End of fault.c ***********************************************/
  21729. /************** Begin file mem0.c ********************************************/
  21730. /*
  21731. ** 2008 October 28
  21732. **
  21733. ** The author disclaims copyright to this source code. In place of
  21734. ** a legal notice, here is a blessing:
  21735. **
  21736. ** May you do good and not evil.
  21737. ** May you find forgiveness for yourself and forgive others.
  21738. ** May you share freely, never taking more than you give.
  21739. **
  21740. *************************************************************************
  21741. **
  21742. ** This file contains a no-op memory allocation drivers for use when
  21743. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  21744. ** here always fail. SQLite will not operate with these drivers. These
  21745. ** are merely placeholders. Real drivers must be substituted using
  21746. ** sqlite3_config() before SQLite will operate.
  21747. */
  21748. /* #include "sqliteInt.h" */
  21749. /*
  21750. ** This version of the memory allocator is the default. It is
  21751. ** used when no other memory allocator is specified using compile-time
  21752. ** macros.
  21753. */
  21754. #ifdef SQLITE_ZERO_MALLOC
  21755. /*
  21756. ** No-op versions of all memory allocation routines
  21757. */
  21758. static void *sqlite3MemMalloc(int nByte){ return 0; }
  21759. static void sqlite3MemFree(void *pPrior){ return; }
  21760. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  21761. static int sqlite3MemSize(void *pPrior){ return 0; }
  21762. static int sqlite3MemRoundup(int n){ return n; }
  21763. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  21764. static void sqlite3MemShutdown(void *NotUsed){ return; }
  21765. /*
  21766. ** This routine is the only routine in this file with external linkage.
  21767. **
  21768. ** Populate the low-level memory allocation function pointers in
  21769. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  21770. */
  21771. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  21772. static const sqlite3_mem_methods defaultMethods = {
  21773. sqlite3MemMalloc,
  21774. sqlite3MemFree,
  21775. sqlite3MemRealloc,
  21776. sqlite3MemSize,
  21777. sqlite3MemRoundup,
  21778. sqlite3MemInit,
  21779. sqlite3MemShutdown,
  21780. 0
  21781. };
  21782. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  21783. }
  21784. #endif /* SQLITE_ZERO_MALLOC */
  21785. /************** End of mem0.c ************************************************/
  21786. /************** Begin file mem1.c ********************************************/
  21787. /*
  21788. ** 2007 August 14
  21789. **
  21790. ** The author disclaims copyright to this source code. In place of
  21791. ** a legal notice, here is a blessing:
  21792. **
  21793. ** May you do good and not evil.
  21794. ** May you find forgiveness for yourself and forgive others.
  21795. ** May you share freely, never taking more than you give.
  21796. **
  21797. *************************************************************************
  21798. **
  21799. ** This file contains low-level memory allocation drivers for when
  21800. ** SQLite will use the standard C-library malloc/realloc/free interface
  21801. ** to obtain the memory it needs.
  21802. **
  21803. ** This file contains implementations of the low-level memory allocation
  21804. ** routines specified in the sqlite3_mem_methods object. The content of
  21805. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  21806. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  21807. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  21808. ** default configuration is to use memory allocation routines in this
  21809. ** file.
  21810. **
  21811. ** C-preprocessor macro summary:
  21812. **
  21813. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  21814. ** the malloc_usable_size() interface exists
  21815. ** on the target platform. Or, this symbol
  21816. ** can be set manually, if desired.
  21817. ** If an equivalent interface exists by
  21818. ** a different name, using a separate -D
  21819. ** option to rename it.
  21820. **
  21821. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  21822. ** memory allocator. Set this symbol to enable
  21823. ** building on older macs.
  21824. **
  21825. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  21826. ** _msize() on windows systems. This might
  21827. ** be necessary when compiling for Delphi,
  21828. ** for example.
  21829. */
  21830. /* #include "sqliteInt.h" */
  21831. /*
  21832. ** This version of the memory allocator is the default. It is
  21833. ** used when no other memory allocator is specified using compile-time
  21834. ** macros.
  21835. */
  21836. #ifdef SQLITE_SYSTEM_MALLOC
  21837. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  21838. /*
  21839. ** Use the zone allocator available on apple products unless the
  21840. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  21841. */
  21842. #include <sys/sysctl.h>
  21843. #include <malloc/malloc.h>
  21844. #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
  21845. #include <libkern/OSAtomic.h>
  21846. #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
  21847. static malloc_zone_t* _sqliteZone_;
  21848. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  21849. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  21850. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  21851. #define SQLITE_MALLOCSIZE(x) \
  21852. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  21853. #else /* if not __APPLE__ */
  21854. /*
  21855. ** Use standard C library malloc and free on non-Apple systems.
  21856. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  21857. */
  21858. #define SQLITE_MALLOC(x) malloc(x)
  21859. #define SQLITE_FREE(x) free(x)
  21860. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  21861. /*
  21862. ** The malloc.h header file is needed for malloc_usable_size() function
  21863. ** on some systems (e.g. Linux).
  21864. */
  21865. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  21866. # define SQLITE_USE_MALLOC_H 1
  21867. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  21868. /*
  21869. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  21870. ** use of _msize() is automatic, but can be disabled by compiling with
  21871. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  21872. ** the malloc.h header file.
  21873. */
  21874. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  21875. # define SQLITE_USE_MALLOC_H
  21876. # define SQLITE_USE_MSIZE
  21877. #endif
  21878. /*
  21879. ** Include the malloc.h header file, if necessary. Also set define macro
  21880. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  21881. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  21882. ** The memory size function can always be overridden manually by defining
  21883. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  21884. */
  21885. #if defined(SQLITE_USE_MALLOC_H)
  21886. # include <malloc.h>
  21887. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  21888. # if !defined(SQLITE_MALLOCSIZE)
  21889. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  21890. # endif
  21891. # elif defined(SQLITE_USE_MSIZE)
  21892. # if !defined(SQLITE_MALLOCSIZE)
  21893. # define SQLITE_MALLOCSIZE _msize
  21894. # endif
  21895. # endif
  21896. #endif /* defined(SQLITE_USE_MALLOC_H) */
  21897. #endif /* __APPLE__ or not __APPLE__ */
  21898. /*
  21899. ** Like malloc(), but remember the size of the allocation
  21900. ** so that we can find it later using sqlite3MemSize().
  21901. **
  21902. ** For this low-level routine, we are guaranteed that nByte>0 because
  21903. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  21904. ** routines.
  21905. */
  21906. static void *sqlite3MemMalloc(int nByte){
  21907. #ifdef SQLITE_MALLOCSIZE
  21908. void *p;
  21909. testcase( ROUND8(nByte)==nByte );
  21910. p = SQLITE_MALLOC( nByte );
  21911. if( p==0 ){
  21912. testcase( sqlite3GlobalConfig.xLog!=0 );
  21913. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  21914. }
  21915. return p;
  21916. #else
  21917. sqlite3_int64 *p;
  21918. assert( nByte>0 );
  21919. testcase( ROUND8(nByte)!=nByte );
  21920. p = SQLITE_MALLOC( nByte+8 );
  21921. if( p ){
  21922. p[0] = nByte;
  21923. p++;
  21924. }else{
  21925. testcase( sqlite3GlobalConfig.xLog!=0 );
  21926. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  21927. }
  21928. return (void *)p;
  21929. #endif
  21930. }
  21931. /*
  21932. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  21933. ** or sqlite3MemRealloc().
  21934. **
  21935. ** For this low-level routine, we already know that pPrior!=0 since
  21936. ** cases where pPrior==0 will have been intecepted and dealt with
  21937. ** by higher-level routines.
  21938. */
  21939. static void sqlite3MemFree(void *pPrior){
  21940. #ifdef SQLITE_MALLOCSIZE
  21941. SQLITE_FREE(pPrior);
  21942. #else
  21943. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  21944. assert( pPrior!=0 );
  21945. p--;
  21946. SQLITE_FREE(p);
  21947. #endif
  21948. }
  21949. /*
  21950. ** Report the allocated size of a prior return from xMalloc()
  21951. ** or xRealloc().
  21952. */
  21953. static int sqlite3MemSize(void *pPrior){
  21954. #ifdef SQLITE_MALLOCSIZE
  21955. assert( pPrior!=0 );
  21956. return (int)SQLITE_MALLOCSIZE(pPrior);
  21957. #else
  21958. sqlite3_int64 *p;
  21959. assert( pPrior!=0 );
  21960. p = (sqlite3_int64*)pPrior;
  21961. p--;
  21962. return (int)p[0];
  21963. #endif
  21964. }
  21965. /*
  21966. ** Like realloc(). Resize an allocation previously obtained from
  21967. ** sqlite3MemMalloc().
  21968. **
  21969. ** For this low-level interface, we know that pPrior!=0. Cases where
  21970. ** pPrior==0 while have been intercepted by higher-level routine and
  21971. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  21972. ** cases where nByte<=0 will have been intercepted by higher-level
  21973. ** routines and redirected to xFree.
  21974. */
  21975. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  21976. #ifdef SQLITE_MALLOCSIZE
  21977. void *p = SQLITE_REALLOC(pPrior, nByte);
  21978. if( p==0 ){
  21979. testcase( sqlite3GlobalConfig.xLog!=0 );
  21980. sqlite3_log(SQLITE_NOMEM,
  21981. "failed memory resize %u to %u bytes",
  21982. SQLITE_MALLOCSIZE(pPrior), nByte);
  21983. }
  21984. return p;
  21985. #else
  21986. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  21987. assert( pPrior!=0 && nByte>0 );
  21988. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  21989. p--;
  21990. p = SQLITE_REALLOC(p, nByte+8 );
  21991. if( p ){
  21992. p[0] = nByte;
  21993. p++;
  21994. }else{
  21995. testcase( sqlite3GlobalConfig.xLog!=0 );
  21996. sqlite3_log(SQLITE_NOMEM,
  21997. "failed memory resize %u to %u bytes",
  21998. sqlite3MemSize(pPrior), nByte);
  21999. }
  22000. return (void*)p;
  22001. #endif
  22002. }
  22003. /*
  22004. ** Round up a request size to the next valid allocation size.
  22005. */
  22006. static int sqlite3MemRoundup(int n){
  22007. return ROUND8(n);
  22008. }
  22009. /*
  22010. ** Initialize this module.
  22011. */
  22012. static int sqlite3MemInit(void *NotUsed){
  22013. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  22014. int cpuCount;
  22015. size_t len;
  22016. if( _sqliteZone_ ){
  22017. return SQLITE_OK;
  22018. }
  22019. len = sizeof(cpuCount);
  22020. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  22021. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  22022. if( cpuCount>1 ){
  22023. /* defer MT decisions to system malloc */
  22024. _sqliteZone_ = malloc_default_zone();
  22025. }else{
  22026. /* only 1 core, use our own zone to contention over global locks,
  22027. ** e.g. we have our own dedicated locks */
  22028. _sqliteZone_ = malloc_create_zone(4096, 0);
  22029. malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
  22030. }
  22031. #endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
  22032. UNUSED_PARAMETER(NotUsed);
  22033. return SQLITE_OK;
  22034. }
  22035. /*
  22036. ** Deinitialize this module.
  22037. */
  22038. static void sqlite3MemShutdown(void *NotUsed){
  22039. UNUSED_PARAMETER(NotUsed);
  22040. return;
  22041. }
  22042. /*
  22043. ** This routine is the only routine in this file with external linkage.
  22044. **
  22045. ** Populate the low-level memory allocation function pointers in
  22046. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  22047. */
  22048. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  22049. static const sqlite3_mem_methods defaultMethods = {
  22050. sqlite3MemMalloc,
  22051. sqlite3MemFree,
  22052. sqlite3MemRealloc,
  22053. sqlite3MemSize,
  22054. sqlite3MemRoundup,
  22055. sqlite3MemInit,
  22056. sqlite3MemShutdown,
  22057. 0
  22058. };
  22059. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  22060. }
  22061. #endif /* SQLITE_SYSTEM_MALLOC */
  22062. /************** End of mem1.c ************************************************/
  22063. /************** Begin file mem2.c ********************************************/
  22064. /*
  22065. ** 2007 August 15
  22066. **
  22067. ** The author disclaims copyright to this source code. In place of
  22068. ** a legal notice, here is a blessing:
  22069. **
  22070. ** May you do good and not evil.
  22071. ** May you find forgiveness for yourself and forgive others.
  22072. ** May you share freely, never taking more than you give.
  22073. **
  22074. *************************************************************************
  22075. **
  22076. ** This file contains low-level memory allocation drivers for when
  22077. ** SQLite will use the standard C-library malloc/realloc/free interface
  22078. ** to obtain the memory it needs while adding lots of additional debugging
  22079. ** information to each allocation in order to help detect and fix memory
  22080. ** leaks and memory usage errors.
  22081. **
  22082. ** This file contains implementations of the low-level memory allocation
  22083. ** routines specified in the sqlite3_mem_methods object.
  22084. */
  22085. /* #include "sqliteInt.h" */
  22086. /*
  22087. ** This version of the memory allocator is used only if the
  22088. ** SQLITE_MEMDEBUG macro is defined
  22089. */
  22090. #ifdef SQLITE_MEMDEBUG
  22091. /*
  22092. ** The backtrace functionality is only available with GLIBC
  22093. */
  22094. #ifdef __GLIBC__
  22095. extern int backtrace(void**,int);
  22096. extern void backtrace_symbols_fd(void*const*,int,int);
  22097. #else
  22098. # define backtrace(A,B) 1
  22099. # define backtrace_symbols_fd(A,B,C)
  22100. #endif
  22101. /* #include <stdio.h> */
  22102. /*
  22103. ** Each memory allocation looks like this:
  22104. **
  22105. ** ------------------------------------------------------------------------
  22106. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  22107. ** ------------------------------------------------------------------------
  22108. **
  22109. ** The application code sees only a pointer to the allocation. We have
  22110. ** to back up from the allocation pointer to find the MemBlockHdr. The
  22111. ** MemBlockHdr tells us the size of the allocation and the number of
  22112. ** backtrace pointers. There is also a guard word at the end of the
  22113. ** MemBlockHdr.
  22114. */
  22115. struct MemBlockHdr {
  22116. i64 iSize; /* Size of this allocation */
  22117. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  22118. char nBacktrace; /* Number of backtraces on this alloc */
  22119. char nBacktraceSlots; /* Available backtrace slots */
  22120. u8 nTitle; /* Bytes of title; includes '\0' */
  22121. u8 eType; /* Allocation type code */
  22122. int iForeGuard; /* Guard word for sanity */
  22123. };
  22124. /*
  22125. ** Guard words
  22126. */
  22127. #define FOREGUARD 0x80F5E153
  22128. #define REARGUARD 0xE4676B53
  22129. /*
  22130. ** Number of malloc size increments to track.
  22131. */
  22132. #define NCSIZE 1000
  22133. /*
  22134. ** All of the static variables used by this module are collected
  22135. ** into a single structure named "mem". This is to keep the
  22136. ** static variables organized and to reduce namespace pollution
  22137. ** when this module is combined with other in the amalgamation.
  22138. */
  22139. static struct {
  22140. /*
  22141. ** Mutex to control access to the memory allocation subsystem.
  22142. */
  22143. sqlite3_mutex *mutex;
  22144. /*
  22145. ** Head and tail of a linked list of all outstanding allocations
  22146. */
  22147. struct MemBlockHdr *pFirst;
  22148. struct MemBlockHdr *pLast;
  22149. /*
  22150. ** The number of levels of backtrace to save in new allocations.
  22151. */
  22152. int nBacktrace;
  22153. void (*xBacktrace)(int, int, void **);
  22154. /*
  22155. ** Title text to insert in front of each block
  22156. */
  22157. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  22158. char zTitle[100]; /* The title text */
  22159. /*
  22160. ** sqlite3MallocDisallow() increments the following counter.
  22161. ** sqlite3MallocAllow() decrements it.
  22162. */
  22163. int disallow; /* Do not allow memory allocation */
  22164. /*
  22165. ** Gather statistics on the sizes of memory allocations.
  22166. ** nAlloc[i] is the number of allocation attempts of i*8
  22167. ** bytes. i==NCSIZE is the number of allocation attempts for
  22168. ** sizes more than NCSIZE*8 bytes.
  22169. */
  22170. int nAlloc[NCSIZE]; /* Total number of allocations */
  22171. int nCurrent[NCSIZE]; /* Current number of allocations */
  22172. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  22173. } mem;
  22174. /*
  22175. ** Adjust memory usage statistics
  22176. */
  22177. static void adjustStats(int iSize, int increment){
  22178. int i = ROUND8(iSize)/8;
  22179. if( i>NCSIZE-1 ){
  22180. i = NCSIZE - 1;
  22181. }
  22182. if( increment>0 ){
  22183. mem.nAlloc[i]++;
  22184. mem.nCurrent[i]++;
  22185. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  22186. mem.mxCurrent[i] = mem.nCurrent[i];
  22187. }
  22188. }else{
  22189. mem.nCurrent[i]--;
  22190. assert( mem.nCurrent[i]>=0 );
  22191. }
  22192. }
  22193. /*
  22194. ** Given an allocation, find the MemBlockHdr for that allocation.
  22195. **
  22196. ** This routine checks the guards at either end of the allocation and
  22197. ** if they are incorrect it asserts.
  22198. */
  22199. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  22200. struct MemBlockHdr *p;
  22201. int *pInt;
  22202. u8 *pU8;
  22203. int nReserve;
  22204. p = (struct MemBlockHdr*)pAllocation;
  22205. p--;
  22206. assert( p->iForeGuard==(int)FOREGUARD );
  22207. nReserve = ROUND8(p->iSize);
  22208. pInt = (int*)pAllocation;
  22209. pU8 = (u8*)pAllocation;
  22210. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  22211. /* This checks any of the "extra" bytes allocated due
  22212. ** to rounding up to an 8 byte boundary to ensure
  22213. ** they haven't been overwritten.
  22214. */
  22215. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  22216. return p;
  22217. }
  22218. /*
  22219. ** Return the number of bytes currently allocated at address p.
  22220. */
  22221. static int sqlite3MemSize(void *p){
  22222. struct MemBlockHdr *pHdr;
  22223. if( !p ){
  22224. return 0;
  22225. }
  22226. pHdr = sqlite3MemsysGetHeader(p);
  22227. return (int)pHdr->iSize;
  22228. }
  22229. /*
  22230. ** Initialize the memory allocation subsystem.
  22231. */
  22232. static int sqlite3MemInit(void *NotUsed){
  22233. UNUSED_PARAMETER(NotUsed);
  22234. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  22235. if( !sqlite3GlobalConfig.bMemstat ){
  22236. /* If memory status is enabled, then the malloc.c wrapper will already
  22237. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  22238. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  22239. }
  22240. return SQLITE_OK;
  22241. }
  22242. /*
  22243. ** Deinitialize the memory allocation subsystem.
  22244. */
  22245. static void sqlite3MemShutdown(void *NotUsed){
  22246. UNUSED_PARAMETER(NotUsed);
  22247. mem.mutex = 0;
  22248. }
  22249. /*
  22250. ** Round up a request size to the next valid allocation size.
  22251. */
  22252. static int sqlite3MemRoundup(int n){
  22253. return ROUND8(n);
  22254. }
  22255. /*
  22256. ** Fill a buffer with pseudo-random bytes. This is used to preset
  22257. ** the content of a new memory allocation to unpredictable values and
  22258. ** to clear the content of a freed allocation to unpredictable values.
  22259. */
  22260. static void randomFill(char *pBuf, int nByte){
  22261. unsigned int x, y, r;
  22262. x = SQLITE_PTR_TO_INT(pBuf);
  22263. y = nByte | 1;
  22264. while( nByte >= 4 ){
  22265. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  22266. y = y*1103515245 + 12345;
  22267. r = x ^ y;
  22268. *(int*)pBuf = r;
  22269. pBuf += 4;
  22270. nByte -= 4;
  22271. }
  22272. while( nByte-- > 0 ){
  22273. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  22274. y = y*1103515245 + 12345;
  22275. r = x ^ y;
  22276. *(pBuf++) = r & 0xff;
  22277. }
  22278. }
  22279. /*
  22280. ** Allocate nByte bytes of memory.
  22281. */
  22282. static void *sqlite3MemMalloc(int nByte){
  22283. struct MemBlockHdr *pHdr;
  22284. void **pBt;
  22285. char *z;
  22286. int *pInt;
  22287. void *p = 0;
  22288. int totalSize;
  22289. int nReserve;
  22290. sqlite3_mutex_enter(mem.mutex);
  22291. assert( mem.disallow==0 );
  22292. nReserve = ROUND8(nByte);
  22293. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  22294. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  22295. p = malloc(totalSize);
  22296. if( p ){
  22297. z = p;
  22298. pBt = (void**)&z[mem.nTitle];
  22299. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  22300. pHdr->pNext = 0;
  22301. pHdr->pPrev = mem.pLast;
  22302. if( mem.pLast ){
  22303. mem.pLast->pNext = pHdr;
  22304. }else{
  22305. mem.pFirst = pHdr;
  22306. }
  22307. mem.pLast = pHdr;
  22308. pHdr->iForeGuard = FOREGUARD;
  22309. pHdr->eType = MEMTYPE_HEAP;
  22310. pHdr->nBacktraceSlots = mem.nBacktrace;
  22311. pHdr->nTitle = mem.nTitle;
  22312. if( mem.nBacktrace ){
  22313. void *aAddr[40];
  22314. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  22315. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  22316. assert(pBt[0]);
  22317. if( mem.xBacktrace ){
  22318. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  22319. }
  22320. }else{
  22321. pHdr->nBacktrace = 0;
  22322. }
  22323. if( mem.nTitle ){
  22324. memcpy(z, mem.zTitle, mem.nTitle);
  22325. }
  22326. pHdr->iSize = nByte;
  22327. adjustStats(nByte, +1);
  22328. pInt = (int*)&pHdr[1];
  22329. pInt[nReserve/sizeof(int)] = REARGUARD;
  22330. randomFill((char*)pInt, nByte);
  22331. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  22332. p = (void*)pInt;
  22333. }
  22334. sqlite3_mutex_leave(mem.mutex);
  22335. return p;
  22336. }
  22337. /*
  22338. ** Free memory.
  22339. */
  22340. static void sqlite3MemFree(void *pPrior){
  22341. struct MemBlockHdr *pHdr;
  22342. void **pBt;
  22343. char *z;
  22344. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  22345. || mem.mutex!=0 );
  22346. pHdr = sqlite3MemsysGetHeader(pPrior);
  22347. pBt = (void**)pHdr;
  22348. pBt -= pHdr->nBacktraceSlots;
  22349. sqlite3_mutex_enter(mem.mutex);
  22350. if( pHdr->pPrev ){
  22351. assert( pHdr->pPrev->pNext==pHdr );
  22352. pHdr->pPrev->pNext = pHdr->pNext;
  22353. }else{
  22354. assert( mem.pFirst==pHdr );
  22355. mem.pFirst = pHdr->pNext;
  22356. }
  22357. if( pHdr->pNext ){
  22358. assert( pHdr->pNext->pPrev==pHdr );
  22359. pHdr->pNext->pPrev = pHdr->pPrev;
  22360. }else{
  22361. assert( mem.pLast==pHdr );
  22362. mem.pLast = pHdr->pPrev;
  22363. }
  22364. z = (char*)pBt;
  22365. z -= pHdr->nTitle;
  22366. adjustStats((int)pHdr->iSize, -1);
  22367. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  22368. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  22369. free(z);
  22370. sqlite3_mutex_leave(mem.mutex);
  22371. }
  22372. /*
  22373. ** Change the size of an existing memory allocation.
  22374. **
  22375. ** For this debugging implementation, we *always* make a copy of the
  22376. ** allocation into a new place in memory. In this way, if the
  22377. ** higher level code is using pointer to the old allocation, it is
  22378. ** much more likely to break and we are much more liking to find
  22379. ** the error.
  22380. */
  22381. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  22382. struct MemBlockHdr *pOldHdr;
  22383. void *pNew;
  22384. assert( mem.disallow==0 );
  22385. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  22386. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  22387. pNew = sqlite3MemMalloc(nByte);
  22388. if( pNew ){
  22389. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  22390. if( nByte>pOldHdr->iSize ){
  22391. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  22392. }
  22393. sqlite3MemFree(pPrior);
  22394. }
  22395. return pNew;
  22396. }
  22397. /*
  22398. ** Populate the low-level memory allocation function pointers in
  22399. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  22400. */
  22401. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  22402. static const sqlite3_mem_methods defaultMethods = {
  22403. sqlite3MemMalloc,
  22404. sqlite3MemFree,
  22405. sqlite3MemRealloc,
  22406. sqlite3MemSize,
  22407. sqlite3MemRoundup,
  22408. sqlite3MemInit,
  22409. sqlite3MemShutdown,
  22410. 0
  22411. };
  22412. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  22413. }
  22414. /*
  22415. ** Set the "type" of an allocation.
  22416. */
  22417. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  22418. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  22419. struct MemBlockHdr *pHdr;
  22420. pHdr = sqlite3MemsysGetHeader(p);
  22421. assert( pHdr->iForeGuard==FOREGUARD );
  22422. pHdr->eType = eType;
  22423. }
  22424. }
  22425. /*
  22426. ** Return TRUE if the mask of type in eType matches the type of the
  22427. ** allocation p. Also return true if p==NULL.
  22428. **
  22429. ** This routine is designed for use within an assert() statement, to
  22430. ** verify the type of an allocation. For example:
  22431. **
  22432. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  22433. */
  22434. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  22435. int rc = 1;
  22436. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  22437. struct MemBlockHdr *pHdr;
  22438. pHdr = sqlite3MemsysGetHeader(p);
  22439. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  22440. if( (pHdr->eType&eType)==0 ){
  22441. rc = 0;
  22442. }
  22443. }
  22444. return rc;
  22445. }
  22446. /*
  22447. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  22448. ** allocation p. Also return true if p==NULL.
  22449. **
  22450. ** This routine is designed for use within an assert() statement, to
  22451. ** verify the type of an allocation. For example:
  22452. **
  22453. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  22454. */
  22455. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  22456. int rc = 1;
  22457. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  22458. struct MemBlockHdr *pHdr;
  22459. pHdr = sqlite3MemsysGetHeader(p);
  22460. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  22461. if( (pHdr->eType&eType)!=0 ){
  22462. rc = 0;
  22463. }
  22464. }
  22465. return rc;
  22466. }
  22467. /*
  22468. ** Set the number of backtrace levels kept for each allocation.
  22469. ** A value of zero turns off backtracing. The number is always rounded
  22470. ** up to a multiple of 2.
  22471. */
  22472. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  22473. if( depth<0 ){ depth = 0; }
  22474. if( depth>20 ){ depth = 20; }
  22475. depth = (depth+1)&0xfe;
  22476. mem.nBacktrace = depth;
  22477. }
  22478. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  22479. mem.xBacktrace = xBacktrace;
  22480. }
  22481. /*
  22482. ** Set the title string for subsequent allocations.
  22483. */
  22484. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  22485. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  22486. sqlite3_mutex_enter(mem.mutex);
  22487. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  22488. memcpy(mem.zTitle, zTitle, n);
  22489. mem.zTitle[n] = 0;
  22490. mem.nTitle = ROUND8(n);
  22491. sqlite3_mutex_leave(mem.mutex);
  22492. }
  22493. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  22494. struct MemBlockHdr *pHdr;
  22495. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  22496. void **pBt = (void**)pHdr;
  22497. pBt -= pHdr->nBacktraceSlots;
  22498. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  22499. }
  22500. }
  22501. /*
  22502. ** Open the file indicated and write a log of all unfreed memory
  22503. ** allocations into that log.
  22504. */
  22505. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  22506. FILE *out;
  22507. struct MemBlockHdr *pHdr;
  22508. void **pBt;
  22509. int i;
  22510. out = fopen(zFilename, "w");
  22511. if( out==0 ){
  22512. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  22513. zFilename);
  22514. return;
  22515. }
  22516. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  22517. char *z = (char*)pHdr;
  22518. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  22519. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  22520. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  22521. if( pHdr->nBacktrace ){
  22522. fflush(out);
  22523. pBt = (void**)pHdr;
  22524. pBt -= pHdr->nBacktraceSlots;
  22525. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  22526. fprintf(out, "\n");
  22527. }
  22528. }
  22529. fprintf(out, "COUNTS:\n");
  22530. for(i=0; i<NCSIZE-1; i++){
  22531. if( mem.nAlloc[i] ){
  22532. fprintf(out, " %5d: %10d %10d %10d\n",
  22533. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  22534. }
  22535. }
  22536. if( mem.nAlloc[NCSIZE-1] ){
  22537. fprintf(out, " %5d: %10d %10d %10d\n",
  22538. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  22539. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  22540. }
  22541. fclose(out);
  22542. }
  22543. /*
  22544. ** Return the number of times sqlite3MemMalloc() has been called.
  22545. */
  22546. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  22547. int i;
  22548. int nTotal = 0;
  22549. for(i=0; i<NCSIZE; i++){
  22550. nTotal += mem.nAlloc[i];
  22551. }
  22552. return nTotal;
  22553. }
  22554. #endif /* SQLITE_MEMDEBUG */
  22555. /************** End of mem2.c ************************************************/
  22556. /************** Begin file mem3.c ********************************************/
  22557. /*
  22558. ** 2007 October 14
  22559. **
  22560. ** The author disclaims copyright to this source code. In place of
  22561. ** a legal notice, here is a blessing:
  22562. **
  22563. ** May you do good and not evil.
  22564. ** May you find forgiveness for yourself and forgive others.
  22565. ** May you share freely, never taking more than you give.
  22566. **
  22567. *************************************************************************
  22568. ** This file contains the C functions that implement a memory
  22569. ** allocation subsystem for use by SQLite.
  22570. **
  22571. ** This version of the memory allocation subsystem omits all
  22572. ** use of malloc(). The SQLite user supplies a block of memory
  22573. ** before calling sqlite3_initialize() from which allocations
  22574. ** are made and returned by the xMalloc() and xRealloc()
  22575. ** implementations. Once sqlite3_initialize() has been called,
  22576. ** the amount of memory available to SQLite is fixed and cannot
  22577. ** be changed.
  22578. **
  22579. ** This version of the memory allocation subsystem is included
  22580. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  22581. */
  22582. /* #include "sqliteInt.h" */
  22583. /*
  22584. ** This version of the memory allocator is only built into the library
  22585. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  22586. ** mean that the library will use a memory-pool by default, just that
  22587. ** it is available. The mempool allocator is activated by calling
  22588. ** sqlite3_config().
  22589. */
  22590. #ifdef SQLITE_ENABLE_MEMSYS3
  22591. /*
  22592. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  22593. */
  22594. #define MX_SMALL 10
  22595. /*
  22596. ** Number of freelist hash slots
  22597. */
  22598. #define N_HASH 61
  22599. /*
  22600. ** A memory allocation (also called a "chunk") consists of two or
  22601. ** more blocks where each block is 8 bytes. The first 8 bytes are
  22602. ** a header that is not returned to the user.
  22603. **
  22604. ** A chunk is two or more blocks that is either checked out or
  22605. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  22606. ** size of the allocation in blocks if the allocation is free.
  22607. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  22608. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  22609. ** is true if the previous chunk is checked out and false if the
  22610. ** previous chunk is free. The u.hdr.prevSize field is the size of
  22611. ** the previous chunk in blocks if the previous chunk is on the
  22612. ** freelist. If the previous chunk is checked out, then
  22613. ** u.hdr.prevSize can be part of the data for that chunk and should
  22614. ** not be read or written.
  22615. **
  22616. ** We often identify a chunk by its index in mem3.aPool[]. When
  22617. ** this is done, the chunk index refers to the second block of
  22618. ** the chunk. In this way, the first chunk has an index of 1.
  22619. ** A chunk index of 0 means "no such chunk" and is the equivalent
  22620. ** of a NULL pointer.
  22621. **
  22622. ** The second block of free chunks is of the form u.list. The
  22623. ** two fields form a double-linked list of chunks of related sizes.
  22624. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  22625. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  22626. **
  22627. ** The second block of a chunk is user data if the chunk is checked
  22628. ** out. If a chunk is checked out, the user data may extend into
  22629. ** the u.hdr.prevSize value of the following chunk.
  22630. */
  22631. typedef struct Mem3Block Mem3Block;
  22632. struct Mem3Block {
  22633. union {
  22634. struct {
  22635. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  22636. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  22637. } hdr;
  22638. struct {
  22639. u32 next; /* Index in mem3.aPool[] of next free chunk */
  22640. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  22641. } list;
  22642. } u;
  22643. };
  22644. /*
  22645. ** All of the static variables used by this module are collected
  22646. ** into a single structure named "mem3". This is to keep the
  22647. ** static variables organized and to reduce namespace pollution
  22648. ** when this module is combined with other in the amalgamation.
  22649. */
  22650. static SQLITE_WSD struct Mem3Global {
  22651. /*
  22652. ** Memory available for allocation. nPool is the size of the array
  22653. ** (in Mem3Blocks) pointed to by aPool less 2.
  22654. */
  22655. u32 nPool;
  22656. Mem3Block *aPool;
  22657. /*
  22658. ** True if we are evaluating an out-of-memory callback.
  22659. */
  22660. int alarmBusy;
  22661. /*
  22662. ** Mutex to control access to the memory allocation subsystem.
  22663. */
  22664. sqlite3_mutex *mutex;
  22665. /*
  22666. ** The minimum amount of free space that we have seen.
  22667. */
  22668. u32 mnMaster;
  22669. /*
  22670. ** iMaster is the index of the master chunk. Most new allocations
  22671. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  22672. ** of the current master. iMaster is 0 if there is not master chunk.
  22673. ** The master chunk is not in either the aiHash[] or aiSmall[].
  22674. */
  22675. u32 iMaster;
  22676. u32 szMaster;
  22677. /*
  22678. ** Array of lists of free blocks according to the block size
  22679. ** for smaller chunks, or a hash on the block size for larger
  22680. ** chunks.
  22681. */
  22682. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  22683. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  22684. } mem3 = { 97535575 };
  22685. #define mem3 GLOBAL(struct Mem3Global, mem3)
  22686. /*
  22687. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  22688. ** on. *pRoot is the list that i is a member of.
  22689. */
  22690. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  22691. u32 next = mem3.aPool[i].u.list.next;
  22692. u32 prev = mem3.aPool[i].u.list.prev;
  22693. assert( sqlite3_mutex_held(mem3.mutex) );
  22694. if( prev==0 ){
  22695. *pRoot = next;
  22696. }else{
  22697. mem3.aPool[prev].u.list.next = next;
  22698. }
  22699. if( next ){
  22700. mem3.aPool[next].u.list.prev = prev;
  22701. }
  22702. mem3.aPool[i].u.list.next = 0;
  22703. mem3.aPool[i].u.list.prev = 0;
  22704. }
  22705. /*
  22706. ** Unlink the chunk at index i from
  22707. ** whatever list is currently a member of.
  22708. */
  22709. static void memsys3Unlink(u32 i){
  22710. u32 size, hash;
  22711. assert( sqlite3_mutex_held(mem3.mutex) );
  22712. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  22713. assert( i>=1 );
  22714. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22715. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  22716. assert( size>=2 );
  22717. if( size <= MX_SMALL ){
  22718. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  22719. }else{
  22720. hash = size % N_HASH;
  22721. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  22722. }
  22723. }
  22724. /*
  22725. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  22726. ** at *pRoot.
  22727. */
  22728. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  22729. assert( sqlite3_mutex_held(mem3.mutex) );
  22730. mem3.aPool[i].u.list.next = *pRoot;
  22731. mem3.aPool[i].u.list.prev = 0;
  22732. if( *pRoot ){
  22733. mem3.aPool[*pRoot].u.list.prev = i;
  22734. }
  22735. *pRoot = i;
  22736. }
  22737. /*
  22738. ** Link the chunk at index i into either the appropriate
  22739. ** small chunk list, or into the large chunk hash table.
  22740. */
  22741. static void memsys3Link(u32 i){
  22742. u32 size, hash;
  22743. assert( sqlite3_mutex_held(mem3.mutex) );
  22744. assert( i>=1 );
  22745. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  22746. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22747. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  22748. assert( size>=2 );
  22749. if( size <= MX_SMALL ){
  22750. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  22751. }else{
  22752. hash = size % N_HASH;
  22753. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  22754. }
  22755. }
  22756. /*
  22757. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  22758. ** will already be held (obtained by code in malloc.c) if
  22759. ** sqlite3GlobalConfig.bMemStat is true.
  22760. */
  22761. static void memsys3Enter(void){
  22762. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  22763. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  22764. }
  22765. sqlite3_mutex_enter(mem3.mutex);
  22766. }
  22767. static void memsys3Leave(void){
  22768. sqlite3_mutex_leave(mem3.mutex);
  22769. }
  22770. /*
  22771. ** Called when we are unable to satisfy an allocation of nBytes.
  22772. */
  22773. static void memsys3OutOfMemory(int nByte){
  22774. if( !mem3.alarmBusy ){
  22775. mem3.alarmBusy = 1;
  22776. assert( sqlite3_mutex_held(mem3.mutex) );
  22777. sqlite3_mutex_leave(mem3.mutex);
  22778. sqlite3_release_memory(nByte);
  22779. sqlite3_mutex_enter(mem3.mutex);
  22780. mem3.alarmBusy = 0;
  22781. }
  22782. }
  22783. /*
  22784. ** Chunk i is a free chunk that has been unlinked. Adjust its
  22785. ** size parameters for check-out and return a pointer to the
  22786. ** user portion of the chunk.
  22787. */
  22788. static void *memsys3Checkout(u32 i, u32 nBlock){
  22789. u32 x;
  22790. assert( sqlite3_mutex_held(mem3.mutex) );
  22791. assert( i>=1 );
  22792. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  22793. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  22794. x = mem3.aPool[i-1].u.hdr.size4x;
  22795. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  22796. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  22797. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  22798. return &mem3.aPool[i];
  22799. }
  22800. /*
  22801. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  22802. ** Return a pointer to the new allocation. Or, if the master chunk
  22803. ** is not large enough, return 0.
  22804. */
  22805. static void *memsys3FromMaster(u32 nBlock){
  22806. assert( sqlite3_mutex_held(mem3.mutex) );
  22807. assert( mem3.szMaster>=nBlock );
  22808. if( nBlock>=mem3.szMaster-1 ){
  22809. /* Use the entire master */
  22810. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  22811. mem3.iMaster = 0;
  22812. mem3.szMaster = 0;
  22813. mem3.mnMaster = 0;
  22814. return p;
  22815. }else{
  22816. /* Split the master block. Return the tail. */
  22817. u32 newi, x;
  22818. newi = mem3.iMaster + mem3.szMaster - nBlock;
  22819. assert( newi > mem3.iMaster+1 );
  22820. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  22821. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  22822. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  22823. mem3.szMaster -= nBlock;
  22824. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  22825. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22826. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22827. if( mem3.szMaster < mem3.mnMaster ){
  22828. mem3.mnMaster = mem3.szMaster;
  22829. }
  22830. return (void*)&mem3.aPool[newi];
  22831. }
  22832. }
  22833. /*
  22834. ** *pRoot is the head of a list of free chunks of the same size
  22835. ** or same size hash. In other words, *pRoot is an entry in either
  22836. ** mem3.aiSmall[] or mem3.aiHash[].
  22837. **
  22838. ** This routine examines all entries on the given list and tries
  22839. ** to coalesce each entries with adjacent free chunks.
  22840. **
  22841. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  22842. ** the current mem3.iMaster with the new larger chunk. In order for
  22843. ** this mem3.iMaster replacement to work, the master chunk must be
  22844. ** linked into the hash tables. That is not the normal state of
  22845. ** affairs, of course. The calling routine must link the master
  22846. ** chunk before invoking this routine, then must unlink the (possibly
  22847. ** changed) master chunk once this routine has finished.
  22848. */
  22849. static void memsys3Merge(u32 *pRoot){
  22850. u32 iNext, prev, size, i, x;
  22851. assert( sqlite3_mutex_held(mem3.mutex) );
  22852. for(i=*pRoot; i>0; i=iNext){
  22853. iNext = mem3.aPool[i].u.list.next;
  22854. size = mem3.aPool[i-1].u.hdr.size4x;
  22855. assert( (size&1)==0 );
  22856. if( (size&2)==0 ){
  22857. memsys3UnlinkFromList(i, pRoot);
  22858. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  22859. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  22860. if( prev==iNext ){
  22861. iNext = mem3.aPool[prev].u.list.next;
  22862. }
  22863. memsys3Unlink(prev);
  22864. size = i + size/4 - prev;
  22865. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  22866. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  22867. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  22868. memsys3Link(prev);
  22869. i = prev;
  22870. }else{
  22871. size /= 4;
  22872. }
  22873. if( size>mem3.szMaster ){
  22874. mem3.iMaster = i;
  22875. mem3.szMaster = size;
  22876. }
  22877. }
  22878. }
  22879. /*
  22880. ** Return a block of memory of at least nBytes in size.
  22881. ** Return NULL if unable.
  22882. **
  22883. ** This function assumes that the necessary mutexes, if any, are
  22884. ** already held by the caller. Hence "Unsafe".
  22885. */
  22886. static void *memsys3MallocUnsafe(int nByte){
  22887. u32 i;
  22888. u32 nBlock;
  22889. u32 toFree;
  22890. assert( sqlite3_mutex_held(mem3.mutex) );
  22891. assert( sizeof(Mem3Block)==8 );
  22892. if( nByte<=12 ){
  22893. nBlock = 2;
  22894. }else{
  22895. nBlock = (nByte + 11)/8;
  22896. }
  22897. assert( nBlock>=2 );
  22898. /* STEP 1:
  22899. ** Look for an entry of the correct size in either the small
  22900. ** chunk table or in the large chunk hash table. This is
  22901. ** successful most of the time (about 9 times out of 10).
  22902. */
  22903. if( nBlock <= MX_SMALL ){
  22904. i = mem3.aiSmall[nBlock-2];
  22905. if( i>0 ){
  22906. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  22907. return memsys3Checkout(i, nBlock);
  22908. }
  22909. }else{
  22910. int hash = nBlock % N_HASH;
  22911. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  22912. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  22913. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  22914. return memsys3Checkout(i, nBlock);
  22915. }
  22916. }
  22917. }
  22918. /* STEP 2:
  22919. ** Try to satisfy the allocation by carving a piece off of the end
  22920. ** of the master chunk. This step usually works if step 1 fails.
  22921. */
  22922. if( mem3.szMaster>=nBlock ){
  22923. return memsys3FromMaster(nBlock);
  22924. }
  22925. /* STEP 3:
  22926. ** Loop through the entire memory pool. Coalesce adjacent free
  22927. ** chunks. Recompute the master chunk as the largest free chunk.
  22928. ** Then try again to satisfy the allocation by carving a piece off
  22929. ** of the end of the master chunk. This step happens very
  22930. ** rarely (we hope!)
  22931. */
  22932. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  22933. memsys3OutOfMemory(toFree);
  22934. if( mem3.iMaster ){
  22935. memsys3Link(mem3.iMaster);
  22936. mem3.iMaster = 0;
  22937. mem3.szMaster = 0;
  22938. }
  22939. for(i=0; i<N_HASH; i++){
  22940. memsys3Merge(&mem3.aiHash[i]);
  22941. }
  22942. for(i=0; i<MX_SMALL-1; i++){
  22943. memsys3Merge(&mem3.aiSmall[i]);
  22944. }
  22945. if( mem3.szMaster ){
  22946. memsys3Unlink(mem3.iMaster);
  22947. if( mem3.szMaster>=nBlock ){
  22948. return memsys3FromMaster(nBlock);
  22949. }
  22950. }
  22951. }
  22952. /* If none of the above worked, then we fail. */
  22953. return 0;
  22954. }
  22955. /*
  22956. ** Free an outstanding memory allocation.
  22957. **
  22958. ** This function assumes that the necessary mutexes, if any, are
  22959. ** already held by the caller. Hence "Unsafe".
  22960. */
  22961. static void memsys3FreeUnsafe(void *pOld){
  22962. Mem3Block *p = (Mem3Block*)pOld;
  22963. int i;
  22964. u32 size, x;
  22965. assert( sqlite3_mutex_held(mem3.mutex) );
  22966. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  22967. i = p - mem3.aPool;
  22968. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  22969. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22970. assert( i+size<=mem3.nPool+1 );
  22971. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  22972. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  22973. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  22974. memsys3Link(i);
  22975. /* Try to expand the master using the newly freed chunk */
  22976. if( mem3.iMaster ){
  22977. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  22978. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  22979. mem3.iMaster -= size;
  22980. mem3.szMaster += size;
  22981. memsys3Unlink(mem3.iMaster);
  22982. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22983. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22984. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  22985. }
  22986. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22987. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  22988. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  22989. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  22990. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22991. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  22992. }
  22993. }
  22994. }
  22995. /*
  22996. ** Return the size of an outstanding allocation, in bytes. The
  22997. ** size returned omits the 8-byte header overhead. This only
  22998. ** works for chunks that are currently checked out.
  22999. */
  23000. static int memsys3Size(void *p){
  23001. Mem3Block *pBlock;
  23002. assert( p!=0 );
  23003. pBlock = (Mem3Block*)p;
  23004. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  23005. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  23006. }
  23007. /*
  23008. ** Round up a request size to the next valid allocation size.
  23009. */
  23010. static int memsys3Roundup(int n){
  23011. if( n<=12 ){
  23012. return 12;
  23013. }else{
  23014. return ((n+11)&~7) - 4;
  23015. }
  23016. }
  23017. /*
  23018. ** Allocate nBytes of memory.
  23019. */
  23020. static void *memsys3Malloc(int nBytes){
  23021. sqlite3_int64 *p;
  23022. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  23023. memsys3Enter();
  23024. p = memsys3MallocUnsafe(nBytes);
  23025. memsys3Leave();
  23026. return (void*)p;
  23027. }
  23028. /*
  23029. ** Free memory.
  23030. */
  23031. static void memsys3Free(void *pPrior){
  23032. assert( pPrior );
  23033. memsys3Enter();
  23034. memsys3FreeUnsafe(pPrior);
  23035. memsys3Leave();
  23036. }
  23037. /*
  23038. ** Change the size of an existing memory allocation
  23039. */
  23040. static void *memsys3Realloc(void *pPrior, int nBytes){
  23041. int nOld;
  23042. void *p;
  23043. if( pPrior==0 ){
  23044. return sqlite3_malloc(nBytes);
  23045. }
  23046. if( nBytes<=0 ){
  23047. sqlite3_free(pPrior);
  23048. return 0;
  23049. }
  23050. nOld = memsys3Size(pPrior);
  23051. if( nBytes<=nOld && nBytes>=nOld-128 ){
  23052. return pPrior;
  23053. }
  23054. memsys3Enter();
  23055. p = memsys3MallocUnsafe(nBytes);
  23056. if( p ){
  23057. if( nOld<nBytes ){
  23058. memcpy(p, pPrior, nOld);
  23059. }else{
  23060. memcpy(p, pPrior, nBytes);
  23061. }
  23062. memsys3FreeUnsafe(pPrior);
  23063. }
  23064. memsys3Leave();
  23065. return p;
  23066. }
  23067. /*
  23068. ** Initialize this module.
  23069. */
  23070. static int memsys3Init(void *NotUsed){
  23071. UNUSED_PARAMETER(NotUsed);
  23072. if( !sqlite3GlobalConfig.pHeap ){
  23073. return SQLITE_ERROR;
  23074. }
  23075. /* Store a pointer to the memory block in global structure mem3. */
  23076. assert( sizeof(Mem3Block)==8 );
  23077. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  23078. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  23079. /* Initialize the master block. */
  23080. mem3.szMaster = mem3.nPool;
  23081. mem3.mnMaster = mem3.szMaster;
  23082. mem3.iMaster = 1;
  23083. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  23084. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  23085. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  23086. return SQLITE_OK;
  23087. }
  23088. /*
  23089. ** Deinitialize this module.
  23090. */
  23091. static void memsys3Shutdown(void *NotUsed){
  23092. UNUSED_PARAMETER(NotUsed);
  23093. mem3.mutex = 0;
  23094. return;
  23095. }
  23096. /*
  23097. ** Open the file indicated and write a log of all unfreed memory
  23098. ** allocations into that log.
  23099. */
  23100. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  23101. #ifdef SQLITE_DEBUG
  23102. FILE *out;
  23103. u32 i, j;
  23104. u32 size;
  23105. if( zFilename==0 || zFilename[0]==0 ){
  23106. out = stdout;
  23107. }else{
  23108. out = fopen(zFilename, "w");
  23109. if( out==0 ){
  23110. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  23111. zFilename);
  23112. return;
  23113. }
  23114. }
  23115. memsys3Enter();
  23116. fprintf(out, "CHUNKS:\n");
  23117. for(i=1; i<=mem3.nPool; i+=size/4){
  23118. size = mem3.aPool[i-1].u.hdr.size4x;
  23119. if( size/4<=1 ){
  23120. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  23121. assert( 0 );
  23122. break;
  23123. }
  23124. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  23125. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  23126. assert( 0 );
  23127. break;
  23128. }
  23129. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  23130. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  23131. assert( 0 );
  23132. break;
  23133. }
  23134. if( size&1 ){
  23135. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  23136. }else{
  23137. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  23138. i==mem3.iMaster ? " **master**" : "");
  23139. }
  23140. }
  23141. for(i=0; i<MX_SMALL-1; i++){
  23142. if( mem3.aiSmall[i]==0 ) continue;
  23143. fprintf(out, "small(%2d):", i);
  23144. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  23145. fprintf(out, " %p(%d)", &mem3.aPool[j],
  23146. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  23147. }
  23148. fprintf(out, "\n");
  23149. }
  23150. for(i=0; i<N_HASH; i++){
  23151. if( mem3.aiHash[i]==0 ) continue;
  23152. fprintf(out, "hash(%2d):", i);
  23153. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  23154. fprintf(out, " %p(%d)", &mem3.aPool[j],
  23155. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  23156. }
  23157. fprintf(out, "\n");
  23158. }
  23159. fprintf(out, "master=%d\n", mem3.iMaster);
  23160. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  23161. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  23162. sqlite3_mutex_leave(mem3.mutex);
  23163. if( out==stdout ){
  23164. fflush(stdout);
  23165. }else{
  23166. fclose(out);
  23167. }
  23168. #else
  23169. UNUSED_PARAMETER(zFilename);
  23170. #endif
  23171. }
  23172. /*
  23173. ** This routine is the only routine in this file with external
  23174. ** linkage.
  23175. **
  23176. ** Populate the low-level memory allocation function pointers in
  23177. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  23178. ** arguments specify the block of memory to manage.
  23179. **
  23180. ** This routine is only called by sqlite3_config(), and therefore
  23181. ** is not required to be threadsafe (it is not).
  23182. */
  23183. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  23184. static const sqlite3_mem_methods mempoolMethods = {
  23185. memsys3Malloc,
  23186. memsys3Free,
  23187. memsys3Realloc,
  23188. memsys3Size,
  23189. memsys3Roundup,
  23190. memsys3Init,
  23191. memsys3Shutdown,
  23192. 0
  23193. };
  23194. return &mempoolMethods;
  23195. }
  23196. #endif /* SQLITE_ENABLE_MEMSYS3 */
  23197. /************** End of mem3.c ************************************************/
  23198. /************** Begin file mem5.c ********************************************/
  23199. /*
  23200. ** 2007 October 14
  23201. **
  23202. ** The author disclaims copyright to this source code. In place of
  23203. ** a legal notice, here is a blessing:
  23204. **
  23205. ** May you do good and not evil.
  23206. ** May you find forgiveness for yourself and forgive others.
  23207. ** May you share freely, never taking more than you give.
  23208. **
  23209. *************************************************************************
  23210. ** This file contains the C functions that implement a memory
  23211. ** allocation subsystem for use by SQLite.
  23212. **
  23213. ** This version of the memory allocation subsystem omits all
  23214. ** use of malloc(). The application gives SQLite a block of memory
  23215. ** before calling sqlite3_initialize() from which allocations
  23216. ** are made and returned by the xMalloc() and xRealloc()
  23217. ** implementations. Once sqlite3_initialize() has been called,
  23218. ** the amount of memory available to SQLite is fixed and cannot
  23219. ** be changed.
  23220. **
  23221. ** This version of the memory allocation subsystem is included
  23222. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  23223. **
  23224. ** This memory allocator uses the following algorithm:
  23225. **
  23226. ** 1. All memory allocation sizes are rounded up to a power of 2.
  23227. **
  23228. ** 2. If two adjacent free blocks are the halves of a larger block,
  23229. ** then the two blocks are coalesced into the single larger block.
  23230. **
  23231. ** 3. New memory is allocated from the first available free block.
  23232. **
  23233. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  23234. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  23235. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  23236. **
  23237. ** Let n be the size of the largest allocation divided by the minimum
  23238. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  23239. ** be the maximum amount of memory ever outstanding at one time. Let
  23240. ** N be the total amount of memory available for allocation. Robson
  23241. ** proved that this memory allocator will never breakdown due to
  23242. ** fragmentation as long as the following constraint holds:
  23243. **
  23244. ** N >= M*(1 + log2(n)/2) - n + 1
  23245. **
  23246. ** The sqlite3_status() logic tracks the maximum values of n and M so
  23247. ** that an application can, at any time, verify this constraint.
  23248. */
  23249. /* #include "sqliteInt.h" */
  23250. /*
  23251. ** This version of the memory allocator is used only when
  23252. ** SQLITE_ENABLE_MEMSYS5 is defined.
  23253. */
  23254. #ifdef SQLITE_ENABLE_MEMSYS5
  23255. /*
  23256. ** A minimum allocation is an instance of the following structure.
  23257. ** Larger allocations are an array of these structures where the
  23258. ** size of the array is a power of 2.
  23259. **
  23260. ** The size of this object must be a power of two. That fact is
  23261. ** verified in memsys5Init().
  23262. */
  23263. typedef struct Mem5Link Mem5Link;
  23264. struct Mem5Link {
  23265. int next; /* Index of next free chunk */
  23266. int prev; /* Index of previous free chunk */
  23267. };
  23268. /*
  23269. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  23270. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  23271. ** it is not actually possible to reach this limit.
  23272. */
  23273. #define LOGMAX 30
  23274. /*
  23275. ** Masks used for mem5.aCtrl[] elements.
  23276. */
  23277. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  23278. #define CTRL_FREE 0x20 /* True if not checked out */
  23279. /*
  23280. ** All of the static variables used by this module are collected
  23281. ** into a single structure named "mem5". This is to keep the
  23282. ** static variables organized and to reduce namespace pollution
  23283. ** when this module is combined with other in the amalgamation.
  23284. */
  23285. static SQLITE_WSD struct Mem5Global {
  23286. /*
  23287. ** Memory available for allocation
  23288. */
  23289. int szAtom; /* Smallest possible allocation in bytes */
  23290. int nBlock; /* Number of szAtom sized blocks in zPool */
  23291. u8 *zPool; /* Memory available to be allocated */
  23292. /*
  23293. ** Mutex to control access to the memory allocation subsystem.
  23294. */
  23295. sqlite3_mutex *mutex;
  23296. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23297. /*
  23298. ** Performance statistics
  23299. */
  23300. u64 nAlloc; /* Total number of calls to malloc */
  23301. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  23302. u64 totalExcess; /* Total internal fragmentation */
  23303. u32 currentOut; /* Current checkout, including internal fragmentation */
  23304. u32 currentCount; /* Current number of distinct checkouts */
  23305. u32 maxOut; /* Maximum instantaneous currentOut */
  23306. u32 maxCount; /* Maximum instantaneous currentCount */
  23307. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  23308. #endif
  23309. /*
  23310. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  23311. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  23312. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
  23313. */
  23314. int aiFreelist[LOGMAX+1];
  23315. /*
  23316. ** Space for tracking which blocks are checked out and the size
  23317. ** of each block. One byte per block.
  23318. */
  23319. u8 *aCtrl;
  23320. } mem5;
  23321. /*
  23322. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  23323. */
  23324. #define mem5 GLOBAL(struct Mem5Global, mem5)
  23325. /*
  23326. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  23327. ** structures, return a pointer to the idx-th such link.
  23328. */
  23329. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  23330. /*
  23331. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  23332. ** on. It should be found on mem5.aiFreelist[iLogsize].
  23333. */
  23334. static void memsys5Unlink(int i, int iLogsize){
  23335. int next, prev;
  23336. assert( i>=0 && i<mem5.nBlock );
  23337. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  23338. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  23339. next = MEM5LINK(i)->next;
  23340. prev = MEM5LINK(i)->prev;
  23341. if( prev<0 ){
  23342. mem5.aiFreelist[iLogsize] = next;
  23343. }else{
  23344. MEM5LINK(prev)->next = next;
  23345. }
  23346. if( next>=0 ){
  23347. MEM5LINK(next)->prev = prev;
  23348. }
  23349. }
  23350. /*
  23351. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  23352. ** free list.
  23353. */
  23354. static void memsys5Link(int i, int iLogsize){
  23355. int x;
  23356. assert( sqlite3_mutex_held(mem5.mutex) );
  23357. assert( i>=0 && i<mem5.nBlock );
  23358. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  23359. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  23360. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  23361. MEM5LINK(i)->prev = -1;
  23362. if( x>=0 ){
  23363. assert( x<mem5.nBlock );
  23364. MEM5LINK(x)->prev = i;
  23365. }
  23366. mem5.aiFreelist[iLogsize] = i;
  23367. }
  23368. /*
  23369. ** Obtain or release the mutex needed to access global data structures.
  23370. */
  23371. static void memsys5Enter(void){
  23372. sqlite3_mutex_enter(mem5.mutex);
  23373. }
  23374. static void memsys5Leave(void){
  23375. sqlite3_mutex_leave(mem5.mutex);
  23376. }
  23377. /*
  23378. ** Return the size of an outstanding allocation, in bytes.
  23379. ** This only works for chunks that are currently checked out.
  23380. */
  23381. static int memsys5Size(void *p){
  23382. int iSize, i;
  23383. assert( p!=0 );
  23384. i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  23385. assert( i>=0 && i<mem5.nBlock );
  23386. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  23387. return iSize;
  23388. }
  23389. /*
  23390. ** Return a block of memory of at least nBytes in size.
  23391. ** Return NULL if unable. Return NULL if nBytes==0.
  23392. **
  23393. ** The caller guarantees that nByte is positive.
  23394. **
  23395. ** The caller has obtained a mutex prior to invoking this
  23396. ** routine so there is never any chance that two or more
  23397. ** threads can be in this routine at the same time.
  23398. */
  23399. static void *memsys5MallocUnsafe(int nByte){
  23400. int i; /* Index of a mem5.aPool[] slot */
  23401. int iBin; /* Index into mem5.aiFreelist[] */
  23402. int iFullSz; /* Size of allocation rounded up to power of 2 */
  23403. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  23404. /* nByte must be a positive */
  23405. assert( nByte>0 );
  23406. /* No more than 1GiB per allocation */
  23407. if( nByte > 0x40000000 ) return 0;
  23408. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23409. /* Keep track of the maximum allocation request. Even unfulfilled
  23410. ** requests are counted */
  23411. if( (u32)nByte>mem5.maxRequest ){
  23412. mem5.maxRequest = nByte;
  23413. }
  23414. #endif
  23415. /* Round nByte up to the next valid power of two */
  23416. for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
  23417. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  23418. ** block. If not, then split a block of the next larger power of
  23419. ** two in order to create a new free block of size iLogsize.
  23420. */
  23421. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  23422. if( iBin>LOGMAX ){
  23423. testcase( sqlite3GlobalConfig.xLog!=0 );
  23424. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  23425. return 0;
  23426. }
  23427. i = mem5.aiFreelist[iBin];
  23428. memsys5Unlink(i, iBin);
  23429. while( iBin>iLogsize ){
  23430. int newSize;
  23431. iBin--;
  23432. newSize = 1 << iBin;
  23433. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  23434. memsys5Link(i+newSize, iBin);
  23435. }
  23436. mem5.aCtrl[i] = iLogsize;
  23437. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23438. /* Update allocator performance statistics. */
  23439. mem5.nAlloc++;
  23440. mem5.totalAlloc += iFullSz;
  23441. mem5.totalExcess += iFullSz - nByte;
  23442. mem5.currentCount++;
  23443. mem5.currentOut += iFullSz;
  23444. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  23445. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  23446. #endif
  23447. #ifdef SQLITE_DEBUG
  23448. /* Make sure the allocated memory does not assume that it is set to zero
  23449. ** or retains a value from a previous allocation */
  23450. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  23451. #endif
  23452. /* Return a pointer to the allocated memory. */
  23453. return (void*)&mem5.zPool[i*mem5.szAtom];
  23454. }
  23455. /*
  23456. ** Free an outstanding memory allocation.
  23457. */
  23458. static void memsys5FreeUnsafe(void *pOld){
  23459. u32 size, iLogsize;
  23460. int iBlock;
  23461. /* Set iBlock to the index of the block pointed to by pOld in
  23462. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  23463. */
  23464. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  23465. /* Check that the pointer pOld points to a valid, non-free block. */
  23466. assert( iBlock>=0 && iBlock<mem5.nBlock );
  23467. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  23468. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  23469. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  23470. size = 1<<iLogsize;
  23471. assert( iBlock+size-1<(u32)mem5.nBlock );
  23472. mem5.aCtrl[iBlock] |= CTRL_FREE;
  23473. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  23474. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  23475. assert( mem5.currentCount>0 );
  23476. assert( mem5.currentOut>=(size*mem5.szAtom) );
  23477. mem5.currentCount--;
  23478. mem5.currentOut -= size*mem5.szAtom;
  23479. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  23480. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  23481. #endif
  23482. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  23483. while( ALWAYS(iLogsize<LOGMAX) ){
  23484. int iBuddy;
  23485. if( (iBlock>>iLogsize) & 1 ){
  23486. iBuddy = iBlock - size;
  23487. assert( iBuddy>=0 );
  23488. }else{
  23489. iBuddy = iBlock + size;
  23490. if( iBuddy>=mem5.nBlock ) break;
  23491. }
  23492. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  23493. memsys5Unlink(iBuddy, iLogsize);
  23494. iLogsize++;
  23495. if( iBuddy<iBlock ){
  23496. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  23497. mem5.aCtrl[iBlock] = 0;
  23498. iBlock = iBuddy;
  23499. }else{
  23500. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  23501. mem5.aCtrl[iBuddy] = 0;
  23502. }
  23503. size *= 2;
  23504. }
  23505. #ifdef SQLITE_DEBUG
  23506. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  23507. ** not used after being freed */
  23508. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  23509. #endif
  23510. memsys5Link(iBlock, iLogsize);
  23511. }
  23512. /*
  23513. ** Allocate nBytes of memory.
  23514. */
  23515. static void *memsys5Malloc(int nBytes){
  23516. sqlite3_int64 *p = 0;
  23517. if( nBytes>0 ){
  23518. memsys5Enter();
  23519. p = memsys5MallocUnsafe(nBytes);
  23520. memsys5Leave();
  23521. }
  23522. return (void*)p;
  23523. }
  23524. /*
  23525. ** Free memory.
  23526. **
  23527. ** The outer layer memory allocator prevents this routine from
  23528. ** being called with pPrior==0.
  23529. */
  23530. static void memsys5Free(void *pPrior){
  23531. assert( pPrior!=0 );
  23532. memsys5Enter();
  23533. memsys5FreeUnsafe(pPrior);
  23534. memsys5Leave();
  23535. }
  23536. /*
  23537. ** Change the size of an existing memory allocation.
  23538. **
  23539. ** The outer layer memory allocator prevents this routine from
  23540. ** being called with pPrior==0.
  23541. **
  23542. ** nBytes is always a value obtained from a prior call to
  23543. ** memsys5Round(). Hence nBytes is always a non-negative power
  23544. ** of two. If nBytes==0 that means that an oversize allocation
  23545. ** (an allocation larger than 0x40000000) was requested and this
  23546. ** routine should return 0 without freeing pPrior.
  23547. */
  23548. static void *memsys5Realloc(void *pPrior, int nBytes){
  23549. int nOld;
  23550. void *p;
  23551. assert( pPrior!=0 );
  23552. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  23553. assert( nBytes>=0 );
  23554. if( nBytes==0 ){
  23555. return 0;
  23556. }
  23557. nOld = memsys5Size(pPrior);
  23558. if( nBytes<=nOld ){
  23559. return pPrior;
  23560. }
  23561. p = memsys5Malloc(nBytes);
  23562. if( p ){
  23563. memcpy(p, pPrior, nOld);
  23564. memsys5Free(pPrior);
  23565. }
  23566. return p;
  23567. }
  23568. /*
  23569. ** Round up a request size to the next valid allocation size. If
  23570. ** the allocation is too large to be handled by this allocation system,
  23571. ** return 0.
  23572. **
  23573. ** All allocations must be a power of two and must be expressed by a
  23574. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  23575. ** or 1073741824 bytes.
  23576. */
  23577. static int memsys5Roundup(int n){
  23578. int iFullSz;
  23579. if( n > 0x40000000 ) return 0;
  23580. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  23581. return iFullSz;
  23582. }
  23583. /*
  23584. ** Return the ceiling of the logarithm base 2 of iValue.
  23585. **
  23586. ** Examples: memsys5Log(1) -> 0
  23587. ** memsys5Log(2) -> 1
  23588. ** memsys5Log(4) -> 2
  23589. ** memsys5Log(5) -> 3
  23590. ** memsys5Log(8) -> 3
  23591. ** memsys5Log(9) -> 4
  23592. */
  23593. static int memsys5Log(int iValue){
  23594. int iLog;
  23595. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  23596. return iLog;
  23597. }
  23598. /*
  23599. ** Initialize the memory allocator.
  23600. **
  23601. ** This routine is not threadsafe. The caller must be holding a mutex
  23602. ** to prevent multiple threads from entering at the same time.
  23603. */
  23604. static int memsys5Init(void *NotUsed){
  23605. int ii; /* Loop counter */
  23606. int nByte; /* Number of bytes of memory available to this allocator */
  23607. u8 *zByte; /* Memory usable by this allocator */
  23608. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  23609. int iOffset; /* An offset into mem5.aCtrl[] */
  23610. UNUSED_PARAMETER(NotUsed);
  23611. /* For the purposes of this routine, disable the mutex */
  23612. mem5.mutex = 0;
  23613. /* The size of a Mem5Link object must be a power of two. Verify that
  23614. ** this is case.
  23615. */
  23616. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  23617. nByte = sqlite3GlobalConfig.nHeap;
  23618. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  23619. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  23620. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  23621. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  23622. mem5.szAtom = (1<<nMinLog);
  23623. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  23624. mem5.szAtom = mem5.szAtom << 1;
  23625. }
  23626. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  23627. mem5.zPool = zByte;
  23628. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  23629. for(ii=0; ii<=LOGMAX; ii++){
  23630. mem5.aiFreelist[ii] = -1;
  23631. }
  23632. iOffset = 0;
  23633. for(ii=LOGMAX; ii>=0; ii--){
  23634. int nAlloc = (1<<ii);
  23635. if( (iOffset+nAlloc)<=mem5.nBlock ){
  23636. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  23637. memsys5Link(iOffset, ii);
  23638. iOffset += nAlloc;
  23639. }
  23640. assert((iOffset+nAlloc)>mem5.nBlock);
  23641. }
  23642. /* If a mutex is required for normal operation, allocate one */
  23643. if( sqlite3GlobalConfig.bMemstat==0 ){
  23644. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  23645. }
  23646. return SQLITE_OK;
  23647. }
  23648. /*
  23649. ** Deinitialize this module.
  23650. */
  23651. static void memsys5Shutdown(void *NotUsed){
  23652. UNUSED_PARAMETER(NotUsed);
  23653. mem5.mutex = 0;
  23654. return;
  23655. }
  23656. #ifdef SQLITE_TEST
  23657. /*
  23658. ** Open the file indicated and write a log of all unfreed memory
  23659. ** allocations into that log.
  23660. */
  23661. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  23662. FILE *out;
  23663. int i, j, n;
  23664. int nMinLog;
  23665. if( zFilename==0 || zFilename[0]==0 ){
  23666. out = stdout;
  23667. }else{
  23668. out = fopen(zFilename, "w");
  23669. if( out==0 ){
  23670. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  23671. zFilename);
  23672. return;
  23673. }
  23674. }
  23675. memsys5Enter();
  23676. nMinLog = memsys5Log(mem5.szAtom);
  23677. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  23678. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  23679. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  23680. }
  23681. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  23682. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  23683. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  23684. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  23685. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  23686. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  23687. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  23688. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  23689. memsys5Leave();
  23690. if( out==stdout ){
  23691. fflush(stdout);
  23692. }else{
  23693. fclose(out);
  23694. }
  23695. }
  23696. #endif
  23697. /*
  23698. ** This routine is the only routine in this file with external
  23699. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  23700. ** struct populated with the memsys5 methods.
  23701. */
  23702. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  23703. static const sqlite3_mem_methods memsys5Methods = {
  23704. memsys5Malloc,
  23705. memsys5Free,
  23706. memsys5Realloc,
  23707. memsys5Size,
  23708. memsys5Roundup,
  23709. memsys5Init,
  23710. memsys5Shutdown,
  23711. 0
  23712. };
  23713. return &memsys5Methods;
  23714. }
  23715. #endif /* SQLITE_ENABLE_MEMSYS5 */
  23716. /************** End of mem5.c ************************************************/
  23717. /************** Begin file mutex.c *******************************************/
  23718. /*
  23719. ** 2007 August 14
  23720. **
  23721. ** The author disclaims copyright to this source code. In place of
  23722. ** a legal notice, here is a blessing:
  23723. **
  23724. ** May you do good and not evil.
  23725. ** May you find forgiveness for yourself and forgive others.
  23726. ** May you share freely, never taking more than you give.
  23727. **
  23728. *************************************************************************
  23729. ** This file contains the C functions that implement mutexes.
  23730. **
  23731. ** This file contains code that is common across all mutex implementations.
  23732. */
  23733. /* #include "sqliteInt.h" */
  23734. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  23735. /*
  23736. ** For debugging purposes, record when the mutex subsystem is initialized
  23737. ** and uninitialized so that we can assert() if there is an attempt to
  23738. ** allocate a mutex while the system is uninitialized.
  23739. */
  23740. static SQLITE_WSD int mutexIsInit = 0;
  23741. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  23742. #ifndef SQLITE_MUTEX_OMIT
  23743. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  23744. /*
  23745. ** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
  23746. ** the implementation of a wrapper around the system default mutex
  23747. ** implementation (sqlite3DefaultMutex()).
  23748. **
  23749. ** Most calls are passed directly through to the underlying default
  23750. ** mutex implementation. Except, if a mutex is configured by calling
  23751. ** sqlite3MutexWarnOnContention() on it, then if contention is ever
  23752. ** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
  23753. **
  23754. ** This type of mutex is used as the database handle mutex when testing
  23755. ** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
  23756. */
  23757. /*
  23758. ** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
  23759. ** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
  23760. ** allocated by the system mutex implementation. Variable iType is usually set
  23761. ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
  23762. ** or one of the static mutex identifiers. Or, if this is a recursive mutex
  23763. ** that has been configured using sqlite3MutexWarnOnContention(), it is
  23764. ** set to SQLITE_MUTEX_WARNONCONTENTION.
  23765. */
  23766. typedef struct CheckMutex CheckMutex;
  23767. struct CheckMutex {
  23768. int iType;
  23769. sqlite3_mutex *mutex;
  23770. };
  23771. #define SQLITE_MUTEX_WARNONCONTENTION (-1)
  23772. /*
  23773. ** Pointer to real mutex methods object used by the CheckMutex
  23774. ** implementation. Set by checkMutexInit().
  23775. */
  23776. static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
  23777. #ifdef SQLITE_DEBUG
  23778. static int checkMutexHeld(sqlite3_mutex *p){
  23779. return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
  23780. }
  23781. static int checkMutexNotheld(sqlite3_mutex *p){
  23782. return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
  23783. }
  23784. #endif
  23785. /*
  23786. ** Initialize and deinitialize the mutex subsystem.
  23787. */
  23788. static int checkMutexInit(void){
  23789. pGlobalMutexMethods = sqlite3DefaultMutex();
  23790. return SQLITE_OK;
  23791. }
  23792. static int checkMutexEnd(void){
  23793. pGlobalMutexMethods = 0;
  23794. return SQLITE_OK;
  23795. }
  23796. /*
  23797. ** Allocate a mutex.
  23798. */
  23799. static sqlite3_mutex *checkMutexAlloc(int iType){
  23800. static CheckMutex staticMutexes[] = {
  23801. {2, 0}, {3, 0}, {4, 0}, {5, 0},
  23802. {6, 0}, {7, 0}, {8, 0}, {9, 0},
  23803. {10, 0}, {11, 0}, {12, 0}, {13, 0}
  23804. };
  23805. CheckMutex *p = 0;
  23806. assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
  23807. if( iType<2 ){
  23808. p = sqlite3MallocZero(sizeof(CheckMutex));
  23809. if( p==0 ) return 0;
  23810. p->iType = iType;
  23811. }else{
  23812. #ifdef SQLITE_ENABLE_API_ARMOR
  23813. if( iType-2>=ArraySize(staticMutexes) ){
  23814. (void)SQLITE_MISUSE_BKPT;
  23815. return 0;
  23816. }
  23817. #endif
  23818. p = &staticMutexes[iType-2];
  23819. }
  23820. if( p->mutex==0 ){
  23821. p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
  23822. if( p->mutex==0 ){
  23823. if( iType<2 ){
  23824. sqlite3_free(p);
  23825. }
  23826. p = 0;
  23827. }
  23828. }
  23829. return (sqlite3_mutex*)p;
  23830. }
  23831. /*
  23832. ** Free a mutex.
  23833. */
  23834. static void checkMutexFree(sqlite3_mutex *p){
  23835. assert( SQLITE_MUTEX_RECURSIVE<2 );
  23836. assert( SQLITE_MUTEX_FAST<2 );
  23837. assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
  23838. #if SQLITE_ENABLE_API_ARMOR
  23839. if( ((CheckMutex*)p)->iType<2 )
  23840. #endif
  23841. {
  23842. CheckMutex *pCheck = (CheckMutex*)p;
  23843. pGlobalMutexMethods->xMutexFree(pCheck->mutex);
  23844. sqlite3_free(pCheck);
  23845. }
  23846. #ifdef SQLITE_ENABLE_API_ARMOR
  23847. else{
  23848. (void)SQLITE_MISUSE_BKPT;
  23849. }
  23850. #endif
  23851. }
  23852. /*
  23853. ** Enter the mutex.
  23854. */
  23855. static void checkMutexEnter(sqlite3_mutex *p){
  23856. CheckMutex *pCheck = (CheckMutex*)p;
  23857. if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
  23858. if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
  23859. return;
  23860. }
  23861. sqlite3_log(SQLITE_MISUSE,
  23862. "illegal multi-threaded access to database connection"
  23863. );
  23864. }
  23865. pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
  23866. }
  23867. /*
  23868. ** Enter the mutex (do not block).
  23869. */
  23870. static int checkMutexTry(sqlite3_mutex *p){
  23871. CheckMutex *pCheck = (CheckMutex*)p;
  23872. return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
  23873. }
  23874. /*
  23875. ** Leave the mutex.
  23876. */
  23877. static void checkMutexLeave(sqlite3_mutex *p){
  23878. CheckMutex *pCheck = (CheckMutex*)p;
  23879. pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
  23880. }
  23881. sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
  23882. static const sqlite3_mutex_methods sMutex = {
  23883. checkMutexInit,
  23884. checkMutexEnd,
  23885. checkMutexAlloc,
  23886. checkMutexFree,
  23887. checkMutexEnter,
  23888. checkMutexTry,
  23889. checkMutexLeave,
  23890. #ifdef SQLITE_DEBUG
  23891. checkMutexHeld,
  23892. checkMutexNotheld
  23893. #else
  23894. 0,
  23895. 0
  23896. #endif
  23897. };
  23898. return &sMutex;
  23899. }
  23900. /*
  23901. ** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
  23902. ** one on which there should be no contention.
  23903. */
  23904. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
  23905. if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
  23906. CheckMutex *pCheck = (CheckMutex*)p;
  23907. assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
  23908. pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
  23909. }
  23910. }
  23911. #endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
  23912. /*
  23913. ** Initialize the mutex system.
  23914. */
  23915. SQLITE_PRIVATE int sqlite3MutexInit(void){
  23916. int rc = SQLITE_OK;
  23917. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  23918. /* If the xMutexAlloc method has not been set, then the user did not
  23919. ** install a mutex implementation via sqlite3_config() prior to
  23920. ** sqlite3_initialize() being called. This block copies pointers to
  23921. ** the default implementation into the sqlite3GlobalConfig structure.
  23922. */
  23923. sqlite3_mutex_methods const *pFrom;
  23924. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  23925. if( sqlite3GlobalConfig.bCoreMutex ){
  23926. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  23927. pFrom = multiThreadedCheckMutex();
  23928. #else
  23929. pFrom = sqlite3DefaultMutex();
  23930. #endif
  23931. }else{
  23932. pFrom = sqlite3NoopMutex();
  23933. }
  23934. pTo->xMutexInit = pFrom->xMutexInit;
  23935. pTo->xMutexEnd = pFrom->xMutexEnd;
  23936. pTo->xMutexFree = pFrom->xMutexFree;
  23937. pTo->xMutexEnter = pFrom->xMutexEnter;
  23938. pTo->xMutexTry = pFrom->xMutexTry;
  23939. pTo->xMutexLeave = pFrom->xMutexLeave;
  23940. pTo->xMutexHeld = pFrom->xMutexHeld;
  23941. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  23942. sqlite3MemoryBarrier();
  23943. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  23944. }
  23945. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  23946. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  23947. #ifdef SQLITE_DEBUG
  23948. GLOBAL(int, mutexIsInit) = 1;
  23949. #endif
  23950. return rc;
  23951. }
  23952. /*
  23953. ** Shutdown the mutex system. This call frees resources allocated by
  23954. ** sqlite3MutexInit().
  23955. */
  23956. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  23957. int rc = SQLITE_OK;
  23958. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  23959. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  23960. }
  23961. #ifdef SQLITE_DEBUG
  23962. GLOBAL(int, mutexIsInit) = 0;
  23963. #endif
  23964. return rc;
  23965. }
  23966. /*
  23967. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  23968. */
  23969. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  23970. #ifndef SQLITE_OMIT_AUTOINIT
  23971. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  23972. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  23973. #endif
  23974. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  23975. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  23976. }
  23977. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  23978. if( !sqlite3GlobalConfig.bCoreMutex ){
  23979. return 0;
  23980. }
  23981. assert( GLOBAL(int, mutexIsInit) );
  23982. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  23983. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  23984. }
  23985. /*
  23986. ** Free a dynamic mutex.
  23987. */
  23988. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  23989. if( p ){
  23990. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  23991. sqlite3GlobalConfig.mutex.xMutexFree(p);
  23992. }
  23993. }
  23994. /*
  23995. ** Obtain the mutex p. If some other thread already has the mutex, block
  23996. ** until it can be obtained.
  23997. */
  23998. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  23999. if( p ){
  24000. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  24001. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  24002. }
  24003. }
  24004. /*
  24005. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  24006. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  24007. */
  24008. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  24009. int rc = SQLITE_OK;
  24010. if( p ){
  24011. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  24012. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  24013. }
  24014. return rc;
  24015. }
  24016. /*
  24017. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  24018. ** entered by the same thread. The behavior is undefined if the mutex
  24019. ** is not currently entered. If a NULL pointer is passed as an argument
  24020. ** this function is a no-op.
  24021. */
  24022. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  24023. if( p ){
  24024. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  24025. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  24026. }
  24027. }
  24028. #ifndef NDEBUG
  24029. /*
  24030. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24031. ** intended for use inside assert() statements.
  24032. */
  24033. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  24034. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  24035. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  24036. }
  24037. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  24038. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  24039. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  24040. }
  24041. #endif
  24042. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  24043. /************** End of mutex.c ***********************************************/
  24044. /************** Begin file mutex_noop.c **************************************/
  24045. /*
  24046. ** 2008 October 07
  24047. **
  24048. ** The author disclaims copyright to this source code. In place of
  24049. ** a legal notice, here is a blessing:
  24050. **
  24051. ** May you do good and not evil.
  24052. ** May you find forgiveness for yourself and forgive others.
  24053. ** May you share freely, never taking more than you give.
  24054. **
  24055. *************************************************************************
  24056. ** This file contains the C functions that implement mutexes.
  24057. **
  24058. ** This implementation in this file does not provide any mutual
  24059. ** exclusion and is thus suitable for use only in applications
  24060. ** that use SQLite in a single thread. The routines defined
  24061. ** here are place-holders. Applications can substitute working
  24062. ** mutex routines at start-time using the
  24063. **
  24064. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  24065. **
  24066. ** interface.
  24067. **
  24068. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  24069. ** that does error checking on mutexes to make sure they are being
  24070. ** called correctly.
  24071. */
  24072. /* #include "sqliteInt.h" */
  24073. #ifndef SQLITE_MUTEX_OMIT
  24074. #ifndef SQLITE_DEBUG
  24075. /*
  24076. ** Stub routines for all mutex methods.
  24077. **
  24078. ** This routines provide no mutual exclusion or error checking.
  24079. */
  24080. static int noopMutexInit(void){ return SQLITE_OK; }
  24081. static int noopMutexEnd(void){ return SQLITE_OK; }
  24082. static sqlite3_mutex *noopMutexAlloc(int id){
  24083. UNUSED_PARAMETER(id);
  24084. return (sqlite3_mutex*)8;
  24085. }
  24086. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  24087. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  24088. static int noopMutexTry(sqlite3_mutex *p){
  24089. UNUSED_PARAMETER(p);
  24090. return SQLITE_OK;
  24091. }
  24092. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  24093. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  24094. static const sqlite3_mutex_methods sMutex = {
  24095. noopMutexInit,
  24096. noopMutexEnd,
  24097. noopMutexAlloc,
  24098. noopMutexFree,
  24099. noopMutexEnter,
  24100. noopMutexTry,
  24101. noopMutexLeave,
  24102. 0,
  24103. 0,
  24104. };
  24105. return &sMutex;
  24106. }
  24107. #endif /* !SQLITE_DEBUG */
  24108. #ifdef SQLITE_DEBUG
  24109. /*
  24110. ** In this implementation, error checking is provided for testing
  24111. ** and debugging purposes. The mutexes still do not provide any
  24112. ** mutual exclusion.
  24113. */
  24114. /*
  24115. ** The mutex object
  24116. */
  24117. typedef struct sqlite3_debug_mutex {
  24118. int id; /* The mutex type */
  24119. int cnt; /* Number of entries without a matching leave */
  24120. } sqlite3_debug_mutex;
  24121. /*
  24122. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24123. ** intended for use inside assert() statements.
  24124. */
  24125. static int debugMutexHeld(sqlite3_mutex *pX){
  24126. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24127. return p==0 || p->cnt>0;
  24128. }
  24129. static int debugMutexNotheld(sqlite3_mutex *pX){
  24130. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24131. return p==0 || p->cnt==0;
  24132. }
  24133. /*
  24134. ** Initialize and deinitialize the mutex subsystem.
  24135. */
  24136. static int debugMutexInit(void){ return SQLITE_OK; }
  24137. static int debugMutexEnd(void){ return SQLITE_OK; }
  24138. /*
  24139. ** The sqlite3_mutex_alloc() routine allocates a new
  24140. ** mutex and returns a pointer to it. If it returns NULL
  24141. ** that means that a mutex could not be allocated.
  24142. */
  24143. static sqlite3_mutex *debugMutexAlloc(int id){
  24144. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  24145. sqlite3_debug_mutex *pNew = 0;
  24146. switch( id ){
  24147. case SQLITE_MUTEX_FAST:
  24148. case SQLITE_MUTEX_RECURSIVE: {
  24149. pNew = sqlite3Malloc(sizeof(*pNew));
  24150. if( pNew ){
  24151. pNew->id = id;
  24152. pNew->cnt = 0;
  24153. }
  24154. break;
  24155. }
  24156. default: {
  24157. #ifdef SQLITE_ENABLE_API_ARMOR
  24158. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  24159. (void)SQLITE_MISUSE_BKPT;
  24160. return 0;
  24161. }
  24162. #endif
  24163. pNew = &aStatic[id-2];
  24164. pNew->id = id;
  24165. break;
  24166. }
  24167. }
  24168. return (sqlite3_mutex*)pNew;
  24169. }
  24170. /*
  24171. ** This routine deallocates a previously allocated mutex.
  24172. */
  24173. static void debugMutexFree(sqlite3_mutex *pX){
  24174. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24175. assert( p->cnt==0 );
  24176. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  24177. sqlite3_free(p);
  24178. }else{
  24179. #ifdef SQLITE_ENABLE_API_ARMOR
  24180. (void)SQLITE_MISUSE_BKPT;
  24181. #endif
  24182. }
  24183. }
  24184. /*
  24185. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  24186. ** to enter a mutex. If another thread is already within the mutex,
  24187. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  24188. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  24189. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  24190. ** be entered multiple times by the same thread. In such cases the,
  24191. ** mutex must be exited an equal number of times before another thread
  24192. ** can enter. If the same thread tries to enter any other kind of mutex
  24193. ** more than once, the behavior is undefined.
  24194. */
  24195. static void debugMutexEnter(sqlite3_mutex *pX){
  24196. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24197. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24198. p->cnt++;
  24199. }
  24200. static int debugMutexTry(sqlite3_mutex *pX){
  24201. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24202. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24203. p->cnt++;
  24204. return SQLITE_OK;
  24205. }
  24206. /*
  24207. ** The sqlite3_mutex_leave() routine exits a mutex that was
  24208. ** previously entered by the same thread. The behavior
  24209. ** is undefined if the mutex is not currently entered or
  24210. ** is not currently allocated. SQLite will never do either.
  24211. */
  24212. static void debugMutexLeave(sqlite3_mutex *pX){
  24213. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24214. assert( debugMutexHeld(pX) );
  24215. p->cnt--;
  24216. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24217. }
  24218. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  24219. static const sqlite3_mutex_methods sMutex = {
  24220. debugMutexInit,
  24221. debugMutexEnd,
  24222. debugMutexAlloc,
  24223. debugMutexFree,
  24224. debugMutexEnter,
  24225. debugMutexTry,
  24226. debugMutexLeave,
  24227. debugMutexHeld,
  24228. debugMutexNotheld
  24229. };
  24230. return &sMutex;
  24231. }
  24232. #endif /* SQLITE_DEBUG */
  24233. /*
  24234. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  24235. ** is used regardless of the run-time threadsafety setting.
  24236. */
  24237. #ifdef SQLITE_MUTEX_NOOP
  24238. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  24239. return sqlite3NoopMutex();
  24240. }
  24241. #endif /* defined(SQLITE_MUTEX_NOOP) */
  24242. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  24243. /************** End of mutex_noop.c ******************************************/
  24244. /************** Begin file mutex_unix.c **************************************/
  24245. /*
  24246. ** 2007 August 28
  24247. **
  24248. ** The author disclaims copyright to this source code. In place of
  24249. ** a legal notice, here is a blessing:
  24250. **
  24251. ** May you do good and not evil.
  24252. ** May you find forgiveness for yourself and forgive others.
  24253. ** May you share freely, never taking more than you give.
  24254. **
  24255. *************************************************************************
  24256. ** This file contains the C functions that implement mutexes for pthreads
  24257. */
  24258. /* #include "sqliteInt.h" */
  24259. /*
  24260. ** The code in this file is only used if we are compiling threadsafe
  24261. ** under unix with pthreads.
  24262. **
  24263. ** Note that this implementation requires a version of pthreads that
  24264. ** supports recursive mutexes.
  24265. */
  24266. #ifdef SQLITE_MUTEX_PTHREADS
  24267. #include <pthread.h>
  24268. /*
  24269. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  24270. ** are necessary under two condidtions: (1) Debug builds and (2) using
  24271. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  24272. */
  24273. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  24274. # define SQLITE_MUTEX_NREF 1
  24275. #else
  24276. # define SQLITE_MUTEX_NREF 0
  24277. #endif
  24278. /*
  24279. ** Each recursive mutex is an instance of the following structure.
  24280. */
  24281. struct sqlite3_mutex {
  24282. pthread_mutex_t mutex; /* Mutex controlling the lock */
  24283. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24284. int id; /* Mutex type */
  24285. #endif
  24286. #if SQLITE_MUTEX_NREF
  24287. volatile int nRef; /* Number of entrances */
  24288. volatile pthread_t owner; /* Thread that is within this mutex */
  24289. int trace; /* True to trace changes */
  24290. #endif
  24291. };
  24292. #if SQLITE_MUTEX_NREF
  24293. # define SQLITE3_MUTEX_INITIALIZER(id) \
  24294. {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}
  24295. #elif defined(SQLITE_ENABLE_API_ARMOR)
  24296. # define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }
  24297. #else
  24298. #define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }
  24299. #endif
  24300. /*
  24301. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24302. ** intended for use only inside assert() statements. On some platforms,
  24303. ** there might be race conditions that can cause these routines to
  24304. ** deliver incorrect results. In particular, if pthread_equal() is
  24305. ** not an atomic operation, then these routines might delivery
  24306. ** incorrect results. On most platforms, pthread_equal() is a
  24307. ** comparison of two integers and is therefore atomic. But we are
  24308. ** told that HPUX is not such a platform. If so, then these routines
  24309. ** will not always work correctly on HPUX.
  24310. **
  24311. ** On those platforms where pthread_equal() is not atomic, SQLite
  24312. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  24313. ** make sure no assert() statements are evaluated and hence these
  24314. ** routines are never called.
  24315. */
  24316. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  24317. static int pthreadMutexHeld(sqlite3_mutex *p){
  24318. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  24319. }
  24320. static int pthreadMutexNotheld(sqlite3_mutex *p){
  24321. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  24322. }
  24323. #endif
  24324. /*
  24325. ** Try to provide a memory barrier operation, needed for initialization
  24326. ** and also for the implementation of xShmBarrier in the VFS in cases
  24327. ** where SQLite is compiled without mutexes.
  24328. */
  24329. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  24330. #if defined(SQLITE_MEMORY_BARRIER)
  24331. SQLITE_MEMORY_BARRIER;
  24332. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  24333. __sync_synchronize();
  24334. #endif
  24335. }
  24336. /*
  24337. ** Initialize and deinitialize the mutex subsystem.
  24338. */
  24339. static int pthreadMutexInit(void){ return SQLITE_OK; }
  24340. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  24341. /*
  24342. ** The sqlite3_mutex_alloc() routine allocates a new
  24343. ** mutex and returns a pointer to it. If it returns NULL
  24344. ** that means that a mutex could not be allocated. SQLite
  24345. ** will unwind its stack and return an error. The argument
  24346. ** to sqlite3_mutex_alloc() is one of these integer constants:
  24347. **
  24348. ** <ul>
  24349. ** <li> SQLITE_MUTEX_FAST
  24350. ** <li> SQLITE_MUTEX_RECURSIVE
  24351. ** <li> SQLITE_MUTEX_STATIC_MASTER
  24352. ** <li> SQLITE_MUTEX_STATIC_MEM
  24353. ** <li> SQLITE_MUTEX_STATIC_OPEN
  24354. ** <li> SQLITE_MUTEX_STATIC_PRNG
  24355. ** <li> SQLITE_MUTEX_STATIC_LRU
  24356. ** <li> SQLITE_MUTEX_STATIC_PMEM
  24357. ** <li> SQLITE_MUTEX_STATIC_APP1
  24358. ** <li> SQLITE_MUTEX_STATIC_APP2
  24359. ** <li> SQLITE_MUTEX_STATIC_APP3
  24360. ** <li> SQLITE_MUTEX_STATIC_VFS1
  24361. ** <li> SQLITE_MUTEX_STATIC_VFS2
  24362. ** <li> SQLITE_MUTEX_STATIC_VFS3
  24363. ** </ul>
  24364. **
  24365. ** The first two constants cause sqlite3_mutex_alloc() to create
  24366. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  24367. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  24368. ** The mutex implementation does not need to make a distinction
  24369. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  24370. ** not want to. But SQLite will only request a recursive mutex in
  24371. ** cases where it really needs one. If a faster non-recursive mutex
  24372. ** implementation is available on the host platform, the mutex subsystem
  24373. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  24374. **
  24375. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  24376. ** a pointer to a static preexisting mutex. Six static mutexes are
  24377. ** used by the current version of SQLite. Future versions of SQLite
  24378. ** may add additional static mutexes. Static mutexes are for internal
  24379. ** use by SQLite only. Applications that use SQLite mutexes should
  24380. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  24381. ** SQLITE_MUTEX_RECURSIVE.
  24382. **
  24383. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  24384. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  24385. ** returns a different mutex on every call. But for the static
  24386. ** mutex types, the same mutex is returned on every call that has
  24387. ** the same type number.
  24388. */
  24389. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  24390. static sqlite3_mutex staticMutexes[] = {
  24391. SQLITE3_MUTEX_INITIALIZER(2),
  24392. SQLITE3_MUTEX_INITIALIZER(3),
  24393. SQLITE3_MUTEX_INITIALIZER(4),
  24394. SQLITE3_MUTEX_INITIALIZER(5),
  24395. SQLITE3_MUTEX_INITIALIZER(6),
  24396. SQLITE3_MUTEX_INITIALIZER(7),
  24397. SQLITE3_MUTEX_INITIALIZER(8),
  24398. SQLITE3_MUTEX_INITIALIZER(9),
  24399. SQLITE3_MUTEX_INITIALIZER(10),
  24400. SQLITE3_MUTEX_INITIALIZER(11),
  24401. SQLITE3_MUTEX_INITIALIZER(12),
  24402. SQLITE3_MUTEX_INITIALIZER(13)
  24403. };
  24404. sqlite3_mutex *p;
  24405. switch( iType ){
  24406. case SQLITE_MUTEX_RECURSIVE: {
  24407. p = sqlite3MallocZero( sizeof(*p) );
  24408. if( p ){
  24409. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24410. /* If recursive mutexes are not available, we will have to
  24411. ** build our own. See below. */
  24412. pthread_mutex_init(&p->mutex, 0);
  24413. #else
  24414. /* Use a recursive mutex if it is available */
  24415. pthread_mutexattr_t recursiveAttr;
  24416. pthread_mutexattr_init(&recursiveAttr);
  24417. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  24418. pthread_mutex_init(&p->mutex, &recursiveAttr);
  24419. pthread_mutexattr_destroy(&recursiveAttr);
  24420. #endif
  24421. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24422. p->id = SQLITE_MUTEX_RECURSIVE;
  24423. #endif
  24424. }
  24425. break;
  24426. }
  24427. case SQLITE_MUTEX_FAST: {
  24428. p = sqlite3MallocZero( sizeof(*p) );
  24429. if( p ){
  24430. pthread_mutex_init(&p->mutex, 0);
  24431. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24432. p->id = SQLITE_MUTEX_FAST;
  24433. #endif
  24434. }
  24435. break;
  24436. }
  24437. default: {
  24438. #ifdef SQLITE_ENABLE_API_ARMOR
  24439. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  24440. (void)SQLITE_MISUSE_BKPT;
  24441. return 0;
  24442. }
  24443. #endif
  24444. p = &staticMutexes[iType-2];
  24445. break;
  24446. }
  24447. }
  24448. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  24449. assert( p==0 || p->id==iType );
  24450. #endif
  24451. return p;
  24452. }
  24453. /*
  24454. ** This routine deallocates a previously
  24455. ** allocated mutex. SQLite is careful to deallocate every
  24456. ** mutex that it allocates.
  24457. */
  24458. static void pthreadMutexFree(sqlite3_mutex *p){
  24459. assert( p->nRef==0 );
  24460. #if SQLITE_ENABLE_API_ARMOR
  24461. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  24462. #endif
  24463. {
  24464. pthread_mutex_destroy(&p->mutex);
  24465. sqlite3_free(p);
  24466. }
  24467. #ifdef SQLITE_ENABLE_API_ARMOR
  24468. else{
  24469. (void)SQLITE_MISUSE_BKPT;
  24470. }
  24471. #endif
  24472. }
  24473. /*
  24474. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  24475. ** to enter a mutex. If another thread is already within the mutex,
  24476. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  24477. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  24478. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  24479. ** be entered multiple times by the same thread. In such cases the,
  24480. ** mutex must be exited an equal number of times before another thread
  24481. ** can enter. If the same thread tries to enter any other kind of mutex
  24482. ** more than once, the behavior is undefined.
  24483. */
  24484. static void pthreadMutexEnter(sqlite3_mutex *p){
  24485. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  24486. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24487. /* If recursive mutexes are not available, then we have to grow
  24488. ** our own. This implementation assumes that pthread_equal()
  24489. ** is atomic - that it cannot be deceived into thinking self
  24490. ** and p->owner are equal if p->owner changes between two values
  24491. ** that are not equal to self while the comparison is taking place.
  24492. ** This implementation also assumes a coherent cache - that
  24493. ** separate processes cannot read different values from the same
  24494. ** address at the same time. If either of these two conditions
  24495. ** are not met, then the mutexes will fail and problems will result.
  24496. */
  24497. {
  24498. pthread_t self = pthread_self();
  24499. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  24500. p->nRef++;
  24501. }else{
  24502. pthread_mutex_lock(&p->mutex);
  24503. assert( p->nRef==0 );
  24504. p->owner = self;
  24505. p->nRef = 1;
  24506. }
  24507. }
  24508. #else
  24509. /* Use the built-in recursive mutexes if they are available.
  24510. */
  24511. pthread_mutex_lock(&p->mutex);
  24512. #if SQLITE_MUTEX_NREF
  24513. assert( p->nRef>0 || p->owner==0 );
  24514. p->owner = pthread_self();
  24515. p->nRef++;
  24516. #endif
  24517. #endif
  24518. #ifdef SQLITE_DEBUG
  24519. if( p->trace ){
  24520. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  24521. }
  24522. #endif
  24523. }
  24524. static int pthreadMutexTry(sqlite3_mutex *p){
  24525. int rc;
  24526. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  24527. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24528. /* If recursive mutexes are not available, then we have to grow
  24529. ** our own. This implementation assumes that pthread_equal()
  24530. ** is atomic - that it cannot be deceived into thinking self
  24531. ** and p->owner are equal if p->owner changes between two values
  24532. ** that are not equal to self while the comparison is taking place.
  24533. ** This implementation also assumes a coherent cache - that
  24534. ** separate processes cannot read different values from the same
  24535. ** address at the same time. If either of these two conditions
  24536. ** are not met, then the mutexes will fail and problems will result.
  24537. */
  24538. {
  24539. pthread_t self = pthread_self();
  24540. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  24541. p->nRef++;
  24542. rc = SQLITE_OK;
  24543. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  24544. assert( p->nRef==0 );
  24545. p->owner = self;
  24546. p->nRef = 1;
  24547. rc = SQLITE_OK;
  24548. }else{
  24549. rc = SQLITE_BUSY;
  24550. }
  24551. }
  24552. #else
  24553. /* Use the built-in recursive mutexes if they are available.
  24554. */
  24555. if( pthread_mutex_trylock(&p->mutex)==0 ){
  24556. #if SQLITE_MUTEX_NREF
  24557. p->owner = pthread_self();
  24558. p->nRef++;
  24559. #endif
  24560. rc = SQLITE_OK;
  24561. }else{
  24562. rc = SQLITE_BUSY;
  24563. }
  24564. #endif
  24565. #ifdef SQLITE_DEBUG
  24566. if( rc==SQLITE_OK && p->trace ){
  24567. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  24568. }
  24569. #endif
  24570. return rc;
  24571. }
  24572. /*
  24573. ** The sqlite3_mutex_leave() routine exits a mutex that was
  24574. ** previously entered by the same thread. The behavior
  24575. ** is undefined if the mutex is not currently entered or
  24576. ** is not currently allocated. SQLite will never do either.
  24577. */
  24578. static void pthreadMutexLeave(sqlite3_mutex *p){
  24579. assert( pthreadMutexHeld(p) );
  24580. #if SQLITE_MUTEX_NREF
  24581. p->nRef--;
  24582. if( p->nRef==0 ) p->owner = 0;
  24583. #endif
  24584. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  24585. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  24586. if( p->nRef==0 ){
  24587. pthread_mutex_unlock(&p->mutex);
  24588. }
  24589. #else
  24590. pthread_mutex_unlock(&p->mutex);
  24591. #endif
  24592. #ifdef SQLITE_DEBUG
  24593. if( p->trace ){
  24594. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  24595. }
  24596. #endif
  24597. }
  24598. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  24599. static const sqlite3_mutex_methods sMutex = {
  24600. pthreadMutexInit,
  24601. pthreadMutexEnd,
  24602. pthreadMutexAlloc,
  24603. pthreadMutexFree,
  24604. pthreadMutexEnter,
  24605. pthreadMutexTry,
  24606. pthreadMutexLeave,
  24607. #ifdef SQLITE_DEBUG
  24608. pthreadMutexHeld,
  24609. pthreadMutexNotheld
  24610. #else
  24611. 0,
  24612. 0
  24613. #endif
  24614. };
  24615. return &sMutex;
  24616. }
  24617. #endif /* SQLITE_MUTEX_PTHREADS */
  24618. /************** End of mutex_unix.c ******************************************/
  24619. /************** Begin file mutex_w32.c ***************************************/
  24620. /*
  24621. ** 2007 August 14
  24622. **
  24623. ** The author disclaims copyright to this source code. In place of
  24624. ** a legal notice, here is a blessing:
  24625. **
  24626. ** May you do good and not evil.
  24627. ** May you find forgiveness for yourself and forgive others.
  24628. ** May you share freely, never taking more than you give.
  24629. **
  24630. *************************************************************************
  24631. ** This file contains the C functions that implement mutexes for Win32.
  24632. */
  24633. /* #include "sqliteInt.h" */
  24634. #if SQLITE_OS_WIN
  24635. /*
  24636. ** Include code that is common to all os_*.c files
  24637. */
  24638. /************** Include os_common.h in the middle of mutex_w32.c *************/
  24639. /************** Begin file os_common.h ***************************************/
  24640. /*
  24641. ** 2004 May 22
  24642. **
  24643. ** The author disclaims copyright to this source code. In place of
  24644. ** a legal notice, here is a blessing:
  24645. **
  24646. ** May you do good and not evil.
  24647. ** May you find forgiveness for yourself and forgive others.
  24648. ** May you share freely, never taking more than you give.
  24649. **
  24650. ******************************************************************************
  24651. **
  24652. ** This file contains macros and a little bit of code that is common to
  24653. ** all of the platform-specific files (os_*.c) and is #included into those
  24654. ** files.
  24655. **
  24656. ** This file should be #included by the os_*.c files only. It is not a
  24657. ** general purpose header file.
  24658. */
  24659. #ifndef _OS_COMMON_H_
  24660. #define _OS_COMMON_H_
  24661. /*
  24662. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  24663. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  24664. ** switch. The following code should catch this problem at compile-time.
  24665. */
  24666. #ifdef MEMORY_DEBUG
  24667. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  24668. #endif
  24669. /*
  24670. ** Macros for performance tracing. Normally turned off. Only works
  24671. ** on i486 hardware.
  24672. */
  24673. #ifdef SQLITE_PERFORMANCE_TRACE
  24674. /*
  24675. ** hwtime.h contains inline assembler code for implementing
  24676. ** high-performance timing routines.
  24677. */
  24678. /************** Include hwtime.h in the middle of os_common.h ****************/
  24679. /************** Begin file hwtime.h ******************************************/
  24680. /*
  24681. ** 2008 May 27
  24682. **
  24683. ** The author disclaims copyright to this source code. In place of
  24684. ** a legal notice, here is a blessing:
  24685. **
  24686. ** May you do good and not evil.
  24687. ** May you find forgiveness for yourself and forgive others.
  24688. ** May you share freely, never taking more than you give.
  24689. **
  24690. ******************************************************************************
  24691. **
  24692. ** This file contains inline asm code for retrieving "high-performance"
  24693. ** counters for x86 class CPUs.
  24694. */
  24695. #ifndef SQLITE_HWTIME_H
  24696. #define SQLITE_HWTIME_H
  24697. /*
  24698. ** The following routine only works on pentium-class (or newer) processors.
  24699. ** It uses the RDTSC opcode to read the cycle count value out of the
  24700. ** processor and returns that value. This can be used for high-res
  24701. ** profiling.
  24702. */
  24703. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  24704. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  24705. #if defined(__GNUC__)
  24706. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24707. unsigned int lo, hi;
  24708. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  24709. return (sqlite_uint64)hi << 32 | lo;
  24710. }
  24711. #elif defined(_MSC_VER)
  24712. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  24713. __asm {
  24714. rdtsc
  24715. ret ; return value at EDX:EAX
  24716. }
  24717. }
  24718. #endif
  24719. #elif (defined(__GNUC__) && defined(__x86_64__))
  24720. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24721. unsigned long val;
  24722. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  24723. return val;
  24724. }
  24725. #elif (defined(__GNUC__) && defined(__ppc__))
  24726. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24727. unsigned long long retval;
  24728. unsigned long junk;
  24729. __asm__ __volatile__ ("\n\
  24730. 1: mftbu %1\n\
  24731. mftb %L0\n\
  24732. mftbu %0\n\
  24733. cmpw %0,%1\n\
  24734. bne 1b"
  24735. : "=r" (retval), "=r" (junk));
  24736. return retval;
  24737. }
  24738. #else
  24739. #error Need implementation of sqlite3Hwtime() for your platform.
  24740. /*
  24741. ** To compile without implementing sqlite3Hwtime() for your platform,
  24742. ** you can remove the above #error and use the following
  24743. ** stub function. You will lose timing support for many
  24744. ** of the debugging and testing utilities, but it should at
  24745. ** least compile and run.
  24746. */
  24747. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  24748. #endif
  24749. #endif /* !defined(SQLITE_HWTIME_H) */
  24750. /************** End of hwtime.h **********************************************/
  24751. /************** Continuing where we left off in os_common.h ******************/
  24752. static sqlite_uint64 g_start;
  24753. static sqlite_uint64 g_elapsed;
  24754. #define TIMER_START g_start=sqlite3Hwtime()
  24755. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  24756. #define TIMER_ELAPSED g_elapsed
  24757. #else
  24758. #define TIMER_START
  24759. #define TIMER_END
  24760. #define TIMER_ELAPSED ((sqlite_uint64)0)
  24761. #endif
  24762. /*
  24763. ** If we compile with the SQLITE_TEST macro set, then the following block
  24764. ** of code will give us the ability to simulate a disk I/O error. This
  24765. ** is used for testing the I/O recovery logic.
  24766. */
  24767. #if defined(SQLITE_TEST)
  24768. SQLITE_API extern int sqlite3_io_error_hit;
  24769. SQLITE_API extern int sqlite3_io_error_hardhit;
  24770. SQLITE_API extern int sqlite3_io_error_pending;
  24771. SQLITE_API extern int sqlite3_io_error_persist;
  24772. SQLITE_API extern int sqlite3_io_error_benign;
  24773. SQLITE_API extern int sqlite3_diskfull_pending;
  24774. SQLITE_API extern int sqlite3_diskfull;
  24775. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  24776. #define SimulateIOError(CODE) \
  24777. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  24778. || sqlite3_io_error_pending-- == 1 ) \
  24779. { local_ioerr(); CODE; }
  24780. static void local_ioerr(){
  24781. IOTRACE(("IOERR\n"));
  24782. sqlite3_io_error_hit++;
  24783. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  24784. }
  24785. #define SimulateDiskfullError(CODE) \
  24786. if( sqlite3_diskfull_pending ){ \
  24787. if( sqlite3_diskfull_pending == 1 ){ \
  24788. local_ioerr(); \
  24789. sqlite3_diskfull = 1; \
  24790. sqlite3_io_error_hit = 1; \
  24791. CODE; \
  24792. }else{ \
  24793. sqlite3_diskfull_pending--; \
  24794. } \
  24795. }
  24796. #else
  24797. #define SimulateIOErrorBenign(X)
  24798. #define SimulateIOError(A)
  24799. #define SimulateDiskfullError(A)
  24800. #endif /* defined(SQLITE_TEST) */
  24801. /*
  24802. ** When testing, keep a count of the number of open files.
  24803. */
  24804. #if defined(SQLITE_TEST)
  24805. SQLITE_API extern int sqlite3_open_file_count;
  24806. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  24807. #else
  24808. #define OpenCounter(X)
  24809. #endif /* defined(SQLITE_TEST) */
  24810. #endif /* !defined(_OS_COMMON_H_) */
  24811. /************** End of os_common.h *******************************************/
  24812. /************** Continuing where we left off in mutex_w32.c ******************/
  24813. /*
  24814. ** Include the header file for the Windows VFS.
  24815. */
  24816. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  24817. /************** Begin file os_win.h ******************************************/
  24818. /*
  24819. ** 2013 November 25
  24820. **
  24821. ** The author disclaims copyright to this source code. In place of
  24822. ** a legal notice, here is a blessing:
  24823. **
  24824. ** May you do good and not evil.
  24825. ** May you find forgiveness for yourself and forgive others.
  24826. ** May you share freely, never taking more than you give.
  24827. **
  24828. ******************************************************************************
  24829. **
  24830. ** This file contains code that is specific to Windows.
  24831. */
  24832. #ifndef SQLITE_OS_WIN_H
  24833. #define SQLITE_OS_WIN_H
  24834. /*
  24835. ** Include the primary Windows SDK header file.
  24836. */
  24837. #include "windows.h"
  24838. #ifdef __CYGWIN__
  24839. # include <sys/cygwin.h>
  24840. # include <errno.h> /* amalgamator: dontcache */
  24841. #endif
  24842. /*
  24843. ** Determine if we are dealing with Windows NT.
  24844. **
  24845. ** We ought to be able to determine if we are compiling for Windows 9x or
  24846. ** Windows NT using the _WIN32_WINNT macro as follows:
  24847. **
  24848. ** #if defined(_WIN32_WINNT)
  24849. ** # define SQLITE_OS_WINNT 1
  24850. ** #else
  24851. ** # define SQLITE_OS_WINNT 0
  24852. ** #endif
  24853. **
  24854. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  24855. ** it ought to, so the above test does not work. We'll just assume that
  24856. ** everything is Windows NT unless the programmer explicitly says otherwise
  24857. ** by setting SQLITE_OS_WINNT to 0.
  24858. */
  24859. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  24860. # define SQLITE_OS_WINNT 1
  24861. #endif
  24862. /*
  24863. ** Determine if we are dealing with Windows CE - which has a much reduced
  24864. ** API.
  24865. */
  24866. #if defined(_WIN32_WCE)
  24867. # define SQLITE_OS_WINCE 1
  24868. #else
  24869. # define SQLITE_OS_WINCE 0
  24870. #endif
  24871. /*
  24872. ** Determine if we are dealing with WinRT, which provides only a subset of
  24873. ** the full Win32 API.
  24874. */
  24875. #if !defined(SQLITE_OS_WINRT)
  24876. # define SQLITE_OS_WINRT 0
  24877. #endif
  24878. /*
  24879. ** For WinCE, some API function parameters do not appear to be declared as
  24880. ** volatile.
  24881. */
  24882. #if SQLITE_OS_WINCE
  24883. # define SQLITE_WIN32_VOLATILE
  24884. #else
  24885. # define SQLITE_WIN32_VOLATILE volatile
  24886. #endif
  24887. /*
  24888. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  24889. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  24890. */
  24891. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  24892. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  24893. # define SQLITE_OS_WIN_THREADS 1
  24894. #else
  24895. # define SQLITE_OS_WIN_THREADS 0
  24896. #endif
  24897. #endif /* SQLITE_OS_WIN_H */
  24898. /************** End of os_win.h **********************************************/
  24899. /************** Continuing where we left off in mutex_w32.c ******************/
  24900. #endif
  24901. /*
  24902. ** The code in this file is only used if we are compiling multithreaded
  24903. ** on a Win32 system.
  24904. */
  24905. #ifdef SQLITE_MUTEX_W32
  24906. /*
  24907. ** Each recursive mutex is an instance of the following structure.
  24908. */
  24909. struct sqlite3_mutex {
  24910. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  24911. int id; /* Mutex type */
  24912. #ifdef SQLITE_DEBUG
  24913. volatile int nRef; /* Number of enterances */
  24914. volatile DWORD owner; /* Thread holding this mutex */
  24915. volatile LONG trace; /* True to trace changes */
  24916. #endif
  24917. };
  24918. /*
  24919. ** These are the initializer values used when declaring a "static" mutex
  24920. ** on Win32. It should be noted that all mutexes require initialization
  24921. ** on the Win32 platform.
  24922. */
  24923. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  24924. #ifdef SQLITE_DEBUG
  24925. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \
  24926. 0L, (DWORD)0, 0 }
  24927. #else
  24928. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }
  24929. #endif
  24930. #ifdef SQLITE_DEBUG
  24931. /*
  24932. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24933. ** intended for use only inside assert() statements.
  24934. */
  24935. static int winMutexHeld(sqlite3_mutex *p){
  24936. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  24937. }
  24938. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  24939. return p->nRef==0 || p->owner!=tid;
  24940. }
  24941. static int winMutexNotheld(sqlite3_mutex *p){
  24942. DWORD tid = GetCurrentThreadId();
  24943. return winMutexNotheld2(p, tid);
  24944. }
  24945. #endif
  24946. /*
  24947. ** Try to provide a memory barrier operation, needed for initialization
  24948. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  24949. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  24950. */
  24951. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  24952. #if defined(SQLITE_MEMORY_BARRIER)
  24953. SQLITE_MEMORY_BARRIER;
  24954. #elif defined(__GNUC__)
  24955. __sync_synchronize();
  24956. #elif MSVC_VERSION>=1300
  24957. _ReadWriteBarrier();
  24958. #elif defined(MemoryBarrier)
  24959. MemoryBarrier();
  24960. #endif
  24961. }
  24962. /*
  24963. ** Initialize and deinitialize the mutex subsystem.
  24964. */
  24965. static sqlite3_mutex winMutex_staticMutexes[] = {
  24966. SQLITE3_MUTEX_INITIALIZER(2),
  24967. SQLITE3_MUTEX_INITIALIZER(3),
  24968. SQLITE3_MUTEX_INITIALIZER(4),
  24969. SQLITE3_MUTEX_INITIALIZER(5),
  24970. SQLITE3_MUTEX_INITIALIZER(6),
  24971. SQLITE3_MUTEX_INITIALIZER(7),
  24972. SQLITE3_MUTEX_INITIALIZER(8),
  24973. SQLITE3_MUTEX_INITIALIZER(9),
  24974. SQLITE3_MUTEX_INITIALIZER(10),
  24975. SQLITE3_MUTEX_INITIALIZER(11),
  24976. SQLITE3_MUTEX_INITIALIZER(12),
  24977. SQLITE3_MUTEX_INITIALIZER(13)
  24978. };
  24979. static int winMutex_isInit = 0;
  24980. static int winMutex_isNt = -1; /* <0 means "need to query" */
  24981. /* As the winMutexInit() and winMutexEnd() functions are called as part
  24982. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  24983. ** "interlocked" magic used here is probably not strictly necessary.
  24984. */
  24985. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  24986. SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
  24987. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  24988. static int winMutexInit(void){
  24989. /* The first to increment to 1 does actual initialization */
  24990. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  24991. int i;
  24992. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  24993. #if SQLITE_OS_WINRT
  24994. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  24995. #else
  24996. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  24997. #endif
  24998. }
  24999. winMutex_isInit = 1;
  25000. }else{
  25001. /* Another thread is (in the process of) initializing the static
  25002. ** mutexes */
  25003. while( !winMutex_isInit ){
  25004. sqlite3_win32_sleep(1);
  25005. }
  25006. }
  25007. return SQLITE_OK;
  25008. }
  25009. static int winMutexEnd(void){
  25010. /* The first to decrement to 0 does actual shutdown
  25011. ** (which should be the last to shutdown.) */
  25012. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  25013. if( winMutex_isInit==1 ){
  25014. int i;
  25015. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  25016. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  25017. }
  25018. winMutex_isInit = 0;
  25019. }
  25020. }
  25021. return SQLITE_OK;
  25022. }
  25023. /*
  25024. ** The sqlite3_mutex_alloc() routine allocates a new
  25025. ** mutex and returns a pointer to it. If it returns NULL
  25026. ** that means that a mutex could not be allocated. SQLite
  25027. ** will unwind its stack and return an error. The argument
  25028. ** to sqlite3_mutex_alloc() is one of these integer constants:
  25029. **
  25030. ** <ul>
  25031. ** <li> SQLITE_MUTEX_FAST
  25032. ** <li> SQLITE_MUTEX_RECURSIVE
  25033. ** <li> SQLITE_MUTEX_STATIC_MASTER
  25034. ** <li> SQLITE_MUTEX_STATIC_MEM
  25035. ** <li> SQLITE_MUTEX_STATIC_OPEN
  25036. ** <li> SQLITE_MUTEX_STATIC_PRNG
  25037. ** <li> SQLITE_MUTEX_STATIC_LRU
  25038. ** <li> SQLITE_MUTEX_STATIC_PMEM
  25039. ** <li> SQLITE_MUTEX_STATIC_APP1
  25040. ** <li> SQLITE_MUTEX_STATIC_APP2
  25041. ** <li> SQLITE_MUTEX_STATIC_APP3
  25042. ** <li> SQLITE_MUTEX_STATIC_VFS1
  25043. ** <li> SQLITE_MUTEX_STATIC_VFS2
  25044. ** <li> SQLITE_MUTEX_STATIC_VFS3
  25045. ** </ul>
  25046. **
  25047. ** The first two constants cause sqlite3_mutex_alloc() to create
  25048. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  25049. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  25050. ** The mutex implementation does not need to make a distinction
  25051. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  25052. ** not want to. But SQLite will only request a recursive mutex in
  25053. ** cases where it really needs one. If a faster non-recursive mutex
  25054. ** implementation is available on the host platform, the mutex subsystem
  25055. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  25056. **
  25057. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  25058. ** a pointer to a static preexisting mutex. Six static mutexes are
  25059. ** used by the current version of SQLite. Future versions of SQLite
  25060. ** may add additional static mutexes. Static mutexes are for internal
  25061. ** use by SQLite only. Applications that use SQLite mutexes should
  25062. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  25063. ** SQLITE_MUTEX_RECURSIVE.
  25064. **
  25065. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  25066. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  25067. ** returns a different mutex on every call. But for the static
  25068. ** mutex types, the same mutex is returned on every call that has
  25069. ** the same type number.
  25070. */
  25071. static sqlite3_mutex *winMutexAlloc(int iType){
  25072. sqlite3_mutex *p;
  25073. switch( iType ){
  25074. case SQLITE_MUTEX_FAST:
  25075. case SQLITE_MUTEX_RECURSIVE: {
  25076. p = sqlite3MallocZero( sizeof(*p) );
  25077. if( p ){
  25078. p->id = iType;
  25079. #ifdef SQLITE_DEBUG
  25080. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  25081. p->trace = 1;
  25082. #endif
  25083. #endif
  25084. #if SQLITE_OS_WINRT
  25085. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  25086. #else
  25087. InitializeCriticalSection(&p->mutex);
  25088. #endif
  25089. }
  25090. break;
  25091. }
  25092. default: {
  25093. #ifdef SQLITE_ENABLE_API_ARMOR
  25094. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  25095. (void)SQLITE_MISUSE_BKPT;
  25096. return 0;
  25097. }
  25098. #endif
  25099. p = &winMutex_staticMutexes[iType-2];
  25100. #ifdef SQLITE_DEBUG
  25101. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  25102. InterlockedCompareExchange(&p->trace, 1, 0);
  25103. #endif
  25104. #endif
  25105. break;
  25106. }
  25107. }
  25108. assert( p==0 || p->id==iType );
  25109. return p;
  25110. }
  25111. /*
  25112. ** This routine deallocates a previously
  25113. ** allocated mutex. SQLite is careful to deallocate every
  25114. ** mutex that it allocates.
  25115. */
  25116. static void winMutexFree(sqlite3_mutex *p){
  25117. assert( p );
  25118. assert( p->nRef==0 && p->owner==0 );
  25119. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  25120. DeleteCriticalSection(&p->mutex);
  25121. sqlite3_free(p);
  25122. }else{
  25123. #ifdef SQLITE_ENABLE_API_ARMOR
  25124. (void)SQLITE_MISUSE_BKPT;
  25125. #endif
  25126. }
  25127. }
  25128. /*
  25129. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  25130. ** to enter a mutex. If another thread is already within the mutex,
  25131. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  25132. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  25133. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  25134. ** be entered multiple times by the same thread. In such cases the,
  25135. ** mutex must be exited an equal number of times before another thread
  25136. ** can enter. If the same thread tries to enter any other kind of mutex
  25137. ** more than once, the behavior is undefined.
  25138. */
  25139. static void winMutexEnter(sqlite3_mutex *p){
  25140. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25141. DWORD tid = GetCurrentThreadId();
  25142. #endif
  25143. #ifdef SQLITE_DEBUG
  25144. assert( p );
  25145. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  25146. #else
  25147. assert( p );
  25148. #endif
  25149. assert( winMutex_isInit==1 );
  25150. EnterCriticalSection(&p->mutex);
  25151. #ifdef SQLITE_DEBUG
  25152. assert( p->nRef>0 || p->owner==0 );
  25153. p->owner = tid;
  25154. p->nRef++;
  25155. if( p->trace ){
  25156. OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  25157. tid, p->id, p, p->trace, p->nRef));
  25158. }
  25159. #endif
  25160. }
  25161. static int winMutexTry(sqlite3_mutex *p){
  25162. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25163. DWORD tid = GetCurrentThreadId();
  25164. #endif
  25165. int rc = SQLITE_BUSY;
  25166. assert( p );
  25167. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  25168. /*
  25169. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  25170. ** is used it is merely an optimization. So it is OK for it to always
  25171. ** fail.
  25172. **
  25173. ** The TryEnterCriticalSection() interface is only available on WinNT.
  25174. ** And some windows compilers complain if you try to use it without
  25175. ** first doing some #defines that prevent SQLite from building on Win98.
  25176. ** For that reason, we will omit this optimization for now. See
  25177. ** ticket #2685.
  25178. */
  25179. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  25180. assert( winMutex_isInit==1 );
  25181. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  25182. if( winMutex_isNt<0 ){
  25183. winMutex_isNt = sqlite3_win32_is_nt();
  25184. }
  25185. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  25186. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  25187. #ifdef SQLITE_DEBUG
  25188. p->owner = tid;
  25189. p->nRef++;
  25190. #endif
  25191. rc = SQLITE_OK;
  25192. }
  25193. #else
  25194. UNUSED_PARAMETER(p);
  25195. #endif
  25196. #ifdef SQLITE_DEBUG
  25197. if( p->trace ){
  25198. OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  25199. tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  25200. }
  25201. #endif
  25202. return rc;
  25203. }
  25204. /*
  25205. ** The sqlite3_mutex_leave() routine exits a mutex that was
  25206. ** previously entered by the same thread. The behavior
  25207. ** is undefined if the mutex is not currently entered or
  25208. ** is not currently allocated. SQLite will never do either.
  25209. */
  25210. static void winMutexLeave(sqlite3_mutex *p){
  25211. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25212. DWORD tid = GetCurrentThreadId();
  25213. #endif
  25214. assert( p );
  25215. #ifdef SQLITE_DEBUG
  25216. assert( p->nRef>0 );
  25217. assert( p->owner==tid );
  25218. p->nRef--;
  25219. if( p->nRef==0 ) p->owner = 0;
  25220. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  25221. #endif
  25222. assert( winMutex_isInit==1 );
  25223. LeaveCriticalSection(&p->mutex);
  25224. #ifdef SQLITE_DEBUG
  25225. if( p->trace ){
  25226. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  25227. tid, p->id, p, p->trace, p->nRef));
  25228. }
  25229. #endif
  25230. }
  25231. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  25232. static const sqlite3_mutex_methods sMutex = {
  25233. winMutexInit,
  25234. winMutexEnd,
  25235. winMutexAlloc,
  25236. winMutexFree,
  25237. winMutexEnter,
  25238. winMutexTry,
  25239. winMutexLeave,
  25240. #ifdef SQLITE_DEBUG
  25241. winMutexHeld,
  25242. winMutexNotheld
  25243. #else
  25244. 0,
  25245. 0
  25246. #endif
  25247. };
  25248. return &sMutex;
  25249. }
  25250. #endif /* SQLITE_MUTEX_W32 */
  25251. /************** End of mutex_w32.c *******************************************/
  25252. /************** Begin file malloc.c ******************************************/
  25253. /*
  25254. ** 2001 September 15
  25255. **
  25256. ** The author disclaims copyright to this source code. In place of
  25257. ** a legal notice, here is a blessing:
  25258. **
  25259. ** May you do good and not evil.
  25260. ** May you find forgiveness for yourself and forgive others.
  25261. ** May you share freely, never taking more than you give.
  25262. **
  25263. *************************************************************************
  25264. **
  25265. ** Memory allocation functions used throughout sqlite.
  25266. */
  25267. /* #include "sqliteInt.h" */
  25268. /* #include <stdarg.h> */
  25269. /*
  25270. ** Attempt to release up to n bytes of non-essential memory currently
  25271. ** held by SQLite. An example of non-essential memory is memory used to
  25272. ** cache database pages that are not currently in use.
  25273. */
  25274. SQLITE_API int sqlite3_release_memory(int n){
  25275. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  25276. return sqlite3PcacheReleaseMemory(n);
  25277. #else
  25278. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  25279. ** is a no-op returning zero if SQLite is not compiled with
  25280. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  25281. UNUSED_PARAMETER(n);
  25282. return 0;
  25283. #endif
  25284. }
  25285. /*
  25286. ** State information local to the memory allocation subsystem.
  25287. */
  25288. static SQLITE_WSD struct Mem0Global {
  25289. sqlite3_mutex *mutex; /* Mutex to serialize access */
  25290. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  25291. /*
  25292. ** True if heap is nearly "full" where "full" is defined by the
  25293. ** sqlite3_soft_heap_limit() setting.
  25294. */
  25295. int nearlyFull;
  25296. } mem0 = { 0, 0, 0 };
  25297. #define mem0 GLOBAL(struct Mem0Global, mem0)
  25298. /*
  25299. ** Return the memory allocator mutex. sqlite3_status() needs it.
  25300. */
  25301. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  25302. return mem0.mutex;
  25303. }
  25304. #ifndef SQLITE_OMIT_DEPRECATED
  25305. /*
  25306. ** Deprecated external interface. It used to set an alarm callback
  25307. ** that was invoked when memory usage grew too large. Now it is a
  25308. ** no-op.
  25309. */
  25310. SQLITE_API int sqlite3_memory_alarm(
  25311. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  25312. void *pArg,
  25313. sqlite3_int64 iThreshold
  25314. ){
  25315. (void)xCallback;
  25316. (void)pArg;
  25317. (void)iThreshold;
  25318. return SQLITE_OK;
  25319. }
  25320. #endif
  25321. /*
  25322. ** Set the soft heap-size limit for the library. Passing a zero or
  25323. ** negative value indicates no limit.
  25324. */
  25325. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  25326. sqlite3_int64 priorLimit;
  25327. sqlite3_int64 excess;
  25328. sqlite3_int64 nUsed;
  25329. #ifndef SQLITE_OMIT_AUTOINIT
  25330. int rc = sqlite3_initialize();
  25331. if( rc ) return -1;
  25332. #endif
  25333. sqlite3_mutex_enter(mem0.mutex);
  25334. priorLimit = mem0.alarmThreshold;
  25335. if( n<0 ){
  25336. sqlite3_mutex_leave(mem0.mutex);
  25337. return priorLimit;
  25338. }
  25339. mem0.alarmThreshold = n;
  25340. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  25341. mem0.nearlyFull = (n>0 && n<=nUsed);
  25342. sqlite3_mutex_leave(mem0.mutex);
  25343. excess = sqlite3_memory_used() - n;
  25344. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  25345. return priorLimit;
  25346. }
  25347. SQLITE_API void sqlite3_soft_heap_limit(int n){
  25348. if( n<0 ) n = 0;
  25349. sqlite3_soft_heap_limit64(n);
  25350. }
  25351. /*
  25352. ** Initialize the memory allocation subsystem.
  25353. */
  25354. SQLITE_PRIVATE int sqlite3MallocInit(void){
  25355. int rc;
  25356. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  25357. sqlite3MemSetDefault();
  25358. }
  25359. memset(&mem0, 0, sizeof(mem0));
  25360. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  25361. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  25362. || sqlite3GlobalConfig.nPage<=0 ){
  25363. sqlite3GlobalConfig.pPage = 0;
  25364. sqlite3GlobalConfig.szPage = 0;
  25365. }
  25366. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  25367. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  25368. return rc;
  25369. }
  25370. /*
  25371. ** Return true if the heap is currently under memory pressure - in other
  25372. ** words if the amount of heap used is close to the limit set by
  25373. ** sqlite3_soft_heap_limit().
  25374. */
  25375. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  25376. return mem0.nearlyFull;
  25377. }
  25378. /*
  25379. ** Deinitialize the memory allocation subsystem.
  25380. */
  25381. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  25382. if( sqlite3GlobalConfig.m.xShutdown ){
  25383. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  25384. }
  25385. memset(&mem0, 0, sizeof(mem0));
  25386. }
  25387. /*
  25388. ** Return the amount of memory currently checked out.
  25389. */
  25390. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  25391. sqlite3_int64 res, mx;
  25392. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  25393. return res;
  25394. }
  25395. /*
  25396. ** Return the maximum amount of memory that has ever been
  25397. ** checked out since either the beginning of this process
  25398. ** or since the most recent reset.
  25399. */
  25400. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  25401. sqlite3_int64 res, mx;
  25402. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  25403. return mx;
  25404. }
  25405. /*
  25406. ** Trigger the alarm
  25407. */
  25408. static void sqlite3MallocAlarm(int nByte){
  25409. if( mem0.alarmThreshold<=0 ) return;
  25410. sqlite3_mutex_leave(mem0.mutex);
  25411. sqlite3_release_memory(nByte);
  25412. sqlite3_mutex_enter(mem0.mutex);
  25413. }
  25414. /*
  25415. ** Do a memory allocation with statistics and alarms. Assume the
  25416. ** lock is already held.
  25417. */
  25418. static void mallocWithAlarm(int n, void **pp){
  25419. void *p;
  25420. int nFull;
  25421. assert( sqlite3_mutex_held(mem0.mutex) );
  25422. assert( n>0 );
  25423. /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
  25424. ** implementation of malloc_good_size(), which must be called in debug
  25425. ** mode and specifically when the DMD "Dark Matter Detector" is enabled
  25426. ** or else a crash results. Hence, do not attempt to optimize out the
  25427. ** following xRoundup() call. */
  25428. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  25429. #ifdef SQLITE_MAX_MEMORY
  25430. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
  25431. *pp = 0;
  25432. return;
  25433. }
  25434. #endif
  25435. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
  25436. if( mem0.alarmThreshold>0 ){
  25437. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  25438. if( nUsed >= mem0.alarmThreshold - nFull ){
  25439. mem0.nearlyFull = 1;
  25440. sqlite3MallocAlarm(nFull);
  25441. }else{
  25442. mem0.nearlyFull = 0;
  25443. }
  25444. }
  25445. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  25446. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  25447. if( p==0 && mem0.alarmThreshold>0 ){
  25448. sqlite3MallocAlarm(nFull);
  25449. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  25450. }
  25451. #endif
  25452. if( p ){
  25453. nFull = sqlite3MallocSize(p);
  25454. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  25455. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  25456. }
  25457. *pp = p;
  25458. }
  25459. /*
  25460. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  25461. ** assumes the memory subsystem has already been initialized.
  25462. */
  25463. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  25464. void *p;
  25465. if( n==0 || n>=0x7fffff00 ){
  25466. /* A memory allocation of a number of bytes which is near the maximum
  25467. ** signed integer value might cause an integer overflow inside of the
  25468. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  25469. ** 255 bytes of overhead. SQLite itself will never use anything near
  25470. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  25471. p = 0;
  25472. }else if( sqlite3GlobalConfig.bMemstat ){
  25473. sqlite3_mutex_enter(mem0.mutex);
  25474. mallocWithAlarm((int)n, &p);
  25475. sqlite3_mutex_leave(mem0.mutex);
  25476. }else{
  25477. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  25478. }
  25479. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  25480. return p;
  25481. }
  25482. /*
  25483. ** This version of the memory allocation is for use by the application.
  25484. ** First make sure the memory subsystem is initialized, then do the
  25485. ** allocation.
  25486. */
  25487. SQLITE_API void *sqlite3_malloc(int n){
  25488. #ifndef SQLITE_OMIT_AUTOINIT
  25489. if( sqlite3_initialize() ) return 0;
  25490. #endif
  25491. return n<=0 ? 0 : sqlite3Malloc(n);
  25492. }
  25493. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
  25494. #ifndef SQLITE_OMIT_AUTOINIT
  25495. if( sqlite3_initialize() ) return 0;
  25496. #endif
  25497. return sqlite3Malloc(n);
  25498. }
  25499. /*
  25500. ** TRUE if p is a lookaside memory allocation from db
  25501. */
  25502. #ifndef SQLITE_OMIT_LOOKASIDE
  25503. static int isLookaside(sqlite3 *db, void *p){
  25504. return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
  25505. }
  25506. #else
  25507. #define isLookaside(A,B) 0
  25508. #endif
  25509. /*
  25510. ** Return the size of a memory allocation previously obtained from
  25511. ** sqlite3Malloc() or sqlite3_malloc().
  25512. */
  25513. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  25514. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25515. return sqlite3GlobalConfig.m.xSize(p);
  25516. }
  25517. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  25518. assert( p!=0 );
  25519. if( db==0 || !isLookaside(db,p) ){
  25520. #ifdef SQLITE_DEBUG
  25521. if( db==0 ){
  25522. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  25523. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25524. }else{
  25525. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25526. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25527. }
  25528. #endif
  25529. return sqlite3GlobalConfig.m.xSize(p);
  25530. }else{
  25531. assert( sqlite3_mutex_held(db->mutex) );
  25532. return db->lookaside.sz;
  25533. }
  25534. }
  25535. SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
  25536. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  25537. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25538. return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
  25539. }
  25540. /*
  25541. ** Free memory previously obtained from sqlite3Malloc().
  25542. */
  25543. SQLITE_API void sqlite3_free(void *p){
  25544. if( p==0 ) return; /* IMP: R-49053-54554 */
  25545. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  25546. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  25547. if( sqlite3GlobalConfig.bMemstat ){
  25548. sqlite3_mutex_enter(mem0.mutex);
  25549. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  25550. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  25551. sqlite3GlobalConfig.m.xFree(p);
  25552. sqlite3_mutex_leave(mem0.mutex);
  25553. }else{
  25554. sqlite3GlobalConfig.m.xFree(p);
  25555. }
  25556. }
  25557. /*
  25558. ** Add the size of memory allocation "p" to the count in
  25559. ** *db->pnBytesFreed.
  25560. */
  25561. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  25562. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  25563. }
  25564. /*
  25565. ** Free memory that might be associated with a particular database
  25566. ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
  25567. ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
  25568. */
  25569. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
  25570. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  25571. assert( p!=0 );
  25572. if( db ){
  25573. if( db->pnBytesFreed ){
  25574. measureAllocationSize(db, p);
  25575. return;
  25576. }
  25577. if( isLookaside(db, p) ){
  25578. LookasideSlot *pBuf = (LookasideSlot*)p;
  25579. #ifdef SQLITE_DEBUG
  25580. /* Trash all content in the buffer being freed */
  25581. memset(p, 0xaa, db->lookaside.sz);
  25582. #endif
  25583. pBuf->pNext = db->lookaside.pFree;
  25584. db->lookaside.pFree = pBuf;
  25585. return;
  25586. }
  25587. }
  25588. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25589. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25590. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  25591. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25592. sqlite3_free(p);
  25593. }
  25594. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  25595. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  25596. if( p ) sqlite3DbFreeNN(db, p);
  25597. }
  25598. /*
  25599. ** Change the size of an existing memory allocation
  25600. */
  25601. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  25602. int nOld, nNew, nDiff;
  25603. void *pNew;
  25604. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  25605. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  25606. if( pOld==0 ){
  25607. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  25608. }
  25609. if( nBytes==0 ){
  25610. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  25611. return 0;
  25612. }
  25613. if( nBytes>=0x7fffff00 ){
  25614. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  25615. return 0;
  25616. }
  25617. nOld = sqlite3MallocSize(pOld);
  25618. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  25619. ** argument to xRealloc is always a value returned by a prior call to
  25620. ** xRoundup. */
  25621. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  25622. if( nOld==nNew ){
  25623. pNew = pOld;
  25624. }else if( sqlite3GlobalConfig.bMemstat ){
  25625. sqlite3_mutex_enter(mem0.mutex);
  25626. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  25627. nDiff = nNew - nOld;
  25628. if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  25629. mem0.alarmThreshold-nDiff ){
  25630. sqlite3MallocAlarm(nDiff);
  25631. }
  25632. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25633. if( pNew==0 && mem0.alarmThreshold>0 ){
  25634. sqlite3MallocAlarm((int)nBytes);
  25635. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25636. }
  25637. if( pNew ){
  25638. nNew = sqlite3MallocSize(pNew);
  25639. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  25640. }
  25641. sqlite3_mutex_leave(mem0.mutex);
  25642. }else{
  25643. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  25644. }
  25645. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  25646. return pNew;
  25647. }
  25648. /*
  25649. ** The public interface to sqlite3Realloc. Make sure that the memory
  25650. ** subsystem is initialized prior to invoking sqliteRealloc.
  25651. */
  25652. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  25653. #ifndef SQLITE_OMIT_AUTOINIT
  25654. if( sqlite3_initialize() ) return 0;
  25655. #endif
  25656. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  25657. return sqlite3Realloc(pOld, n);
  25658. }
  25659. SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  25660. #ifndef SQLITE_OMIT_AUTOINIT
  25661. if( sqlite3_initialize() ) return 0;
  25662. #endif
  25663. return sqlite3Realloc(pOld, n);
  25664. }
  25665. /*
  25666. ** Allocate and zero memory.
  25667. */
  25668. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  25669. void *p = sqlite3Malloc(n);
  25670. if( p ){
  25671. memset(p, 0, (size_t)n);
  25672. }
  25673. return p;
  25674. }
  25675. /*
  25676. ** Allocate and zero memory. If the allocation fails, make
  25677. ** the mallocFailed flag in the connection pointer.
  25678. */
  25679. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  25680. void *p;
  25681. testcase( db==0 );
  25682. p = sqlite3DbMallocRaw(db, n);
  25683. if( p ) memset(p, 0, (size_t)n);
  25684. return p;
  25685. }
  25686. /* Finish the work of sqlite3DbMallocRawNN for the unusual and
  25687. ** slower case when the allocation cannot be fulfilled using lookaside.
  25688. */
  25689. static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
  25690. void *p;
  25691. assert( db!=0 );
  25692. p = sqlite3Malloc(n);
  25693. if( !p ) sqlite3OomFault(db);
  25694. sqlite3MemdebugSetType(p,
  25695. (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  25696. return p;
  25697. }
  25698. /*
  25699. ** Allocate memory, either lookaside (if possible) or heap.
  25700. ** If the allocation fails, set the mallocFailed flag in
  25701. ** the connection pointer.
  25702. **
  25703. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  25704. ** failure on the same database connection) then always return 0.
  25705. ** Hence for a particular database connection, once malloc starts
  25706. ** failing, it fails consistently until mallocFailed is reset.
  25707. ** This is an important assumption. There are many places in the
  25708. ** code that do things like this:
  25709. **
  25710. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  25711. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  25712. ** if( b ) a[10] = 9;
  25713. **
  25714. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  25715. ** that all prior mallocs (ex: "a") worked too.
  25716. **
  25717. ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
  25718. ** not a NULL pointer.
  25719. */
  25720. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  25721. void *p;
  25722. if( db ) return sqlite3DbMallocRawNN(db, n);
  25723. p = sqlite3Malloc(n);
  25724. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25725. return p;
  25726. }
  25727. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
  25728. #ifndef SQLITE_OMIT_LOOKASIDE
  25729. LookasideSlot *pBuf;
  25730. assert( db!=0 );
  25731. assert( sqlite3_mutex_held(db->mutex) );
  25732. assert( db->pnBytesFreed==0 );
  25733. if( db->lookaside.bDisable==0 ){
  25734. assert( db->mallocFailed==0 );
  25735. if( n>db->lookaside.sz ){
  25736. db->lookaside.anStat[1]++;
  25737. }else if( (pBuf = db->lookaside.pFree)!=0 ){
  25738. db->lookaside.pFree = pBuf->pNext;
  25739. db->lookaside.anStat[0]++;
  25740. return (void*)pBuf;
  25741. }else if( (pBuf = db->lookaside.pInit)!=0 ){
  25742. db->lookaside.pInit = pBuf->pNext;
  25743. db->lookaside.anStat[0]++;
  25744. return (void*)pBuf;
  25745. }else{
  25746. db->lookaside.anStat[2]++;
  25747. }
  25748. }else if( db->mallocFailed ){
  25749. return 0;
  25750. }
  25751. #else
  25752. assert( db!=0 );
  25753. assert( sqlite3_mutex_held(db->mutex) );
  25754. assert( db->pnBytesFreed==0 );
  25755. if( db->mallocFailed ){
  25756. return 0;
  25757. }
  25758. #endif
  25759. return dbMallocRawFinish(db, n);
  25760. }
  25761. /* Forward declaration */
  25762. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
  25763. /*
  25764. ** Resize the block of memory pointed to by p to n bytes. If the
  25765. ** resize fails, set the mallocFailed flag in the connection object.
  25766. */
  25767. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  25768. assert( db!=0 );
  25769. if( p==0 ) return sqlite3DbMallocRawNN(db, n);
  25770. assert( sqlite3_mutex_held(db->mutex) );
  25771. if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
  25772. return dbReallocFinish(db, p, n);
  25773. }
  25774. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
  25775. void *pNew = 0;
  25776. assert( db!=0 );
  25777. assert( p!=0 );
  25778. if( db->mallocFailed==0 ){
  25779. if( isLookaside(db, p) ){
  25780. pNew = sqlite3DbMallocRawNN(db, n);
  25781. if( pNew ){
  25782. memcpy(pNew, p, db->lookaside.sz);
  25783. sqlite3DbFree(db, p);
  25784. }
  25785. }else{
  25786. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25787. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  25788. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  25789. pNew = sqlite3_realloc64(p, n);
  25790. if( !pNew ){
  25791. sqlite3OomFault(db);
  25792. }
  25793. sqlite3MemdebugSetType(pNew,
  25794. (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  25795. }
  25796. }
  25797. return pNew;
  25798. }
  25799. /*
  25800. ** Attempt to reallocate p. If the reallocation fails, then free p
  25801. ** and set the mallocFailed flag in the database connection.
  25802. */
  25803. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  25804. void *pNew;
  25805. pNew = sqlite3DbRealloc(db, p, n);
  25806. if( !pNew ){
  25807. sqlite3DbFree(db, p);
  25808. }
  25809. return pNew;
  25810. }
  25811. /*
  25812. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  25813. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  25814. ** is because when memory debugging is turned on, these two functions are
  25815. ** called via macros that record the current file and line number in the
  25816. ** ThreadData structure.
  25817. */
  25818. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  25819. char *zNew;
  25820. size_t n;
  25821. if( z==0 ){
  25822. return 0;
  25823. }
  25824. n = strlen(z) + 1;
  25825. zNew = sqlite3DbMallocRaw(db, n);
  25826. if( zNew ){
  25827. memcpy(zNew, z, n);
  25828. }
  25829. return zNew;
  25830. }
  25831. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  25832. char *zNew;
  25833. assert( db!=0 );
  25834. if( z==0 ){
  25835. return 0;
  25836. }
  25837. assert( (n&0x7fffffff)==n );
  25838. zNew = sqlite3DbMallocRawNN(db, n+1);
  25839. if( zNew ){
  25840. memcpy(zNew, z, (size_t)n);
  25841. zNew[n] = 0;
  25842. }
  25843. return zNew;
  25844. }
  25845. /*
  25846. ** The text between zStart and zEnd represents a phrase within a larger
  25847. ** SQL statement. Make a copy of this phrase in space obtained form
  25848. ** sqlite3DbMalloc(). Omit leading and trailing whitespace.
  25849. */
  25850. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  25851. int n;
  25852. while( sqlite3Isspace(zStart[0]) ) zStart++;
  25853. n = (int)(zEnd - zStart);
  25854. while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
  25855. return sqlite3DbStrNDup(db, zStart, n);
  25856. }
  25857. /*
  25858. ** Free any prior content in *pz and replace it with a copy of zNew.
  25859. */
  25860. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  25861. sqlite3DbFree(db, *pz);
  25862. *pz = sqlite3DbStrDup(db, zNew);
  25863. }
  25864. /*
  25865. ** Call this routine to record the fact that an OOM (out-of-memory) error
  25866. ** has happened. This routine will set db->mallocFailed, and also
  25867. ** temporarily disable the lookaside memory allocator and interrupt
  25868. ** any running VDBEs.
  25869. */
  25870. SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
  25871. if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
  25872. db->mallocFailed = 1;
  25873. if( db->nVdbeExec>0 ){
  25874. db->u1.isInterrupted = 1;
  25875. }
  25876. db->lookaside.bDisable++;
  25877. if( db->pParse ){
  25878. db->pParse->rc = SQLITE_NOMEM_BKPT;
  25879. }
  25880. }
  25881. }
  25882. /*
  25883. ** This routine reactivates the memory allocator and clears the
  25884. ** db->mallocFailed flag as necessary.
  25885. **
  25886. ** The memory allocator is not restarted if there are running
  25887. ** VDBEs.
  25888. */
  25889. SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
  25890. if( db->mallocFailed && db->nVdbeExec==0 ){
  25891. db->mallocFailed = 0;
  25892. db->u1.isInterrupted = 0;
  25893. assert( db->lookaside.bDisable>0 );
  25894. db->lookaside.bDisable--;
  25895. }
  25896. }
  25897. /*
  25898. ** Take actions at the end of an API call to indicate an OOM error
  25899. */
  25900. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  25901. sqlite3OomClear(db);
  25902. sqlite3Error(db, SQLITE_NOMEM);
  25903. return SQLITE_NOMEM_BKPT;
  25904. }
  25905. /*
  25906. ** This function must be called before exiting any API function (i.e.
  25907. ** returning control to the user) that has called sqlite3_malloc or
  25908. ** sqlite3_realloc.
  25909. **
  25910. ** The returned value is normally a copy of the second argument to this
  25911. ** function. However, if a malloc() failure has occurred since the previous
  25912. ** invocation SQLITE_NOMEM is returned instead.
  25913. **
  25914. ** If an OOM as occurred, then the connection error-code (the value
  25915. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  25916. */
  25917. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  25918. /* If the db handle must hold the connection handle mutex here.
  25919. ** Otherwise the read (and possible write) of db->mallocFailed
  25920. ** is unsafe, as is the call to sqlite3Error().
  25921. */
  25922. assert( db!=0 );
  25923. assert( sqlite3_mutex_held(db->mutex) );
  25924. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  25925. return apiOomError(db);
  25926. }
  25927. return rc & db->errMask;
  25928. }
  25929. /************** End of malloc.c **********************************************/
  25930. /************** Begin file printf.c ******************************************/
  25931. /*
  25932. ** The "printf" code that follows dates from the 1980's. It is in
  25933. ** the public domain.
  25934. **
  25935. **************************************************************************
  25936. **
  25937. ** This file contains code for a set of "printf"-like routines. These
  25938. ** routines format strings much like the printf() from the standard C
  25939. ** library, though the implementation here has enhancements to support
  25940. ** SQLite.
  25941. */
  25942. /* #include "sqliteInt.h" */
  25943. /*
  25944. ** Conversion types fall into various categories as defined by the
  25945. ** following enumeration.
  25946. */
  25947. #define etRADIX 0 /* non-decimal integer types. %x %o */
  25948. #define etFLOAT 1 /* Floating point. %f */
  25949. #define etEXP 2 /* Exponentional notation. %e and %E */
  25950. #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
  25951. #define etSIZE 4 /* Return number of characters processed so far. %n */
  25952. #define etSTRING 5 /* Strings. %s */
  25953. #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
  25954. #define etPERCENT 7 /* Percent symbol. %% */
  25955. #define etCHARX 8 /* Characters. %c */
  25956. /* The rest are extensions, not normally found in printf() */
  25957. #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
  25958. #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
  25959. NULL pointers replaced by SQL NULL. %Q */
  25960. #define etTOKEN 11 /* a pointer to a Token structure */
  25961. #define etSRCLIST 12 /* a pointer to a SrcList */
  25962. #define etPOINTER 13 /* The %p conversion */
  25963. #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
  25964. #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  25965. #define etDECIMAL 16 /* %d or %u, but not %x, %o */
  25966. #define etINVALID 17 /* Any unrecognized conversion type */
  25967. /*
  25968. ** An "etByte" is an 8-bit unsigned value.
  25969. */
  25970. typedef unsigned char etByte;
  25971. /*
  25972. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  25973. ** by an instance of the following structure
  25974. */
  25975. typedef struct et_info { /* Information about each format field */
  25976. char fmttype; /* The format field code letter */
  25977. etByte base; /* The base for radix conversion */
  25978. etByte flags; /* One or more of FLAG_ constants below */
  25979. etByte type; /* Conversion paradigm */
  25980. etByte charset; /* Offset into aDigits[] of the digits string */
  25981. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  25982. } et_info;
  25983. /*
  25984. ** Allowed values for et_info.flags
  25985. */
  25986. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  25987. #define FLAG_STRING 4 /* Allow infinite precision */
  25988. /*
  25989. ** The following table is searched linearly, so it is good to put the
  25990. ** most frequently used conversion types first.
  25991. */
  25992. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  25993. static const char aPrefix[] = "-x0\000X0";
  25994. static const et_info fmtinfo[] = {
  25995. { 'd', 10, 1, etDECIMAL, 0, 0 },
  25996. { 's', 0, 4, etSTRING, 0, 0 },
  25997. { 'g', 0, 1, etGENERIC, 30, 0 },
  25998. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  25999. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  26000. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  26001. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  26002. { 'c', 0, 0, etCHARX, 0, 0 },
  26003. { 'o', 8, 0, etRADIX, 0, 2 },
  26004. { 'u', 10, 0, etDECIMAL, 0, 0 },
  26005. { 'x', 16, 0, etRADIX, 16, 1 },
  26006. { 'X', 16, 0, etRADIX, 0, 4 },
  26007. #ifndef SQLITE_OMIT_FLOATING_POINT
  26008. { 'f', 0, 1, etFLOAT, 0, 0 },
  26009. { 'e', 0, 1, etEXP, 30, 0 },
  26010. { 'E', 0, 1, etEXP, 14, 0 },
  26011. { 'G', 0, 1, etGENERIC, 14, 0 },
  26012. #endif
  26013. { 'i', 10, 1, etDECIMAL, 0, 0 },
  26014. { 'n', 0, 0, etSIZE, 0, 0 },
  26015. { '%', 0, 0, etPERCENT, 0, 0 },
  26016. { 'p', 16, 0, etPOINTER, 0, 1 },
  26017. /* All the rest are undocumented and are for internal use only */
  26018. { 'T', 0, 0, etTOKEN, 0, 0 },
  26019. { 'S', 0, 0, etSRCLIST, 0, 0 },
  26020. { 'r', 10, 1, etORDINAL, 0, 0 },
  26021. };
  26022. /*
  26023. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  26024. ** conversions will work.
  26025. */
  26026. #ifndef SQLITE_OMIT_FLOATING_POINT
  26027. /*
  26028. ** "*val" is a double such that 0.1 <= *val < 10.0
  26029. ** Return the ascii code for the leading digit of *val, then
  26030. ** multiply "*val" by 10.0 to renormalize.
  26031. **
  26032. ** Example:
  26033. ** input: *val = 3.14159
  26034. ** output: *val = 1.4159 function return = '3'
  26035. **
  26036. ** The counter *cnt is incremented each time. After counter exceeds
  26037. ** 16 (the number of significant digits in a 64-bit float) '0' is
  26038. ** always returned.
  26039. */
  26040. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  26041. int digit;
  26042. LONGDOUBLE_TYPE d;
  26043. if( (*cnt)<=0 ) return '0';
  26044. (*cnt)--;
  26045. digit = (int)*val;
  26046. d = digit;
  26047. digit += '0';
  26048. *val = (*val - d)*10.0;
  26049. return (char)digit;
  26050. }
  26051. #endif /* SQLITE_OMIT_FLOATING_POINT */
  26052. /*
  26053. ** Set the StrAccum object to an error mode.
  26054. */
  26055. static void setStrAccumError(StrAccum *p, u8 eError){
  26056. assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
  26057. p->accError = eError;
  26058. if( p->mxAlloc ) sqlite3_str_reset(p);
  26059. if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
  26060. }
  26061. /*
  26062. ** Extra argument values from a PrintfArguments object
  26063. */
  26064. static sqlite3_int64 getIntArg(PrintfArguments *p){
  26065. if( p->nArg<=p->nUsed ) return 0;
  26066. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  26067. }
  26068. static double getDoubleArg(PrintfArguments *p){
  26069. if( p->nArg<=p->nUsed ) return 0.0;
  26070. return sqlite3_value_double(p->apArg[p->nUsed++]);
  26071. }
  26072. static char *getTextArg(PrintfArguments *p){
  26073. if( p->nArg<=p->nUsed ) return 0;
  26074. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  26075. }
  26076. /*
  26077. ** Allocate memory for a temporary buffer needed for printf rendering.
  26078. **
  26079. ** If the requested size of the temp buffer is larger than the size
  26080. ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
  26081. ** Do the size check before the memory allocation to prevent rogue
  26082. ** SQL from requesting large allocations using the precision or width
  26083. ** field of the printf() function.
  26084. */
  26085. static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
  26086. char *z;
  26087. if( pAccum->accError ) return 0;
  26088. if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
  26089. setStrAccumError(pAccum, SQLITE_TOOBIG);
  26090. return 0;
  26091. }
  26092. z = sqlite3DbMallocRaw(pAccum->db, n);
  26093. if( z==0 ){
  26094. setStrAccumError(pAccum, SQLITE_NOMEM);
  26095. }
  26096. return z;
  26097. }
  26098. /*
  26099. ** On machines with a small stack size, you can redefine the
  26100. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  26101. */
  26102. #ifndef SQLITE_PRINT_BUF_SIZE
  26103. # define SQLITE_PRINT_BUF_SIZE 70
  26104. #endif
  26105. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  26106. /*
  26107. ** Render a string given by "fmt" into the StrAccum object.
  26108. */
  26109. SQLITE_API void sqlite3_str_vappendf(
  26110. sqlite3_str *pAccum, /* Accumulate results here */
  26111. const char *fmt, /* Format string */
  26112. va_list ap /* arguments */
  26113. ){
  26114. int c; /* Next character in the format string */
  26115. char *bufpt; /* Pointer to the conversion buffer */
  26116. int precision; /* Precision of the current field */
  26117. int length; /* Length of the field */
  26118. int idx; /* A general purpose loop counter */
  26119. int width; /* Width of the current field */
  26120. etByte flag_leftjustify; /* True if "-" flag is present */
  26121. etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
  26122. etByte flag_alternateform; /* True if "#" flag is present */
  26123. etByte flag_altform2; /* True if "!" flag is present */
  26124. etByte flag_zeropad; /* True if field width constant starts with zero */
  26125. etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
  26126. etByte done; /* Loop termination flag */
  26127. etByte cThousand; /* Thousands separator for %d and %u */
  26128. etByte xtype = etINVALID; /* Conversion paradigm */
  26129. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  26130. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  26131. sqlite_uint64 longvalue; /* Value for integer types */
  26132. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  26133. const et_info *infop; /* Pointer to the appropriate info structure */
  26134. char *zOut; /* Rendering buffer */
  26135. int nOut; /* Size of the rendering buffer */
  26136. char *zExtra = 0; /* Malloced memory used by some conversion */
  26137. #ifndef SQLITE_OMIT_FLOATING_POINT
  26138. int exp, e2; /* exponent of real numbers */
  26139. int nsd; /* Number of significant digits returned */
  26140. double rounder; /* Used for rounding floating point values */
  26141. etByte flag_dp; /* True if decimal point should be shown */
  26142. etByte flag_rtz; /* True if trailing zeros should be removed */
  26143. #endif
  26144. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  26145. char buf[etBUFSIZE]; /* Conversion buffer */
  26146. /* pAccum never starts out with an empty buffer that was obtained from
  26147. ** malloc(). This precondition is required by the mprintf("%z...")
  26148. ** optimization. */
  26149. assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  26150. bufpt = 0;
  26151. if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
  26152. pArgList = va_arg(ap, PrintfArguments*);
  26153. bArgList = 1;
  26154. }else{
  26155. bArgList = 0;
  26156. }
  26157. for(; (c=(*fmt))!=0; ++fmt){
  26158. if( c!='%' ){
  26159. bufpt = (char *)fmt;
  26160. #if HAVE_STRCHRNUL
  26161. fmt = strchrnul(fmt, '%');
  26162. #else
  26163. do{ fmt++; }while( *fmt && *fmt != '%' );
  26164. #endif
  26165. sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
  26166. if( *fmt==0 ) break;
  26167. }
  26168. if( (c=(*++fmt))==0 ){
  26169. sqlite3_str_append(pAccum, "%", 1);
  26170. break;
  26171. }
  26172. /* Find out what flags are present */
  26173. flag_leftjustify = flag_prefix = cThousand =
  26174. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  26175. done = 0;
  26176. width = 0;
  26177. flag_long = 0;
  26178. precision = -1;
  26179. do{
  26180. switch( c ){
  26181. case '-': flag_leftjustify = 1; break;
  26182. case '+': flag_prefix = '+'; break;
  26183. case ' ': flag_prefix = ' '; break;
  26184. case '#': flag_alternateform = 1; break;
  26185. case '!': flag_altform2 = 1; break;
  26186. case '0': flag_zeropad = 1; break;
  26187. case ',': cThousand = ','; break;
  26188. default: done = 1; break;
  26189. case 'l': {
  26190. flag_long = 1;
  26191. c = *++fmt;
  26192. if( c=='l' ){
  26193. c = *++fmt;
  26194. flag_long = 2;
  26195. }
  26196. done = 1;
  26197. break;
  26198. }
  26199. case '1': case '2': case '3': case '4': case '5':
  26200. case '6': case '7': case '8': case '9': {
  26201. unsigned wx = c - '0';
  26202. while( (c = *++fmt)>='0' && c<='9' ){
  26203. wx = wx*10 + c - '0';
  26204. }
  26205. testcase( wx>0x7fffffff );
  26206. width = wx & 0x7fffffff;
  26207. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  26208. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  26209. width = SQLITE_PRINTF_PRECISION_LIMIT;
  26210. }
  26211. #endif
  26212. if( c!='.' && c!='l' ){
  26213. done = 1;
  26214. }else{
  26215. fmt--;
  26216. }
  26217. break;
  26218. }
  26219. case '*': {
  26220. if( bArgList ){
  26221. width = (int)getIntArg(pArgList);
  26222. }else{
  26223. width = va_arg(ap,int);
  26224. }
  26225. if( width<0 ){
  26226. flag_leftjustify = 1;
  26227. width = width >= -2147483647 ? -width : 0;
  26228. }
  26229. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  26230. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  26231. width = SQLITE_PRINTF_PRECISION_LIMIT;
  26232. }
  26233. #endif
  26234. if( (c = fmt[1])!='.' && c!='l' ){
  26235. c = *++fmt;
  26236. done = 1;
  26237. }
  26238. break;
  26239. }
  26240. case '.': {
  26241. c = *++fmt;
  26242. if( c=='*' ){
  26243. if( bArgList ){
  26244. precision = (int)getIntArg(pArgList);
  26245. }else{
  26246. precision = va_arg(ap,int);
  26247. }
  26248. if( precision<0 ){
  26249. precision = precision >= -2147483647 ? -precision : -1;
  26250. }
  26251. c = *++fmt;
  26252. }else{
  26253. unsigned px = 0;
  26254. while( c>='0' && c<='9' ){
  26255. px = px*10 + c - '0';
  26256. c = *++fmt;
  26257. }
  26258. testcase( px>0x7fffffff );
  26259. precision = px & 0x7fffffff;
  26260. }
  26261. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  26262. if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
  26263. precision = SQLITE_PRINTF_PRECISION_LIMIT;
  26264. }
  26265. #endif
  26266. if( c=='l' ){
  26267. --fmt;
  26268. }else{
  26269. done = 1;
  26270. }
  26271. break;
  26272. }
  26273. }
  26274. }while( !done && (c=(*++fmt))!=0 );
  26275. /* Fetch the info entry for the field */
  26276. infop = &fmtinfo[0];
  26277. xtype = etINVALID;
  26278. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  26279. if( c==fmtinfo[idx].fmttype ){
  26280. infop = &fmtinfo[idx];
  26281. xtype = infop->type;
  26282. break;
  26283. }
  26284. }
  26285. /*
  26286. ** At this point, variables are initialized as follows:
  26287. **
  26288. ** flag_alternateform TRUE if a '#' is present.
  26289. ** flag_altform2 TRUE if a '!' is present.
  26290. ** flag_prefix '+' or ' ' or zero
  26291. ** flag_leftjustify TRUE if a '-' is present or if the
  26292. ** field width was negative.
  26293. ** flag_zeropad TRUE if the width began with 0.
  26294. ** flag_long 1 for "l", 2 for "ll"
  26295. ** width The specified field width. This is
  26296. ** always non-negative. Zero is the default.
  26297. ** precision The specified precision. The default
  26298. ** is -1.
  26299. ** xtype The class of the conversion.
  26300. ** infop Pointer to the appropriate info struct.
  26301. */
  26302. switch( xtype ){
  26303. case etPOINTER:
  26304. flag_long = sizeof(char*)==sizeof(i64) ? 2 :
  26305. sizeof(char*)==sizeof(long int) ? 1 : 0;
  26306. /* Fall through into the next case */
  26307. case etORDINAL:
  26308. case etRADIX:
  26309. cThousand = 0;
  26310. /* Fall through into the next case */
  26311. case etDECIMAL:
  26312. if( infop->flags & FLAG_SIGNED ){
  26313. i64 v;
  26314. if( bArgList ){
  26315. v = getIntArg(pArgList);
  26316. }else if( flag_long ){
  26317. if( flag_long==2 ){
  26318. v = va_arg(ap,i64) ;
  26319. }else{
  26320. v = va_arg(ap,long int);
  26321. }
  26322. }else{
  26323. v = va_arg(ap,int);
  26324. }
  26325. if( v<0 ){
  26326. if( v==SMALLEST_INT64 ){
  26327. longvalue = ((u64)1)<<63;
  26328. }else{
  26329. longvalue = -v;
  26330. }
  26331. prefix = '-';
  26332. }else{
  26333. longvalue = v;
  26334. prefix = flag_prefix;
  26335. }
  26336. }else{
  26337. if( bArgList ){
  26338. longvalue = (u64)getIntArg(pArgList);
  26339. }else if( flag_long ){
  26340. if( flag_long==2 ){
  26341. longvalue = va_arg(ap,u64);
  26342. }else{
  26343. longvalue = va_arg(ap,unsigned long int);
  26344. }
  26345. }else{
  26346. longvalue = va_arg(ap,unsigned int);
  26347. }
  26348. prefix = 0;
  26349. }
  26350. if( longvalue==0 ) flag_alternateform = 0;
  26351. if( flag_zeropad && precision<width-(prefix!=0) ){
  26352. precision = width-(prefix!=0);
  26353. }
  26354. if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
  26355. nOut = etBUFSIZE;
  26356. zOut = buf;
  26357. }else{
  26358. u64 n;
  26359. n = (u64)precision + 10;
  26360. if( cThousand ) n += precision/3;
  26361. zOut = zExtra = printfTempBuf(pAccum, n);
  26362. if( zOut==0 ) return;
  26363. nOut = (int)n;
  26364. }
  26365. bufpt = &zOut[nOut-1];
  26366. if( xtype==etORDINAL ){
  26367. static const char zOrd[] = "thstndrd";
  26368. int x = (int)(longvalue % 10);
  26369. if( x>=4 || (longvalue/10)%10==1 ){
  26370. x = 0;
  26371. }
  26372. *(--bufpt) = zOrd[x*2+1];
  26373. *(--bufpt) = zOrd[x*2];
  26374. }
  26375. {
  26376. const char *cset = &aDigits[infop->charset];
  26377. u8 base = infop->base;
  26378. do{ /* Convert to ascii */
  26379. *(--bufpt) = cset[longvalue%base];
  26380. longvalue = longvalue/base;
  26381. }while( longvalue>0 );
  26382. }
  26383. length = (int)(&zOut[nOut-1]-bufpt);
  26384. while( precision>length ){
  26385. *(--bufpt) = '0'; /* Zero pad */
  26386. length++;
  26387. }
  26388. if( cThousand ){
  26389. int nn = (length - 1)/3; /* Number of "," to insert */
  26390. int ix = (length - 1)%3 + 1;
  26391. bufpt -= nn;
  26392. for(idx=0; nn>0; idx++){
  26393. bufpt[idx] = bufpt[idx+nn];
  26394. ix--;
  26395. if( ix==0 ){
  26396. bufpt[++idx] = cThousand;
  26397. nn--;
  26398. ix = 3;
  26399. }
  26400. }
  26401. }
  26402. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  26403. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  26404. const char *pre;
  26405. char x;
  26406. pre = &aPrefix[infop->prefix];
  26407. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  26408. }
  26409. length = (int)(&zOut[nOut-1]-bufpt);
  26410. break;
  26411. case etFLOAT:
  26412. case etEXP:
  26413. case etGENERIC:
  26414. if( bArgList ){
  26415. realvalue = getDoubleArg(pArgList);
  26416. }else{
  26417. realvalue = va_arg(ap,double);
  26418. }
  26419. #ifdef SQLITE_OMIT_FLOATING_POINT
  26420. length = 0;
  26421. #else
  26422. if( precision<0 ) precision = 6; /* Set default precision */
  26423. if( realvalue<0.0 ){
  26424. realvalue = -realvalue;
  26425. prefix = '-';
  26426. }else{
  26427. prefix = flag_prefix;
  26428. }
  26429. if( xtype==etGENERIC && precision>0 ) precision--;
  26430. testcase( precision>0xfff );
  26431. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  26432. if( xtype==etFLOAT ) realvalue += rounder;
  26433. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  26434. exp = 0;
  26435. if( sqlite3IsNaN((double)realvalue) ){
  26436. bufpt = "NaN";
  26437. length = 3;
  26438. break;
  26439. }
  26440. if( realvalue>0.0 ){
  26441. LONGDOUBLE_TYPE scale = 1.0;
  26442. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  26443. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  26444. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  26445. realvalue /= scale;
  26446. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  26447. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  26448. if( exp>350 ){
  26449. bufpt = buf;
  26450. buf[0] = prefix;
  26451. memcpy(buf+(prefix!=0),"Inf",4);
  26452. length = 3+(prefix!=0);
  26453. break;
  26454. }
  26455. }
  26456. bufpt = buf;
  26457. /*
  26458. ** If the field type is etGENERIC, then convert to either etEXP
  26459. ** or etFLOAT, as appropriate.
  26460. */
  26461. if( xtype!=etFLOAT ){
  26462. realvalue += rounder;
  26463. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  26464. }
  26465. if( xtype==etGENERIC ){
  26466. flag_rtz = !flag_alternateform;
  26467. if( exp<-4 || exp>precision ){
  26468. xtype = etEXP;
  26469. }else{
  26470. precision = precision - exp;
  26471. xtype = etFLOAT;
  26472. }
  26473. }else{
  26474. flag_rtz = flag_altform2;
  26475. }
  26476. if( xtype==etEXP ){
  26477. e2 = 0;
  26478. }else{
  26479. e2 = exp;
  26480. }
  26481. {
  26482. i64 szBufNeeded; /* Size of a temporary buffer needed */
  26483. szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
  26484. if( szBufNeeded > etBUFSIZE ){
  26485. bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
  26486. if( bufpt==0 ) return;
  26487. }
  26488. }
  26489. zOut = bufpt;
  26490. nsd = 16 + flag_altform2*10;
  26491. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  26492. /* The sign in front of the number */
  26493. if( prefix ){
  26494. *(bufpt++) = prefix;
  26495. }
  26496. /* Digits prior to the decimal point */
  26497. if( e2<0 ){
  26498. *(bufpt++) = '0';
  26499. }else{
  26500. for(; e2>=0; e2--){
  26501. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  26502. }
  26503. }
  26504. /* The decimal point */
  26505. if( flag_dp ){
  26506. *(bufpt++) = '.';
  26507. }
  26508. /* "0" digits after the decimal point but before the first
  26509. ** significant digit of the number */
  26510. for(e2++; e2<0; precision--, e2++){
  26511. assert( precision>0 );
  26512. *(bufpt++) = '0';
  26513. }
  26514. /* Significant digits after the decimal point */
  26515. while( (precision--)>0 ){
  26516. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  26517. }
  26518. /* Remove trailing zeros and the "." if no digits follow the "." */
  26519. if( flag_rtz && flag_dp ){
  26520. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  26521. assert( bufpt>zOut );
  26522. if( bufpt[-1]=='.' ){
  26523. if( flag_altform2 ){
  26524. *(bufpt++) = '0';
  26525. }else{
  26526. *(--bufpt) = 0;
  26527. }
  26528. }
  26529. }
  26530. /* Add the "eNNN" suffix */
  26531. if( xtype==etEXP ){
  26532. *(bufpt++) = aDigits[infop->charset];
  26533. if( exp<0 ){
  26534. *(bufpt++) = '-'; exp = -exp;
  26535. }else{
  26536. *(bufpt++) = '+';
  26537. }
  26538. if( exp>=100 ){
  26539. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  26540. exp %= 100;
  26541. }
  26542. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  26543. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  26544. }
  26545. *bufpt = 0;
  26546. /* The converted number is in buf[] and zero terminated. Output it.
  26547. ** Note that the number is in the usual order, not reversed as with
  26548. ** integer conversions. */
  26549. length = (int)(bufpt-zOut);
  26550. bufpt = zOut;
  26551. /* Special case: Add leading zeros if the flag_zeropad flag is
  26552. ** set and we are not left justified */
  26553. if( flag_zeropad && !flag_leftjustify && length < width){
  26554. int i;
  26555. int nPad = width - length;
  26556. for(i=width; i>=nPad; i--){
  26557. bufpt[i] = bufpt[i-nPad];
  26558. }
  26559. i = prefix!=0;
  26560. while( nPad-- ) bufpt[i++] = '0';
  26561. length = width;
  26562. }
  26563. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  26564. break;
  26565. case etSIZE:
  26566. if( !bArgList ){
  26567. *(va_arg(ap,int*)) = pAccum->nChar;
  26568. }
  26569. length = width = 0;
  26570. break;
  26571. case etPERCENT:
  26572. buf[0] = '%';
  26573. bufpt = buf;
  26574. length = 1;
  26575. break;
  26576. case etCHARX:
  26577. if( bArgList ){
  26578. bufpt = getTextArg(pArgList);
  26579. length = 1;
  26580. if( bufpt ){
  26581. buf[0] = c = *(bufpt++);
  26582. if( (c&0xc0)==0xc0 ){
  26583. while( length<4 && (bufpt[0]&0xc0)==0x80 ){
  26584. buf[length++] = *(bufpt++);
  26585. }
  26586. }
  26587. }else{
  26588. buf[0] = 0;
  26589. }
  26590. }else{
  26591. unsigned int ch = va_arg(ap,unsigned int);
  26592. if( ch<0x00080 ){
  26593. buf[0] = ch & 0xff;
  26594. length = 1;
  26595. }else if( ch<0x00800 ){
  26596. buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
  26597. buf[1] = 0x80 + (u8)(ch & 0x3f);
  26598. length = 2;
  26599. }else if( ch<0x10000 ){
  26600. buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
  26601. buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
  26602. buf[2] = 0x80 + (u8)(ch & 0x3f);
  26603. length = 3;
  26604. }else{
  26605. buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
  26606. buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
  26607. buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
  26608. buf[3] = 0x80 + (u8)(ch & 0x3f);
  26609. length = 4;
  26610. }
  26611. }
  26612. if( precision>1 ){
  26613. width -= precision-1;
  26614. if( width>1 && !flag_leftjustify ){
  26615. sqlite3_str_appendchar(pAccum, width-1, ' ');
  26616. width = 0;
  26617. }
  26618. while( precision-- > 1 ){
  26619. sqlite3_str_append(pAccum, buf, length);
  26620. }
  26621. }
  26622. bufpt = buf;
  26623. flag_altform2 = 1;
  26624. goto adjust_width_for_utf8;
  26625. case etSTRING:
  26626. case etDYNSTRING:
  26627. if( bArgList ){
  26628. bufpt = getTextArg(pArgList);
  26629. xtype = etSTRING;
  26630. }else{
  26631. bufpt = va_arg(ap,char*);
  26632. }
  26633. if( bufpt==0 ){
  26634. bufpt = "";
  26635. }else if( xtype==etDYNSTRING ){
  26636. if( pAccum->nChar==0
  26637. && pAccum->mxAlloc
  26638. && width==0
  26639. && precision<0
  26640. && pAccum->accError==0
  26641. ){
  26642. /* Special optimization for sqlite3_mprintf("%z..."):
  26643. ** Extend an existing memory allocation rather than creating
  26644. ** a new one. */
  26645. assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  26646. pAccum->zText = bufpt;
  26647. pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
  26648. pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
  26649. pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
  26650. length = 0;
  26651. break;
  26652. }
  26653. zExtra = bufpt;
  26654. }
  26655. if( precision>=0 ){
  26656. if( flag_altform2 ){
  26657. /* Set length to the number of bytes needed in order to display
  26658. ** precision characters */
  26659. unsigned char *z = (unsigned char*)bufpt;
  26660. while( precision-- > 0 && z[0] ){
  26661. SQLITE_SKIP_UTF8(z);
  26662. }
  26663. length = (int)(z - (unsigned char*)bufpt);
  26664. }else{
  26665. for(length=0; length<precision && bufpt[length]; length++){}
  26666. }
  26667. }else{
  26668. length = 0x7fffffff & (int)strlen(bufpt);
  26669. }
  26670. adjust_width_for_utf8:
  26671. if( flag_altform2 && width>0 ){
  26672. /* Adjust width to account for extra bytes in UTF-8 characters */
  26673. int ii = length - 1;
  26674. while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
  26675. }
  26676. break;
  26677. case etSQLESCAPE: /* %q: Escape ' characters */
  26678. case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
  26679. case etSQLESCAPE3: { /* %w: Escape " characters */
  26680. int i, j, k, n, isnull;
  26681. int needQuote;
  26682. char ch;
  26683. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  26684. char *escarg;
  26685. if( bArgList ){
  26686. escarg = getTextArg(pArgList);
  26687. }else{
  26688. escarg = va_arg(ap,char*);
  26689. }
  26690. isnull = escarg==0;
  26691. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  26692. /* For %q, %Q, and %w, the precision is the number of byte (or
  26693. ** characters if the ! flags is present) to use from the input.
  26694. ** Because of the extra quoting characters inserted, the number
  26695. ** of output characters may be larger than the precision.
  26696. */
  26697. k = precision;
  26698. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  26699. if( ch==q ) n++;
  26700. if( flag_altform2 && (ch&0xc0)==0xc0 ){
  26701. while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
  26702. }
  26703. }
  26704. needQuote = !isnull && xtype==etSQLESCAPE2;
  26705. n += i + 3;
  26706. if( n>etBUFSIZE ){
  26707. bufpt = zExtra = printfTempBuf(pAccum, n);
  26708. if( bufpt==0 ) return;
  26709. }else{
  26710. bufpt = buf;
  26711. }
  26712. j = 0;
  26713. if( needQuote ) bufpt[j++] = q;
  26714. k = i;
  26715. for(i=0; i<k; i++){
  26716. bufpt[j++] = ch = escarg[i];
  26717. if( ch==q ) bufpt[j++] = ch;
  26718. }
  26719. if( needQuote ) bufpt[j++] = q;
  26720. bufpt[j] = 0;
  26721. length = j;
  26722. goto adjust_width_for_utf8;
  26723. }
  26724. case etTOKEN: {
  26725. Token *pToken;
  26726. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  26727. pToken = va_arg(ap, Token*);
  26728. assert( bArgList==0 );
  26729. if( pToken && pToken->n ){
  26730. sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
  26731. }
  26732. length = width = 0;
  26733. break;
  26734. }
  26735. case etSRCLIST: {
  26736. SrcList *pSrc;
  26737. int k;
  26738. struct SrcList_item *pItem;
  26739. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  26740. pSrc = va_arg(ap, SrcList*);
  26741. k = va_arg(ap, int);
  26742. pItem = &pSrc->a[k];
  26743. assert( bArgList==0 );
  26744. assert( k>=0 && k<pSrc->nSrc );
  26745. if( pItem->zDatabase ){
  26746. sqlite3_str_appendall(pAccum, pItem->zDatabase);
  26747. sqlite3_str_append(pAccum, ".", 1);
  26748. }
  26749. sqlite3_str_appendall(pAccum, pItem->zName);
  26750. length = width = 0;
  26751. break;
  26752. }
  26753. default: {
  26754. assert( xtype==etINVALID );
  26755. return;
  26756. }
  26757. }/* End switch over the format type */
  26758. /*
  26759. ** The text of the conversion is pointed to by "bufpt" and is
  26760. ** "length" characters long. The field width is "width". Do
  26761. ** the output. Both length and width are in bytes, not characters,
  26762. ** at this point. If the "!" flag was present on string conversions
  26763. ** indicating that width and precision should be expressed in characters,
  26764. ** then the values have been translated prior to reaching this point.
  26765. */
  26766. width -= length;
  26767. if( width>0 ){
  26768. if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
  26769. sqlite3_str_append(pAccum, bufpt, length);
  26770. if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
  26771. }else{
  26772. sqlite3_str_append(pAccum, bufpt, length);
  26773. }
  26774. if( zExtra ){
  26775. sqlite3DbFree(pAccum->db, zExtra);
  26776. zExtra = 0;
  26777. }
  26778. }/* End for loop over the format string */
  26779. } /* End of function */
  26780. /*
  26781. ** Enlarge the memory allocation on a StrAccum object so that it is
  26782. ** able to accept at least N more bytes of text.
  26783. **
  26784. ** Return the number of bytes of text that StrAccum is able to accept
  26785. ** after the attempted enlargement. The value returned might be zero.
  26786. */
  26787. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  26788. char *zNew;
  26789. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  26790. if( p->accError ){
  26791. testcase(p->accError==SQLITE_TOOBIG);
  26792. testcase(p->accError==SQLITE_NOMEM);
  26793. return 0;
  26794. }
  26795. if( p->mxAlloc==0 ){
  26796. setStrAccumError(p, SQLITE_TOOBIG);
  26797. return p->nAlloc - p->nChar - 1;
  26798. }else{
  26799. char *zOld = isMalloced(p) ? p->zText : 0;
  26800. i64 szNew = p->nChar;
  26801. szNew += N + 1;
  26802. if( szNew+p->nChar<=p->mxAlloc ){
  26803. /* Force exponential buffer size growth as long as it does not overflow,
  26804. ** to avoid having to call this routine too often */
  26805. szNew += p->nChar;
  26806. }
  26807. if( szNew > p->mxAlloc ){
  26808. sqlite3_str_reset(p);
  26809. setStrAccumError(p, SQLITE_TOOBIG);
  26810. return 0;
  26811. }else{
  26812. p->nAlloc = (int)szNew;
  26813. }
  26814. if( p->db ){
  26815. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  26816. }else{
  26817. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  26818. }
  26819. if( zNew ){
  26820. assert( p->zText!=0 || p->nChar==0 );
  26821. if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  26822. p->zText = zNew;
  26823. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  26824. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  26825. }else{
  26826. sqlite3_str_reset(p);
  26827. setStrAccumError(p, SQLITE_NOMEM);
  26828. return 0;
  26829. }
  26830. }
  26831. return N;
  26832. }
  26833. /*
  26834. ** Append N copies of character c to the given string buffer.
  26835. */
  26836. SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
  26837. testcase( p->nChar + (i64)N > 0x7fffffff );
  26838. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  26839. return;
  26840. }
  26841. while( (N--)>0 ) p->zText[p->nChar++] = c;
  26842. }
  26843. /*
  26844. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  26845. ** So enlarge if first, then do the append.
  26846. **
  26847. ** This is a helper routine to sqlite3_str_append() that does special-case
  26848. ** work (enlarging the buffer) using tail recursion, so that the
  26849. ** sqlite3_str_append() routine can use fast calling semantics.
  26850. */
  26851. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  26852. N = sqlite3StrAccumEnlarge(p, N);
  26853. if( N>0 ){
  26854. memcpy(&p->zText[p->nChar], z, N);
  26855. p->nChar += N;
  26856. }
  26857. }
  26858. /*
  26859. ** Append N bytes of text from z to the StrAccum object. Increase the
  26860. ** size of the memory allocation for StrAccum if necessary.
  26861. */
  26862. SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
  26863. assert( z!=0 || N==0 );
  26864. assert( p->zText!=0 || p->nChar==0 || p->accError );
  26865. assert( N>=0 );
  26866. assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
  26867. if( p->nChar+N >= p->nAlloc ){
  26868. enlargeAndAppend(p,z,N);
  26869. }else if( N ){
  26870. assert( p->zText );
  26871. p->nChar += N;
  26872. memcpy(&p->zText[p->nChar-N], z, N);
  26873. }
  26874. }
  26875. /*
  26876. ** Append the complete text of zero-terminated string z[] to the p string.
  26877. */
  26878. SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
  26879. sqlite3_str_append(p, z, sqlite3Strlen30(z));
  26880. }
  26881. /*
  26882. ** Finish off a string by making sure it is zero-terminated.
  26883. ** Return a pointer to the resulting string. Return a NULL
  26884. ** pointer if any kind of error was encountered.
  26885. */
  26886. static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
  26887. char *zText;
  26888. assert( p->mxAlloc>0 && !isMalloced(p) );
  26889. zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  26890. if( zText ){
  26891. memcpy(zText, p->zText, p->nChar+1);
  26892. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  26893. }else{
  26894. setStrAccumError(p, SQLITE_NOMEM);
  26895. }
  26896. p->zText = zText;
  26897. return zText;
  26898. }
  26899. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  26900. if( p->zText ){
  26901. p->zText[p->nChar] = 0;
  26902. if( p->mxAlloc>0 && !isMalloced(p) ){
  26903. return strAccumFinishRealloc(p);
  26904. }
  26905. }
  26906. return p->zText;
  26907. }
  26908. /*
  26909. ** This singleton is an sqlite3_str object that is returned if
  26910. ** sqlite3_malloc() fails to provide space for a real one. This
  26911. ** sqlite3_str object accepts no new text and always returns
  26912. ** an SQLITE_NOMEM error.
  26913. */
  26914. static sqlite3_str sqlite3OomStr = {
  26915. 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
  26916. };
  26917. /* Finalize a string created using sqlite3_str_new().
  26918. */
  26919. SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
  26920. char *z;
  26921. if( p!=0 && p!=&sqlite3OomStr ){
  26922. z = sqlite3StrAccumFinish(p);
  26923. sqlite3_free(p);
  26924. }else{
  26925. z = 0;
  26926. }
  26927. return z;
  26928. }
  26929. /* Return any error code associated with p */
  26930. SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){
  26931. return p ? p->accError : SQLITE_NOMEM;
  26932. }
  26933. /* Return the current length of p in bytes */
  26934. SQLITE_API int sqlite3_str_length(sqlite3_str *p){
  26935. return p ? p->nChar : 0;
  26936. }
  26937. /* Return the current value for p */
  26938. SQLITE_API char *sqlite3_str_value(sqlite3_str *p){
  26939. if( p==0 || p->nChar==0 ) return 0;
  26940. p->zText[p->nChar] = 0;
  26941. return p->zText;
  26942. }
  26943. /*
  26944. ** Reset an StrAccum string. Reclaim all malloced memory.
  26945. */
  26946. SQLITE_API void sqlite3_str_reset(StrAccum *p){
  26947. if( isMalloced(p) ){
  26948. sqlite3DbFree(p->db, p->zText);
  26949. p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
  26950. }
  26951. p->nAlloc = 0;
  26952. p->nChar = 0;
  26953. p->zText = 0;
  26954. }
  26955. /*
  26956. ** Initialize a string accumulator.
  26957. **
  26958. ** p: The accumulator to be initialized.
  26959. ** db: Pointer to a database connection. May be NULL. Lookaside
  26960. ** memory is used if not NULL. db->mallocFailed is set appropriately
  26961. ** when not NULL.
  26962. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  26963. ** is malloced.
  26964. ** n: Size of zBase in bytes. If total space requirements never exceed
  26965. ** n then no memory allocations ever occur.
  26966. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  26967. ** allocations will ever occur.
  26968. */
  26969. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  26970. p->zText = zBase;
  26971. p->db = db;
  26972. p->nAlloc = n;
  26973. p->mxAlloc = mx;
  26974. p->nChar = 0;
  26975. p->accError = 0;
  26976. p->printfFlags = 0;
  26977. }
  26978. /* Allocate and initialize a new dynamic string object */
  26979. SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){
  26980. sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
  26981. if( p ){
  26982. sqlite3StrAccumInit(p, 0, 0, 0,
  26983. db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
  26984. }else{
  26985. p = &sqlite3OomStr;
  26986. }
  26987. return p;
  26988. }
  26989. /*
  26990. ** Print into memory obtained from sqliteMalloc(). Use the internal
  26991. ** %-conversion extensions.
  26992. */
  26993. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  26994. char *z;
  26995. char zBase[SQLITE_PRINT_BUF_SIZE];
  26996. StrAccum acc;
  26997. assert( db!=0 );
  26998. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  26999. db->aLimit[SQLITE_LIMIT_LENGTH]);
  27000. acc.printfFlags = SQLITE_PRINTF_INTERNAL;
  27001. sqlite3_str_vappendf(&acc, zFormat, ap);
  27002. z = sqlite3StrAccumFinish(&acc);
  27003. if( acc.accError==SQLITE_NOMEM ){
  27004. sqlite3OomFault(db);
  27005. }
  27006. return z;
  27007. }
  27008. /*
  27009. ** Print into memory obtained from sqliteMalloc(). Use the internal
  27010. ** %-conversion extensions.
  27011. */
  27012. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  27013. va_list ap;
  27014. char *z;
  27015. va_start(ap, zFormat);
  27016. z = sqlite3VMPrintf(db, zFormat, ap);
  27017. va_end(ap);
  27018. return z;
  27019. }
  27020. /*
  27021. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  27022. ** %-conversion extensions.
  27023. */
  27024. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  27025. char *z;
  27026. char zBase[SQLITE_PRINT_BUF_SIZE];
  27027. StrAccum acc;
  27028. #ifdef SQLITE_ENABLE_API_ARMOR
  27029. if( zFormat==0 ){
  27030. (void)SQLITE_MISUSE_BKPT;
  27031. return 0;
  27032. }
  27033. #endif
  27034. #ifndef SQLITE_OMIT_AUTOINIT
  27035. if( sqlite3_initialize() ) return 0;
  27036. #endif
  27037. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  27038. sqlite3_str_vappendf(&acc, zFormat, ap);
  27039. z = sqlite3StrAccumFinish(&acc);
  27040. return z;
  27041. }
  27042. /*
  27043. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  27044. ** %-conversion extensions.
  27045. */
  27046. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  27047. va_list ap;
  27048. char *z;
  27049. #ifndef SQLITE_OMIT_AUTOINIT
  27050. if( sqlite3_initialize() ) return 0;
  27051. #endif
  27052. va_start(ap, zFormat);
  27053. z = sqlite3_vmprintf(zFormat, ap);
  27054. va_end(ap);
  27055. return z;
  27056. }
  27057. /*
  27058. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  27059. ** current locale settings. This is important for SQLite because we
  27060. ** are not able to use a "," as the decimal point in place of "." as
  27061. ** specified by some locales.
  27062. **
  27063. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  27064. ** from the snprintf() standard. Unfortunately, it is too late to change
  27065. ** this without breaking compatibility, so we just have to live with the
  27066. ** mistake.
  27067. **
  27068. ** sqlite3_vsnprintf() is the varargs version.
  27069. */
  27070. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  27071. StrAccum acc;
  27072. if( n<=0 ) return zBuf;
  27073. #ifdef SQLITE_ENABLE_API_ARMOR
  27074. if( zBuf==0 || zFormat==0 ) {
  27075. (void)SQLITE_MISUSE_BKPT;
  27076. if( zBuf ) zBuf[0] = 0;
  27077. return zBuf;
  27078. }
  27079. #endif
  27080. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  27081. sqlite3_str_vappendf(&acc, zFormat, ap);
  27082. zBuf[acc.nChar] = 0;
  27083. return zBuf;
  27084. }
  27085. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  27086. char *z;
  27087. va_list ap;
  27088. va_start(ap,zFormat);
  27089. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  27090. va_end(ap);
  27091. return z;
  27092. }
  27093. /*
  27094. ** This is the routine that actually formats the sqlite3_log() message.
  27095. ** We house it in a separate routine from sqlite3_log() to avoid using
  27096. ** stack space on small-stack systems when logging is disabled.
  27097. **
  27098. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  27099. ** allocate memory because it might be called while the memory allocator
  27100. ** mutex is held.
  27101. **
  27102. ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
  27103. ** certain format characters (%q) or for very large precisions or widths.
  27104. ** Care must be taken that any sqlite3_log() calls that occur while the
  27105. ** memory mutex is held do not use these mechanisms.
  27106. */
  27107. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  27108. StrAccum acc; /* String accumulator */
  27109. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  27110. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  27111. sqlite3_str_vappendf(&acc, zFormat, ap);
  27112. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  27113. sqlite3StrAccumFinish(&acc));
  27114. }
  27115. /*
  27116. ** Format and write a message to the log if logging is enabled.
  27117. */
  27118. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  27119. va_list ap; /* Vararg list */
  27120. if( sqlite3GlobalConfig.xLog ){
  27121. va_start(ap, zFormat);
  27122. renderLogMsg(iErrCode, zFormat, ap);
  27123. va_end(ap);
  27124. }
  27125. }
  27126. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  27127. /*
  27128. ** A version of printf() that understands %lld. Used for debugging.
  27129. ** The printf() built into some versions of windows does not understand %lld
  27130. ** and segfaults if you give it a long long int.
  27131. */
  27132. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  27133. va_list ap;
  27134. StrAccum acc;
  27135. char zBuf[500];
  27136. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  27137. va_start(ap,zFormat);
  27138. sqlite3_str_vappendf(&acc, zFormat, ap);
  27139. va_end(ap);
  27140. sqlite3StrAccumFinish(&acc);
  27141. #ifdef SQLITE_OS_TRACE_PROC
  27142. {
  27143. extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
  27144. SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
  27145. }
  27146. #else
  27147. fprintf(stdout,"%s", zBuf);
  27148. fflush(stdout);
  27149. #endif
  27150. }
  27151. #endif
  27152. /*
  27153. ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
  27154. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  27155. */
  27156. SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
  27157. va_list ap;
  27158. va_start(ap,zFormat);
  27159. sqlite3_str_vappendf(p, zFormat, ap);
  27160. va_end(ap);
  27161. }
  27162. /************** End of printf.c **********************************************/
  27163. /************** Begin file treeview.c ****************************************/
  27164. /*
  27165. ** 2015-06-08
  27166. **
  27167. ** The author disclaims copyright to this source code. In place of
  27168. ** a legal notice, here is a blessing:
  27169. **
  27170. ** May you do good and not evil.
  27171. ** May you find forgiveness for yourself and forgive others.
  27172. ** May you share freely, never taking more than you give.
  27173. **
  27174. *************************************************************************
  27175. **
  27176. ** This file contains C code to implement the TreeView debugging routines.
  27177. ** These routines print a parse tree to standard output for debugging and
  27178. ** analysis.
  27179. **
  27180. ** The interfaces in this file is only available when compiling
  27181. ** with SQLITE_DEBUG.
  27182. */
  27183. /* #include "sqliteInt.h" */
  27184. #ifdef SQLITE_DEBUG
  27185. /*
  27186. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  27187. ** is not the last item in the tree.
  27188. */
  27189. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  27190. if( p==0 ){
  27191. p = sqlite3_malloc64( sizeof(*p) );
  27192. if( p==0 ) return 0;
  27193. memset(p, 0, sizeof(*p));
  27194. }else{
  27195. p->iLevel++;
  27196. }
  27197. assert( moreToFollow==0 || moreToFollow==1 );
  27198. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  27199. return p;
  27200. }
  27201. /*
  27202. ** Finished with one layer of the tree
  27203. */
  27204. static void sqlite3TreeViewPop(TreeView *p){
  27205. if( p==0 ) return;
  27206. p->iLevel--;
  27207. if( p->iLevel<0 ) sqlite3_free(p);
  27208. }
  27209. /*
  27210. ** Generate a single line of output for the tree, with a prefix that contains
  27211. ** all the appropriate tree lines
  27212. */
  27213. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  27214. va_list ap;
  27215. int i;
  27216. StrAccum acc;
  27217. char zBuf[500];
  27218. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  27219. if( p ){
  27220. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  27221. sqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4);
  27222. }
  27223. sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  27224. }
  27225. if( zFormat!=0 ){
  27226. va_start(ap, zFormat);
  27227. sqlite3_str_vappendf(&acc, zFormat, ap);
  27228. va_end(ap);
  27229. assert( acc.nChar>0 );
  27230. sqlite3_str_append(&acc, "\n", 1);
  27231. }
  27232. sqlite3StrAccumFinish(&acc);
  27233. fprintf(stdout,"%s", zBuf);
  27234. fflush(stdout);
  27235. }
  27236. /*
  27237. ** Shorthand for starting a new tree item that consists of a single label
  27238. */
  27239. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  27240. p = sqlite3TreeViewPush(p, moreFollows);
  27241. sqlite3TreeViewLine(p, "%s", zLabel);
  27242. }
  27243. /*
  27244. ** Generate a human-readable description of a WITH clause.
  27245. */
  27246. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
  27247. int i;
  27248. if( pWith==0 ) return;
  27249. if( pWith->nCte==0 ) return;
  27250. if( pWith->pOuter ){
  27251. sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
  27252. }else{
  27253. sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
  27254. }
  27255. if( pWith->nCte>0 ){
  27256. pView = sqlite3TreeViewPush(pView, 1);
  27257. for(i=0; i<pWith->nCte; i++){
  27258. StrAccum x;
  27259. char zLine[1000];
  27260. const struct Cte *pCte = &pWith->a[i];
  27261. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  27262. sqlite3_str_appendf(&x, "%s", pCte->zName);
  27263. if( pCte->pCols && pCte->pCols->nExpr>0 ){
  27264. char cSep = '(';
  27265. int j;
  27266. for(j=0; j<pCte->pCols->nExpr; j++){
  27267. sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
  27268. cSep = ',';
  27269. }
  27270. sqlite3_str_appendf(&x, ")");
  27271. }
  27272. sqlite3_str_appendf(&x, " AS");
  27273. sqlite3StrAccumFinish(&x);
  27274. sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
  27275. sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
  27276. sqlite3TreeViewPop(pView);
  27277. }
  27278. sqlite3TreeViewPop(pView);
  27279. }
  27280. }
  27281. /*
  27282. ** Generate a human-readable description of a SrcList object.
  27283. */
  27284. SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){
  27285. int i;
  27286. for(i=0; i<pSrc->nSrc; i++){
  27287. const struct SrcList_item *pItem = &pSrc->a[i];
  27288. StrAccum x;
  27289. char zLine[100];
  27290. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  27291. sqlite3_str_appendf(&x, "{%d,*}", pItem->iCursor);
  27292. if( pItem->zDatabase ){
  27293. sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
  27294. }else if( pItem->zName ){
  27295. sqlite3_str_appendf(&x, " %s", pItem->zName);
  27296. }
  27297. if( pItem->pTab ){
  27298. sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p",
  27299. pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab);
  27300. }
  27301. if( pItem->zAlias ){
  27302. sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
  27303. }
  27304. if( pItem->fg.jointype & JT_LEFT ){
  27305. sqlite3_str_appendf(&x, " LEFT-JOIN");
  27306. }
  27307. sqlite3StrAccumFinish(&x);
  27308. sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1);
  27309. if( pItem->pSelect ){
  27310. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  27311. }
  27312. if( pItem->fg.isTabFunc ){
  27313. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  27314. }
  27315. sqlite3TreeViewPop(pView);
  27316. }
  27317. }
  27318. /*
  27319. ** Generate a human-readable description of a Select object.
  27320. */
  27321. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  27322. int n = 0;
  27323. int cnt = 0;
  27324. if( p==0 ){
  27325. sqlite3TreeViewLine(pView, "nil-SELECT");
  27326. return;
  27327. }
  27328. pView = sqlite3TreeViewPush(pView, moreToFollow);
  27329. if( p->pWith ){
  27330. sqlite3TreeViewWith(pView, p->pWith, 1);
  27331. cnt = 1;
  27332. sqlite3TreeViewPush(pView, 1);
  27333. }
  27334. do{
  27335. sqlite3TreeViewLine(pView,
  27336. "SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d",
  27337. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  27338. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
  27339. p->selId, p, p->selFlags,
  27340. (int)p->nSelectRow
  27341. );
  27342. if( cnt++ ) sqlite3TreeViewPop(pView);
  27343. if( p->pPrior ){
  27344. n = 1000;
  27345. }else{
  27346. n = 0;
  27347. if( p->pSrc && p->pSrc->nSrc ) n++;
  27348. if( p->pWhere ) n++;
  27349. if( p->pGroupBy ) n++;
  27350. if( p->pHaving ) n++;
  27351. if( p->pOrderBy ) n++;
  27352. if( p->pLimit ) n++;
  27353. #ifndef SQLITE_OMIT_WINDOWFUNC
  27354. if( p->pWin ) n++;
  27355. if( p->pWinDefn ) n++;
  27356. #endif
  27357. }
  27358. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  27359. #ifndef SQLITE_OMIT_WINDOWFUNC
  27360. if( p->pWin ){
  27361. Window *pX;
  27362. pView = sqlite3TreeViewPush(pView, (n--)>0);
  27363. sqlite3TreeViewLine(pView, "window-functions");
  27364. for(pX=p->pWin; pX; pX=pX->pNextWin){
  27365. sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);
  27366. }
  27367. sqlite3TreeViewPop(pView);
  27368. }
  27369. #endif
  27370. if( p->pSrc && p->pSrc->nSrc ){
  27371. pView = sqlite3TreeViewPush(pView, (n--)>0);
  27372. sqlite3TreeViewLine(pView, "FROM");
  27373. sqlite3TreeViewSrcList(pView, p->pSrc);
  27374. sqlite3TreeViewPop(pView);
  27375. }
  27376. if( p->pWhere ){
  27377. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  27378. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  27379. sqlite3TreeViewPop(pView);
  27380. }
  27381. if( p->pGroupBy ){
  27382. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  27383. }
  27384. if( p->pHaving ){
  27385. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  27386. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  27387. sqlite3TreeViewPop(pView);
  27388. }
  27389. #ifndef SQLITE_OMIT_WINDOWFUNC
  27390. if( p->pWinDefn ){
  27391. Window *pX;
  27392. sqlite3TreeViewItem(pView, "WINDOW", (n--)>0);
  27393. for(pX=p->pWinDefn; pX; pX=pX->pNextWin){
  27394. sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0);
  27395. }
  27396. sqlite3TreeViewPop(pView);
  27397. }
  27398. #endif
  27399. if( p->pOrderBy ){
  27400. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  27401. }
  27402. if( p->pLimit ){
  27403. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  27404. sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
  27405. if( p->pLimit->pRight ){
  27406. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  27407. sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
  27408. sqlite3TreeViewPop(pView);
  27409. }
  27410. sqlite3TreeViewPop(pView);
  27411. }
  27412. if( p->pPrior ){
  27413. const char *zOp = "UNION";
  27414. switch( p->op ){
  27415. case TK_ALL: zOp = "UNION ALL"; break;
  27416. case TK_INTERSECT: zOp = "INTERSECT"; break;
  27417. case TK_EXCEPT: zOp = "EXCEPT"; break;
  27418. }
  27419. sqlite3TreeViewItem(pView, zOp, 1);
  27420. }
  27421. p = p->pPrior;
  27422. }while( p!=0 );
  27423. sqlite3TreeViewPop(pView);
  27424. }
  27425. #ifndef SQLITE_OMIT_WINDOWFUNC
  27426. /*
  27427. ** Generate a description of starting or stopping bounds
  27428. */
  27429. SQLITE_PRIVATE void sqlite3TreeViewBound(
  27430. TreeView *pView, /* View context */
  27431. u8 eBound, /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */
  27432. Expr *pExpr, /* Value for PRECEDING or FOLLOWING */
  27433. u8 moreToFollow /* True if more to follow */
  27434. ){
  27435. switch( eBound ){
  27436. case TK_UNBOUNDED: {
  27437. sqlite3TreeViewItem(pView, "UNBOUNDED", moreToFollow);
  27438. sqlite3TreeViewPop(pView);
  27439. break;
  27440. }
  27441. case TK_CURRENT: {
  27442. sqlite3TreeViewItem(pView, "CURRENT", moreToFollow);
  27443. sqlite3TreeViewPop(pView);
  27444. break;
  27445. }
  27446. case TK_PRECEDING: {
  27447. sqlite3TreeViewItem(pView, "PRECEDING", moreToFollow);
  27448. sqlite3TreeViewExpr(pView, pExpr, 0);
  27449. sqlite3TreeViewPop(pView);
  27450. break;
  27451. }
  27452. case TK_FOLLOWING: {
  27453. sqlite3TreeViewItem(pView, "FOLLOWING", moreToFollow);
  27454. sqlite3TreeViewExpr(pView, pExpr, 0);
  27455. sqlite3TreeViewPop(pView);
  27456. break;
  27457. }
  27458. }
  27459. }
  27460. #endif /* SQLITE_OMIT_WINDOWFUNC */
  27461. #ifndef SQLITE_OMIT_WINDOWFUNC
  27462. /*
  27463. ** Generate a human-readable explanation for a Window object
  27464. */
  27465. SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){
  27466. int nElement = 0;
  27467. if( pWin->pFilter ){
  27468. sqlite3TreeViewItem(pView, "FILTER", 1);
  27469. sqlite3TreeViewExpr(pView, pWin->pFilter, 0);
  27470. sqlite3TreeViewPop(pView);
  27471. }
  27472. pView = sqlite3TreeViewPush(pView, more);
  27473. if( pWin->zName ){
  27474. sqlite3TreeViewLine(pView, "OVER %s (%p)", pWin->zName, pWin);
  27475. }else{
  27476. sqlite3TreeViewLine(pView, "OVER (%p)", pWin);
  27477. }
  27478. if( pWin->zBase ) nElement++;
  27479. if( pWin->pOrderBy ) nElement++;
  27480. if( pWin->eFrmType ) nElement++;
  27481. if( pWin->eExclude ) nElement++;
  27482. if( pWin->zBase ){
  27483. sqlite3TreeViewPush(pView, (--nElement)>0);
  27484. sqlite3TreeViewLine(pView, "window: %s", pWin->zBase);
  27485. sqlite3TreeViewPop(pView);
  27486. }
  27487. if( pWin->pPartition ){
  27488. sqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,"PARTITION-BY");
  27489. }
  27490. if( pWin->pOrderBy ){
  27491. sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY");
  27492. }
  27493. if( pWin->eFrmType ){
  27494. char zBuf[30];
  27495. const char *zFrmType = "ROWS";
  27496. if( pWin->eFrmType==TK_RANGE ) zFrmType = "RANGE";
  27497. if( pWin->eFrmType==TK_GROUPS ) zFrmType = "GROUPS";
  27498. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s%s",zFrmType,
  27499. pWin->bImplicitFrame ? " (implied)" : "");
  27500. sqlite3TreeViewItem(pView, zBuf, (--nElement)>0);
  27501. sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1);
  27502. sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0);
  27503. sqlite3TreeViewPop(pView);
  27504. }
  27505. if( pWin->eExclude ){
  27506. char zBuf[30];
  27507. const char *zExclude;
  27508. switch( pWin->eExclude ){
  27509. case TK_NO: zExclude = "NO OTHERS"; break;
  27510. case TK_CURRENT: zExclude = "CURRENT ROW"; break;
  27511. case TK_GROUP: zExclude = "GROUP"; break;
  27512. case TK_TIES: zExclude = "TIES"; break;
  27513. default:
  27514. sqlite3_snprintf(sizeof(zBuf),zBuf,"invalid(%d)", pWin->eExclude);
  27515. zExclude = zBuf;
  27516. break;
  27517. }
  27518. sqlite3TreeViewPush(pView, 0);
  27519. sqlite3TreeViewLine(pView, "EXCLUDE %s", zExclude);
  27520. sqlite3TreeViewPop(pView);
  27521. }
  27522. sqlite3TreeViewPop(pView);
  27523. }
  27524. #endif /* SQLITE_OMIT_WINDOWFUNC */
  27525. #ifndef SQLITE_OMIT_WINDOWFUNC
  27526. /*
  27527. ** Generate a human-readable explanation for a Window Function object
  27528. */
  27529. SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){
  27530. pView = sqlite3TreeViewPush(pView, more);
  27531. sqlite3TreeViewLine(pView, "WINFUNC %s(%d)",
  27532. pWin->pFunc->zName, pWin->pFunc->nArg);
  27533. sqlite3TreeViewWindow(pView, pWin, 0);
  27534. sqlite3TreeViewPop(pView);
  27535. }
  27536. #endif /* SQLITE_OMIT_WINDOWFUNC */
  27537. /*
  27538. ** Generate a human-readable explanation of an expression tree.
  27539. */
  27540. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  27541. const char *zBinOp = 0; /* Binary operator */
  27542. const char *zUniOp = 0; /* Unary operator */
  27543. char zFlgs[60];
  27544. pView = sqlite3TreeViewPush(pView, moreToFollow);
  27545. if( pExpr==0 ){
  27546. sqlite3TreeViewLine(pView, "nil");
  27547. sqlite3TreeViewPop(pView);
  27548. return;
  27549. }
  27550. if( pExpr->flags ){
  27551. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  27552. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x iRJT=%d",
  27553. pExpr->flags, pExpr->iRightJoinTable);
  27554. }else{
  27555. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  27556. }
  27557. }else{
  27558. zFlgs[0] = 0;
  27559. }
  27560. switch( pExpr->op ){
  27561. case TK_AGG_COLUMN: {
  27562. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  27563. pExpr->iTable, pExpr->iColumn, zFlgs);
  27564. break;
  27565. }
  27566. case TK_COLUMN: {
  27567. if( pExpr->iTable<0 ){
  27568. /* This only happens when coding check constraints */
  27569. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  27570. }else{
  27571. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  27572. pExpr->iTable, pExpr->iColumn, zFlgs);
  27573. }
  27574. if( ExprHasProperty(pExpr, EP_FixedCol) ){
  27575. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27576. }
  27577. break;
  27578. }
  27579. case TK_INTEGER: {
  27580. if( pExpr->flags & EP_IntValue ){
  27581. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  27582. }else{
  27583. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  27584. }
  27585. break;
  27586. }
  27587. #ifndef SQLITE_OMIT_FLOATING_POINT
  27588. case TK_FLOAT: {
  27589. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  27590. break;
  27591. }
  27592. #endif
  27593. case TK_STRING: {
  27594. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  27595. break;
  27596. }
  27597. case TK_NULL: {
  27598. sqlite3TreeViewLine(pView,"NULL");
  27599. break;
  27600. }
  27601. case TK_TRUEFALSE: {
  27602. sqlite3TreeViewLine(pView,
  27603. sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE");
  27604. break;
  27605. }
  27606. #ifndef SQLITE_OMIT_BLOB_LITERAL
  27607. case TK_BLOB: {
  27608. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  27609. break;
  27610. }
  27611. #endif
  27612. case TK_VARIABLE: {
  27613. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  27614. pExpr->u.zToken, pExpr->iColumn);
  27615. break;
  27616. }
  27617. case TK_REGISTER: {
  27618. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  27619. break;
  27620. }
  27621. case TK_ID: {
  27622. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  27623. break;
  27624. }
  27625. #ifndef SQLITE_OMIT_CAST
  27626. case TK_CAST: {
  27627. /* Expressions of the form: CAST(pLeft AS token) */
  27628. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  27629. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27630. break;
  27631. }
  27632. #endif /* SQLITE_OMIT_CAST */
  27633. case TK_LT: zBinOp = "LT"; break;
  27634. case TK_LE: zBinOp = "LE"; break;
  27635. case TK_GT: zBinOp = "GT"; break;
  27636. case TK_GE: zBinOp = "GE"; break;
  27637. case TK_NE: zBinOp = "NE"; break;
  27638. case TK_EQ: zBinOp = "EQ"; break;
  27639. case TK_IS: zBinOp = "IS"; break;
  27640. case TK_ISNOT: zBinOp = "ISNOT"; break;
  27641. case TK_AND: zBinOp = "AND"; break;
  27642. case TK_OR: zBinOp = "OR"; break;
  27643. case TK_PLUS: zBinOp = "ADD"; break;
  27644. case TK_STAR: zBinOp = "MUL"; break;
  27645. case TK_MINUS: zBinOp = "SUB"; break;
  27646. case TK_REM: zBinOp = "REM"; break;
  27647. case TK_BITAND: zBinOp = "BITAND"; break;
  27648. case TK_BITOR: zBinOp = "BITOR"; break;
  27649. case TK_SLASH: zBinOp = "DIV"; break;
  27650. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  27651. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  27652. case TK_CONCAT: zBinOp = "CONCAT"; break;
  27653. case TK_DOT: zBinOp = "DOT"; break;
  27654. case TK_UMINUS: zUniOp = "UMINUS"; break;
  27655. case TK_UPLUS: zUniOp = "UPLUS"; break;
  27656. case TK_BITNOT: zUniOp = "BITNOT"; break;
  27657. case TK_NOT: zUniOp = "NOT"; break;
  27658. case TK_ISNULL: zUniOp = "ISNULL"; break;
  27659. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  27660. case TK_TRUTH: {
  27661. int x;
  27662. const char *azOp[] = {
  27663. "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
  27664. };
  27665. assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
  27666. assert( pExpr->pRight );
  27667. assert( pExpr->pRight->op==TK_TRUEFALSE );
  27668. x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
  27669. zUniOp = azOp[x];
  27670. break;
  27671. }
  27672. case TK_SPAN: {
  27673. sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
  27674. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27675. break;
  27676. }
  27677. case TK_COLLATE: {
  27678. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  27679. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27680. break;
  27681. }
  27682. case TK_AGG_FUNCTION:
  27683. case TK_FUNCTION: {
  27684. ExprList *pFarg; /* List of function arguments */
  27685. Window *pWin;
  27686. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  27687. pFarg = 0;
  27688. pWin = 0;
  27689. }else{
  27690. pFarg = pExpr->x.pList;
  27691. #ifndef SQLITE_OMIT_WINDOWFUNC
  27692. pWin = pExpr->y.pWin;
  27693. #else
  27694. pWin = 0;
  27695. #endif
  27696. }
  27697. if( pExpr->op==TK_AGG_FUNCTION ){
  27698. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  27699. pExpr->op2, pExpr->u.zToken);
  27700. }else{
  27701. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  27702. }
  27703. if( pFarg ){
  27704. sqlite3TreeViewExprList(pView, pFarg, pWin!=0, 0);
  27705. }
  27706. #ifndef SQLITE_OMIT_WINDOWFUNC
  27707. if( pWin ){
  27708. sqlite3TreeViewWindow(pView, pWin, 0);
  27709. }
  27710. #endif
  27711. break;
  27712. }
  27713. #ifndef SQLITE_OMIT_SUBQUERY
  27714. case TK_EXISTS: {
  27715. sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
  27716. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  27717. break;
  27718. }
  27719. case TK_SELECT: {
  27720. sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
  27721. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  27722. break;
  27723. }
  27724. case TK_IN: {
  27725. sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
  27726. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  27727. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  27728. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  27729. }else{
  27730. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  27731. }
  27732. break;
  27733. }
  27734. #endif /* SQLITE_OMIT_SUBQUERY */
  27735. /*
  27736. ** x BETWEEN y AND z
  27737. **
  27738. ** This is equivalent to
  27739. **
  27740. ** x>=y AND x<=z
  27741. **
  27742. ** X is stored in pExpr->pLeft.
  27743. ** Y is stored in pExpr->pList->a[0].pExpr.
  27744. ** Z is stored in pExpr->pList->a[1].pExpr.
  27745. */
  27746. case TK_BETWEEN: {
  27747. Expr *pX = pExpr->pLeft;
  27748. Expr *pY = pExpr->x.pList->a[0].pExpr;
  27749. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  27750. sqlite3TreeViewLine(pView, "BETWEEN");
  27751. sqlite3TreeViewExpr(pView, pX, 1);
  27752. sqlite3TreeViewExpr(pView, pY, 1);
  27753. sqlite3TreeViewExpr(pView, pZ, 0);
  27754. break;
  27755. }
  27756. case TK_TRIGGER: {
  27757. /* If the opcode is TK_TRIGGER, then the expression is a reference
  27758. ** to a column in the new.* or old.* pseudo-tables available to
  27759. ** trigger programs. In this case Expr.iTable is set to 1 for the
  27760. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  27761. ** is set to the column of the pseudo-table to read, or to -1 to
  27762. ** read the rowid field.
  27763. */
  27764. sqlite3TreeViewLine(pView, "%s(%d)",
  27765. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  27766. break;
  27767. }
  27768. case TK_CASE: {
  27769. sqlite3TreeViewLine(pView, "CASE");
  27770. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  27771. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  27772. break;
  27773. }
  27774. #ifndef SQLITE_OMIT_TRIGGER
  27775. case TK_RAISE: {
  27776. const char *zType = "unk";
  27777. switch( pExpr->affinity ){
  27778. case OE_Rollback: zType = "rollback"; break;
  27779. case OE_Abort: zType = "abort"; break;
  27780. case OE_Fail: zType = "fail"; break;
  27781. case OE_Ignore: zType = "ignore"; break;
  27782. }
  27783. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  27784. break;
  27785. }
  27786. #endif
  27787. case TK_MATCH: {
  27788. sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
  27789. pExpr->iTable, pExpr->iColumn, zFlgs);
  27790. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  27791. break;
  27792. }
  27793. case TK_VECTOR: {
  27794. sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
  27795. break;
  27796. }
  27797. case TK_SELECT_COLUMN: {
  27798. sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
  27799. sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
  27800. break;
  27801. }
  27802. case TK_IF_NULL_ROW: {
  27803. sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
  27804. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27805. break;
  27806. }
  27807. default: {
  27808. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  27809. break;
  27810. }
  27811. }
  27812. if( zBinOp ){
  27813. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  27814. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  27815. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  27816. }else if( zUniOp ){
  27817. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  27818. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  27819. }
  27820. sqlite3TreeViewPop(pView);
  27821. }
  27822. /*
  27823. ** Generate a human-readable explanation of an expression list.
  27824. */
  27825. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
  27826. TreeView *pView,
  27827. const ExprList *pList,
  27828. const char *zLabel
  27829. ){
  27830. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  27831. if( pList==0 ){
  27832. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  27833. }else{
  27834. int i;
  27835. sqlite3TreeViewLine(pView, "%s", zLabel);
  27836. for(i=0; i<pList->nExpr; i++){
  27837. int j = pList->a[i].u.x.iOrderByCol;
  27838. char *zName = pList->a[i].zName;
  27839. int moreToFollow = i<pList->nExpr - 1;
  27840. if( j || zName ){
  27841. sqlite3TreeViewPush(pView, moreToFollow);
  27842. moreToFollow = 0;
  27843. sqlite3TreeViewLine(pView, 0);
  27844. if( zName ){
  27845. fprintf(stdout, "AS %s ", zName);
  27846. }
  27847. if( j ){
  27848. fprintf(stdout, "iOrderByCol=%d", j);
  27849. }
  27850. fprintf(stdout, "\n");
  27851. fflush(stdout);
  27852. }
  27853. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);
  27854. if( j || zName ){
  27855. sqlite3TreeViewPop(pView);
  27856. }
  27857. }
  27858. }
  27859. }
  27860. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  27861. TreeView *pView,
  27862. const ExprList *pList,
  27863. u8 moreToFollow,
  27864. const char *zLabel
  27865. ){
  27866. pView = sqlite3TreeViewPush(pView, moreToFollow);
  27867. sqlite3TreeViewBareExprList(pView, pList, zLabel);
  27868. sqlite3TreeViewPop(pView);
  27869. }
  27870. #endif /* SQLITE_DEBUG */
  27871. /************** End of treeview.c ********************************************/
  27872. /************** Begin file random.c ******************************************/
  27873. /*
  27874. ** 2001 September 15
  27875. **
  27876. ** The author disclaims copyright to this source code. In place of
  27877. ** a legal notice, here is a blessing:
  27878. **
  27879. ** May you do good and not evil.
  27880. ** May you find forgiveness for yourself and forgive others.
  27881. ** May you share freely, never taking more than you give.
  27882. **
  27883. *************************************************************************
  27884. ** This file contains code to implement a pseudo-random number
  27885. ** generator (PRNG) for SQLite.
  27886. **
  27887. ** Random numbers are used by some of the database backends in order
  27888. ** to generate random integer keys for tables or random filenames.
  27889. */
  27890. /* #include "sqliteInt.h" */
  27891. /* All threads share a single random number generator.
  27892. ** This structure is the current state of the generator.
  27893. */
  27894. static SQLITE_WSD struct sqlite3PrngType {
  27895. unsigned char isInit; /* True if initialized */
  27896. unsigned char i, j; /* State variables */
  27897. unsigned char s[256]; /* State variables */
  27898. } sqlite3Prng;
  27899. /*
  27900. ** Return N random bytes.
  27901. */
  27902. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  27903. unsigned char t;
  27904. unsigned char *zBuf = pBuf;
  27905. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  27906. ** state vector. If writable static data is unsupported on the target,
  27907. ** we have to locate the state vector at run-time. In the more common
  27908. ** case where writable static data is supported, wsdPrng can refer directly
  27909. ** to the "sqlite3Prng" state vector declared above.
  27910. */
  27911. #ifdef SQLITE_OMIT_WSD
  27912. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  27913. # define wsdPrng p[0]
  27914. #else
  27915. # define wsdPrng sqlite3Prng
  27916. #endif
  27917. #if SQLITE_THREADSAFE
  27918. sqlite3_mutex *mutex;
  27919. #endif
  27920. #ifndef SQLITE_OMIT_AUTOINIT
  27921. if( sqlite3_initialize() ) return;
  27922. #endif
  27923. #if SQLITE_THREADSAFE
  27924. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  27925. #endif
  27926. sqlite3_mutex_enter(mutex);
  27927. if( N<=0 || pBuf==0 ){
  27928. wsdPrng.isInit = 0;
  27929. sqlite3_mutex_leave(mutex);
  27930. return;
  27931. }
  27932. /* Initialize the state of the random number generator once,
  27933. ** the first time this routine is called. The seed value does
  27934. ** not need to contain a lot of randomness since we are not
  27935. ** trying to do secure encryption or anything like that...
  27936. **
  27937. ** Nothing in this file or anywhere else in SQLite does any kind of
  27938. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  27939. ** number generator) not as an encryption device.
  27940. */
  27941. if( !wsdPrng.isInit ){
  27942. int i;
  27943. char k[256];
  27944. wsdPrng.j = 0;
  27945. wsdPrng.i = 0;
  27946. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  27947. for(i=0; i<256; i++){
  27948. wsdPrng.s[i] = (u8)i;
  27949. }
  27950. for(i=0; i<256; i++){
  27951. wsdPrng.j += wsdPrng.s[i] + k[i];
  27952. t = wsdPrng.s[wsdPrng.j];
  27953. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  27954. wsdPrng.s[i] = t;
  27955. }
  27956. wsdPrng.isInit = 1;
  27957. }
  27958. assert( N>0 );
  27959. do{
  27960. wsdPrng.i++;
  27961. t = wsdPrng.s[wsdPrng.i];
  27962. wsdPrng.j += t;
  27963. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  27964. wsdPrng.s[wsdPrng.j] = t;
  27965. t += wsdPrng.s[wsdPrng.i];
  27966. *(zBuf++) = wsdPrng.s[t];
  27967. }while( --N );
  27968. sqlite3_mutex_leave(mutex);
  27969. }
  27970. #ifndef SQLITE_UNTESTABLE
  27971. /*
  27972. ** For testing purposes, we sometimes want to preserve the state of
  27973. ** PRNG and restore the PRNG to its saved state at a later time, or
  27974. ** to reset the PRNG to its initial state. These routines accomplish
  27975. ** those tasks.
  27976. **
  27977. ** The sqlite3_test_control() interface calls these routines to
  27978. ** control the PRNG.
  27979. */
  27980. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  27981. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  27982. memcpy(
  27983. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  27984. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  27985. sizeof(sqlite3Prng)
  27986. );
  27987. }
  27988. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  27989. memcpy(
  27990. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  27991. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  27992. sizeof(sqlite3Prng)
  27993. );
  27994. }
  27995. #endif /* SQLITE_UNTESTABLE */
  27996. /************** End of random.c **********************************************/
  27997. /************** Begin file threads.c *****************************************/
  27998. /*
  27999. ** 2012 July 21
  28000. **
  28001. ** The author disclaims copyright to this source code. In place of
  28002. ** a legal notice, here is a blessing:
  28003. **
  28004. ** May you do good and not evil.
  28005. ** May you find forgiveness for yourself and forgive others.
  28006. ** May you share freely, never taking more than you give.
  28007. **
  28008. ******************************************************************************
  28009. **
  28010. ** This file presents a simple cross-platform threading interface for
  28011. ** use internally by SQLite.
  28012. **
  28013. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  28014. ** runs independently of its creator until it is joined using
  28015. ** sqlite3ThreadJoin(), at which point it terminates.
  28016. **
  28017. ** Threads do not have to be real. It could be that the work of the
  28018. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  28019. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  28020. ** single threaded systems. Nothing in SQLite requires multiple threads.
  28021. ** This interface exists so that applications that want to take advantage
  28022. ** of multiple cores can do so, while also allowing applications to stay
  28023. ** single-threaded if desired.
  28024. */
  28025. /* #include "sqliteInt.h" */
  28026. #if SQLITE_OS_WIN
  28027. /* # include "os_win.h" */
  28028. #endif
  28029. #if SQLITE_MAX_WORKER_THREADS>0
  28030. /********************************* Unix Pthreads ****************************/
  28031. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  28032. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  28033. /* #include <pthread.h> */
  28034. /* A running thread */
  28035. struct SQLiteThread {
  28036. pthread_t tid; /* Thread ID */
  28037. int done; /* Set to true when thread finishes */
  28038. void *pOut; /* Result returned by the thread */
  28039. void *(*xTask)(void*); /* The thread routine */
  28040. void *pIn; /* Argument to the thread */
  28041. };
  28042. /* Create a new thread */
  28043. SQLITE_PRIVATE int sqlite3ThreadCreate(
  28044. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  28045. void *(*xTask)(void*), /* Routine to run in a separate thread */
  28046. void *pIn /* Argument passed into xTask() */
  28047. ){
  28048. SQLiteThread *p;
  28049. int rc;
  28050. assert( ppThread!=0 );
  28051. assert( xTask!=0 );
  28052. /* This routine is never used in single-threaded mode */
  28053. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  28054. *ppThread = 0;
  28055. p = sqlite3Malloc(sizeof(*p));
  28056. if( p==0 ) return SQLITE_NOMEM_BKPT;
  28057. memset(p, 0, sizeof(*p));
  28058. p->xTask = xTask;
  28059. p->pIn = pIn;
  28060. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  28061. ** function that returns SQLITE_ERROR when passed the argument 200, that
  28062. ** forces worker threads to run sequentially and deterministically
  28063. ** for testing purposes. */
  28064. if( sqlite3FaultSim(200) ){
  28065. rc = 1;
  28066. }else{
  28067. rc = pthread_create(&p->tid, 0, xTask, pIn);
  28068. }
  28069. if( rc ){
  28070. p->done = 1;
  28071. p->pOut = xTask(pIn);
  28072. }
  28073. *ppThread = p;
  28074. return SQLITE_OK;
  28075. }
  28076. /* Get the results of the thread */
  28077. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  28078. int rc;
  28079. assert( ppOut!=0 );
  28080. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  28081. if( p->done ){
  28082. *ppOut = p->pOut;
  28083. rc = SQLITE_OK;
  28084. }else{
  28085. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  28086. }
  28087. sqlite3_free(p);
  28088. return rc;
  28089. }
  28090. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  28091. /******************************** End Unix Pthreads *************************/
  28092. /********************************* Win32 Threads ****************************/
  28093. #if SQLITE_OS_WIN_THREADS
  28094. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  28095. #include <process.h>
  28096. /* A running thread */
  28097. struct SQLiteThread {
  28098. void *tid; /* The thread handle */
  28099. unsigned id; /* The thread identifier */
  28100. void *(*xTask)(void*); /* The routine to run as a thread */
  28101. void *pIn; /* Argument to xTask */
  28102. void *pResult; /* Result of xTask */
  28103. };
  28104. /* Thread procedure Win32 compatibility shim */
  28105. static unsigned __stdcall sqlite3ThreadProc(
  28106. void *pArg /* IN: Pointer to the SQLiteThread structure */
  28107. ){
  28108. SQLiteThread *p = (SQLiteThread *)pArg;
  28109. assert( p!=0 );
  28110. #if 0
  28111. /*
  28112. ** This assert appears to trigger spuriously on certain
  28113. ** versions of Windows, possibly due to _beginthreadex()
  28114. ** and/or CreateThread() not fully setting their thread
  28115. ** ID parameter before starting the thread.
  28116. */
  28117. assert( p->id==GetCurrentThreadId() );
  28118. #endif
  28119. assert( p->xTask!=0 );
  28120. p->pResult = p->xTask(p->pIn);
  28121. _endthreadex(0);
  28122. return 0; /* NOT REACHED */
  28123. }
  28124. /* Create a new thread */
  28125. SQLITE_PRIVATE int sqlite3ThreadCreate(
  28126. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  28127. void *(*xTask)(void*), /* Routine to run in a separate thread */
  28128. void *pIn /* Argument passed into xTask() */
  28129. ){
  28130. SQLiteThread *p;
  28131. assert( ppThread!=0 );
  28132. assert( xTask!=0 );
  28133. *ppThread = 0;
  28134. p = sqlite3Malloc(sizeof(*p));
  28135. if( p==0 ) return SQLITE_NOMEM_BKPT;
  28136. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  28137. ** function that returns SQLITE_ERROR when passed the argument 200, that
  28138. ** forces worker threads to run sequentially and deterministically
  28139. ** (via the sqlite3FaultSim() term of the conditional) for testing
  28140. ** purposes. */
  28141. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  28142. memset(p, 0, sizeof(*p));
  28143. }else{
  28144. p->xTask = xTask;
  28145. p->pIn = pIn;
  28146. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  28147. if( p->tid==0 ){
  28148. memset(p, 0, sizeof(*p));
  28149. }
  28150. }
  28151. if( p->xTask==0 ){
  28152. p->id = GetCurrentThreadId();
  28153. p->pResult = xTask(pIn);
  28154. }
  28155. *ppThread = p;
  28156. return SQLITE_OK;
  28157. }
  28158. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  28159. /* Get the results of the thread */
  28160. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  28161. DWORD rc;
  28162. BOOL bRc;
  28163. assert( ppOut!=0 );
  28164. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  28165. if( p->xTask==0 ){
  28166. /* assert( p->id==GetCurrentThreadId() ); */
  28167. rc = WAIT_OBJECT_0;
  28168. assert( p->tid==0 );
  28169. }else{
  28170. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  28171. rc = sqlite3Win32Wait((HANDLE)p->tid);
  28172. assert( rc!=WAIT_IO_COMPLETION );
  28173. bRc = CloseHandle((HANDLE)p->tid);
  28174. assert( bRc );
  28175. }
  28176. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  28177. sqlite3_free(p);
  28178. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  28179. }
  28180. #endif /* SQLITE_OS_WIN_THREADS */
  28181. /******************************** End Win32 Threads *************************/
  28182. /********************************* Single-Threaded **************************/
  28183. #ifndef SQLITE_THREADS_IMPLEMENTED
  28184. /*
  28185. ** This implementation does not actually create a new thread. It does the
  28186. ** work of the thread in the main thread, when either the thread is created
  28187. ** or when it is joined
  28188. */
  28189. /* A running thread */
  28190. struct SQLiteThread {
  28191. void *(*xTask)(void*); /* The routine to run as a thread */
  28192. void *pIn; /* Argument to xTask */
  28193. void *pResult; /* Result of xTask */
  28194. };
  28195. /* Create a new thread */
  28196. SQLITE_PRIVATE int sqlite3ThreadCreate(
  28197. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  28198. void *(*xTask)(void*), /* Routine to run in a separate thread */
  28199. void *pIn /* Argument passed into xTask() */
  28200. ){
  28201. SQLiteThread *p;
  28202. assert( ppThread!=0 );
  28203. assert( xTask!=0 );
  28204. *ppThread = 0;
  28205. p = sqlite3Malloc(sizeof(*p));
  28206. if( p==0 ) return SQLITE_NOMEM_BKPT;
  28207. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  28208. p->xTask = xTask;
  28209. p->pIn = pIn;
  28210. }else{
  28211. p->xTask = 0;
  28212. p->pResult = xTask(pIn);
  28213. }
  28214. *ppThread = p;
  28215. return SQLITE_OK;
  28216. }
  28217. /* Get the results of the thread */
  28218. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  28219. assert( ppOut!=0 );
  28220. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  28221. if( p->xTask ){
  28222. *ppOut = p->xTask(p->pIn);
  28223. }else{
  28224. *ppOut = p->pResult;
  28225. }
  28226. sqlite3_free(p);
  28227. #if defined(SQLITE_TEST)
  28228. {
  28229. void *pTstAlloc = sqlite3Malloc(10);
  28230. if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
  28231. sqlite3_free(pTstAlloc);
  28232. }
  28233. #endif
  28234. return SQLITE_OK;
  28235. }
  28236. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  28237. /****************************** End Single-Threaded *************************/
  28238. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  28239. /************** End of threads.c *********************************************/
  28240. /************** Begin file utf.c *********************************************/
  28241. /*
  28242. ** 2004 April 13
  28243. **
  28244. ** The author disclaims copyright to this source code. In place of
  28245. ** a legal notice, here is a blessing:
  28246. **
  28247. ** May you do good and not evil.
  28248. ** May you find forgiveness for yourself and forgive others.
  28249. ** May you share freely, never taking more than you give.
  28250. **
  28251. *************************************************************************
  28252. ** This file contains routines used to translate between UTF-8,
  28253. ** UTF-16, UTF-16BE, and UTF-16LE.
  28254. **
  28255. ** Notes on UTF-8:
  28256. **
  28257. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  28258. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  28259. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  28260. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  28261. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  28262. **
  28263. **
  28264. ** Notes on UTF-16: (with wwww+1==uuuuu)
  28265. **
  28266. ** Word-0 Word-1 Value
  28267. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  28268. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  28269. **
  28270. **
  28271. ** BOM or Byte Order Mark:
  28272. ** 0xff 0xfe little-endian utf-16 follows
  28273. ** 0xfe 0xff big-endian utf-16 follows
  28274. **
  28275. */
  28276. /* #include "sqliteInt.h" */
  28277. /* #include <assert.h> */
  28278. /* #include "vdbeInt.h" */
  28279. #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
  28280. /*
  28281. ** The following constant value is used by the SQLITE_BIGENDIAN and
  28282. ** SQLITE_LITTLEENDIAN macros.
  28283. */
  28284. SQLITE_PRIVATE const int sqlite3one = 1;
  28285. #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
  28286. /*
  28287. ** This lookup table is used to help decode the first byte of
  28288. ** a multi-byte UTF8 character.
  28289. */
  28290. static const unsigned char sqlite3Utf8Trans1[] = {
  28291. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  28292. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  28293. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  28294. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  28295. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  28296. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  28297. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  28298. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  28299. };
  28300. #define WRITE_UTF8(zOut, c) { \
  28301. if( c<0x00080 ){ \
  28302. *zOut++ = (u8)(c&0xFF); \
  28303. } \
  28304. else if( c<0x00800 ){ \
  28305. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  28306. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  28307. } \
  28308. else if( c<0x10000 ){ \
  28309. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  28310. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  28311. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  28312. }else{ \
  28313. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  28314. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  28315. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  28316. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  28317. } \
  28318. }
  28319. #define WRITE_UTF16LE(zOut, c) { \
  28320. if( c<=0xFFFF ){ \
  28321. *zOut++ = (u8)(c&0x00FF); \
  28322. *zOut++ = (u8)((c>>8)&0x00FF); \
  28323. }else{ \
  28324. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  28325. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  28326. *zOut++ = (u8)(c&0x00FF); \
  28327. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  28328. } \
  28329. }
  28330. #define WRITE_UTF16BE(zOut, c) { \
  28331. if( c<=0xFFFF ){ \
  28332. *zOut++ = (u8)((c>>8)&0x00FF); \
  28333. *zOut++ = (u8)(c&0x00FF); \
  28334. }else{ \
  28335. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  28336. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  28337. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  28338. *zOut++ = (u8)(c&0x00FF); \
  28339. } \
  28340. }
  28341. #define READ_UTF16LE(zIn, TERM, c){ \
  28342. c = (*zIn++); \
  28343. c += ((*zIn++)<<8); \
  28344. if( c>=0xD800 && c<0xE000 && TERM ){ \
  28345. int c2 = (*zIn++); \
  28346. c2 += ((*zIn++)<<8); \
  28347. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  28348. } \
  28349. }
  28350. #define READ_UTF16BE(zIn, TERM, c){ \
  28351. c = ((*zIn++)<<8); \
  28352. c += (*zIn++); \
  28353. if( c>=0xD800 && c<0xE000 && TERM ){ \
  28354. int c2 = ((*zIn++)<<8); \
  28355. c2 += (*zIn++); \
  28356. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  28357. } \
  28358. }
  28359. /*
  28360. ** Translate a single UTF-8 character. Return the unicode value.
  28361. **
  28362. ** During translation, assume that the byte that zTerm points
  28363. ** is a 0x00.
  28364. **
  28365. ** Write a pointer to the next unread byte back into *pzNext.
  28366. **
  28367. ** Notes On Invalid UTF-8:
  28368. **
  28369. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  28370. ** be encoded as a multi-byte character. Any multi-byte character that
  28371. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  28372. **
  28373. ** * This routine never allows a UTF16 surrogate value to be encoded.
  28374. ** If a multi-byte character attempts to encode a value between
  28375. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  28376. **
  28377. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  28378. ** byte of a character are interpreted as single-byte characters
  28379. ** and rendered as themselves even though they are technically
  28380. ** invalid characters.
  28381. **
  28382. ** * This routine accepts over-length UTF8 encodings
  28383. ** for unicode values 0x80 and greater. It does not change over-length
  28384. ** encodings to 0xfffd as some systems recommend.
  28385. */
  28386. #define READ_UTF8(zIn, zTerm, c) \
  28387. c = *(zIn++); \
  28388. if( c>=0xc0 ){ \
  28389. c = sqlite3Utf8Trans1[c-0xc0]; \
  28390. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  28391. c = (c<<6) + (0x3f & *(zIn++)); \
  28392. } \
  28393. if( c<0x80 \
  28394. || (c&0xFFFFF800)==0xD800 \
  28395. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  28396. }
  28397. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  28398. const unsigned char **pz /* Pointer to string from which to read char */
  28399. ){
  28400. unsigned int c;
  28401. /* Same as READ_UTF8() above but without the zTerm parameter.
  28402. ** For this routine, we assume the UTF8 string is always zero-terminated.
  28403. */
  28404. c = *((*pz)++);
  28405. if( c>=0xc0 ){
  28406. c = sqlite3Utf8Trans1[c-0xc0];
  28407. while( (*(*pz) & 0xc0)==0x80 ){
  28408. c = (c<<6) + (0x3f & *((*pz)++));
  28409. }
  28410. if( c<0x80
  28411. || (c&0xFFFFF800)==0xD800
  28412. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  28413. }
  28414. return c;
  28415. }
  28416. /*
  28417. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  28418. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  28419. */
  28420. /* #define TRANSLATE_TRACE 1 */
  28421. #ifndef SQLITE_OMIT_UTF16
  28422. /*
  28423. ** This routine transforms the internal text encoding used by pMem to
  28424. ** desiredEnc. It is an error if the string is already of the desired
  28425. ** encoding, or if *pMem does not contain a string value.
  28426. */
  28427. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  28428. sqlite3_int64 len; /* Maximum length of output string in bytes */
  28429. unsigned char *zOut; /* Output buffer */
  28430. unsigned char *zIn; /* Input iterator */
  28431. unsigned char *zTerm; /* End of input */
  28432. unsigned char *z; /* Output iterator */
  28433. unsigned int c;
  28434. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  28435. assert( pMem->flags&MEM_Str );
  28436. assert( pMem->enc!=desiredEnc );
  28437. assert( pMem->enc!=0 );
  28438. assert( pMem->n>=0 );
  28439. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  28440. {
  28441. char zBuf[100];
  28442. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  28443. fprintf(stderr, "INPUT: %s\n", zBuf);
  28444. }
  28445. #endif
  28446. /* If the translation is between UTF-16 little and big endian, then
  28447. ** all that is required is to swap the byte order. This case is handled
  28448. ** differently from the others.
  28449. */
  28450. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  28451. u8 temp;
  28452. int rc;
  28453. rc = sqlite3VdbeMemMakeWriteable(pMem);
  28454. if( rc!=SQLITE_OK ){
  28455. assert( rc==SQLITE_NOMEM );
  28456. return SQLITE_NOMEM_BKPT;
  28457. }
  28458. zIn = (u8*)pMem->z;
  28459. zTerm = &zIn[pMem->n&~1];
  28460. while( zIn<zTerm ){
  28461. temp = *zIn;
  28462. *zIn = *(zIn+1);
  28463. zIn++;
  28464. *zIn++ = temp;
  28465. }
  28466. pMem->enc = desiredEnc;
  28467. goto translate_out;
  28468. }
  28469. /* Set len to the maximum number of bytes required in the output buffer. */
  28470. if( desiredEnc==SQLITE_UTF8 ){
  28471. /* When converting from UTF-16, the maximum growth results from
  28472. ** translating a 2-byte character to a 4-byte UTF-8 character.
  28473. ** A single byte is required for the output string
  28474. ** nul-terminator.
  28475. */
  28476. pMem->n &= ~1;
  28477. len = 2 * (sqlite3_int64)pMem->n + 1;
  28478. }else{
  28479. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  28480. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  28481. ** character. Two bytes are required in the output buffer for the
  28482. ** nul-terminator.
  28483. */
  28484. len = 2 * (sqlite3_int64)pMem->n + 2;
  28485. }
  28486. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  28487. ** byte past the end.
  28488. **
  28489. ** Variable zOut is set to point at the output buffer, space obtained
  28490. ** from sqlite3_malloc().
  28491. */
  28492. zIn = (u8*)pMem->z;
  28493. zTerm = &zIn[pMem->n];
  28494. zOut = sqlite3DbMallocRaw(pMem->db, len);
  28495. if( !zOut ){
  28496. return SQLITE_NOMEM_BKPT;
  28497. }
  28498. z = zOut;
  28499. if( pMem->enc==SQLITE_UTF8 ){
  28500. if( desiredEnc==SQLITE_UTF16LE ){
  28501. /* UTF-8 -> UTF-16 Little-endian */
  28502. while( zIn<zTerm ){
  28503. READ_UTF8(zIn, zTerm, c);
  28504. WRITE_UTF16LE(z, c);
  28505. }
  28506. }else{
  28507. assert( desiredEnc==SQLITE_UTF16BE );
  28508. /* UTF-8 -> UTF-16 Big-endian */
  28509. while( zIn<zTerm ){
  28510. READ_UTF8(zIn, zTerm, c);
  28511. WRITE_UTF16BE(z, c);
  28512. }
  28513. }
  28514. pMem->n = (int)(z - zOut);
  28515. *z++ = 0;
  28516. }else{
  28517. assert( desiredEnc==SQLITE_UTF8 );
  28518. if( pMem->enc==SQLITE_UTF16LE ){
  28519. /* UTF-16 Little-endian -> UTF-8 */
  28520. while( zIn<zTerm ){
  28521. READ_UTF16LE(zIn, zIn<zTerm, c);
  28522. WRITE_UTF8(z, c);
  28523. }
  28524. }else{
  28525. /* UTF-16 Big-endian -> UTF-8 */
  28526. while( zIn<zTerm ){
  28527. READ_UTF16BE(zIn, zIn<zTerm, c);
  28528. WRITE_UTF8(z, c);
  28529. }
  28530. }
  28531. pMem->n = (int)(z - zOut);
  28532. }
  28533. *z = 0;
  28534. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  28535. c = pMem->flags;
  28536. sqlite3VdbeMemRelease(pMem);
  28537. pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
  28538. pMem->enc = desiredEnc;
  28539. pMem->z = (char*)zOut;
  28540. pMem->zMalloc = pMem->z;
  28541. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  28542. translate_out:
  28543. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  28544. {
  28545. char zBuf[100];
  28546. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  28547. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  28548. }
  28549. #endif
  28550. return SQLITE_OK;
  28551. }
  28552. #endif /* SQLITE_OMIT_UTF16 */
  28553. #ifndef SQLITE_OMIT_UTF16
  28554. /*
  28555. ** This routine checks for a byte-order mark at the beginning of the
  28556. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  28557. ** the encoding of the Mem adjusted. This routine does not do any
  28558. ** byte-swapping, it just sets Mem.enc appropriately.
  28559. **
  28560. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  28561. ** changed by this function.
  28562. */
  28563. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  28564. int rc = SQLITE_OK;
  28565. u8 bom = 0;
  28566. assert( pMem->n>=0 );
  28567. if( pMem->n>1 ){
  28568. u8 b1 = *(u8 *)pMem->z;
  28569. u8 b2 = *(((u8 *)pMem->z) + 1);
  28570. if( b1==0xFE && b2==0xFF ){
  28571. bom = SQLITE_UTF16BE;
  28572. }
  28573. if( b1==0xFF && b2==0xFE ){
  28574. bom = SQLITE_UTF16LE;
  28575. }
  28576. }
  28577. if( bom ){
  28578. rc = sqlite3VdbeMemMakeWriteable(pMem);
  28579. if( rc==SQLITE_OK ){
  28580. pMem->n -= 2;
  28581. memmove(pMem->z, &pMem->z[2], pMem->n);
  28582. pMem->z[pMem->n] = '\0';
  28583. pMem->z[pMem->n+1] = '\0';
  28584. pMem->flags |= MEM_Term;
  28585. pMem->enc = bom;
  28586. }
  28587. }
  28588. return rc;
  28589. }
  28590. #endif /* SQLITE_OMIT_UTF16 */
  28591. /*
  28592. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  28593. ** return the number of unicode characters in pZ up to (but not including)
  28594. ** the first 0x00 byte. If nByte is not less than zero, return the
  28595. ** number of unicode characters in the first nByte of pZ (or up to
  28596. ** the first 0x00, whichever comes first).
  28597. */
  28598. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  28599. int r = 0;
  28600. const u8 *z = (const u8*)zIn;
  28601. const u8 *zTerm;
  28602. if( nByte>=0 ){
  28603. zTerm = &z[nByte];
  28604. }else{
  28605. zTerm = (const u8*)(-1);
  28606. }
  28607. assert( z<=zTerm );
  28608. while( *z!=0 && z<zTerm ){
  28609. SQLITE_SKIP_UTF8(z);
  28610. r++;
  28611. }
  28612. return r;
  28613. }
  28614. /* This test function is not currently used by the automated test-suite.
  28615. ** Hence it is only available in debug builds.
  28616. */
  28617. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  28618. /*
  28619. ** Translate UTF-8 to UTF-8.
  28620. **
  28621. ** This has the effect of making sure that the string is well-formed
  28622. ** UTF-8. Miscoded characters are removed.
  28623. **
  28624. ** The translation is done in-place and aborted if the output
  28625. ** overruns the input.
  28626. */
  28627. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  28628. unsigned char *zOut = zIn;
  28629. unsigned char *zStart = zIn;
  28630. u32 c;
  28631. while( zIn[0] && zOut<=zIn ){
  28632. c = sqlite3Utf8Read((const u8**)&zIn);
  28633. if( c!=0xfffd ){
  28634. WRITE_UTF8(zOut, c);
  28635. }
  28636. }
  28637. *zOut = 0;
  28638. return (int)(zOut - zStart);
  28639. }
  28640. #endif
  28641. #ifndef SQLITE_OMIT_UTF16
  28642. /*
  28643. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  28644. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  28645. ** be freed by the calling function.
  28646. **
  28647. ** NULL is returned if there is an allocation error.
  28648. */
  28649. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  28650. Mem m;
  28651. memset(&m, 0, sizeof(m));
  28652. m.db = db;
  28653. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  28654. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  28655. if( db->mallocFailed ){
  28656. sqlite3VdbeMemRelease(&m);
  28657. m.z = 0;
  28658. }
  28659. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  28660. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  28661. assert( m.z || db->mallocFailed );
  28662. return m.z;
  28663. }
  28664. /*
  28665. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  28666. ** Return the number of bytes in the first nChar unicode characters
  28667. ** in pZ. nChar must be non-negative.
  28668. */
  28669. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  28670. int c;
  28671. unsigned char const *z = zIn;
  28672. int n = 0;
  28673. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  28674. while( n<nChar ){
  28675. READ_UTF16BE(z, 1, c);
  28676. n++;
  28677. }
  28678. }else{
  28679. while( n<nChar ){
  28680. READ_UTF16LE(z, 1, c);
  28681. n++;
  28682. }
  28683. }
  28684. return (int)(z-(unsigned char const *)zIn);
  28685. }
  28686. #if defined(SQLITE_TEST)
  28687. /*
  28688. ** This routine is called from the TCL test function "translate_selftest".
  28689. ** It checks that the primitives for serializing and deserializing
  28690. ** characters in each encoding are inverses of each other.
  28691. */
  28692. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  28693. unsigned int i, t;
  28694. unsigned char zBuf[20];
  28695. unsigned char *z;
  28696. int n;
  28697. unsigned int c;
  28698. for(i=0; i<0x00110000; i++){
  28699. z = zBuf;
  28700. WRITE_UTF8(z, i);
  28701. n = (int)(z-zBuf);
  28702. assert( n>0 && n<=4 );
  28703. z[0] = 0;
  28704. z = zBuf;
  28705. c = sqlite3Utf8Read((const u8**)&z);
  28706. t = i;
  28707. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  28708. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  28709. assert( c==t );
  28710. assert( (z-zBuf)==n );
  28711. }
  28712. for(i=0; i<0x00110000; i++){
  28713. if( i>=0xD800 && i<0xE000 ) continue;
  28714. z = zBuf;
  28715. WRITE_UTF16LE(z, i);
  28716. n = (int)(z-zBuf);
  28717. assert( n>0 && n<=4 );
  28718. z[0] = 0;
  28719. z = zBuf;
  28720. READ_UTF16LE(z, 1, c);
  28721. assert( c==i );
  28722. assert( (z-zBuf)==n );
  28723. }
  28724. for(i=0; i<0x00110000; i++){
  28725. if( i>=0xD800 && i<0xE000 ) continue;
  28726. z = zBuf;
  28727. WRITE_UTF16BE(z, i);
  28728. n = (int)(z-zBuf);
  28729. assert( n>0 && n<=4 );
  28730. z[0] = 0;
  28731. z = zBuf;
  28732. READ_UTF16BE(z, 1, c);
  28733. assert( c==i );
  28734. assert( (z-zBuf)==n );
  28735. }
  28736. }
  28737. #endif /* SQLITE_TEST */
  28738. #endif /* SQLITE_OMIT_UTF16 */
  28739. /************** End of utf.c *************************************************/
  28740. /************** Begin file util.c ********************************************/
  28741. /*
  28742. ** 2001 September 15
  28743. **
  28744. ** The author disclaims copyright to this source code. In place of
  28745. ** a legal notice, here is a blessing:
  28746. **
  28747. ** May you do good and not evil.
  28748. ** May you find forgiveness for yourself and forgive others.
  28749. ** May you share freely, never taking more than you give.
  28750. **
  28751. *************************************************************************
  28752. ** Utility functions used throughout sqlite.
  28753. **
  28754. ** This file contains functions for allocating memory, comparing
  28755. ** strings, and stuff like that.
  28756. **
  28757. */
  28758. /* #include "sqliteInt.h" */
  28759. /* #include <stdarg.h> */
  28760. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  28761. # include <math.h>
  28762. #endif
  28763. /*
  28764. ** Routine needed to support the testcase() macro.
  28765. */
  28766. #ifdef SQLITE_COVERAGE_TEST
  28767. SQLITE_PRIVATE void sqlite3Coverage(int x){
  28768. static unsigned dummy = 0;
  28769. dummy += (unsigned)x;
  28770. }
  28771. #endif
  28772. /*
  28773. ** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
  28774. ** or to bypass normal error detection during testing in order to let
  28775. ** execute proceed futher downstream.
  28776. **
  28777. ** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0). The
  28778. ** sqlite3FaultSim() function only returns non-zero during testing.
  28779. **
  28780. ** During testing, if the test harness has set a fault-sim callback using
  28781. ** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
  28782. ** each call to sqlite3FaultSim() is relayed to that application-supplied
  28783. ** callback and the integer return value form the application-supplied
  28784. ** callback is returned by sqlite3FaultSim().
  28785. **
  28786. ** The integer argument to sqlite3FaultSim() is a code to identify which
  28787. ** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
  28788. ** should have a unique code. To prevent legacy testing applications from
  28789. ** breaking, the codes should not be changed or reused.
  28790. */
  28791. #ifndef SQLITE_UNTESTABLE
  28792. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  28793. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  28794. return xCallback ? xCallback(iTest) : SQLITE_OK;
  28795. }
  28796. #endif
  28797. #ifndef SQLITE_OMIT_FLOATING_POINT
  28798. /*
  28799. ** Return true if the floating point value is Not a Number (NaN).
  28800. **
  28801. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  28802. ** Otherwise, we have our own implementation that works on most systems.
  28803. */
  28804. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  28805. int rc; /* The value return */
  28806. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  28807. /*
  28808. ** Systems that support the isnan() library function should probably
  28809. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  28810. ** found that many systems do not have a working isnan() function so
  28811. ** this implementation is provided as an alternative.
  28812. **
  28813. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  28814. ** On the other hand, the use of -ffast-math comes with the following
  28815. ** warning:
  28816. **
  28817. ** This option [-ffast-math] should never be turned on by any
  28818. ** -O option since it can result in incorrect output for programs
  28819. ** which depend on an exact implementation of IEEE or ISO
  28820. ** rules/specifications for math functions.
  28821. **
  28822. ** Under MSVC, this NaN test may fail if compiled with a floating-
  28823. ** point precision mode other than /fp:precise. From the MSDN
  28824. ** documentation:
  28825. **
  28826. ** The compiler [with /fp:precise] will properly handle comparisons
  28827. ** involving NaN. For example, x != x evaluates to true if x is NaN
  28828. ** ...
  28829. */
  28830. #ifdef __FAST_MATH__
  28831. # error SQLite will not work correctly with the -ffast-math option of GCC.
  28832. #endif
  28833. volatile double y = x;
  28834. volatile double z = y;
  28835. rc = (y!=z);
  28836. #else /* if HAVE_ISNAN */
  28837. rc = isnan(x);
  28838. #endif /* HAVE_ISNAN */
  28839. testcase( rc );
  28840. return rc;
  28841. }
  28842. #endif /* SQLITE_OMIT_FLOATING_POINT */
  28843. /*
  28844. ** Compute a string length that is limited to what can be stored in
  28845. ** lower 30 bits of a 32-bit signed integer.
  28846. **
  28847. ** The value returned will never be negative. Nor will it ever be greater
  28848. ** than the actual length of the string. For very long strings (greater
  28849. ** than 1GiB) the value returned might be less than the true string length.
  28850. */
  28851. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  28852. if( z==0 ) return 0;
  28853. return 0x3fffffff & (int)strlen(z);
  28854. }
  28855. /*
  28856. ** Return the declared type of a column. Or return zDflt if the column
  28857. ** has no declared type.
  28858. **
  28859. ** The column type is an extra string stored after the zero-terminator on
  28860. ** the column name if and only if the COLFLAG_HASTYPE flag is set.
  28861. */
  28862. SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
  28863. if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
  28864. return pCol->zName + strlen(pCol->zName) + 1;
  28865. }
  28866. /*
  28867. ** Helper function for sqlite3Error() - called rarely. Broken out into
  28868. ** a separate routine to avoid unnecessary register saves on entry to
  28869. ** sqlite3Error().
  28870. */
  28871. static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
  28872. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  28873. sqlite3SystemError(db, err_code);
  28874. }
  28875. /*
  28876. ** Set the current error code to err_code and clear any prior error message.
  28877. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
  28878. ** that would be appropriate.
  28879. */
  28880. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  28881. assert( db!=0 );
  28882. db->errCode = err_code;
  28883. if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
  28884. }
  28885. /*
  28886. ** Load the sqlite3.iSysErrno field if that is an appropriate thing
  28887. ** to do based on the SQLite error code in rc.
  28888. */
  28889. SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
  28890. if( rc==SQLITE_IOERR_NOMEM ) return;
  28891. rc &= 0xff;
  28892. if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
  28893. db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
  28894. }
  28895. }
  28896. /*
  28897. ** Set the most recent error code and error string for the sqlite
  28898. ** handle "db". The error code is set to "err_code".
  28899. **
  28900. ** If it is not NULL, string zFormat specifies the format of the
  28901. ** error string in the style of the printf functions: The following
  28902. ** format characters are allowed:
  28903. **
  28904. ** %s Insert a string
  28905. ** %z A string that should be freed after use
  28906. ** %d Insert an integer
  28907. ** %T Insert a token
  28908. ** %S Insert the first element of a SrcList
  28909. **
  28910. ** zFormat and any string tokens that follow it are assumed to be
  28911. ** encoded in UTF-8.
  28912. **
  28913. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  28914. ** should be called with err_code set to SQLITE_OK and zFormat set
  28915. ** to NULL.
  28916. */
  28917. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  28918. assert( db!=0 );
  28919. db->errCode = err_code;
  28920. sqlite3SystemError(db, err_code);
  28921. if( zFormat==0 ){
  28922. sqlite3Error(db, err_code);
  28923. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  28924. char *z;
  28925. va_list ap;
  28926. va_start(ap, zFormat);
  28927. z = sqlite3VMPrintf(db, zFormat, ap);
  28928. va_end(ap);
  28929. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  28930. }
  28931. }
  28932. /*
  28933. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  28934. ** The following formatting characters are allowed:
  28935. **
  28936. ** %s Insert a string
  28937. ** %z A string that should be freed after use
  28938. ** %d Insert an integer
  28939. ** %T Insert a token
  28940. ** %S Insert the first element of a SrcList
  28941. **
  28942. ** This function should be used to report any error that occurs while
  28943. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  28944. ** last thing the sqlite3_prepare() function does is copy the error
  28945. ** stored by this function into the database handle using sqlite3Error().
  28946. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  28947. ** during statement execution (sqlite3_step() etc.).
  28948. */
  28949. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  28950. char *zMsg;
  28951. va_list ap;
  28952. sqlite3 *db = pParse->db;
  28953. va_start(ap, zFormat);
  28954. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  28955. va_end(ap);
  28956. if( db->suppressErr ){
  28957. sqlite3DbFree(db, zMsg);
  28958. }else{
  28959. pParse->nErr++;
  28960. sqlite3DbFree(db, pParse->zErrMsg);
  28961. pParse->zErrMsg = zMsg;
  28962. pParse->rc = SQLITE_ERROR;
  28963. }
  28964. }
  28965. /*
  28966. ** If database connection db is currently parsing SQL, then transfer
  28967. ** error code errCode to that parser if the parser has not already
  28968. ** encountered some other kind of error.
  28969. */
  28970. SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3 *db, int errCode){
  28971. Parse *pParse;
  28972. if( db==0 || (pParse = db->pParse)==0 ) return errCode;
  28973. pParse->rc = errCode;
  28974. pParse->nErr++;
  28975. return errCode;
  28976. }
  28977. /*
  28978. ** Convert an SQL-style quoted string into a normal string by removing
  28979. ** the quote characters. The conversion is done in-place. If the
  28980. ** input does not begin with a quote character, then this routine
  28981. ** is a no-op.
  28982. **
  28983. ** The input string must be zero-terminated. A new zero-terminator
  28984. ** is added to the dequoted string.
  28985. **
  28986. ** The return value is -1 if no dequoting occurs or the length of the
  28987. ** dequoted string, exclusive of the zero terminator, if dequoting does
  28988. ** occur.
  28989. **
  28990. ** 2002-02-14: This routine is extended to remove MS-Access style
  28991. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  28992. ** "a-b-c".
  28993. */
  28994. SQLITE_PRIVATE void sqlite3Dequote(char *z){
  28995. char quote;
  28996. int i, j;
  28997. if( z==0 ) return;
  28998. quote = z[0];
  28999. if( !sqlite3Isquote(quote) ) return;
  29000. if( quote=='[' ) quote = ']';
  29001. for(i=1, j=0;; i++){
  29002. assert( z[i] );
  29003. if( z[i]==quote ){
  29004. if( z[i+1]==quote ){
  29005. z[j++] = quote;
  29006. i++;
  29007. }else{
  29008. break;
  29009. }
  29010. }else{
  29011. z[j++] = z[i];
  29012. }
  29013. }
  29014. z[j] = 0;
  29015. }
  29016. SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
  29017. assert( sqlite3Isquote(p->u.zToken[0]) );
  29018. p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
  29019. sqlite3Dequote(p->u.zToken);
  29020. }
  29021. /*
  29022. ** Generate a Token object from a string
  29023. */
  29024. SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
  29025. p->z = z;
  29026. p->n = sqlite3Strlen30(z);
  29027. }
  29028. /* Convenient short-hand */
  29029. #define UpperToLower sqlite3UpperToLower
  29030. /*
  29031. ** Some systems have stricmp(). Others have strcasecmp(). Because
  29032. ** there is no consistency, we will define our own.
  29033. **
  29034. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  29035. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  29036. ** the contents of two buffers containing UTF-8 strings in a
  29037. ** case-independent fashion, using the same definition of "case
  29038. ** independence" that SQLite uses internally when comparing identifiers.
  29039. */
  29040. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  29041. if( zLeft==0 ){
  29042. return zRight ? -1 : 0;
  29043. }else if( zRight==0 ){
  29044. return 1;
  29045. }
  29046. return sqlite3StrICmp(zLeft, zRight);
  29047. }
  29048. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  29049. unsigned char *a, *b;
  29050. int c;
  29051. a = (unsigned char *)zLeft;
  29052. b = (unsigned char *)zRight;
  29053. for(;;){
  29054. c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
  29055. if( c || *a==0 ) break;
  29056. a++;
  29057. b++;
  29058. }
  29059. return c;
  29060. }
  29061. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  29062. register unsigned char *a, *b;
  29063. if( zLeft==0 ){
  29064. return zRight ? -1 : 0;
  29065. }else if( zRight==0 ){
  29066. return 1;
  29067. }
  29068. a = (unsigned char *)zLeft;
  29069. b = (unsigned char *)zRight;
  29070. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  29071. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  29072. }
  29073. /*
  29074. ** Compute 10 to the E-th power. Examples: E==1 results in 10.
  29075. ** E==2 results in 100. E==50 results in 1.0e50.
  29076. **
  29077. ** This routine only works for values of E between 1 and 341.
  29078. */
  29079. static LONGDOUBLE_TYPE sqlite3Pow10(int E){
  29080. #if defined(_MSC_VER)
  29081. static const LONGDOUBLE_TYPE x[] = {
  29082. 1.0e+001,
  29083. 1.0e+002,
  29084. 1.0e+004,
  29085. 1.0e+008,
  29086. 1.0e+016,
  29087. 1.0e+032,
  29088. 1.0e+064,
  29089. 1.0e+128,
  29090. 1.0e+256
  29091. };
  29092. LONGDOUBLE_TYPE r = 1.0;
  29093. int i;
  29094. assert( E>=0 && E<=307 );
  29095. for(i=0; E!=0; i++, E >>=1){
  29096. if( E & 1 ) r *= x[i];
  29097. }
  29098. return r;
  29099. #else
  29100. LONGDOUBLE_TYPE x = 10.0;
  29101. LONGDOUBLE_TYPE r = 1.0;
  29102. while(1){
  29103. if( E & 1 ) r *= x;
  29104. E >>= 1;
  29105. if( E==0 ) break;
  29106. x *= x;
  29107. }
  29108. return r;
  29109. #endif
  29110. }
  29111. /*
  29112. ** The string z[] is an text representation of a real number.
  29113. ** Convert this string to a double and write it into *pResult.
  29114. **
  29115. ** The string z[] is length bytes in length (bytes, not characters) and
  29116. ** uses the encoding enc. The string is not necessarily zero-terminated.
  29117. **
  29118. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  29119. ** if the string is empty or contains extraneous text. Valid numbers
  29120. ** are in one of these formats:
  29121. **
  29122. ** [+-]digits[E[+-]digits]
  29123. ** [+-]digits.[digits][E[+-]digits]
  29124. ** [+-].digits[E[+-]digits]
  29125. **
  29126. ** Leading and trailing whitespace is ignored for the purpose of determining
  29127. ** validity.
  29128. **
  29129. ** If some prefix of the input string is a valid number, this routine
  29130. ** returns FALSE but it still converts the prefix and writes the result
  29131. ** into *pResult.
  29132. */
  29133. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  29134. #ifndef SQLITE_OMIT_FLOATING_POINT
  29135. int incr;
  29136. const char *zEnd = z + length;
  29137. /* sign * significand * (10 ^ (esign * exponent)) */
  29138. int sign = 1; /* sign of significand */
  29139. i64 s = 0; /* significand */
  29140. int d = 0; /* adjust exponent for shifting decimal point */
  29141. int esign = 1; /* sign of exponent */
  29142. int e = 0; /* exponent */
  29143. int eValid = 1; /* True exponent is either not used or is well-formed */
  29144. double result;
  29145. int nDigits = 0;
  29146. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  29147. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  29148. *pResult = 0.0; /* Default return value, in case of an error */
  29149. if( enc==SQLITE_UTF8 ){
  29150. incr = 1;
  29151. }else{
  29152. int i;
  29153. incr = 2;
  29154. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  29155. for(i=3-enc; i<length && z[i]==0; i+=2){}
  29156. nonNum = i<length;
  29157. zEnd = &z[i^1];
  29158. z += (enc&1);
  29159. }
  29160. /* skip leading spaces */
  29161. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  29162. if( z>=zEnd ) return 0;
  29163. /* get sign of significand */
  29164. if( *z=='-' ){
  29165. sign = -1;
  29166. z+=incr;
  29167. }else if( *z=='+' ){
  29168. z+=incr;
  29169. }
  29170. /* copy max significant digits to significand */
  29171. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  29172. s = s*10 + (*z - '0');
  29173. z+=incr; nDigits++;
  29174. }
  29175. /* skip non-significant significand digits
  29176. ** (increase exponent by d to shift decimal left) */
  29177. while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; nDigits++; d++; }
  29178. if( z>=zEnd ) goto do_atof_calc;
  29179. /* if decimal point is present */
  29180. if( *z=='.' ){
  29181. z+=incr;
  29182. /* copy digits from after decimal to significand
  29183. ** (decrease exponent by d to shift decimal right) */
  29184. while( z<zEnd && sqlite3Isdigit(*z) ){
  29185. if( s<((LARGEST_INT64-9)/10) ){
  29186. s = s*10 + (*z - '0');
  29187. d--;
  29188. }
  29189. z+=incr; nDigits++;
  29190. }
  29191. }
  29192. if( z>=zEnd ) goto do_atof_calc;
  29193. /* if exponent is present */
  29194. if( *z=='e' || *z=='E' ){
  29195. z+=incr;
  29196. eValid = 0;
  29197. /* This branch is needed to avoid a (harmless) buffer overread. The
  29198. ** special comment alerts the mutation tester that the correct answer
  29199. ** is obtained even if the branch is omitted */
  29200. if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
  29201. /* get sign of exponent */
  29202. if( *z=='-' ){
  29203. esign = -1;
  29204. z+=incr;
  29205. }else if( *z=='+' ){
  29206. z+=incr;
  29207. }
  29208. /* copy digits to exponent */
  29209. while( z<zEnd && sqlite3Isdigit(*z) ){
  29210. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  29211. z+=incr;
  29212. eValid = 1;
  29213. }
  29214. }
  29215. /* skip trailing spaces */
  29216. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  29217. do_atof_calc:
  29218. /* adjust exponent by d, and update sign */
  29219. e = (e*esign) + d;
  29220. if( e<0 ) {
  29221. esign = -1;
  29222. e *= -1;
  29223. } else {
  29224. esign = 1;
  29225. }
  29226. if( s==0 ) {
  29227. /* In the IEEE 754 standard, zero is signed. */
  29228. result = sign<0 ? -(double)0 : (double)0;
  29229. } else {
  29230. /* Attempt to reduce exponent.
  29231. **
  29232. ** Branches that are not required for the correct answer but which only
  29233. ** help to obtain the correct answer faster are marked with special
  29234. ** comments, as a hint to the mutation tester.
  29235. */
  29236. while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
  29237. if( esign>0 ){
  29238. if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
  29239. s *= 10;
  29240. }else{
  29241. if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
  29242. s /= 10;
  29243. }
  29244. e--;
  29245. }
  29246. /* adjust the sign of significand */
  29247. s = sign<0 ? -s : s;
  29248. if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
  29249. result = (double)s;
  29250. }else{
  29251. /* attempt to handle extremely small/large numbers better */
  29252. if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
  29253. if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
  29254. LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
  29255. if( esign<0 ){
  29256. result = s / scale;
  29257. result /= 1.0e+308;
  29258. }else{
  29259. result = s * scale;
  29260. result *= 1.0e+308;
  29261. }
  29262. }else{ assert( e>=342 );
  29263. if( esign<0 ){
  29264. result = 0.0*s;
  29265. }else{
  29266. #ifdef INFINITY
  29267. result = INFINITY*s;
  29268. #else
  29269. result = 1e308*1e308*s; /* Infinity */
  29270. #endif
  29271. }
  29272. }
  29273. }else{
  29274. LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
  29275. if( esign<0 ){
  29276. result = s / scale;
  29277. }else{
  29278. result = s * scale;
  29279. }
  29280. }
  29281. }
  29282. }
  29283. /* store the result */
  29284. *pResult = result;
  29285. /* return true if number and no extra non-whitespace chracters after */
  29286. return z==zEnd && nDigits>0 && eValid && nonNum==0;
  29287. #else
  29288. return !sqlite3Atoi64(z, pResult, length, enc);
  29289. #endif /* SQLITE_OMIT_FLOATING_POINT */
  29290. }
  29291. /*
  29292. ** Compare the 19-character string zNum against the text representation
  29293. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  29294. ** if zNum is less than, equal to, or greater than the string.
  29295. ** Note that zNum must contain exactly 19 characters.
  29296. **
  29297. ** Unlike memcmp() this routine is guaranteed to return the difference
  29298. ** in the values of the last digit if the only difference is in the
  29299. ** last digit. So, for example,
  29300. **
  29301. ** compare2pow63("9223372036854775800", 1)
  29302. **
  29303. ** will return -8.
  29304. */
  29305. static int compare2pow63(const char *zNum, int incr){
  29306. int c = 0;
  29307. int i;
  29308. /* 012345678901234567 */
  29309. const char *pow63 = "922337203685477580";
  29310. for(i=0; c==0 && i<18; i++){
  29311. c = (zNum[i*incr]-pow63[i])*10;
  29312. }
  29313. if( c==0 ){
  29314. c = zNum[18*incr] - '8';
  29315. testcase( c==(-1) );
  29316. testcase( c==0 );
  29317. testcase( c==(+1) );
  29318. }
  29319. return c;
  29320. }
  29321. /*
  29322. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  29323. ** routine does *not* accept hexadecimal notation.
  29324. **
  29325. ** Returns:
  29326. **
  29327. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  29328. ** 1 Excess non-space text after the integer value
  29329. ** 2 Integer too large for a 64-bit signed integer or is malformed
  29330. ** 3 Special case of 9223372036854775808
  29331. **
  29332. ** length is the number of bytes in the string (bytes, not characters).
  29333. ** The string is not necessarily zero-terminated. The encoding is
  29334. ** given by enc.
  29335. */
  29336. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  29337. int incr;
  29338. u64 u = 0;
  29339. int neg = 0; /* assume positive */
  29340. int i;
  29341. int c = 0;
  29342. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  29343. int rc; /* Baseline return code */
  29344. const char *zStart;
  29345. const char *zEnd = zNum + length;
  29346. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  29347. if( enc==SQLITE_UTF8 ){
  29348. incr = 1;
  29349. }else{
  29350. incr = 2;
  29351. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  29352. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  29353. nonNum = i<length;
  29354. zEnd = &zNum[i^1];
  29355. zNum += (enc&1);
  29356. }
  29357. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  29358. if( zNum<zEnd ){
  29359. if( *zNum=='-' ){
  29360. neg = 1;
  29361. zNum+=incr;
  29362. }else if( *zNum=='+' ){
  29363. zNum+=incr;
  29364. }
  29365. }
  29366. zStart = zNum;
  29367. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  29368. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  29369. u = u*10 + c - '0';
  29370. }
  29371. testcase( i==18*incr );
  29372. testcase( i==19*incr );
  29373. testcase( i==20*incr );
  29374. if( u>LARGEST_INT64 ){
  29375. /* This test and assignment is needed only to suppress UB warnings
  29376. ** from clang and -fsanitize=undefined. This test and assignment make
  29377. ** the code a little larger and slower, and no harm comes from omitting
  29378. ** them, but we must appaise the undefined-behavior pharisees. */
  29379. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  29380. }else if( neg ){
  29381. *pNum = -(i64)u;
  29382. }else{
  29383. *pNum = (i64)u;
  29384. }
  29385. rc = 0;
  29386. if( (i==0 && zStart==zNum) /* No digits */
  29387. || nonNum /* UTF16 with high-order bytes non-zero */
  29388. ){
  29389. rc = 1;
  29390. }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */
  29391. int jj = i;
  29392. do{
  29393. if( !sqlite3Isspace(zNum[jj]) ){
  29394. rc = 1; /* Extra non-space text after the integer */
  29395. break;
  29396. }
  29397. jj += incr;
  29398. }while( &zNum[jj]<zEnd );
  29399. }
  29400. if( i<19*incr ){
  29401. /* Less than 19 digits, so we know that it fits in 64 bits */
  29402. assert( u<=LARGEST_INT64 );
  29403. return rc;
  29404. }else{
  29405. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  29406. c = i>19*incr ? 1 : compare2pow63(zNum, incr);
  29407. if( c<0 ){
  29408. /* zNum is less than 9223372036854775808 so it fits */
  29409. assert( u<=LARGEST_INT64 );
  29410. return rc;
  29411. }else{
  29412. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  29413. if( c>0 ){
  29414. /* zNum is greater than 9223372036854775808 so it overflows */
  29415. return 2;
  29416. }else{
  29417. /* zNum is exactly 9223372036854775808. Fits if negative. The
  29418. ** special case 2 overflow if positive */
  29419. assert( u-1==LARGEST_INT64 );
  29420. return neg ? rc : 3;
  29421. }
  29422. }
  29423. }
  29424. }
  29425. /*
  29426. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  29427. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  29428. ** whereas sqlite3Atoi64() does not.
  29429. **
  29430. ** Returns:
  29431. **
  29432. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  29433. ** 1 Excess text after the integer value
  29434. ** 2 Integer too large for a 64-bit signed integer or is malformed
  29435. ** 3 Special case of 9223372036854775808
  29436. */
  29437. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  29438. #ifndef SQLITE_OMIT_HEX_INTEGER
  29439. if( z[0]=='0'
  29440. && (z[1]=='x' || z[1]=='X')
  29441. ){
  29442. u64 u = 0;
  29443. int i, k;
  29444. for(i=2; z[i]=='0'; i++){}
  29445. for(k=i; sqlite3Isxdigit(z[k]); k++){
  29446. u = u*16 + sqlite3HexToInt(z[k]);
  29447. }
  29448. memcpy(pOut, &u, 8);
  29449. return (z[k]==0 && k-i<=16) ? 0 : 2;
  29450. }else
  29451. #endif /* SQLITE_OMIT_HEX_INTEGER */
  29452. {
  29453. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  29454. }
  29455. }
  29456. /*
  29457. ** If zNum represents an integer that will fit in 32-bits, then set
  29458. ** *pValue to that integer and return true. Otherwise return false.
  29459. **
  29460. ** This routine accepts both decimal and hexadecimal notation for integers.
  29461. **
  29462. ** Any non-numeric characters that following zNum are ignored.
  29463. ** This is different from sqlite3Atoi64() which requires the
  29464. ** input number to be zero-terminated.
  29465. */
  29466. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  29467. sqlite_int64 v = 0;
  29468. int i, c;
  29469. int neg = 0;
  29470. if( zNum[0]=='-' ){
  29471. neg = 1;
  29472. zNum++;
  29473. }else if( zNum[0]=='+' ){
  29474. zNum++;
  29475. }
  29476. #ifndef SQLITE_OMIT_HEX_INTEGER
  29477. else if( zNum[0]=='0'
  29478. && (zNum[1]=='x' || zNum[1]=='X')
  29479. && sqlite3Isxdigit(zNum[2])
  29480. ){
  29481. u32 u = 0;
  29482. zNum += 2;
  29483. while( zNum[0]=='0' ) zNum++;
  29484. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  29485. u = u*16 + sqlite3HexToInt(zNum[i]);
  29486. }
  29487. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  29488. memcpy(pValue, &u, 4);
  29489. return 1;
  29490. }else{
  29491. return 0;
  29492. }
  29493. }
  29494. #endif
  29495. if( !sqlite3Isdigit(zNum[0]) ) return 0;
  29496. while( zNum[0]=='0' ) zNum++;
  29497. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  29498. v = v*10 + c;
  29499. }
  29500. /* The longest decimal representation of a 32 bit integer is 10 digits:
  29501. **
  29502. ** 1234567890
  29503. ** 2^31 -> 2147483648
  29504. */
  29505. testcase( i==10 );
  29506. if( i>10 ){
  29507. return 0;
  29508. }
  29509. testcase( v-neg==2147483647 );
  29510. if( v-neg>2147483647 ){
  29511. return 0;
  29512. }
  29513. if( neg ){
  29514. v = -v;
  29515. }
  29516. *pValue = (int)v;
  29517. return 1;
  29518. }
  29519. /*
  29520. ** Return a 32-bit integer value extracted from a string. If the
  29521. ** string is not an integer, just return 0.
  29522. */
  29523. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  29524. int x = 0;
  29525. if( z ) sqlite3GetInt32(z, &x);
  29526. return x;
  29527. }
  29528. /*
  29529. ** The variable-length integer encoding is as follows:
  29530. **
  29531. ** KEY:
  29532. ** A = 0xxxxxxx 7 bits of data and one flag bit
  29533. ** B = 1xxxxxxx 7 bits of data and one flag bit
  29534. ** C = xxxxxxxx 8 bits of data
  29535. **
  29536. ** 7 bits - A
  29537. ** 14 bits - BA
  29538. ** 21 bits - BBA
  29539. ** 28 bits - BBBA
  29540. ** 35 bits - BBBBA
  29541. ** 42 bits - BBBBBA
  29542. ** 49 bits - BBBBBBA
  29543. ** 56 bits - BBBBBBBA
  29544. ** 64 bits - BBBBBBBBC
  29545. */
  29546. /*
  29547. ** Write a 64-bit variable-length integer to memory starting at p[0].
  29548. ** The length of data write will be between 1 and 9 bytes. The number
  29549. ** of bytes written is returned.
  29550. **
  29551. ** A variable-length integer consists of the lower 7 bits of each byte
  29552. ** for all bytes that have the 8th bit set and one byte with the 8th
  29553. ** bit clear. Except, if we get to the 9th byte, it stores the full
  29554. ** 8 bits and is the last byte.
  29555. */
  29556. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  29557. int i, j, n;
  29558. u8 buf[10];
  29559. if( v & (((u64)0xff000000)<<32) ){
  29560. p[8] = (u8)v;
  29561. v >>= 8;
  29562. for(i=7; i>=0; i--){
  29563. p[i] = (u8)((v & 0x7f) | 0x80);
  29564. v >>= 7;
  29565. }
  29566. return 9;
  29567. }
  29568. n = 0;
  29569. do{
  29570. buf[n++] = (u8)((v & 0x7f) | 0x80);
  29571. v >>= 7;
  29572. }while( v!=0 );
  29573. buf[0] &= 0x7f;
  29574. assert( n<=9 );
  29575. for(i=0, j=n-1; j>=0; j--, i++){
  29576. p[i] = buf[j];
  29577. }
  29578. return n;
  29579. }
  29580. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  29581. if( v<=0x7f ){
  29582. p[0] = v&0x7f;
  29583. return 1;
  29584. }
  29585. if( v<=0x3fff ){
  29586. p[0] = ((v>>7)&0x7f)|0x80;
  29587. p[1] = v&0x7f;
  29588. return 2;
  29589. }
  29590. return putVarint64(p,v);
  29591. }
  29592. /*
  29593. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  29594. ** are defined here rather than simply putting the constant expressions
  29595. ** inline in order to work around bugs in the RVT compiler.
  29596. **
  29597. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  29598. **
  29599. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  29600. */
  29601. #define SLOT_2_0 0x001fc07f
  29602. #define SLOT_4_2_0 0xf01fc07f
  29603. /*
  29604. ** Read a 64-bit variable-length integer from memory starting at p[0].
  29605. ** Return the number of bytes read. The value is stored in *v.
  29606. */
  29607. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  29608. u32 a,b,s;
  29609. a = *p;
  29610. /* a: p0 (unmasked) */
  29611. if (!(a&0x80))
  29612. {
  29613. *v = a;
  29614. return 1;
  29615. }
  29616. p++;
  29617. b = *p;
  29618. /* b: p1 (unmasked) */
  29619. if (!(b&0x80))
  29620. {
  29621. a &= 0x7f;
  29622. a = a<<7;
  29623. a |= b;
  29624. *v = a;
  29625. return 2;
  29626. }
  29627. /* Verify that constants are precomputed correctly */
  29628. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  29629. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  29630. p++;
  29631. a = a<<14;
  29632. a |= *p;
  29633. /* a: p0<<14 | p2 (unmasked) */
  29634. if (!(a&0x80))
  29635. {
  29636. a &= SLOT_2_0;
  29637. b &= 0x7f;
  29638. b = b<<7;
  29639. a |= b;
  29640. *v = a;
  29641. return 3;
  29642. }
  29643. /* CSE1 from below */
  29644. a &= SLOT_2_0;
  29645. p++;
  29646. b = b<<14;
  29647. b |= *p;
  29648. /* b: p1<<14 | p3 (unmasked) */
  29649. if (!(b&0x80))
  29650. {
  29651. b &= SLOT_2_0;
  29652. /* moved CSE1 up */
  29653. /* a &= (0x7f<<14)|(0x7f); */
  29654. a = a<<7;
  29655. a |= b;
  29656. *v = a;
  29657. return 4;
  29658. }
  29659. /* a: p0<<14 | p2 (masked) */
  29660. /* b: p1<<14 | p3 (unmasked) */
  29661. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  29662. /* moved CSE1 up */
  29663. /* a &= (0x7f<<14)|(0x7f); */
  29664. b &= SLOT_2_0;
  29665. s = a;
  29666. /* s: p0<<14 | p2 (masked) */
  29667. p++;
  29668. a = a<<14;
  29669. a |= *p;
  29670. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  29671. if (!(a&0x80))
  29672. {
  29673. /* we can skip these cause they were (effectively) done above
  29674. ** while calculating s */
  29675. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  29676. /* b &= (0x7f<<14)|(0x7f); */
  29677. b = b<<7;
  29678. a |= b;
  29679. s = s>>18;
  29680. *v = ((u64)s)<<32 | a;
  29681. return 5;
  29682. }
  29683. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  29684. s = s<<7;
  29685. s |= b;
  29686. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  29687. p++;
  29688. b = b<<14;
  29689. b |= *p;
  29690. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  29691. if (!(b&0x80))
  29692. {
  29693. /* we can skip this cause it was (effectively) done above in calc'ing s */
  29694. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  29695. a &= SLOT_2_0;
  29696. a = a<<7;
  29697. a |= b;
  29698. s = s>>18;
  29699. *v = ((u64)s)<<32 | a;
  29700. return 6;
  29701. }
  29702. p++;
  29703. a = a<<14;
  29704. a |= *p;
  29705. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  29706. if (!(a&0x80))
  29707. {
  29708. a &= SLOT_4_2_0;
  29709. b &= SLOT_2_0;
  29710. b = b<<7;
  29711. a |= b;
  29712. s = s>>11;
  29713. *v = ((u64)s)<<32 | a;
  29714. return 7;
  29715. }
  29716. /* CSE2 from below */
  29717. a &= SLOT_2_0;
  29718. p++;
  29719. b = b<<14;
  29720. b |= *p;
  29721. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  29722. if (!(b&0x80))
  29723. {
  29724. b &= SLOT_4_2_0;
  29725. /* moved CSE2 up */
  29726. /* a &= (0x7f<<14)|(0x7f); */
  29727. a = a<<7;
  29728. a |= b;
  29729. s = s>>4;
  29730. *v = ((u64)s)<<32 | a;
  29731. return 8;
  29732. }
  29733. p++;
  29734. a = a<<15;
  29735. a |= *p;
  29736. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  29737. /* moved CSE2 up */
  29738. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  29739. b &= SLOT_2_0;
  29740. b = b<<8;
  29741. a |= b;
  29742. s = s<<4;
  29743. b = p[-4];
  29744. b &= 0x7f;
  29745. b = b>>3;
  29746. s |= b;
  29747. *v = ((u64)s)<<32 | a;
  29748. return 9;
  29749. }
  29750. /*
  29751. ** Read a 32-bit variable-length integer from memory starting at p[0].
  29752. ** Return the number of bytes read. The value is stored in *v.
  29753. **
  29754. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  29755. ** integer, then set *v to 0xffffffff.
  29756. **
  29757. ** A MACRO version, getVarint32, is provided which inlines the
  29758. ** single-byte case. All code should use the MACRO version as
  29759. ** this function assumes the single-byte case has already been handled.
  29760. */
  29761. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  29762. u32 a,b;
  29763. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  29764. ** by the getVarin32() macro */
  29765. a = *p;
  29766. /* a: p0 (unmasked) */
  29767. #ifndef getVarint32
  29768. if (!(a&0x80))
  29769. {
  29770. /* Values between 0 and 127 */
  29771. *v = a;
  29772. return 1;
  29773. }
  29774. #endif
  29775. /* The 2-byte case */
  29776. p++;
  29777. b = *p;
  29778. /* b: p1 (unmasked) */
  29779. if (!(b&0x80))
  29780. {
  29781. /* Values between 128 and 16383 */
  29782. a &= 0x7f;
  29783. a = a<<7;
  29784. *v = a | b;
  29785. return 2;
  29786. }
  29787. /* The 3-byte case */
  29788. p++;
  29789. a = a<<14;
  29790. a |= *p;
  29791. /* a: p0<<14 | p2 (unmasked) */
  29792. if (!(a&0x80))
  29793. {
  29794. /* Values between 16384 and 2097151 */
  29795. a &= (0x7f<<14)|(0x7f);
  29796. b &= 0x7f;
  29797. b = b<<7;
  29798. *v = a | b;
  29799. return 3;
  29800. }
  29801. /* A 32-bit varint is used to store size information in btrees.
  29802. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  29803. ** A 3-byte varint is sufficient, for example, to record the size
  29804. ** of a 1048569-byte BLOB or string.
  29805. **
  29806. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  29807. ** rare larger cases can be handled by the slower 64-bit varint
  29808. ** routine.
  29809. */
  29810. #if 1
  29811. {
  29812. u64 v64;
  29813. u8 n;
  29814. p -= 2;
  29815. n = sqlite3GetVarint(p, &v64);
  29816. assert( n>3 && n<=9 );
  29817. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  29818. *v = 0xffffffff;
  29819. }else{
  29820. *v = (u32)v64;
  29821. }
  29822. return n;
  29823. }
  29824. #else
  29825. /* For following code (kept for historical record only) shows an
  29826. ** unrolling for the 3- and 4-byte varint cases. This code is
  29827. ** slightly faster, but it is also larger and much harder to test.
  29828. */
  29829. p++;
  29830. b = b<<14;
  29831. b |= *p;
  29832. /* b: p1<<14 | p3 (unmasked) */
  29833. if (!(b&0x80))
  29834. {
  29835. /* Values between 2097152 and 268435455 */
  29836. b &= (0x7f<<14)|(0x7f);
  29837. a &= (0x7f<<14)|(0x7f);
  29838. a = a<<7;
  29839. *v = a | b;
  29840. return 4;
  29841. }
  29842. p++;
  29843. a = a<<14;
  29844. a |= *p;
  29845. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  29846. if (!(a&0x80))
  29847. {
  29848. /* Values between 268435456 and 34359738367 */
  29849. a &= SLOT_4_2_0;
  29850. b &= SLOT_4_2_0;
  29851. b = b<<7;
  29852. *v = a | b;
  29853. return 5;
  29854. }
  29855. /* We can only reach this point when reading a corrupt database
  29856. ** file. In that case we are not in any hurry. Use the (relatively
  29857. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  29858. ** value. */
  29859. {
  29860. u64 v64;
  29861. u8 n;
  29862. p -= 4;
  29863. n = sqlite3GetVarint(p, &v64);
  29864. assert( n>5 && n<=9 );
  29865. *v = (u32)v64;
  29866. return n;
  29867. }
  29868. #endif
  29869. }
  29870. /*
  29871. ** Return the number of bytes that will be needed to store the given
  29872. ** 64-bit integer.
  29873. */
  29874. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  29875. int i;
  29876. for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
  29877. return i;
  29878. }
  29879. /*
  29880. ** Read or write a four-byte big-endian integer value.
  29881. */
  29882. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  29883. #if SQLITE_BYTEORDER==4321
  29884. u32 x;
  29885. memcpy(&x,p,4);
  29886. return x;
  29887. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  29888. u32 x;
  29889. memcpy(&x,p,4);
  29890. return __builtin_bswap32(x);
  29891. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  29892. u32 x;
  29893. memcpy(&x,p,4);
  29894. return _byteswap_ulong(x);
  29895. #else
  29896. testcase( p[0]&0x80 );
  29897. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  29898. #endif
  29899. }
  29900. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  29901. #if SQLITE_BYTEORDER==4321
  29902. memcpy(p,&v,4);
  29903. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  29904. u32 x = __builtin_bswap32(v);
  29905. memcpy(p,&x,4);
  29906. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  29907. u32 x = _byteswap_ulong(v);
  29908. memcpy(p,&x,4);
  29909. #else
  29910. p[0] = (u8)(v>>24);
  29911. p[1] = (u8)(v>>16);
  29912. p[2] = (u8)(v>>8);
  29913. p[3] = (u8)v;
  29914. #endif
  29915. }
  29916. /*
  29917. ** Translate a single byte of Hex into an integer.
  29918. ** This routine only works if h really is a valid hexadecimal
  29919. ** character: 0..9a..fA..F
  29920. */
  29921. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  29922. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  29923. #ifdef SQLITE_ASCII
  29924. h += 9*(1&(h>>6));
  29925. #endif
  29926. #ifdef SQLITE_EBCDIC
  29927. h += 9*(1&~(h>>4));
  29928. #endif
  29929. return (u8)(h & 0xf);
  29930. }
  29931. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  29932. /*
  29933. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  29934. ** value. Return a pointer to its binary value. Space to hold the
  29935. ** binary value has been obtained from malloc and must be freed by
  29936. ** the calling routine.
  29937. */
  29938. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  29939. char *zBlob;
  29940. int i;
  29941. zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
  29942. n--;
  29943. if( zBlob ){
  29944. for(i=0; i<n; i+=2){
  29945. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  29946. }
  29947. zBlob[i/2] = 0;
  29948. }
  29949. return zBlob;
  29950. }
  29951. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  29952. /*
  29953. ** Log an error that is an API call on a connection pointer that should
  29954. ** not have been used. The "type" of connection pointer is given as the
  29955. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  29956. */
  29957. static void logBadConnection(const char *zType){
  29958. sqlite3_log(SQLITE_MISUSE,
  29959. "API call with %s database connection pointer",
  29960. zType
  29961. );
  29962. }
  29963. /*
  29964. ** Check to make sure we have a valid db pointer. This test is not
  29965. ** foolproof but it does provide some measure of protection against
  29966. ** misuse of the interface such as passing in db pointers that are
  29967. ** NULL or which have been previously closed. If this routine returns
  29968. ** 1 it means that the db pointer is valid and 0 if it should not be
  29969. ** dereferenced for any reason. The calling function should invoke
  29970. ** SQLITE_MISUSE immediately.
  29971. **
  29972. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  29973. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  29974. ** open properly and is not fit for general use but which can be
  29975. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  29976. */
  29977. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  29978. u32 magic;
  29979. if( db==0 ){
  29980. logBadConnection("NULL");
  29981. return 0;
  29982. }
  29983. magic = db->magic;
  29984. if( magic!=SQLITE_MAGIC_OPEN ){
  29985. if( sqlite3SafetyCheckSickOrOk(db) ){
  29986. testcase( sqlite3GlobalConfig.xLog!=0 );
  29987. logBadConnection("unopened");
  29988. }
  29989. return 0;
  29990. }else{
  29991. return 1;
  29992. }
  29993. }
  29994. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  29995. u32 magic;
  29996. magic = db->magic;
  29997. if( magic!=SQLITE_MAGIC_SICK &&
  29998. magic!=SQLITE_MAGIC_OPEN &&
  29999. magic!=SQLITE_MAGIC_BUSY ){
  30000. testcase( sqlite3GlobalConfig.xLog!=0 );
  30001. logBadConnection("invalid");
  30002. return 0;
  30003. }else{
  30004. return 1;
  30005. }
  30006. }
  30007. /*
  30008. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  30009. ** the other 64-bit signed integer at *pA and store the result in *pA.
  30010. ** Return 0 on success. Or if the operation would have resulted in an
  30011. ** overflow, leave *pA unchanged and return 1.
  30012. */
  30013. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  30014. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  30015. return __builtin_add_overflow(*pA, iB, pA);
  30016. #else
  30017. i64 iA = *pA;
  30018. testcase( iA==0 ); testcase( iA==1 );
  30019. testcase( iB==-1 ); testcase( iB==0 );
  30020. if( iB>=0 ){
  30021. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  30022. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  30023. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  30024. }else{
  30025. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  30026. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  30027. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  30028. }
  30029. *pA += iB;
  30030. return 0;
  30031. #endif
  30032. }
  30033. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  30034. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  30035. return __builtin_sub_overflow(*pA, iB, pA);
  30036. #else
  30037. testcase( iB==SMALLEST_INT64+1 );
  30038. if( iB==SMALLEST_INT64 ){
  30039. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  30040. if( (*pA)>=0 ) return 1;
  30041. *pA -= iB;
  30042. return 0;
  30043. }else{
  30044. return sqlite3AddInt64(pA, -iB);
  30045. }
  30046. #endif
  30047. }
  30048. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  30049. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  30050. return __builtin_mul_overflow(*pA, iB, pA);
  30051. #else
  30052. i64 iA = *pA;
  30053. if( iB>0 ){
  30054. if( iA>LARGEST_INT64/iB ) return 1;
  30055. if( iA<SMALLEST_INT64/iB ) return 1;
  30056. }else if( iB<0 ){
  30057. if( iA>0 ){
  30058. if( iB<SMALLEST_INT64/iA ) return 1;
  30059. }else if( iA<0 ){
  30060. if( iB==SMALLEST_INT64 ) return 1;
  30061. if( iA==SMALLEST_INT64 ) return 1;
  30062. if( -iA>LARGEST_INT64/-iB ) return 1;
  30063. }
  30064. }
  30065. *pA = iA*iB;
  30066. return 0;
  30067. #endif
  30068. }
  30069. /*
  30070. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  30071. ** if the integer has a value of -2147483648, return +2147483647
  30072. */
  30073. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  30074. if( x>=0 ) return x;
  30075. if( x==(int)0x80000000 ) return 0x7fffffff;
  30076. return -x;
  30077. }
  30078. #ifdef SQLITE_ENABLE_8_3_NAMES
  30079. /*
  30080. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  30081. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  30082. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  30083. ** three characters, then shorten the suffix on z[] to be the last three
  30084. ** characters of the original suffix.
  30085. **
  30086. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  30087. ** do the suffix shortening regardless of URI parameter.
  30088. **
  30089. ** Examples:
  30090. **
  30091. ** test.db-journal => test.nal
  30092. ** test.db-wal => test.wal
  30093. ** test.db-shm => test.shm
  30094. ** test.db-mj7f3319fa => test.9fa
  30095. */
  30096. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  30097. #if SQLITE_ENABLE_8_3_NAMES<2
  30098. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  30099. #endif
  30100. {
  30101. int i, sz;
  30102. sz = sqlite3Strlen30(z);
  30103. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  30104. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  30105. }
  30106. }
  30107. #endif
  30108. /*
  30109. ** Find (an approximate) sum of two LogEst values. This computation is
  30110. ** not a simple "+" operator because LogEst is stored as a logarithmic
  30111. ** value.
  30112. **
  30113. */
  30114. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  30115. static const unsigned char x[] = {
  30116. 10, 10, /* 0,1 */
  30117. 9, 9, /* 2,3 */
  30118. 8, 8, /* 4,5 */
  30119. 7, 7, 7, /* 6,7,8 */
  30120. 6, 6, 6, /* 9,10,11 */
  30121. 5, 5, 5, /* 12-14 */
  30122. 4, 4, 4, 4, /* 15-18 */
  30123. 3, 3, 3, 3, 3, 3, /* 19-24 */
  30124. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  30125. };
  30126. if( a>=b ){
  30127. if( a>b+49 ) return a;
  30128. if( a>b+31 ) return a+1;
  30129. return a+x[a-b];
  30130. }else{
  30131. if( b>a+49 ) return b;
  30132. if( b>a+31 ) return b+1;
  30133. return b+x[b-a];
  30134. }
  30135. }
  30136. /*
  30137. ** Convert an integer into a LogEst. In other words, compute an
  30138. ** approximation for 10*log2(x).
  30139. */
  30140. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  30141. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  30142. LogEst y = 40;
  30143. if( x<8 ){
  30144. if( x<2 ) return 0;
  30145. while( x<8 ){ y -= 10; x <<= 1; }
  30146. }else{
  30147. #if GCC_VERSION>=5004000
  30148. int i = 60 - __builtin_clzll(x);
  30149. y += i*10;
  30150. x >>= i;
  30151. #else
  30152. while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
  30153. while( x>15 ){ y += 10; x >>= 1; }
  30154. #endif
  30155. }
  30156. return a[x&7] + y - 10;
  30157. }
  30158. #ifndef SQLITE_OMIT_VIRTUALTABLE
  30159. /*
  30160. ** Convert a double into a LogEst
  30161. ** In other words, compute an approximation for 10*log2(x).
  30162. */
  30163. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  30164. u64 a;
  30165. LogEst e;
  30166. assert( sizeof(x)==8 && sizeof(a)==8 );
  30167. if( x<=1 ) return 0;
  30168. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  30169. memcpy(&a, &x, 8);
  30170. e = (a>>52) - 1022;
  30171. return e*10;
  30172. }
  30173. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  30174. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  30175. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  30176. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  30177. /*
  30178. ** Convert a LogEst into an integer.
  30179. **
  30180. ** Note that this routine is only used when one or more of various
  30181. ** non-standard compile-time options is enabled.
  30182. */
  30183. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  30184. u64 n;
  30185. n = x%10;
  30186. x /= 10;
  30187. if( n>=5 ) n -= 2;
  30188. else if( n>=1 ) n -= 1;
  30189. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  30190. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  30191. if( x>60 ) return (u64)LARGEST_INT64;
  30192. #else
  30193. /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
  30194. ** possible to this routine is 310, resulting in a maximum x of 31 */
  30195. assert( x<=60 );
  30196. #endif
  30197. return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
  30198. }
  30199. #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
  30200. /*
  30201. ** Add a new name/number pair to a VList. This might require that the
  30202. ** VList object be reallocated, so return the new VList. If an OOM
  30203. ** error occurs, the original VList returned and the
  30204. ** db->mallocFailed flag is set.
  30205. **
  30206. ** A VList is really just an array of integers. To destroy a VList,
  30207. ** simply pass it to sqlite3DbFree().
  30208. **
  30209. ** The first integer is the number of integers allocated for the whole
  30210. ** VList. The second integer is the number of integers actually used.
  30211. ** Each name/number pair is encoded by subsequent groups of 3 or more
  30212. ** integers.
  30213. **
  30214. ** Each name/number pair starts with two integers which are the numeric
  30215. ** value for the pair and the size of the name/number pair, respectively.
  30216. ** The text name overlays one or more following integers. The text name
  30217. ** is always zero-terminated.
  30218. **
  30219. ** Conceptually:
  30220. **
  30221. ** struct VList {
  30222. ** int nAlloc; // Number of allocated slots
  30223. ** int nUsed; // Number of used slots
  30224. ** struct VListEntry {
  30225. ** int iValue; // Value for this entry
  30226. ** int nSlot; // Slots used by this entry
  30227. ** // ... variable name goes here
  30228. ** } a[0];
  30229. ** }
  30230. **
  30231. ** During code generation, pointers to the variable names within the
  30232. ** VList are taken. When that happens, nAlloc is set to zero as an
  30233. ** indication that the VList may never again be enlarged, since the
  30234. ** accompanying realloc() would invalidate the pointers.
  30235. */
  30236. SQLITE_PRIVATE VList *sqlite3VListAdd(
  30237. sqlite3 *db, /* The database connection used for malloc() */
  30238. VList *pIn, /* The input VList. Might be NULL */
  30239. const char *zName, /* Name of symbol to add */
  30240. int nName, /* Bytes of text in zName */
  30241. int iVal /* Value to associate with zName */
  30242. ){
  30243. int nInt; /* number of sizeof(int) objects needed for zName */
  30244. char *z; /* Pointer to where zName will be stored */
  30245. int i; /* Index in pIn[] where zName is stored */
  30246. nInt = nName/4 + 3;
  30247. assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
  30248. if( pIn==0 || pIn[1]+nInt > pIn[0] ){
  30249. /* Enlarge the allocation */
  30250. sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
  30251. VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
  30252. if( pOut==0 ) return pIn;
  30253. if( pIn==0 ) pOut[1] = 2;
  30254. pIn = pOut;
  30255. pIn[0] = nAlloc;
  30256. }
  30257. i = pIn[1];
  30258. pIn[i] = iVal;
  30259. pIn[i+1] = nInt;
  30260. z = (char*)&pIn[i+2];
  30261. pIn[1] = i+nInt;
  30262. assert( pIn[1]<=pIn[0] );
  30263. memcpy(z, zName, nName);
  30264. z[nName] = 0;
  30265. return pIn;
  30266. }
  30267. /*
  30268. ** Return a pointer to the name of a variable in the given VList that
  30269. ** has the value iVal. Or return a NULL if there is no such variable in
  30270. ** the list
  30271. */
  30272. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
  30273. int i, mx;
  30274. if( pIn==0 ) return 0;
  30275. mx = pIn[1];
  30276. i = 2;
  30277. do{
  30278. if( pIn[i]==iVal ) return (char*)&pIn[i+2];
  30279. i += pIn[i+1];
  30280. }while( i<mx );
  30281. return 0;
  30282. }
  30283. /*
  30284. ** Return the number of the variable named zName, if it is in VList.
  30285. ** or return 0 if there is no such variable.
  30286. */
  30287. SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
  30288. int i, mx;
  30289. if( pIn==0 ) return 0;
  30290. mx = pIn[1];
  30291. i = 2;
  30292. do{
  30293. const char *z = (const char*)&pIn[i+2];
  30294. if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
  30295. i += pIn[i+1];
  30296. }while( i<mx );
  30297. return 0;
  30298. }
  30299. /************** End of util.c ************************************************/
  30300. /************** Begin file hash.c ********************************************/
  30301. /*
  30302. ** 2001 September 22
  30303. **
  30304. ** The author disclaims copyright to this source code. In place of
  30305. ** a legal notice, here is a blessing:
  30306. **
  30307. ** May you do good and not evil.
  30308. ** May you find forgiveness for yourself and forgive others.
  30309. ** May you share freely, never taking more than you give.
  30310. **
  30311. *************************************************************************
  30312. ** This is the implementation of generic hash-tables
  30313. ** used in SQLite.
  30314. */
  30315. /* #include "sqliteInt.h" */
  30316. /* #include <assert.h> */
  30317. /* Turn bulk memory into a hash table object by initializing the
  30318. ** fields of the Hash structure.
  30319. **
  30320. ** "pNew" is a pointer to the hash table that is to be initialized.
  30321. */
  30322. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  30323. assert( pNew!=0 );
  30324. pNew->first = 0;
  30325. pNew->count = 0;
  30326. pNew->htsize = 0;
  30327. pNew->ht = 0;
  30328. }
  30329. /* Remove all entries from a hash table. Reclaim all memory.
  30330. ** Call this routine to delete a hash table or to reset a hash table
  30331. ** to the empty state.
  30332. */
  30333. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  30334. HashElem *elem; /* For looping over all elements of the table */
  30335. assert( pH!=0 );
  30336. elem = pH->first;
  30337. pH->first = 0;
  30338. sqlite3_free(pH->ht);
  30339. pH->ht = 0;
  30340. pH->htsize = 0;
  30341. while( elem ){
  30342. HashElem *next_elem = elem->next;
  30343. sqlite3_free(elem);
  30344. elem = next_elem;
  30345. }
  30346. pH->count = 0;
  30347. }
  30348. /*
  30349. ** The hashing function.
  30350. */
  30351. static unsigned int strHash(const char *z){
  30352. unsigned int h = 0;
  30353. unsigned char c;
  30354. while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
  30355. /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
  30356. ** 0x9e3779b1 is 2654435761 which is the closest prime number to
  30357. ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
  30358. h += sqlite3UpperToLower[c];
  30359. h *= 0x9e3779b1;
  30360. }
  30361. return h;
  30362. }
  30363. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  30364. ** insert pNew into the pEntry hash bucket.
  30365. */
  30366. static void insertElement(
  30367. Hash *pH, /* The complete hash table */
  30368. struct _ht *pEntry, /* The entry into which pNew is inserted */
  30369. HashElem *pNew /* The element to be inserted */
  30370. ){
  30371. HashElem *pHead; /* First element already in pEntry */
  30372. if( pEntry ){
  30373. pHead = pEntry->count ? pEntry->chain : 0;
  30374. pEntry->count++;
  30375. pEntry->chain = pNew;
  30376. }else{
  30377. pHead = 0;
  30378. }
  30379. if( pHead ){
  30380. pNew->next = pHead;
  30381. pNew->prev = pHead->prev;
  30382. if( pHead->prev ){ pHead->prev->next = pNew; }
  30383. else { pH->first = pNew; }
  30384. pHead->prev = pNew;
  30385. }else{
  30386. pNew->next = pH->first;
  30387. if( pH->first ){ pH->first->prev = pNew; }
  30388. pNew->prev = 0;
  30389. pH->first = pNew;
  30390. }
  30391. }
  30392. /* Resize the hash table so that it cantains "new_size" buckets.
  30393. **
  30394. ** The hash table might fail to resize if sqlite3_malloc() fails or
  30395. ** if the new size is the same as the prior size.
  30396. ** Return TRUE if the resize occurs and false if not.
  30397. */
  30398. static int rehash(Hash *pH, unsigned int new_size){
  30399. struct _ht *new_ht; /* The new hash table */
  30400. HashElem *elem, *next_elem; /* For looping over existing elements */
  30401. #if SQLITE_MALLOC_SOFT_LIMIT>0
  30402. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  30403. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  30404. }
  30405. if( new_size==pH->htsize ) return 0;
  30406. #endif
  30407. /* The inability to allocates space for a larger hash table is
  30408. ** a performance hit but it is not a fatal error. So mark the
  30409. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  30410. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  30411. ** only zeroes the requested number of bytes whereas this module will
  30412. ** use the actual amount of space allocated for the hash table (which
  30413. ** may be larger than the requested amount).
  30414. */
  30415. sqlite3BeginBenignMalloc();
  30416. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  30417. sqlite3EndBenignMalloc();
  30418. if( new_ht==0 ) return 0;
  30419. sqlite3_free(pH->ht);
  30420. pH->ht = new_ht;
  30421. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  30422. memset(new_ht, 0, new_size*sizeof(struct _ht));
  30423. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  30424. unsigned int h = strHash(elem->pKey) % new_size;
  30425. next_elem = elem->next;
  30426. insertElement(pH, &new_ht[h], elem);
  30427. }
  30428. return 1;
  30429. }
  30430. /* This function (for internal use only) locates an element in an
  30431. ** hash table that matches the given key. If no element is found,
  30432. ** a pointer to a static null element with HashElem.data==0 is returned.
  30433. ** If pH is not NULL, then the hash for this key is written to *pH.
  30434. */
  30435. static HashElem *findElementWithHash(
  30436. const Hash *pH, /* The pH to be searched */
  30437. const char *pKey, /* The key we are searching for */
  30438. unsigned int *pHash /* Write the hash value here */
  30439. ){
  30440. HashElem *elem; /* Used to loop thru the element list */
  30441. unsigned int count; /* Number of elements left to test */
  30442. unsigned int h; /* The computed hash */
  30443. static HashElem nullElement = { 0, 0, 0, 0 };
  30444. if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
  30445. struct _ht *pEntry;
  30446. h = strHash(pKey) % pH->htsize;
  30447. pEntry = &pH->ht[h];
  30448. elem = pEntry->chain;
  30449. count = pEntry->count;
  30450. }else{
  30451. h = 0;
  30452. elem = pH->first;
  30453. count = pH->count;
  30454. }
  30455. if( pHash ) *pHash = h;
  30456. while( count-- ){
  30457. assert( elem!=0 );
  30458. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  30459. return elem;
  30460. }
  30461. elem = elem->next;
  30462. }
  30463. return &nullElement;
  30464. }
  30465. /* Remove a single entry from the hash table given a pointer to that
  30466. ** element and a hash on the element's key.
  30467. */
  30468. static void removeElementGivenHash(
  30469. Hash *pH, /* The pH containing "elem" */
  30470. HashElem* elem, /* The element to be removed from the pH */
  30471. unsigned int h /* Hash value for the element */
  30472. ){
  30473. struct _ht *pEntry;
  30474. if( elem->prev ){
  30475. elem->prev->next = elem->next;
  30476. }else{
  30477. pH->first = elem->next;
  30478. }
  30479. if( elem->next ){
  30480. elem->next->prev = elem->prev;
  30481. }
  30482. if( pH->ht ){
  30483. pEntry = &pH->ht[h];
  30484. if( pEntry->chain==elem ){
  30485. pEntry->chain = elem->next;
  30486. }
  30487. assert( pEntry->count>0 );
  30488. pEntry->count--;
  30489. }
  30490. sqlite3_free( elem );
  30491. pH->count--;
  30492. if( pH->count==0 ){
  30493. assert( pH->first==0 );
  30494. assert( pH->count==0 );
  30495. sqlite3HashClear(pH);
  30496. }
  30497. }
  30498. /* Attempt to locate an element of the hash table pH with a key
  30499. ** that matches pKey. Return the data for this element if it is
  30500. ** found, or NULL if there is no match.
  30501. */
  30502. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  30503. assert( pH!=0 );
  30504. assert( pKey!=0 );
  30505. return findElementWithHash(pH, pKey, 0)->data;
  30506. }
  30507. /* Insert an element into the hash table pH. The key is pKey
  30508. ** and the data is "data".
  30509. **
  30510. ** If no element exists with a matching key, then a new
  30511. ** element is created and NULL is returned.
  30512. **
  30513. ** If another element already exists with the same key, then the
  30514. ** new data replaces the old data and the old data is returned.
  30515. ** The key is not copied in this instance. If a malloc fails, then
  30516. ** the new data is returned and the hash table is unchanged.
  30517. **
  30518. ** If the "data" parameter to this function is NULL, then the
  30519. ** element corresponding to "key" is removed from the hash table.
  30520. */
  30521. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  30522. unsigned int h; /* the hash of the key modulo hash table size */
  30523. HashElem *elem; /* Used to loop thru the element list */
  30524. HashElem *new_elem; /* New element added to the pH */
  30525. assert( pH!=0 );
  30526. assert( pKey!=0 );
  30527. elem = findElementWithHash(pH,pKey,&h);
  30528. if( elem->data ){
  30529. void *old_data = elem->data;
  30530. if( data==0 ){
  30531. removeElementGivenHash(pH,elem,h);
  30532. }else{
  30533. elem->data = data;
  30534. elem->pKey = pKey;
  30535. }
  30536. return old_data;
  30537. }
  30538. if( data==0 ) return 0;
  30539. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  30540. if( new_elem==0 ) return data;
  30541. new_elem->pKey = pKey;
  30542. new_elem->data = data;
  30543. pH->count++;
  30544. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  30545. if( rehash(pH, pH->count*2) ){
  30546. assert( pH->htsize>0 );
  30547. h = strHash(pKey) % pH->htsize;
  30548. }
  30549. }
  30550. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  30551. return 0;
  30552. }
  30553. /************** End of hash.c ************************************************/
  30554. /************** Begin file opcodes.c *****************************************/
  30555. /* Automatically generated. Do not edit */
  30556. /* See the tool/mkopcodec.tcl script for details. */
  30557. #if !defined(SQLITE_OMIT_EXPLAIN) \
  30558. || defined(VDBE_PROFILE) \
  30559. || defined(SQLITE_DEBUG)
  30560. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  30561. # define OpHelp(X) "\0" X
  30562. #else
  30563. # define OpHelp(X)
  30564. #endif
  30565. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  30566. static const char *const azName[] = {
  30567. /* 0 */ "Savepoint" OpHelp(""),
  30568. /* 1 */ "AutoCommit" OpHelp(""),
  30569. /* 2 */ "Transaction" OpHelp(""),
  30570. /* 3 */ "SorterNext" OpHelp(""),
  30571. /* 4 */ "Prev" OpHelp(""),
  30572. /* 5 */ "Next" OpHelp(""),
  30573. /* 6 */ "Checkpoint" OpHelp(""),
  30574. /* 7 */ "JournalMode" OpHelp(""),
  30575. /* 8 */ "Vacuum" OpHelp(""),
  30576. /* 9 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  30577. /* 10 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  30578. /* 11 */ "Goto" OpHelp(""),
  30579. /* 12 */ "Gosub" OpHelp(""),
  30580. /* 13 */ "InitCoroutine" OpHelp(""),
  30581. /* 14 */ "Yield" OpHelp(""),
  30582. /* 15 */ "MustBeInt" OpHelp(""),
  30583. /* 16 */ "Jump" OpHelp(""),
  30584. /* 17 */ "Once" OpHelp(""),
  30585. /* 18 */ "If" OpHelp(""),
  30586. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  30587. /* 20 */ "IfNot" OpHelp(""),
  30588. /* 21 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
  30589. /* 22 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  30590. /* 23 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  30591. /* 24 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  30592. /* 25 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  30593. /* 26 */ "IfNoHope" OpHelp("key=r[P3@P4]"),
  30594. /* 27 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  30595. /* 28 */ "NotFound" OpHelp("key=r[P3@P4]"),
  30596. /* 29 */ "Found" OpHelp("key=r[P3@P4]"),
  30597. /* 30 */ "SeekRowid" OpHelp("intkey=r[P3]"),
  30598. /* 31 */ "NotExists" OpHelp("intkey=r[P3]"),
  30599. /* 32 */ "Last" OpHelp(""),
  30600. /* 33 */ "IfSmaller" OpHelp(""),
  30601. /* 34 */ "SorterSort" OpHelp(""),
  30602. /* 35 */ "Sort" OpHelp(""),
  30603. /* 36 */ "Rewind" OpHelp(""),
  30604. /* 37 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  30605. /* 38 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  30606. /* 39 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  30607. /* 40 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  30608. /* 41 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  30609. /* 42 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  30610. /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  30611. /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  30612. /* 45 */ "Program" OpHelp(""),
  30613. /* 46 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  30614. /* 47 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  30615. /* 48 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
  30616. /* 49 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  30617. /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  30618. /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  30619. /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
  30620. /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
  30621. /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
  30622. /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
  30623. /* 56 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
  30624. /* 57 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
  30625. /* 58 */ "ElseNotEq" OpHelp(""),
  30626. /* 59 */ "IncrVacuum" OpHelp(""),
  30627. /* 60 */ "VNext" OpHelp(""),
  30628. /* 61 */ "Init" OpHelp("Start at P2"),
  30629. /* 62 */ "PureFunc0" OpHelp(""),
  30630. /* 63 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  30631. /* 64 */ "PureFunc" OpHelp(""),
  30632. /* 65 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  30633. /* 66 */ "Return" OpHelp(""),
  30634. /* 67 */ "EndCoroutine" OpHelp(""),
  30635. /* 68 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  30636. /* 69 */ "Halt" OpHelp(""),
  30637. /* 70 */ "Integer" OpHelp("r[P2]=P1"),
  30638. /* 71 */ "Int64" OpHelp("r[P2]=P4"),
  30639. /* 72 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  30640. /* 73 */ "Null" OpHelp("r[P2..P3]=NULL"),
  30641. /* 74 */ "SoftNull" OpHelp("r[P1]=NULL"),
  30642. /* 75 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  30643. /* 76 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  30644. /* 77 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  30645. /* 78 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  30646. /* 79 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  30647. /* 80 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
  30648. /* 81 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  30649. /* 82 */ "CollSeq" OpHelp(""),
  30650. /* 83 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  30651. /* 84 */ "RealAffinity" OpHelp(""),
  30652. /* 85 */ "Cast" OpHelp("affinity(r[P1])"),
  30653. /* 86 */ "Permutation" OpHelp(""),
  30654. /* 87 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  30655. /* 88 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
  30656. /* 89 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"),
  30657. /* 90 */ "Column" OpHelp("r[P3]=PX"),
  30658. /* 91 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  30659. /* 92 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  30660. /* 93 */ "Count" OpHelp("r[P2]=count()"),
  30661. /* 94 */ "ReadCookie" OpHelp(""),
  30662. /* 95 */ "SetCookie" OpHelp(""),
  30663. /* 96 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  30664. /* 97 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  30665. /* 98 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  30666. /* 99 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  30667. /* 100 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  30668. /* 101 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  30669. /* 102 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  30670. /* 103 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  30671. /* 104 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  30672. /* 105 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  30673. /* 106 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  30674. /* 107 */ "BitNot" OpHelp("r[P2]= ~r[P1]"),
  30675. /* 108 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  30676. /* 109 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  30677. /* 110 */ "String8" OpHelp("r[P2]='P4'"),
  30678. /* 111 */ "OpenDup" OpHelp(""),
  30679. /* 112 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  30680. /* 113 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  30681. /* 114 */ "SorterOpen" OpHelp(""),
  30682. /* 115 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  30683. /* 116 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  30684. /* 117 */ "Close" OpHelp(""),
  30685. /* 118 */ "ColumnsUsed" OpHelp(""),
  30686. /* 119 */ "SeekHit" OpHelp("seekHit=P2"),
  30687. /* 120 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  30688. /* 121 */ "NewRowid" OpHelp("r[P2]=rowid"),
  30689. /* 122 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  30690. /* 123 */ "Delete" OpHelp(""),
  30691. /* 124 */ "ResetCount" OpHelp(""),
  30692. /* 125 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  30693. /* 126 */ "SorterData" OpHelp("r[P2]=data"),
  30694. /* 127 */ "RowData" OpHelp("r[P2]=data"),
  30695. /* 128 */ "Rowid" OpHelp("r[P2]=rowid"),
  30696. /* 129 */ "NullRow" OpHelp(""),
  30697. /* 130 */ "SeekEnd" OpHelp(""),
  30698. /* 131 */ "SorterInsert" OpHelp("key=r[P2]"),
  30699. /* 132 */ "IdxInsert" OpHelp("key=r[P2]"),
  30700. /* 133 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  30701. /* 134 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
  30702. /* 135 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  30703. /* 136 */ "Destroy" OpHelp(""),
  30704. /* 137 */ "Clear" OpHelp(""),
  30705. /* 138 */ "ResetSorter" OpHelp(""),
  30706. /* 139 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
  30707. /* 140 */ "SqlExec" OpHelp(""),
  30708. /* 141 */ "ParseSchema" OpHelp(""),
  30709. /* 142 */ "LoadAnalysis" OpHelp(""),
  30710. /* 143 */ "DropTable" OpHelp(""),
  30711. /* 144 */ "DropIndex" OpHelp(""),
  30712. /* 145 */ "Real" OpHelp("r[P2]=P4"),
  30713. /* 146 */ "DropTrigger" OpHelp(""),
  30714. /* 147 */ "IntegrityCk" OpHelp(""),
  30715. /* 148 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  30716. /* 149 */ "Param" OpHelp(""),
  30717. /* 150 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  30718. /* 151 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  30719. /* 152 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
  30720. /* 153 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),
  30721. /* 154 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  30722. /* 155 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),
  30723. /* 156 */ "AggValue" OpHelp("r[P3]=value N=P2"),
  30724. /* 157 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  30725. /* 158 */ "Expire" OpHelp(""),
  30726. /* 159 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  30727. /* 160 */ "VBegin" OpHelp(""),
  30728. /* 161 */ "VCreate" OpHelp(""),
  30729. /* 162 */ "VDestroy" OpHelp(""),
  30730. /* 163 */ "VOpen" OpHelp(""),
  30731. /* 164 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  30732. /* 165 */ "VRename" OpHelp(""),
  30733. /* 166 */ "Pagecount" OpHelp(""),
  30734. /* 167 */ "MaxPgcnt" OpHelp(""),
  30735. /* 168 */ "Trace" OpHelp(""),
  30736. /* 169 */ "CursorHint" OpHelp(""),
  30737. /* 170 */ "Noop" OpHelp(""),
  30738. /* 171 */ "Explain" OpHelp(""),
  30739. /* 172 */ "Abortable" OpHelp(""),
  30740. };
  30741. return azName[i];
  30742. }
  30743. #endif
  30744. /************** End of opcodes.c *********************************************/
  30745. /************** Begin file os_unix.c *****************************************/
  30746. /*
  30747. ** 2004 May 22
  30748. **
  30749. ** The author disclaims copyright to this source code. In place of
  30750. ** a legal notice, here is a blessing:
  30751. **
  30752. ** May you do good and not evil.
  30753. ** May you find forgiveness for yourself and forgive others.
  30754. ** May you share freely, never taking more than you give.
  30755. **
  30756. ******************************************************************************
  30757. **
  30758. ** This file contains the VFS implementation for unix-like operating systems
  30759. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  30760. **
  30761. ** There are actually several different VFS implementations in this file.
  30762. ** The differences are in the way that file locking is done. The default
  30763. ** implementation uses Posix Advisory Locks. Alternative implementations
  30764. ** use flock(), dot-files, various proprietary locking schemas, or simply
  30765. ** skip locking all together.
  30766. **
  30767. ** This source file is organized into divisions where the logic for various
  30768. ** subfunctions is contained within the appropriate division. PLEASE
  30769. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  30770. ** in the correct division and should be clearly labeled.
  30771. **
  30772. ** The layout of divisions is as follows:
  30773. **
  30774. ** * General-purpose declarations and utility functions.
  30775. ** * Unique file ID logic used by VxWorks.
  30776. ** * Various locking primitive implementations (all except proxy locking):
  30777. ** + for Posix Advisory Locks
  30778. ** + for no-op locks
  30779. ** + for dot-file locks
  30780. ** + for flock() locking
  30781. ** + for named semaphore locks (VxWorks only)
  30782. ** + for AFP filesystem locks (MacOSX only)
  30783. ** * sqlite3_file methods not associated with locking.
  30784. ** * Definitions of sqlite3_io_methods objects for all locking
  30785. ** methods plus "finder" functions for each locking method.
  30786. ** * sqlite3_vfs method implementations.
  30787. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  30788. ** * Definitions of sqlite3_vfs objects for all locking methods
  30789. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  30790. */
  30791. /* #include "sqliteInt.h" */
  30792. #if SQLITE_OS_UNIX /* This file is used on unix only */
  30793. /*
  30794. ** There are various methods for file locking used for concurrency
  30795. ** control:
  30796. **
  30797. ** 1. POSIX locking (the default),
  30798. ** 2. No locking,
  30799. ** 3. Dot-file locking,
  30800. ** 4. flock() locking,
  30801. ** 5. AFP locking (OSX only),
  30802. ** 6. Named POSIX semaphores (VXWorks only),
  30803. ** 7. proxy locking. (OSX only)
  30804. **
  30805. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  30806. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  30807. ** selection of the appropriate locking style based on the filesystem
  30808. ** where the database is located.
  30809. */
  30810. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  30811. # if defined(__APPLE__)
  30812. # define SQLITE_ENABLE_LOCKING_STYLE 1
  30813. # else
  30814. # define SQLITE_ENABLE_LOCKING_STYLE 0
  30815. # endif
  30816. #endif
  30817. /* Use pread() and pwrite() if they are available */
  30818. #if defined(__APPLE__)
  30819. # define HAVE_PREAD 1
  30820. # define HAVE_PWRITE 1
  30821. #endif
  30822. #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
  30823. # undef USE_PREAD
  30824. # define USE_PREAD64 1
  30825. #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
  30826. # undef USE_PREAD64
  30827. # define USE_PREAD 1
  30828. #endif
  30829. /*
  30830. ** standard include files.
  30831. */
  30832. #include <sys/types.h>
  30833. #include <sys/stat.h>
  30834. #include <fcntl.h>
  30835. #include <sys/ioctl.h>
  30836. #include <unistd.h>
  30837. /* #include <time.h> */
  30838. #include <sys/time.h>
  30839. #include <errno.h>
  30840. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  30841. # include <sys/mman.h>
  30842. #endif
  30843. #if SQLITE_ENABLE_LOCKING_STYLE
  30844. /* # include <sys/ioctl.h> */
  30845. # include <sys/file.h>
  30846. # include <sys/param.h>
  30847. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  30848. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  30849. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  30850. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  30851. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  30852. # define HAVE_GETHOSTUUID 1
  30853. # else
  30854. # warning "gethostuuid() is disabled."
  30855. # endif
  30856. #endif
  30857. #if OS_VXWORKS
  30858. /* # include <sys/ioctl.h> */
  30859. # include <semaphore.h>
  30860. # include <limits.h>
  30861. #endif /* OS_VXWORKS */
  30862. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  30863. # include <sys/mount.h>
  30864. #endif
  30865. #ifdef HAVE_UTIME
  30866. # include <utime.h>
  30867. #endif
  30868. /*
  30869. ** Allowed values of unixFile.fsFlags
  30870. */
  30871. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  30872. /*
  30873. ** If we are to be thread-safe, include the pthreads header.
  30874. */
  30875. #if SQLITE_THREADSAFE
  30876. /* # include <pthread.h> */
  30877. #endif
  30878. /*
  30879. ** Default permissions when creating a new file
  30880. */
  30881. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  30882. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  30883. #endif
  30884. /*
  30885. ** Default permissions when creating auto proxy dir
  30886. */
  30887. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  30888. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  30889. #endif
  30890. /*
  30891. ** Maximum supported path-length.
  30892. */
  30893. #define MAX_PATHNAME 512
  30894. /*
  30895. ** Maximum supported symbolic links
  30896. */
  30897. #define SQLITE_MAX_SYMLINKS 100
  30898. /* Always cast the getpid() return type for compatibility with
  30899. ** kernel modules in VxWorks. */
  30900. #define osGetpid(X) (pid_t)getpid()
  30901. /*
  30902. ** Only set the lastErrno if the error code is a real error and not
  30903. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  30904. */
  30905. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  30906. /* Forward references */
  30907. typedef struct unixShm unixShm; /* Connection shared memory */
  30908. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  30909. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  30910. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  30911. /*
  30912. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  30913. ** cannot be closed immediately. In these cases, instances of the following
  30914. ** structure are used to store the file descriptor while waiting for an
  30915. ** opportunity to either close or reuse it.
  30916. */
  30917. struct UnixUnusedFd {
  30918. int fd; /* File descriptor to close */
  30919. int flags; /* Flags this file descriptor was opened with */
  30920. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  30921. };
  30922. /*
  30923. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  30924. ** VFS implementations.
  30925. */
  30926. typedef struct unixFile unixFile;
  30927. struct unixFile {
  30928. sqlite3_io_methods const *pMethod; /* Always the first entry */
  30929. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  30930. unixInodeInfo *pInode; /* Info about locks on this inode */
  30931. int h; /* The file descriptor */
  30932. unsigned char eFileLock; /* The type of lock held on this fd */
  30933. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  30934. int lastErrno; /* The unix errno from last I/O error */
  30935. void *lockingContext; /* Locking style specific state */
  30936. UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
  30937. const char *zPath; /* Name of the file */
  30938. unixShm *pShm; /* Shared memory segment information */
  30939. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  30940. #if SQLITE_MAX_MMAP_SIZE>0
  30941. int nFetchOut; /* Number of outstanding xFetch refs */
  30942. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  30943. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  30944. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  30945. void *pMapRegion; /* Memory mapped region */
  30946. #endif
  30947. int sectorSize; /* Device sector size */
  30948. int deviceCharacteristics; /* Precomputed device characteristics */
  30949. #if SQLITE_ENABLE_LOCKING_STYLE
  30950. int openFlags; /* The flags specified at open() */
  30951. #endif
  30952. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  30953. unsigned fsFlags; /* cached details from statfs() */
  30954. #endif
  30955. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  30956. unsigned iBusyTimeout; /* Wait this many millisec on locks */
  30957. #endif
  30958. #if OS_VXWORKS
  30959. struct vxworksFileId *pId; /* Unique file ID */
  30960. #endif
  30961. #ifdef SQLITE_DEBUG
  30962. /* The next group of variables are used to track whether or not the
  30963. ** transaction counter in bytes 24-27 of database files are updated
  30964. ** whenever any part of the database changes. An assertion fault will
  30965. ** occur if a file is updated without also updating the transaction
  30966. ** counter. This test is made to avoid new problems similar to the
  30967. ** one described by ticket #3584.
  30968. */
  30969. unsigned char transCntrChng; /* True if the transaction counter changed */
  30970. unsigned char dbUpdate; /* True if any part of database file changed */
  30971. unsigned char inNormalWrite; /* True if in a normal write operation */
  30972. #endif
  30973. #ifdef SQLITE_TEST
  30974. /* In test mode, increase the size of this structure a bit so that
  30975. ** it is larger than the struct CrashFile defined in test6.c.
  30976. */
  30977. char aPadding[32];
  30978. #endif
  30979. };
  30980. /* This variable holds the process id (pid) from when the xRandomness()
  30981. ** method was called. If xOpen() is called from a different process id,
  30982. ** indicating that a fork() has occurred, the PRNG will be reset.
  30983. */
  30984. static pid_t randomnessPid = 0;
  30985. /*
  30986. ** Allowed values for the unixFile.ctrlFlags bitmask:
  30987. */
  30988. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  30989. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  30990. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  30991. #ifndef SQLITE_DISABLE_DIRSYNC
  30992. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  30993. #else
  30994. # define UNIXFILE_DIRSYNC 0x00
  30995. #endif
  30996. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  30997. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  30998. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  30999. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  31000. /*
  31001. ** Include code that is common to all os_*.c files
  31002. */
  31003. /************** Include os_common.h in the middle of os_unix.c ***************/
  31004. /************** Begin file os_common.h ***************************************/
  31005. /*
  31006. ** 2004 May 22
  31007. **
  31008. ** The author disclaims copyright to this source code. In place of
  31009. ** a legal notice, here is a blessing:
  31010. **
  31011. ** May you do good and not evil.
  31012. ** May you find forgiveness for yourself and forgive others.
  31013. ** May you share freely, never taking more than you give.
  31014. **
  31015. ******************************************************************************
  31016. **
  31017. ** This file contains macros and a little bit of code that is common to
  31018. ** all of the platform-specific files (os_*.c) and is #included into those
  31019. ** files.
  31020. **
  31021. ** This file should be #included by the os_*.c files only. It is not a
  31022. ** general purpose header file.
  31023. */
  31024. #ifndef _OS_COMMON_H_
  31025. #define _OS_COMMON_H_
  31026. /*
  31027. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  31028. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  31029. ** switch. The following code should catch this problem at compile-time.
  31030. */
  31031. #ifdef MEMORY_DEBUG
  31032. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  31033. #endif
  31034. /*
  31035. ** Macros for performance tracing. Normally turned off. Only works
  31036. ** on i486 hardware.
  31037. */
  31038. #ifdef SQLITE_PERFORMANCE_TRACE
  31039. /*
  31040. ** hwtime.h contains inline assembler code for implementing
  31041. ** high-performance timing routines.
  31042. */
  31043. /************** Include hwtime.h in the middle of os_common.h ****************/
  31044. /************** Begin file hwtime.h ******************************************/
  31045. /*
  31046. ** 2008 May 27
  31047. **
  31048. ** The author disclaims copyright to this source code. In place of
  31049. ** a legal notice, here is a blessing:
  31050. **
  31051. ** May you do good and not evil.
  31052. ** May you find forgiveness for yourself and forgive others.
  31053. ** May you share freely, never taking more than you give.
  31054. **
  31055. ******************************************************************************
  31056. **
  31057. ** This file contains inline asm code for retrieving "high-performance"
  31058. ** counters for x86 class CPUs.
  31059. */
  31060. #ifndef SQLITE_HWTIME_H
  31061. #define SQLITE_HWTIME_H
  31062. /*
  31063. ** The following routine only works on pentium-class (or newer) processors.
  31064. ** It uses the RDTSC opcode to read the cycle count value out of the
  31065. ** processor and returns that value. This can be used for high-res
  31066. ** profiling.
  31067. */
  31068. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  31069. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  31070. #if defined(__GNUC__)
  31071. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31072. unsigned int lo, hi;
  31073. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  31074. return (sqlite_uint64)hi << 32 | lo;
  31075. }
  31076. #elif defined(_MSC_VER)
  31077. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  31078. __asm {
  31079. rdtsc
  31080. ret ; return value at EDX:EAX
  31081. }
  31082. }
  31083. #endif
  31084. #elif (defined(__GNUC__) && defined(__x86_64__))
  31085. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31086. unsigned long val;
  31087. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  31088. return val;
  31089. }
  31090. #elif (defined(__GNUC__) && defined(__ppc__))
  31091. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31092. unsigned long long retval;
  31093. unsigned long junk;
  31094. __asm__ __volatile__ ("\n\
  31095. 1: mftbu %1\n\
  31096. mftb %L0\n\
  31097. mftbu %0\n\
  31098. cmpw %0,%1\n\
  31099. bne 1b"
  31100. : "=r" (retval), "=r" (junk));
  31101. return retval;
  31102. }
  31103. #else
  31104. #error Need implementation of sqlite3Hwtime() for your platform.
  31105. /*
  31106. ** To compile without implementing sqlite3Hwtime() for your platform,
  31107. ** you can remove the above #error and use the following
  31108. ** stub function. You will lose timing support for many
  31109. ** of the debugging and testing utilities, but it should at
  31110. ** least compile and run.
  31111. */
  31112. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  31113. #endif
  31114. #endif /* !defined(SQLITE_HWTIME_H) */
  31115. /************** End of hwtime.h **********************************************/
  31116. /************** Continuing where we left off in os_common.h ******************/
  31117. static sqlite_uint64 g_start;
  31118. static sqlite_uint64 g_elapsed;
  31119. #define TIMER_START g_start=sqlite3Hwtime()
  31120. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  31121. #define TIMER_ELAPSED g_elapsed
  31122. #else
  31123. #define TIMER_START
  31124. #define TIMER_END
  31125. #define TIMER_ELAPSED ((sqlite_uint64)0)
  31126. #endif
  31127. /*
  31128. ** If we compile with the SQLITE_TEST macro set, then the following block
  31129. ** of code will give us the ability to simulate a disk I/O error. This
  31130. ** is used for testing the I/O recovery logic.
  31131. */
  31132. #if defined(SQLITE_TEST)
  31133. SQLITE_API extern int sqlite3_io_error_hit;
  31134. SQLITE_API extern int sqlite3_io_error_hardhit;
  31135. SQLITE_API extern int sqlite3_io_error_pending;
  31136. SQLITE_API extern int sqlite3_io_error_persist;
  31137. SQLITE_API extern int sqlite3_io_error_benign;
  31138. SQLITE_API extern int sqlite3_diskfull_pending;
  31139. SQLITE_API extern int sqlite3_diskfull;
  31140. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  31141. #define SimulateIOError(CODE) \
  31142. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  31143. || sqlite3_io_error_pending-- == 1 ) \
  31144. { local_ioerr(); CODE; }
  31145. static void local_ioerr(){
  31146. IOTRACE(("IOERR\n"));
  31147. sqlite3_io_error_hit++;
  31148. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  31149. }
  31150. #define SimulateDiskfullError(CODE) \
  31151. if( sqlite3_diskfull_pending ){ \
  31152. if( sqlite3_diskfull_pending == 1 ){ \
  31153. local_ioerr(); \
  31154. sqlite3_diskfull = 1; \
  31155. sqlite3_io_error_hit = 1; \
  31156. CODE; \
  31157. }else{ \
  31158. sqlite3_diskfull_pending--; \
  31159. } \
  31160. }
  31161. #else
  31162. #define SimulateIOErrorBenign(X)
  31163. #define SimulateIOError(A)
  31164. #define SimulateDiskfullError(A)
  31165. #endif /* defined(SQLITE_TEST) */
  31166. /*
  31167. ** When testing, keep a count of the number of open files.
  31168. */
  31169. #if defined(SQLITE_TEST)
  31170. SQLITE_API extern int sqlite3_open_file_count;
  31171. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  31172. #else
  31173. #define OpenCounter(X)
  31174. #endif /* defined(SQLITE_TEST) */
  31175. #endif /* !defined(_OS_COMMON_H_) */
  31176. /************** End of os_common.h *******************************************/
  31177. /************** Continuing where we left off in os_unix.c ********************/
  31178. /*
  31179. ** Define various macros that are missing from some systems.
  31180. */
  31181. #ifndef O_LARGEFILE
  31182. # define O_LARGEFILE 0
  31183. #endif
  31184. #ifdef SQLITE_DISABLE_LFS
  31185. # undef O_LARGEFILE
  31186. # define O_LARGEFILE 0
  31187. #endif
  31188. #ifndef O_NOFOLLOW
  31189. # define O_NOFOLLOW 0
  31190. #endif
  31191. #ifndef O_BINARY
  31192. # define O_BINARY 0
  31193. #endif
  31194. /*
  31195. ** The threadid macro resolves to the thread-id or to 0. Used for
  31196. ** testing and debugging only.
  31197. */
  31198. #if SQLITE_THREADSAFE
  31199. #define threadid pthread_self()
  31200. #else
  31201. #define threadid 0
  31202. #endif
  31203. /*
  31204. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  31205. */
  31206. #if !defined(HAVE_MREMAP)
  31207. # if defined(__linux__) && defined(_GNU_SOURCE)
  31208. # define HAVE_MREMAP 1
  31209. # else
  31210. # define HAVE_MREMAP 0
  31211. # endif
  31212. #endif
  31213. /*
  31214. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  31215. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  31216. */
  31217. #ifdef __ANDROID__
  31218. # define lseek lseek64
  31219. #endif
  31220. #ifdef __linux__
  31221. /*
  31222. ** Linux-specific IOCTL magic numbers used for controlling F2FS
  31223. */
  31224. #define F2FS_IOCTL_MAGIC 0xf5
  31225. #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
  31226. #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
  31227. #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
  31228. #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
  31229. #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
  31230. #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
  31231. #endif /* __linux__ */
  31232. /*
  31233. ** Different Unix systems declare open() in different ways. Same use
  31234. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  31235. ** The difference is important when using a pointer to the function.
  31236. **
  31237. ** The safest way to deal with the problem is to always use this wrapper
  31238. ** which always has the same well-defined interface.
  31239. */
  31240. static int posixOpen(const char *zFile, int flags, int mode){
  31241. return open(zFile, flags, mode);
  31242. }
  31243. /* Forward reference */
  31244. static int openDirectory(const char*, int*);
  31245. static int unixGetpagesize(void);
  31246. /*
  31247. ** Many system calls are accessed through pointer-to-functions so that
  31248. ** they may be overridden at runtime to facilitate fault injection during
  31249. ** testing and sandboxing. The following array holds the names and pointers
  31250. ** to all overrideable system calls.
  31251. */
  31252. static struct unix_syscall {
  31253. const char *zName; /* Name of the system call */
  31254. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  31255. sqlite3_syscall_ptr pDefault; /* Default value */
  31256. } aSyscall[] = {
  31257. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  31258. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  31259. { "close", (sqlite3_syscall_ptr)close, 0 },
  31260. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  31261. { "access", (sqlite3_syscall_ptr)access, 0 },
  31262. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  31263. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  31264. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  31265. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  31266. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  31267. /*
  31268. ** The DJGPP compiler environment looks mostly like Unix, but it
  31269. ** lacks the fcntl() system call. So redefine fcntl() to be something
  31270. ** that always succeeds. This means that locking does not occur under
  31271. ** DJGPP. But it is DOS - what did you expect?
  31272. */
  31273. #ifdef __DJGPP__
  31274. { "fstat", 0, 0 },
  31275. #define osFstat(a,b,c) 0
  31276. #else
  31277. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  31278. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  31279. #endif
  31280. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  31281. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  31282. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  31283. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  31284. { "read", (sqlite3_syscall_ptr)read, 0 },
  31285. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  31286. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  31287. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  31288. #else
  31289. { "pread", (sqlite3_syscall_ptr)0, 0 },
  31290. #endif
  31291. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  31292. #if defined(USE_PREAD64)
  31293. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  31294. #else
  31295. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  31296. #endif
  31297. #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
  31298. { "write", (sqlite3_syscall_ptr)write, 0 },
  31299. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  31300. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  31301. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  31302. #else
  31303. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  31304. #endif
  31305. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  31306. aSyscall[12].pCurrent)
  31307. #if defined(USE_PREAD64)
  31308. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  31309. #else
  31310. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  31311. #endif
  31312. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
  31313. aSyscall[13].pCurrent)
  31314. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  31315. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  31316. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  31317. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  31318. #else
  31319. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  31320. #endif
  31321. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  31322. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  31323. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  31324. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  31325. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  31326. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  31327. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  31328. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  31329. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  31330. #if defined(HAVE_FCHOWN)
  31331. { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
  31332. #else
  31333. { "fchown", (sqlite3_syscall_ptr)0, 0 },
  31334. #endif
  31335. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  31336. #if defined(HAVE_FCHOWN)
  31337. { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
  31338. #else
  31339. { "geteuid", (sqlite3_syscall_ptr)0, 0 },
  31340. #endif
  31341. #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
  31342. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  31343. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  31344. #else
  31345. { "mmap", (sqlite3_syscall_ptr)0, 0 },
  31346. #endif
  31347. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
  31348. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  31349. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  31350. #else
  31351. { "munmap", (sqlite3_syscall_ptr)0, 0 },
  31352. #endif
  31353. #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
  31354. #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  31355. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  31356. #else
  31357. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  31358. #endif
  31359. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
  31360. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  31361. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  31362. #else
  31363. { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
  31364. #endif
  31365. #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
  31366. #if defined(HAVE_READLINK)
  31367. { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
  31368. #else
  31369. { "readlink", (sqlite3_syscall_ptr)0, 0 },
  31370. #endif
  31371. #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
  31372. #if defined(HAVE_LSTAT)
  31373. { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
  31374. #else
  31375. { "lstat", (sqlite3_syscall_ptr)0, 0 },
  31376. #endif
  31377. #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
  31378. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  31379. # ifdef __ANDROID__
  31380. { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
  31381. # else
  31382. { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
  31383. # endif
  31384. #else
  31385. { "ioctl", (sqlite3_syscall_ptr)0, 0 },
  31386. #endif
  31387. #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
  31388. }; /* End of the overrideable system calls */
  31389. /*
  31390. ** On some systems, calls to fchown() will trigger a message in a security
  31391. ** log if they come from non-root processes. So avoid calling fchown() if
  31392. ** we are not running as root.
  31393. */
  31394. static int robustFchown(int fd, uid_t uid, gid_t gid){
  31395. #if defined(HAVE_FCHOWN)
  31396. return osGeteuid() ? 0 : osFchown(fd,uid,gid);
  31397. #else
  31398. return 0;
  31399. #endif
  31400. }
  31401. /*
  31402. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  31403. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  31404. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  31405. ** system call named zName.
  31406. */
  31407. static int unixSetSystemCall(
  31408. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  31409. const char *zName, /* Name of system call to override */
  31410. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  31411. ){
  31412. unsigned int i;
  31413. int rc = SQLITE_NOTFOUND;
  31414. UNUSED_PARAMETER(pNotUsed);
  31415. if( zName==0 ){
  31416. /* If no zName is given, restore all system calls to their default
  31417. ** settings and return NULL
  31418. */
  31419. rc = SQLITE_OK;
  31420. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31421. if( aSyscall[i].pDefault ){
  31422. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  31423. }
  31424. }
  31425. }else{
  31426. /* If zName is specified, operate on only the one system call
  31427. ** specified.
  31428. */
  31429. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31430. if( strcmp(zName, aSyscall[i].zName)==0 ){
  31431. if( aSyscall[i].pDefault==0 ){
  31432. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  31433. }
  31434. rc = SQLITE_OK;
  31435. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  31436. aSyscall[i].pCurrent = pNewFunc;
  31437. break;
  31438. }
  31439. }
  31440. }
  31441. return rc;
  31442. }
  31443. /*
  31444. ** Return the value of a system call. Return NULL if zName is not a
  31445. ** recognized system call name. NULL is also returned if the system call
  31446. ** is currently undefined.
  31447. */
  31448. static sqlite3_syscall_ptr unixGetSystemCall(
  31449. sqlite3_vfs *pNotUsed,
  31450. const char *zName
  31451. ){
  31452. unsigned int i;
  31453. UNUSED_PARAMETER(pNotUsed);
  31454. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31455. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  31456. }
  31457. return 0;
  31458. }
  31459. /*
  31460. ** Return the name of the first system call after zName. If zName==NULL
  31461. ** then return the name of the first system call. Return NULL if zName
  31462. ** is the last system call or if zName is not the name of a valid
  31463. ** system call.
  31464. */
  31465. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  31466. int i = -1;
  31467. UNUSED_PARAMETER(p);
  31468. if( zName ){
  31469. for(i=0; i<ArraySize(aSyscall)-1; i++){
  31470. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  31471. }
  31472. }
  31473. for(i++; i<ArraySize(aSyscall); i++){
  31474. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  31475. }
  31476. return 0;
  31477. }
  31478. /*
  31479. ** Do not accept any file descriptor less than this value, in order to avoid
  31480. ** opening database file using file descriptors that are commonly used for
  31481. ** standard input, output, and error.
  31482. */
  31483. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  31484. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  31485. #endif
  31486. /*
  31487. ** Invoke open(). Do so multiple times, until it either succeeds or
  31488. ** fails for some reason other than EINTR.
  31489. **
  31490. ** If the file creation mode "m" is 0 then set it to the default for
  31491. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  31492. ** 0644) as modified by the system umask. If m is not 0, then
  31493. ** make the file creation mode be exactly m ignoring the umask.
  31494. **
  31495. ** The m parameter will be non-zero only when creating -wal, -journal,
  31496. ** and -shm files. We want those files to have *exactly* the same
  31497. ** permissions as their original database, unadulterated by the umask.
  31498. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  31499. ** transaction crashes and leaves behind hot journals, then any
  31500. ** process that is able to write to the database will also be able to
  31501. ** recover the hot journals.
  31502. */
  31503. static int robust_open(const char *z, int f, mode_t m){
  31504. int fd;
  31505. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  31506. while(1){
  31507. #if defined(O_CLOEXEC)
  31508. fd = osOpen(z,f|O_CLOEXEC,m2);
  31509. #else
  31510. fd = osOpen(z,f,m2);
  31511. #endif
  31512. if( fd<0 ){
  31513. if( errno==EINTR ) continue;
  31514. break;
  31515. }
  31516. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  31517. osClose(fd);
  31518. sqlite3_log(SQLITE_WARNING,
  31519. "attempt to open \"%s\" as file descriptor %d", z, fd);
  31520. fd = -1;
  31521. if( osOpen("/dev/null", f, m)<0 ) break;
  31522. }
  31523. if( fd>=0 ){
  31524. if( m!=0 ){
  31525. struct stat statbuf;
  31526. if( osFstat(fd, &statbuf)==0
  31527. && statbuf.st_size==0
  31528. && (statbuf.st_mode&0777)!=m
  31529. ){
  31530. osFchmod(fd, m);
  31531. }
  31532. }
  31533. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  31534. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  31535. #endif
  31536. }
  31537. return fd;
  31538. }
  31539. /*
  31540. ** Helper functions to obtain and relinquish the global mutex. The
  31541. ** global mutex is used to protect the unixInodeInfo and
  31542. ** vxworksFileId objects used by this file, all of which may be
  31543. ** shared by multiple threads.
  31544. **
  31545. ** Function unixMutexHeld() is used to assert() that the global mutex
  31546. ** is held when required. This function is only used as part of assert()
  31547. ** statements. e.g.
  31548. **
  31549. ** unixEnterMutex()
  31550. ** assert( unixMutexHeld() );
  31551. ** unixEnterLeave()
  31552. **
  31553. ** To prevent deadlock, the global unixBigLock must must be acquired
  31554. ** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
  31555. ** OK to get the pLockMutex without holding unixBigLock first, but if
  31556. ** that happens, the unixBigLock mutex must not be acquired until after
  31557. ** pLockMutex is released.
  31558. **
  31559. ** OK: enter(unixBigLock), enter(pLockInfo)
  31560. ** OK: enter(unixBigLock)
  31561. ** OK: enter(pLockInfo)
  31562. ** ERROR: enter(pLockInfo), enter(unixBigLock)
  31563. */
  31564. static sqlite3_mutex *unixBigLock = 0;
  31565. static void unixEnterMutex(void){
  31566. assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
  31567. sqlite3_mutex_enter(unixBigLock);
  31568. }
  31569. static void unixLeaveMutex(void){
  31570. assert( sqlite3_mutex_held(unixBigLock) );
  31571. sqlite3_mutex_leave(unixBigLock);
  31572. }
  31573. #ifdef SQLITE_DEBUG
  31574. static int unixMutexHeld(void) {
  31575. return sqlite3_mutex_held(unixBigLock);
  31576. }
  31577. #endif
  31578. #ifdef SQLITE_HAVE_OS_TRACE
  31579. /*
  31580. ** Helper function for printing out trace information from debugging
  31581. ** binaries. This returns the string representation of the supplied
  31582. ** integer lock-type.
  31583. */
  31584. static const char *azFileLock(int eFileLock){
  31585. switch( eFileLock ){
  31586. case NO_LOCK: return "NONE";
  31587. case SHARED_LOCK: return "SHARED";
  31588. case RESERVED_LOCK: return "RESERVED";
  31589. case PENDING_LOCK: return "PENDING";
  31590. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  31591. }
  31592. return "ERROR";
  31593. }
  31594. #endif
  31595. #ifdef SQLITE_LOCK_TRACE
  31596. /*
  31597. ** Print out information about all locking operations.
  31598. **
  31599. ** This routine is used for troubleshooting locks on multithreaded
  31600. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  31601. ** command-line option on the compiler. This code is normally
  31602. ** turned off.
  31603. */
  31604. static int lockTrace(int fd, int op, struct flock *p){
  31605. char *zOpName, *zType;
  31606. int s;
  31607. int savedErrno;
  31608. if( op==F_GETLK ){
  31609. zOpName = "GETLK";
  31610. }else if( op==F_SETLK ){
  31611. zOpName = "SETLK";
  31612. }else{
  31613. s = osFcntl(fd, op, p);
  31614. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  31615. return s;
  31616. }
  31617. if( p->l_type==F_RDLCK ){
  31618. zType = "RDLCK";
  31619. }else if( p->l_type==F_WRLCK ){
  31620. zType = "WRLCK";
  31621. }else if( p->l_type==F_UNLCK ){
  31622. zType = "UNLCK";
  31623. }else{
  31624. assert( 0 );
  31625. }
  31626. assert( p->l_whence==SEEK_SET );
  31627. s = osFcntl(fd, op, p);
  31628. savedErrno = errno;
  31629. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  31630. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  31631. (int)p->l_pid, s);
  31632. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  31633. struct flock l2;
  31634. l2 = *p;
  31635. osFcntl(fd, F_GETLK, &l2);
  31636. if( l2.l_type==F_RDLCK ){
  31637. zType = "RDLCK";
  31638. }else if( l2.l_type==F_WRLCK ){
  31639. zType = "WRLCK";
  31640. }else if( l2.l_type==F_UNLCK ){
  31641. zType = "UNLCK";
  31642. }else{
  31643. assert( 0 );
  31644. }
  31645. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  31646. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  31647. }
  31648. errno = savedErrno;
  31649. return s;
  31650. }
  31651. #undef osFcntl
  31652. #define osFcntl lockTrace
  31653. #endif /* SQLITE_LOCK_TRACE */
  31654. /*
  31655. ** Retry ftruncate() calls that fail due to EINTR
  31656. **
  31657. ** All calls to ftruncate() within this file should be made through
  31658. ** this wrapper. On the Android platform, bypassing the logic below
  31659. ** could lead to a corrupt database.
  31660. */
  31661. static int robust_ftruncate(int h, sqlite3_int64 sz){
  31662. int rc;
  31663. #ifdef __ANDROID__
  31664. /* On Android, ftruncate() always uses 32-bit offsets, even if
  31665. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  31666. ** truncate a file to any size larger than 2GiB. Silently ignore any
  31667. ** such attempts. */
  31668. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  31669. rc = SQLITE_OK;
  31670. }else
  31671. #endif
  31672. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  31673. return rc;
  31674. }
  31675. /*
  31676. ** This routine translates a standard POSIX errno code into something
  31677. ** useful to the clients of the sqlite3 functions. Specifically, it is
  31678. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  31679. ** and a variety of "please close the file descriptor NOW" errors into
  31680. ** SQLITE_IOERR
  31681. **
  31682. ** Errors during initialization of locks, or file system support for locks,
  31683. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  31684. */
  31685. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  31686. assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  31687. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  31688. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  31689. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
  31690. switch (posixError) {
  31691. case EACCES:
  31692. case EAGAIN:
  31693. case ETIMEDOUT:
  31694. case EBUSY:
  31695. case EINTR:
  31696. case ENOLCK:
  31697. /* random NFS retry error, unless during file system support
  31698. * introspection, in which it actually means what it says */
  31699. return SQLITE_BUSY;
  31700. case EPERM:
  31701. return SQLITE_PERM;
  31702. default:
  31703. return sqliteIOErr;
  31704. }
  31705. }
  31706. /******************************************************************************
  31707. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  31708. **
  31709. ** On most versions of unix, we can get a unique ID for a file by concatenating
  31710. ** the device number and the inode number. But this does not work on VxWorks.
  31711. ** On VxWorks, a unique file id must be based on the canonical filename.
  31712. **
  31713. ** A pointer to an instance of the following structure can be used as a
  31714. ** unique file ID in VxWorks. Each instance of this structure contains
  31715. ** a copy of the canonical filename. There is also a reference count.
  31716. ** The structure is reclaimed when the number of pointers to it drops to
  31717. ** zero.
  31718. **
  31719. ** There are never very many files open at one time and lookups are not
  31720. ** a performance-critical path, so it is sufficient to put these
  31721. ** structures on a linked list.
  31722. */
  31723. struct vxworksFileId {
  31724. struct vxworksFileId *pNext; /* Next in a list of them all */
  31725. int nRef; /* Number of references to this one */
  31726. int nName; /* Length of the zCanonicalName[] string */
  31727. char *zCanonicalName; /* Canonical filename */
  31728. };
  31729. #if OS_VXWORKS
  31730. /*
  31731. ** All unique filenames are held on a linked list headed by this
  31732. ** variable:
  31733. */
  31734. static struct vxworksFileId *vxworksFileList = 0;
  31735. /*
  31736. ** Simplify a filename into its canonical form
  31737. ** by making the following changes:
  31738. **
  31739. ** * removing any trailing and duplicate /
  31740. ** * convert /./ into just /
  31741. ** * convert /A/../ where A is any simple name into just /
  31742. **
  31743. ** Changes are made in-place. Return the new name length.
  31744. **
  31745. ** The original filename is in z[0..n-1]. Return the number of
  31746. ** characters in the simplified name.
  31747. */
  31748. static int vxworksSimplifyName(char *z, int n){
  31749. int i, j;
  31750. while( n>1 && z[n-1]=='/' ){ n--; }
  31751. for(i=j=0; i<n; i++){
  31752. if( z[i]=='/' ){
  31753. if( z[i+1]=='/' ) continue;
  31754. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  31755. i += 1;
  31756. continue;
  31757. }
  31758. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  31759. while( j>0 && z[j-1]!='/' ){ j--; }
  31760. if( j>0 ){ j--; }
  31761. i += 2;
  31762. continue;
  31763. }
  31764. }
  31765. z[j++] = z[i];
  31766. }
  31767. z[j] = 0;
  31768. return j;
  31769. }
  31770. /*
  31771. ** Find a unique file ID for the given absolute pathname. Return
  31772. ** a pointer to the vxworksFileId object. This pointer is the unique
  31773. ** file ID.
  31774. **
  31775. ** The nRef field of the vxworksFileId object is incremented before
  31776. ** the object is returned. A new vxworksFileId object is created
  31777. ** and added to the global list if necessary.
  31778. **
  31779. ** If a memory allocation error occurs, return NULL.
  31780. */
  31781. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  31782. struct vxworksFileId *pNew; /* search key and new file ID */
  31783. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  31784. int n; /* Length of zAbsoluteName string */
  31785. assert( zAbsoluteName[0]=='/' );
  31786. n = (int)strlen(zAbsoluteName);
  31787. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  31788. if( pNew==0 ) return 0;
  31789. pNew->zCanonicalName = (char*)&pNew[1];
  31790. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  31791. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  31792. /* Search for an existing entry that matching the canonical name.
  31793. ** If found, increment the reference count and return a pointer to
  31794. ** the existing file ID.
  31795. */
  31796. unixEnterMutex();
  31797. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  31798. if( pCandidate->nName==n
  31799. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  31800. ){
  31801. sqlite3_free(pNew);
  31802. pCandidate->nRef++;
  31803. unixLeaveMutex();
  31804. return pCandidate;
  31805. }
  31806. }
  31807. /* No match was found. We will make a new file ID */
  31808. pNew->nRef = 1;
  31809. pNew->nName = n;
  31810. pNew->pNext = vxworksFileList;
  31811. vxworksFileList = pNew;
  31812. unixLeaveMutex();
  31813. return pNew;
  31814. }
  31815. /*
  31816. ** Decrement the reference count on a vxworksFileId object. Free
  31817. ** the object when the reference count reaches zero.
  31818. */
  31819. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  31820. unixEnterMutex();
  31821. assert( pId->nRef>0 );
  31822. pId->nRef--;
  31823. if( pId->nRef==0 ){
  31824. struct vxworksFileId **pp;
  31825. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  31826. assert( *pp==pId );
  31827. *pp = pId->pNext;
  31828. sqlite3_free(pId);
  31829. }
  31830. unixLeaveMutex();
  31831. }
  31832. #endif /* OS_VXWORKS */
  31833. /*************** End of Unique File ID Utility Used By VxWorks ****************
  31834. ******************************************************************************/
  31835. /******************************************************************************
  31836. *************************** Posix Advisory Locking ****************************
  31837. **
  31838. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  31839. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  31840. ** sets or clears a lock, that operation overrides any prior locks set
  31841. ** by the same process. It does not explicitly say so, but this implies
  31842. ** that it overrides locks set by the same process using a different
  31843. ** file descriptor. Consider this test case:
  31844. **
  31845. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  31846. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  31847. **
  31848. ** Suppose ./file1 and ./file2 are really the same file (because
  31849. ** one is a hard or symbolic link to the other) then if you set
  31850. ** an exclusive lock on fd1, then try to get an exclusive lock
  31851. ** on fd2, it works. I would have expected the second lock to
  31852. ** fail since there was already a lock on the file due to fd1.
  31853. ** But not so. Since both locks came from the same process, the
  31854. ** second overrides the first, even though they were on different
  31855. ** file descriptors opened on different file names.
  31856. **
  31857. ** This means that we cannot use POSIX locks to synchronize file access
  31858. ** among competing threads of the same process. POSIX locks will work fine
  31859. ** to synchronize access for threads in separate processes, but not
  31860. ** threads within the same process.
  31861. **
  31862. ** To work around the problem, SQLite has to manage file locks internally
  31863. ** on its own. Whenever a new database is opened, we have to find the
  31864. ** specific inode of the database file (the inode is determined by the
  31865. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  31866. ** and check for locks already existing on that inode. When locks are
  31867. ** created or removed, we have to look at our own internal record of the
  31868. ** locks to see if another thread has previously set a lock on that same
  31869. ** inode.
  31870. **
  31871. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  31872. ** For VxWorks, we have to use the alternative unique ID system based on
  31873. ** canonical filename and implemented in the previous division.)
  31874. **
  31875. ** The sqlite3_file structure for POSIX is no longer just an integer file
  31876. ** descriptor. It is now a structure that holds the integer file
  31877. ** descriptor and a pointer to a structure that describes the internal
  31878. ** locks on the corresponding inode. There is one locking structure
  31879. ** per inode, so if the same inode is opened twice, both unixFile structures
  31880. ** point to the same locking structure. The locking structure keeps
  31881. ** a reference count (so we will know when to delete it) and a "cnt"
  31882. ** field that tells us its internal lock status. cnt==0 means the
  31883. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  31884. ** cnt>0 means there are cnt shared locks on the file.
  31885. **
  31886. ** Any attempt to lock or unlock a file first checks the locking
  31887. ** structure. The fcntl() system call is only invoked to set a
  31888. ** POSIX lock if the internal lock structure transitions between
  31889. ** a locked and an unlocked state.
  31890. **
  31891. ** But wait: there are yet more problems with POSIX advisory locks.
  31892. **
  31893. ** If you close a file descriptor that points to a file that has locks,
  31894. ** all locks on that file that are owned by the current process are
  31895. ** released. To work around this problem, each unixInodeInfo object
  31896. ** maintains a count of the number of pending locks on tha inode.
  31897. ** When an attempt is made to close an unixFile, if there are
  31898. ** other unixFile open on the same inode that are holding locks, the call
  31899. ** to close() the file descriptor is deferred until all of the locks clear.
  31900. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  31901. ** be closed and that list is walked (and cleared) when the last lock
  31902. ** clears.
  31903. **
  31904. ** Yet another problem: LinuxThreads do not play well with posix locks.
  31905. **
  31906. ** Many older versions of linux use the LinuxThreads library which is
  31907. ** not posix compliant. Under LinuxThreads, a lock created by thread
  31908. ** A cannot be modified or overridden by a different thread B.
  31909. ** Only thread A can modify the lock. Locking behavior is correct
  31910. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  31911. ** on linux - with NPTL a lock created by thread A can override locks
  31912. ** in thread B. But there is no way to know at compile-time which
  31913. ** threading library is being used. So there is no way to know at
  31914. ** compile-time whether or not thread A can override locks on thread B.
  31915. ** One has to do a run-time check to discover the behavior of the
  31916. ** current process.
  31917. **
  31918. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  31919. ** was dropped beginning with version 3.7.0. SQLite will still work with
  31920. ** LinuxThreads provided that (1) there is no more than one connection
  31921. ** per database file in the same process and (2) database connections
  31922. ** do not move across threads.
  31923. */
  31924. /*
  31925. ** An instance of the following structure serves as the key used
  31926. ** to locate a particular unixInodeInfo object.
  31927. */
  31928. struct unixFileId {
  31929. dev_t dev; /* Device number */
  31930. #if OS_VXWORKS
  31931. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  31932. #else
  31933. /* We are told that some versions of Android contain a bug that
  31934. ** sizes ino_t at only 32-bits instead of 64-bits. (See
  31935. ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
  31936. ** To work around this, always allocate 64-bits for the inode number.
  31937. ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
  31938. ** but that should not be a big deal. */
  31939. /* WAS: ino_t ino; */
  31940. u64 ino; /* Inode number */
  31941. #endif
  31942. };
  31943. /*
  31944. ** An instance of the following structure is allocated for each open
  31945. ** inode.
  31946. **
  31947. ** A single inode can have multiple file descriptors, so each unixFile
  31948. ** structure contains a pointer to an instance of this object and this
  31949. ** object keeps a count of the number of unixFile pointing to it.
  31950. **
  31951. ** Mutex rules:
  31952. **
  31953. ** (1) Only the pLockMutex mutex must be held in order to read or write
  31954. ** any of the locking fields:
  31955. ** nShared, nLock, eFileLock, bProcessLock, pUnused
  31956. **
  31957. ** (2) When nRef>0, then the following fields are unchanging and can
  31958. ** be read (but not written) without holding any mutex:
  31959. ** fileId, pLockMutex
  31960. **
  31961. ** (3) With the exceptions above, all the fields may only be read
  31962. ** or written while holding the global unixBigLock mutex.
  31963. **
  31964. ** Deadlock prevention: The global unixBigLock mutex may not
  31965. ** be acquired while holding the pLockMutex mutex. If both unixBigLock
  31966. ** and pLockMutex are needed, then unixBigLock must be acquired first.
  31967. */
  31968. struct unixInodeInfo {
  31969. struct unixFileId fileId; /* The lookup key */
  31970. sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
  31971. int nShared; /* Number of SHARED locks held */
  31972. int nLock; /* Number of outstanding file locks */
  31973. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  31974. unsigned char bProcessLock; /* An exclusive process lock is held */
  31975. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  31976. int nRef; /* Number of pointers to this structure */
  31977. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  31978. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  31979. unixInodeInfo *pPrev; /* .... doubly linked */
  31980. #if SQLITE_ENABLE_LOCKING_STYLE
  31981. unsigned long long sharedByte; /* for AFP simulated shared lock */
  31982. #endif
  31983. #if OS_VXWORKS
  31984. sem_t *pSem; /* Named POSIX semaphore */
  31985. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  31986. #endif
  31987. };
  31988. /*
  31989. ** A lists of all unixInodeInfo objects.
  31990. **
  31991. ** Must hold unixBigLock in order to read or write this variable.
  31992. */
  31993. static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
  31994. #ifdef SQLITE_DEBUG
  31995. /*
  31996. ** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
  31997. ** This routine is used only within assert() to help verify correct mutex
  31998. ** usage.
  31999. */
  32000. int unixFileMutexHeld(unixFile *pFile){
  32001. assert( pFile->pInode );
  32002. return sqlite3_mutex_held(pFile->pInode->pLockMutex);
  32003. }
  32004. int unixFileMutexNotheld(unixFile *pFile){
  32005. assert( pFile->pInode );
  32006. return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
  32007. }
  32008. #endif
  32009. /*
  32010. **
  32011. ** This function - unixLogErrorAtLine(), is only ever called via the macro
  32012. ** unixLogError().
  32013. **
  32014. ** It is invoked after an error occurs in an OS function and errno has been
  32015. ** set. It logs a message using sqlite3_log() containing the current value of
  32016. ** errno and, if possible, the human-readable equivalent from strerror() or
  32017. ** strerror_r().
  32018. **
  32019. ** The first argument passed to the macro should be the error code that
  32020. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  32021. ** The two subsequent arguments should be the name of the OS function that
  32022. ** failed (e.g. "unlink", "open") and the associated file-system path,
  32023. ** if any.
  32024. */
  32025. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  32026. static int unixLogErrorAtLine(
  32027. int errcode, /* SQLite error code */
  32028. const char *zFunc, /* Name of OS function that failed */
  32029. const char *zPath, /* File path associated with error */
  32030. int iLine /* Source line number where error occurred */
  32031. ){
  32032. char *zErr; /* Message from strerror() or equivalent */
  32033. int iErrno = errno; /* Saved syscall error number */
  32034. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  32035. ** the strerror() function to obtain the human-readable error message
  32036. ** equivalent to errno. Otherwise, use strerror_r().
  32037. */
  32038. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  32039. char aErr[80];
  32040. memset(aErr, 0, sizeof(aErr));
  32041. zErr = aErr;
  32042. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  32043. ** assume that the system provides the GNU version of strerror_r() that
  32044. ** returns a pointer to a buffer containing the error message. That pointer
  32045. ** may point to aErr[], or it may point to some static storage somewhere.
  32046. ** Otherwise, assume that the system provides the POSIX version of
  32047. ** strerror_r(), which always writes an error message into aErr[].
  32048. **
  32049. ** If the code incorrectly assumes that it is the POSIX version that is
  32050. ** available, the error message will often be an empty string. Not a
  32051. ** huge problem. Incorrectly concluding that the GNU version is available
  32052. ** could lead to a segfault though.
  32053. */
  32054. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  32055. zErr =
  32056. # endif
  32057. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  32058. #elif SQLITE_THREADSAFE
  32059. /* This is a threadsafe build, but strerror_r() is not available. */
  32060. zErr = "";
  32061. #else
  32062. /* Non-threadsafe build, use strerror(). */
  32063. zErr = strerror(iErrno);
  32064. #endif
  32065. if( zPath==0 ) zPath = "";
  32066. sqlite3_log(errcode,
  32067. "os_unix.c:%d: (%d) %s(%s) - %s",
  32068. iLine, iErrno, zFunc, zPath, zErr
  32069. );
  32070. return errcode;
  32071. }
  32072. /*
  32073. ** Close a file descriptor.
  32074. **
  32075. ** We assume that close() almost always works, since it is only in a
  32076. ** very sick application or on a very sick platform that it might fail.
  32077. ** If it does fail, simply leak the file descriptor, but do log the
  32078. ** error.
  32079. **
  32080. ** Note that it is not safe to retry close() after EINTR since the
  32081. ** file descriptor might have already been reused by another thread.
  32082. ** So we don't even try to recover from an EINTR. Just log the error
  32083. ** and move on.
  32084. */
  32085. static void robust_close(unixFile *pFile, int h, int lineno){
  32086. if( osClose(h) ){
  32087. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  32088. pFile ? pFile->zPath : 0, lineno);
  32089. }
  32090. }
  32091. /*
  32092. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  32093. ** a convenient place to set a breakpoint.
  32094. */
  32095. static void storeLastErrno(unixFile *pFile, int error){
  32096. pFile->lastErrno = error;
  32097. }
  32098. /*
  32099. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  32100. */
  32101. static void closePendingFds(unixFile *pFile){
  32102. unixInodeInfo *pInode = pFile->pInode;
  32103. UnixUnusedFd *p;
  32104. UnixUnusedFd *pNext;
  32105. assert( unixFileMutexHeld(pFile) );
  32106. for(p=pInode->pUnused; p; p=pNext){
  32107. pNext = p->pNext;
  32108. robust_close(pFile, p->fd, __LINE__);
  32109. sqlite3_free(p);
  32110. }
  32111. pInode->pUnused = 0;
  32112. }
  32113. /*
  32114. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  32115. **
  32116. ** The global mutex must be held when this routine is called, but the mutex
  32117. ** on the inode being deleted must NOT be held.
  32118. */
  32119. static void releaseInodeInfo(unixFile *pFile){
  32120. unixInodeInfo *pInode = pFile->pInode;
  32121. assert( unixMutexHeld() );
  32122. assert( unixFileMutexNotheld(pFile) );
  32123. if( ALWAYS(pInode) ){
  32124. pInode->nRef--;
  32125. if( pInode->nRef==0 ){
  32126. assert( pInode->pShmNode==0 );
  32127. sqlite3_mutex_enter(pInode->pLockMutex);
  32128. closePendingFds(pFile);
  32129. sqlite3_mutex_leave(pInode->pLockMutex);
  32130. if( pInode->pPrev ){
  32131. assert( pInode->pPrev->pNext==pInode );
  32132. pInode->pPrev->pNext = pInode->pNext;
  32133. }else{
  32134. assert( inodeList==pInode );
  32135. inodeList = pInode->pNext;
  32136. }
  32137. if( pInode->pNext ){
  32138. assert( pInode->pNext->pPrev==pInode );
  32139. pInode->pNext->pPrev = pInode->pPrev;
  32140. }
  32141. sqlite3_mutex_free(pInode->pLockMutex);
  32142. sqlite3_free(pInode);
  32143. }
  32144. }
  32145. }
  32146. /*
  32147. ** Given a file descriptor, locate the unixInodeInfo object that
  32148. ** describes that file descriptor. Create a new one if necessary. The
  32149. ** return value might be uninitialized if an error occurs.
  32150. **
  32151. ** The global mutex must held when calling this routine.
  32152. **
  32153. ** Return an appropriate error code.
  32154. */
  32155. static int findInodeInfo(
  32156. unixFile *pFile, /* Unix file with file desc used in the key */
  32157. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  32158. ){
  32159. int rc; /* System call return code */
  32160. int fd; /* The file descriptor for pFile */
  32161. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  32162. struct stat statbuf; /* Low-level file information */
  32163. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  32164. assert( unixMutexHeld() );
  32165. /* Get low-level information about the file that we can used to
  32166. ** create a unique name for the file.
  32167. */
  32168. fd = pFile->h;
  32169. rc = osFstat(fd, &statbuf);
  32170. if( rc!=0 ){
  32171. storeLastErrno(pFile, errno);
  32172. #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
  32173. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  32174. #endif
  32175. return SQLITE_IOERR;
  32176. }
  32177. #ifdef __APPLE__
  32178. /* On OS X on an msdos filesystem, the inode number is reported
  32179. ** incorrectly for zero-size files. See ticket #3260. To work
  32180. ** around this problem (we consider it a bug in OS X, not SQLite)
  32181. ** we always increase the file size to 1 by writing a single byte
  32182. ** prior to accessing the inode number. The one byte written is
  32183. ** an ASCII 'S' character which also happens to be the first byte
  32184. ** in the header of every SQLite database. In this way, if there
  32185. ** is a race condition such that another thread has already populated
  32186. ** the first page of the database, no damage is done.
  32187. */
  32188. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  32189. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  32190. if( rc!=1 ){
  32191. storeLastErrno(pFile, errno);
  32192. return SQLITE_IOERR;
  32193. }
  32194. rc = osFstat(fd, &statbuf);
  32195. if( rc!=0 ){
  32196. storeLastErrno(pFile, errno);
  32197. return SQLITE_IOERR;
  32198. }
  32199. }
  32200. #endif
  32201. memset(&fileId, 0, sizeof(fileId));
  32202. fileId.dev = statbuf.st_dev;
  32203. #if OS_VXWORKS
  32204. fileId.pId = pFile->pId;
  32205. #else
  32206. fileId.ino = (u64)statbuf.st_ino;
  32207. #endif
  32208. assert( unixMutexHeld() );
  32209. pInode = inodeList;
  32210. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  32211. pInode = pInode->pNext;
  32212. }
  32213. if( pInode==0 ){
  32214. pInode = sqlite3_malloc64( sizeof(*pInode) );
  32215. if( pInode==0 ){
  32216. return SQLITE_NOMEM_BKPT;
  32217. }
  32218. memset(pInode, 0, sizeof(*pInode));
  32219. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  32220. if( sqlite3GlobalConfig.bCoreMutex ){
  32221. pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  32222. if( pInode->pLockMutex==0 ){
  32223. sqlite3_free(pInode);
  32224. return SQLITE_NOMEM_BKPT;
  32225. }
  32226. }
  32227. pInode->nRef = 1;
  32228. assert( unixMutexHeld() );
  32229. pInode->pNext = inodeList;
  32230. pInode->pPrev = 0;
  32231. if( inodeList ) inodeList->pPrev = pInode;
  32232. inodeList = pInode;
  32233. }else{
  32234. pInode->nRef++;
  32235. }
  32236. *ppInode = pInode;
  32237. return SQLITE_OK;
  32238. }
  32239. /*
  32240. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  32241. */
  32242. static int fileHasMoved(unixFile *pFile){
  32243. #if OS_VXWORKS
  32244. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  32245. #else
  32246. struct stat buf;
  32247. return pFile->pInode!=0 &&
  32248. (osStat(pFile->zPath, &buf)!=0
  32249. || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
  32250. #endif
  32251. }
  32252. /*
  32253. ** Check a unixFile that is a database. Verify the following:
  32254. **
  32255. ** (1) There is exactly one hard link on the file
  32256. ** (2) The file is not a symbolic link
  32257. ** (3) The file has not been renamed or unlinked
  32258. **
  32259. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  32260. */
  32261. static void verifyDbFile(unixFile *pFile){
  32262. struct stat buf;
  32263. int rc;
  32264. /* These verifications occurs for the main database only */
  32265. if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
  32266. rc = osFstat(pFile->h, &buf);
  32267. if( rc!=0 ){
  32268. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  32269. return;
  32270. }
  32271. if( buf.st_nlink==0 ){
  32272. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  32273. return;
  32274. }
  32275. if( buf.st_nlink>1 ){
  32276. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  32277. return;
  32278. }
  32279. if( fileHasMoved(pFile) ){
  32280. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  32281. return;
  32282. }
  32283. }
  32284. /*
  32285. ** This routine checks if there is a RESERVED lock held on the specified
  32286. ** file by this or any other process. If such a lock is held, set *pResOut
  32287. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32288. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32289. */
  32290. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  32291. int rc = SQLITE_OK;
  32292. int reserved = 0;
  32293. unixFile *pFile = (unixFile*)id;
  32294. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32295. assert( pFile );
  32296. assert( pFile->eFileLock<=SHARED_LOCK );
  32297. sqlite3_mutex_enter(pFile->pInode->pLockMutex);
  32298. /* Check if a thread in this process holds such a lock */
  32299. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  32300. reserved = 1;
  32301. }
  32302. /* Otherwise see if some other process holds it.
  32303. */
  32304. #ifndef __DJGPP__
  32305. if( !reserved && !pFile->pInode->bProcessLock ){
  32306. struct flock lock;
  32307. lock.l_whence = SEEK_SET;
  32308. lock.l_start = RESERVED_BYTE;
  32309. lock.l_len = 1;
  32310. lock.l_type = F_WRLCK;
  32311. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  32312. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  32313. storeLastErrno(pFile, errno);
  32314. } else if( lock.l_type!=F_UNLCK ){
  32315. reserved = 1;
  32316. }
  32317. }
  32318. #endif
  32319. sqlite3_mutex_leave(pFile->pInode->pLockMutex);
  32320. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  32321. *pResOut = reserved;
  32322. return rc;
  32323. }
  32324. /*
  32325. ** Set a posix-advisory-lock.
  32326. **
  32327. ** There are two versions of this routine. If compiled with
  32328. ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
  32329. ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
  32330. ** value is set, then it is the number of milliseconds to wait before
  32331. ** failing the lock. The iBusyTimeout value is always reset back to
  32332. ** zero on each call.
  32333. **
  32334. ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
  32335. ** attempt to set the lock.
  32336. */
  32337. #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
  32338. # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
  32339. #else
  32340. static int osSetPosixAdvisoryLock(
  32341. int h, /* The file descriptor on which to take the lock */
  32342. struct flock *pLock, /* The description of the lock */
  32343. unixFile *pFile /* Structure holding timeout value */
  32344. ){
  32345. int rc = osFcntl(h,F_SETLK,pLock);
  32346. while( rc<0 && pFile->iBusyTimeout>0 ){
  32347. /* On systems that support some kind of blocking file lock with a timeout,
  32348. ** make appropriate changes here to invoke that blocking file lock. On
  32349. ** generic posix, however, there is no such API. So we simply try the
  32350. ** lock once every millisecond until either the timeout expires, or until
  32351. ** the lock is obtained. */
  32352. usleep(1000);
  32353. rc = osFcntl(h,F_SETLK,pLock);
  32354. pFile->iBusyTimeout--;
  32355. }
  32356. return rc;
  32357. }
  32358. #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
  32359. /*
  32360. ** Attempt to set a system-lock on the file pFile. The lock is
  32361. ** described by pLock.
  32362. **
  32363. ** If the pFile was opened read/write from unix-excl, then the only lock
  32364. ** ever obtained is an exclusive lock, and it is obtained exactly once
  32365. ** the first time any lock is attempted. All subsequent system locking
  32366. ** operations become no-ops. Locking operations still happen internally,
  32367. ** in order to coordinate access between separate database connections
  32368. ** within this process, but all of that is handled in memory and the
  32369. ** operating system does not participate.
  32370. **
  32371. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  32372. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  32373. ** and is read-only.
  32374. **
  32375. ** Zero is returned if the call completes successfully, or -1 if a call
  32376. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  32377. */
  32378. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  32379. int rc;
  32380. unixInodeInfo *pInode = pFile->pInode;
  32381. assert( pInode!=0 );
  32382. assert( sqlite3_mutex_held(pInode->pLockMutex) );
  32383. if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
  32384. if( pInode->bProcessLock==0 ){
  32385. struct flock lock;
  32386. assert( pInode->nLock==0 );
  32387. lock.l_whence = SEEK_SET;
  32388. lock.l_start = SHARED_FIRST;
  32389. lock.l_len = SHARED_SIZE;
  32390. lock.l_type = F_WRLCK;
  32391. rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
  32392. if( rc<0 ) return rc;
  32393. pInode->bProcessLock = 1;
  32394. pInode->nLock++;
  32395. }else{
  32396. rc = 0;
  32397. }
  32398. }else{
  32399. rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
  32400. }
  32401. return rc;
  32402. }
  32403. /*
  32404. ** Lock the file with the lock specified by parameter eFileLock - one
  32405. ** of the following:
  32406. **
  32407. ** (1) SHARED_LOCK
  32408. ** (2) RESERVED_LOCK
  32409. ** (3) PENDING_LOCK
  32410. ** (4) EXCLUSIVE_LOCK
  32411. **
  32412. ** Sometimes when requesting one lock state, additional lock states
  32413. ** are inserted in between. The locking might fail on one of the later
  32414. ** transitions leaving the lock state different from what it started but
  32415. ** still short of its goal. The following chart shows the allowed
  32416. ** transitions and the inserted intermediate states:
  32417. **
  32418. ** UNLOCKED -> SHARED
  32419. ** SHARED -> RESERVED
  32420. ** SHARED -> (PENDING) -> EXCLUSIVE
  32421. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32422. ** PENDING -> EXCLUSIVE
  32423. **
  32424. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32425. ** routine to lower a locking level.
  32426. */
  32427. static int unixLock(sqlite3_file *id, int eFileLock){
  32428. /* The following describes the implementation of the various locks and
  32429. ** lock transitions in terms of the POSIX advisory shared and exclusive
  32430. ** lock primitives (called read-locks and write-locks below, to avoid
  32431. ** confusion with SQLite lock names). The algorithms are complicated
  32432. ** slightly in order to be compatible with Windows95 systems simultaneously
  32433. ** accessing the same database file, in case that is ever required.
  32434. **
  32435. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  32436. ** byte', each single bytes at well known offsets, and the 'shared byte
  32437. ** range', a range of 510 bytes at a well known offset.
  32438. **
  32439. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  32440. ** byte'. If this is successful, 'shared byte range' is read-locked
  32441. ** and the lock on the 'pending byte' released. (Legacy note: When
  32442. ** SQLite was first developed, Windows95 systems were still very common,
  32443. ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
  32444. ** single randomly selected by from the 'shared byte range' is locked.
  32445. ** Windows95 is now pretty much extinct, but this work-around for the
  32446. ** lack of shared-locks on Windows95 lives on, for backwards
  32447. ** compatibility.)
  32448. **
  32449. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  32450. ** A RESERVED lock is implemented by grabbing a write-lock on the
  32451. ** 'reserved byte'.
  32452. **
  32453. ** A process may only obtain a PENDING lock after it has obtained a
  32454. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  32455. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  32456. ** obtained, but existing SHARED locks are allowed to persist. A process
  32457. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  32458. ** This property is used by the algorithm for rolling back a journal file
  32459. ** after a crash.
  32460. **
  32461. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  32462. ** implemented by obtaining a write-lock on the entire 'shared byte
  32463. ** range'. Since all other locks require a read-lock on one of the bytes
  32464. ** within this range, this ensures that no other locks are held on the
  32465. ** database.
  32466. */
  32467. int rc = SQLITE_OK;
  32468. unixFile *pFile = (unixFile*)id;
  32469. unixInodeInfo *pInode;
  32470. struct flock lock;
  32471. int tErrno = 0;
  32472. assert( pFile );
  32473. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  32474. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  32475. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  32476. osGetpid(0)));
  32477. /* If there is already a lock of this type or more restrictive on the
  32478. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  32479. ** unixEnterMutex() hasn't been called yet.
  32480. */
  32481. if( pFile->eFileLock>=eFileLock ){
  32482. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  32483. azFileLock(eFileLock)));
  32484. return SQLITE_OK;
  32485. }
  32486. /* Make sure the locking sequence is correct.
  32487. ** (1) We never move from unlocked to anything higher than shared lock.
  32488. ** (2) SQLite never explicitly requests a pendig lock.
  32489. ** (3) A shared lock is always held when a reserve lock is requested.
  32490. */
  32491. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  32492. assert( eFileLock!=PENDING_LOCK );
  32493. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  32494. /* This mutex is needed because pFile->pInode is shared across threads
  32495. */
  32496. pInode = pFile->pInode;
  32497. sqlite3_mutex_enter(pInode->pLockMutex);
  32498. /* If some thread using this PID has a lock via a different unixFile*
  32499. ** handle that precludes the requested lock, return BUSY.
  32500. */
  32501. if( (pFile->eFileLock!=pInode->eFileLock &&
  32502. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  32503. ){
  32504. rc = SQLITE_BUSY;
  32505. goto end_lock;
  32506. }
  32507. /* If a SHARED lock is requested, and some thread using this PID already
  32508. ** has a SHARED or RESERVED lock, then increment reference counts and
  32509. ** return SQLITE_OK.
  32510. */
  32511. if( eFileLock==SHARED_LOCK &&
  32512. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  32513. assert( eFileLock==SHARED_LOCK );
  32514. assert( pFile->eFileLock==0 );
  32515. assert( pInode->nShared>0 );
  32516. pFile->eFileLock = SHARED_LOCK;
  32517. pInode->nShared++;
  32518. pInode->nLock++;
  32519. goto end_lock;
  32520. }
  32521. /* A PENDING lock is needed before acquiring a SHARED lock and before
  32522. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  32523. ** be released.
  32524. */
  32525. lock.l_len = 1L;
  32526. lock.l_whence = SEEK_SET;
  32527. if( eFileLock==SHARED_LOCK
  32528. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  32529. ){
  32530. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  32531. lock.l_start = PENDING_BYTE;
  32532. if( unixFileLock(pFile, &lock) ){
  32533. tErrno = errno;
  32534. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32535. if( rc!=SQLITE_BUSY ){
  32536. storeLastErrno(pFile, tErrno);
  32537. }
  32538. goto end_lock;
  32539. }
  32540. }
  32541. /* If control gets to this point, then actually go ahead and make
  32542. ** operating system calls for the specified lock.
  32543. */
  32544. if( eFileLock==SHARED_LOCK ){
  32545. assert( pInode->nShared==0 );
  32546. assert( pInode->eFileLock==0 );
  32547. assert( rc==SQLITE_OK );
  32548. /* Now get the read-lock */
  32549. lock.l_start = SHARED_FIRST;
  32550. lock.l_len = SHARED_SIZE;
  32551. if( unixFileLock(pFile, &lock) ){
  32552. tErrno = errno;
  32553. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32554. }
  32555. /* Drop the temporary PENDING lock */
  32556. lock.l_start = PENDING_BYTE;
  32557. lock.l_len = 1L;
  32558. lock.l_type = F_UNLCK;
  32559. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  32560. /* This could happen with a network mount */
  32561. tErrno = errno;
  32562. rc = SQLITE_IOERR_UNLOCK;
  32563. }
  32564. if( rc ){
  32565. if( rc!=SQLITE_BUSY ){
  32566. storeLastErrno(pFile, tErrno);
  32567. }
  32568. goto end_lock;
  32569. }else{
  32570. pFile->eFileLock = SHARED_LOCK;
  32571. pInode->nLock++;
  32572. pInode->nShared = 1;
  32573. }
  32574. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  32575. /* We are trying for an exclusive lock but another thread in this
  32576. ** same process is still holding a shared lock. */
  32577. rc = SQLITE_BUSY;
  32578. }else{
  32579. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  32580. ** assumed that there is a SHARED or greater lock on the file
  32581. ** already.
  32582. */
  32583. assert( 0!=pFile->eFileLock );
  32584. lock.l_type = F_WRLCK;
  32585. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  32586. if( eFileLock==RESERVED_LOCK ){
  32587. lock.l_start = RESERVED_BYTE;
  32588. lock.l_len = 1L;
  32589. }else{
  32590. lock.l_start = SHARED_FIRST;
  32591. lock.l_len = SHARED_SIZE;
  32592. }
  32593. if( unixFileLock(pFile, &lock) ){
  32594. tErrno = errno;
  32595. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  32596. if( rc!=SQLITE_BUSY ){
  32597. storeLastErrno(pFile, tErrno);
  32598. }
  32599. }
  32600. }
  32601. #ifdef SQLITE_DEBUG
  32602. /* Set up the transaction-counter change checking flags when
  32603. ** transitioning from a SHARED to a RESERVED lock. The change
  32604. ** from SHARED to RESERVED marks the beginning of a normal
  32605. ** write operation (not a hot journal rollback).
  32606. */
  32607. if( rc==SQLITE_OK
  32608. && pFile->eFileLock<=SHARED_LOCK
  32609. && eFileLock==RESERVED_LOCK
  32610. ){
  32611. pFile->transCntrChng = 0;
  32612. pFile->dbUpdate = 0;
  32613. pFile->inNormalWrite = 1;
  32614. }
  32615. #endif
  32616. if( rc==SQLITE_OK ){
  32617. pFile->eFileLock = eFileLock;
  32618. pInode->eFileLock = eFileLock;
  32619. }else if( eFileLock==EXCLUSIVE_LOCK ){
  32620. pFile->eFileLock = PENDING_LOCK;
  32621. pInode->eFileLock = PENDING_LOCK;
  32622. }
  32623. end_lock:
  32624. sqlite3_mutex_leave(pInode->pLockMutex);
  32625. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  32626. rc==SQLITE_OK ? "ok" : "failed"));
  32627. return rc;
  32628. }
  32629. /*
  32630. ** Add the file descriptor used by file handle pFile to the corresponding
  32631. ** pUnused list.
  32632. */
  32633. static void setPendingFd(unixFile *pFile){
  32634. unixInodeInfo *pInode = pFile->pInode;
  32635. UnixUnusedFd *p = pFile->pPreallocatedUnused;
  32636. assert( unixFileMutexHeld(pFile) );
  32637. p->pNext = pInode->pUnused;
  32638. pInode->pUnused = p;
  32639. pFile->h = -1;
  32640. pFile->pPreallocatedUnused = 0;
  32641. }
  32642. /*
  32643. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32644. ** must be either NO_LOCK or SHARED_LOCK.
  32645. **
  32646. ** If the locking level of the file descriptor is already at or below
  32647. ** the requested locking level, this routine is a no-op.
  32648. **
  32649. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  32650. ** the byte range is divided into 2 parts and the first part is unlocked then
  32651. ** set to a read lock, then the other part is simply unlocked. This works
  32652. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  32653. ** remove the write lock on a region when a read lock is set.
  32654. */
  32655. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  32656. unixFile *pFile = (unixFile*)id;
  32657. unixInodeInfo *pInode;
  32658. struct flock lock;
  32659. int rc = SQLITE_OK;
  32660. assert( pFile );
  32661. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  32662. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  32663. osGetpid(0)));
  32664. assert( eFileLock<=SHARED_LOCK );
  32665. if( pFile->eFileLock<=eFileLock ){
  32666. return SQLITE_OK;
  32667. }
  32668. pInode = pFile->pInode;
  32669. sqlite3_mutex_enter(pInode->pLockMutex);
  32670. assert( pInode->nShared!=0 );
  32671. if( pFile->eFileLock>SHARED_LOCK ){
  32672. assert( pInode->eFileLock==pFile->eFileLock );
  32673. #ifdef SQLITE_DEBUG
  32674. /* When reducing a lock such that other processes can start
  32675. ** reading the database file again, make sure that the
  32676. ** transaction counter was updated if any part of the database
  32677. ** file changed. If the transaction counter is not updated,
  32678. ** other connections to the same file might not realize that
  32679. ** the file has changed and hence might not know to flush their
  32680. ** cache. The use of a stale cache can lead to database corruption.
  32681. */
  32682. pFile->inNormalWrite = 0;
  32683. #endif
  32684. /* downgrading to a shared lock on NFS involves clearing the write lock
  32685. ** before establishing the readlock - to avoid a race condition we downgrade
  32686. ** the lock in 2 blocks, so that part of the range will be covered by a
  32687. ** write lock until the rest is covered by a read lock:
  32688. ** 1: [WWWWW]
  32689. ** 2: [....W]
  32690. ** 3: [RRRRW]
  32691. ** 4: [RRRR.]
  32692. */
  32693. if( eFileLock==SHARED_LOCK ){
  32694. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  32695. (void)handleNFSUnlock;
  32696. assert( handleNFSUnlock==0 );
  32697. #endif
  32698. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  32699. if( handleNFSUnlock ){
  32700. int tErrno; /* Error code from system call errors */
  32701. off_t divSize = SHARED_SIZE - 1;
  32702. lock.l_type = F_UNLCK;
  32703. lock.l_whence = SEEK_SET;
  32704. lock.l_start = SHARED_FIRST;
  32705. lock.l_len = divSize;
  32706. if( unixFileLock(pFile, &lock)==(-1) ){
  32707. tErrno = errno;
  32708. rc = SQLITE_IOERR_UNLOCK;
  32709. storeLastErrno(pFile, tErrno);
  32710. goto end_unlock;
  32711. }
  32712. lock.l_type = F_RDLCK;
  32713. lock.l_whence = SEEK_SET;
  32714. lock.l_start = SHARED_FIRST;
  32715. lock.l_len = divSize;
  32716. if( unixFileLock(pFile, &lock)==(-1) ){
  32717. tErrno = errno;
  32718. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  32719. if( IS_LOCK_ERROR(rc) ){
  32720. storeLastErrno(pFile, tErrno);
  32721. }
  32722. goto end_unlock;
  32723. }
  32724. lock.l_type = F_UNLCK;
  32725. lock.l_whence = SEEK_SET;
  32726. lock.l_start = SHARED_FIRST+divSize;
  32727. lock.l_len = SHARED_SIZE-divSize;
  32728. if( unixFileLock(pFile, &lock)==(-1) ){
  32729. tErrno = errno;
  32730. rc = SQLITE_IOERR_UNLOCK;
  32731. storeLastErrno(pFile, tErrno);
  32732. goto end_unlock;
  32733. }
  32734. }else
  32735. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  32736. {
  32737. lock.l_type = F_RDLCK;
  32738. lock.l_whence = SEEK_SET;
  32739. lock.l_start = SHARED_FIRST;
  32740. lock.l_len = SHARED_SIZE;
  32741. if( unixFileLock(pFile, &lock) ){
  32742. /* In theory, the call to unixFileLock() cannot fail because another
  32743. ** process is holding an incompatible lock. If it does, this
  32744. ** indicates that the other process is not following the locking
  32745. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  32746. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  32747. ** an assert to fail). */
  32748. rc = SQLITE_IOERR_RDLOCK;
  32749. storeLastErrno(pFile, errno);
  32750. goto end_unlock;
  32751. }
  32752. }
  32753. }
  32754. lock.l_type = F_UNLCK;
  32755. lock.l_whence = SEEK_SET;
  32756. lock.l_start = PENDING_BYTE;
  32757. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  32758. if( unixFileLock(pFile, &lock)==0 ){
  32759. pInode->eFileLock = SHARED_LOCK;
  32760. }else{
  32761. rc = SQLITE_IOERR_UNLOCK;
  32762. storeLastErrno(pFile, errno);
  32763. goto end_unlock;
  32764. }
  32765. }
  32766. if( eFileLock==NO_LOCK ){
  32767. /* Decrement the shared lock counter. Release the lock using an
  32768. ** OS call only when all threads in this same process have released
  32769. ** the lock.
  32770. */
  32771. pInode->nShared--;
  32772. if( pInode->nShared==0 ){
  32773. lock.l_type = F_UNLCK;
  32774. lock.l_whence = SEEK_SET;
  32775. lock.l_start = lock.l_len = 0L;
  32776. if( unixFileLock(pFile, &lock)==0 ){
  32777. pInode->eFileLock = NO_LOCK;
  32778. }else{
  32779. rc = SQLITE_IOERR_UNLOCK;
  32780. storeLastErrno(pFile, errno);
  32781. pInode->eFileLock = NO_LOCK;
  32782. pFile->eFileLock = NO_LOCK;
  32783. }
  32784. }
  32785. /* Decrement the count of locks against this same file. When the
  32786. ** count reaches zero, close any other file descriptors whose close
  32787. ** was deferred because of outstanding locks.
  32788. */
  32789. pInode->nLock--;
  32790. assert( pInode->nLock>=0 );
  32791. if( pInode->nLock==0 ) closePendingFds(pFile);
  32792. }
  32793. end_unlock:
  32794. sqlite3_mutex_leave(pInode->pLockMutex);
  32795. if( rc==SQLITE_OK ){
  32796. pFile->eFileLock = eFileLock;
  32797. }
  32798. return rc;
  32799. }
  32800. /*
  32801. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32802. ** must be either NO_LOCK or SHARED_LOCK.
  32803. **
  32804. ** If the locking level of the file descriptor is already at or below
  32805. ** the requested locking level, this routine is a no-op.
  32806. */
  32807. static int unixUnlock(sqlite3_file *id, int eFileLock){
  32808. #if SQLITE_MAX_MMAP_SIZE>0
  32809. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  32810. #endif
  32811. return posixUnlock(id, eFileLock, 0);
  32812. }
  32813. #if SQLITE_MAX_MMAP_SIZE>0
  32814. static int unixMapfile(unixFile *pFd, i64 nByte);
  32815. static void unixUnmapfile(unixFile *pFd);
  32816. #endif
  32817. /*
  32818. ** This function performs the parts of the "close file" operation
  32819. ** common to all locking schemes. It closes the directory and file
  32820. ** handles, if they are valid, and sets all fields of the unixFile
  32821. ** structure to 0.
  32822. **
  32823. ** It is *not* necessary to hold the mutex when this routine is called,
  32824. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  32825. ** vxworksReleaseFileId() routine.
  32826. */
  32827. static int closeUnixFile(sqlite3_file *id){
  32828. unixFile *pFile = (unixFile*)id;
  32829. #if SQLITE_MAX_MMAP_SIZE>0
  32830. unixUnmapfile(pFile);
  32831. #endif
  32832. if( pFile->h>=0 ){
  32833. robust_close(pFile, pFile->h, __LINE__);
  32834. pFile->h = -1;
  32835. }
  32836. #if OS_VXWORKS
  32837. if( pFile->pId ){
  32838. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  32839. osUnlink(pFile->pId->zCanonicalName);
  32840. }
  32841. vxworksReleaseFileId(pFile->pId);
  32842. pFile->pId = 0;
  32843. }
  32844. #endif
  32845. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  32846. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  32847. osUnlink(pFile->zPath);
  32848. sqlite3_free(*(char**)&pFile->zPath);
  32849. pFile->zPath = 0;
  32850. }
  32851. #endif
  32852. OSTRACE(("CLOSE %-3d\n", pFile->h));
  32853. OpenCounter(-1);
  32854. sqlite3_free(pFile->pPreallocatedUnused);
  32855. memset(pFile, 0, sizeof(unixFile));
  32856. return SQLITE_OK;
  32857. }
  32858. /*
  32859. ** Close a file.
  32860. */
  32861. static int unixClose(sqlite3_file *id){
  32862. int rc = SQLITE_OK;
  32863. unixFile *pFile = (unixFile *)id;
  32864. unixInodeInfo *pInode = pFile->pInode;
  32865. assert( pInode!=0 );
  32866. verifyDbFile(pFile);
  32867. unixUnlock(id, NO_LOCK);
  32868. assert( unixFileMutexNotheld(pFile) );
  32869. unixEnterMutex();
  32870. /* unixFile.pInode is always valid here. Otherwise, a different close
  32871. ** routine (e.g. nolockClose()) would be called instead.
  32872. */
  32873. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  32874. sqlite3_mutex_enter(pInode->pLockMutex);
  32875. if( pInode->nLock ){
  32876. /* If there are outstanding locks, do not actually close the file just
  32877. ** yet because that would clear those locks. Instead, add the file
  32878. ** descriptor to pInode->pUnused list. It will be automatically closed
  32879. ** when the last lock is cleared.
  32880. */
  32881. setPendingFd(pFile);
  32882. }
  32883. sqlite3_mutex_leave(pInode->pLockMutex);
  32884. releaseInodeInfo(pFile);
  32885. rc = closeUnixFile(id);
  32886. unixLeaveMutex();
  32887. return rc;
  32888. }
  32889. /************** End of the posix advisory lock implementation *****************
  32890. ******************************************************************************/
  32891. /******************************************************************************
  32892. ****************************** No-op Locking **********************************
  32893. **
  32894. ** Of the various locking implementations available, this is by far the
  32895. ** simplest: locking is ignored. No attempt is made to lock the database
  32896. ** file for reading or writing.
  32897. **
  32898. ** This locking mode is appropriate for use on read-only databases
  32899. ** (ex: databases that are burned into CD-ROM, for example.) It can
  32900. ** also be used if the application employs some external mechanism to
  32901. ** prevent simultaneous access of the same database by two or more
  32902. ** database connections. But there is a serious risk of database
  32903. ** corruption if this locking mode is used in situations where multiple
  32904. ** database connections are accessing the same database file at the same
  32905. ** time and one or more of those connections are writing.
  32906. */
  32907. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  32908. UNUSED_PARAMETER(NotUsed);
  32909. *pResOut = 0;
  32910. return SQLITE_OK;
  32911. }
  32912. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  32913. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  32914. return SQLITE_OK;
  32915. }
  32916. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  32917. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  32918. return SQLITE_OK;
  32919. }
  32920. /*
  32921. ** Close the file.
  32922. */
  32923. static int nolockClose(sqlite3_file *id) {
  32924. return closeUnixFile(id);
  32925. }
  32926. /******************* End of the no-op lock implementation *********************
  32927. ******************************************************************************/
  32928. /******************************************************************************
  32929. ************************* Begin dot-file Locking ******************************
  32930. **
  32931. ** The dotfile locking implementation uses the existence of separate lock
  32932. ** files (really a directory) to control access to the database. This works
  32933. ** on just about every filesystem imaginable. But there are serious downsides:
  32934. **
  32935. ** (1) There is zero concurrency. A single reader blocks all other
  32936. ** connections from reading or writing the database.
  32937. **
  32938. ** (2) An application crash or power loss can leave stale lock files
  32939. ** sitting around that need to be cleared manually.
  32940. **
  32941. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  32942. ** other locking strategy is available.
  32943. **
  32944. ** Dotfile locking works by creating a subdirectory in the same directory as
  32945. ** the database and with the same name but with a ".lock" extension added.
  32946. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  32947. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  32948. */
  32949. /*
  32950. ** The file suffix added to the data base filename in order to create the
  32951. ** lock directory.
  32952. */
  32953. #define DOTLOCK_SUFFIX ".lock"
  32954. /*
  32955. ** This routine checks if there is a RESERVED lock held on the specified
  32956. ** file by this or any other process. If such a lock is held, set *pResOut
  32957. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32958. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32959. **
  32960. ** In dotfile locking, either a lock exists or it does not. So in this
  32961. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  32962. ** is held on the file and false if the file is unlocked.
  32963. */
  32964. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  32965. int rc = SQLITE_OK;
  32966. int reserved = 0;
  32967. unixFile *pFile = (unixFile*)id;
  32968. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32969. assert( pFile );
  32970. reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
  32971. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  32972. *pResOut = reserved;
  32973. return rc;
  32974. }
  32975. /*
  32976. ** Lock the file with the lock specified by parameter eFileLock - one
  32977. ** of the following:
  32978. **
  32979. ** (1) SHARED_LOCK
  32980. ** (2) RESERVED_LOCK
  32981. ** (3) PENDING_LOCK
  32982. ** (4) EXCLUSIVE_LOCK
  32983. **
  32984. ** Sometimes when requesting one lock state, additional lock states
  32985. ** are inserted in between. The locking might fail on one of the later
  32986. ** transitions leaving the lock state different from what it started but
  32987. ** still short of its goal. The following chart shows the allowed
  32988. ** transitions and the inserted intermediate states:
  32989. **
  32990. ** UNLOCKED -> SHARED
  32991. ** SHARED -> RESERVED
  32992. ** SHARED -> (PENDING) -> EXCLUSIVE
  32993. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32994. ** PENDING -> EXCLUSIVE
  32995. **
  32996. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32997. ** routine to lower a locking level.
  32998. **
  32999. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  33000. ** But we track the other locking levels internally.
  33001. */
  33002. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  33003. unixFile *pFile = (unixFile*)id;
  33004. char *zLockFile = (char *)pFile->lockingContext;
  33005. int rc = SQLITE_OK;
  33006. /* If we have any lock, then the lock file already exists. All we have
  33007. ** to do is adjust our internal record of the lock level.
  33008. */
  33009. if( pFile->eFileLock > NO_LOCK ){
  33010. pFile->eFileLock = eFileLock;
  33011. /* Always update the timestamp on the old file */
  33012. #ifdef HAVE_UTIME
  33013. utime(zLockFile, NULL);
  33014. #else
  33015. utimes(zLockFile, NULL);
  33016. #endif
  33017. return SQLITE_OK;
  33018. }
  33019. /* grab an exclusive lock */
  33020. rc = osMkdir(zLockFile, 0777);
  33021. if( rc<0 ){
  33022. /* failed to open/create the lock directory */
  33023. int tErrno = errno;
  33024. if( EEXIST == tErrno ){
  33025. rc = SQLITE_BUSY;
  33026. } else {
  33027. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  33028. if( rc!=SQLITE_BUSY ){
  33029. storeLastErrno(pFile, tErrno);
  33030. }
  33031. }
  33032. return rc;
  33033. }
  33034. /* got it, set the type and return ok */
  33035. pFile->eFileLock = eFileLock;
  33036. return rc;
  33037. }
  33038. /*
  33039. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33040. ** must be either NO_LOCK or SHARED_LOCK.
  33041. **
  33042. ** If the locking level of the file descriptor is already at or below
  33043. ** the requested locking level, this routine is a no-op.
  33044. **
  33045. ** When the locking level reaches NO_LOCK, delete the lock file.
  33046. */
  33047. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  33048. unixFile *pFile = (unixFile*)id;
  33049. char *zLockFile = (char *)pFile->lockingContext;
  33050. int rc;
  33051. assert( pFile );
  33052. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  33053. pFile->eFileLock, osGetpid(0)));
  33054. assert( eFileLock<=SHARED_LOCK );
  33055. /* no-op if possible */
  33056. if( pFile->eFileLock==eFileLock ){
  33057. return SQLITE_OK;
  33058. }
  33059. /* To downgrade to shared, simply update our internal notion of the
  33060. ** lock state. No need to mess with the file on disk.
  33061. */
  33062. if( eFileLock==SHARED_LOCK ){
  33063. pFile->eFileLock = SHARED_LOCK;
  33064. return SQLITE_OK;
  33065. }
  33066. /* To fully unlock the database, delete the lock file */
  33067. assert( eFileLock==NO_LOCK );
  33068. rc = osRmdir(zLockFile);
  33069. if( rc<0 ){
  33070. int tErrno = errno;
  33071. if( tErrno==ENOENT ){
  33072. rc = SQLITE_OK;
  33073. }else{
  33074. rc = SQLITE_IOERR_UNLOCK;
  33075. storeLastErrno(pFile, tErrno);
  33076. }
  33077. return rc;
  33078. }
  33079. pFile->eFileLock = NO_LOCK;
  33080. return SQLITE_OK;
  33081. }
  33082. /*
  33083. ** Close a file. Make sure the lock has been released before closing.
  33084. */
  33085. static int dotlockClose(sqlite3_file *id) {
  33086. unixFile *pFile = (unixFile*)id;
  33087. assert( id!=0 );
  33088. dotlockUnlock(id, NO_LOCK);
  33089. sqlite3_free(pFile->lockingContext);
  33090. return closeUnixFile(id);
  33091. }
  33092. /****************** End of the dot-file lock implementation *******************
  33093. ******************************************************************************/
  33094. /******************************************************************************
  33095. ************************** Begin flock Locking ********************************
  33096. **
  33097. ** Use the flock() system call to do file locking.
  33098. **
  33099. ** flock() locking is like dot-file locking in that the various
  33100. ** fine-grain locking levels supported by SQLite are collapsed into
  33101. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  33102. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  33103. ** still works when you do this, but concurrency is reduced since
  33104. ** only a single process can be reading the database at a time.
  33105. **
  33106. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  33107. */
  33108. #if SQLITE_ENABLE_LOCKING_STYLE
  33109. /*
  33110. ** Retry flock() calls that fail with EINTR
  33111. */
  33112. #ifdef EINTR
  33113. static int robust_flock(int fd, int op){
  33114. int rc;
  33115. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  33116. return rc;
  33117. }
  33118. #else
  33119. # define robust_flock(a,b) flock(a,b)
  33120. #endif
  33121. /*
  33122. ** This routine checks if there is a RESERVED lock held on the specified
  33123. ** file by this or any other process. If such a lock is held, set *pResOut
  33124. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  33125. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  33126. */
  33127. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  33128. int rc = SQLITE_OK;
  33129. int reserved = 0;
  33130. unixFile *pFile = (unixFile*)id;
  33131. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33132. assert( pFile );
  33133. /* Check if a thread in this process holds such a lock */
  33134. if( pFile->eFileLock>SHARED_LOCK ){
  33135. reserved = 1;
  33136. }
  33137. /* Otherwise see if some other process holds it. */
  33138. if( !reserved ){
  33139. /* attempt to get the lock */
  33140. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  33141. if( !lrc ){
  33142. /* got the lock, unlock it */
  33143. lrc = robust_flock(pFile->h, LOCK_UN);
  33144. if ( lrc ) {
  33145. int tErrno = errno;
  33146. /* unlock failed with an error */
  33147. lrc = SQLITE_IOERR_UNLOCK;
  33148. storeLastErrno(pFile, tErrno);
  33149. rc = lrc;
  33150. }
  33151. } else {
  33152. int tErrno = errno;
  33153. reserved = 1;
  33154. /* someone else might have it reserved */
  33155. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  33156. if( IS_LOCK_ERROR(lrc) ){
  33157. storeLastErrno(pFile, tErrno);
  33158. rc = lrc;
  33159. }
  33160. }
  33161. }
  33162. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  33163. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  33164. if( (rc & 0xff) == SQLITE_IOERR ){
  33165. rc = SQLITE_OK;
  33166. reserved=1;
  33167. }
  33168. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  33169. *pResOut = reserved;
  33170. return rc;
  33171. }
  33172. /*
  33173. ** Lock the file with the lock specified by parameter eFileLock - one
  33174. ** of the following:
  33175. **
  33176. ** (1) SHARED_LOCK
  33177. ** (2) RESERVED_LOCK
  33178. ** (3) PENDING_LOCK
  33179. ** (4) EXCLUSIVE_LOCK
  33180. **
  33181. ** Sometimes when requesting one lock state, additional lock states
  33182. ** are inserted in between. The locking might fail on one of the later
  33183. ** transitions leaving the lock state different from what it started but
  33184. ** still short of its goal. The following chart shows the allowed
  33185. ** transitions and the inserted intermediate states:
  33186. **
  33187. ** UNLOCKED -> SHARED
  33188. ** SHARED -> RESERVED
  33189. ** SHARED -> (PENDING) -> EXCLUSIVE
  33190. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33191. ** PENDING -> EXCLUSIVE
  33192. **
  33193. ** flock() only really support EXCLUSIVE locks. We track intermediate
  33194. ** lock states in the sqlite3_file structure, but all locks SHARED or
  33195. ** above are really EXCLUSIVE locks and exclude all other processes from
  33196. ** access the file.
  33197. **
  33198. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33199. ** routine to lower a locking level.
  33200. */
  33201. static int flockLock(sqlite3_file *id, int eFileLock) {
  33202. int rc = SQLITE_OK;
  33203. unixFile *pFile = (unixFile*)id;
  33204. assert( pFile );
  33205. /* if we already have a lock, it is exclusive.
  33206. ** Just adjust level and punt on outta here. */
  33207. if (pFile->eFileLock > NO_LOCK) {
  33208. pFile->eFileLock = eFileLock;
  33209. return SQLITE_OK;
  33210. }
  33211. /* grab an exclusive lock */
  33212. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  33213. int tErrno = errno;
  33214. /* didn't get, must be busy */
  33215. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  33216. if( IS_LOCK_ERROR(rc) ){
  33217. storeLastErrno(pFile, tErrno);
  33218. }
  33219. } else {
  33220. /* got it, set the type and return ok */
  33221. pFile->eFileLock = eFileLock;
  33222. }
  33223. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  33224. rc==SQLITE_OK ? "ok" : "failed"));
  33225. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  33226. if( (rc & 0xff) == SQLITE_IOERR ){
  33227. rc = SQLITE_BUSY;
  33228. }
  33229. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  33230. return rc;
  33231. }
  33232. /*
  33233. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33234. ** must be either NO_LOCK or SHARED_LOCK.
  33235. **
  33236. ** If the locking level of the file descriptor is already at or below
  33237. ** the requested locking level, this routine is a no-op.
  33238. */
  33239. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  33240. unixFile *pFile = (unixFile*)id;
  33241. assert( pFile );
  33242. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  33243. pFile->eFileLock, osGetpid(0)));
  33244. assert( eFileLock<=SHARED_LOCK );
  33245. /* no-op if possible */
  33246. if( pFile->eFileLock==eFileLock ){
  33247. return SQLITE_OK;
  33248. }
  33249. /* shared can just be set because we always have an exclusive */
  33250. if (eFileLock==SHARED_LOCK) {
  33251. pFile->eFileLock = eFileLock;
  33252. return SQLITE_OK;
  33253. }
  33254. /* no, really, unlock. */
  33255. if( robust_flock(pFile->h, LOCK_UN) ){
  33256. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  33257. return SQLITE_OK;
  33258. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  33259. return SQLITE_IOERR_UNLOCK;
  33260. }else{
  33261. pFile->eFileLock = NO_LOCK;
  33262. return SQLITE_OK;
  33263. }
  33264. }
  33265. /*
  33266. ** Close a file.
  33267. */
  33268. static int flockClose(sqlite3_file *id) {
  33269. assert( id!=0 );
  33270. flockUnlock(id, NO_LOCK);
  33271. return closeUnixFile(id);
  33272. }
  33273. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  33274. /******************* End of the flock lock implementation *********************
  33275. ******************************************************************************/
  33276. /******************************************************************************
  33277. ************************ Begin Named Semaphore Locking ************************
  33278. **
  33279. ** Named semaphore locking is only supported on VxWorks.
  33280. **
  33281. ** Semaphore locking is like dot-lock and flock in that it really only
  33282. ** supports EXCLUSIVE locking. Only a single process can read or write
  33283. ** the database file at a time. This reduces potential concurrency, but
  33284. ** makes the lock implementation much easier.
  33285. */
  33286. #if OS_VXWORKS
  33287. /*
  33288. ** This routine checks if there is a RESERVED lock held on the specified
  33289. ** file by this or any other process. If such a lock is held, set *pResOut
  33290. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  33291. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  33292. */
  33293. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  33294. int rc = SQLITE_OK;
  33295. int reserved = 0;
  33296. unixFile *pFile = (unixFile*)id;
  33297. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33298. assert( pFile );
  33299. /* Check if a thread in this process holds such a lock */
  33300. if( pFile->eFileLock>SHARED_LOCK ){
  33301. reserved = 1;
  33302. }
  33303. /* Otherwise see if some other process holds it. */
  33304. if( !reserved ){
  33305. sem_t *pSem = pFile->pInode->pSem;
  33306. if( sem_trywait(pSem)==-1 ){
  33307. int tErrno = errno;
  33308. if( EAGAIN != tErrno ){
  33309. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  33310. storeLastErrno(pFile, tErrno);
  33311. } else {
  33312. /* someone else has the lock when we are in NO_LOCK */
  33313. reserved = (pFile->eFileLock < SHARED_LOCK);
  33314. }
  33315. }else{
  33316. /* we could have it if we want it */
  33317. sem_post(pSem);
  33318. }
  33319. }
  33320. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  33321. *pResOut = reserved;
  33322. return rc;
  33323. }
  33324. /*
  33325. ** Lock the file with the lock specified by parameter eFileLock - one
  33326. ** of the following:
  33327. **
  33328. ** (1) SHARED_LOCK
  33329. ** (2) RESERVED_LOCK
  33330. ** (3) PENDING_LOCK
  33331. ** (4) EXCLUSIVE_LOCK
  33332. **
  33333. ** Sometimes when requesting one lock state, additional lock states
  33334. ** are inserted in between. The locking might fail on one of the later
  33335. ** transitions leaving the lock state different from what it started but
  33336. ** still short of its goal. The following chart shows the allowed
  33337. ** transitions and the inserted intermediate states:
  33338. **
  33339. ** UNLOCKED -> SHARED
  33340. ** SHARED -> RESERVED
  33341. ** SHARED -> (PENDING) -> EXCLUSIVE
  33342. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33343. ** PENDING -> EXCLUSIVE
  33344. **
  33345. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  33346. ** lock states in the sqlite3_file structure, but all locks SHARED or
  33347. ** above are really EXCLUSIVE locks and exclude all other processes from
  33348. ** access the file.
  33349. **
  33350. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33351. ** routine to lower a locking level.
  33352. */
  33353. static int semXLock(sqlite3_file *id, int eFileLock) {
  33354. unixFile *pFile = (unixFile*)id;
  33355. sem_t *pSem = pFile->pInode->pSem;
  33356. int rc = SQLITE_OK;
  33357. /* if we already have a lock, it is exclusive.
  33358. ** Just adjust level and punt on outta here. */
  33359. if (pFile->eFileLock > NO_LOCK) {
  33360. pFile->eFileLock = eFileLock;
  33361. rc = SQLITE_OK;
  33362. goto sem_end_lock;
  33363. }
  33364. /* lock semaphore now but bail out when already locked. */
  33365. if( sem_trywait(pSem)==-1 ){
  33366. rc = SQLITE_BUSY;
  33367. goto sem_end_lock;
  33368. }
  33369. /* got it, set the type and return ok */
  33370. pFile->eFileLock = eFileLock;
  33371. sem_end_lock:
  33372. return rc;
  33373. }
  33374. /*
  33375. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33376. ** must be either NO_LOCK or SHARED_LOCK.
  33377. **
  33378. ** If the locking level of the file descriptor is already at or below
  33379. ** the requested locking level, this routine is a no-op.
  33380. */
  33381. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  33382. unixFile *pFile = (unixFile*)id;
  33383. sem_t *pSem = pFile->pInode->pSem;
  33384. assert( pFile );
  33385. assert( pSem );
  33386. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  33387. pFile->eFileLock, osGetpid(0)));
  33388. assert( eFileLock<=SHARED_LOCK );
  33389. /* no-op if possible */
  33390. if( pFile->eFileLock==eFileLock ){
  33391. return SQLITE_OK;
  33392. }
  33393. /* shared can just be set because we always have an exclusive */
  33394. if (eFileLock==SHARED_LOCK) {
  33395. pFile->eFileLock = eFileLock;
  33396. return SQLITE_OK;
  33397. }
  33398. /* no, really unlock. */
  33399. if ( sem_post(pSem)==-1 ) {
  33400. int rc, tErrno = errno;
  33401. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  33402. if( IS_LOCK_ERROR(rc) ){
  33403. storeLastErrno(pFile, tErrno);
  33404. }
  33405. return rc;
  33406. }
  33407. pFile->eFileLock = NO_LOCK;
  33408. return SQLITE_OK;
  33409. }
  33410. /*
  33411. ** Close a file.
  33412. */
  33413. static int semXClose(sqlite3_file *id) {
  33414. if( id ){
  33415. unixFile *pFile = (unixFile*)id;
  33416. semXUnlock(id, NO_LOCK);
  33417. assert( pFile );
  33418. assert( unixFileMutexNotheld(pFile) );
  33419. unixEnterMutex();
  33420. releaseInodeInfo(pFile);
  33421. unixLeaveMutex();
  33422. closeUnixFile(id);
  33423. }
  33424. return SQLITE_OK;
  33425. }
  33426. #endif /* OS_VXWORKS */
  33427. /*
  33428. ** Named semaphore locking is only available on VxWorks.
  33429. **
  33430. *************** End of the named semaphore lock implementation ****************
  33431. ******************************************************************************/
  33432. /******************************************************************************
  33433. *************************** Begin AFP Locking *********************************
  33434. **
  33435. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  33436. ** on Apple Macintosh computers - both OS9 and OSX.
  33437. **
  33438. ** Third-party implementations of AFP are available. But this code here
  33439. ** only works on OSX.
  33440. */
  33441. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33442. /*
  33443. ** The afpLockingContext structure contains all afp lock specific state
  33444. */
  33445. typedef struct afpLockingContext afpLockingContext;
  33446. struct afpLockingContext {
  33447. int reserved;
  33448. const char *dbPath; /* Name of the open file */
  33449. };
  33450. struct ByteRangeLockPB2
  33451. {
  33452. unsigned long long offset; /* offset to first byte to lock */
  33453. unsigned long long length; /* nbr of bytes to lock */
  33454. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  33455. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  33456. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  33457. int fd; /* file desc to assoc this lock with */
  33458. };
  33459. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  33460. /*
  33461. ** This is a utility for setting or clearing a bit-range lock on an
  33462. ** AFP filesystem.
  33463. **
  33464. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  33465. */
  33466. static int afpSetLock(
  33467. const char *path, /* Name of the file to be locked or unlocked */
  33468. unixFile *pFile, /* Open file descriptor on path */
  33469. unsigned long long offset, /* First byte to be locked */
  33470. unsigned long long length, /* Number of bytes to lock */
  33471. int setLockFlag /* True to set lock. False to clear lock */
  33472. ){
  33473. struct ByteRangeLockPB2 pb;
  33474. int err;
  33475. pb.unLockFlag = setLockFlag ? 0 : 1;
  33476. pb.startEndFlag = 0;
  33477. pb.offset = offset;
  33478. pb.length = length;
  33479. pb.fd = pFile->h;
  33480. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  33481. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  33482. offset, length));
  33483. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  33484. if ( err==-1 ) {
  33485. int rc;
  33486. int tErrno = errno;
  33487. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  33488. path, tErrno, strerror(tErrno)));
  33489. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  33490. rc = SQLITE_BUSY;
  33491. #else
  33492. rc = sqliteErrorFromPosixError(tErrno,
  33493. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  33494. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  33495. if( IS_LOCK_ERROR(rc) ){
  33496. storeLastErrno(pFile, tErrno);
  33497. }
  33498. return rc;
  33499. } else {
  33500. return SQLITE_OK;
  33501. }
  33502. }
  33503. /*
  33504. ** This routine checks if there is a RESERVED lock held on the specified
  33505. ** file by this or any other process. If such a lock is held, set *pResOut
  33506. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  33507. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  33508. */
  33509. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  33510. int rc = SQLITE_OK;
  33511. int reserved = 0;
  33512. unixFile *pFile = (unixFile*)id;
  33513. afpLockingContext *context;
  33514. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33515. assert( pFile );
  33516. context = (afpLockingContext *) pFile->lockingContext;
  33517. if( context->reserved ){
  33518. *pResOut = 1;
  33519. return SQLITE_OK;
  33520. }
  33521. sqlite3_mutex_enter(pFile->pInode->pLockMutex);
  33522. /* Check if a thread in this process holds such a lock */
  33523. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  33524. reserved = 1;
  33525. }
  33526. /* Otherwise see if some other process holds it.
  33527. */
  33528. if( !reserved ){
  33529. /* lock the RESERVED byte */
  33530. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  33531. if( SQLITE_OK==lrc ){
  33532. /* if we succeeded in taking the reserved lock, unlock it to restore
  33533. ** the original state */
  33534. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  33535. } else {
  33536. /* if we failed to get the lock then someone else must have it */
  33537. reserved = 1;
  33538. }
  33539. if( IS_LOCK_ERROR(lrc) ){
  33540. rc=lrc;
  33541. }
  33542. }
  33543. sqlite3_mutex_leave(pFile->pInode->pLockMutex);
  33544. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  33545. *pResOut = reserved;
  33546. return rc;
  33547. }
  33548. /*
  33549. ** Lock the file with the lock specified by parameter eFileLock - one
  33550. ** of the following:
  33551. **
  33552. ** (1) SHARED_LOCK
  33553. ** (2) RESERVED_LOCK
  33554. ** (3) PENDING_LOCK
  33555. ** (4) EXCLUSIVE_LOCK
  33556. **
  33557. ** Sometimes when requesting one lock state, additional lock states
  33558. ** are inserted in between. The locking might fail on one of the later
  33559. ** transitions leaving the lock state different from what it started but
  33560. ** still short of its goal. The following chart shows the allowed
  33561. ** transitions and the inserted intermediate states:
  33562. **
  33563. ** UNLOCKED -> SHARED
  33564. ** SHARED -> RESERVED
  33565. ** SHARED -> (PENDING) -> EXCLUSIVE
  33566. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33567. ** PENDING -> EXCLUSIVE
  33568. **
  33569. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33570. ** routine to lower a locking level.
  33571. */
  33572. static int afpLock(sqlite3_file *id, int eFileLock){
  33573. int rc = SQLITE_OK;
  33574. unixFile *pFile = (unixFile*)id;
  33575. unixInodeInfo *pInode = pFile->pInode;
  33576. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  33577. assert( pFile );
  33578. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  33579. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  33580. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  33581. /* If there is already a lock of this type or more restrictive on the
  33582. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  33583. ** unixEnterMutex() hasn't been called yet.
  33584. */
  33585. if( pFile->eFileLock>=eFileLock ){
  33586. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  33587. azFileLock(eFileLock)));
  33588. return SQLITE_OK;
  33589. }
  33590. /* Make sure the locking sequence is correct
  33591. ** (1) We never move from unlocked to anything higher than shared lock.
  33592. ** (2) SQLite never explicitly requests a pendig lock.
  33593. ** (3) A shared lock is always held when a reserve lock is requested.
  33594. */
  33595. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  33596. assert( eFileLock!=PENDING_LOCK );
  33597. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  33598. /* This mutex is needed because pFile->pInode is shared across threads
  33599. */
  33600. pInode = pFile->pInode;
  33601. sqlite3_mutex_enter(pInode->pLockMutex);
  33602. /* If some thread using this PID has a lock via a different unixFile*
  33603. ** handle that precludes the requested lock, return BUSY.
  33604. */
  33605. if( (pFile->eFileLock!=pInode->eFileLock &&
  33606. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  33607. ){
  33608. rc = SQLITE_BUSY;
  33609. goto afp_end_lock;
  33610. }
  33611. /* If a SHARED lock is requested, and some thread using this PID already
  33612. ** has a SHARED or RESERVED lock, then increment reference counts and
  33613. ** return SQLITE_OK.
  33614. */
  33615. if( eFileLock==SHARED_LOCK &&
  33616. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  33617. assert( eFileLock==SHARED_LOCK );
  33618. assert( pFile->eFileLock==0 );
  33619. assert( pInode->nShared>0 );
  33620. pFile->eFileLock = SHARED_LOCK;
  33621. pInode->nShared++;
  33622. pInode->nLock++;
  33623. goto afp_end_lock;
  33624. }
  33625. /* A PENDING lock is needed before acquiring a SHARED lock and before
  33626. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  33627. ** be released.
  33628. */
  33629. if( eFileLock==SHARED_LOCK
  33630. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  33631. ){
  33632. int failed;
  33633. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  33634. if (failed) {
  33635. rc = failed;
  33636. goto afp_end_lock;
  33637. }
  33638. }
  33639. /* If control gets to this point, then actually go ahead and make
  33640. ** operating system calls for the specified lock.
  33641. */
  33642. if( eFileLock==SHARED_LOCK ){
  33643. int lrc1, lrc2, lrc1Errno = 0;
  33644. long lk, mask;
  33645. assert( pInode->nShared==0 );
  33646. assert( pInode->eFileLock==0 );
  33647. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  33648. /* Now get the read-lock SHARED_LOCK */
  33649. /* note that the quality of the randomness doesn't matter that much */
  33650. lk = random();
  33651. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  33652. lrc1 = afpSetLock(context->dbPath, pFile,
  33653. SHARED_FIRST+pInode->sharedByte, 1, 1);
  33654. if( IS_LOCK_ERROR(lrc1) ){
  33655. lrc1Errno = pFile->lastErrno;
  33656. }
  33657. /* Drop the temporary PENDING lock */
  33658. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  33659. if( IS_LOCK_ERROR(lrc1) ) {
  33660. storeLastErrno(pFile, lrc1Errno);
  33661. rc = lrc1;
  33662. goto afp_end_lock;
  33663. } else if( IS_LOCK_ERROR(lrc2) ){
  33664. rc = lrc2;
  33665. goto afp_end_lock;
  33666. } else if( lrc1 != SQLITE_OK ) {
  33667. rc = lrc1;
  33668. } else {
  33669. pFile->eFileLock = SHARED_LOCK;
  33670. pInode->nLock++;
  33671. pInode->nShared = 1;
  33672. }
  33673. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  33674. /* We are trying for an exclusive lock but another thread in this
  33675. ** same process is still holding a shared lock. */
  33676. rc = SQLITE_BUSY;
  33677. }else{
  33678. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  33679. ** assumed that there is a SHARED or greater lock on the file
  33680. ** already.
  33681. */
  33682. int failed = 0;
  33683. assert( 0!=pFile->eFileLock );
  33684. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  33685. /* Acquire a RESERVED lock */
  33686. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  33687. if( !failed ){
  33688. context->reserved = 1;
  33689. }
  33690. }
  33691. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  33692. /* Acquire an EXCLUSIVE lock */
  33693. /* Remove the shared lock before trying the range. we'll need to
  33694. ** reestablish the shared lock if we can't get the afpUnlock
  33695. */
  33696. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  33697. pInode->sharedByte, 1, 0)) ){
  33698. int failed2 = SQLITE_OK;
  33699. /* now attemmpt to get the exclusive lock range */
  33700. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  33701. SHARED_SIZE, 1);
  33702. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  33703. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  33704. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  33705. ** a critical I/O error
  33706. */
  33707. rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
  33708. SQLITE_IOERR_LOCK;
  33709. goto afp_end_lock;
  33710. }
  33711. }else{
  33712. rc = failed;
  33713. }
  33714. }
  33715. if( failed ){
  33716. rc = failed;
  33717. }
  33718. }
  33719. if( rc==SQLITE_OK ){
  33720. pFile->eFileLock = eFileLock;
  33721. pInode->eFileLock = eFileLock;
  33722. }else if( eFileLock==EXCLUSIVE_LOCK ){
  33723. pFile->eFileLock = PENDING_LOCK;
  33724. pInode->eFileLock = PENDING_LOCK;
  33725. }
  33726. afp_end_lock:
  33727. sqlite3_mutex_leave(pInode->pLockMutex);
  33728. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  33729. rc==SQLITE_OK ? "ok" : "failed"));
  33730. return rc;
  33731. }
  33732. /*
  33733. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33734. ** must be either NO_LOCK or SHARED_LOCK.
  33735. **
  33736. ** If the locking level of the file descriptor is already at or below
  33737. ** the requested locking level, this routine is a no-op.
  33738. */
  33739. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  33740. int rc = SQLITE_OK;
  33741. unixFile *pFile = (unixFile*)id;
  33742. unixInodeInfo *pInode;
  33743. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  33744. int skipShared = 0;
  33745. #ifdef SQLITE_TEST
  33746. int h = pFile->h;
  33747. #endif
  33748. assert( pFile );
  33749. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  33750. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  33751. osGetpid(0)));
  33752. assert( eFileLock<=SHARED_LOCK );
  33753. if( pFile->eFileLock<=eFileLock ){
  33754. return SQLITE_OK;
  33755. }
  33756. pInode = pFile->pInode;
  33757. sqlite3_mutex_enter(pInode->pLockMutex);
  33758. assert( pInode->nShared!=0 );
  33759. if( pFile->eFileLock>SHARED_LOCK ){
  33760. assert( pInode->eFileLock==pFile->eFileLock );
  33761. SimulateIOErrorBenign(1);
  33762. SimulateIOError( h=(-1) )
  33763. SimulateIOErrorBenign(0);
  33764. #ifdef SQLITE_DEBUG
  33765. /* When reducing a lock such that other processes can start
  33766. ** reading the database file again, make sure that the
  33767. ** transaction counter was updated if any part of the database
  33768. ** file changed. If the transaction counter is not updated,
  33769. ** other connections to the same file might not realize that
  33770. ** the file has changed and hence might not know to flush their
  33771. ** cache. The use of a stale cache can lead to database corruption.
  33772. */
  33773. assert( pFile->inNormalWrite==0
  33774. || pFile->dbUpdate==0
  33775. || pFile->transCntrChng==1 );
  33776. pFile->inNormalWrite = 0;
  33777. #endif
  33778. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  33779. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  33780. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  33781. /* only re-establish the shared lock if necessary */
  33782. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  33783. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  33784. } else {
  33785. skipShared = 1;
  33786. }
  33787. }
  33788. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  33789. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  33790. }
  33791. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  33792. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  33793. if( !rc ){
  33794. context->reserved = 0;
  33795. }
  33796. }
  33797. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  33798. pInode->eFileLock = SHARED_LOCK;
  33799. }
  33800. }
  33801. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  33802. /* Decrement the shared lock counter. Release the lock using an
  33803. ** OS call only when all threads in this same process have released
  33804. ** the lock.
  33805. */
  33806. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  33807. pInode->nShared--;
  33808. if( pInode->nShared==0 ){
  33809. SimulateIOErrorBenign(1);
  33810. SimulateIOError( h=(-1) )
  33811. SimulateIOErrorBenign(0);
  33812. if( !skipShared ){
  33813. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  33814. }
  33815. if( !rc ){
  33816. pInode->eFileLock = NO_LOCK;
  33817. pFile->eFileLock = NO_LOCK;
  33818. }
  33819. }
  33820. if( rc==SQLITE_OK ){
  33821. pInode->nLock--;
  33822. assert( pInode->nLock>=0 );
  33823. if( pInode->nLock==0 ) closePendingFds(pFile);
  33824. }
  33825. }
  33826. sqlite3_mutex_leave(pInode->pLockMutex);
  33827. if( rc==SQLITE_OK ){
  33828. pFile->eFileLock = eFileLock;
  33829. }
  33830. return rc;
  33831. }
  33832. /*
  33833. ** Close a file & cleanup AFP specific locking context
  33834. */
  33835. static int afpClose(sqlite3_file *id) {
  33836. int rc = SQLITE_OK;
  33837. unixFile *pFile = (unixFile*)id;
  33838. assert( id!=0 );
  33839. afpUnlock(id, NO_LOCK);
  33840. assert( unixFileMutexNotheld(pFile) );
  33841. unixEnterMutex();
  33842. if( pFile->pInode ){
  33843. unixInodeInfo *pInode = pFile->pInode;
  33844. sqlite3_mutex_enter(pInode->pLockMutex);
  33845. if( pInode->nLock ){
  33846. /* If there are outstanding locks, do not actually close the file just
  33847. ** yet because that would clear those locks. Instead, add the file
  33848. ** descriptor to pInode->aPending. It will be automatically closed when
  33849. ** the last lock is cleared.
  33850. */
  33851. setPendingFd(pFile);
  33852. }
  33853. sqlite3_mutex_leave(pInode->pLockMutex);
  33854. }
  33855. releaseInodeInfo(pFile);
  33856. sqlite3_free(pFile->lockingContext);
  33857. rc = closeUnixFile(id);
  33858. unixLeaveMutex();
  33859. return rc;
  33860. }
  33861. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  33862. /*
  33863. ** The code above is the AFP lock implementation. The code is specific
  33864. ** to MacOSX and does not work on other unix platforms. No alternative
  33865. ** is available. If you don't compile for a mac, then the "unix-afp"
  33866. ** VFS is not available.
  33867. **
  33868. ********************* End of the AFP lock implementation **********************
  33869. ******************************************************************************/
  33870. /******************************************************************************
  33871. *************************** Begin NFS Locking ********************************/
  33872. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33873. /*
  33874. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33875. ** must be either NO_LOCK or SHARED_LOCK.
  33876. **
  33877. ** If the locking level of the file descriptor is already at or below
  33878. ** the requested locking level, this routine is a no-op.
  33879. */
  33880. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  33881. return posixUnlock(id, eFileLock, 1);
  33882. }
  33883. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  33884. /*
  33885. ** The code above is the NFS lock implementation. The code is specific
  33886. ** to MacOSX and does not work on other unix platforms. No alternative
  33887. ** is available.
  33888. **
  33889. ********************* End of the NFS lock implementation **********************
  33890. ******************************************************************************/
  33891. /******************************************************************************
  33892. **************** Non-locking sqlite3_file methods *****************************
  33893. **
  33894. ** The next division contains implementations for all methods of the
  33895. ** sqlite3_file object other than the locking methods. The locking
  33896. ** methods were defined in divisions above (one locking method per
  33897. ** division). Those methods that are common to all locking modes
  33898. ** are gather together into this division.
  33899. */
  33900. /*
  33901. ** Seek to the offset passed as the second argument, then read cnt
  33902. ** bytes into pBuf. Return the number of bytes actually read.
  33903. **
  33904. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  33905. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  33906. ** one system to another. Since SQLite does not define USE_PREAD
  33907. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  33908. ** See tickets #2741 and #2681.
  33909. **
  33910. ** To avoid stomping the errno value on a failed read the lastErrno value
  33911. ** is set before returning.
  33912. */
  33913. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  33914. int got;
  33915. int prior = 0;
  33916. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  33917. i64 newOffset;
  33918. #endif
  33919. TIMER_START;
  33920. assert( cnt==(cnt&0x1ffff) );
  33921. assert( id->h>2 );
  33922. do{
  33923. #if defined(USE_PREAD)
  33924. got = osPread(id->h, pBuf, cnt, offset);
  33925. SimulateIOError( got = -1 );
  33926. #elif defined(USE_PREAD64)
  33927. got = osPread64(id->h, pBuf, cnt, offset);
  33928. SimulateIOError( got = -1 );
  33929. #else
  33930. newOffset = lseek(id->h, offset, SEEK_SET);
  33931. SimulateIOError( newOffset = -1 );
  33932. if( newOffset<0 ){
  33933. storeLastErrno((unixFile*)id, errno);
  33934. return -1;
  33935. }
  33936. got = osRead(id->h, pBuf, cnt);
  33937. #endif
  33938. if( got==cnt ) break;
  33939. if( got<0 ){
  33940. if( errno==EINTR ){ got = 1; continue; }
  33941. prior = 0;
  33942. storeLastErrno((unixFile*)id, errno);
  33943. break;
  33944. }else if( got>0 ){
  33945. cnt -= got;
  33946. offset += got;
  33947. prior += got;
  33948. pBuf = (void*)(got + (char*)pBuf);
  33949. }
  33950. }while( got>0 );
  33951. TIMER_END;
  33952. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  33953. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  33954. return got+prior;
  33955. }
  33956. /*
  33957. ** Read data from a file into a buffer. Return SQLITE_OK if all
  33958. ** bytes were read successfully and SQLITE_IOERR if anything goes
  33959. ** wrong.
  33960. */
  33961. static int unixRead(
  33962. sqlite3_file *id,
  33963. void *pBuf,
  33964. int amt,
  33965. sqlite3_int64 offset
  33966. ){
  33967. unixFile *pFile = (unixFile *)id;
  33968. int got;
  33969. assert( id );
  33970. assert( offset>=0 );
  33971. assert( amt>0 );
  33972. /* If this is a database file (not a journal, master-journal or temp
  33973. ** file), the bytes in the locking range should never be read or written. */
  33974. #if 0
  33975. assert( pFile->pPreallocatedUnused==0
  33976. || offset>=PENDING_BYTE+512
  33977. || offset+amt<=PENDING_BYTE
  33978. );
  33979. #endif
  33980. #if SQLITE_MAX_MMAP_SIZE>0
  33981. /* Deal with as much of this read request as possible by transfering
  33982. ** data from the memory mapping using memcpy(). */
  33983. if( offset<pFile->mmapSize ){
  33984. if( offset+amt <= pFile->mmapSize ){
  33985. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  33986. return SQLITE_OK;
  33987. }else{
  33988. int nCopy = pFile->mmapSize - offset;
  33989. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  33990. pBuf = &((u8 *)pBuf)[nCopy];
  33991. amt -= nCopy;
  33992. offset += nCopy;
  33993. }
  33994. }
  33995. #endif
  33996. got = seekAndRead(pFile, offset, pBuf, amt);
  33997. if( got==amt ){
  33998. return SQLITE_OK;
  33999. }else if( got<0 ){
  34000. /* lastErrno set by seekAndRead */
  34001. return SQLITE_IOERR_READ;
  34002. }else{
  34003. storeLastErrno(pFile, 0); /* not a system error */
  34004. /* Unread parts of the buffer must be zero-filled */
  34005. memset(&((char*)pBuf)[got], 0, amt-got);
  34006. return SQLITE_IOERR_SHORT_READ;
  34007. }
  34008. }
  34009. /*
  34010. ** Attempt to seek the file-descriptor passed as the first argument to
  34011. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  34012. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  34013. ** return the actual number of bytes written (which may be less than
  34014. ** nBuf).
  34015. */
  34016. static int seekAndWriteFd(
  34017. int fd, /* File descriptor to write to */
  34018. i64 iOff, /* File offset to begin writing at */
  34019. const void *pBuf, /* Copy data from this buffer to the file */
  34020. int nBuf, /* Size of buffer pBuf in bytes */
  34021. int *piErrno /* OUT: Error number if error occurs */
  34022. ){
  34023. int rc = 0; /* Value returned by system call */
  34024. assert( nBuf==(nBuf&0x1ffff) );
  34025. assert( fd>2 );
  34026. assert( piErrno!=0 );
  34027. nBuf &= 0x1ffff;
  34028. TIMER_START;
  34029. #if defined(USE_PREAD)
  34030. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  34031. #elif defined(USE_PREAD64)
  34032. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  34033. #else
  34034. do{
  34035. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  34036. SimulateIOError( iSeek = -1 );
  34037. if( iSeek<0 ){
  34038. rc = -1;
  34039. break;
  34040. }
  34041. rc = osWrite(fd, pBuf, nBuf);
  34042. }while( rc<0 && errno==EINTR );
  34043. #endif
  34044. TIMER_END;
  34045. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  34046. if( rc<0 ) *piErrno = errno;
  34047. return rc;
  34048. }
  34049. /*
  34050. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  34051. ** Return the number of bytes actually read. Update the offset.
  34052. **
  34053. ** To avoid stomping the errno value on a failed write the lastErrno value
  34054. ** is set before returning.
  34055. */
  34056. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  34057. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  34058. }
  34059. /*
  34060. ** Write data from a buffer into a file. Return SQLITE_OK on success
  34061. ** or some other error code on failure.
  34062. */
  34063. static int unixWrite(
  34064. sqlite3_file *id,
  34065. const void *pBuf,
  34066. int amt,
  34067. sqlite3_int64 offset
  34068. ){
  34069. unixFile *pFile = (unixFile*)id;
  34070. int wrote = 0;
  34071. assert( id );
  34072. assert( amt>0 );
  34073. /* If this is a database file (not a journal, master-journal or temp
  34074. ** file), the bytes in the locking range should never be read or written. */
  34075. #if 0
  34076. assert( pFile->pPreallocatedUnused==0
  34077. || offset>=PENDING_BYTE+512
  34078. || offset+amt<=PENDING_BYTE
  34079. );
  34080. #endif
  34081. #ifdef SQLITE_DEBUG
  34082. /* If we are doing a normal write to a database file (as opposed to
  34083. ** doing a hot-journal rollback or a write to some file other than a
  34084. ** normal database file) then record the fact that the database
  34085. ** has changed. If the transaction counter is modified, record that
  34086. ** fact too.
  34087. */
  34088. if( pFile->inNormalWrite ){
  34089. pFile->dbUpdate = 1; /* The database has been modified */
  34090. if( offset<=24 && offset+amt>=27 ){
  34091. int rc;
  34092. char oldCntr[4];
  34093. SimulateIOErrorBenign(1);
  34094. rc = seekAndRead(pFile, 24, oldCntr, 4);
  34095. SimulateIOErrorBenign(0);
  34096. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  34097. pFile->transCntrChng = 1; /* The transaction counter has changed */
  34098. }
  34099. }
  34100. }
  34101. #endif
  34102. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  34103. /* Deal with as much of this write request as possible by transfering
  34104. ** data from the memory mapping using memcpy(). */
  34105. if( offset<pFile->mmapSize ){
  34106. if( offset+amt <= pFile->mmapSize ){
  34107. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  34108. return SQLITE_OK;
  34109. }else{
  34110. int nCopy = pFile->mmapSize - offset;
  34111. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  34112. pBuf = &((u8 *)pBuf)[nCopy];
  34113. amt -= nCopy;
  34114. offset += nCopy;
  34115. }
  34116. }
  34117. #endif
  34118. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  34119. amt -= wrote;
  34120. offset += wrote;
  34121. pBuf = &((char*)pBuf)[wrote];
  34122. }
  34123. SimulateIOError(( wrote=(-1), amt=1 ));
  34124. SimulateDiskfullError(( wrote=0, amt=1 ));
  34125. if( amt>wrote ){
  34126. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  34127. /* lastErrno set by seekAndWrite */
  34128. return SQLITE_IOERR_WRITE;
  34129. }else{
  34130. storeLastErrno(pFile, 0); /* not a system error */
  34131. return SQLITE_FULL;
  34132. }
  34133. }
  34134. return SQLITE_OK;
  34135. }
  34136. #ifdef SQLITE_TEST
  34137. /*
  34138. ** Count the number of fullsyncs and normal syncs. This is used to test
  34139. ** that syncs and fullsyncs are occurring at the right times.
  34140. */
  34141. SQLITE_API int sqlite3_sync_count = 0;
  34142. SQLITE_API int sqlite3_fullsync_count = 0;
  34143. #endif
  34144. /*
  34145. ** We do not trust systems to provide a working fdatasync(). Some do.
  34146. ** Others do no. To be safe, we will stick with the (slightly slower)
  34147. ** fsync(). If you know that your system does support fdatasync() correctly,
  34148. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  34149. */
  34150. #if !defined(fdatasync) && !HAVE_FDATASYNC
  34151. # define fdatasync fsync
  34152. #endif
  34153. /*
  34154. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  34155. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  34156. ** only available on Mac OS X. But that could change.
  34157. */
  34158. #ifdef F_FULLFSYNC
  34159. # define HAVE_FULLFSYNC 1
  34160. #else
  34161. # define HAVE_FULLFSYNC 0
  34162. #endif
  34163. /*
  34164. ** The fsync() system call does not work as advertised on many
  34165. ** unix systems. The following procedure is an attempt to make
  34166. ** it work better.
  34167. **
  34168. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  34169. ** for testing when we want to run through the test suite quickly.
  34170. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  34171. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  34172. ** or power failure will likely corrupt the database file.
  34173. **
  34174. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  34175. ** The idea behind dataOnly is that it should only write the file content
  34176. ** to disk, not the inode. We only set dataOnly if the file size is
  34177. ** unchanged since the file size is part of the inode. However,
  34178. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  34179. ** file size has changed. The only real difference between fdatasync()
  34180. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  34181. ** inode if the mtime or owner or other inode attributes have changed.
  34182. ** We only care about the file size, not the other file attributes, so
  34183. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  34184. ** So, we always use fdatasync() if it is available, regardless of
  34185. ** the value of the dataOnly flag.
  34186. */
  34187. static int full_fsync(int fd, int fullSync, int dataOnly){
  34188. int rc;
  34189. /* The following "ifdef/elif/else/" block has the same structure as
  34190. ** the one below. It is replicated here solely to avoid cluttering
  34191. ** up the real code with the UNUSED_PARAMETER() macros.
  34192. */
  34193. #ifdef SQLITE_NO_SYNC
  34194. UNUSED_PARAMETER(fd);
  34195. UNUSED_PARAMETER(fullSync);
  34196. UNUSED_PARAMETER(dataOnly);
  34197. #elif HAVE_FULLFSYNC
  34198. UNUSED_PARAMETER(dataOnly);
  34199. #else
  34200. UNUSED_PARAMETER(fullSync);
  34201. UNUSED_PARAMETER(dataOnly);
  34202. #endif
  34203. /* Record the number of times that we do a normal fsync() and
  34204. ** FULLSYNC. This is used during testing to verify that this procedure
  34205. ** gets called with the correct arguments.
  34206. */
  34207. #ifdef SQLITE_TEST
  34208. if( fullSync ) sqlite3_fullsync_count++;
  34209. sqlite3_sync_count++;
  34210. #endif
  34211. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  34212. ** no-op. But go ahead and call fstat() to validate the file
  34213. ** descriptor as we need a method to provoke a failure during
  34214. ** coverate testing.
  34215. */
  34216. #ifdef SQLITE_NO_SYNC
  34217. {
  34218. struct stat buf;
  34219. rc = osFstat(fd, &buf);
  34220. }
  34221. #elif HAVE_FULLFSYNC
  34222. if( fullSync ){
  34223. rc = osFcntl(fd, F_FULLFSYNC, 0);
  34224. }else{
  34225. rc = 1;
  34226. }
  34227. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  34228. ** It shouldn't be possible for fullfsync to fail on the local
  34229. ** file system (on OSX), so failure indicates that FULLFSYNC
  34230. ** isn't supported for this file system. So, attempt an fsync
  34231. ** and (for now) ignore the overhead of a superfluous fcntl call.
  34232. ** It'd be better to detect fullfsync support once and avoid
  34233. ** the fcntl call every time sync is called.
  34234. */
  34235. if( rc ) rc = fsync(fd);
  34236. #elif defined(__APPLE__)
  34237. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  34238. ** so currently we default to the macro that redefines fdatasync to fsync
  34239. */
  34240. rc = fsync(fd);
  34241. #else
  34242. rc = fdatasync(fd);
  34243. #if OS_VXWORKS
  34244. if( rc==-1 && errno==ENOTSUP ){
  34245. rc = fsync(fd);
  34246. }
  34247. #endif /* OS_VXWORKS */
  34248. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  34249. if( OS_VXWORKS && rc!= -1 ){
  34250. rc = 0;
  34251. }
  34252. return rc;
  34253. }
  34254. /*
  34255. ** Open a file descriptor to the directory containing file zFilename.
  34256. ** If successful, *pFd is set to the opened file descriptor and
  34257. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  34258. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  34259. ** value.
  34260. **
  34261. ** The directory file descriptor is used for only one thing - to
  34262. ** fsync() a directory to make sure file creation and deletion events
  34263. ** are flushed to disk. Such fsyncs are not needed on newer
  34264. ** journaling filesystems, but are required on older filesystems.
  34265. **
  34266. ** This routine can be overridden using the xSetSysCall interface.
  34267. ** The ability to override this routine was added in support of the
  34268. ** chromium sandbox. Opening a directory is a security risk (we are
  34269. ** told) so making it overrideable allows the chromium sandbox to
  34270. ** replace this routine with a harmless no-op. To make this routine
  34271. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  34272. ** *pFd set to a negative number.
  34273. **
  34274. ** If SQLITE_OK is returned, the caller is responsible for closing
  34275. ** the file descriptor *pFd using close().
  34276. */
  34277. static int openDirectory(const char *zFilename, int *pFd){
  34278. int ii;
  34279. int fd = -1;
  34280. char zDirname[MAX_PATHNAME+1];
  34281. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  34282. for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
  34283. if( ii>0 ){
  34284. zDirname[ii] = '\0';
  34285. }else{
  34286. if( zDirname[0]!='/' ) zDirname[0] = '.';
  34287. zDirname[1] = 0;
  34288. }
  34289. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  34290. if( fd>=0 ){
  34291. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  34292. }
  34293. *pFd = fd;
  34294. if( fd>=0 ) return SQLITE_OK;
  34295. return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
  34296. }
  34297. /*
  34298. ** Make sure all writes to a particular file are committed to disk.
  34299. **
  34300. ** If dataOnly==0 then both the file itself and its metadata (file
  34301. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  34302. ** file data is synced.
  34303. **
  34304. ** Under Unix, also make sure that the directory entry for the file
  34305. ** has been created by fsync-ing the directory that contains the file.
  34306. ** If we do not do this and we encounter a power failure, the directory
  34307. ** entry for the journal might not exist after we reboot. The next
  34308. ** SQLite to access the file will not know that the journal exists (because
  34309. ** the directory entry for the journal was never created) and the transaction
  34310. ** will not roll back - possibly leading to database corruption.
  34311. */
  34312. static int unixSync(sqlite3_file *id, int flags){
  34313. int rc;
  34314. unixFile *pFile = (unixFile*)id;
  34315. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  34316. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  34317. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  34318. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  34319. || (flags&0x0F)==SQLITE_SYNC_FULL
  34320. );
  34321. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  34322. ** line is to test that doing so does not cause any problems.
  34323. */
  34324. SimulateDiskfullError( return SQLITE_FULL );
  34325. assert( pFile );
  34326. OSTRACE(("SYNC %-3d\n", pFile->h));
  34327. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  34328. SimulateIOError( rc=1 );
  34329. if( rc ){
  34330. storeLastErrno(pFile, errno);
  34331. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  34332. }
  34333. /* Also fsync the directory containing the file if the DIRSYNC flag
  34334. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  34335. ** are unable to fsync a directory, so ignore errors on the fsync.
  34336. */
  34337. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  34338. int dirfd;
  34339. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  34340. HAVE_FULLFSYNC, isFullsync));
  34341. rc = osOpenDirectory(pFile->zPath, &dirfd);
  34342. if( rc==SQLITE_OK ){
  34343. full_fsync(dirfd, 0, 0);
  34344. robust_close(pFile, dirfd, __LINE__);
  34345. }else{
  34346. assert( rc==SQLITE_CANTOPEN );
  34347. rc = SQLITE_OK;
  34348. }
  34349. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  34350. }
  34351. return rc;
  34352. }
  34353. /*
  34354. ** Truncate an open file to a specified size
  34355. */
  34356. static int unixTruncate(sqlite3_file *id, i64 nByte){
  34357. unixFile *pFile = (unixFile *)id;
  34358. int rc;
  34359. assert( pFile );
  34360. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  34361. /* If the user has configured a chunk-size for this file, truncate the
  34362. ** file so that it consists of an integer number of chunks (i.e. the
  34363. ** actual file size after the operation may be larger than the requested
  34364. ** size).
  34365. */
  34366. if( pFile->szChunk>0 ){
  34367. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  34368. }
  34369. rc = robust_ftruncate(pFile->h, nByte);
  34370. if( rc ){
  34371. storeLastErrno(pFile, errno);
  34372. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  34373. }else{
  34374. #ifdef SQLITE_DEBUG
  34375. /* If we are doing a normal write to a database file (as opposed to
  34376. ** doing a hot-journal rollback or a write to some file other than a
  34377. ** normal database file) and we truncate the file to zero length,
  34378. ** that effectively updates the change counter. This might happen
  34379. ** when restoring a database using the backup API from a zero-length
  34380. ** source.
  34381. */
  34382. if( pFile->inNormalWrite && nByte==0 ){
  34383. pFile->transCntrChng = 1;
  34384. }
  34385. #endif
  34386. #if SQLITE_MAX_MMAP_SIZE>0
  34387. /* If the file was just truncated to a size smaller than the currently
  34388. ** mapped region, reduce the effective mapping size as well. SQLite will
  34389. ** use read() and write() to access data beyond this point from now on.
  34390. */
  34391. if( nByte<pFile->mmapSize ){
  34392. pFile->mmapSize = nByte;
  34393. }
  34394. #endif
  34395. return SQLITE_OK;
  34396. }
  34397. }
  34398. /*
  34399. ** Determine the current size of a file in bytes
  34400. */
  34401. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  34402. int rc;
  34403. struct stat buf;
  34404. assert( id );
  34405. rc = osFstat(((unixFile*)id)->h, &buf);
  34406. SimulateIOError( rc=1 );
  34407. if( rc!=0 ){
  34408. storeLastErrno((unixFile*)id, errno);
  34409. return SQLITE_IOERR_FSTAT;
  34410. }
  34411. *pSize = buf.st_size;
  34412. /* When opening a zero-size database, the findInodeInfo() procedure
  34413. ** writes a single byte into that file in order to work around a bug
  34414. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  34415. ** layers, we need to report this file size as zero even though it is
  34416. ** really 1. Ticket #3260.
  34417. */
  34418. if( *pSize==1 ) *pSize = 0;
  34419. return SQLITE_OK;
  34420. }
  34421. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  34422. /*
  34423. ** Handler for proxy-locking file-control verbs. Defined below in the
  34424. ** proxying locking division.
  34425. */
  34426. static int proxyFileControl(sqlite3_file*,int,void*);
  34427. #endif
  34428. /*
  34429. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  34430. ** file-control operation. Enlarge the database to nBytes in size
  34431. ** (rounded up to the next chunk-size). If the database is already
  34432. ** nBytes or larger, this routine is a no-op.
  34433. */
  34434. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  34435. if( pFile->szChunk>0 ){
  34436. i64 nSize; /* Required file size */
  34437. struct stat buf; /* Used to hold return values of fstat() */
  34438. if( osFstat(pFile->h, &buf) ){
  34439. return SQLITE_IOERR_FSTAT;
  34440. }
  34441. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  34442. if( nSize>(i64)buf.st_size ){
  34443. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  34444. /* The code below is handling the return value of osFallocate()
  34445. ** correctly. posix_fallocate() is defined to "returns zero on success,
  34446. ** or an error number on failure". See the manpage for details. */
  34447. int err;
  34448. do{
  34449. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  34450. }while( err==EINTR );
  34451. if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
  34452. #else
  34453. /* If the OS does not have posix_fallocate(), fake it. Write a
  34454. ** single byte to the last byte in each block that falls entirely
  34455. ** within the extended region. Then, if required, a single byte
  34456. ** at offset (nSize-1), to set the size of the file correctly.
  34457. ** This is a similar technique to that used by glibc on systems
  34458. ** that do not have a real fallocate() call.
  34459. */
  34460. int nBlk = buf.st_blksize; /* File-system block size */
  34461. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  34462. i64 iWrite; /* Next offset to write to */
  34463. iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
  34464. assert( iWrite>=buf.st_size );
  34465. assert( ((iWrite+1)%nBlk)==0 );
  34466. for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
  34467. if( iWrite>=nSize ) iWrite = nSize - 1;
  34468. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  34469. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  34470. }
  34471. #endif
  34472. }
  34473. }
  34474. #if SQLITE_MAX_MMAP_SIZE>0
  34475. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  34476. int rc;
  34477. if( pFile->szChunk<=0 ){
  34478. if( robust_ftruncate(pFile->h, nByte) ){
  34479. storeLastErrno(pFile, errno);
  34480. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  34481. }
  34482. }
  34483. rc = unixMapfile(pFile, nByte);
  34484. return rc;
  34485. }
  34486. #endif
  34487. return SQLITE_OK;
  34488. }
  34489. /*
  34490. ** If *pArg is initially negative then this is a query. Set *pArg to
  34491. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  34492. **
  34493. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  34494. */
  34495. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  34496. if( *pArg<0 ){
  34497. *pArg = (pFile->ctrlFlags & mask)!=0;
  34498. }else if( (*pArg)==0 ){
  34499. pFile->ctrlFlags &= ~mask;
  34500. }else{
  34501. pFile->ctrlFlags |= mask;
  34502. }
  34503. }
  34504. /* Forward declaration */
  34505. static int unixGetTempname(int nBuf, char *zBuf);
  34506. /*
  34507. ** Information and control of an open file handle.
  34508. */
  34509. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  34510. unixFile *pFile = (unixFile*)id;
  34511. switch( op ){
  34512. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  34513. case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
  34514. int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
  34515. return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
  34516. }
  34517. case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
  34518. int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
  34519. return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
  34520. }
  34521. case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
  34522. int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
  34523. return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
  34524. }
  34525. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  34526. case SQLITE_FCNTL_LOCKSTATE: {
  34527. *(int*)pArg = pFile->eFileLock;
  34528. return SQLITE_OK;
  34529. }
  34530. case SQLITE_FCNTL_LAST_ERRNO: {
  34531. *(int*)pArg = pFile->lastErrno;
  34532. return SQLITE_OK;
  34533. }
  34534. case SQLITE_FCNTL_CHUNK_SIZE: {
  34535. pFile->szChunk = *(int *)pArg;
  34536. return SQLITE_OK;
  34537. }
  34538. case SQLITE_FCNTL_SIZE_HINT: {
  34539. int rc;
  34540. SimulateIOErrorBenign(1);
  34541. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  34542. SimulateIOErrorBenign(0);
  34543. return rc;
  34544. }
  34545. case SQLITE_FCNTL_PERSIST_WAL: {
  34546. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  34547. return SQLITE_OK;
  34548. }
  34549. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  34550. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  34551. return SQLITE_OK;
  34552. }
  34553. case SQLITE_FCNTL_VFSNAME: {
  34554. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  34555. return SQLITE_OK;
  34556. }
  34557. case SQLITE_FCNTL_TEMPFILENAME: {
  34558. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  34559. if( zTFile ){
  34560. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  34561. *(char**)pArg = zTFile;
  34562. }
  34563. return SQLITE_OK;
  34564. }
  34565. case SQLITE_FCNTL_HAS_MOVED: {
  34566. *(int*)pArg = fileHasMoved(pFile);
  34567. return SQLITE_OK;
  34568. }
  34569. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  34570. case SQLITE_FCNTL_LOCK_TIMEOUT: {
  34571. pFile->iBusyTimeout = *(int*)pArg;
  34572. return SQLITE_OK;
  34573. }
  34574. #endif
  34575. #if SQLITE_MAX_MMAP_SIZE>0
  34576. case SQLITE_FCNTL_MMAP_SIZE: {
  34577. i64 newLimit = *(i64*)pArg;
  34578. int rc = SQLITE_OK;
  34579. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  34580. newLimit = sqlite3GlobalConfig.mxMmap;
  34581. }
  34582. /* The value of newLimit may be eventually cast to (size_t) and passed
  34583. ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
  34584. ** 64-bit type. */
  34585. if( newLimit>0 && sizeof(size_t)<8 ){
  34586. newLimit = (newLimit & 0x7FFFFFFF);
  34587. }
  34588. *(i64*)pArg = pFile->mmapSizeMax;
  34589. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  34590. pFile->mmapSizeMax = newLimit;
  34591. if( pFile->mmapSize>0 ){
  34592. unixUnmapfile(pFile);
  34593. rc = unixMapfile(pFile, -1);
  34594. }
  34595. }
  34596. return rc;
  34597. }
  34598. #endif
  34599. #ifdef SQLITE_DEBUG
  34600. /* The pager calls this method to signal that it has done
  34601. ** a rollback and that the database is therefore unchanged and
  34602. ** it hence it is OK for the transaction change counter to be
  34603. ** unchanged.
  34604. */
  34605. case SQLITE_FCNTL_DB_UNCHANGED: {
  34606. ((unixFile*)id)->dbUpdate = 0;
  34607. return SQLITE_OK;
  34608. }
  34609. #endif
  34610. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  34611. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  34612. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  34613. return proxyFileControl(id,op,pArg);
  34614. }
  34615. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  34616. }
  34617. return SQLITE_NOTFOUND;
  34618. }
  34619. /*
  34620. ** If pFd->sectorSize is non-zero when this function is called, it is a
  34621. ** no-op. Otherwise, the values of pFd->sectorSize and
  34622. ** pFd->deviceCharacteristics are set according to the file-system
  34623. ** characteristics.
  34624. **
  34625. ** There are two versions of this function. One for QNX and one for all
  34626. ** other systems.
  34627. */
  34628. #ifndef __QNXNTO__
  34629. static void setDeviceCharacteristics(unixFile *pFd){
  34630. assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
  34631. if( pFd->sectorSize==0 ){
  34632. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  34633. int res;
  34634. u32 f = 0;
  34635. /* Check for support for F2FS atomic batch writes. */
  34636. res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
  34637. if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
  34638. pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
  34639. }
  34640. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  34641. /* Set the POWERSAFE_OVERWRITE flag if requested. */
  34642. if( pFd->ctrlFlags & UNIXFILE_PSOW ){
  34643. pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  34644. }
  34645. pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  34646. }
  34647. }
  34648. #else
  34649. #include <sys/dcmd_blk.h>
  34650. #include <sys/statvfs.h>
  34651. static void setDeviceCharacteristics(unixFile *pFile){
  34652. if( pFile->sectorSize == 0 ){
  34653. struct statvfs fsInfo;
  34654. /* Set defaults for non-supported filesystems */
  34655. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  34656. pFile->deviceCharacteristics = 0;
  34657. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  34658. return;
  34659. }
  34660. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  34661. pFile->sectorSize = fsInfo.f_bsize;
  34662. pFile->deviceCharacteristics =
  34663. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  34664. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34665. ** the write succeeds */
  34666. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34667. ** so it is ordered */
  34668. 0;
  34669. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  34670. pFile->sectorSize = fsInfo.f_bsize;
  34671. pFile->deviceCharacteristics =
  34672. /* etfs cluster size writes are atomic */
  34673. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  34674. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34675. ** the write succeeds */
  34676. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34677. ** so it is ordered */
  34678. 0;
  34679. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  34680. pFile->sectorSize = fsInfo.f_bsize;
  34681. pFile->deviceCharacteristics =
  34682. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  34683. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34684. ** the write succeeds */
  34685. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34686. ** so it is ordered */
  34687. 0;
  34688. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  34689. pFile->sectorSize = fsInfo.f_bsize;
  34690. pFile->deviceCharacteristics =
  34691. /* full bitset of atomics from max sector size and smaller */
  34692. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  34693. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34694. ** so it is ordered */
  34695. 0;
  34696. }else if( strstr(fsInfo.f_basetype, "dos") ){
  34697. pFile->sectorSize = fsInfo.f_bsize;
  34698. pFile->deviceCharacteristics =
  34699. /* full bitset of atomics from max sector size and smaller */
  34700. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  34701. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  34702. ** so it is ordered */
  34703. 0;
  34704. }else{
  34705. pFile->deviceCharacteristics =
  34706. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  34707. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  34708. ** the write succeeds */
  34709. 0;
  34710. }
  34711. }
  34712. /* Last chance verification. If the sector size isn't a multiple of 512
  34713. ** then it isn't valid.*/
  34714. if( pFile->sectorSize % 512 != 0 ){
  34715. pFile->deviceCharacteristics = 0;
  34716. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  34717. }
  34718. }
  34719. #endif
  34720. /*
  34721. ** Return the sector size in bytes of the underlying block device for
  34722. ** the specified file. This is almost always 512 bytes, but may be
  34723. ** larger for some devices.
  34724. **
  34725. ** SQLite code assumes this function cannot fail. It also assumes that
  34726. ** if two files are created in the same file-system directory (i.e.
  34727. ** a database and its journal file) that the sector size will be the
  34728. ** same for both.
  34729. */
  34730. static int unixSectorSize(sqlite3_file *id){
  34731. unixFile *pFd = (unixFile*)id;
  34732. setDeviceCharacteristics(pFd);
  34733. return pFd->sectorSize;
  34734. }
  34735. /*
  34736. ** Return the device characteristics for the file.
  34737. **
  34738. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  34739. ** However, that choice is controversial since technically the underlying
  34740. ** file system does not always provide powersafe overwrites. (In other
  34741. ** words, after a power-loss event, parts of the file that were never
  34742. ** written might end up being altered.) However, non-PSOW behavior is very,
  34743. ** very rare. And asserting PSOW makes a large reduction in the amount
  34744. ** of required I/O for journaling, since a lot of padding is eliminated.
  34745. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  34746. ** available to turn it off and URI query parameter available to turn it off.
  34747. */
  34748. static int unixDeviceCharacteristics(sqlite3_file *id){
  34749. unixFile *pFd = (unixFile*)id;
  34750. setDeviceCharacteristics(pFd);
  34751. return pFd->deviceCharacteristics;
  34752. }
  34753. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  34754. /*
  34755. ** Return the system page size.
  34756. **
  34757. ** This function should not be called directly by other code in this file.
  34758. ** Instead, it should be called via macro osGetpagesize().
  34759. */
  34760. static int unixGetpagesize(void){
  34761. #if OS_VXWORKS
  34762. return 1024;
  34763. #elif defined(_BSD_SOURCE)
  34764. return getpagesize();
  34765. #else
  34766. return (int)sysconf(_SC_PAGESIZE);
  34767. #endif
  34768. }
  34769. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  34770. #ifndef SQLITE_OMIT_WAL
  34771. /*
  34772. ** Object used to represent an shared memory buffer.
  34773. **
  34774. ** When multiple threads all reference the same wal-index, each thread
  34775. ** has its own unixShm object, but they all point to a single instance
  34776. ** of this unixShmNode object. In other words, each wal-index is opened
  34777. ** only once per process.
  34778. **
  34779. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  34780. ** We could coalesce this object into unixInodeInfo, but that would mean
  34781. ** every open file that does not use shared memory (in other words, most
  34782. ** open files) would have to carry around this extra information. So
  34783. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  34784. ** and the unixShmNode object is created only when needed.
  34785. **
  34786. ** unixMutexHeld() must be true when creating or destroying
  34787. ** this object or while reading or writing the following fields:
  34788. **
  34789. ** nRef
  34790. **
  34791. ** The following fields are read-only after the object is created:
  34792. **
  34793. ** hShm
  34794. ** zFilename
  34795. **
  34796. ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
  34797. ** unixMutexHeld() is true when reading or writing any other field
  34798. ** in this structure.
  34799. */
  34800. struct unixShmNode {
  34801. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  34802. sqlite3_mutex *pShmMutex; /* Mutex to access this object */
  34803. char *zFilename; /* Name of the mmapped file */
  34804. int hShm; /* Open file descriptor */
  34805. int szRegion; /* Size of shared-memory regions */
  34806. u16 nRegion; /* Size of array apRegion */
  34807. u8 isReadonly; /* True if read-only */
  34808. u8 isUnlocked; /* True if no DMS lock held */
  34809. char **apRegion; /* Array of mapped shared-memory regions */
  34810. int nRef; /* Number of unixShm objects pointing to this */
  34811. unixShm *pFirst; /* All unixShm objects pointing to this */
  34812. #ifdef SQLITE_DEBUG
  34813. u8 exclMask; /* Mask of exclusive locks held */
  34814. u8 sharedMask; /* Mask of shared locks held */
  34815. u8 nextShmId; /* Next available unixShm.id value */
  34816. #endif
  34817. };
  34818. /*
  34819. ** Structure used internally by this VFS to record the state of an
  34820. ** open shared memory connection.
  34821. **
  34822. ** The following fields are initialized when this object is created and
  34823. ** are read-only thereafter:
  34824. **
  34825. ** unixShm.pShmNode
  34826. ** unixShm.id
  34827. **
  34828. ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
  34829. ** be held while accessing any read/write fields.
  34830. */
  34831. struct unixShm {
  34832. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  34833. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  34834. u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
  34835. u8 id; /* Id of this connection within its unixShmNode */
  34836. u16 sharedMask; /* Mask of shared locks held */
  34837. u16 exclMask; /* Mask of exclusive locks held */
  34838. };
  34839. /*
  34840. ** Constants used for locking
  34841. */
  34842. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  34843. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  34844. /*
  34845. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  34846. **
  34847. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  34848. ** otherwise.
  34849. */
  34850. static int unixShmSystemLock(
  34851. unixFile *pFile, /* Open connection to the WAL file */
  34852. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  34853. int ofst, /* First byte of the locking range */
  34854. int n /* Number of bytes to lock */
  34855. ){
  34856. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  34857. struct flock f; /* The posix advisory locking structure */
  34858. int rc = SQLITE_OK; /* Result code form fcntl() */
  34859. /* Access to the unixShmNode object is serialized by the caller */
  34860. pShmNode = pFile->pInode->pShmNode;
  34861. assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
  34862. assert( pShmNode->nRef>0 || unixMutexHeld() );
  34863. /* Shared locks never span more than one byte */
  34864. assert( n==1 || lockType!=F_RDLCK );
  34865. /* Locks are within range */
  34866. assert( n>=1 && n<=SQLITE_SHM_NLOCK );
  34867. if( pShmNode->hShm>=0 ){
  34868. /* Initialize the locking parameters */
  34869. f.l_type = lockType;
  34870. f.l_whence = SEEK_SET;
  34871. f.l_start = ofst;
  34872. f.l_len = n;
  34873. rc = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
  34874. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  34875. }
  34876. /* Update the global lock state and do debug tracing */
  34877. #ifdef SQLITE_DEBUG
  34878. { u16 mask;
  34879. OSTRACE(("SHM-LOCK "));
  34880. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  34881. if( rc==SQLITE_OK ){
  34882. if( lockType==F_UNLCK ){
  34883. OSTRACE(("unlock %d ok", ofst));
  34884. pShmNode->exclMask &= ~mask;
  34885. pShmNode->sharedMask &= ~mask;
  34886. }else if( lockType==F_RDLCK ){
  34887. OSTRACE(("read-lock %d ok", ofst));
  34888. pShmNode->exclMask &= ~mask;
  34889. pShmNode->sharedMask |= mask;
  34890. }else{
  34891. assert( lockType==F_WRLCK );
  34892. OSTRACE(("write-lock %d ok", ofst));
  34893. pShmNode->exclMask |= mask;
  34894. pShmNode->sharedMask &= ~mask;
  34895. }
  34896. }else{
  34897. if( lockType==F_UNLCK ){
  34898. OSTRACE(("unlock %d failed", ofst));
  34899. }else if( lockType==F_RDLCK ){
  34900. OSTRACE(("read-lock failed"));
  34901. }else{
  34902. assert( lockType==F_WRLCK );
  34903. OSTRACE(("write-lock %d failed", ofst));
  34904. }
  34905. }
  34906. OSTRACE((" - afterwards %03x,%03x\n",
  34907. pShmNode->sharedMask, pShmNode->exclMask));
  34908. }
  34909. #endif
  34910. return rc;
  34911. }
  34912. /*
  34913. ** Return the minimum number of 32KB shm regions that should be mapped at
  34914. ** a time, assuming that each mapping must be an integer multiple of the
  34915. ** current system page-size.
  34916. **
  34917. ** Usually, this is 1. The exception seems to be systems that are configured
  34918. ** to use 64KB pages - in this case each mapping must cover at least two
  34919. ** shm regions.
  34920. */
  34921. static int unixShmRegionPerMap(void){
  34922. int shmsz = 32*1024; /* SHM region size */
  34923. int pgsz = osGetpagesize(); /* System page size */
  34924. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  34925. if( pgsz<shmsz ) return 1;
  34926. return pgsz/shmsz;
  34927. }
  34928. /*
  34929. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  34930. **
  34931. ** This is not a VFS shared-memory method; it is a utility function called
  34932. ** by VFS shared-memory methods.
  34933. */
  34934. static void unixShmPurge(unixFile *pFd){
  34935. unixShmNode *p = pFd->pInode->pShmNode;
  34936. assert( unixMutexHeld() );
  34937. if( p && ALWAYS(p->nRef==0) ){
  34938. int nShmPerMap = unixShmRegionPerMap();
  34939. int i;
  34940. assert( p->pInode==pFd->pInode );
  34941. sqlite3_mutex_free(p->pShmMutex);
  34942. for(i=0; i<p->nRegion; i+=nShmPerMap){
  34943. if( p->hShm>=0 ){
  34944. osMunmap(p->apRegion[i], p->szRegion);
  34945. }else{
  34946. sqlite3_free(p->apRegion[i]);
  34947. }
  34948. }
  34949. sqlite3_free(p->apRegion);
  34950. if( p->hShm>=0 ){
  34951. robust_close(pFd, p->hShm, __LINE__);
  34952. p->hShm = -1;
  34953. }
  34954. p->pInode->pShmNode = 0;
  34955. sqlite3_free(p);
  34956. }
  34957. }
  34958. /*
  34959. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  34960. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  34961. ** code otherwise.
  34962. **
  34963. ** If the DMS cannot be locked because this is a readonly_shm=1
  34964. ** connection and no other process already holds a lock, return
  34965. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  34966. */
  34967. static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
  34968. struct flock lock;
  34969. int rc = SQLITE_OK;
  34970. /* Use F_GETLK to determine the locks other processes are holding
  34971. ** on the DMS byte. If it indicates that another process is holding
  34972. ** a SHARED lock, then this process may also take a SHARED lock
  34973. ** and proceed with opening the *-shm file.
  34974. **
  34975. ** Or, if no other process is holding any lock, then this process
  34976. ** is the first to open it. In this case take an EXCLUSIVE lock on the
  34977. ** DMS byte and truncate the *-shm file to zero bytes in size. Then
  34978. ** downgrade to a SHARED lock on the DMS byte.
  34979. **
  34980. ** If another process is holding an EXCLUSIVE lock on the DMS byte,
  34981. ** return SQLITE_BUSY to the caller (it will try again). An earlier
  34982. ** version of this code attempted the SHARED lock at this point. But
  34983. ** this introduced a subtle race condition: if the process holding
  34984. ** EXCLUSIVE failed just before truncating the *-shm file, then this
  34985. ** process might open and use the *-shm file without truncating it.
  34986. ** And if the *-shm file has been corrupted by a power failure or
  34987. ** system crash, the database itself may also become corrupt. */
  34988. lock.l_whence = SEEK_SET;
  34989. lock.l_start = UNIX_SHM_DMS;
  34990. lock.l_len = 1;
  34991. lock.l_type = F_WRLCK;
  34992. if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
  34993. rc = SQLITE_IOERR_LOCK;
  34994. }else if( lock.l_type==F_UNLCK ){
  34995. if( pShmNode->isReadonly ){
  34996. pShmNode->isUnlocked = 1;
  34997. rc = SQLITE_READONLY_CANTINIT;
  34998. }else{
  34999. rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
  35000. /* The first connection to attach must truncate the -shm file. We
  35001. ** truncate to 3 bytes (an arbitrary small number, less than the
  35002. ** -shm header size) rather than 0 as a system debugging aid, to
  35003. ** help detect if a -shm file truncation is legitimate or is the work
  35004. ** or a rogue process. */
  35005. if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
  35006. rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
  35007. }
  35008. }
  35009. }else if( lock.l_type==F_WRLCK ){
  35010. rc = SQLITE_BUSY;
  35011. }
  35012. if( rc==SQLITE_OK ){
  35013. assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
  35014. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  35015. }
  35016. return rc;
  35017. }
  35018. /*
  35019. ** Open a shared-memory area associated with open database file pDbFd.
  35020. ** This particular implementation uses mmapped files.
  35021. **
  35022. ** The file used to implement shared-memory is in the same directory
  35023. ** as the open database file and has the same name as the open database
  35024. ** file with the "-shm" suffix added. For example, if the database file
  35025. ** is "/home/user1/config.db" then the file that is created and mmapped
  35026. ** for shared memory will be called "/home/user1/config.db-shm".
  35027. **
  35028. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  35029. ** some other tmpfs mount. But if a file in a different directory
  35030. ** from the database file is used, then differing access permissions
  35031. ** or a chroot() might cause two different processes on the same
  35032. ** database to end up using different files for shared memory -
  35033. ** meaning that their memory would not really be shared - resulting
  35034. ** in database corruption. Nevertheless, this tmpfs file usage
  35035. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  35036. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  35037. ** option results in an incompatible build of SQLite; builds of SQLite
  35038. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  35039. ** same database file at the same time, database corruption will likely
  35040. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  35041. ** "unsupported" and may go away in a future SQLite release.
  35042. **
  35043. ** When opening a new shared-memory file, if no other instances of that
  35044. ** file are currently open, in this process or in other processes, then
  35045. ** the file must be truncated to zero length or have its header cleared.
  35046. **
  35047. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  35048. ** that means that an exclusive lock is held on the database file and
  35049. ** that no other processes are able to read or write the database. In
  35050. ** that case, we do not really need shared memory. No shared memory
  35051. ** file is created. The shared memory will be simulated with heap memory.
  35052. */
  35053. static int unixOpenSharedMemory(unixFile *pDbFd){
  35054. struct unixShm *p = 0; /* The connection to be opened */
  35055. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  35056. int rc = SQLITE_OK; /* Result code */
  35057. unixInodeInfo *pInode; /* The inode of fd */
  35058. char *zShm; /* Name of the file used for SHM */
  35059. int nShmFilename; /* Size of the SHM filename in bytes */
  35060. /* Allocate space for the new unixShm object. */
  35061. p = sqlite3_malloc64( sizeof(*p) );
  35062. if( p==0 ) return SQLITE_NOMEM_BKPT;
  35063. memset(p, 0, sizeof(*p));
  35064. assert( pDbFd->pShm==0 );
  35065. /* Check to see if a unixShmNode object already exists. Reuse an existing
  35066. ** one if present. Create a new one if necessary.
  35067. */
  35068. assert( unixFileMutexNotheld(pDbFd) );
  35069. unixEnterMutex();
  35070. pInode = pDbFd->pInode;
  35071. pShmNode = pInode->pShmNode;
  35072. if( pShmNode==0 ){
  35073. struct stat sStat; /* fstat() info for database file */
  35074. #ifndef SQLITE_SHM_DIRECTORY
  35075. const char *zBasePath = pDbFd->zPath;
  35076. #endif
  35077. /* Call fstat() to figure out the permissions on the database file. If
  35078. ** a new *-shm file is created, an attempt will be made to create it
  35079. ** with the same permissions.
  35080. */
  35081. if( osFstat(pDbFd->h, &sStat) ){
  35082. rc = SQLITE_IOERR_FSTAT;
  35083. goto shm_open_err;
  35084. }
  35085. #ifdef SQLITE_SHM_DIRECTORY
  35086. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  35087. #else
  35088. nShmFilename = 6 + (int)strlen(zBasePath);
  35089. #endif
  35090. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  35091. if( pShmNode==0 ){
  35092. rc = SQLITE_NOMEM_BKPT;
  35093. goto shm_open_err;
  35094. }
  35095. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  35096. zShm = pShmNode->zFilename = (char*)&pShmNode[1];
  35097. #ifdef SQLITE_SHM_DIRECTORY
  35098. sqlite3_snprintf(nShmFilename, zShm,
  35099. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  35100. (u32)sStat.st_ino, (u32)sStat.st_dev);
  35101. #else
  35102. sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
  35103. sqlite3FileSuffix3(pDbFd->zPath, zShm);
  35104. #endif
  35105. pShmNode->hShm = -1;
  35106. pDbFd->pInode->pShmNode = pShmNode;
  35107. pShmNode->pInode = pDbFd->pInode;
  35108. if( sqlite3GlobalConfig.bCoreMutex ){
  35109. pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  35110. if( pShmNode->pShmMutex==0 ){
  35111. rc = SQLITE_NOMEM_BKPT;
  35112. goto shm_open_err;
  35113. }
  35114. }
  35115. if( pInode->bProcessLock==0 ){
  35116. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  35117. pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT,(sStat.st_mode&0777));
  35118. }
  35119. if( pShmNode->hShm<0 ){
  35120. pShmNode->hShm = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
  35121. if( pShmNode->hShm<0 ){
  35122. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
  35123. goto shm_open_err;
  35124. }
  35125. pShmNode->isReadonly = 1;
  35126. }
  35127. /* If this process is running as root, make sure that the SHM file
  35128. ** is owned by the same user that owns the original database. Otherwise,
  35129. ** the original owner will not be able to connect.
  35130. */
  35131. robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
  35132. rc = unixLockSharedMemory(pDbFd, pShmNode);
  35133. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  35134. }
  35135. }
  35136. /* Make the new connection a child of the unixShmNode */
  35137. p->pShmNode = pShmNode;
  35138. #ifdef SQLITE_DEBUG
  35139. p->id = pShmNode->nextShmId++;
  35140. #endif
  35141. pShmNode->nRef++;
  35142. pDbFd->pShm = p;
  35143. unixLeaveMutex();
  35144. /* The reference count on pShmNode has already been incremented under
  35145. ** the cover of the unixEnterMutex() mutex and the pointer from the
  35146. ** new (struct unixShm) object to the pShmNode has been set. All that is
  35147. ** left to do is to link the new object into the linked list starting
  35148. ** at pShmNode->pFirst. This must be done while holding the
  35149. ** pShmNode->pShmMutex.
  35150. */
  35151. sqlite3_mutex_enter(pShmNode->pShmMutex);
  35152. p->pNext = pShmNode->pFirst;
  35153. pShmNode->pFirst = p;
  35154. sqlite3_mutex_leave(pShmNode->pShmMutex);
  35155. return rc;
  35156. /* Jump here on any error */
  35157. shm_open_err:
  35158. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  35159. sqlite3_free(p);
  35160. unixLeaveMutex();
  35161. return rc;
  35162. }
  35163. /*
  35164. ** This function is called to obtain a pointer to region iRegion of the
  35165. ** shared-memory associated with the database file fd. Shared-memory regions
  35166. ** are numbered starting from zero. Each shared-memory region is szRegion
  35167. ** bytes in size.
  35168. **
  35169. ** If an error occurs, an error code is returned and *pp is set to NULL.
  35170. **
  35171. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  35172. ** region has not been allocated (by any client, including one running in a
  35173. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  35174. ** bExtend is non-zero and the requested shared-memory region has not yet
  35175. ** been allocated, it is allocated by this function.
  35176. **
  35177. ** If the shared-memory region has already been allocated or is allocated by
  35178. ** this call as described above, then it is mapped into this processes
  35179. ** address space (if it is not already), *pp is set to point to the mapped
  35180. ** memory and SQLITE_OK returned.
  35181. */
  35182. static int unixShmMap(
  35183. sqlite3_file *fd, /* Handle open on database file */
  35184. int iRegion, /* Region to retrieve */
  35185. int szRegion, /* Size of regions */
  35186. int bExtend, /* True to extend file if necessary */
  35187. void volatile **pp /* OUT: Mapped memory */
  35188. ){
  35189. unixFile *pDbFd = (unixFile*)fd;
  35190. unixShm *p;
  35191. unixShmNode *pShmNode;
  35192. int rc = SQLITE_OK;
  35193. int nShmPerMap = unixShmRegionPerMap();
  35194. int nReqRegion;
  35195. /* If the shared-memory file has not yet been opened, open it now. */
  35196. if( pDbFd->pShm==0 ){
  35197. rc = unixOpenSharedMemory(pDbFd);
  35198. if( rc!=SQLITE_OK ) return rc;
  35199. }
  35200. p = pDbFd->pShm;
  35201. pShmNode = p->pShmNode;
  35202. sqlite3_mutex_enter(pShmNode->pShmMutex);
  35203. if( pShmNode->isUnlocked ){
  35204. rc = unixLockSharedMemory(pDbFd, pShmNode);
  35205. if( rc!=SQLITE_OK ) goto shmpage_out;
  35206. pShmNode->isUnlocked = 0;
  35207. }
  35208. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  35209. assert( pShmNode->pInode==pDbFd->pInode );
  35210. assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
  35211. assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
  35212. /* Minimum number of regions required to be mapped. */
  35213. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  35214. if( pShmNode->nRegion<nReqRegion ){
  35215. char **apNew; /* New apRegion[] array */
  35216. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  35217. struct stat sStat; /* Used by fstat() */
  35218. pShmNode->szRegion = szRegion;
  35219. if( pShmNode->hShm>=0 ){
  35220. /* The requested region is not mapped into this processes address space.
  35221. ** Check to see if it has been allocated (i.e. if the wal-index file is
  35222. ** large enough to contain the requested region).
  35223. */
  35224. if( osFstat(pShmNode->hShm, &sStat) ){
  35225. rc = SQLITE_IOERR_SHMSIZE;
  35226. goto shmpage_out;
  35227. }
  35228. if( sStat.st_size<nByte ){
  35229. /* The requested memory region does not exist. If bExtend is set to
  35230. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  35231. */
  35232. if( !bExtend ){
  35233. goto shmpage_out;
  35234. }
  35235. /* Alternatively, if bExtend is true, extend the file. Do this by
  35236. ** writing a single byte to the end of each (OS) page being
  35237. ** allocated or extended. Technically, we need only write to the
  35238. ** last page in order to extend the file. But writing to all new
  35239. ** pages forces the OS to allocate them immediately, which reduces
  35240. ** the chances of SIGBUS while accessing the mapped region later on.
  35241. */
  35242. else{
  35243. static const int pgsz = 4096;
  35244. int iPg;
  35245. /* Write to the last byte of each newly allocated or extended page */
  35246. assert( (nByte % pgsz)==0 );
  35247. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  35248. int x = 0;
  35249. if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
  35250. const char *zFile = pShmNode->zFilename;
  35251. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  35252. goto shmpage_out;
  35253. }
  35254. }
  35255. }
  35256. }
  35257. }
  35258. /* Map the requested memory region into this processes address space. */
  35259. apNew = (char **)sqlite3_realloc(
  35260. pShmNode->apRegion, nReqRegion*sizeof(char *)
  35261. );
  35262. if( !apNew ){
  35263. rc = SQLITE_IOERR_NOMEM_BKPT;
  35264. goto shmpage_out;
  35265. }
  35266. pShmNode->apRegion = apNew;
  35267. while( pShmNode->nRegion<nReqRegion ){
  35268. int nMap = szRegion*nShmPerMap;
  35269. int i;
  35270. void *pMem;
  35271. if( pShmNode->hShm>=0 ){
  35272. pMem = osMmap(0, nMap,
  35273. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  35274. MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
  35275. );
  35276. if( pMem==MAP_FAILED ){
  35277. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  35278. goto shmpage_out;
  35279. }
  35280. }else{
  35281. pMem = sqlite3_malloc64(nMap);
  35282. if( pMem==0 ){
  35283. rc = SQLITE_NOMEM_BKPT;
  35284. goto shmpage_out;
  35285. }
  35286. memset(pMem, 0, nMap);
  35287. }
  35288. for(i=0; i<nShmPerMap; i++){
  35289. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  35290. }
  35291. pShmNode->nRegion += nShmPerMap;
  35292. }
  35293. }
  35294. shmpage_out:
  35295. if( pShmNode->nRegion>iRegion ){
  35296. *pp = pShmNode->apRegion[iRegion];
  35297. }else{
  35298. *pp = 0;
  35299. }
  35300. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  35301. sqlite3_mutex_leave(pShmNode->pShmMutex);
  35302. return rc;
  35303. }
  35304. /*
  35305. ** Change the lock state for a shared-memory segment.
  35306. **
  35307. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  35308. ** different here than in posix. In xShmLock(), one can go from unlocked
  35309. ** to shared and back or from unlocked to exclusive and back. But one may
  35310. ** not go from shared to exclusive or from exclusive to shared.
  35311. */
  35312. static int unixShmLock(
  35313. sqlite3_file *fd, /* Database file holding the shared memory */
  35314. int ofst, /* First lock to acquire or release */
  35315. int n, /* Number of locks to acquire or release */
  35316. int flags /* What to do with the lock */
  35317. ){
  35318. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  35319. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  35320. unixShm *pX; /* For looping over all siblings */
  35321. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  35322. int rc = SQLITE_OK; /* Result code */
  35323. u16 mask; /* Mask of locks to take or release */
  35324. assert( pShmNode==pDbFd->pInode->pShmNode );
  35325. assert( pShmNode->pInode==pDbFd->pInode );
  35326. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  35327. assert( n>=1 );
  35328. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  35329. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  35330. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  35331. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  35332. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  35333. assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
  35334. assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
  35335. mask = (1<<(ofst+n)) - (1<<ofst);
  35336. assert( n>1 || mask==(1<<ofst) );
  35337. sqlite3_mutex_enter(pShmNode->pShmMutex);
  35338. if( flags & SQLITE_SHM_UNLOCK ){
  35339. u16 allMask = 0; /* Mask of locks held by siblings */
  35340. /* See if any siblings hold this same lock */
  35341. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35342. if( pX==p ) continue;
  35343. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  35344. allMask |= pX->sharedMask;
  35345. }
  35346. /* Unlock the system-level locks */
  35347. if( (mask & allMask)==0 ){
  35348. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  35349. }else{
  35350. rc = SQLITE_OK;
  35351. }
  35352. /* Undo the local locks */
  35353. if( rc==SQLITE_OK ){
  35354. p->exclMask &= ~mask;
  35355. p->sharedMask &= ~mask;
  35356. }
  35357. }else if( flags & SQLITE_SHM_SHARED ){
  35358. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  35359. /* Find out which shared locks are already held by sibling connections.
  35360. ** If any sibling already holds an exclusive lock, go ahead and return
  35361. ** SQLITE_BUSY.
  35362. */
  35363. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35364. if( (pX->exclMask & mask)!=0 ){
  35365. rc = SQLITE_BUSY;
  35366. break;
  35367. }
  35368. allShared |= pX->sharedMask;
  35369. }
  35370. /* Get shared locks at the system level, if necessary */
  35371. if( rc==SQLITE_OK ){
  35372. if( (allShared & mask)==0 ){
  35373. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  35374. }else{
  35375. rc = SQLITE_OK;
  35376. }
  35377. }
  35378. /* Get the local shared locks */
  35379. if( rc==SQLITE_OK ){
  35380. p->sharedMask |= mask;
  35381. }
  35382. }else{
  35383. /* Make sure no sibling connections hold locks that will block this
  35384. ** lock. If any do, return SQLITE_BUSY right away.
  35385. */
  35386. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35387. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  35388. rc = SQLITE_BUSY;
  35389. break;
  35390. }
  35391. }
  35392. /* Get the exclusive locks at the system level. Then if successful
  35393. ** also mark the local connection as being locked.
  35394. */
  35395. if( rc==SQLITE_OK ){
  35396. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  35397. if( rc==SQLITE_OK ){
  35398. assert( (p->sharedMask & mask)==0 );
  35399. p->exclMask |= mask;
  35400. }
  35401. }
  35402. }
  35403. sqlite3_mutex_leave(pShmNode->pShmMutex);
  35404. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  35405. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  35406. return rc;
  35407. }
  35408. /*
  35409. ** Implement a memory barrier or memory fence on shared memory.
  35410. **
  35411. ** All loads and stores begun before the barrier must complete before
  35412. ** any load or store begun after the barrier.
  35413. */
  35414. static void unixShmBarrier(
  35415. sqlite3_file *fd /* Database file holding the shared memory */
  35416. ){
  35417. UNUSED_PARAMETER(fd);
  35418. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  35419. assert( fd->pMethods->xLock==nolockLock
  35420. || unixFileMutexNotheld((unixFile*)fd)
  35421. );
  35422. unixEnterMutex(); /* Also mutex, for redundancy */
  35423. unixLeaveMutex();
  35424. }
  35425. /*
  35426. ** Close a connection to shared-memory. Delete the underlying
  35427. ** storage if deleteFlag is true.
  35428. **
  35429. ** If there is no shared memory associated with the connection then this
  35430. ** routine is a harmless no-op.
  35431. */
  35432. static int unixShmUnmap(
  35433. sqlite3_file *fd, /* The underlying database file */
  35434. int deleteFlag /* Delete shared-memory if true */
  35435. ){
  35436. unixShm *p; /* The connection to be closed */
  35437. unixShmNode *pShmNode; /* The underlying shared-memory file */
  35438. unixShm **pp; /* For looping over sibling connections */
  35439. unixFile *pDbFd; /* The underlying database file */
  35440. pDbFd = (unixFile*)fd;
  35441. p = pDbFd->pShm;
  35442. if( p==0 ) return SQLITE_OK;
  35443. pShmNode = p->pShmNode;
  35444. assert( pShmNode==pDbFd->pInode->pShmNode );
  35445. assert( pShmNode->pInode==pDbFd->pInode );
  35446. /* Remove connection p from the set of connections associated
  35447. ** with pShmNode */
  35448. sqlite3_mutex_enter(pShmNode->pShmMutex);
  35449. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  35450. *pp = p->pNext;
  35451. /* Free the connection p */
  35452. sqlite3_free(p);
  35453. pDbFd->pShm = 0;
  35454. sqlite3_mutex_leave(pShmNode->pShmMutex);
  35455. /* If pShmNode->nRef has reached 0, then close the underlying
  35456. ** shared-memory file, too */
  35457. assert( unixFileMutexNotheld(pDbFd) );
  35458. unixEnterMutex();
  35459. assert( pShmNode->nRef>0 );
  35460. pShmNode->nRef--;
  35461. if( pShmNode->nRef==0 ){
  35462. if( deleteFlag && pShmNode->hShm>=0 ){
  35463. osUnlink(pShmNode->zFilename);
  35464. }
  35465. unixShmPurge(pDbFd);
  35466. }
  35467. unixLeaveMutex();
  35468. return SQLITE_OK;
  35469. }
  35470. #else
  35471. # define unixShmMap 0
  35472. # define unixShmLock 0
  35473. # define unixShmBarrier 0
  35474. # define unixShmUnmap 0
  35475. #endif /* #ifndef SQLITE_OMIT_WAL */
  35476. #if SQLITE_MAX_MMAP_SIZE>0
  35477. /*
  35478. ** If it is currently memory mapped, unmap file pFd.
  35479. */
  35480. static void unixUnmapfile(unixFile *pFd){
  35481. assert( pFd->nFetchOut==0 );
  35482. if( pFd->pMapRegion ){
  35483. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  35484. pFd->pMapRegion = 0;
  35485. pFd->mmapSize = 0;
  35486. pFd->mmapSizeActual = 0;
  35487. }
  35488. }
  35489. /*
  35490. ** Attempt to set the size of the memory mapping maintained by file
  35491. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  35492. **
  35493. ** If successful, this function sets the following variables:
  35494. **
  35495. ** unixFile.pMapRegion
  35496. ** unixFile.mmapSize
  35497. ** unixFile.mmapSizeActual
  35498. **
  35499. ** If unsuccessful, an error message is logged via sqlite3_log() and
  35500. ** the three variables above are zeroed. In this case SQLite should
  35501. ** continue accessing the database using the xRead() and xWrite()
  35502. ** methods.
  35503. */
  35504. static void unixRemapfile(
  35505. unixFile *pFd, /* File descriptor object */
  35506. i64 nNew /* Required mapping size */
  35507. ){
  35508. const char *zErr = "mmap";
  35509. int h = pFd->h; /* File descriptor open on db file */
  35510. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  35511. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  35512. u8 *pNew = 0; /* Location of new mapping */
  35513. int flags = PROT_READ; /* Flags to pass to mmap() */
  35514. assert( pFd->nFetchOut==0 );
  35515. assert( nNew>pFd->mmapSize );
  35516. assert( nNew<=pFd->mmapSizeMax );
  35517. assert( nNew>0 );
  35518. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  35519. assert( MAP_FAILED!=0 );
  35520. #ifdef SQLITE_MMAP_READWRITE
  35521. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  35522. #endif
  35523. if( pOrig ){
  35524. #if HAVE_MREMAP
  35525. i64 nReuse = pFd->mmapSize;
  35526. #else
  35527. const int szSyspage = osGetpagesize();
  35528. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  35529. #endif
  35530. u8 *pReq = &pOrig[nReuse];
  35531. /* Unmap any pages of the existing mapping that cannot be reused. */
  35532. if( nReuse!=nOrig ){
  35533. osMunmap(pReq, nOrig-nReuse);
  35534. }
  35535. #if HAVE_MREMAP
  35536. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  35537. zErr = "mremap";
  35538. #else
  35539. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  35540. if( pNew!=MAP_FAILED ){
  35541. if( pNew!=pReq ){
  35542. osMunmap(pNew, nNew - nReuse);
  35543. pNew = 0;
  35544. }else{
  35545. pNew = pOrig;
  35546. }
  35547. }
  35548. #endif
  35549. /* The attempt to extend the existing mapping failed. Free it. */
  35550. if( pNew==MAP_FAILED || pNew==0 ){
  35551. osMunmap(pOrig, nReuse);
  35552. }
  35553. }
  35554. /* If pNew is still NULL, try to create an entirely new mapping. */
  35555. if( pNew==0 ){
  35556. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  35557. }
  35558. if( pNew==MAP_FAILED ){
  35559. pNew = 0;
  35560. nNew = 0;
  35561. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  35562. /* If the mmap() above failed, assume that all subsequent mmap() calls
  35563. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  35564. ** in this case. */
  35565. pFd->mmapSizeMax = 0;
  35566. }
  35567. pFd->pMapRegion = (void *)pNew;
  35568. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  35569. }
  35570. /*
  35571. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  35572. ** is already mapped, the existing mapping is replaced by the new). Or, if
  35573. ** there already exists a mapping for this file, and there are still
  35574. ** outstanding xFetch() references to it, this function is a no-op.
  35575. **
  35576. ** If parameter nByte is non-negative, then it is the requested size of
  35577. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  35578. ** requested size is the size of the file on disk. The actual size of the
  35579. ** created mapping is either the requested size or the value configured
  35580. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  35581. **
  35582. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  35583. ** recreated as a result of outstanding references) or an SQLite error
  35584. ** code otherwise.
  35585. */
  35586. static int unixMapfile(unixFile *pFd, i64 nMap){
  35587. assert( nMap>=0 || pFd->nFetchOut==0 );
  35588. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  35589. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  35590. if( nMap<0 ){
  35591. struct stat statbuf; /* Low-level file information */
  35592. if( osFstat(pFd->h, &statbuf) ){
  35593. return SQLITE_IOERR_FSTAT;
  35594. }
  35595. nMap = statbuf.st_size;
  35596. }
  35597. if( nMap>pFd->mmapSizeMax ){
  35598. nMap = pFd->mmapSizeMax;
  35599. }
  35600. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  35601. if( nMap!=pFd->mmapSize ){
  35602. unixRemapfile(pFd, nMap);
  35603. }
  35604. return SQLITE_OK;
  35605. }
  35606. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  35607. /*
  35608. ** If possible, return a pointer to a mapping of file fd starting at offset
  35609. ** iOff. The mapping must be valid for at least nAmt bytes.
  35610. **
  35611. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  35612. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  35613. ** Finally, if an error does occur, return an SQLite error code. The final
  35614. ** value of *pp is undefined in this case.
  35615. **
  35616. ** If this function does return a pointer, the caller must eventually
  35617. ** release the reference by calling unixUnfetch().
  35618. */
  35619. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  35620. #if SQLITE_MAX_MMAP_SIZE>0
  35621. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  35622. #endif
  35623. *pp = 0;
  35624. #if SQLITE_MAX_MMAP_SIZE>0
  35625. if( pFd->mmapSizeMax>0 ){
  35626. if( pFd->pMapRegion==0 ){
  35627. int rc = unixMapfile(pFd, -1);
  35628. if( rc!=SQLITE_OK ) return rc;
  35629. }
  35630. if( pFd->mmapSize >= iOff+nAmt ){
  35631. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  35632. pFd->nFetchOut++;
  35633. }
  35634. }
  35635. #endif
  35636. return SQLITE_OK;
  35637. }
  35638. /*
  35639. ** If the third argument is non-NULL, then this function releases a
  35640. ** reference obtained by an earlier call to unixFetch(). The second
  35641. ** argument passed to this function must be the same as the corresponding
  35642. ** argument that was passed to the unixFetch() invocation.
  35643. **
  35644. ** Or, if the third argument is NULL, then this function is being called
  35645. ** to inform the VFS layer that, according to POSIX, any existing mapping
  35646. ** may now be invalid and should be unmapped.
  35647. */
  35648. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  35649. #if SQLITE_MAX_MMAP_SIZE>0
  35650. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  35651. UNUSED_PARAMETER(iOff);
  35652. /* If p==0 (unmap the entire file) then there must be no outstanding
  35653. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  35654. ** then there must be at least one outstanding. */
  35655. assert( (p==0)==(pFd->nFetchOut==0) );
  35656. /* If p!=0, it must match the iOff value. */
  35657. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  35658. if( p ){
  35659. pFd->nFetchOut--;
  35660. }else{
  35661. unixUnmapfile(pFd);
  35662. }
  35663. assert( pFd->nFetchOut>=0 );
  35664. #else
  35665. UNUSED_PARAMETER(fd);
  35666. UNUSED_PARAMETER(p);
  35667. UNUSED_PARAMETER(iOff);
  35668. #endif
  35669. return SQLITE_OK;
  35670. }
  35671. /*
  35672. ** Here ends the implementation of all sqlite3_file methods.
  35673. **
  35674. ********************** End sqlite3_file Methods *******************************
  35675. ******************************************************************************/
  35676. /*
  35677. ** This division contains definitions of sqlite3_io_methods objects that
  35678. ** implement various file locking strategies. It also contains definitions
  35679. ** of "finder" functions. A finder-function is used to locate the appropriate
  35680. ** sqlite3_io_methods object for a particular database file. The pAppData
  35681. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  35682. ** the correct finder-function for that VFS.
  35683. **
  35684. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  35685. ** object. The only interesting finder-function is autolockIoFinder, which
  35686. ** looks at the filesystem type and tries to guess the best locking
  35687. ** strategy from that.
  35688. **
  35689. ** For finder-function F, two objects are created:
  35690. **
  35691. ** (1) The real finder-function named "FImpt()".
  35692. **
  35693. ** (2) A constant pointer to this function named just "F".
  35694. **
  35695. **
  35696. ** A pointer to the F pointer is used as the pAppData value for VFS
  35697. ** objects. We have to do this instead of letting pAppData point
  35698. ** directly at the finder-function since C90 rules prevent a void*
  35699. ** from be cast into a function pointer.
  35700. **
  35701. **
  35702. ** Each instance of this macro generates two objects:
  35703. **
  35704. ** * A constant sqlite3_io_methods object call METHOD that has locking
  35705. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  35706. **
  35707. ** * An I/O method finder function called FINDER that returns a pointer
  35708. ** to the METHOD object in the previous bullet.
  35709. */
  35710. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  35711. static const sqlite3_io_methods METHOD = { \
  35712. VERSION, /* iVersion */ \
  35713. CLOSE, /* xClose */ \
  35714. unixRead, /* xRead */ \
  35715. unixWrite, /* xWrite */ \
  35716. unixTruncate, /* xTruncate */ \
  35717. unixSync, /* xSync */ \
  35718. unixFileSize, /* xFileSize */ \
  35719. LOCK, /* xLock */ \
  35720. UNLOCK, /* xUnlock */ \
  35721. CKLOCK, /* xCheckReservedLock */ \
  35722. unixFileControl, /* xFileControl */ \
  35723. unixSectorSize, /* xSectorSize */ \
  35724. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  35725. SHMMAP, /* xShmMap */ \
  35726. unixShmLock, /* xShmLock */ \
  35727. unixShmBarrier, /* xShmBarrier */ \
  35728. unixShmUnmap, /* xShmUnmap */ \
  35729. unixFetch, /* xFetch */ \
  35730. unixUnfetch, /* xUnfetch */ \
  35731. }; \
  35732. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  35733. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  35734. return &METHOD; \
  35735. } \
  35736. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  35737. = FINDER##Impl;
  35738. /*
  35739. ** Here are all of the sqlite3_io_methods objects for each of the
  35740. ** locking strategies. Functions that return pointers to these methods
  35741. ** are also created.
  35742. */
  35743. IOMETHODS(
  35744. posixIoFinder, /* Finder function name */
  35745. posixIoMethods, /* sqlite3_io_methods object name */
  35746. 3, /* shared memory and mmap are enabled */
  35747. unixClose, /* xClose method */
  35748. unixLock, /* xLock method */
  35749. unixUnlock, /* xUnlock method */
  35750. unixCheckReservedLock, /* xCheckReservedLock method */
  35751. unixShmMap /* xShmMap method */
  35752. )
  35753. IOMETHODS(
  35754. nolockIoFinder, /* Finder function name */
  35755. nolockIoMethods, /* sqlite3_io_methods object name */
  35756. 3, /* shared memory and mmap are enabled */
  35757. nolockClose, /* xClose method */
  35758. nolockLock, /* xLock method */
  35759. nolockUnlock, /* xUnlock method */
  35760. nolockCheckReservedLock, /* xCheckReservedLock method */
  35761. 0 /* xShmMap method */
  35762. )
  35763. IOMETHODS(
  35764. dotlockIoFinder, /* Finder function name */
  35765. dotlockIoMethods, /* sqlite3_io_methods object name */
  35766. 1, /* shared memory is disabled */
  35767. dotlockClose, /* xClose method */
  35768. dotlockLock, /* xLock method */
  35769. dotlockUnlock, /* xUnlock method */
  35770. dotlockCheckReservedLock, /* xCheckReservedLock method */
  35771. 0 /* xShmMap method */
  35772. )
  35773. #if SQLITE_ENABLE_LOCKING_STYLE
  35774. IOMETHODS(
  35775. flockIoFinder, /* Finder function name */
  35776. flockIoMethods, /* sqlite3_io_methods object name */
  35777. 1, /* shared memory is disabled */
  35778. flockClose, /* xClose method */
  35779. flockLock, /* xLock method */
  35780. flockUnlock, /* xUnlock method */
  35781. flockCheckReservedLock, /* xCheckReservedLock method */
  35782. 0 /* xShmMap method */
  35783. )
  35784. #endif
  35785. #if OS_VXWORKS
  35786. IOMETHODS(
  35787. semIoFinder, /* Finder function name */
  35788. semIoMethods, /* sqlite3_io_methods object name */
  35789. 1, /* shared memory is disabled */
  35790. semXClose, /* xClose method */
  35791. semXLock, /* xLock method */
  35792. semXUnlock, /* xUnlock method */
  35793. semXCheckReservedLock, /* xCheckReservedLock method */
  35794. 0 /* xShmMap method */
  35795. )
  35796. #endif
  35797. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35798. IOMETHODS(
  35799. afpIoFinder, /* Finder function name */
  35800. afpIoMethods, /* sqlite3_io_methods object name */
  35801. 1, /* shared memory is disabled */
  35802. afpClose, /* xClose method */
  35803. afpLock, /* xLock method */
  35804. afpUnlock, /* xUnlock method */
  35805. afpCheckReservedLock, /* xCheckReservedLock method */
  35806. 0 /* xShmMap method */
  35807. )
  35808. #endif
  35809. /*
  35810. ** The proxy locking method is a "super-method" in the sense that it
  35811. ** opens secondary file descriptors for the conch and lock files and
  35812. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  35813. ** secondary files. For this reason, the division that implements
  35814. ** proxy locking is located much further down in the file. But we need
  35815. ** to go ahead and define the sqlite3_io_methods and finder function
  35816. ** for proxy locking here. So we forward declare the I/O methods.
  35817. */
  35818. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35819. static int proxyClose(sqlite3_file*);
  35820. static int proxyLock(sqlite3_file*, int);
  35821. static int proxyUnlock(sqlite3_file*, int);
  35822. static int proxyCheckReservedLock(sqlite3_file*, int*);
  35823. IOMETHODS(
  35824. proxyIoFinder, /* Finder function name */
  35825. proxyIoMethods, /* sqlite3_io_methods object name */
  35826. 1, /* shared memory is disabled */
  35827. proxyClose, /* xClose method */
  35828. proxyLock, /* xLock method */
  35829. proxyUnlock, /* xUnlock method */
  35830. proxyCheckReservedLock, /* xCheckReservedLock method */
  35831. 0 /* xShmMap method */
  35832. )
  35833. #endif
  35834. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  35835. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35836. IOMETHODS(
  35837. nfsIoFinder, /* Finder function name */
  35838. nfsIoMethods, /* sqlite3_io_methods object name */
  35839. 1, /* shared memory is disabled */
  35840. unixClose, /* xClose method */
  35841. unixLock, /* xLock method */
  35842. nfsUnlock, /* xUnlock method */
  35843. unixCheckReservedLock, /* xCheckReservedLock method */
  35844. 0 /* xShmMap method */
  35845. )
  35846. #endif
  35847. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35848. /*
  35849. ** This "finder" function attempts to determine the best locking strategy
  35850. ** for the database file "filePath". It then returns the sqlite3_io_methods
  35851. ** object that implements that strategy.
  35852. **
  35853. ** This is for MacOSX only.
  35854. */
  35855. static const sqlite3_io_methods *autolockIoFinderImpl(
  35856. const char *filePath, /* name of the database file */
  35857. unixFile *pNew /* open file object for the database file */
  35858. ){
  35859. static const struct Mapping {
  35860. const char *zFilesystem; /* Filesystem type name */
  35861. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  35862. } aMap[] = {
  35863. { "hfs", &posixIoMethods },
  35864. { "ufs", &posixIoMethods },
  35865. { "afpfs", &afpIoMethods },
  35866. { "smbfs", &afpIoMethods },
  35867. { "webdav", &nolockIoMethods },
  35868. { 0, 0 }
  35869. };
  35870. int i;
  35871. struct statfs fsInfo;
  35872. struct flock lockInfo;
  35873. if( !filePath ){
  35874. /* If filePath==NULL that means we are dealing with a transient file
  35875. ** that does not need to be locked. */
  35876. return &nolockIoMethods;
  35877. }
  35878. if( statfs(filePath, &fsInfo) != -1 ){
  35879. if( fsInfo.f_flags & MNT_RDONLY ){
  35880. return &nolockIoMethods;
  35881. }
  35882. for(i=0; aMap[i].zFilesystem; i++){
  35883. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  35884. return aMap[i].pMethods;
  35885. }
  35886. }
  35887. }
  35888. /* Default case. Handles, amongst others, "nfs".
  35889. ** Test byte-range lock using fcntl(). If the call succeeds,
  35890. ** assume that the file-system supports POSIX style locks.
  35891. */
  35892. lockInfo.l_len = 1;
  35893. lockInfo.l_start = 0;
  35894. lockInfo.l_whence = SEEK_SET;
  35895. lockInfo.l_type = F_RDLCK;
  35896. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  35897. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  35898. return &nfsIoMethods;
  35899. } else {
  35900. return &posixIoMethods;
  35901. }
  35902. }else{
  35903. return &dotlockIoMethods;
  35904. }
  35905. }
  35906. static const sqlite3_io_methods
  35907. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  35908. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  35909. #if OS_VXWORKS
  35910. /*
  35911. ** This "finder" function for VxWorks checks to see if posix advisory
  35912. ** locking works. If it does, then that is what is used. If it does not
  35913. ** work, then fallback to named semaphore locking.
  35914. */
  35915. static const sqlite3_io_methods *vxworksIoFinderImpl(
  35916. const char *filePath, /* name of the database file */
  35917. unixFile *pNew /* the open file object */
  35918. ){
  35919. struct flock lockInfo;
  35920. if( !filePath ){
  35921. /* If filePath==NULL that means we are dealing with a transient file
  35922. ** that does not need to be locked. */
  35923. return &nolockIoMethods;
  35924. }
  35925. /* Test if fcntl() is supported and use POSIX style locks.
  35926. ** Otherwise fall back to the named semaphore method.
  35927. */
  35928. lockInfo.l_len = 1;
  35929. lockInfo.l_start = 0;
  35930. lockInfo.l_whence = SEEK_SET;
  35931. lockInfo.l_type = F_RDLCK;
  35932. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  35933. return &posixIoMethods;
  35934. }else{
  35935. return &semIoMethods;
  35936. }
  35937. }
  35938. static const sqlite3_io_methods
  35939. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  35940. #endif /* OS_VXWORKS */
  35941. /*
  35942. ** An abstract type for a pointer to an IO method finder function:
  35943. */
  35944. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  35945. /****************************************************************************
  35946. **************************** sqlite3_vfs methods ****************************
  35947. **
  35948. ** This division contains the implementation of methods on the
  35949. ** sqlite3_vfs object.
  35950. */
  35951. /*
  35952. ** Initialize the contents of the unixFile structure pointed to by pId.
  35953. */
  35954. static int fillInUnixFile(
  35955. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  35956. int h, /* Open file descriptor of file being opened */
  35957. sqlite3_file *pId, /* Write to the unixFile structure here */
  35958. const char *zFilename, /* Name of the file being opened */
  35959. int ctrlFlags /* Zero or more UNIXFILE_* values */
  35960. ){
  35961. const sqlite3_io_methods *pLockingStyle;
  35962. unixFile *pNew = (unixFile *)pId;
  35963. int rc = SQLITE_OK;
  35964. assert( pNew->pInode==NULL );
  35965. /* No locking occurs in temporary files */
  35966. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  35967. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  35968. pNew->h = h;
  35969. pNew->pVfs = pVfs;
  35970. pNew->zPath = zFilename;
  35971. pNew->ctrlFlags = (u8)ctrlFlags;
  35972. #if SQLITE_MAX_MMAP_SIZE>0
  35973. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  35974. #endif
  35975. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  35976. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  35977. pNew->ctrlFlags |= UNIXFILE_PSOW;
  35978. }
  35979. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  35980. pNew->ctrlFlags |= UNIXFILE_EXCL;
  35981. }
  35982. #if OS_VXWORKS
  35983. pNew->pId = vxworksFindFileId(zFilename);
  35984. if( pNew->pId==0 ){
  35985. ctrlFlags |= UNIXFILE_NOLOCK;
  35986. rc = SQLITE_NOMEM_BKPT;
  35987. }
  35988. #endif
  35989. if( ctrlFlags & UNIXFILE_NOLOCK ){
  35990. pLockingStyle = &nolockIoMethods;
  35991. }else{
  35992. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  35993. #if SQLITE_ENABLE_LOCKING_STYLE
  35994. /* Cache zFilename in the locking context (AFP and dotlock override) for
  35995. ** proxyLock activation is possible (remote proxy is based on db name)
  35996. ** zFilename remains valid until file is closed, to support */
  35997. pNew->lockingContext = (void*)zFilename;
  35998. #endif
  35999. }
  36000. if( pLockingStyle == &posixIoMethods
  36001. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  36002. || pLockingStyle == &nfsIoMethods
  36003. #endif
  36004. ){
  36005. unixEnterMutex();
  36006. rc = findInodeInfo(pNew, &pNew->pInode);
  36007. if( rc!=SQLITE_OK ){
  36008. /* If an error occurred in findInodeInfo(), close the file descriptor
  36009. ** immediately, before releasing the mutex. findInodeInfo() may fail
  36010. ** in two scenarios:
  36011. **
  36012. ** (a) A call to fstat() failed.
  36013. ** (b) A malloc failed.
  36014. **
  36015. ** Scenario (b) may only occur if the process is holding no other
  36016. ** file descriptors open on the same file. If there were other file
  36017. ** descriptors on this file, then no malloc would be required by
  36018. ** findInodeInfo(). If this is the case, it is quite safe to close
  36019. ** handle h - as it is guaranteed that no posix locks will be released
  36020. ** by doing so.
  36021. **
  36022. ** If scenario (a) caused the error then things are not so safe. The
  36023. ** implicit assumption here is that if fstat() fails, things are in
  36024. ** such bad shape that dropping a lock or two doesn't matter much.
  36025. */
  36026. robust_close(pNew, h, __LINE__);
  36027. h = -1;
  36028. }
  36029. unixLeaveMutex();
  36030. }
  36031. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  36032. else if( pLockingStyle == &afpIoMethods ){
  36033. /* AFP locking uses the file path so it needs to be included in
  36034. ** the afpLockingContext.
  36035. */
  36036. afpLockingContext *pCtx;
  36037. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  36038. if( pCtx==0 ){
  36039. rc = SQLITE_NOMEM_BKPT;
  36040. }else{
  36041. /* NB: zFilename exists and remains valid until the file is closed
  36042. ** according to requirement F11141. So we do not need to make a
  36043. ** copy of the filename. */
  36044. pCtx->dbPath = zFilename;
  36045. pCtx->reserved = 0;
  36046. srandomdev();
  36047. unixEnterMutex();
  36048. rc = findInodeInfo(pNew, &pNew->pInode);
  36049. if( rc!=SQLITE_OK ){
  36050. sqlite3_free(pNew->lockingContext);
  36051. robust_close(pNew, h, __LINE__);
  36052. h = -1;
  36053. }
  36054. unixLeaveMutex();
  36055. }
  36056. }
  36057. #endif
  36058. else if( pLockingStyle == &dotlockIoMethods ){
  36059. /* Dotfile locking uses the file path so it needs to be included in
  36060. ** the dotlockLockingContext
  36061. */
  36062. char *zLockFile;
  36063. int nFilename;
  36064. assert( zFilename!=0 );
  36065. nFilename = (int)strlen(zFilename) + 6;
  36066. zLockFile = (char *)sqlite3_malloc64(nFilename);
  36067. if( zLockFile==0 ){
  36068. rc = SQLITE_NOMEM_BKPT;
  36069. }else{
  36070. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  36071. }
  36072. pNew->lockingContext = zLockFile;
  36073. }
  36074. #if OS_VXWORKS
  36075. else if( pLockingStyle == &semIoMethods ){
  36076. /* Named semaphore locking uses the file path so it needs to be
  36077. ** included in the semLockingContext
  36078. */
  36079. unixEnterMutex();
  36080. rc = findInodeInfo(pNew, &pNew->pInode);
  36081. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  36082. char *zSemName = pNew->pInode->aSemName;
  36083. int n;
  36084. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  36085. pNew->pId->zCanonicalName);
  36086. for( n=1; zSemName[n]; n++ )
  36087. if( zSemName[n]=='/' ) zSemName[n] = '_';
  36088. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  36089. if( pNew->pInode->pSem == SEM_FAILED ){
  36090. rc = SQLITE_NOMEM_BKPT;
  36091. pNew->pInode->aSemName[0] = '\0';
  36092. }
  36093. }
  36094. unixLeaveMutex();
  36095. }
  36096. #endif
  36097. storeLastErrno(pNew, 0);
  36098. #if OS_VXWORKS
  36099. if( rc!=SQLITE_OK ){
  36100. if( h>=0 ) robust_close(pNew, h, __LINE__);
  36101. h = -1;
  36102. osUnlink(zFilename);
  36103. pNew->ctrlFlags |= UNIXFILE_DELETE;
  36104. }
  36105. #endif
  36106. if( rc!=SQLITE_OK ){
  36107. if( h>=0 ) robust_close(pNew, h, __LINE__);
  36108. }else{
  36109. pNew->pMethod = pLockingStyle;
  36110. OpenCounter(+1);
  36111. verifyDbFile(pNew);
  36112. }
  36113. return rc;
  36114. }
  36115. /*
  36116. ** Return the name of a directory in which to put temporary files.
  36117. ** If no suitable temporary file directory can be found, return NULL.
  36118. */
  36119. static const char *unixTempFileDir(void){
  36120. static const char *azDirs[] = {
  36121. 0,
  36122. 0,
  36123. "/var/tmp",
  36124. "/usr/tmp",
  36125. "/tmp",
  36126. "."
  36127. };
  36128. unsigned int i = 0;
  36129. struct stat buf;
  36130. const char *zDir = sqlite3_temp_directory;
  36131. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  36132. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  36133. while(1){
  36134. if( zDir!=0
  36135. && osStat(zDir, &buf)==0
  36136. && S_ISDIR(buf.st_mode)
  36137. && osAccess(zDir, 03)==0
  36138. ){
  36139. return zDir;
  36140. }
  36141. if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
  36142. zDir = azDirs[i++];
  36143. }
  36144. return 0;
  36145. }
  36146. /*
  36147. ** Create a temporary file name in zBuf. zBuf must be allocated
  36148. ** by the calling process and must be big enough to hold at least
  36149. ** pVfs->mxPathname bytes.
  36150. */
  36151. static int unixGetTempname(int nBuf, char *zBuf){
  36152. const char *zDir;
  36153. int iLimit = 0;
  36154. /* It's odd to simulate an io-error here, but really this is just
  36155. ** using the io-error infrastructure to test that SQLite handles this
  36156. ** function failing.
  36157. */
  36158. zBuf[0] = 0;
  36159. SimulateIOError( return SQLITE_IOERR );
  36160. zDir = unixTempFileDir();
  36161. if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
  36162. do{
  36163. u64 r;
  36164. sqlite3_randomness(sizeof(r), &r);
  36165. assert( nBuf>2 );
  36166. zBuf[nBuf-2] = 0;
  36167. sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
  36168. zDir, r, 0);
  36169. if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
  36170. }while( osAccess(zBuf,0)==0 );
  36171. return SQLITE_OK;
  36172. }
  36173. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  36174. /*
  36175. ** Routine to transform a unixFile into a proxy-locking unixFile.
  36176. ** Implementation in the proxy-lock division, but used by unixOpen()
  36177. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  36178. */
  36179. static int proxyTransformUnixFile(unixFile*, const char*);
  36180. #endif
  36181. /*
  36182. ** Search for an unused file descriptor that was opened on the database
  36183. ** file (not a journal or master-journal file) identified by pathname
  36184. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  36185. ** argument to this function.
  36186. **
  36187. ** Such a file descriptor may exist if a database connection was closed
  36188. ** but the associated file descriptor could not be closed because some
  36189. ** other file descriptor open on the same file is holding a file-lock.
  36190. ** Refer to comments in the unixClose() function and the lengthy comment
  36191. ** describing "Posix Advisory Locking" at the start of this file for
  36192. ** further details. Also, ticket #4018.
  36193. **
  36194. ** If a suitable file descriptor is found, then it is returned. If no
  36195. ** such file descriptor is located, -1 is returned.
  36196. */
  36197. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  36198. UnixUnusedFd *pUnused = 0;
  36199. /* Do not search for an unused file descriptor on vxworks. Not because
  36200. ** vxworks would not benefit from the change (it might, we're not sure),
  36201. ** but because no way to test it is currently available. It is better
  36202. ** not to risk breaking vxworks support for the sake of such an obscure
  36203. ** feature. */
  36204. #if !OS_VXWORKS
  36205. struct stat sStat; /* Results of stat() call */
  36206. unixEnterMutex();
  36207. /* A stat() call may fail for various reasons. If this happens, it is
  36208. ** almost certain that an open() call on the same path will also fail.
  36209. ** For this reason, if an error occurs in the stat() call here, it is
  36210. ** ignored and -1 is returned. The caller will try to open a new file
  36211. ** descriptor on the same path, fail, and return an error to SQLite.
  36212. **
  36213. ** Even if a subsequent open() call does succeed, the consequences of
  36214. ** not searching for a reusable file descriptor are not dire. */
  36215. if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
  36216. unixInodeInfo *pInode;
  36217. pInode = inodeList;
  36218. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  36219. || pInode->fileId.ino!=(u64)sStat.st_ino) ){
  36220. pInode = pInode->pNext;
  36221. }
  36222. if( pInode ){
  36223. UnixUnusedFd **pp;
  36224. assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
  36225. sqlite3_mutex_enter(pInode->pLockMutex);
  36226. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  36227. pUnused = *pp;
  36228. if( pUnused ){
  36229. *pp = pUnused->pNext;
  36230. }
  36231. sqlite3_mutex_leave(pInode->pLockMutex);
  36232. }
  36233. }
  36234. unixLeaveMutex();
  36235. #endif /* if !OS_VXWORKS */
  36236. return pUnused;
  36237. }
  36238. /*
  36239. ** Find the mode, uid and gid of file zFile.
  36240. */
  36241. static int getFileMode(
  36242. const char *zFile, /* File name */
  36243. mode_t *pMode, /* OUT: Permissions of zFile */
  36244. uid_t *pUid, /* OUT: uid of zFile. */
  36245. gid_t *pGid /* OUT: gid of zFile. */
  36246. ){
  36247. struct stat sStat; /* Output of stat() on database file */
  36248. int rc = SQLITE_OK;
  36249. if( 0==osStat(zFile, &sStat) ){
  36250. *pMode = sStat.st_mode & 0777;
  36251. *pUid = sStat.st_uid;
  36252. *pGid = sStat.st_gid;
  36253. }else{
  36254. rc = SQLITE_IOERR_FSTAT;
  36255. }
  36256. return rc;
  36257. }
  36258. /*
  36259. ** This function is called by unixOpen() to determine the unix permissions
  36260. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  36261. ** and a value suitable for passing as the third argument to open(2) is
  36262. ** written to *pMode. If an IO error occurs, an SQLite error code is
  36263. ** returned and the value of *pMode is not modified.
  36264. **
  36265. ** In most cases, this routine sets *pMode to 0, which will become
  36266. ** an indication to robust_open() to create the file using
  36267. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  36268. ** But if the file being opened is a WAL or regular journal file, then
  36269. ** this function queries the file-system for the permissions on the
  36270. ** corresponding database file and sets *pMode to this value. Whenever
  36271. ** possible, WAL and journal files are created using the same permissions
  36272. ** as the associated database file.
  36273. **
  36274. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  36275. ** original filename is unavailable. But 8_3_NAMES is only used for
  36276. ** FAT filesystems and permissions do not matter there, so just use
  36277. ** the default permissions.
  36278. */
  36279. static int findCreateFileMode(
  36280. const char *zPath, /* Path of file (possibly) being created */
  36281. int flags, /* Flags passed as 4th argument to xOpen() */
  36282. mode_t *pMode, /* OUT: Permissions to open file with */
  36283. uid_t *pUid, /* OUT: uid to set on the file */
  36284. gid_t *pGid /* OUT: gid to set on the file */
  36285. ){
  36286. int rc = SQLITE_OK; /* Return Code */
  36287. *pMode = 0;
  36288. *pUid = 0;
  36289. *pGid = 0;
  36290. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  36291. char zDb[MAX_PATHNAME+1]; /* Database file path */
  36292. int nDb; /* Number of valid bytes in zDb */
  36293. /* zPath is a path to a WAL or journal file. The following block derives
  36294. ** the path to the associated database file from zPath. This block handles
  36295. ** the following naming conventions:
  36296. **
  36297. ** "<path to db>-journal"
  36298. ** "<path to db>-wal"
  36299. ** "<path to db>-journalNN"
  36300. ** "<path to db>-walNN"
  36301. **
  36302. ** where NN is a decimal number. The NN naming schemes are
  36303. ** used by the test_multiplex.c module.
  36304. */
  36305. nDb = sqlite3Strlen30(zPath) - 1;
  36306. while( zPath[nDb]!='-' ){
  36307. /* In normal operation, the journal file name will always contain
  36308. ** a '-' character. However in 8+3 filename mode, or if a corrupt
  36309. ** rollback journal specifies a master journal with a goofy name, then
  36310. ** the '-' might be missing. */
  36311. if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  36312. nDb--;
  36313. }
  36314. memcpy(zDb, zPath, nDb);
  36315. zDb[nDb] = '\0';
  36316. rc = getFileMode(zDb, pMode, pUid, pGid);
  36317. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  36318. *pMode = 0600;
  36319. }else if( flags & SQLITE_OPEN_URI ){
  36320. /* If this is a main database file and the file was opened using a URI
  36321. ** filename, check for the "modeof" parameter. If present, interpret
  36322. ** its value as a filename and try to copy the mode, uid and gid from
  36323. ** that file. */
  36324. const char *z = sqlite3_uri_parameter(zPath, "modeof");
  36325. if( z ){
  36326. rc = getFileMode(z, pMode, pUid, pGid);
  36327. }
  36328. }
  36329. return rc;
  36330. }
  36331. /*
  36332. ** Open the file zPath.
  36333. **
  36334. ** Previously, the SQLite OS layer used three functions in place of this
  36335. ** one:
  36336. **
  36337. ** sqlite3OsOpenReadWrite();
  36338. ** sqlite3OsOpenReadOnly();
  36339. ** sqlite3OsOpenExclusive();
  36340. **
  36341. ** These calls correspond to the following combinations of flags:
  36342. **
  36343. ** ReadWrite() -> (READWRITE | CREATE)
  36344. ** ReadOnly() -> (READONLY)
  36345. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  36346. **
  36347. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  36348. ** true, the file was configured to be automatically deleted when the
  36349. ** file handle closed. To achieve the same effect using this new
  36350. ** interface, add the DELETEONCLOSE flag to those specified above for
  36351. ** OpenExclusive().
  36352. */
  36353. static int unixOpen(
  36354. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  36355. const char *zPath, /* Pathname of file to be opened */
  36356. sqlite3_file *pFile, /* The file descriptor to be filled in */
  36357. int flags, /* Input flags to control the opening */
  36358. int *pOutFlags /* Output flags returned to SQLite core */
  36359. ){
  36360. unixFile *p = (unixFile *)pFile;
  36361. int fd = -1; /* File descriptor returned by open() */
  36362. int openFlags = 0; /* Flags to pass to open() */
  36363. int eType = flags&0xFFFFFF00; /* Type of file to open */
  36364. int noLock; /* True to omit locking primitives */
  36365. int rc = SQLITE_OK; /* Function Return Code */
  36366. int ctrlFlags = 0; /* UNIXFILE_* flags */
  36367. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  36368. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  36369. int isCreate = (flags & SQLITE_OPEN_CREATE);
  36370. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  36371. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  36372. #if SQLITE_ENABLE_LOCKING_STYLE
  36373. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  36374. #endif
  36375. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  36376. struct statfs fsInfo;
  36377. #endif
  36378. /* If creating a master or main-file journal, this function will open
  36379. ** a file-descriptor on the directory too. The first time unixSync()
  36380. ** is called the directory file descriptor will be fsync()ed and close()d.
  36381. */
  36382. int isNewJrnl = (isCreate && (
  36383. eType==SQLITE_OPEN_MASTER_JOURNAL
  36384. || eType==SQLITE_OPEN_MAIN_JOURNAL
  36385. || eType==SQLITE_OPEN_WAL
  36386. ));
  36387. /* If argument zPath is a NULL pointer, this function is required to open
  36388. ** a temporary file. Use this buffer to store the file name in.
  36389. */
  36390. char zTmpname[MAX_PATHNAME+2];
  36391. const char *zName = zPath;
  36392. /* Check the following statements are true:
  36393. **
  36394. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  36395. ** (b) if CREATE is set, then READWRITE must also be set, and
  36396. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  36397. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  36398. */
  36399. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  36400. assert(isCreate==0 || isReadWrite);
  36401. assert(isExclusive==0 || isCreate);
  36402. assert(isDelete==0 || isCreate);
  36403. /* The main DB, main journal, WAL file and master journal are never
  36404. ** automatically deleted. Nor are they ever temporary files. */
  36405. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  36406. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  36407. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  36408. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  36409. /* Assert that the upper layer has set one of the "file-type" flags. */
  36410. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  36411. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  36412. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  36413. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  36414. );
  36415. /* Detect a pid change and reset the PRNG. There is a race condition
  36416. ** here such that two or more threads all trying to open databases at
  36417. ** the same instant might all reset the PRNG. But multiple resets
  36418. ** are harmless.
  36419. */
  36420. if( randomnessPid!=osGetpid(0) ){
  36421. randomnessPid = osGetpid(0);
  36422. sqlite3_randomness(0,0);
  36423. }
  36424. memset(p, 0, sizeof(unixFile));
  36425. if( eType==SQLITE_OPEN_MAIN_DB ){
  36426. UnixUnusedFd *pUnused;
  36427. pUnused = findReusableFd(zName, flags);
  36428. if( pUnused ){
  36429. fd = pUnused->fd;
  36430. }else{
  36431. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  36432. if( !pUnused ){
  36433. return SQLITE_NOMEM_BKPT;
  36434. }
  36435. }
  36436. p->pPreallocatedUnused = pUnused;
  36437. /* Database filenames are double-zero terminated if they are not
  36438. ** URIs with parameters. Hence, they can always be passed into
  36439. ** sqlite3_uri_parameter(). */
  36440. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  36441. }else if( !zName ){
  36442. /* If zName is NULL, the upper layer is requesting a temp file. */
  36443. assert(isDelete && !isNewJrnl);
  36444. rc = unixGetTempname(pVfs->mxPathname, zTmpname);
  36445. if( rc!=SQLITE_OK ){
  36446. return rc;
  36447. }
  36448. zName = zTmpname;
  36449. /* Generated temporary filenames are always double-zero terminated
  36450. ** for use by sqlite3_uri_parameter(). */
  36451. assert( zName[strlen(zName)+1]==0 );
  36452. }
  36453. /* Determine the value of the flags parameter passed to POSIX function
  36454. ** open(). These must be calculated even if open() is not called, as
  36455. ** they may be stored as part of the file handle and used by the
  36456. ** 'conch file' locking functions later on. */
  36457. if( isReadonly ) openFlags |= O_RDONLY;
  36458. if( isReadWrite ) openFlags |= O_RDWR;
  36459. if( isCreate ) openFlags |= O_CREAT;
  36460. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  36461. openFlags |= (O_LARGEFILE|O_BINARY);
  36462. if( fd<0 ){
  36463. mode_t openMode; /* Permissions to create file with */
  36464. uid_t uid; /* Userid for the file */
  36465. gid_t gid; /* Groupid for the file */
  36466. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  36467. if( rc!=SQLITE_OK ){
  36468. assert( !p->pPreallocatedUnused );
  36469. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  36470. return rc;
  36471. }
  36472. fd = robust_open(zName, openFlags, openMode);
  36473. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  36474. assert( !isExclusive || (openFlags & O_CREAT)!=0 );
  36475. if( fd<0 ){
  36476. if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
  36477. /* If unable to create a journal because the directory is not
  36478. ** writable, change the error code to indicate that. */
  36479. rc = SQLITE_READONLY_DIRECTORY;
  36480. }else if( errno!=EISDIR && isReadWrite ){
  36481. /* Failed to open the file for read/write access. Try read-only. */
  36482. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  36483. openFlags &= ~(O_RDWR|O_CREAT);
  36484. flags |= SQLITE_OPEN_READONLY;
  36485. openFlags |= O_RDONLY;
  36486. isReadonly = 1;
  36487. fd = robust_open(zName, openFlags, openMode);
  36488. }
  36489. }
  36490. if( fd<0 ){
  36491. int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  36492. if( rc==SQLITE_OK ) rc = rc2;
  36493. goto open_finished;
  36494. }
  36495. /* If this process is running as root and if creating a new rollback
  36496. ** journal or WAL file, set the ownership of the journal or WAL to be
  36497. ** the same as the original database.
  36498. */
  36499. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  36500. robustFchown(fd, uid, gid);
  36501. }
  36502. }
  36503. assert( fd>=0 );
  36504. if( pOutFlags ){
  36505. *pOutFlags = flags;
  36506. }
  36507. if( p->pPreallocatedUnused ){
  36508. p->pPreallocatedUnused->fd = fd;
  36509. p->pPreallocatedUnused->flags = flags;
  36510. }
  36511. if( isDelete ){
  36512. #if OS_VXWORKS
  36513. zPath = zName;
  36514. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  36515. zPath = sqlite3_mprintf("%s", zName);
  36516. if( zPath==0 ){
  36517. robust_close(p, fd, __LINE__);
  36518. return SQLITE_NOMEM_BKPT;
  36519. }
  36520. #else
  36521. osUnlink(zName);
  36522. #endif
  36523. }
  36524. #if SQLITE_ENABLE_LOCKING_STYLE
  36525. else{
  36526. p->openFlags = openFlags;
  36527. }
  36528. #endif
  36529. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  36530. if( fstatfs(fd, &fsInfo) == -1 ){
  36531. storeLastErrno(p, errno);
  36532. robust_close(p, fd, __LINE__);
  36533. return SQLITE_IOERR_ACCESS;
  36534. }
  36535. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  36536. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  36537. }
  36538. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  36539. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  36540. }
  36541. #endif
  36542. /* Set up appropriate ctrlFlags */
  36543. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  36544. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  36545. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  36546. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  36547. if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
  36548. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  36549. #if SQLITE_ENABLE_LOCKING_STYLE
  36550. #if SQLITE_PREFER_PROXY_LOCKING
  36551. isAutoProxy = 1;
  36552. #endif
  36553. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  36554. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  36555. int useProxy = 0;
  36556. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  36557. ** never use proxy, NULL means use proxy for non-local files only. */
  36558. if( envforce!=NULL ){
  36559. useProxy = atoi(envforce)>0;
  36560. }else{
  36561. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  36562. }
  36563. if( useProxy ){
  36564. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  36565. if( rc==SQLITE_OK ){
  36566. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  36567. if( rc!=SQLITE_OK ){
  36568. /* Use unixClose to clean up the resources added in fillInUnixFile
  36569. ** and clear all the structure's references. Specifically,
  36570. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  36571. */
  36572. unixClose(pFile);
  36573. return rc;
  36574. }
  36575. }
  36576. goto open_finished;
  36577. }
  36578. }
  36579. #endif
  36580. assert( zPath==0 || zPath[0]=='/'
  36581. || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
  36582. );
  36583. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  36584. open_finished:
  36585. if( rc!=SQLITE_OK ){
  36586. sqlite3_free(p->pPreallocatedUnused);
  36587. }
  36588. return rc;
  36589. }
  36590. /*
  36591. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  36592. ** the directory after deleting the file.
  36593. */
  36594. static int unixDelete(
  36595. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  36596. const char *zPath, /* Name of file to be deleted */
  36597. int dirSync /* If true, fsync() directory after deleting file */
  36598. ){
  36599. int rc = SQLITE_OK;
  36600. UNUSED_PARAMETER(NotUsed);
  36601. SimulateIOError(return SQLITE_IOERR_DELETE);
  36602. if( osUnlink(zPath)==(-1) ){
  36603. if( errno==ENOENT
  36604. #if OS_VXWORKS
  36605. || osAccess(zPath,0)!=0
  36606. #endif
  36607. ){
  36608. rc = SQLITE_IOERR_DELETE_NOENT;
  36609. }else{
  36610. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  36611. }
  36612. return rc;
  36613. }
  36614. #ifndef SQLITE_DISABLE_DIRSYNC
  36615. if( (dirSync & 1)!=0 ){
  36616. int fd;
  36617. rc = osOpenDirectory(zPath, &fd);
  36618. if( rc==SQLITE_OK ){
  36619. if( full_fsync(fd,0,0) ){
  36620. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  36621. }
  36622. robust_close(0, fd, __LINE__);
  36623. }else{
  36624. assert( rc==SQLITE_CANTOPEN );
  36625. rc = SQLITE_OK;
  36626. }
  36627. }
  36628. #endif
  36629. return rc;
  36630. }
  36631. /*
  36632. ** Test the existence of or access permissions of file zPath. The
  36633. ** test performed depends on the value of flags:
  36634. **
  36635. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  36636. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  36637. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  36638. **
  36639. ** Otherwise return 0.
  36640. */
  36641. static int unixAccess(
  36642. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  36643. const char *zPath, /* Path of the file to examine */
  36644. int flags, /* What do we want to learn about the zPath file? */
  36645. int *pResOut /* Write result boolean here */
  36646. ){
  36647. UNUSED_PARAMETER(NotUsed);
  36648. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  36649. assert( pResOut!=0 );
  36650. /* The spec says there are three possible values for flags. But only
  36651. ** two of them are actually used */
  36652. assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
  36653. if( flags==SQLITE_ACCESS_EXISTS ){
  36654. struct stat buf;
  36655. *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
  36656. }else{
  36657. *pResOut = osAccess(zPath, W_OK|R_OK)==0;
  36658. }
  36659. return SQLITE_OK;
  36660. }
  36661. /*
  36662. **
  36663. */
  36664. static int mkFullPathname(
  36665. const char *zPath, /* Input path */
  36666. char *zOut, /* Output buffer */
  36667. int nOut /* Allocated size of buffer zOut */
  36668. ){
  36669. int nPath = sqlite3Strlen30(zPath);
  36670. int iOff = 0;
  36671. if( zPath[0]!='/' ){
  36672. if( osGetcwd(zOut, nOut-2)==0 ){
  36673. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  36674. }
  36675. iOff = sqlite3Strlen30(zOut);
  36676. zOut[iOff++] = '/';
  36677. }
  36678. if( (iOff+nPath+1)>nOut ){
  36679. /* SQLite assumes that xFullPathname() nul-terminates the output buffer
  36680. ** even if it returns an error. */
  36681. zOut[iOff] = '\0';
  36682. return SQLITE_CANTOPEN_BKPT;
  36683. }
  36684. sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
  36685. return SQLITE_OK;
  36686. }
  36687. /*
  36688. ** Turn a relative pathname into a full pathname. The relative path
  36689. ** is stored as a nul-terminated string in the buffer pointed to by
  36690. ** zPath.
  36691. **
  36692. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  36693. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  36694. ** this buffer before returning.
  36695. */
  36696. static int unixFullPathname(
  36697. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  36698. const char *zPath, /* Possibly relative input path */
  36699. int nOut, /* Size of output buffer in bytes */
  36700. char *zOut /* Output buffer */
  36701. ){
  36702. #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
  36703. return mkFullPathname(zPath, zOut, nOut);
  36704. #else
  36705. int rc = SQLITE_OK;
  36706. int nByte;
  36707. int nLink = 1; /* Number of symbolic links followed so far */
  36708. const char *zIn = zPath; /* Input path for each iteration of loop */
  36709. char *zDel = 0;
  36710. assert( pVfs->mxPathname==MAX_PATHNAME );
  36711. UNUSED_PARAMETER(pVfs);
  36712. /* It's odd to simulate an io-error here, but really this is just
  36713. ** using the io-error infrastructure to test that SQLite handles this
  36714. ** function failing. This function could fail if, for example, the
  36715. ** current working directory has been unlinked.
  36716. */
  36717. SimulateIOError( return SQLITE_ERROR );
  36718. do {
  36719. /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
  36720. ** link, or false otherwise. */
  36721. int bLink = 0;
  36722. struct stat buf;
  36723. if( osLstat(zIn, &buf)!=0 ){
  36724. if( errno!=ENOENT ){
  36725. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
  36726. }
  36727. }else{
  36728. bLink = S_ISLNK(buf.st_mode);
  36729. }
  36730. if( bLink ){
  36731. if( zDel==0 ){
  36732. zDel = sqlite3_malloc(nOut);
  36733. if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
  36734. }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
  36735. rc = SQLITE_CANTOPEN_BKPT;
  36736. }
  36737. if( rc==SQLITE_OK ){
  36738. nByte = osReadlink(zIn, zDel, nOut-1);
  36739. if( nByte<0 ){
  36740. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
  36741. }else{
  36742. if( zDel[0]!='/' ){
  36743. int n;
  36744. for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
  36745. if( nByte+n+1>nOut ){
  36746. rc = SQLITE_CANTOPEN_BKPT;
  36747. }else{
  36748. memmove(&zDel[n], zDel, nByte+1);
  36749. memcpy(zDel, zIn, n);
  36750. nByte += n;
  36751. }
  36752. }
  36753. zDel[nByte] = '\0';
  36754. }
  36755. }
  36756. zIn = zDel;
  36757. }
  36758. assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
  36759. if( rc==SQLITE_OK && zIn!=zOut ){
  36760. rc = mkFullPathname(zIn, zOut, nOut);
  36761. }
  36762. if( bLink==0 ) break;
  36763. zIn = zOut;
  36764. }while( rc==SQLITE_OK );
  36765. sqlite3_free(zDel);
  36766. return rc;
  36767. #endif /* HAVE_READLINK && HAVE_LSTAT */
  36768. }
  36769. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  36770. /*
  36771. ** Interfaces for opening a shared library, finding entry points
  36772. ** within the shared library, and closing the shared library.
  36773. */
  36774. #include <dlfcn.h>
  36775. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  36776. UNUSED_PARAMETER(NotUsed);
  36777. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  36778. }
  36779. /*
  36780. ** SQLite calls this function immediately after a call to unixDlSym() or
  36781. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  36782. ** message is available, it is written to zBufOut. If no error message
  36783. ** is available, zBufOut is left unmodified and SQLite uses a default
  36784. ** error message.
  36785. */
  36786. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  36787. const char *zErr;
  36788. UNUSED_PARAMETER(NotUsed);
  36789. unixEnterMutex();
  36790. zErr = dlerror();
  36791. if( zErr ){
  36792. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  36793. }
  36794. unixLeaveMutex();
  36795. }
  36796. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  36797. /*
  36798. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  36799. ** cast into a pointer to a function. And yet the library dlsym() routine
  36800. ** returns a void* which is really a pointer to a function. So how do we
  36801. ** use dlsym() with -pedantic-errors?
  36802. **
  36803. ** Variable x below is defined to be a pointer to a function taking
  36804. ** parameters void* and const char* and returning a pointer to a function.
  36805. ** We initialize x by assigning it a pointer to the dlsym() function.
  36806. ** (That assignment requires a cast.) Then we call the function that
  36807. ** x points to.
  36808. **
  36809. ** This work-around is unlikely to work correctly on any system where
  36810. ** you really cannot cast a function pointer into void*. But then, on the
  36811. ** other hand, dlsym() will not work on such a system either, so we have
  36812. ** not really lost anything.
  36813. */
  36814. void (*(*x)(void*,const char*))(void);
  36815. UNUSED_PARAMETER(NotUsed);
  36816. x = (void(*(*)(void*,const char*))(void))dlsym;
  36817. return (*x)(p, zSym);
  36818. }
  36819. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  36820. UNUSED_PARAMETER(NotUsed);
  36821. dlclose(pHandle);
  36822. }
  36823. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  36824. #define unixDlOpen 0
  36825. #define unixDlError 0
  36826. #define unixDlSym 0
  36827. #define unixDlClose 0
  36828. #endif
  36829. /*
  36830. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  36831. */
  36832. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  36833. UNUSED_PARAMETER(NotUsed);
  36834. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  36835. /* We have to initialize zBuf to prevent valgrind from reporting
  36836. ** errors. The reports issued by valgrind are incorrect - we would
  36837. ** prefer that the randomness be increased by making use of the
  36838. ** uninitialized space in zBuf - but valgrind errors tend to worry
  36839. ** some users. Rather than argue, it seems easier just to initialize
  36840. ** the whole array and silence valgrind, even if that means less randomness
  36841. ** in the random seed.
  36842. **
  36843. ** When testing, initializing zBuf[] to zero is all we do. That means
  36844. ** that we always use the same random number sequence. This makes the
  36845. ** tests repeatable.
  36846. */
  36847. memset(zBuf, 0, nBuf);
  36848. randomnessPid = osGetpid(0);
  36849. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  36850. {
  36851. int fd, got;
  36852. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  36853. if( fd<0 ){
  36854. time_t t;
  36855. time(&t);
  36856. memcpy(zBuf, &t, sizeof(t));
  36857. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  36858. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  36859. nBuf = sizeof(t) + sizeof(randomnessPid);
  36860. }else{
  36861. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  36862. robust_close(0, fd, __LINE__);
  36863. }
  36864. }
  36865. #endif
  36866. return nBuf;
  36867. }
  36868. /*
  36869. ** Sleep for a little while. Return the amount of time slept.
  36870. ** The argument is the number of microseconds we want to sleep.
  36871. ** The return value is the number of microseconds of sleep actually
  36872. ** requested from the underlying operating system, a number which
  36873. ** might be greater than or equal to the argument, but not less
  36874. ** than the argument.
  36875. */
  36876. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  36877. #if OS_VXWORKS
  36878. struct timespec sp;
  36879. sp.tv_sec = microseconds / 1000000;
  36880. sp.tv_nsec = (microseconds % 1000000) * 1000;
  36881. nanosleep(&sp, NULL);
  36882. UNUSED_PARAMETER(NotUsed);
  36883. return microseconds;
  36884. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  36885. usleep(microseconds);
  36886. UNUSED_PARAMETER(NotUsed);
  36887. return microseconds;
  36888. #else
  36889. int seconds = (microseconds+999999)/1000000;
  36890. sleep(seconds);
  36891. UNUSED_PARAMETER(NotUsed);
  36892. return seconds*1000000;
  36893. #endif
  36894. }
  36895. /*
  36896. ** The following variable, if set to a non-zero value, is interpreted as
  36897. ** the number of seconds since 1970 and is used to set the result of
  36898. ** sqlite3OsCurrentTime() during testing.
  36899. */
  36900. #ifdef SQLITE_TEST
  36901. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  36902. #endif
  36903. /*
  36904. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  36905. ** the current time and date as a Julian Day number times 86_400_000. In
  36906. ** other words, write into *piNow the number of milliseconds since the Julian
  36907. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  36908. ** proleptic Gregorian calendar.
  36909. **
  36910. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  36911. ** cannot be found.
  36912. */
  36913. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  36914. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  36915. int rc = SQLITE_OK;
  36916. #if defined(NO_GETTOD)
  36917. time_t t;
  36918. time(&t);
  36919. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  36920. #elif OS_VXWORKS
  36921. struct timespec sNow;
  36922. clock_gettime(CLOCK_REALTIME, &sNow);
  36923. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  36924. #else
  36925. struct timeval sNow;
  36926. (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
  36927. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  36928. #endif
  36929. #ifdef SQLITE_TEST
  36930. if( sqlite3_current_time ){
  36931. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  36932. }
  36933. #endif
  36934. UNUSED_PARAMETER(NotUsed);
  36935. return rc;
  36936. }
  36937. #ifndef SQLITE_OMIT_DEPRECATED
  36938. /*
  36939. ** Find the current time (in Universal Coordinated Time). Write the
  36940. ** current time and date as a Julian Day number into *prNow and
  36941. ** return 0. Return 1 if the time and date cannot be found.
  36942. */
  36943. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  36944. sqlite3_int64 i = 0;
  36945. int rc;
  36946. UNUSED_PARAMETER(NotUsed);
  36947. rc = unixCurrentTimeInt64(0, &i);
  36948. *prNow = i/86400000.0;
  36949. return rc;
  36950. }
  36951. #else
  36952. # define unixCurrentTime 0
  36953. #endif
  36954. /*
  36955. ** The xGetLastError() method is designed to return a better
  36956. ** low-level error message when operating-system problems come up
  36957. ** during SQLite operation. Only the integer return code is currently
  36958. ** used.
  36959. */
  36960. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  36961. UNUSED_PARAMETER(NotUsed);
  36962. UNUSED_PARAMETER(NotUsed2);
  36963. UNUSED_PARAMETER(NotUsed3);
  36964. return errno;
  36965. }
  36966. /*
  36967. ************************ End of sqlite3_vfs methods ***************************
  36968. ******************************************************************************/
  36969. /******************************************************************************
  36970. ************************** Begin Proxy Locking ********************************
  36971. **
  36972. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  36973. ** other locking methods on secondary lock files. Proxy locking is a
  36974. ** meta-layer over top of the primitive locking implemented above. For
  36975. ** this reason, the division that implements of proxy locking is deferred
  36976. ** until late in the file (here) after all of the other I/O methods have
  36977. ** been defined - so that the primitive locking methods are available
  36978. ** as services to help with the implementation of proxy locking.
  36979. **
  36980. ****
  36981. **
  36982. ** The default locking schemes in SQLite use byte-range locks on the
  36983. ** database file to coordinate safe, concurrent access by multiple readers
  36984. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  36985. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  36986. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  36987. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  36988. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  36989. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  36990. ** address in the shared range is taken for a SHARED lock, the entire
  36991. ** shared range is taken for an EXCLUSIVE lock):
  36992. **
  36993. ** PENDING_BYTE 0x40000000
  36994. ** RESERVED_BYTE 0x40000001
  36995. ** SHARED_RANGE 0x40000002 -> 0x40000200
  36996. **
  36997. ** This works well on the local file system, but shows a nearly 100x
  36998. ** slowdown in read performance on AFP because the AFP client disables
  36999. ** the read cache when byte-range locks are present. Enabling the read
  37000. ** cache exposes a cache coherency problem that is present on all OS X
  37001. ** supported network file systems. NFS and AFP both observe the
  37002. ** close-to-open semantics for ensuring cache coherency
  37003. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  37004. ** address the requirements for concurrent database access by multiple
  37005. ** readers and writers
  37006. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  37007. **
  37008. ** To address the performance and cache coherency issues, proxy file locking
  37009. ** changes the way database access is controlled by limiting access to a
  37010. ** single host at a time and moving file locks off of the database file
  37011. ** and onto a proxy file on the local file system.
  37012. **
  37013. **
  37014. ** Using proxy locks
  37015. ** -----------------
  37016. **
  37017. ** C APIs
  37018. **
  37019. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  37020. ** <proxy_path> | ":auto:");
  37021. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  37022. ** &<proxy_path>);
  37023. **
  37024. **
  37025. ** SQL pragmas
  37026. **
  37027. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  37028. ** PRAGMA [database.]lock_proxy_file
  37029. **
  37030. ** Specifying ":auto:" means that if there is a conch file with a matching
  37031. ** host ID in it, the proxy path in the conch file will be used, otherwise
  37032. ** a proxy path based on the user's temp dir
  37033. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  37034. ** actual proxy file name is generated from the name and path of the
  37035. ** database file. For example:
  37036. **
  37037. ** For database path "/Users/me/foo.db"
  37038. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  37039. **
  37040. ** Once a lock proxy is configured for a database connection, it can not
  37041. ** be removed, however it may be switched to a different proxy path via
  37042. ** the above APIs (assuming the conch file is not being held by another
  37043. ** connection or process).
  37044. **
  37045. **
  37046. ** How proxy locking works
  37047. ** -----------------------
  37048. **
  37049. ** Proxy file locking relies primarily on two new supporting files:
  37050. **
  37051. ** * conch file to limit access to the database file to a single host
  37052. ** at a time
  37053. **
  37054. ** * proxy file to act as a proxy for the advisory locks normally
  37055. ** taken on the database
  37056. **
  37057. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  37058. ** by taking an sqlite-style shared lock on the conch file, reading the
  37059. ** contents and comparing the host's unique host ID (see below) and lock
  37060. ** proxy path against the values stored in the conch. The conch file is
  37061. ** stored in the same directory as the database file and the file name
  37062. ** is patterned after the database file name as ".<databasename>-conch".
  37063. ** If the conch file does not exist, or its contents do not match the
  37064. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  37065. ** lock and the conch file contents is updated with the host ID and proxy
  37066. ** path and the lock is downgraded to a shared lock again. If the conch
  37067. ** is held by another process (with a shared lock), the exclusive lock
  37068. ** will fail and SQLITE_BUSY is returned.
  37069. **
  37070. ** The proxy file - a single-byte file used for all advisory file locks
  37071. ** normally taken on the database file. This allows for safe sharing
  37072. ** of the database file for multiple readers and writers on the same
  37073. ** host (the conch ensures that they all use the same local lock file).
  37074. **
  37075. ** Requesting the lock proxy does not immediately take the conch, it is
  37076. ** only taken when the first request to lock database file is made.
  37077. ** This matches the semantics of the traditional locking behavior, where
  37078. ** opening a connection to a database file does not take a lock on it.
  37079. ** The shared lock and an open file descriptor are maintained until
  37080. ** the connection to the database is closed.
  37081. **
  37082. ** The proxy file and the lock file are never deleted so they only need
  37083. ** to be created the first time they are used.
  37084. **
  37085. ** Configuration options
  37086. ** ---------------------
  37087. **
  37088. ** SQLITE_PREFER_PROXY_LOCKING
  37089. **
  37090. ** Database files accessed on non-local file systems are
  37091. ** automatically configured for proxy locking, lock files are
  37092. ** named automatically using the same logic as
  37093. ** PRAGMA lock_proxy_file=":auto:"
  37094. **
  37095. ** SQLITE_PROXY_DEBUG
  37096. **
  37097. ** Enables the logging of error messages during host id file
  37098. ** retrieval and creation
  37099. **
  37100. ** LOCKPROXYDIR
  37101. **
  37102. ** Overrides the default directory used for lock proxy files that
  37103. ** are named automatically via the ":auto:" setting
  37104. **
  37105. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  37106. **
  37107. ** Permissions to use when creating a directory for storing the
  37108. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  37109. **
  37110. **
  37111. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  37112. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  37113. ** force proxy locking to be used for every database file opened, and 0
  37114. ** will force automatic proxy locking to be disabled for all database
  37115. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  37116. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  37117. */
  37118. /*
  37119. ** Proxy locking is only available on MacOSX
  37120. */
  37121. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  37122. /*
  37123. ** The proxyLockingContext has the path and file structures for the remote
  37124. ** and local proxy files in it
  37125. */
  37126. typedef struct proxyLockingContext proxyLockingContext;
  37127. struct proxyLockingContext {
  37128. unixFile *conchFile; /* Open conch file */
  37129. char *conchFilePath; /* Name of the conch file */
  37130. unixFile *lockProxy; /* Open proxy lock file */
  37131. char *lockProxyPath; /* Name of the proxy lock file */
  37132. char *dbPath; /* Name of the open file */
  37133. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  37134. int nFails; /* Number of conch taking failures */
  37135. void *oldLockingContext; /* Original lockingcontext to restore on close */
  37136. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  37137. };
  37138. /*
  37139. ** The proxy lock file path for the database at dbPath is written into lPath,
  37140. ** which must point to valid, writable memory large enough for a maxLen length
  37141. ** file path.
  37142. */
  37143. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  37144. int len;
  37145. int dbLen;
  37146. int i;
  37147. #ifdef LOCKPROXYDIR
  37148. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  37149. #else
  37150. # ifdef _CS_DARWIN_USER_TEMP_DIR
  37151. {
  37152. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  37153. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  37154. lPath, errno, osGetpid(0)));
  37155. return SQLITE_IOERR_LOCK;
  37156. }
  37157. len = strlcat(lPath, "sqliteplocks", maxLen);
  37158. }
  37159. # else
  37160. len = strlcpy(lPath, "/tmp/", maxLen);
  37161. # endif
  37162. #endif
  37163. if( lPath[len-1]!='/' ){
  37164. len = strlcat(lPath, "/", maxLen);
  37165. }
  37166. /* transform the db path to a unique cache name */
  37167. dbLen = (int)strlen(dbPath);
  37168. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  37169. char c = dbPath[i];
  37170. lPath[i+len] = (c=='/')?'_':c;
  37171. }
  37172. lPath[i+len]='\0';
  37173. strlcat(lPath, ":auto:", maxLen);
  37174. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  37175. return SQLITE_OK;
  37176. }
  37177. /*
  37178. ** Creates the lock file and any missing directories in lockPath
  37179. */
  37180. static int proxyCreateLockPath(const char *lockPath){
  37181. int i, len;
  37182. char buf[MAXPATHLEN];
  37183. int start = 0;
  37184. assert(lockPath!=NULL);
  37185. /* try to create all the intermediate directories */
  37186. len = (int)strlen(lockPath);
  37187. buf[0] = lockPath[0];
  37188. for( i=1; i<len; i++ ){
  37189. if( lockPath[i] == '/' && (i - start > 0) ){
  37190. /* only mkdir if leaf dir != "." or "/" or ".." */
  37191. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  37192. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  37193. buf[i]='\0';
  37194. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  37195. int err=errno;
  37196. if( err!=EEXIST ) {
  37197. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  37198. "'%s' proxy lock path=%s pid=%d\n",
  37199. buf, strerror(err), lockPath, osGetpid(0)));
  37200. return err;
  37201. }
  37202. }
  37203. }
  37204. start=i+1;
  37205. }
  37206. buf[i] = lockPath[i];
  37207. }
  37208. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
  37209. return 0;
  37210. }
  37211. /*
  37212. ** Create a new VFS file descriptor (stored in memory obtained from
  37213. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  37214. **
  37215. ** The caller is responsible not only for closing the file descriptor
  37216. ** but also for freeing the memory associated with the file descriptor.
  37217. */
  37218. static int proxyCreateUnixFile(
  37219. const char *path, /* path for the new unixFile */
  37220. unixFile **ppFile, /* unixFile created and returned by ref */
  37221. int islockfile /* if non zero missing dirs will be created */
  37222. ) {
  37223. int fd = -1;
  37224. unixFile *pNew;
  37225. int rc = SQLITE_OK;
  37226. int openFlags = O_RDWR | O_CREAT;
  37227. sqlite3_vfs dummyVfs;
  37228. int terrno = 0;
  37229. UnixUnusedFd *pUnused = NULL;
  37230. /* 1. first try to open/create the file
  37231. ** 2. if that fails, and this is a lock file (not-conch), try creating
  37232. ** the parent directories and then try again.
  37233. ** 3. if that fails, try to open the file read-only
  37234. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  37235. */
  37236. pUnused = findReusableFd(path, openFlags);
  37237. if( pUnused ){
  37238. fd = pUnused->fd;
  37239. }else{
  37240. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  37241. if( !pUnused ){
  37242. return SQLITE_NOMEM_BKPT;
  37243. }
  37244. }
  37245. if( fd<0 ){
  37246. fd = robust_open(path, openFlags, 0);
  37247. terrno = errno;
  37248. if( fd<0 && errno==ENOENT && islockfile ){
  37249. if( proxyCreateLockPath(path) == SQLITE_OK ){
  37250. fd = robust_open(path, openFlags, 0);
  37251. }
  37252. }
  37253. }
  37254. if( fd<0 ){
  37255. openFlags = O_RDONLY;
  37256. fd = robust_open(path, openFlags, 0);
  37257. terrno = errno;
  37258. }
  37259. if( fd<0 ){
  37260. if( islockfile ){
  37261. return SQLITE_BUSY;
  37262. }
  37263. switch (terrno) {
  37264. case EACCES:
  37265. return SQLITE_PERM;
  37266. case EIO:
  37267. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  37268. default:
  37269. return SQLITE_CANTOPEN_BKPT;
  37270. }
  37271. }
  37272. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  37273. if( pNew==NULL ){
  37274. rc = SQLITE_NOMEM_BKPT;
  37275. goto end_create_proxy;
  37276. }
  37277. memset(pNew, 0, sizeof(unixFile));
  37278. pNew->openFlags = openFlags;
  37279. memset(&dummyVfs, 0, sizeof(dummyVfs));
  37280. dummyVfs.pAppData = (void*)&autolockIoFinder;
  37281. dummyVfs.zName = "dummy";
  37282. pUnused->fd = fd;
  37283. pUnused->flags = openFlags;
  37284. pNew->pPreallocatedUnused = pUnused;
  37285. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  37286. if( rc==SQLITE_OK ){
  37287. *ppFile = pNew;
  37288. return SQLITE_OK;
  37289. }
  37290. end_create_proxy:
  37291. robust_close(pNew, fd, __LINE__);
  37292. sqlite3_free(pNew);
  37293. sqlite3_free(pUnused);
  37294. return rc;
  37295. }
  37296. #ifdef SQLITE_TEST
  37297. /* simulate multiple hosts by creating unique hostid file paths */
  37298. SQLITE_API int sqlite3_hostid_num = 0;
  37299. #endif
  37300. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  37301. #ifdef HAVE_GETHOSTUUID
  37302. /* Not always defined in the headers as it ought to be */
  37303. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  37304. #endif
  37305. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  37306. ** bytes of writable memory.
  37307. */
  37308. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  37309. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  37310. memset(pHostID, 0, PROXY_HOSTIDLEN);
  37311. #ifdef HAVE_GETHOSTUUID
  37312. {
  37313. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  37314. if( gethostuuid(pHostID, &timeout) ){
  37315. int err = errno;
  37316. if( pError ){
  37317. *pError = err;
  37318. }
  37319. return SQLITE_IOERR;
  37320. }
  37321. }
  37322. #else
  37323. UNUSED_PARAMETER(pError);
  37324. #endif
  37325. #ifdef SQLITE_TEST
  37326. /* simulate multiple hosts by creating unique hostid file paths */
  37327. if( sqlite3_hostid_num != 0){
  37328. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  37329. }
  37330. #endif
  37331. return SQLITE_OK;
  37332. }
  37333. /* The conch file contains the header, host id and lock file path
  37334. */
  37335. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  37336. #define PROXY_HEADERLEN 1 /* conch file header length */
  37337. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  37338. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  37339. /*
  37340. ** Takes an open conch file, copies the contents to a new path and then moves
  37341. ** it back. The newly created file's file descriptor is assigned to the
  37342. ** conch file structure and finally the original conch file descriptor is
  37343. ** closed. Returns zero if successful.
  37344. */
  37345. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  37346. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37347. unixFile *conchFile = pCtx->conchFile;
  37348. char tPath[MAXPATHLEN];
  37349. char buf[PROXY_MAXCONCHLEN];
  37350. char *cPath = pCtx->conchFilePath;
  37351. size_t readLen = 0;
  37352. size_t pathLen = 0;
  37353. char errmsg[64] = "";
  37354. int fd = -1;
  37355. int rc = -1;
  37356. UNUSED_PARAMETER(myHostID);
  37357. /* create a new path by replace the trailing '-conch' with '-break' */
  37358. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  37359. if( pathLen>MAXPATHLEN || pathLen<6 ||
  37360. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  37361. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  37362. goto end_breaklock;
  37363. }
  37364. /* read the conch content */
  37365. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  37366. if( readLen<PROXY_PATHINDEX ){
  37367. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  37368. goto end_breaklock;
  37369. }
  37370. /* write it out to the temporary break file */
  37371. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  37372. if( fd<0 ){
  37373. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  37374. goto end_breaklock;
  37375. }
  37376. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  37377. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  37378. goto end_breaklock;
  37379. }
  37380. if( rename(tPath, cPath) ){
  37381. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  37382. goto end_breaklock;
  37383. }
  37384. rc = 0;
  37385. fprintf(stderr, "broke stale lock on %s\n", cPath);
  37386. robust_close(pFile, conchFile->h, __LINE__);
  37387. conchFile->h = fd;
  37388. conchFile->openFlags = O_RDWR | O_CREAT;
  37389. end_breaklock:
  37390. if( rc ){
  37391. if( fd>=0 ){
  37392. osUnlink(tPath);
  37393. robust_close(pFile, fd, __LINE__);
  37394. }
  37395. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  37396. }
  37397. return rc;
  37398. }
  37399. /* Take the requested lock on the conch file and break a stale lock if the
  37400. ** host id matches.
  37401. */
  37402. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  37403. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37404. unixFile *conchFile = pCtx->conchFile;
  37405. int rc = SQLITE_OK;
  37406. int nTries = 0;
  37407. struct timespec conchModTime;
  37408. memset(&conchModTime, 0, sizeof(conchModTime));
  37409. do {
  37410. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  37411. nTries ++;
  37412. if( rc==SQLITE_BUSY ){
  37413. /* If the lock failed (busy):
  37414. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  37415. * 2nd try: fail if the mod time changed or host id is different, wait
  37416. * 10 sec and try again
  37417. * 3rd try: break the lock unless the mod time has changed.
  37418. */
  37419. struct stat buf;
  37420. if( osFstat(conchFile->h, &buf) ){
  37421. storeLastErrno(pFile, errno);
  37422. return SQLITE_IOERR_LOCK;
  37423. }
  37424. if( nTries==1 ){
  37425. conchModTime = buf.st_mtimespec;
  37426. usleep(500000); /* wait 0.5 sec and try the lock again*/
  37427. continue;
  37428. }
  37429. assert( nTries>1 );
  37430. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  37431. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  37432. return SQLITE_BUSY;
  37433. }
  37434. if( nTries==2 ){
  37435. char tBuf[PROXY_MAXCONCHLEN];
  37436. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  37437. if( len<0 ){
  37438. storeLastErrno(pFile, errno);
  37439. return SQLITE_IOERR_LOCK;
  37440. }
  37441. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  37442. /* don't break the lock if the host id doesn't match */
  37443. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  37444. return SQLITE_BUSY;
  37445. }
  37446. }else{
  37447. /* don't break the lock on short read or a version mismatch */
  37448. return SQLITE_BUSY;
  37449. }
  37450. usleep(10000000); /* wait 10 sec and try the lock again */
  37451. continue;
  37452. }
  37453. assert( nTries==3 );
  37454. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  37455. rc = SQLITE_OK;
  37456. if( lockType==EXCLUSIVE_LOCK ){
  37457. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  37458. }
  37459. if( !rc ){
  37460. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  37461. }
  37462. }
  37463. }
  37464. } while( rc==SQLITE_BUSY && nTries<3 );
  37465. return rc;
  37466. }
  37467. /* Takes the conch by taking a shared lock and read the contents conch, if
  37468. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  37469. ** lockPath means that the lockPath in the conch file will be used if the
  37470. ** host IDs match, or a new lock path will be generated automatically
  37471. ** and written to the conch file.
  37472. */
  37473. static int proxyTakeConch(unixFile *pFile){
  37474. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37475. if( pCtx->conchHeld!=0 ){
  37476. return SQLITE_OK;
  37477. }else{
  37478. unixFile *conchFile = pCtx->conchFile;
  37479. uuid_t myHostID;
  37480. int pError = 0;
  37481. char readBuf[PROXY_MAXCONCHLEN];
  37482. char lockPath[MAXPATHLEN];
  37483. char *tempLockPath = NULL;
  37484. int rc = SQLITE_OK;
  37485. int createConch = 0;
  37486. int hostIdMatch = 0;
  37487. int readLen = 0;
  37488. int tryOldLockPath = 0;
  37489. int forceNewLockPath = 0;
  37490. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  37491. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  37492. osGetpid(0)));
  37493. rc = proxyGetHostID(myHostID, &pError);
  37494. if( (rc&0xff)==SQLITE_IOERR ){
  37495. storeLastErrno(pFile, pError);
  37496. goto end_takeconch;
  37497. }
  37498. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  37499. if( rc!=SQLITE_OK ){
  37500. goto end_takeconch;
  37501. }
  37502. /* read the existing conch file */
  37503. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  37504. if( readLen<0 ){
  37505. /* I/O error: lastErrno set by seekAndRead */
  37506. storeLastErrno(pFile, conchFile->lastErrno);
  37507. rc = SQLITE_IOERR_READ;
  37508. goto end_takeconch;
  37509. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  37510. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  37511. /* a short read or version format mismatch means we need to create a new
  37512. ** conch file.
  37513. */
  37514. createConch = 1;
  37515. }
  37516. /* if the host id matches and the lock path already exists in the conch
  37517. ** we'll try to use the path there, if we can't open that path, we'll
  37518. ** retry with a new auto-generated path
  37519. */
  37520. do { /* in case we need to try again for an :auto: named lock file */
  37521. if( !createConch && !forceNewLockPath ){
  37522. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  37523. PROXY_HOSTIDLEN);
  37524. /* if the conch has data compare the contents */
  37525. if( !pCtx->lockProxyPath ){
  37526. /* for auto-named local lock file, just check the host ID and we'll
  37527. ** use the local lock file path that's already in there
  37528. */
  37529. if( hostIdMatch ){
  37530. size_t pathLen = (readLen - PROXY_PATHINDEX);
  37531. if( pathLen>=MAXPATHLEN ){
  37532. pathLen=MAXPATHLEN-1;
  37533. }
  37534. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  37535. lockPath[pathLen] = 0;
  37536. tempLockPath = lockPath;
  37537. tryOldLockPath = 1;
  37538. /* create a copy of the lock path if the conch is taken */
  37539. goto end_takeconch;
  37540. }
  37541. }else if( hostIdMatch
  37542. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  37543. readLen-PROXY_PATHINDEX)
  37544. ){
  37545. /* conch host and lock path match */
  37546. goto end_takeconch;
  37547. }
  37548. }
  37549. /* if the conch isn't writable and doesn't match, we can't take it */
  37550. if( (conchFile->openFlags&O_RDWR) == 0 ){
  37551. rc = SQLITE_BUSY;
  37552. goto end_takeconch;
  37553. }
  37554. /* either the conch didn't match or we need to create a new one */
  37555. if( !pCtx->lockProxyPath ){
  37556. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  37557. tempLockPath = lockPath;
  37558. /* create a copy of the lock path _only_ if the conch is taken */
  37559. }
  37560. /* update conch with host and path (this will fail if other process
  37561. ** has a shared lock already), if the host id matches, use the big
  37562. ** stick.
  37563. */
  37564. futimes(conchFile->h, NULL);
  37565. if( hostIdMatch && !createConch ){
  37566. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  37567. /* We are trying for an exclusive lock but another thread in this
  37568. ** same process is still holding a shared lock. */
  37569. rc = SQLITE_BUSY;
  37570. } else {
  37571. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  37572. }
  37573. }else{
  37574. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  37575. }
  37576. if( rc==SQLITE_OK ){
  37577. char writeBuffer[PROXY_MAXCONCHLEN];
  37578. int writeSize = 0;
  37579. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  37580. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  37581. if( pCtx->lockProxyPath!=NULL ){
  37582. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  37583. MAXPATHLEN);
  37584. }else{
  37585. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  37586. }
  37587. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  37588. robust_ftruncate(conchFile->h, writeSize);
  37589. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  37590. full_fsync(conchFile->h,0,0);
  37591. /* If we created a new conch file (not just updated the contents of a
  37592. ** valid conch file), try to match the permissions of the database
  37593. */
  37594. if( rc==SQLITE_OK && createConch ){
  37595. struct stat buf;
  37596. int err = osFstat(pFile->h, &buf);
  37597. if( err==0 ){
  37598. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  37599. S_IROTH|S_IWOTH);
  37600. /* try to match the database file R/W permissions, ignore failure */
  37601. #ifndef SQLITE_PROXY_DEBUG
  37602. osFchmod(conchFile->h, cmode);
  37603. #else
  37604. do{
  37605. rc = osFchmod(conchFile->h, cmode);
  37606. }while( rc==(-1) && errno==EINTR );
  37607. if( rc!=0 ){
  37608. int code = errno;
  37609. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  37610. cmode, code, strerror(code));
  37611. } else {
  37612. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  37613. }
  37614. }else{
  37615. int code = errno;
  37616. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  37617. err, code, strerror(code));
  37618. #endif
  37619. }
  37620. }
  37621. }
  37622. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  37623. end_takeconch:
  37624. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  37625. if( rc==SQLITE_OK && pFile->openFlags ){
  37626. int fd;
  37627. if( pFile->h>=0 ){
  37628. robust_close(pFile, pFile->h, __LINE__);
  37629. }
  37630. pFile->h = -1;
  37631. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  37632. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  37633. if( fd>=0 ){
  37634. pFile->h = fd;
  37635. }else{
  37636. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  37637. during locking */
  37638. }
  37639. }
  37640. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  37641. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  37642. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  37643. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  37644. /* we couldn't create the proxy lock file with the old lock file path
  37645. ** so try again via auto-naming
  37646. */
  37647. forceNewLockPath = 1;
  37648. tryOldLockPath = 0;
  37649. continue; /* go back to the do {} while start point, try again */
  37650. }
  37651. }
  37652. if( rc==SQLITE_OK ){
  37653. /* Need to make a copy of path if we extracted the value
  37654. ** from the conch file or the path was allocated on the stack
  37655. */
  37656. if( tempLockPath ){
  37657. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  37658. if( !pCtx->lockProxyPath ){
  37659. rc = SQLITE_NOMEM_BKPT;
  37660. }
  37661. }
  37662. }
  37663. if( rc==SQLITE_OK ){
  37664. pCtx->conchHeld = 1;
  37665. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  37666. afpLockingContext *afpCtx;
  37667. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  37668. afpCtx->dbPath = pCtx->lockProxyPath;
  37669. }
  37670. } else {
  37671. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  37672. }
  37673. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  37674. rc==SQLITE_OK?"ok":"failed"));
  37675. return rc;
  37676. } while (1); /* in case we need to retry the :auto: lock file -
  37677. ** we should never get here except via the 'continue' call. */
  37678. }
  37679. }
  37680. /*
  37681. ** If pFile holds a lock on a conch file, then release that lock.
  37682. */
  37683. static int proxyReleaseConch(unixFile *pFile){
  37684. int rc = SQLITE_OK; /* Subroutine return code */
  37685. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  37686. unixFile *conchFile; /* Name of the conch file */
  37687. pCtx = (proxyLockingContext *)pFile->lockingContext;
  37688. conchFile = pCtx->conchFile;
  37689. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  37690. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  37691. osGetpid(0)));
  37692. if( pCtx->conchHeld>0 ){
  37693. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  37694. }
  37695. pCtx->conchHeld = 0;
  37696. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  37697. (rc==SQLITE_OK ? "ok" : "failed")));
  37698. return rc;
  37699. }
  37700. /*
  37701. ** Given the name of a database file, compute the name of its conch file.
  37702. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  37703. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  37704. ** or SQLITE_NOMEM if unable to obtain memory.
  37705. **
  37706. ** The caller is responsible for ensuring that the allocated memory
  37707. ** space is eventually freed.
  37708. **
  37709. ** *pConchPath is set to NULL if a memory allocation error occurs.
  37710. */
  37711. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  37712. int i; /* Loop counter */
  37713. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  37714. char *conchPath; /* buffer in which to construct conch name */
  37715. /* Allocate space for the conch filename and initialize the name to
  37716. ** the name of the original database file. */
  37717. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  37718. if( conchPath==0 ){
  37719. return SQLITE_NOMEM_BKPT;
  37720. }
  37721. memcpy(conchPath, dbPath, len+1);
  37722. /* now insert a "." before the last / character */
  37723. for( i=(len-1); i>=0; i-- ){
  37724. if( conchPath[i]=='/' ){
  37725. i++;
  37726. break;
  37727. }
  37728. }
  37729. conchPath[i]='.';
  37730. while ( i<len ){
  37731. conchPath[i+1]=dbPath[i];
  37732. i++;
  37733. }
  37734. /* append the "-conch" suffix to the file */
  37735. memcpy(&conchPath[i+1], "-conch", 7);
  37736. assert( (int)strlen(conchPath) == len+7 );
  37737. return SQLITE_OK;
  37738. }
  37739. /* Takes a fully configured proxy locking-style unix file and switches
  37740. ** the local lock file path
  37741. */
  37742. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  37743. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  37744. char *oldPath = pCtx->lockProxyPath;
  37745. int rc = SQLITE_OK;
  37746. if( pFile->eFileLock!=NO_LOCK ){
  37747. return SQLITE_BUSY;
  37748. }
  37749. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  37750. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  37751. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  37752. return SQLITE_OK;
  37753. }else{
  37754. unixFile *lockProxy = pCtx->lockProxy;
  37755. pCtx->lockProxy=NULL;
  37756. pCtx->conchHeld = 0;
  37757. if( lockProxy!=NULL ){
  37758. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  37759. if( rc ) return rc;
  37760. sqlite3_free(lockProxy);
  37761. }
  37762. sqlite3_free(oldPath);
  37763. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  37764. }
  37765. return rc;
  37766. }
  37767. /*
  37768. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  37769. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  37770. **
  37771. ** This routine find the filename associated with pFile and writes it
  37772. ** int dbPath.
  37773. */
  37774. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  37775. #if defined(__APPLE__)
  37776. if( pFile->pMethod == &afpIoMethods ){
  37777. /* afp style keeps a reference to the db path in the filePath field
  37778. ** of the struct */
  37779. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  37780. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  37781. MAXPATHLEN);
  37782. } else
  37783. #endif
  37784. if( pFile->pMethod == &dotlockIoMethods ){
  37785. /* dot lock style uses the locking context to store the dot lock
  37786. ** file path */
  37787. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  37788. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  37789. }else{
  37790. /* all other styles use the locking context to store the db file path */
  37791. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  37792. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  37793. }
  37794. return SQLITE_OK;
  37795. }
  37796. /*
  37797. ** Takes an already filled in unix file and alters it so all file locking
  37798. ** will be performed on the local proxy lock file. The following fields
  37799. ** are preserved in the locking context so that they can be restored and
  37800. ** the unix structure properly cleaned up at close time:
  37801. ** ->lockingContext
  37802. ** ->pMethod
  37803. */
  37804. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  37805. proxyLockingContext *pCtx;
  37806. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  37807. char *lockPath=NULL;
  37808. int rc = SQLITE_OK;
  37809. if( pFile->eFileLock!=NO_LOCK ){
  37810. return SQLITE_BUSY;
  37811. }
  37812. proxyGetDbPathForUnixFile(pFile, dbPath);
  37813. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  37814. lockPath=NULL;
  37815. }else{
  37816. lockPath=(char *)path;
  37817. }
  37818. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  37819. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  37820. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  37821. if( pCtx==0 ){
  37822. return SQLITE_NOMEM_BKPT;
  37823. }
  37824. memset(pCtx, 0, sizeof(*pCtx));
  37825. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  37826. if( rc==SQLITE_OK ){
  37827. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  37828. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  37829. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  37830. ** (c) the file system is read-only, then enable no-locking access.
  37831. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  37832. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  37833. */
  37834. struct statfs fsInfo;
  37835. struct stat conchInfo;
  37836. int goLockless = 0;
  37837. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  37838. int err = errno;
  37839. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  37840. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  37841. }
  37842. }
  37843. if( goLockless ){
  37844. pCtx->conchHeld = -1; /* read only FS/ lockless */
  37845. rc = SQLITE_OK;
  37846. }
  37847. }
  37848. }
  37849. if( rc==SQLITE_OK && lockPath ){
  37850. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  37851. }
  37852. if( rc==SQLITE_OK ){
  37853. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  37854. if( pCtx->dbPath==NULL ){
  37855. rc = SQLITE_NOMEM_BKPT;
  37856. }
  37857. }
  37858. if( rc==SQLITE_OK ){
  37859. /* all memory is allocated, proxys are created and assigned,
  37860. ** switch the locking context and pMethod then return.
  37861. */
  37862. pCtx->oldLockingContext = pFile->lockingContext;
  37863. pFile->lockingContext = pCtx;
  37864. pCtx->pOldMethod = pFile->pMethod;
  37865. pFile->pMethod = &proxyIoMethods;
  37866. }else{
  37867. if( pCtx->conchFile ){
  37868. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  37869. sqlite3_free(pCtx->conchFile);
  37870. }
  37871. sqlite3DbFree(0, pCtx->lockProxyPath);
  37872. sqlite3_free(pCtx->conchFilePath);
  37873. sqlite3_free(pCtx);
  37874. }
  37875. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  37876. (rc==SQLITE_OK ? "ok" : "failed")));
  37877. return rc;
  37878. }
  37879. /*
  37880. ** This routine handles sqlite3_file_control() calls that are specific
  37881. ** to proxy locking.
  37882. */
  37883. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  37884. switch( op ){
  37885. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  37886. unixFile *pFile = (unixFile*)id;
  37887. if( pFile->pMethod == &proxyIoMethods ){
  37888. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  37889. proxyTakeConch(pFile);
  37890. if( pCtx->lockProxyPath ){
  37891. *(const char **)pArg = pCtx->lockProxyPath;
  37892. }else{
  37893. *(const char **)pArg = ":auto: (not held)";
  37894. }
  37895. } else {
  37896. *(const char **)pArg = NULL;
  37897. }
  37898. return SQLITE_OK;
  37899. }
  37900. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  37901. unixFile *pFile = (unixFile*)id;
  37902. int rc = SQLITE_OK;
  37903. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  37904. if( pArg==NULL || (const char *)pArg==0 ){
  37905. if( isProxyStyle ){
  37906. /* turn off proxy locking - not supported. If support is added for
  37907. ** switching proxy locking mode off then it will need to fail if
  37908. ** the journal mode is WAL mode.
  37909. */
  37910. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  37911. }else{
  37912. /* turn off proxy locking - already off - NOOP */
  37913. rc = SQLITE_OK;
  37914. }
  37915. }else{
  37916. const char *proxyPath = (const char *)pArg;
  37917. if( isProxyStyle ){
  37918. proxyLockingContext *pCtx =
  37919. (proxyLockingContext*)pFile->lockingContext;
  37920. if( !strcmp(pArg, ":auto:")
  37921. || (pCtx->lockProxyPath &&
  37922. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  37923. ){
  37924. rc = SQLITE_OK;
  37925. }else{
  37926. rc = switchLockProxyPath(pFile, proxyPath);
  37927. }
  37928. }else{
  37929. /* turn on proxy file locking */
  37930. rc = proxyTransformUnixFile(pFile, proxyPath);
  37931. }
  37932. }
  37933. return rc;
  37934. }
  37935. default: {
  37936. assert( 0 ); /* The call assures that only valid opcodes are sent */
  37937. }
  37938. }
  37939. /*NOTREACHED*/
  37940. return SQLITE_ERROR;
  37941. }
  37942. /*
  37943. ** Within this division (the proxying locking implementation) the procedures
  37944. ** above this point are all utilities. The lock-related methods of the
  37945. ** proxy-locking sqlite3_io_method object follow.
  37946. */
  37947. /*
  37948. ** This routine checks if there is a RESERVED lock held on the specified
  37949. ** file by this or any other process. If such a lock is held, set *pResOut
  37950. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  37951. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  37952. */
  37953. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  37954. unixFile *pFile = (unixFile*)id;
  37955. int rc = proxyTakeConch(pFile);
  37956. if( rc==SQLITE_OK ){
  37957. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37958. if( pCtx->conchHeld>0 ){
  37959. unixFile *proxy = pCtx->lockProxy;
  37960. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  37961. }else{ /* conchHeld < 0 is lockless */
  37962. pResOut=0;
  37963. }
  37964. }
  37965. return rc;
  37966. }
  37967. /*
  37968. ** Lock the file with the lock specified by parameter eFileLock - one
  37969. ** of the following:
  37970. **
  37971. ** (1) SHARED_LOCK
  37972. ** (2) RESERVED_LOCK
  37973. ** (3) PENDING_LOCK
  37974. ** (4) EXCLUSIVE_LOCK
  37975. **
  37976. ** Sometimes when requesting one lock state, additional lock states
  37977. ** are inserted in between. The locking might fail on one of the later
  37978. ** transitions leaving the lock state different from what it started but
  37979. ** still short of its goal. The following chart shows the allowed
  37980. ** transitions and the inserted intermediate states:
  37981. **
  37982. ** UNLOCKED -> SHARED
  37983. ** SHARED -> RESERVED
  37984. ** SHARED -> (PENDING) -> EXCLUSIVE
  37985. ** RESERVED -> (PENDING) -> EXCLUSIVE
  37986. ** PENDING -> EXCLUSIVE
  37987. **
  37988. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  37989. ** routine to lower a locking level.
  37990. */
  37991. static int proxyLock(sqlite3_file *id, int eFileLock) {
  37992. unixFile *pFile = (unixFile*)id;
  37993. int rc = proxyTakeConch(pFile);
  37994. if( rc==SQLITE_OK ){
  37995. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  37996. if( pCtx->conchHeld>0 ){
  37997. unixFile *proxy = pCtx->lockProxy;
  37998. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  37999. pFile->eFileLock = proxy->eFileLock;
  38000. }else{
  38001. /* conchHeld < 0 is lockless */
  38002. }
  38003. }
  38004. return rc;
  38005. }
  38006. /*
  38007. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  38008. ** must be either NO_LOCK or SHARED_LOCK.
  38009. **
  38010. ** If the locking level of the file descriptor is already at or below
  38011. ** the requested locking level, this routine is a no-op.
  38012. */
  38013. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  38014. unixFile *pFile = (unixFile*)id;
  38015. int rc = proxyTakeConch(pFile);
  38016. if( rc==SQLITE_OK ){
  38017. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  38018. if( pCtx->conchHeld>0 ){
  38019. unixFile *proxy = pCtx->lockProxy;
  38020. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  38021. pFile->eFileLock = proxy->eFileLock;
  38022. }else{
  38023. /* conchHeld < 0 is lockless */
  38024. }
  38025. }
  38026. return rc;
  38027. }
  38028. /*
  38029. ** Close a file that uses proxy locks.
  38030. */
  38031. static int proxyClose(sqlite3_file *id) {
  38032. if( ALWAYS(id) ){
  38033. unixFile *pFile = (unixFile*)id;
  38034. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  38035. unixFile *lockProxy = pCtx->lockProxy;
  38036. unixFile *conchFile = pCtx->conchFile;
  38037. int rc = SQLITE_OK;
  38038. if( lockProxy ){
  38039. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  38040. if( rc ) return rc;
  38041. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  38042. if( rc ) return rc;
  38043. sqlite3_free(lockProxy);
  38044. pCtx->lockProxy = 0;
  38045. }
  38046. if( conchFile ){
  38047. if( pCtx->conchHeld ){
  38048. rc = proxyReleaseConch(pFile);
  38049. if( rc ) return rc;
  38050. }
  38051. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  38052. if( rc ) return rc;
  38053. sqlite3_free(conchFile);
  38054. }
  38055. sqlite3DbFree(0, pCtx->lockProxyPath);
  38056. sqlite3_free(pCtx->conchFilePath);
  38057. sqlite3DbFree(0, pCtx->dbPath);
  38058. /* restore the original locking context and pMethod then close it */
  38059. pFile->lockingContext = pCtx->oldLockingContext;
  38060. pFile->pMethod = pCtx->pOldMethod;
  38061. sqlite3_free(pCtx);
  38062. return pFile->pMethod->xClose(id);
  38063. }
  38064. return SQLITE_OK;
  38065. }
  38066. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  38067. /*
  38068. ** The proxy locking style is intended for use with AFP filesystems.
  38069. ** And since AFP is only supported on MacOSX, the proxy locking is also
  38070. ** restricted to MacOSX.
  38071. **
  38072. **
  38073. ******************* End of the proxy lock implementation **********************
  38074. ******************************************************************************/
  38075. /*
  38076. ** Initialize the operating system interface.
  38077. **
  38078. ** This routine registers all VFS implementations for unix-like operating
  38079. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  38080. ** should be the only routines in this file that are visible from other
  38081. ** files.
  38082. **
  38083. ** This routine is called once during SQLite initialization and by a
  38084. ** single thread. The memory allocation and mutex subsystems have not
  38085. ** necessarily been initialized when this routine is called, and so they
  38086. ** should not be used.
  38087. */
  38088. SQLITE_API int sqlite3_os_init(void){
  38089. /*
  38090. ** The following macro defines an initializer for an sqlite3_vfs object.
  38091. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  38092. ** to the "finder" function. (pAppData is a pointer to a pointer because
  38093. ** silly C90 rules prohibit a void* from being cast to a function pointer
  38094. ** and so we have to go through the intermediate pointer to avoid problems
  38095. ** when compiling with -pedantic-errors on GCC.)
  38096. **
  38097. ** The FINDER parameter to this macro is the name of the pointer to the
  38098. ** finder-function. The finder-function returns a pointer to the
  38099. ** sqlite_io_methods object that implements the desired locking
  38100. ** behaviors. See the division above that contains the IOMETHODS
  38101. ** macro for addition information on finder-functions.
  38102. **
  38103. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  38104. ** object. But the "autolockIoFinder" available on MacOSX does a little
  38105. ** more than that; it looks at the filesystem type that hosts the
  38106. ** database file and tries to choose an locking method appropriate for
  38107. ** that filesystem time.
  38108. */
  38109. #define UNIXVFS(VFSNAME, FINDER) { \
  38110. 3, /* iVersion */ \
  38111. sizeof(unixFile), /* szOsFile */ \
  38112. MAX_PATHNAME, /* mxPathname */ \
  38113. 0, /* pNext */ \
  38114. VFSNAME, /* zName */ \
  38115. (void*)&FINDER, /* pAppData */ \
  38116. unixOpen, /* xOpen */ \
  38117. unixDelete, /* xDelete */ \
  38118. unixAccess, /* xAccess */ \
  38119. unixFullPathname, /* xFullPathname */ \
  38120. unixDlOpen, /* xDlOpen */ \
  38121. unixDlError, /* xDlError */ \
  38122. unixDlSym, /* xDlSym */ \
  38123. unixDlClose, /* xDlClose */ \
  38124. unixRandomness, /* xRandomness */ \
  38125. unixSleep, /* xSleep */ \
  38126. unixCurrentTime, /* xCurrentTime */ \
  38127. unixGetLastError, /* xGetLastError */ \
  38128. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  38129. unixSetSystemCall, /* xSetSystemCall */ \
  38130. unixGetSystemCall, /* xGetSystemCall */ \
  38131. unixNextSystemCall, /* xNextSystemCall */ \
  38132. }
  38133. /*
  38134. ** All default VFSes for unix are contained in the following array.
  38135. **
  38136. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  38137. ** by the SQLite core when the VFS is registered. So the following
  38138. ** array cannot be const.
  38139. */
  38140. static sqlite3_vfs aVfs[] = {
  38141. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  38142. UNIXVFS("unix", autolockIoFinder ),
  38143. #elif OS_VXWORKS
  38144. UNIXVFS("unix", vxworksIoFinder ),
  38145. #else
  38146. UNIXVFS("unix", posixIoFinder ),
  38147. #endif
  38148. UNIXVFS("unix-none", nolockIoFinder ),
  38149. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  38150. UNIXVFS("unix-excl", posixIoFinder ),
  38151. #if OS_VXWORKS
  38152. UNIXVFS("unix-namedsem", semIoFinder ),
  38153. #endif
  38154. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  38155. UNIXVFS("unix-posix", posixIoFinder ),
  38156. #endif
  38157. #if SQLITE_ENABLE_LOCKING_STYLE
  38158. UNIXVFS("unix-flock", flockIoFinder ),
  38159. #endif
  38160. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  38161. UNIXVFS("unix-afp", afpIoFinder ),
  38162. UNIXVFS("unix-nfs", nfsIoFinder ),
  38163. UNIXVFS("unix-proxy", proxyIoFinder ),
  38164. #endif
  38165. };
  38166. unsigned int i; /* Loop counter */
  38167. /* Double-check that the aSyscall[] array has been constructed
  38168. ** correctly. See ticket [bb3a86e890c8e96ab] */
  38169. assert( ArraySize(aSyscall)==29 );
  38170. /* Register all VFSes defined in the aVfs[] array */
  38171. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  38172. sqlite3_vfs_register(&aVfs[i], i==0);
  38173. }
  38174. unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  38175. return SQLITE_OK;
  38176. }
  38177. /*
  38178. ** Shutdown the operating system interface.
  38179. **
  38180. ** Some operating systems might need to do some cleanup in this routine,
  38181. ** to release dynamically allocated objects. But not on unix.
  38182. ** This routine is a no-op for unix.
  38183. */
  38184. SQLITE_API int sqlite3_os_end(void){
  38185. unixBigLock = 0;
  38186. return SQLITE_OK;
  38187. }
  38188. #endif /* SQLITE_OS_UNIX */
  38189. /************** End of os_unix.c *********************************************/
  38190. /************** Begin file os_win.c ******************************************/
  38191. /*
  38192. ** 2004 May 22
  38193. **
  38194. ** The author disclaims copyright to this source code. In place of
  38195. ** a legal notice, here is a blessing:
  38196. **
  38197. ** May you do good and not evil.
  38198. ** May you find forgiveness for yourself and forgive others.
  38199. ** May you share freely, never taking more than you give.
  38200. **
  38201. ******************************************************************************
  38202. **
  38203. ** This file contains code that is specific to Windows.
  38204. */
  38205. /* #include "sqliteInt.h" */
  38206. #if SQLITE_OS_WIN /* This file is used for Windows only */
  38207. /*
  38208. ** Include code that is common to all os_*.c files
  38209. */
  38210. /************** Include os_common.h in the middle of os_win.c ****************/
  38211. /************** Begin file os_common.h ***************************************/
  38212. /*
  38213. ** 2004 May 22
  38214. **
  38215. ** The author disclaims copyright to this source code. In place of
  38216. ** a legal notice, here is a blessing:
  38217. **
  38218. ** May you do good and not evil.
  38219. ** May you find forgiveness for yourself and forgive others.
  38220. ** May you share freely, never taking more than you give.
  38221. **
  38222. ******************************************************************************
  38223. **
  38224. ** This file contains macros and a little bit of code that is common to
  38225. ** all of the platform-specific files (os_*.c) and is #included into those
  38226. ** files.
  38227. **
  38228. ** This file should be #included by the os_*.c files only. It is not a
  38229. ** general purpose header file.
  38230. */
  38231. #ifndef _OS_COMMON_H_
  38232. #define _OS_COMMON_H_
  38233. /*
  38234. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  38235. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  38236. ** switch. The following code should catch this problem at compile-time.
  38237. */
  38238. #ifdef MEMORY_DEBUG
  38239. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  38240. #endif
  38241. /*
  38242. ** Macros for performance tracing. Normally turned off. Only works
  38243. ** on i486 hardware.
  38244. */
  38245. #ifdef SQLITE_PERFORMANCE_TRACE
  38246. /*
  38247. ** hwtime.h contains inline assembler code for implementing
  38248. ** high-performance timing routines.
  38249. */
  38250. /************** Include hwtime.h in the middle of os_common.h ****************/
  38251. /************** Begin file hwtime.h ******************************************/
  38252. /*
  38253. ** 2008 May 27
  38254. **
  38255. ** The author disclaims copyright to this source code. In place of
  38256. ** a legal notice, here is a blessing:
  38257. **
  38258. ** May you do good and not evil.
  38259. ** May you find forgiveness for yourself and forgive others.
  38260. ** May you share freely, never taking more than you give.
  38261. **
  38262. ******************************************************************************
  38263. **
  38264. ** This file contains inline asm code for retrieving "high-performance"
  38265. ** counters for x86 class CPUs.
  38266. */
  38267. #ifndef SQLITE_HWTIME_H
  38268. #define SQLITE_HWTIME_H
  38269. /*
  38270. ** The following routine only works on pentium-class (or newer) processors.
  38271. ** It uses the RDTSC opcode to read the cycle count value out of the
  38272. ** processor and returns that value. This can be used for high-res
  38273. ** profiling.
  38274. */
  38275. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  38276. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  38277. #if defined(__GNUC__)
  38278. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  38279. unsigned int lo, hi;
  38280. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  38281. return (sqlite_uint64)hi << 32 | lo;
  38282. }
  38283. #elif defined(_MSC_VER)
  38284. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  38285. __asm {
  38286. rdtsc
  38287. ret ; return value at EDX:EAX
  38288. }
  38289. }
  38290. #endif
  38291. #elif (defined(__GNUC__) && defined(__x86_64__))
  38292. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  38293. unsigned long val;
  38294. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  38295. return val;
  38296. }
  38297. #elif (defined(__GNUC__) && defined(__ppc__))
  38298. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  38299. unsigned long long retval;
  38300. unsigned long junk;
  38301. __asm__ __volatile__ ("\n\
  38302. 1: mftbu %1\n\
  38303. mftb %L0\n\
  38304. mftbu %0\n\
  38305. cmpw %0,%1\n\
  38306. bne 1b"
  38307. : "=r" (retval), "=r" (junk));
  38308. return retval;
  38309. }
  38310. #else
  38311. #error Need implementation of sqlite3Hwtime() for your platform.
  38312. /*
  38313. ** To compile without implementing sqlite3Hwtime() for your platform,
  38314. ** you can remove the above #error and use the following
  38315. ** stub function. You will lose timing support for many
  38316. ** of the debugging and testing utilities, but it should at
  38317. ** least compile and run.
  38318. */
  38319. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  38320. #endif
  38321. #endif /* !defined(SQLITE_HWTIME_H) */
  38322. /************** End of hwtime.h **********************************************/
  38323. /************** Continuing where we left off in os_common.h ******************/
  38324. static sqlite_uint64 g_start;
  38325. static sqlite_uint64 g_elapsed;
  38326. #define TIMER_START g_start=sqlite3Hwtime()
  38327. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  38328. #define TIMER_ELAPSED g_elapsed
  38329. #else
  38330. #define TIMER_START
  38331. #define TIMER_END
  38332. #define TIMER_ELAPSED ((sqlite_uint64)0)
  38333. #endif
  38334. /*
  38335. ** If we compile with the SQLITE_TEST macro set, then the following block
  38336. ** of code will give us the ability to simulate a disk I/O error. This
  38337. ** is used for testing the I/O recovery logic.
  38338. */
  38339. #if defined(SQLITE_TEST)
  38340. SQLITE_API extern int sqlite3_io_error_hit;
  38341. SQLITE_API extern int sqlite3_io_error_hardhit;
  38342. SQLITE_API extern int sqlite3_io_error_pending;
  38343. SQLITE_API extern int sqlite3_io_error_persist;
  38344. SQLITE_API extern int sqlite3_io_error_benign;
  38345. SQLITE_API extern int sqlite3_diskfull_pending;
  38346. SQLITE_API extern int sqlite3_diskfull;
  38347. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  38348. #define SimulateIOError(CODE) \
  38349. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  38350. || sqlite3_io_error_pending-- == 1 ) \
  38351. { local_ioerr(); CODE; }
  38352. static void local_ioerr(){
  38353. IOTRACE(("IOERR\n"));
  38354. sqlite3_io_error_hit++;
  38355. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  38356. }
  38357. #define SimulateDiskfullError(CODE) \
  38358. if( sqlite3_diskfull_pending ){ \
  38359. if( sqlite3_diskfull_pending == 1 ){ \
  38360. local_ioerr(); \
  38361. sqlite3_diskfull = 1; \
  38362. sqlite3_io_error_hit = 1; \
  38363. CODE; \
  38364. }else{ \
  38365. sqlite3_diskfull_pending--; \
  38366. } \
  38367. }
  38368. #else
  38369. #define SimulateIOErrorBenign(X)
  38370. #define SimulateIOError(A)
  38371. #define SimulateDiskfullError(A)
  38372. #endif /* defined(SQLITE_TEST) */
  38373. /*
  38374. ** When testing, keep a count of the number of open files.
  38375. */
  38376. #if defined(SQLITE_TEST)
  38377. SQLITE_API extern int sqlite3_open_file_count;
  38378. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  38379. #else
  38380. #define OpenCounter(X)
  38381. #endif /* defined(SQLITE_TEST) */
  38382. #endif /* !defined(_OS_COMMON_H_) */
  38383. /************** End of os_common.h *******************************************/
  38384. /************** Continuing where we left off in os_win.c *********************/
  38385. /*
  38386. ** Include the header file for the Windows VFS.
  38387. */
  38388. /* #include "os_win.h" */
  38389. /*
  38390. ** Compiling and using WAL mode requires several APIs that are only
  38391. ** available in Windows platforms based on the NT kernel.
  38392. */
  38393. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  38394. # error "WAL mode requires support from the Windows NT kernel, compile\
  38395. with SQLITE_OMIT_WAL."
  38396. #endif
  38397. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  38398. # error "Memory mapped files require support from the Windows NT kernel,\
  38399. compile with SQLITE_MAX_MMAP_SIZE=0."
  38400. #endif
  38401. /*
  38402. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  38403. ** based on the sub-platform)?
  38404. */
  38405. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  38406. # define SQLITE_WIN32_HAS_ANSI
  38407. #endif
  38408. /*
  38409. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  38410. ** based on the sub-platform)?
  38411. */
  38412. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  38413. !defined(SQLITE_WIN32_NO_WIDE)
  38414. # define SQLITE_WIN32_HAS_WIDE
  38415. #endif
  38416. /*
  38417. ** Make sure at least one set of Win32 APIs is available.
  38418. */
  38419. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  38420. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  38421. must be defined."
  38422. #endif
  38423. /*
  38424. ** Define the required Windows SDK version constants if they are not
  38425. ** already available.
  38426. */
  38427. #ifndef NTDDI_WIN8
  38428. # define NTDDI_WIN8 0x06020000
  38429. #endif
  38430. #ifndef NTDDI_WINBLUE
  38431. # define NTDDI_WINBLUE 0x06030000
  38432. #endif
  38433. #ifndef NTDDI_WINTHRESHOLD
  38434. # define NTDDI_WINTHRESHOLD 0x06040000
  38435. #endif
  38436. /*
  38437. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  38438. ** target system. GetVersionEx was first deprecated in Win8.1.
  38439. */
  38440. #ifndef SQLITE_WIN32_GETVERSIONEX
  38441. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  38442. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  38443. # else
  38444. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  38445. # endif
  38446. #endif
  38447. /*
  38448. ** Check to see if the CreateFileMappingA function is supported on the
  38449. ** target system. It is unavailable when using "mincore.lib" on Win10.
  38450. ** When compiling for Windows 10, always assume "mincore.lib" is in use.
  38451. */
  38452. #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
  38453. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
  38454. # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
  38455. # else
  38456. # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
  38457. # endif
  38458. #endif
  38459. /*
  38460. ** This constant should already be defined (in the "WinDef.h" SDK file).
  38461. */
  38462. #ifndef MAX_PATH
  38463. # define MAX_PATH (260)
  38464. #endif
  38465. /*
  38466. ** Maximum pathname length (in chars) for Win32. This should normally be
  38467. ** MAX_PATH.
  38468. */
  38469. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  38470. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  38471. #endif
  38472. /*
  38473. ** This constant should already be defined (in the "WinNT.h" SDK file).
  38474. */
  38475. #ifndef UNICODE_STRING_MAX_CHARS
  38476. # define UNICODE_STRING_MAX_CHARS (32767)
  38477. #endif
  38478. /*
  38479. ** Maximum pathname length (in chars) for WinNT. This should normally be
  38480. ** UNICODE_STRING_MAX_CHARS.
  38481. */
  38482. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  38483. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  38484. #endif
  38485. /*
  38486. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  38487. ** characters, so we allocate 4 bytes per character assuming worst-case of
  38488. ** 4-bytes-per-character for UTF8.
  38489. */
  38490. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  38491. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  38492. #endif
  38493. /*
  38494. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  38495. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  38496. */
  38497. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  38498. # define SQLITE_WINNT_MAX_PATH_BYTES \
  38499. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  38500. #endif
  38501. /*
  38502. ** Maximum error message length (in chars) for WinRT.
  38503. */
  38504. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  38505. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  38506. #endif
  38507. /*
  38508. ** Returns non-zero if the character should be treated as a directory
  38509. ** separator.
  38510. */
  38511. #ifndef winIsDirSep
  38512. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  38513. #endif
  38514. /*
  38515. ** This macro is used when a local variable is set to a value that is
  38516. ** [sometimes] not used by the code (e.g. via conditional compilation).
  38517. */
  38518. #ifndef UNUSED_VARIABLE_VALUE
  38519. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  38520. #endif
  38521. /*
  38522. ** Returns the character that should be used as the directory separator.
  38523. */
  38524. #ifndef winGetDirSep
  38525. # define winGetDirSep() '\\'
  38526. #endif
  38527. /*
  38528. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  38529. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  38530. ** CE SDK; however, they are not present in the header file)?
  38531. */
  38532. #if SQLITE_WIN32_FILEMAPPING_API && \
  38533. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  38534. /*
  38535. ** Two of the file mapping APIs are different under WinRT. Figure out which
  38536. ** set we need.
  38537. */
  38538. #if SQLITE_OS_WINRT
  38539. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  38540. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  38541. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  38542. #else
  38543. #if defined(SQLITE_WIN32_HAS_ANSI)
  38544. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  38545. DWORD, DWORD, DWORD, LPCSTR);
  38546. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  38547. #if defined(SQLITE_WIN32_HAS_WIDE)
  38548. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  38549. DWORD, DWORD, DWORD, LPCWSTR);
  38550. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  38551. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  38552. #endif /* SQLITE_OS_WINRT */
  38553. /*
  38554. ** These file mapping APIs are common to both Win32 and WinRT.
  38555. */
  38556. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  38557. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  38558. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  38559. /*
  38560. ** Some Microsoft compilers lack this definition.
  38561. */
  38562. #ifndef INVALID_FILE_ATTRIBUTES
  38563. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  38564. #endif
  38565. #ifndef FILE_FLAG_MASK
  38566. # define FILE_FLAG_MASK (0xFF3C0000)
  38567. #endif
  38568. #ifndef FILE_ATTRIBUTE_MASK
  38569. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  38570. #endif
  38571. #ifndef SQLITE_OMIT_WAL
  38572. /* Forward references to structures used for WAL */
  38573. typedef struct winShm winShm; /* A connection to shared-memory */
  38574. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  38575. #endif
  38576. /*
  38577. ** WinCE lacks native support for file locking so we have to fake it
  38578. ** with some code of our own.
  38579. */
  38580. #if SQLITE_OS_WINCE
  38581. typedef struct winceLock {
  38582. int nReaders; /* Number of reader locks obtained */
  38583. BOOL bPending; /* Indicates a pending lock has been obtained */
  38584. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  38585. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  38586. } winceLock;
  38587. #endif
  38588. /*
  38589. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  38590. ** portability layer.
  38591. */
  38592. typedef struct winFile winFile;
  38593. struct winFile {
  38594. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  38595. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  38596. HANDLE h; /* Handle for accessing the file */
  38597. u8 locktype; /* Type of lock currently held on this file */
  38598. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  38599. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  38600. DWORD lastErrno; /* The Windows errno from the last I/O error */
  38601. #ifndef SQLITE_OMIT_WAL
  38602. winShm *pShm; /* Instance of shared memory on this file */
  38603. #endif
  38604. const char *zPath; /* Full pathname of this file */
  38605. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  38606. #if SQLITE_OS_WINCE
  38607. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  38608. HANDLE hMutex; /* Mutex used to control access to shared lock */
  38609. HANDLE hShared; /* Shared memory segment used for locking */
  38610. winceLock local; /* Locks obtained by this instance of winFile */
  38611. winceLock *shared; /* Global shared lock memory for the file */
  38612. #endif
  38613. #if SQLITE_MAX_MMAP_SIZE>0
  38614. int nFetchOut; /* Number of outstanding xFetch references */
  38615. HANDLE hMap; /* Handle for accessing memory mapping */
  38616. void *pMapRegion; /* Area memory mapped */
  38617. sqlite3_int64 mmapSize; /* Size of mapped region */
  38618. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  38619. #endif
  38620. };
  38621. /*
  38622. ** The winVfsAppData structure is used for the pAppData member for all of the
  38623. ** Win32 VFS variants.
  38624. */
  38625. typedef struct winVfsAppData winVfsAppData;
  38626. struct winVfsAppData {
  38627. const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
  38628. void *pAppData; /* The extra pAppData, if any. */
  38629. BOOL bNoLock; /* Non-zero if locking is disabled. */
  38630. };
  38631. /*
  38632. ** Allowed values for winFile.ctrlFlags
  38633. */
  38634. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  38635. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  38636. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  38637. /*
  38638. * The size of the buffer used by sqlite3_win32_write_debug().
  38639. */
  38640. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  38641. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  38642. #endif
  38643. /*
  38644. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  38645. * various Win32 API heap functions instead of our own.
  38646. */
  38647. #ifdef SQLITE_WIN32_MALLOC
  38648. /*
  38649. * If this is non-zero, an isolated heap will be created by the native Win32
  38650. * allocator subsystem; otherwise, the default process heap will be used. This
  38651. * setting has no effect when compiling for WinRT. By default, this is enabled
  38652. * and an isolated heap will be created to store all allocated data.
  38653. *
  38654. ******************************************************************************
  38655. * WARNING: It is important to note that when this setting is non-zero and the
  38656. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  38657. * function), all data that was allocated using the isolated heap will
  38658. * be freed immediately and any attempt to access any of that freed
  38659. * data will almost certainly result in an immediate access violation.
  38660. ******************************************************************************
  38661. */
  38662. #ifndef SQLITE_WIN32_HEAP_CREATE
  38663. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  38664. #endif
  38665. /*
  38666. * This is the maximum possible initial size of the Win32-specific heap, in
  38667. * bytes.
  38668. */
  38669. #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
  38670. # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
  38671. #endif
  38672. /*
  38673. * This is the extra space for the initial size of the Win32-specific heap,
  38674. * in bytes. This value may be zero.
  38675. */
  38676. #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
  38677. # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
  38678. #endif
  38679. /*
  38680. * Calculate the maximum legal cache size, in pages, based on the maximum
  38681. * possible initial heap size and the default page size, setting aside the
  38682. * needed extra space.
  38683. */
  38684. #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
  38685. # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
  38686. (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
  38687. (SQLITE_DEFAULT_PAGE_SIZE))
  38688. #endif
  38689. /*
  38690. * This is cache size used in the calculation of the initial size of the
  38691. * Win32-specific heap. It cannot be negative.
  38692. */
  38693. #ifndef SQLITE_WIN32_CACHE_SIZE
  38694. # if SQLITE_DEFAULT_CACHE_SIZE>=0
  38695. # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
  38696. # else
  38697. # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
  38698. # endif
  38699. #endif
  38700. /*
  38701. * Make sure that the calculated cache size, in pages, cannot cause the
  38702. * initial size of the Win32-specific heap to exceed the maximum amount
  38703. * of memory that can be specified in the call to HeapCreate.
  38704. */
  38705. #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
  38706. # undef SQLITE_WIN32_CACHE_SIZE
  38707. # define SQLITE_WIN32_CACHE_SIZE (2000)
  38708. #endif
  38709. /*
  38710. * The initial size of the Win32-specific heap. This value may be zero.
  38711. */
  38712. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  38713. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
  38714. (SQLITE_DEFAULT_PAGE_SIZE) + \
  38715. (SQLITE_WIN32_HEAP_INIT_EXTRA))
  38716. #endif
  38717. /*
  38718. * The maximum size of the Win32-specific heap. This value may be zero.
  38719. */
  38720. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  38721. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  38722. #endif
  38723. /*
  38724. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  38725. * zero for the default behavior.
  38726. */
  38727. #ifndef SQLITE_WIN32_HEAP_FLAGS
  38728. # define SQLITE_WIN32_HEAP_FLAGS (0)
  38729. #endif
  38730. /*
  38731. ** The winMemData structure stores information required by the Win32-specific
  38732. ** sqlite3_mem_methods implementation.
  38733. */
  38734. typedef struct winMemData winMemData;
  38735. struct winMemData {
  38736. #ifndef NDEBUG
  38737. u32 magic1; /* Magic number to detect structure corruption. */
  38738. #endif
  38739. HANDLE hHeap; /* The handle to our heap. */
  38740. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  38741. #ifndef NDEBUG
  38742. u32 magic2; /* Magic number to detect structure corruption. */
  38743. #endif
  38744. };
  38745. #ifndef NDEBUG
  38746. #define WINMEM_MAGIC1 0x42b2830b
  38747. #define WINMEM_MAGIC2 0xbd4d7cf4
  38748. #endif
  38749. static struct winMemData win_mem_data = {
  38750. #ifndef NDEBUG
  38751. WINMEM_MAGIC1,
  38752. #endif
  38753. NULL, FALSE
  38754. #ifndef NDEBUG
  38755. ,WINMEM_MAGIC2
  38756. #endif
  38757. };
  38758. #ifndef NDEBUG
  38759. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  38760. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  38761. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  38762. #else
  38763. #define winMemAssertMagic()
  38764. #endif
  38765. #define winMemGetDataPtr() &win_mem_data
  38766. #define winMemGetHeap() win_mem_data.hHeap
  38767. #define winMemGetOwned() win_mem_data.bOwned
  38768. static void *winMemMalloc(int nBytes);
  38769. static void winMemFree(void *pPrior);
  38770. static void *winMemRealloc(void *pPrior, int nBytes);
  38771. static int winMemSize(void *p);
  38772. static int winMemRoundup(int n);
  38773. static int winMemInit(void *pAppData);
  38774. static void winMemShutdown(void *pAppData);
  38775. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  38776. #endif /* SQLITE_WIN32_MALLOC */
  38777. /*
  38778. ** The following variable is (normally) set once and never changes
  38779. ** thereafter. It records whether the operating system is Win9x
  38780. ** or WinNT.
  38781. **
  38782. ** 0: Operating system unknown.
  38783. ** 1: Operating system is Win9x.
  38784. ** 2: Operating system is WinNT.
  38785. **
  38786. ** In order to facilitate testing on a WinNT system, the test fixture
  38787. ** can manually set this value to 1 to emulate Win98 behavior.
  38788. */
  38789. #ifdef SQLITE_TEST
  38790. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  38791. #else
  38792. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  38793. #endif
  38794. #ifndef SYSCALL
  38795. # define SYSCALL sqlite3_syscall_ptr
  38796. #endif
  38797. /*
  38798. ** This function is not available on Windows CE or WinRT.
  38799. */
  38800. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  38801. # define osAreFileApisANSI() 1
  38802. #endif
  38803. /*
  38804. ** Many system calls are accessed through pointer-to-functions so that
  38805. ** they may be overridden at runtime to facilitate fault injection during
  38806. ** testing and sandboxing. The following array holds the names and pointers
  38807. ** to all overrideable system calls.
  38808. */
  38809. static struct win_syscall {
  38810. const char *zName; /* Name of the system call */
  38811. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  38812. sqlite3_syscall_ptr pDefault; /* Default value */
  38813. } aSyscall[] = {
  38814. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  38815. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  38816. #else
  38817. { "AreFileApisANSI", (SYSCALL)0, 0 },
  38818. #endif
  38819. #ifndef osAreFileApisANSI
  38820. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  38821. #endif
  38822. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  38823. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  38824. #else
  38825. { "CharLowerW", (SYSCALL)0, 0 },
  38826. #endif
  38827. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  38828. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  38829. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  38830. #else
  38831. { "CharUpperW", (SYSCALL)0, 0 },
  38832. #endif
  38833. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  38834. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  38835. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  38836. #if defined(SQLITE_WIN32_HAS_ANSI)
  38837. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  38838. #else
  38839. { "CreateFileA", (SYSCALL)0, 0 },
  38840. #endif
  38841. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  38842. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  38843. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38844. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  38845. #else
  38846. { "CreateFileW", (SYSCALL)0, 0 },
  38847. #endif
  38848. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  38849. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  38850. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  38851. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
  38852. SQLITE_WIN32_CREATEFILEMAPPINGA
  38853. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  38854. #else
  38855. { "CreateFileMappingA", (SYSCALL)0, 0 },
  38856. #endif
  38857. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  38858. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  38859. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  38860. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  38861. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  38862. #else
  38863. { "CreateFileMappingW", (SYSCALL)0, 0 },
  38864. #endif
  38865. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  38866. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  38867. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38868. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  38869. #else
  38870. { "CreateMutexW", (SYSCALL)0, 0 },
  38871. #endif
  38872. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  38873. LPCWSTR))aSyscall[8].pCurrent)
  38874. #if defined(SQLITE_WIN32_HAS_ANSI)
  38875. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  38876. #else
  38877. { "DeleteFileA", (SYSCALL)0, 0 },
  38878. #endif
  38879. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  38880. #if defined(SQLITE_WIN32_HAS_WIDE)
  38881. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  38882. #else
  38883. { "DeleteFileW", (SYSCALL)0, 0 },
  38884. #endif
  38885. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  38886. #if SQLITE_OS_WINCE
  38887. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  38888. #else
  38889. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  38890. #endif
  38891. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  38892. LPFILETIME))aSyscall[11].pCurrent)
  38893. #if SQLITE_OS_WINCE
  38894. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  38895. #else
  38896. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  38897. #endif
  38898. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  38899. LPSYSTEMTIME))aSyscall[12].pCurrent)
  38900. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  38901. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  38902. #if defined(SQLITE_WIN32_HAS_ANSI)
  38903. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  38904. #else
  38905. { "FormatMessageA", (SYSCALL)0, 0 },
  38906. #endif
  38907. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  38908. DWORD,va_list*))aSyscall[14].pCurrent)
  38909. #if defined(SQLITE_WIN32_HAS_WIDE)
  38910. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  38911. #else
  38912. { "FormatMessageW", (SYSCALL)0, 0 },
  38913. #endif
  38914. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  38915. DWORD,va_list*))aSyscall[15].pCurrent)
  38916. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38917. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  38918. #else
  38919. { "FreeLibrary", (SYSCALL)0, 0 },
  38920. #endif
  38921. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  38922. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  38923. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  38924. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  38925. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  38926. #else
  38927. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  38928. #endif
  38929. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  38930. LPDWORD))aSyscall[18].pCurrent)
  38931. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38932. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  38933. #else
  38934. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  38935. #endif
  38936. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  38937. LPDWORD))aSyscall[19].pCurrent)
  38938. #if defined(SQLITE_WIN32_HAS_ANSI)
  38939. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  38940. #else
  38941. { "GetFileAttributesA", (SYSCALL)0, 0 },
  38942. #endif
  38943. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  38944. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38945. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  38946. #else
  38947. { "GetFileAttributesW", (SYSCALL)0, 0 },
  38948. #endif
  38949. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  38950. #if defined(SQLITE_WIN32_HAS_WIDE)
  38951. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  38952. #else
  38953. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  38954. #endif
  38955. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  38956. LPVOID))aSyscall[22].pCurrent)
  38957. #if !SQLITE_OS_WINRT
  38958. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  38959. #else
  38960. { "GetFileSize", (SYSCALL)0, 0 },
  38961. #endif
  38962. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  38963. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  38964. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  38965. #else
  38966. { "GetFullPathNameA", (SYSCALL)0, 0 },
  38967. #endif
  38968. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  38969. LPSTR*))aSyscall[24].pCurrent)
  38970. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  38971. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  38972. #else
  38973. { "GetFullPathNameW", (SYSCALL)0, 0 },
  38974. #endif
  38975. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  38976. LPWSTR*))aSyscall[25].pCurrent)
  38977. { "GetLastError", (SYSCALL)GetLastError, 0 },
  38978. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  38979. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  38980. #if SQLITE_OS_WINCE
  38981. /* The GetProcAddressA() routine is only available on Windows CE. */
  38982. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  38983. #else
  38984. /* All other Windows platforms expect GetProcAddress() to take
  38985. ** an ANSI string regardless of the _UNICODE setting */
  38986. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  38987. #endif
  38988. #else
  38989. { "GetProcAddressA", (SYSCALL)0, 0 },
  38990. #endif
  38991. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  38992. LPCSTR))aSyscall[27].pCurrent)
  38993. #if !SQLITE_OS_WINRT
  38994. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  38995. #else
  38996. { "GetSystemInfo", (SYSCALL)0, 0 },
  38997. #endif
  38998. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  38999. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  39000. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  39001. #if !SQLITE_OS_WINCE
  39002. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  39003. #else
  39004. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  39005. #endif
  39006. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  39007. LPFILETIME))aSyscall[30].pCurrent)
  39008. #if defined(SQLITE_WIN32_HAS_ANSI)
  39009. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  39010. #else
  39011. { "GetTempPathA", (SYSCALL)0, 0 },
  39012. #endif
  39013. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  39014. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  39015. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  39016. #else
  39017. { "GetTempPathW", (SYSCALL)0, 0 },
  39018. #endif
  39019. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  39020. #if !SQLITE_OS_WINRT
  39021. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  39022. #else
  39023. { "GetTickCount", (SYSCALL)0, 0 },
  39024. #endif
  39025. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  39026. #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
  39027. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  39028. #else
  39029. { "GetVersionExA", (SYSCALL)0, 0 },
  39030. #endif
  39031. #define osGetVersionExA ((BOOL(WINAPI*)( \
  39032. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  39033. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  39034. SQLITE_WIN32_GETVERSIONEX
  39035. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  39036. #else
  39037. { "GetVersionExW", (SYSCALL)0, 0 },
  39038. #endif
  39039. #define osGetVersionExW ((BOOL(WINAPI*)( \
  39040. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  39041. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  39042. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  39043. SIZE_T))aSyscall[36].pCurrent)
  39044. #if !SQLITE_OS_WINRT
  39045. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  39046. #else
  39047. { "HeapCreate", (SYSCALL)0, 0 },
  39048. #endif
  39049. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  39050. SIZE_T))aSyscall[37].pCurrent)
  39051. #if !SQLITE_OS_WINRT
  39052. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  39053. #else
  39054. { "HeapDestroy", (SYSCALL)0, 0 },
  39055. #endif
  39056. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  39057. { "HeapFree", (SYSCALL)HeapFree, 0 },
  39058. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  39059. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  39060. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  39061. SIZE_T))aSyscall[40].pCurrent)
  39062. { "HeapSize", (SYSCALL)HeapSize, 0 },
  39063. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  39064. LPCVOID))aSyscall[41].pCurrent)
  39065. #if !SQLITE_OS_WINRT
  39066. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  39067. #else
  39068. { "HeapValidate", (SYSCALL)0, 0 },
  39069. #endif
  39070. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  39071. LPCVOID))aSyscall[42].pCurrent)
  39072. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  39073. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  39074. #else
  39075. { "HeapCompact", (SYSCALL)0, 0 },
  39076. #endif
  39077. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  39078. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  39079. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  39080. #else
  39081. { "LoadLibraryA", (SYSCALL)0, 0 },
  39082. #endif
  39083. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  39084. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  39085. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  39086. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  39087. #else
  39088. { "LoadLibraryW", (SYSCALL)0, 0 },
  39089. #endif
  39090. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  39091. #if !SQLITE_OS_WINRT
  39092. { "LocalFree", (SYSCALL)LocalFree, 0 },
  39093. #else
  39094. { "LocalFree", (SYSCALL)0, 0 },
  39095. #endif
  39096. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  39097. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  39098. { "LockFile", (SYSCALL)LockFile, 0 },
  39099. #else
  39100. { "LockFile", (SYSCALL)0, 0 },
  39101. #endif
  39102. #ifndef osLockFile
  39103. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  39104. DWORD))aSyscall[47].pCurrent)
  39105. #endif
  39106. #if !SQLITE_OS_WINCE
  39107. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  39108. #else
  39109. { "LockFileEx", (SYSCALL)0, 0 },
  39110. #endif
  39111. #ifndef osLockFileEx
  39112. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  39113. LPOVERLAPPED))aSyscall[48].pCurrent)
  39114. #endif
  39115. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  39116. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  39117. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  39118. #else
  39119. { "MapViewOfFile", (SYSCALL)0, 0 },
  39120. #endif
  39121. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  39122. SIZE_T))aSyscall[49].pCurrent)
  39123. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  39124. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  39125. int))aSyscall[50].pCurrent)
  39126. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  39127. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  39128. LARGE_INTEGER*))aSyscall[51].pCurrent)
  39129. { "ReadFile", (SYSCALL)ReadFile, 0 },
  39130. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  39131. LPOVERLAPPED))aSyscall[52].pCurrent)
  39132. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  39133. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  39134. #if !SQLITE_OS_WINRT
  39135. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  39136. #else
  39137. { "SetFilePointer", (SYSCALL)0, 0 },
  39138. #endif
  39139. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  39140. DWORD))aSyscall[54].pCurrent)
  39141. #if !SQLITE_OS_WINRT
  39142. { "Sleep", (SYSCALL)Sleep, 0 },
  39143. #else
  39144. { "Sleep", (SYSCALL)0, 0 },
  39145. #endif
  39146. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  39147. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  39148. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  39149. LPFILETIME))aSyscall[56].pCurrent)
  39150. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  39151. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  39152. #else
  39153. { "UnlockFile", (SYSCALL)0, 0 },
  39154. #endif
  39155. #ifndef osUnlockFile
  39156. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  39157. DWORD))aSyscall[57].pCurrent)
  39158. #endif
  39159. #if !SQLITE_OS_WINCE
  39160. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  39161. #else
  39162. { "UnlockFileEx", (SYSCALL)0, 0 },
  39163. #endif
  39164. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  39165. LPOVERLAPPED))aSyscall[58].pCurrent)
  39166. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  39167. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  39168. #else
  39169. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  39170. #endif
  39171. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  39172. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  39173. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  39174. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  39175. { "WriteFile", (SYSCALL)WriteFile, 0 },
  39176. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  39177. LPOVERLAPPED))aSyscall[61].pCurrent)
  39178. #if SQLITE_OS_WINRT
  39179. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  39180. #else
  39181. { "CreateEventExW", (SYSCALL)0, 0 },
  39182. #endif
  39183. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  39184. DWORD,DWORD))aSyscall[62].pCurrent)
  39185. #if !SQLITE_OS_WINRT
  39186. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  39187. #else
  39188. { "WaitForSingleObject", (SYSCALL)0, 0 },
  39189. #endif
  39190. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  39191. DWORD))aSyscall[63].pCurrent)
  39192. #if !SQLITE_OS_WINCE
  39193. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  39194. #else
  39195. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  39196. #endif
  39197. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  39198. BOOL))aSyscall[64].pCurrent)
  39199. #if SQLITE_OS_WINRT
  39200. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  39201. #else
  39202. { "SetFilePointerEx", (SYSCALL)0, 0 },
  39203. #endif
  39204. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  39205. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  39206. #if SQLITE_OS_WINRT
  39207. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  39208. #else
  39209. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  39210. #endif
  39211. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  39212. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  39213. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  39214. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  39215. #else
  39216. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  39217. #endif
  39218. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  39219. SIZE_T))aSyscall[67].pCurrent)
  39220. #if SQLITE_OS_WINRT
  39221. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  39222. #else
  39223. { "CreateFile2", (SYSCALL)0, 0 },
  39224. #endif
  39225. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  39226. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  39227. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  39228. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  39229. #else
  39230. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  39231. #endif
  39232. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  39233. DWORD))aSyscall[69].pCurrent)
  39234. #if SQLITE_OS_WINRT
  39235. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  39236. #else
  39237. { "GetTickCount64", (SYSCALL)0, 0 },
  39238. #endif
  39239. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  39240. #if SQLITE_OS_WINRT
  39241. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  39242. #else
  39243. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  39244. #endif
  39245. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  39246. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  39247. #if defined(SQLITE_WIN32_HAS_ANSI)
  39248. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  39249. #else
  39250. { "OutputDebugStringA", (SYSCALL)0, 0 },
  39251. #endif
  39252. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  39253. #if defined(SQLITE_WIN32_HAS_WIDE)
  39254. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  39255. #else
  39256. { "OutputDebugStringW", (SYSCALL)0, 0 },
  39257. #endif
  39258. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  39259. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  39260. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  39261. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  39262. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  39263. #else
  39264. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  39265. #endif
  39266. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  39267. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  39268. /*
  39269. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  39270. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  39271. ** So do not try to make this is into a redefinable interface.
  39272. */
  39273. #if defined(InterlockedCompareExchange)
  39274. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  39275. #define osInterlockedCompareExchange InterlockedCompareExchange
  39276. #else
  39277. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  39278. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  39279. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  39280. #endif /* defined(InterlockedCompareExchange) */
  39281. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  39282. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  39283. #else
  39284. { "UuidCreate", (SYSCALL)0, 0 },
  39285. #endif
  39286. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  39287. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  39288. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  39289. #else
  39290. { "UuidCreateSequential", (SYSCALL)0, 0 },
  39291. #endif
  39292. #define osUuidCreateSequential \
  39293. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  39294. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  39295. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  39296. #else
  39297. { "FlushViewOfFile", (SYSCALL)0, 0 },
  39298. #endif
  39299. #define osFlushViewOfFile \
  39300. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  39301. }; /* End of the overrideable system calls */
  39302. /*
  39303. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  39304. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  39305. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  39306. ** system call named zName.
  39307. */
  39308. static int winSetSystemCall(
  39309. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  39310. const char *zName, /* Name of system call to override */
  39311. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  39312. ){
  39313. unsigned int i;
  39314. int rc = SQLITE_NOTFOUND;
  39315. UNUSED_PARAMETER(pNotUsed);
  39316. if( zName==0 ){
  39317. /* If no zName is given, restore all system calls to their default
  39318. ** settings and return NULL
  39319. */
  39320. rc = SQLITE_OK;
  39321. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  39322. if( aSyscall[i].pDefault ){
  39323. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  39324. }
  39325. }
  39326. }else{
  39327. /* If zName is specified, operate on only the one system call
  39328. ** specified.
  39329. */
  39330. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  39331. if( strcmp(zName, aSyscall[i].zName)==0 ){
  39332. if( aSyscall[i].pDefault==0 ){
  39333. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  39334. }
  39335. rc = SQLITE_OK;
  39336. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  39337. aSyscall[i].pCurrent = pNewFunc;
  39338. break;
  39339. }
  39340. }
  39341. }
  39342. return rc;
  39343. }
  39344. /*
  39345. ** Return the value of a system call. Return NULL if zName is not a
  39346. ** recognized system call name. NULL is also returned if the system call
  39347. ** is currently undefined.
  39348. */
  39349. static sqlite3_syscall_ptr winGetSystemCall(
  39350. sqlite3_vfs *pNotUsed,
  39351. const char *zName
  39352. ){
  39353. unsigned int i;
  39354. UNUSED_PARAMETER(pNotUsed);
  39355. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  39356. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  39357. }
  39358. return 0;
  39359. }
  39360. /*
  39361. ** Return the name of the first system call after zName. If zName==NULL
  39362. ** then return the name of the first system call. Return NULL if zName
  39363. ** is the last system call or if zName is not the name of a valid
  39364. ** system call.
  39365. */
  39366. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  39367. int i = -1;
  39368. UNUSED_PARAMETER(p);
  39369. if( zName ){
  39370. for(i=0; i<ArraySize(aSyscall)-1; i++){
  39371. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  39372. }
  39373. }
  39374. for(i++; i<ArraySize(aSyscall); i++){
  39375. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  39376. }
  39377. return 0;
  39378. }
  39379. #ifdef SQLITE_WIN32_MALLOC
  39380. /*
  39381. ** If a Win32 native heap has been configured, this function will attempt to
  39382. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  39383. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  39384. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  39385. ** largest committed free block in the heap, in bytes.
  39386. */
  39387. SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
  39388. int rc = SQLITE_OK;
  39389. UINT nLargest = 0;
  39390. HANDLE hHeap;
  39391. winMemAssertMagic();
  39392. hHeap = winMemGetHeap();
  39393. assert( hHeap!=0 );
  39394. assert( hHeap!=INVALID_HANDLE_VALUE );
  39395. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39396. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39397. #endif
  39398. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  39399. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  39400. DWORD lastErrno = osGetLastError();
  39401. if( lastErrno==NO_ERROR ){
  39402. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  39403. (void*)hHeap);
  39404. rc = SQLITE_NOMEM_BKPT;
  39405. }else{
  39406. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  39407. osGetLastError(), (void*)hHeap);
  39408. rc = SQLITE_ERROR;
  39409. }
  39410. }
  39411. #else
  39412. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  39413. (void*)hHeap);
  39414. rc = SQLITE_NOTFOUND;
  39415. #endif
  39416. if( pnLargest ) *pnLargest = nLargest;
  39417. return rc;
  39418. }
  39419. /*
  39420. ** If a Win32 native heap has been configured, this function will attempt to
  39421. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  39422. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  39423. ** be returned and no changes will be made to the Win32 native heap.
  39424. */
  39425. SQLITE_API int sqlite3_win32_reset_heap(){
  39426. int rc;
  39427. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  39428. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  39429. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  39430. MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
  39431. sqlite3_mutex_enter(pMaster);
  39432. sqlite3_mutex_enter(pMem);
  39433. winMemAssertMagic();
  39434. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  39435. /*
  39436. ** At this point, there should be no outstanding memory allocations on
  39437. ** the heap. Also, since both the master and memsys locks are currently
  39438. ** being held by us, no other function (i.e. from another thread) should
  39439. ** be able to even access the heap. Attempt to destroy and recreate our
  39440. ** isolated Win32 native heap now.
  39441. */
  39442. assert( winMemGetHeap()!=NULL );
  39443. assert( winMemGetOwned() );
  39444. assert( sqlite3_memory_used()==0 );
  39445. winMemShutdown(winMemGetDataPtr());
  39446. assert( winMemGetHeap()==NULL );
  39447. assert( !winMemGetOwned() );
  39448. assert( sqlite3_memory_used()==0 );
  39449. rc = winMemInit(winMemGetDataPtr());
  39450. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  39451. assert( rc!=SQLITE_OK || winMemGetOwned() );
  39452. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  39453. }else{
  39454. /*
  39455. ** The Win32 native heap cannot be modified because it may be in use.
  39456. */
  39457. rc = SQLITE_BUSY;
  39458. }
  39459. sqlite3_mutex_leave(pMem);
  39460. sqlite3_mutex_leave(pMaster);
  39461. return rc;
  39462. }
  39463. #endif /* SQLITE_WIN32_MALLOC */
  39464. /*
  39465. ** This function outputs the specified (ANSI) string to the Win32 debugger
  39466. ** (if available).
  39467. */
  39468. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  39469. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  39470. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  39471. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  39472. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  39473. #ifdef SQLITE_ENABLE_API_ARMOR
  39474. if( !zBuf ){
  39475. (void)SQLITE_MISUSE_BKPT;
  39476. return;
  39477. }
  39478. #endif
  39479. #if defined(SQLITE_WIN32_HAS_ANSI)
  39480. if( nMin>0 ){
  39481. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  39482. memcpy(zDbgBuf, zBuf, nMin);
  39483. osOutputDebugStringA(zDbgBuf);
  39484. }else{
  39485. osOutputDebugStringA(zBuf);
  39486. }
  39487. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39488. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  39489. if ( osMultiByteToWideChar(
  39490. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  39491. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  39492. return;
  39493. }
  39494. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  39495. #else
  39496. if( nMin>0 ){
  39497. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  39498. memcpy(zDbgBuf, zBuf, nMin);
  39499. fprintf(stderr, "%s", zDbgBuf);
  39500. }else{
  39501. fprintf(stderr, "%s", zBuf);
  39502. }
  39503. #endif
  39504. }
  39505. /*
  39506. ** The following routine suspends the current thread for at least ms
  39507. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  39508. */
  39509. #if SQLITE_OS_WINRT
  39510. static HANDLE sleepObj = NULL;
  39511. #endif
  39512. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  39513. #if SQLITE_OS_WINRT
  39514. if ( sleepObj==NULL ){
  39515. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  39516. SYNCHRONIZE);
  39517. }
  39518. assert( sleepObj!=NULL );
  39519. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  39520. #else
  39521. osSleep(milliseconds);
  39522. #endif
  39523. }
  39524. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  39525. SQLITE_THREADSAFE>0
  39526. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  39527. DWORD rc;
  39528. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  39529. TRUE))==WAIT_IO_COMPLETION ){}
  39530. return rc;
  39531. }
  39532. #endif
  39533. /*
  39534. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  39535. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  39536. **
  39537. ** Here is an interesting observation: Win95, Win98, and WinME lack
  39538. ** the LockFileEx() API. But we can still statically link against that
  39539. ** API as long as we don't call it when running Win95/98/ME. A call to
  39540. ** this routine is used to determine if the host is Win95/98/ME or
  39541. ** WinNT/2K/XP so that we will know whether or not we can safely call
  39542. ** the LockFileEx() API.
  39543. */
  39544. #if !SQLITE_WIN32_GETVERSIONEX
  39545. # define osIsNT() (1)
  39546. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  39547. # define osIsNT() (1)
  39548. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  39549. # define osIsNT() (0)
  39550. #else
  39551. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  39552. #endif
  39553. /*
  39554. ** This function determines if the machine is running a version of Windows
  39555. ** based on the NT kernel.
  39556. */
  39557. SQLITE_API int sqlite3_win32_is_nt(void){
  39558. #if SQLITE_OS_WINRT
  39559. /*
  39560. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  39561. ** kernel.
  39562. */
  39563. return 1;
  39564. #elif SQLITE_WIN32_GETVERSIONEX
  39565. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  39566. #if defined(SQLITE_WIN32_HAS_ANSI)
  39567. OSVERSIONINFOA sInfo;
  39568. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  39569. osGetVersionExA(&sInfo);
  39570. osInterlockedCompareExchange(&sqlite3_os_type,
  39571. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  39572. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39573. OSVERSIONINFOW sInfo;
  39574. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  39575. osGetVersionExW(&sInfo);
  39576. osInterlockedCompareExchange(&sqlite3_os_type,
  39577. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  39578. #endif
  39579. }
  39580. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  39581. #elif SQLITE_TEST
  39582. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  39583. #else
  39584. /*
  39585. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  39586. ** deprecated are always assumed to be based on the NT kernel.
  39587. */
  39588. return 1;
  39589. #endif
  39590. }
  39591. #ifdef SQLITE_WIN32_MALLOC
  39592. /*
  39593. ** Allocate nBytes of memory.
  39594. */
  39595. static void *winMemMalloc(int nBytes){
  39596. HANDLE hHeap;
  39597. void *p;
  39598. winMemAssertMagic();
  39599. hHeap = winMemGetHeap();
  39600. assert( hHeap!=0 );
  39601. assert( hHeap!=INVALID_HANDLE_VALUE );
  39602. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39603. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39604. #endif
  39605. assert( nBytes>=0 );
  39606. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  39607. if( !p ){
  39608. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  39609. nBytes, osGetLastError(), (void*)hHeap);
  39610. }
  39611. return p;
  39612. }
  39613. /*
  39614. ** Free memory.
  39615. */
  39616. static void winMemFree(void *pPrior){
  39617. HANDLE hHeap;
  39618. winMemAssertMagic();
  39619. hHeap = winMemGetHeap();
  39620. assert( hHeap!=0 );
  39621. assert( hHeap!=INVALID_HANDLE_VALUE );
  39622. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39623. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  39624. #endif
  39625. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  39626. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  39627. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  39628. pPrior, osGetLastError(), (void*)hHeap);
  39629. }
  39630. }
  39631. /*
  39632. ** Change the size of an existing memory allocation
  39633. */
  39634. static void *winMemRealloc(void *pPrior, int nBytes){
  39635. HANDLE hHeap;
  39636. void *p;
  39637. winMemAssertMagic();
  39638. hHeap = winMemGetHeap();
  39639. assert( hHeap!=0 );
  39640. assert( hHeap!=INVALID_HANDLE_VALUE );
  39641. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39642. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  39643. #endif
  39644. assert( nBytes>=0 );
  39645. if( !pPrior ){
  39646. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  39647. }else{
  39648. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  39649. }
  39650. if( !p ){
  39651. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  39652. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  39653. (void*)hHeap);
  39654. }
  39655. return p;
  39656. }
  39657. /*
  39658. ** Return the size of an outstanding allocation, in bytes.
  39659. */
  39660. static int winMemSize(void *p){
  39661. HANDLE hHeap;
  39662. SIZE_T n;
  39663. winMemAssertMagic();
  39664. hHeap = winMemGetHeap();
  39665. assert( hHeap!=0 );
  39666. assert( hHeap!=INVALID_HANDLE_VALUE );
  39667. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39668. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  39669. #endif
  39670. if( !p ) return 0;
  39671. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  39672. if( n==(SIZE_T)-1 ){
  39673. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  39674. p, osGetLastError(), (void*)hHeap);
  39675. return 0;
  39676. }
  39677. return (int)n;
  39678. }
  39679. /*
  39680. ** Round up a request size to the next valid allocation size.
  39681. */
  39682. static int winMemRoundup(int n){
  39683. return n;
  39684. }
  39685. /*
  39686. ** Initialize this module.
  39687. */
  39688. static int winMemInit(void *pAppData){
  39689. winMemData *pWinMemData = (winMemData *)pAppData;
  39690. if( !pWinMemData ) return SQLITE_ERROR;
  39691. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  39692. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  39693. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  39694. if( !pWinMemData->hHeap ){
  39695. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  39696. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  39697. if( dwMaximumSize==0 ){
  39698. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  39699. }else if( dwInitialSize>dwMaximumSize ){
  39700. dwInitialSize = dwMaximumSize;
  39701. }
  39702. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  39703. dwInitialSize, dwMaximumSize);
  39704. if( !pWinMemData->hHeap ){
  39705. sqlite3_log(SQLITE_NOMEM,
  39706. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  39707. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  39708. dwMaximumSize);
  39709. return SQLITE_NOMEM_BKPT;
  39710. }
  39711. pWinMemData->bOwned = TRUE;
  39712. assert( pWinMemData->bOwned );
  39713. }
  39714. #else
  39715. pWinMemData->hHeap = osGetProcessHeap();
  39716. if( !pWinMemData->hHeap ){
  39717. sqlite3_log(SQLITE_NOMEM,
  39718. "failed to GetProcessHeap (%lu)", osGetLastError());
  39719. return SQLITE_NOMEM_BKPT;
  39720. }
  39721. pWinMemData->bOwned = FALSE;
  39722. assert( !pWinMemData->bOwned );
  39723. #endif
  39724. assert( pWinMemData->hHeap!=0 );
  39725. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  39726. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39727. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39728. #endif
  39729. return SQLITE_OK;
  39730. }
  39731. /*
  39732. ** Deinitialize this module.
  39733. */
  39734. static void winMemShutdown(void *pAppData){
  39735. winMemData *pWinMemData = (winMemData *)pAppData;
  39736. if( !pWinMemData ) return;
  39737. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  39738. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  39739. if( pWinMemData->hHeap ){
  39740. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  39741. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  39742. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  39743. #endif
  39744. if( pWinMemData->bOwned ){
  39745. if( !osHeapDestroy(pWinMemData->hHeap) ){
  39746. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  39747. osGetLastError(), (void*)pWinMemData->hHeap);
  39748. }
  39749. pWinMemData->bOwned = FALSE;
  39750. }
  39751. pWinMemData->hHeap = NULL;
  39752. }
  39753. }
  39754. /*
  39755. ** Populate the low-level memory allocation function pointers in
  39756. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  39757. ** arguments specify the block of memory to manage.
  39758. **
  39759. ** This routine is only called by sqlite3_config(), and therefore
  39760. ** is not required to be threadsafe (it is not).
  39761. */
  39762. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  39763. static const sqlite3_mem_methods winMemMethods = {
  39764. winMemMalloc,
  39765. winMemFree,
  39766. winMemRealloc,
  39767. winMemSize,
  39768. winMemRoundup,
  39769. winMemInit,
  39770. winMemShutdown,
  39771. &win_mem_data
  39772. };
  39773. return &winMemMethods;
  39774. }
  39775. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  39776. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  39777. }
  39778. #endif /* SQLITE_WIN32_MALLOC */
  39779. /*
  39780. ** Convert a UTF-8 string to Microsoft Unicode.
  39781. **
  39782. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39783. */
  39784. static LPWSTR winUtf8ToUnicode(const char *zText){
  39785. int nChar;
  39786. LPWSTR zWideText;
  39787. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
  39788. if( nChar==0 ){
  39789. return 0;
  39790. }
  39791. zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
  39792. if( zWideText==0 ){
  39793. return 0;
  39794. }
  39795. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
  39796. nChar);
  39797. if( nChar==0 ){
  39798. sqlite3_free(zWideText);
  39799. zWideText = 0;
  39800. }
  39801. return zWideText;
  39802. }
  39803. /*
  39804. ** Convert a Microsoft Unicode string to UTF-8.
  39805. **
  39806. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39807. */
  39808. static char *winUnicodeToUtf8(LPCWSTR zWideText){
  39809. int nByte;
  39810. char *zText;
  39811. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
  39812. if( nByte == 0 ){
  39813. return 0;
  39814. }
  39815. zText = sqlite3MallocZero( nByte );
  39816. if( zText==0 ){
  39817. return 0;
  39818. }
  39819. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
  39820. 0, 0);
  39821. if( nByte == 0 ){
  39822. sqlite3_free(zText);
  39823. zText = 0;
  39824. }
  39825. return zText;
  39826. }
  39827. /*
  39828. ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
  39829. ** code page.
  39830. **
  39831. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39832. */
  39833. static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
  39834. int nByte;
  39835. LPWSTR zMbcsText;
  39836. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  39837. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
  39838. 0)*sizeof(WCHAR);
  39839. if( nByte==0 ){
  39840. return 0;
  39841. }
  39842. zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
  39843. if( zMbcsText==0 ){
  39844. return 0;
  39845. }
  39846. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
  39847. nByte);
  39848. if( nByte==0 ){
  39849. sqlite3_free(zMbcsText);
  39850. zMbcsText = 0;
  39851. }
  39852. return zMbcsText;
  39853. }
  39854. /*
  39855. ** Convert a Microsoft Unicode string to a multi-byte character string,
  39856. ** using the ANSI or OEM code page.
  39857. **
  39858. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39859. */
  39860. static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
  39861. int nByte;
  39862. char *zText;
  39863. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  39864. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
  39865. if( nByte == 0 ){
  39866. return 0;
  39867. }
  39868. zText = sqlite3MallocZero( nByte );
  39869. if( zText==0 ){
  39870. return 0;
  39871. }
  39872. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
  39873. nByte, 0, 0);
  39874. if( nByte == 0 ){
  39875. sqlite3_free(zText);
  39876. zText = 0;
  39877. }
  39878. return zText;
  39879. }
  39880. /*
  39881. ** Convert a multi-byte character string to UTF-8.
  39882. **
  39883. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39884. */
  39885. static char *winMbcsToUtf8(const char *zText, int useAnsi){
  39886. char *zTextUtf8;
  39887. LPWSTR zTmpWide;
  39888. zTmpWide = winMbcsToUnicode(zText, useAnsi);
  39889. if( zTmpWide==0 ){
  39890. return 0;
  39891. }
  39892. zTextUtf8 = winUnicodeToUtf8(zTmpWide);
  39893. sqlite3_free(zTmpWide);
  39894. return zTextUtf8;
  39895. }
  39896. /*
  39897. ** Convert a UTF-8 string to a multi-byte character string.
  39898. **
  39899. ** Space to hold the returned string is obtained from sqlite3_malloc().
  39900. */
  39901. static char *winUtf8ToMbcs(const char *zText, int useAnsi){
  39902. char *zTextMbcs;
  39903. LPWSTR zTmpWide;
  39904. zTmpWide = winUtf8ToUnicode(zText);
  39905. if( zTmpWide==0 ){
  39906. return 0;
  39907. }
  39908. zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
  39909. sqlite3_free(zTmpWide);
  39910. return zTextMbcs;
  39911. }
  39912. /*
  39913. ** This is a public wrapper for the winUtf8ToUnicode() function.
  39914. */
  39915. SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
  39916. #ifdef SQLITE_ENABLE_API_ARMOR
  39917. if( !zText ){
  39918. (void)SQLITE_MISUSE_BKPT;
  39919. return 0;
  39920. }
  39921. #endif
  39922. #ifndef SQLITE_OMIT_AUTOINIT
  39923. if( sqlite3_initialize() ) return 0;
  39924. #endif
  39925. return winUtf8ToUnicode(zText);
  39926. }
  39927. /*
  39928. ** This is a public wrapper for the winUnicodeToUtf8() function.
  39929. */
  39930. SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
  39931. #ifdef SQLITE_ENABLE_API_ARMOR
  39932. if( !zWideText ){
  39933. (void)SQLITE_MISUSE_BKPT;
  39934. return 0;
  39935. }
  39936. #endif
  39937. #ifndef SQLITE_OMIT_AUTOINIT
  39938. if( sqlite3_initialize() ) return 0;
  39939. #endif
  39940. return winUnicodeToUtf8(zWideText);
  39941. }
  39942. /*
  39943. ** This is a public wrapper for the winMbcsToUtf8() function.
  39944. */
  39945. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
  39946. #ifdef SQLITE_ENABLE_API_ARMOR
  39947. if( !zText ){
  39948. (void)SQLITE_MISUSE_BKPT;
  39949. return 0;
  39950. }
  39951. #endif
  39952. #ifndef SQLITE_OMIT_AUTOINIT
  39953. if( sqlite3_initialize() ) return 0;
  39954. #endif
  39955. return winMbcsToUtf8(zText, osAreFileApisANSI());
  39956. }
  39957. /*
  39958. ** This is a public wrapper for the winMbcsToUtf8() function.
  39959. */
  39960. SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
  39961. #ifdef SQLITE_ENABLE_API_ARMOR
  39962. if( !zText ){
  39963. (void)SQLITE_MISUSE_BKPT;
  39964. return 0;
  39965. }
  39966. #endif
  39967. #ifndef SQLITE_OMIT_AUTOINIT
  39968. if( sqlite3_initialize() ) return 0;
  39969. #endif
  39970. return winMbcsToUtf8(zText, useAnsi);
  39971. }
  39972. /*
  39973. ** This is a public wrapper for the winUtf8ToMbcs() function.
  39974. */
  39975. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
  39976. #ifdef SQLITE_ENABLE_API_ARMOR
  39977. if( !zText ){
  39978. (void)SQLITE_MISUSE_BKPT;
  39979. return 0;
  39980. }
  39981. #endif
  39982. #ifndef SQLITE_OMIT_AUTOINIT
  39983. if( sqlite3_initialize() ) return 0;
  39984. #endif
  39985. return winUtf8ToMbcs(zText, osAreFileApisANSI());
  39986. }
  39987. /*
  39988. ** This is a public wrapper for the winUtf8ToMbcs() function.
  39989. */
  39990. SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
  39991. #ifdef SQLITE_ENABLE_API_ARMOR
  39992. if( !zText ){
  39993. (void)SQLITE_MISUSE_BKPT;
  39994. return 0;
  39995. }
  39996. #endif
  39997. #ifndef SQLITE_OMIT_AUTOINIT
  39998. if( sqlite3_initialize() ) return 0;
  39999. #endif
  40000. return winUtf8ToMbcs(zText, useAnsi);
  40001. }
  40002. /*
  40003. ** This function is the same as sqlite3_win32_set_directory (below); however,
  40004. ** it accepts a UTF-8 string.
  40005. */
  40006. SQLITE_API int sqlite3_win32_set_directory8(
  40007. unsigned long type, /* Identifier for directory being set or reset */
  40008. const char *zValue /* New value for directory being set or reset */
  40009. ){
  40010. char **ppDirectory = 0;
  40011. #ifndef SQLITE_OMIT_AUTOINIT
  40012. int rc = sqlite3_initialize();
  40013. if( rc ) return rc;
  40014. #endif
  40015. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  40016. ppDirectory = &sqlite3_data_directory;
  40017. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  40018. ppDirectory = &sqlite3_temp_directory;
  40019. }
  40020. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  40021. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  40022. );
  40023. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  40024. if( ppDirectory ){
  40025. char *zCopy = 0;
  40026. if( zValue && zValue[0] ){
  40027. zCopy = sqlite3_mprintf("%s", zValue);
  40028. if ( zCopy==0 ){
  40029. return SQLITE_NOMEM_BKPT;
  40030. }
  40031. }
  40032. sqlite3_free(*ppDirectory);
  40033. *ppDirectory = zCopy;
  40034. return SQLITE_OK;
  40035. }
  40036. return SQLITE_ERROR;
  40037. }
  40038. /*
  40039. ** This function is the same as sqlite3_win32_set_directory (below); however,
  40040. ** it accepts a UTF-16 string.
  40041. */
  40042. SQLITE_API int sqlite3_win32_set_directory16(
  40043. unsigned long type, /* Identifier for directory being set or reset */
  40044. const void *zValue /* New value for directory being set or reset */
  40045. ){
  40046. int rc;
  40047. char *zUtf8 = 0;
  40048. if( zValue ){
  40049. zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
  40050. if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
  40051. }
  40052. rc = sqlite3_win32_set_directory8(type, zUtf8);
  40053. if( zUtf8 ) sqlite3_free(zUtf8);
  40054. return rc;
  40055. }
  40056. /*
  40057. ** This function sets the data directory or the temporary directory based on
  40058. ** the provided arguments. The type argument must be 1 in order to set the
  40059. ** data directory or 2 in order to set the temporary directory. The zValue
  40060. ** argument is the name of the directory to use. The return value will be
  40061. ** SQLITE_OK if successful.
  40062. */
  40063. SQLITE_API int sqlite3_win32_set_directory(
  40064. unsigned long type, /* Identifier for directory being set or reset */
  40065. void *zValue /* New value for directory being set or reset */
  40066. ){
  40067. return sqlite3_win32_set_directory16(type, zValue);
  40068. }
  40069. /*
  40070. ** The return value of winGetLastErrorMsg
  40071. ** is zero if the error message fits in the buffer, or non-zero
  40072. ** otherwise (if the message was truncated).
  40073. */
  40074. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  40075. /* FormatMessage returns 0 on failure. Otherwise it
  40076. ** returns the number of TCHARs written to the output
  40077. ** buffer, excluding the terminating null char.
  40078. */
  40079. DWORD dwLen = 0;
  40080. char *zOut = 0;
  40081. if( osIsNT() ){
  40082. #if SQLITE_OS_WINRT
  40083. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  40084. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  40085. FORMAT_MESSAGE_IGNORE_INSERTS,
  40086. NULL,
  40087. lastErrno,
  40088. 0,
  40089. zTempWide,
  40090. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  40091. 0);
  40092. #else
  40093. LPWSTR zTempWide = NULL;
  40094. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  40095. FORMAT_MESSAGE_FROM_SYSTEM |
  40096. FORMAT_MESSAGE_IGNORE_INSERTS,
  40097. NULL,
  40098. lastErrno,
  40099. 0,
  40100. (LPWSTR) &zTempWide,
  40101. 0,
  40102. 0);
  40103. #endif
  40104. if( dwLen > 0 ){
  40105. /* allocate a buffer and convert to UTF8 */
  40106. sqlite3BeginBenignMalloc();
  40107. zOut = winUnicodeToUtf8(zTempWide);
  40108. sqlite3EndBenignMalloc();
  40109. #if !SQLITE_OS_WINRT
  40110. /* free the system buffer allocated by FormatMessage */
  40111. osLocalFree(zTempWide);
  40112. #endif
  40113. }
  40114. }
  40115. #ifdef SQLITE_WIN32_HAS_ANSI
  40116. else{
  40117. char *zTemp = NULL;
  40118. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  40119. FORMAT_MESSAGE_FROM_SYSTEM |
  40120. FORMAT_MESSAGE_IGNORE_INSERTS,
  40121. NULL,
  40122. lastErrno,
  40123. 0,
  40124. (LPSTR) &zTemp,
  40125. 0,
  40126. 0);
  40127. if( dwLen > 0 ){
  40128. /* allocate a buffer and convert to UTF8 */
  40129. sqlite3BeginBenignMalloc();
  40130. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  40131. sqlite3EndBenignMalloc();
  40132. /* free the system buffer allocated by FormatMessage */
  40133. osLocalFree(zTemp);
  40134. }
  40135. }
  40136. #endif
  40137. if( 0 == dwLen ){
  40138. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  40139. }else{
  40140. /* copy a maximum of nBuf chars to output buffer */
  40141. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  40142. /* free the UTF8 buffer */
  40143. sqlite3_free(zOut);
  40144. }
  40145. return 0;
  40146. }
  40147. /*
  40148. **
  40149. ** This function - winLogErrorAtLine() - is only ever called via the macro
  40150. ** winLogError().
  40151. **
  40152. ** This routine is invoked after an error occurs in an OS function.
  40153. ** It logs a message using sqlite3_log() containing the current value of
  40154. ** error code and, if possible, the human-readable equivalent from
  40155. ** FormatMessage.
  40156. **
  40157. ** The first argument passed to the macro should be the error code that
  40158. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  40159. ** The two subsequent arguments should be the name of the OS function that
  40160. ** failed and the associated file-system path, if any.
  40161. */
  40162. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  40163. static int winLogErrorAtLine(
  40164. int errcode, /* SQLite error code */
  40165. DWORD lastErrno, /* Win32 last error */
  40166. const char *zFunc, /* Name of OS function that failed */
  40167. const char *zPath, /* File path associated with error */
  40168. int iLine /* Source line number where error occurred */
  40169. ){
  40170. char zMsg[500]; /* Human readable error text */
  40171. int i; /* Loop counter */
  40172. zMsg[0] = 0;
  40173. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  40174. assert( errcode!=SQLITE_OK );
  40175. if( zPath==0 ) zPath = "";
  40176. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  40177. zMsg[i] = 0;
  40178. sqlite3_log(errcode,
  40179. "os_win.c:%d: (%lu) %s(%s) - %s",
  40180. iLine, lastErrno, zFunc, zPath, zMsg
  40181. );
  40182. return errcode;
  40183. }
  40184. /*
  40185. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  40186. ** will be retried following a locking error - probably caused by
  40187. ** antivirus software. Also the initial delay before the first retry.
  40188. ** The delay increases linearly with each retry.
  40189. */
  40190. #ifndef SQLITE_WIN32_IOERR_RETRY
  40191. # define SQLITE_WIN32_IOERR_RETRY 10
  40192. #endif
  40193. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  40194. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  40195. #endif
  40196. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  40197. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  40198. /*
  40199. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  40200. ** error code obtained via GetLastError() is eligible to be retried. It
  40201. ** must accept the error code DWORD as its only argument and should return
  40202. ** non-zero if the error code is transient in nature and the operation
  40203. ** responsible for generating the original error might succeed upon being
  40204. ** retried. The argument to this macro should be a variable.
  40205. **
  40206. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  40207. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  40208. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  40209. ** may be used to include additional error codes in the set that should
  40210. ** result in the failing I/O operation being retried by the caller. If
  40211. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  40212. ** identical to those of the "winIoerrCanRetry1" macro.
  40213. */
  40214. #if !defined(winIoerrCanRetry1)
  40215. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  40216. ((a)==ERROR_SHARING_VIOLATION) || \
  40217. ((a)==ERROR_LOCK_VIOLATION) || \
  40218. ((a)==ERROR_DEV_NOT_EXIST) || \
  40219. ((a)==ERROR_NETNAME_DELETED) || \
  40220. ((a)==ERROR_SEM_TIMEOUT) || \
  40221. ((a)==ERROR_NETWORK_UNREACHABLE))
  40222. #endif
  40223. /*
  40224. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  40225. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  40226. ** to give up with an error.
  40227. */
  40228. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  40229. DWORD e = osGetLastError();
  40230. if( *pnRetry>=winIoerrRetry ){
  40231. if( pError ){
  40232. *pError = e;
  40233. }
  40234. return 0;
  40235. }
  40236. if( winIoerrCanRetry1(e) ){
  40237. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  40238. ++*pnRetry;
  40239. return 1;
  40240. }
  40241. #if defined(winIoerrCanRetry2)
  40242. else if( winIoerrCanRetry2(e) ){
  40243. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  40244. ++*pnRetry;
  40245. return 1;
  40246. }
  40247. #endif
  40248. if( pError ){
  40249. *pError = e;
  40250. }
  40251. return 0;
  40252. }
  40253. /*
  40254. ** Log a I/O error retry episode.
  40255. */
  40256. static void winLogIoerr(int nRetry, int lineno){
  40257. if( nRetry ){
  40258. sqlite3_log(SQLITE_NOTICE,
  40259. "delayed %dms for lock/sharing conflict at line %d",
  40260. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  40261. );
  40262. }
  40263. }
  40264. /*
  40265. ** This #if does not rely on the SQLITE_OS_WINCE define because the
  40266. ** corresponding section in "date.c" cannot use it.
  40267. */
  40268. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  40269. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  40270. /*
  40271. ** The MSVC CRT on Windows CE may not have a localtime() function.
  40272. ** So define a substitute.
  40273. */
  40274. /* # include <time.h> */
  40275. struct tm *__cdecl localtime(const time_t *t)
  40276. {
  40277. static struct tm y;
  40278. FILETIME uTm, lTm;
  40279. SYSTEMTIME pTm;
  40280. sqlite3_int64 t64;
  40281. t64 = *t;
  40282. t64 = (t64 + 11644473600)*10000000;
  40283. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  40284. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  40285. osFileTimeToLocalFileTime(&uTm,&lTm);
  40286. osFileTimeToSystemTime(&lTm,&pTm);
  40287. y.tm_year = pTm.wYear - 1900;
  40288. y.tm_mon = pTm.wMonth - 1;
  40289. y.tm_wday = pTm.wDayOfWeek;
  40290. y.tm_mday = pTm.wDay;
  40291. y.tm_hour = pTm.wHour;
  40292. y.tm_min = pTm.wMinute;
  40293. y.tm_sec = pTm.wSecond;
  40294. return &y;
  40295. }
  40296. #endif
  40297. #if SQLITE_OS_WINCE
  40298. /*************************************************************************
  40299. ** This section contains code for WinCE only.
  40300. */
  40301. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  40302. /*
  40303. ** Acquire a lock on the handle h
  40304. */
  40305. static void winceMutexAcquire(HANDLE h){
  40306. DWORD dwErr;
  40307. do {
  40308. dwErr = osWaitForSingleObject(h, INFINITE);
  40309. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  40310. }
  40311. /*
  40312. ** Release a lock acquired by winceMutexAcquire()
  40313. */
  40314. #define winceMutexRelease(h) ReleaseMutex(h)
  40315. /*
  40316. ** Create the mutex and shared memory used for locking in the file
  40317. ** descriptor pFile
  40318. */
  40319. static int winceCreateLock(const char *zFilename, winFile *pFile){
  40320. LPWSTR zTok;
  40321. LPWSTR zName;
  40322. DWORD lastErrno;
  40323. BOOL bLogged = FALSE;
  40324. BOOL bInit = TRUE;
  40325. zName = winUtf8ToUnicode(zFilename);
  40326. if( zName==0 ){
  40327. /* out of memory */
  40328. return SQLITE_IOERR_NOMEM_BKPT;
  40329. }
  40330. /* Initialize the local lockdata */
  40331. memset(&pFile->local, 0, sizeof(pFile->local));
  40332. /* Replace the backslashes from the filename and lowercase it
  40333. ** to derive a mutex name. */
  40334. zTok = osCharLowerW(zName);
  40335. for (;*zTok;zTok++){
  40336. if (*zTok == '\\') *zTok = '_';
  40337. }
  40338. /* Create/open the named mutex */
  40339. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  40340. if (!pFile->hMutex){
  40341. pFile->lastErrno = osGetLastError();
  40342. sqlite3_free(zName);
  40343. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  40344. "winceCreateLock1", zFilename);
  40345. }
  40346. /* Acquire the mutex before continuing */
  40347. winceMutexAcquire(pFile->hMutex);
  40348. /* Since the names of named mutexes, semaphores, file mappings etc are
  40349. ** case-sensitive, take advantage of that by uppercasing the mutex name
  40350. ** and using that as the shared filemapping name.
  40351. */
  40352. osCharUpperW(zName);
  40353. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  40354. PAGE_READWRITE, 0, sizeof(winceLock),
  40355. zName);
  40356. /* Set a flag that indicates we're the first to create the memory so it
  40357. ** must be zero-initialized */
  40358. lastErrno = osGetLastError();
  40359. if (lastErrno == ERROR_ALREADY_EXISTS){
  40360. bInit = FALSE;
  40361. }
  40362. sqlite3_free(zName);
  40363. /* If we succeeded in making the shared memory handle, map it. */
  40364. if( pFile->hShared ){
  40365. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  40366. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  40367. /* If mapping failed, close the shared memory handle and erase it */
  40368. if( !pFile->shared ){
  40369. pFile->lastErrno = osGetLastError();
  40370. winLogError(SQLITE_IOERR, pFile->lastErrno,
  40371. "winceCreateLock2", zFilename);
  40372. bLogged = TRUE;
  40373. osCloseHandle(pFile->hShared);
  40374. pFile->hShared = NULL;
  40375. }
  40376. }
  40377. /* If shared memory could not be created, then close the mutex and fail */
  40378. if( pFile->hShared==NULL ){
  40379. if( !bLogged ){
  40380. pFile->lastErrno = lastErrno;
  40381. winLogError(SQLITE_IOERR, pFile->lastErrno,
  40382. "winceCreateLock3", zFilename);
  40383. bLogged = TRUE;
  40384. }
  40385. winceMutexRelease(pFile->hMutex);
  40386. osCloseHandle(pFile->hMutex);
  40387. pFile->hMutex = NULL;
  40388. return SQLITE_IOERR;
  40389. }
  40390. /* Initialize the shared memory if we're supposed to */
  40391. if( bInit ){
  40392. memset(pFile->shared, 0, sizeof(winceLock));
  40393. }
  40394. winceMutexRelease(pFile->hMutex);
  40395. return SQLITE_OK;
  40396. }
  40397. /*
  40398. ** Destroy the part of winFile that deals with wince locks
  40399. */
  40400. static void winceDestroyLock(winFile *pFile){
  40401. if (pFile->hMutex){
  40402. /* Acquire the mutex */
  40403. winceMutexAcquire(pFile->hMutex);
  40404. /* The following blocks should probably assert in debug mode, but they
  40405. are to cleanup in case any locks remained open */
  40406. if (pFile->local.nReaders){
  40407. pFile->shared->nReaders --;
  40408. }
  40409. if (pFile->local.bReserved){
  40410. pFile->shared->bReserved = FALSE;
  40411. }
  40412. if (pFile->local.bPending){
  40413. pFile->shared->bPending = FALSE;
  40414. }
  40415. if (pFile->local.bExclusive){
  40416. pFile->shared->bExclusive = FALSE;
  40417. }
  40418. /* De-reference and close our copy of the shared memory handle */
  40419. osUnmapViewOfFile(pFile->shared);
  40420. osCloseHandle(pFile->hShared);
  40421. /* Done with the mutex */
  40422. winceMutexRelease(pFile->hMutex);
  40423. osCloseHandle(pFile->hMutex);
  40424. pFile->hMutex = NULL;
  40425. }
  40426. }
  40427. /*
  40428. ** An implementation of the LockFile() API of Windows for CE
  40429. */
  40430. static BOOL winceLockFile(
  40431. LPHANDLE phFile,
  40432. DWORD dwFileOffsetLow,
  40433. DWORD dwFileOffsetHigh,
  40434. DWORD nNumberOfBytesToLockLow,
  40435. DWORD nNumberOfBytesToLockHigh
  40436. ){
  40437. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  40438. BOOL bReturn = FALSE;
  40439. UNUSED_PARAMETER(dwFileOffsetHigh);
  40440. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  40441. if (!pFile->hMutex) return TRUE;
  40442. winceMutexAcquire(pFile->hMutex);
  40443. /* Wanting an exclusive lock? */
  40444. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  40445. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  40446. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  40447. pFile->shared->bExclusive = TRUE;
  40448. pFile->local.bExclusive = TRUE;
  40449. bReturn = TRUE;
  40450. }
  40451. }
  40452. /* Want a read-only lock? */
  40453. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  40454. nNumberOfBytesToLockLow == 1){
  40455. if (pFile->shared->bExclusive == 0){
  40456. pFile->local.nReaders ++;
  40457. if (pFile->local.nReaders == 1){
  40458. pFile->shared->nReaders ++;
  40459. }
  40460. bReturn = TRUE;
  40461. }
  40462. }
  40463. /* Want a pending lock? */
  40464. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  40465. && nNumberOfBytesToLockLow == 1){
  40466. /* If no pending lock has been acquired, then acquire it */
  40467. if (pFile->shared->bPending == 0) {
  40468. pFile->shared->bPending = TRUE;
  40469. pFile->local.bPending = TRUE;
  40470. bReturn = TRUE;
  40471. }
  40472. }
  40473. /* Want a reserved lock? */
  40474. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  40475. && nNumberOfBytesToLockLow == 1){
  40476. if (pFile->shared->bReserved == 0) {
  40477. pFile->shared->bReserved = TRUE;
  40478. pFile->local.bReserved = TRUE;
  40479. bReturn = TRUE;
  40480. }
  40481. }
  40482. winceMutexRelease(pFile->hMutex);
  40483. return bReturn;
  40484. }
  40485. /*
  40486. ** An implementation of the UnlockFile API of Windows for CE
  40487. */
  40488. static BOOL winceUnlockFile(
  40489. LPHANDLE phFile,
  40490. DWORD dwFileOffsetLow,
  40491. DWORD dwFileOffsetHigh,
  40492. DWORD nNumberOfBytesToUnlockLow,
  40493. DWORD nNumberOfBytesToUnlockHigh
  40494. ){
  40495. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  40496. BOOL bReturn = FALSE;
  40497. UNUSED_PARAMETER(dwFileOffsetHigh);
  40498. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  40499. if (!pFile->hMutex) return TRUE;
  40500. winceMutexAcquire(pFile->hMutex);
  40501. /* Releasing a reader lock or an exclusive lock */
  40502. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  40503. /* Did we have an exclusive lock? */
  40504. if (pFile->local.bExclusive){
  40505. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  40506. pFile->local.bExclusive = FALSE;
  40507. pFile->shared->bExclusive = FALSE;
  40508. bReturn = TRUE;
  40509. }
  40510. /* Did we just have a reader lock? */
  40511. else if (pFile->local.nReaders){
  40512. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  40513. || nNumberOfBytesToUnlockLow == 1);
  40514. pFile->local.nReaders --;
  40515. if (pFile->local.nReaders == 0)
  40516. {
  40517. pFile->shared->nReaders --;
  40518. }
  40519. bReturn = TRUE;
  40520. }
  40521. }
  40522. /* Releasing a pending lock */
  40523. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  40524. && nNumberOfBytesToUnlockLow == 1){
  40525. if (pFile->local.bPending){
  40526. pFile->local.bPending = FALSE;
  40527. pFile->shared->bPending = FALSE;
  40528. bReturn = TRUE;
  40529. }
  40530. }
  40531. /* Releasing a reserved lock */
  40532. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  40533. && nNumberOfBytesToUnlockLow == 1){
  40534. if (pFile->local.bReserved) {
  40535. pFile->local.bReserved = FALSE;
  40536. pFile->shared->bReserved = FALSE;
  40537. bReturn = TRUE;
  40538. }
  40539. }
  40540. winceMutexRelease(pFile->hMutex);
  40541. return bReturn;
  40542. }
  40543. /*
  40544. ** End of the special code for wince
  40545. *****************************************************************************/
  40546. #endif /* SQLITE_OS_WINCE */
  40547. /*
  40548. ** Lock a file region.
  40549. */
  40550. static BOOL winLockFile(
  40551. LPHANDLE phFile,
  40552. DWORD flags,
  40553. DWORD offsetLow,
  40554. DWORD offsetHigh,
  40555. DWORD numBytesLow,
  40556. DWORD numBytesHigh
  40557. ){
  40558. #if SQLITE_OS_WINCE
  40559. /*
  40560. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  40561. ** API LockFile.
  40562. */
  40563. return winceLockFile(phFile, offsetLow, offsetHigh,
  40564. numBytesLow, numBytesHigh);
  40565. #else
  40566. if( osIsNT() ){
  40567. OVERLAPPED ovlp;
  40568. memset(&ovlp, 0, sizeof(OVERLAPPED));
  40569. ovlp.Offset = offsetLow;
  40570. ovlp.OffsetHigh = offsetHigh;
  40571. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  40572. }else{
  40573. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  40574. numBytesHigh);
  40575. }
  40576. #endif
  40577. }
  40578. /*
  40579. ** Unlock a file region.
  40580. */
  40581. static BOOL winUnlockFile(
  40582. LPHANDLE phFile,
  40583. DWORD offsetLow,
  40584. DWORD offsetHigh,
  40585. DWORD numBytesLow,
  40586. DWORD numBytesHigh
  40587. ){
  40588. #if SQLITE_OS_WINCE
  40589. /*
  40590. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  40591. ** API UnlockFile.
  40592. */
  40593. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  40594. numBytesLow, numBytesHigh);
  40595. #else
  40596. if( osIsNT() ){
  40597. OVERLAPPED ovlp;
  40598. memset(&ovlp, 0, sizeof(OVERLAPPED));
  40599. ovlp.Offset = offsetLow;
  40600. ovlp.OffsetHigh = offsetHigh;
  40601. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  40602. }else{
  40603. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  40604. numBytesHigh);
  40605. }
  40606. #endif
  40607. }
  40608. /*****************************************************************************
  40609. ** The next group of routines implement the I/O methods specified
  40610. ** by the sqlite3_io_methods object.
  40611. ******************************************************************************/
  40612. /*
  40613. ** Some Microsoft compilers lack this definition.
  40614. */
  40615. #ifndef INVALID_SET_FILE_POINTER
  40616. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  40617. #endif
  40618. /*
  40619. ** Move the current position of the file handle passed as the first
  40620. ** argument to offset iOffset within the file. If successful, return 0.
  40621. ** Otherwise, set pFile->lastErrno and return non-zero.
  40622. */
  40623. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  40624. #if !SQLITE_OS_WINRT
  40625. LONG upperBits; /* Most sig. 32 bits of new offset */
  40626. LONG lowerBits; /* Least sig. 32 bits of new offset */
  40627. DWORD dwRet; /* Value returned by SetFilePointer() */
  40628. DWORD lastErrno; /* Value returned by GetLastError() */
  40629. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  40630. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  40631. lowerBits = (LONG)(iOffset & 0xffffffff);
  40632. /* API oddity: If successful, SetFilePointer() returns a dword
  40633. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  40634. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  40635. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  40636. ** whether an error has actually occurred, it is also necessary to call
  40637. ** GetLastError().
  40638. */
  40639. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  40640. if( (dwRet==INVALID_SET_FILE_POINTER
  40641. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  40642. pFile->lastErrno = lastErrno;
  40643. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  40644. "winSeekFile", pFile->zPath);
  40645. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  40646. return 1;
  40647. }
  40648. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  40649. return 0;
  40650. #else
  40651. /*
  40652. ** Same as above, except that this implementation works for WinRT.
  40653. */
  40654. LARGE_INTEGER x; /* The new offset */
  40655. BOOL bRet; /* Value returned by SetFilePointerEx() */
  40656. x.QuadPart = iOffset;
  40657. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  40658. if(!bRet){
  40659. pFile->lastErrno = osGetLastError();
  40660. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  40661. "winSeekFile", pFile->zPath);
  40662. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  40663. return 1;
  40664. }
  40665. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  40666. return 0;
  40667. #endif
  40668. }
  40669. #if SQLITE_MAX_MMAP_SIZE>0
  40670. /* Forward references to VFS helper methods used for memory mapped files */
  40671. static int winMapfile(winFile*, sqlite3_int64);
  40672. static int winUnmapfile(winFile*);
  40673. #endif
  40674. /*
  40675. ** Close a file.
  40676. **
  40677. ** It is reported that an attempt to close a handle might sometimes
  40678. ** fail. This is a very unreasonable result, but Windows is notorious
  40679. ** for being unreasonable so I do not doubt that it might happen. If
  40680. ** the close fails, we pause for 100 milliseconds and try again. As
  40681. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  40682. ** giving up and returning an error.
  40683. */
  40684. #define MX_CLOSE_ATTEMPT 3
  40685. static int winClose(sqlite3_file *id){
  40686. int rc, cnt = 0;
  40687. winFile *pFile = (winFile*)id;
  40688. assert( id!=0 );
  40689. #ifndef SQLITE_OMIT_WAL
  40690. assert( pFile->pShm==0 );
  40691. #endif
  40692. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  40693. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  40694. osGetCurrentProcessId(), pFile, pFile->h));
  40695. #if SQLITE_MAX_MMAP_SIZE>0
  40696. winUnmapfile(pFile);
  40697. #endif
  40698. do{
  40699. rc = osCloseHandle(pFile->h);
  40700. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  40701. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  40702. #if SQLITE_OS_WINCE
  40703. #define WINCE_DELETION_ATTEMPTS 3
  40704. {
  40705. winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
  40706. if( pAppData==NULL || !pAppData->bNoLock ){
  40707. winceDestroyLock(pFile);
  40708. }
  40709. }
  40710. if( pFile->zDeleteOnClose ){
  40711. int cnt = 0;
  40712. while(
  40713. osDeleteFileW(pFile->zDeleteOnClose)==0
  40714. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  40715. && cnt++ < WINCE_DELETION_ATTEMPTS
  40716. ){
  40717. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  40718. }
  40719. sqlite3_free(pFile->zDeleteOnClose);
  40720. }
  40721. #endif
  40722. if( rc ){
  40723. pFile->h = NULL;
  40724. }
  40725. OpenCounter(-1);
  40726. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  40727. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  40728. return rc ? SQLITE_OK
  40729. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  40730. "winClose", pFile->zPath);
  40731. }
  40732. /*
  40733. ** Read data from a file into a buffer. Return SQLITE_OK if all
  40734. ** bytes were read successfully and SQLITE_IOERR if anything goes
  40735. ** wrong.
  40736. */
  40737. static int winRead(
  40738. sqlite3_file *id, /* File to read from */
  40739. void *pBuf, /* Write content into this buffer */
  40740. int amt, /* Number of bytes to read */
  40741. sqlite3_int64 offset /* Begin reading at this offset */
  40742. ){
  40743. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40744. OVERLAPPED overlapped; /* The offset for ReadFile. */
  40745. #endif
  40746. winFile *pFile = (winFile*)id; /* file handle */
  40747. DWORD nRead; /* Number of bytes actually read from file */
  40748. int nRetry = 0; /* Number of retrys */
  40749. assert( id!=0 );
  40750. assert( amt>0 );
  40751. assert( offset>=0 );
  40752. SimulateIOError(return SQLITE_IOERR_READ);
  40753. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  40754. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  40755. pFile->h, pBuf, amt, offset, pFile->locktype));
  40756. #if SQLITE_MAX_MMAP_SIZE>0
  40757. /* Deal with as much of this read request as possible by transfering
  40758. ** data from the memory mapping using memcpy(). */
  40759. if( offset<pFile->mmapSize ){
  40760. if( offset+amt <= pFile->mmapSize ){
  40761. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  40762. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40763. osGetCurrentProcessId(), pFile, pFile->h));
  40764. return SQLITE_OK;
  40765. }else{
  40766. int nCopy = (int)(pFile->mmapSize - offset);
  40767. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  40768. pBuf = &((u8 *)pBuf)[nCopy];
  40769. amt -= nCopy;
  40770. offset += nCopy;
  40771. }
  40772. }
  40773. #endif
  40774. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  40775. if( winSeekFile(pFile, offset) ){
  40776. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  40777. osGetCurrentProcessId(), pFile, pFile->h));
  40778. return SQLITE_FULL;
  40779. }
  40780. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  40781. #else
  40782. memset(&overlapped, 0, sizeof(OVERLAPPED));
  40783. overlapped.Offset = (LONG)(offset & 0xffffffff);
  40784. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  40785. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  40786. osGetLastError()!=ERROR_HANDLE_EOF ){
  40787. #endif
  40788. DWORD lastErrno;
  40789. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  40790. pFile->lastErrno = lastErrno;
  40791. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  40792. osGetCurrentProcessId(), pFile, pFile->h));
  40793. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  40794. "winRead", pFile->zPath);
  40795. }
  40796. winLogIoerr(nRetry, __LINE__);
  40797. if( nRead<(DWORD)amt ){
  40798. /* Unread parts of the buffer must be zero-filled */
  40799. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  40800. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  40801. osGetCurrentProcessId(), pFile, pFile->h));
  40802. return SQLITE_IOERR_SHORT_READ;
  40803. }
  40804. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40805. osGetCurrentProcessId(), pFile, pFile->h));
  40806. return SQLITE_OK;
  40807. }
  40808. /*
  40809. ** Write data from a buffer into a file. Return SQLITE_OK on success
  40810. ** or some other error code on failure.
  40811. */
  40812. static int winWrite(
  40813. sqlite3_file *id, /* File to write into */
  40814. const void *pBuf, /* The bytes to be written */
  40815. int amt, /* Number of bytes to write */
  40816. sqlite3_int64 offset /* Offset into the file to begin writing at */
  40817. ){
  40818. int rc = 0; /* True if error has occurred, else false */
  40819. winFile *pFile = (winFile*)id; /* File handle */
  40820. int nRetry = 0; /* Number of retries */
  40821. assert( amt>0 );
  40822. assert( pFile );
  40823. SimulateIOError(return SQLITE_IOERR_WRITE);
  40824. SimulateDiskfullError(return SQLITE_FULL);
  40825. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  40826. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  40827. pFile->h, pBuf, amt, offset, pFile->locktype));
  40828. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  40829. /* Deal with as much of this write request as possible by transfering
  40830. ** data from the memory mapping using memcpy(). */
  40831. if( offset<pFile->mmapSize ){
  40832. if( offset+amt <= pFile->mmapSize ){
  40833. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  40834. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40835. osGetCurrentProcessId(), pFile, pFile->h));
  40836. return SQLITE_OK;
  40837. }else{
  40838. int nCopy = (int)(pFile->mmapSize - offset);
  40839. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  40840. pBuf = &((u8 *)pBuf)[nCopy];
  40841. amt -= nCopy;
  40842. offset += nCopy;
  40843. }
  40844. }
  40845. #endif
  40846. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  40847. rc = winSeekFile(pFile, offset);
  40848. if( rc==0 ){
  40849. #else
  40850. {
  40851. #endif
  40852. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40853. OVERLAPPED overlapped; /* The offset for WriteFile. */
  40854. #endif
  40855. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  40856. int nRem = amt; /* Number of bytes yet to be written */
  40857. DWORD nWrite; /* Bytes written by each WriteFile() call */
  40858. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  40859. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40860. memset(&overlapped, 0, sizeof(OVERLAPPED));
  40861. overlapped.Offset = (LONG)(offset & 0xffffffff);
  40862. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  40863. #endif
  40864. while( nRem>0 ){
  40865. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  40866. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  40867. #else
  40868. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  40869. #endif
  40870. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  40871. break;
  40872. }
  40873. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  40874. if( nWrite==0 || nWrite>(DWORD)nRem ){
  40875. lastErrno = osGetLastError();
  40876. break;
  40877. }
  40878. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  40879. offset += nWrite;
  40880. overlapped.Offset = (LONG)(offset & 0xffffffff);
  40881. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  40882. #endif
  40883. aRem += nWrite;
  40884. nRem -= nWrite;
  40885. }
  40886. if( nRem>0 ){
  40887. pFile->lastErrno = lastErrno;
  40888. rc = 1;
  40889. }
  40890. }
  40891. if( rc ){
  40892. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  40893. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  40894. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  40895. osGetCurrentProcessId(), pFile, pFile->h));
  40896. return winLogError(SQLITE_FULL, pFile->lastErrno,
  40897. "winWrite1", pFile->zPath);
  40898. }
  40899. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  40900. osGetCurrentProcessId(), pFile, pFile->h));
  40901. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  40902. "winWrite2", pFile->zPath);
  40903. }else{
  40904. winLogIoerr(nRetry, __LINE__);
  40905. }
  40906. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  40907. osGetCurrentProcessId(), pFile, pFile->h));
  40908. return SQLITE_OK;
  40909. }
  40910. /*
  40911. ** Truncate an open file to a specified size
  40912. */
  40913. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  40914. winFile *pFile = (winFile*)id; /* File handle object */
  40915. int rc = SQLITE_OK; /* Return code for this function */
  40916. DWORD lastErrno;
  40917. #if SQLITE_MAX_MMAP_SIZE>0
  40918. sqlite3_int64 oldMmapSize;
  40919. if( pFile->nFetchOut>0 ){
  40920. /* File truncation is a no-op if there are outstanding memory mapped
  40921. ** pages. This is because truncating the file means temporarily unmapping
  40922. ** the file, and that might delete memory out from under existing cursors.
  40923. **
  40924. ** This can result in incremental vacuum not truncating the file,
  40925. ** if there is an active read cursor when the incremental vacuum occurs.
  40926. ** No real harm comes of this - the database file is not corrupted,
  40927. ** though some folks might complain that the file is bigger than it
  40928. ** needs to be.
  40929. **
  40930. ** The only feasible work-around is to defer the truncation until after
  40931. ** all references to memory-mapped content are closed. That is doable,
  40932. ** but involves adding a few branches in the common write code path which
  40933. ** could slow down normal operations slightly. Hence, we have decided for
  40934. ** now to simply make trancations a no-op if there are pending reads. We
  40935. ** can maybe revisit this decision in the future.
  40936. */
  40937. return SQLITE_OK;
  40938. }
  40939. #endif
  40940. assert( pFile );
  40941. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  40942. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  40943. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  40944. /* If the user has configured a chunk-size for this file, truncate the
  40945. ** file so that it consists of an integer number of chunks (i.e. the
  40946. ** actual file size after the operation may be larger than the requested
  40947. ** size).
  40948. */
  40949. if( pFile->szChunk>0 ){
  40950. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  40951. }
  40952. #if SQLITE_MAX_MMAP_SIZE>0
  40953. if( pFile->pMapRegion ){
  40954. oldMmapSize = pFile->mmapSize;
  40955. }else{
  40956. oldMmapSize = 0;
  40957. }
  40958. winUnmapfile(pFile);
  40959. #endif
  40960. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  40961. if( winSeekFile(pFile, nByte) ){
  40962. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  40963. "winTruncate1", pFile->zPath);
  40964. }else if( 0==osSetEndOfFile(pFile->h) &&
  40965. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  40966. pFile->lastErrno = lastErrno;
  40967. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  40968. "winTruncate2", pFile->zPath);
  40969. }
  40970. #if SQLITE_MAX_MMAP_SIZE>0
  40971. if( rc==SQLITE_OK && oldMmapSize>0 ){
  40972. if( oldMmapSize>nByte ){
  40973. winMapfile(pFile, -1);
  40974. }else{
  40975. winMapfile(pFile, oldMmapSize);
  40976. }
  40977. }
  40978. #endif
  40979. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  40980. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  40981. return rc;
  40982. }
  40983. #ifdef SQLITE_TEST
  40984. /*
  40985. ** Count the number of fullsyncs and normal syncs. This is used to test
  40986. ** that syncs and fullsyncs are occuring at the right times.
  40987. */
  40988. SQLITE_API int sqlite3_sync_count = 0;
  40989. SQLITE_API int sqlite3_fullsync_count = 0;
  40990. #endif
  40991. /*
  40992. ** Make sure all writes to a particular file are committed to disk.
  40993. */
  40994. static int winSync(sqlite3_file *id, int flags){
  40995. #ifndef SQLITE_NO_SYNC
  40996. /*
  40997. ** Used only when SQLITE_NO_SYNC is not defined.
  40998. */
  40999. BOOL rc;
  41000. #endif
  41001. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  41002. defined(SQLITE_HAVE_OS_TRACE)
  41003. /*
  41004. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  41005. ** OSTRACE() macros.
  41006. */
  41007. winFile *pFile = (winFile*)id;
  41008. #else
  41009. UNUSED_PARAMETER(id);
  41010. #endif
  41011. assert( pFile );
  41012. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  41013. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  41014. || (flags&0x0F)==SQLITE_SYNC_FULL
  41015. );
  41016. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  41017. ** line is to test that doing so does not cause any problems.
  41018. */
  41019. SimulateDiskfullError( return SQLITE_FULL );
  41020. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  41021. osGetCurrentProcessId(), pFile, pFile->h, flags,
  41022. pFile->locktype));
  41023. #ifndef SQLITE_TEST
  41024. UNUSED_PARAMETER(flags);
  41025. #else
  41026. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  41027. sqlite3_fullsync_count++;
  41028. }
  41029. sqlite3_sync_count++;
  41030. #endif
  41031. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  41032. ** no-op
  41033. */
  41034. #ifdef SQLITE_NO_SYNC
  41035. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  41036. osGetCurrentProcessId(), pFile, pFile->h));
  41037. return SQLITE_OK;
  41038. #else
  41039. #if SQLITE_MAX_MMAP_SIZE>0
  41040. if( pFile->pMapRegion ){
  41041. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  41042. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  41043. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  41044. pFile, pFile->pMapRegion));
  41045. }else{
  41046. pFile->lastErrno = osGetLastError();
  41047. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  41048. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  41049. pFile, pFile->pMapRegion));
  41050. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  41051. "winSync1", pFile->zPath);
  41052. }
  41053. }
  41054. #endif
  41055. rc = osFlushFileBuffers(pFile->h);
  41056. SimulateIOError( rc=FALSE );
  41057. if( rc ){
  41058. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  41059. osGetCurrentProcessId(), pFile, pFile->h));
  41060. return SQLITE_OK;
  41061. }else{
  41062. pFile->lastErrno = osGetLastError();
  41063. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  41064. osGetCurrentProcessId(), pFile, pFile->h));
  41065. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  41066. "winSync2", pFile->zPath);
  41067. }
  41068. #endif
  41069. }
  41070. /*
  41071. ** Determine the current size of a file in bytes
  41072. */
  41073. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  41074. winFile *pFile = (winFile*)id;
  41075. int rc = SQLITE_OK;
  41076. assert( id!=0 );
  41077. assert( pSize!=0 );
  41078. SimulateIOError(return SQLITE_IOERR_FSTAT);
  41079. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  41080. #if SQLITE_OS_WINRT
  41081. {
  41082. FILE_STANDARD_INFO info;
  41083. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  41084. &info, sizeof(info)) ){
  41085. *pSize = info.EndOfFile.QuadPart;
  41086. }else{
  41087. pFile->lastErrno = osGetLastError();
  41088. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  41089. "winFileSize", pFile->zPath);
  41090. }
  41091. }
  41092. #else
  41093. {
  41094. DWORD upperBits;
  41095. DWORD lowerBits;
  41096. DWORD lastErrno;
  41097. lowerBits = osGetFileSize(pFile->h, &upperBits);
  41098. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  41099. if( (lowerBits == INVALID_FILE_SIZE)
  41100. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  41101. pFile->lastErrno = lastErrno;
  41102. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  41103. "winFileSize", pFile->zPath);
  41104. }
  41105. }
  41106. #endif
  41107. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  41108. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  41109. return rc;
  41110. }
  41111. /*
  41112. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  41113. */
  41114. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  41115. # define LOCKFILE_FAIL_IMMEDIATELY 1
  41116. #endif
  41117. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  41118. # define LOCKFILE_EXCLUSIVE_LOCK 2
  41119. #endif
  41120. /*
  41121. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  41122. ** When the LockFile function was used, it was always expected to fail
  41123. ** immediately if the lock could not be obtained. Also, it always expected to
  41124. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  41125. ** and reflect those expectations; therefore, they should not be changed.
  41126. */
  41127. #ifndef SQLITE_LOCKFILE_FLAGS
  41128. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  41129. LOCKFILE_EXCLUSIVE_LOCK)
  41130. #endif
  41131. /*
  41132. ** Currently, SQLite never calls the LockFileEx function without wanting the
  41133. ** call to fail immediately if the lock cannot be obtained.
  41134. */
  41135. #ifndef SQLITE_LOCKFILEEX_FLAGS
  41136. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  41137. #endif
  41138. /*
  41139. ** Acquire a reader lock.
  41140. ** Different API routines are called depending on whether or not this
  41141. ** is Win9x or WinNT.
  41142. */
  41143. static int winGetReadLock(winFile *pFile){
  41144. int res;
  41145. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  41146. if( osIsNT() ){
  41147. #if SQLITE_OS_WINCE
  41148. /*
  41149. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  41150. ** API LockFileEx.
  41151. */
  41152. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  41153. #else
  41154. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  41155. SHARED_SIZE, 0);
  41156. #endif
  41157. }
  41158. #ifdef SQLITE_WIN32_HAS_ANSI
  41159. else{
  41160. int lk;
  41161. sqlite3_randomness(sizeof(lk), &lk);
  41162. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  41163. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  41164. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  41165. }
  41166. #endif
  41167. if( res == 0 ){
  41168. pFile->lastErrno = osGetLastError();
  41169. /* No need to log a failure to lock */
  41170. }
  41171. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  41172. return res;
  41173. }
  41174. /*
  41175. ** Undo a readlock
  41176. */
  41177. static int winUnlockReadLock(winFile *pFile){
  41178. int res;
  41179. DWORD lastErrno;
  41180. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  41181. if( osIsNT() ){
  41182. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  41183. }
  41184. #ifdef SQLITE_WIN32_HAS_ANSI
  41185. else{
  41186. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  41187. }
  41188. #endif
  41189. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  41190. pFile->lastErrno = lastErrno;
  41191. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  41192. "winUnlockReadLock", pFile->zPath);
  41193. }
  41194. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  41195. return res;
  41196. }
  41197. /*
  41198. ** Lock the file with the lock specified by parameter locktype - one
  41199. ** of the following:
  41200. **
  41201. ** (1) SHARED_LOCK
  41202. ** (2) RESERVED_LOCK
  41203. ** (3) PENDING_LOCK
  41204. ** (4) EXCLUSIVE_LOCK
  41205. **
  41206. ** Sometimes when requesting one lock state, additional lock states
  41207. ** are inserted in between. The locking might fail on one of the later
  41208. ** transitions leaving the lock state different from what it started but
  41209. ** still short of its goal. The following chart shows the allowed
  41210. ** transitions and the inserted intermediate states:
  41211. **
  41212. ** UNLOCKED -> SHARED
  41213. ** SHARED -> RESERVED
  41214. ** SHARED -> (PENDING) -> EXCLUSIVE
  41215. ** RESERVED -> (PENDING) -> EXCLUSIVE
  41216. ** PENDING -> EXCLUSIVE
  41217. **
  41218. ** This routine will only increase a lock. The winUnlock() routine
  41219. ** erases all locks at once and returns us immediately to locking level 0.
  41220. ** It is not possible to lower the locking level one step at a time. You
  41221. ** must go straight to locking level 0.
  41222. */
  41223. static int winLock(sqlite3_file *id, int locktype){
  41224. int rc = SQLITE_OK; /* Return code from subroutines */
  41225. int res = 1; /* Result of a Windows lock call */
  41226. int newLocktype; /* Set pFile->locktype to this value before exiting */
  41227. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  41228. winFile *pFile = (winFile*)id;
  41229. DWORD lastErrno = NO_ERROR;
  41230. assert( id!=0 );
  41231. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  41232. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  41233. /* If there is already a lock of this type or more restrictive on the
  41234. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  41235. ** sqlite3OsEnterMutex() hasn't been called yet.
  41236. */
  41237. if( pFile->locktype>=locktype ){
  41238. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  41239. return SQLITE_OK;
  41240. }
  41241. /* Do not allow any kind of write-lock on a read-only database
  41242. */
  41243. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  41244. return SQLITE_IOERR_LOCK;
  41245. }
  41246. /* Make sure the locking sequence is correct
  41247. */
  41248. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  41249. assert( locktype!=PENDING_LOCK );
  41250. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  41251. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  41252. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  41253. ** the PENDING_LOCK byte is temporary.
  41254. */
  41255. newLocktype = pFile->locktype;
  41256. if( pFile->locktype==NO_LOCK
  41257. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
  41258. ){
  41259. int cnt = 3;
  41260. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  41261. PENDING_BYTE, 0, 1, 0))==0 ){
  41262. /* Try 3 times to get the pending lock. This is needed to work
  41263. ** around problems caused by indexing and/or anti-virus software on
  41264. ** Windows systems.
  41265. ** If you are using this code as a model for alternative VFSes, do not
  41266. ** copy this retry logic. It is a hack intended for Windows only.
  41267. */
  41268. lastErrno = osGetLastError();
  41269. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  41270. pFile->h, cnt, res));
  41271. if( lastErrno==ERROR_INVALID_HANDLE ){
  41272. pFile->lastErrno = lastErrno;
  41273. rc = SQLITE_IOERR_LOCK;
  41274. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  41275. pFile->h, cnt, sqlite3ErrName(rc)));
  41276. return rc;
  41277. }
  41278. if( cnt ) sqlite3_win32_sleep(1);
  41279. }
  41280. gotPendingLock = res;
  41281. if( !res ){
  41282. lastErrno = osGetLastError();
  41283. }
  41284. }
  41285. /* Acquire a shared lock
  41286. */
  41287. if( locktype==SHARED_LOCK && res ){
  41288. assert( pFile->locktype==NO_LOCK );
  41289. res = winGetReadLock(pFile);
  41290. if( res ){
  41291. newLocktype = SHARED_LOCK;
  41292. }else{
  41293. lastErrno = osGetLastError();
  41294. }
  41295. }
  41296. /* Acquire a RESERVED lock
  41297. */
  41298. if( locktype==RESERVED_LOCK && res ){
  41299. assert( pFile->locktype==SHARED_LOCK );
  41300. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  41301. if( res ){
  41302. newLocktype = RESERVED_LOCK;
  41303. }else{
  41304. lastErrno = osGetLastError();
  41305. }
  41306. }
  41307. /* Acquire a PENDING lock
  41308. */
  41309. if( locktype==EXCLUSIVE_LOCK && res ){
  41310. newLocktype = PENDING_LOCK;
  41311. gotPendingLock = 0;
  41312. }
  41313. /* Acquire an EXCLUSIVE lock
  41314. */
  41315. if( locktype==EXCLUSIVE_LOCK && res ){
  41316. assert( pFile->locktype>=SHARED_LOCK );
  41317. res = winUnlockReadLock(pFile);
  41318. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  41319. SHARED_SIZE, 0);
  41320. if( res ){
  41321. newLocktype = EXCLUSIVE_LOCK;
  41322. }else{
  41323. lastErrno = osGetLastError();
  41324. winGetReadLock(pFile);
  41325. }
  41326. }
  41327. /* If we are holding a PENDING lock that ought to be released, then
  41328. ** release it now.
  41329. */
  41330. if( gotPendingLock && locktype==SHARED_LOCK ){
  41331. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  41332. }
  41333. /* Update the state of the lock has held in the file descriptor then
  41334. ** return the appropriate result code.
  41335. */
  41336. if( res ){
  41337. rc = SQLITE_OK;
  41338. }else{
  41339. pFile->lastErrno = lastErrno;
  41340. rc = SQLITE_BUSY;
  41341. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  41342. pFile->h, locktype, newLocktype));
  41343. }
  41344. pFile->locktype = (u8)newLocktype;
  41345. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  41346. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  41347. return rc;
  41348. }
  41349. /*
  41350. ** This routine checks if there is a RESERVED lock held on the specified
  41351. ** file by this or any other process. If such a lock is held, return
  41352. ** non-zero, otherwise zero.
  41353. */
  41354. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  41355. int res;
  41356. winFile *pFile = (winFile*)id;
  41357. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  41358. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  41359. assert( id!=0 );
  41360. if( pFile->locktype>=RESERVED_LOCK ){
  41361. res = 1;
  41362. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  41363. }else{
  41364. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
  41365. if( res ){
  41366. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  41367. }
  41368. res = !res;
  41369. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  41370. }
  41371. *pResOut = res;
  41372. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  41373. pFile->h, pResOut, *pResOut));
  41374. return SQLITE_OK;
  41375. }
  41376. /*
  41377. ** Lower the locking level on file descriptor id to locktype. locktype
  41378. ** must be either NO_LOCK or SHARED_LOCK.
  41379. **
  41380. ** If the locking level of the file descriptor is already at or below
  41381. ** the requested locking level, this routine is a no-op.
  41382. **
  41383. ** It is not possible for this routine to fail if the second argument
  41384. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  41385. ** might return SQLITE_IOERR;
  41386. */
  41387. static int winUnlock(sqlite3_file *id, int locktype){
  41388. int type;
  41389. winFile *pFile = (winFile*)id;
  41390. int rc = SQLITE_OK;
  41391. assert( pFile!=0 );
  41392. assert( locktype<=SHARED_LOCK );
  41393. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  41394. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  41395. type = pFile->locktype;
  41396. if( type>=EXCLUSIVE_LOCK ){
  41397. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  41398. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  41399. /* This should never happen. We should always be able to
  41400. ** reacquire the read lock */
  41401. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  41402. "winUnlock", pFile->zPath);
  41403. }
  41404. }
  41405. if( type>=RESERVED_LOCK ){
  41406. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  41407. }
  41408. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  41409. winUnlockReadLock(pFile);
  41410. }
  41411. if( type>=PENDING_LOCK ){
  41412. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  41413. }
  41414. pFile->locktype = (u8)locktype;
  41415. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  41416. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  41417. return rc;
  41418. }
  41419. /******************************************************************************
  41420. ****************************** No-op Locking **********************************
  41421. **
  41422. ** Of the various locking implementations available, this is by far the
  41423. ** simplest: locking is ignored. No attempt is made to lock the database
  41424. ** file for reading or writing.
  41425. **
  41426. ** This locking mode is appropriate for use on read-only databases
  41427. ** (ex: databases that are burned into CD-ROM, for example.) It can
  41428. ** also be used if the application employs some external mechanism to
  41429. ** prevent simultaneous access of the same database by two or more
  41430. ** database connections. But there is a serious risk of database
  41431. ** corruption if this locking mode is used in situations where multiple
  41432. ** database connections are accessing the same database file at the same
  41433. ** time and one or more of those connections are writing.
  41434. */
  41435. static int winNolockLock(sqlite3_file *id, int locktype){
  41436. UNUSED_PARAMETER(id);
  41437. UNUSED_PARAMETER(locktype);
  41438. return SQLITE_OK;
  41439. }
  41440. static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
  41441. UNUSED_PARAMETER(id);
  41442. UNUSED_PARAMETER(pResOut);
  41443. return SQLITE_OK;
  41444. }
  41445. static int winNolockUnlock(sqlite3_file *id, int locktype){
  41446. UNUSED_PARAMETER(id);
  41447. UNUSED_PARAMETER(locktype);
  41448. return SQLITE_OK;
  41449. }
  41450. /******************* End of the no-op lock implementation *********************
  41451. ******************************************************************************/
  41452. /*
  41453. ** If *pArg is initially negative then this is a query. Set *pArg to
  41454. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  41455. **
  41456. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  41457. */
  41458. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  41459. if( *pArg<0 ){
  41460. *pArg = (pFile->ctrlFlags & mask)!=0;
  41461. }else if( (*pArg)==0 ){
  41462. pFile->ctrlFlags &= ~mask;
  41463. }else{
  41464. pFile->ctrlFlags |= mask;
  41465. }
  41466. }
  41467. /* Forward references to VFS helper methods used for temporary files */
  41468. static int winGetTempname(sqlite3_vfs *, char **);
  41469. static int winIsDir(const void *);
  41470. static BOOL winIsDriveLetterAndColon(const char *);
  41471. /*
  41472. ** Control and query of the open file handle.
  41473. */
  41474. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  41475. winFile *pFile = (winFile*)id;
  41476. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  41477. switch( op ){
  41478. case SQLITE_FCNTL_LOCKSTATE: {
  41479. *(int*)pArg = pFile->locktype;
  41480. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41481. return SQLITE_OK;
  41482. }
  41483. case SQLITE_FCNTL_LAST_ERRNO: {
  41484. *(int*)pArg = (int)pFile->lastErrno;
  41485. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41486. return SQLITE_OK;
  41487. }
  41488. case SQLITE_FCNTL_CHUNK_SIZE: {
  41489. pFile->szChunk = *(int *)pArg;
  41490. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41491. return SQLITE_OK;
  41492. }
  41493. case SQLITE_FCNTL_SIZE_HINT: {
  41494. if( pFile->szChunk>0 ){
  41495. sqlite3_int64 oldSz;
  41496. int rc = winFileSize(id, &oldSz);
  41497. if( rc==SQLITE_OK ){
  41498. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  41499. if( newSz>oldSz ){
  41500. SimulateIOErrorBenign(1);
  41501. rc = winTruncate(id, newSz);
  41502. SimulateIOErrorBenign(0);
  41503. }
  41504. }
  41505. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  41506. return rc;
  41507. }
  41508. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41509. return SQLITE_OK;
  41510. }
  41511. case SQLITE_FCNTL_PERSIST_WAL: {
  41512. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  41513. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41514. return SQLITE_OK;
  41515. }
  41516. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  41517. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  41518. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41519. return SQLITE_OK;
  41520. }
  41521. case SQLITE_FCNTL_VFSNAME: {
  41522. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  41523. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41524. return SQLITE_OK;
  41525. }
  41526. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  41527. int *a = (int*)pArg;
  41528. if( a[0]>0 ){
  41529. winIoerrRetry = a[0];
  41530. }else{
  41531. a[0] = winIoerrRetry;
  41532. }
  41533. if( a[1]>0 ){
  41534. winIoerrRetryDelay = a[1];
  41535. }else{
  41536. a[1] = winIoerrRetryDelay;
  41537. }
  41538. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41539. return SQLITE_OK;
  41540. }
  41541. case SQLITE_FCNTL_WIN32_GET_HANDLE: {
  41542. LPHANDLE phFile = (LPHANDLE)pArg;
  41543. *phFile = pFile->h;
  41544. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  41545. return SQLITE_OK;
  41546. }
  41547. #ifdef SQLITE_TEST
  41548. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  41549. LPHANDLE phFile = (LPHANDLE)pArg;
  41550. HANDLE hOldFile = pFile->h;
  41551. pFile->h = *phFile;
  41552. *phFile = hOldFile;
  41553. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  41554. hOldFile, pFile->h));
  41555. return SQLITE_OK;
  41556. }
  41557. #endif
  41558. case SQLITE_FCNTL_TEMPFILENAME: {
  41559. char *zTFile = 0;
  41560. int rc = winGetTempname(pFile->pVfs, &zTFile);
  41561. if( rc==SQLITE_OK ){
  41562. *(char**)pArg = zTFile;
  41563. }
  41564. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  41565. return rc;
  41566. }
  41567. #if SQLITE_MAX_MMAP_SIZE>0
  41568. case SQLITE_FCNTL_MMAP_SIZE: {
  41569. i64 newLimit = *(i64*)pArg;
  41570. int rc = SQLITE_OK;
  41571. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  41572. newLimit = sqlite3GlobalConfig.mxMmap;
  41573. }
  41574. /* The value of newLimit may be eventually cast to (SIZE_T) and passed
  41575. ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
  41576. ** least a 64-bit type. */
  41577. if( newLimit>0 && sizeof(SIZE_T)<8 ){
  41578. newLimit = (newLimit & 0x7FFFFFFF);
  41579. }
  41580. *(i64*)pArg = pFile->mmapSizeMax;
  41581. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  41582. pFile->mmapSizeMax = newLimit;
  41583. if( pFile->mmapSize>0 ){
  41584. winUnmapfile(pFile);
  41585. rc = winMapfile(pFile, -1);
  41586. }
  41587. }
  41588. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  41589. return rc;
  41590. }
  41591. #endif
  41592. }
  41593. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  41594. return SQLITE_NOTFOUND;
  41595. }
  41596. /*
  41597. ** Return the sector size in bytes of the underlying block device for
  41598. ** the specified file. This is almost always 512 bytes, but may be
  41599. ** larger for some devices.
  41600. **
  41601. ** SQLite code assumes this function cannot fail. It also assumes that
  41602. ** if two files are created in the same file-system directory (i.e.
  41603. ** a database and its journal file) that the sector size will be the
  41604. ** same for both.
  41605. */
  41606. static int winSectorSize(sqlite3_file *id){
  41607. (void)id;
  41608. return SQLITE_DEFAULT_SECTOR_SIZE;
  41609. }
  41610. /*
  41611. ** Return a vector of device characteristics.
  41612. */
  41613. static int winDeviceCharacteristics(sqlite3_file *id){
  41614. winFile *p = (winFile*)id;
  41615. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  41616. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  41617. }
  41618. /*
  41619. ** Windows will only let you create file view mappings
  41620. ** on allocation size granularity boundaries.
  41621. ** During sqlite3_os_init() we do a GetSystemInfo()
  41622. ** to get the granularity size.
  41623. */
  41624. static SYSTEM_INFO winSysInfo;
  41625. #ifndef SQLITE_OMIT_WAL
  41626. /*
  41627. ** Helper functions to obtain and relinquish the global mutex. The
  41628. ** global mutex is used to protect the winLockInfo objects used by
  41629. ** this file, all of which may be shared by multiple threads.
  41630. **
  41631. ** Function winShmMutexHeld() is used to assert() that the global mutex
  41632. ** is held when required. This function is only used as part of assert()
  41633. ** statements. e.g.
  41634. **
  41635. ** winShmEnterMutex()
  41636. ** assert( winShmMutexHeld() );
  41637. ** winShmLeaveMutex()
  41638. */
  41639. static sqlite3_mutex *winBigLock = 0;
  41640. static void winShmEnterMutex(void){
  41641. sqlite3_mutex_enter(winBigLock);
  41642. }
  41643. static void winShmLeaveMutex(void){
  41644. sqlite3_mutex_leave(winBigLock);
  41645. }
  41646. #ifndef NDEBUG
  41647. static int winShmMutexHeld(void) {
  41648. return sqlite3_mutex_held(winBigLock);
  41649. }
  41650. #endif
  41651. /*
  41652. ** Object used to represent a single file opened and mmapped to provide
  41653. ** shared memory. When multiple threads all reference the same
  41654. ** log-summary, each thread has its own winFile object, but they all
  41655. ** point to a single instance of this object. In other words, each
  41656. ** log-summary is opened only once per process.
  41657. **
  41658. ** winShmMutexHeld() must be true when creating or destroying
  41659. ** this object or while reading or writing the following fields:
  41660. **
  41661. ** nRef
  41662. ** pNext
  41663. **
  41664. ** The following fields are read-only after the object is created:
  41665. **
  41666. ** fid
  41667. ** zFilename
  41668. **
  41669. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  41670. ** winShmMutexHeld() is true when reading or writing any other field
  41671. ** in this structure.
  41672. **
  41673. */
  41674. struct winShmNode {
  41675. sqlite3_mutex *mutex; /* Mutex to access this object */
  41676. char *zFilename; /* Name of the file */
  41677. winFile hFile; /* File handle from winOpen */
  41678. int szRegion; /* Size of shared-memory regions */
  41679. int nRegion; /* Size of array apRegion */
  41680. u8 isReadonly; /* True if read-only */
  41681. u8 isUnlocked; /* True if no DMS lock held */
  41682. struct ShmRegion {
  41683. HANDLE hMap; /* File handle from CreateFileMapping */
  41684. void *pMap;
  41685. } *aRegion;
  41686. DWORD lastErrno; /* The Windows errno from the last I/O error */
  41687. int nRef; /* Number of winShm objects pointing to this */
  41688. winShm *pFirst; /* All winShm objects pointing to this */
  41689. winShmNode *pNext; /* Next in list of all winShmNode objects */
  41690. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  41691. u8 nextShmId; /* Next available winShm.id value */
  41692. #endif
  41693. };
  41694. /*
  41695. ** A global array of all winShmNode objects.
  41696. **
  41697. ** The winShmMutexHeld() must be true while reading or writing this list.
  41698. */
  41699. static winShmNode *winShmNodeList = 0;
  41700. /*
  41701. ** Structure used internally by this VFS to record the state of an
  41702. ** open shared memory connection.
  41703. **
  41704. ** The following fields are initialized when this object is created and
  41705. ** are read-only thereafter:
  41706. **
  41707. ** winShm.pShmNode
  41708. ** winShm.id
  41709. **
  41710. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  41711. ** while accessing any read/write fields.
  41712. */
  41713. struct winShm {
  41714. winShmNode *pShmNode; /* The underlying winShmNode object */
  41715. winShm *pNext; /* Next winShm with the same winShmNode */
  41716. u8 hasMutex; /* True if holding the winShmNode mutex */
  41717. u16 sharedMask; /* Mask of shared locks held */
  41718. u16 exclMask; /* Mask of exclusive locks held */
  41719. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  41720. u8 id; /* Id of this connection with its winShmNode */
  41721. #endif
  41722. };
  41723. /*
  41724. ** Constants used for locking
  41725. */
  41726. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  41727. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  41728. /*
  41729. ** Apply advisory locks for all n bytes beginning at ofst.
  41730. */
  41731. #define WINSHM_UNLCK 1
  41732. #define WINSHM_RDLCK 2
  41733. #define WINSHM_WRLCK 3
  41734. static int winShmSystemLock(
  41735. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  41736. int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
  41737. int ofst, /* Offset to first byte to be locked/unlocked */
  41738. int nByte /* Number of bytes to lock or unlock */
  41739. ){
  41740. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  41741. /* Access to the winShmNode object is serialized by the caller */
  41742. assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
  41743. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  41744. pFile->hFile.h, lockType, ofst, nByte));
  41745. /* Release/Acquire the system-level lock */
  41746. if( lockType==WINSHM_UNLCK ){
  41747. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  41748. }else{
  41749. /* Initialize the locking parameters */
  41750. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  41751. if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  41752. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  41753. }
  41754. if( rc!= 0 ){
  41755. rc = SQLITE_OK;
  41756. }else{
  41757. pFile->lastErrno = osGetLastError();
  41758. rc = SQLITE_BUSY;
  41759. }
  41760. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  41761. pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
  41762. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  41763. return rc;
  41764. }
  41765. /* Forward references to VFS methods */
  41766. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  41767. static int winDelete(sqlite3_vfs *,const char*,int);
  41768. /*
  41769. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  41770. **
  41771. ** This is not a VFS shared-memory method; it is a utility function called
  41772. ** by VFS shared-memory methods.
  41773. */
  41774. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  41775. winShmNode **pp;
  41776. winShmNode *p;
  41777. assert( winShmMutexHeld() );
  41778. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  41779. osGetCurrentProcessId(), deleteFlag));
  41780. pp = &winShmNodeList;
  41781. while( (p = *pp)!=0 ){
  41782. if( p->nRef==0 ){
  41783. int i;
  41784. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  41785. for(i=0; i<p->nRegion; i++){
  41786. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  41787. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  41788. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  41789. UNUSED_VARIABLE_VALUE(bRc);
  41790. bRc = osCloseHandle(p->aRegion[i].hMap);
  41791. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  41792. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  41793. UNUSED_VARIABLE_VALUE(bRc);
  41794. }
  41795. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  41796. SimulateIOErrorBenign(1);
  41797. winClose((sqlite3_file *)&p->hFile);
  41798. SimulateIOErrorBenign(0);
  41799. }
  41800. if( deleteFlag ){
  41801. SimulateIOErrorBenign(1);
  41802. sqlite3BeginBenignMalloc();
  41803. winDelete(pVfs, p->zFilename, 0);
  41804. sqlite3EndBenignMalloc();
  41805. SimulateIOErrorBenign(0);
  41806. }
  41807. *pp = p->pNext;
  41808. sqlite3_free(p->aRegion);
  41809. sqlite3_free(p);
  41810. }else{
  41811. pp = &p->pNext;
  41812. }
  41813. }
  41814. }
  41815. /*
  41816. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  41817. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  41818. ** code otherwise.
  41819. **
  41820. ** If the DMS cannot be locked because this is a readonly_shm=1
  41821. ** connection and no other process already holds a lock, return
  41822. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  41823. */
  41824. static int winLockSharedMemory(winShmNode *pShmNode){
  41825. int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
  41826. if( rc==SQLITE_OK ){
  41827. if( pShmNode->isReadonly ){
  41828. pShmNode->isUnlocked = 1;
  41829. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  41830. return SQLITE_READONLY_CANTINIT;
  41831. }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
  41832. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  41833. return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  41834. "winLockSharedMemory", pShmNode->zFilename);
  41835. }
  41836. }
  41837. if( rc==SQLITE_OK ){
  41838. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  41839. }
  41840. return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
  41841. }
  41842. /*
  41843. ** Open the shared-memory area associated with database file pDbFd.
  41844. **
  41845. ** When opening a new shared-memory file, if no other instances of that
  41846. ** file are currently open, in this process or in other processes, then
  41847. ** the file must be truncated to zero length or have its header cleared.
  41848. */
  41849. static int winOpenSharedMemory(winFile *pDbFd){
  41850. struct winShm *p; /* The connection to be opened */
  41851. winShmNode *pShmNode = 0; /* The underlying mmapped file */
  41852. int rc = SQLITE_OK; /* Result code */
  41853. winShmNode *pNew; /* Newly allocated winShmNode */
  41854. int nName; /* Size of zName in bytes */
  41855. assert( pDbFd->pShm==0 ); /* Not previously opened */
  41856. /* Allocate space for the new sqlite3_shm object. Also speculatively
  41857. ** allocate space for a new winShmNode and filename.
  41858. */
  41859. p = sqlite3MallocZero( sizeof(*p) );
  41860. if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
  41861. nName = sqlite3Strlen30(pDbFd->zPath);
  41862. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  41863. if( pNew==0 ){
  41864. sqlite3_free(p);
  41865. return SQLITE_IOERR_NOMEM_BKPT;
  41866. }
  41867. pNew->zFilename = (char*)&pNew[1];
  41868. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  41869. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  41870. /* Look to see if there is an existing winShmNode that can be used.
  41871. ** If no matching winShmNode currently exists, create a new one.
  41872. */
  41873. winShmEnterMutex();
  41874. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  41875. /* TBD need to come up with better match here. Perhaps
  41876. ** use FILE_ID_BOTH_DIR_INFO Structure.
  41877. */
  41878. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  41879. }
  41880. if( pShmNode ){
  41881. sqlite3_free(pNew);
  41882. }else{
  41883. int inFlags = SQLITE_OPEN_WAL;
  41884. int outFlags = 0;
  41885. pShmNode = pNew;
  41886. pNew = 0;
  41887. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  41888. pShmNode->pNext = winShmNodeList;
  41889. winShmNodeList = pShmNode;
  41890. if( sqlite3GlobalConfig.bCoreMutex ){
  41891. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  41892. if( pShmNode->mutex==0 ){
  41893. rc = SQLITE_IOERR_NOMEM_BKPT;
  41894. goto shm_open_err;
  41895. }
  41896. }
  41897. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  41898. inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
  41899. }else{
  41900. inFlags |= SQLITE_OPEN_READONLY;
  41901. }
  41902. rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
  41903. (sqlite3_file*)&pShmNode->hFile,
  41904. inFlags, &outFlags);
  41905. if( rc!=SQLITE_OK ){
  41906. rc = winLogError(rc, osGetLastError(), "winOpenShm",
  41907. pShmNode->zFilename);
  41908. goto shm_open_err;
  41909. }
  41910. if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
  41911. rc = winLockSharedMemory(pShmNode);
  41912. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  41913. }
  41914. /* Make the new connection a child of the winShmNode */
  41915. p->pShmNode = pShmNode;
  41916. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  41917. p->id = pShmNode->nextShmId++;
  41918. #endif
  41919. pShmNode->nRef++;
  41920. pDbFd->pShm = p;
  41921. winShmLeaveMutex();
  41922. /* The reference count on pShmNode has already been incremented under
  41923. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  41924. ** new (struct winShm) object to the pShmNode has been set. All that is
  41925. ** left to do is to link the new object into the linked list starting
  41926. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  41927. ** mutex.
  41928. */
  41929. sqlite3_mutex_enter(pShmNode->mutex);
  41930. p->pNext = pShmNode->pFirst;
  41931. pShmNode->pFirst = p;
  41932. sqlite3_mutex_leave(pShmNode->mutex);
  41933. return rc;
  41934. /* Jump here on any error */
  41935. shm_open_err:
  41936. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  41937. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  41938. sqlite3_free(p);
  41939. sqlite3_free(pNew);
  41940. winShmLeaveMutex();
  41941. return rc;
  41942. }
  41943. /*
  41944. ** Close a connection to shared-memory. Delete the underlying
  41945. ** storage if deleteFlag is true.
  41946. */
  41947. static int winShmUnmap(
  41948. sqlite3_file *fd, /* Database holding shared memory */
  41949. int deleteFlag /* Delete after closing if true */
  41950. ){
  41951. winFile *pDbFd; /* Database holding shared-memory */
  41952. winShm *p; /* The connection to be closed */
  41953. winShmNode *pShmNode; /* The underlying shared-memory file */
  41954. winShm **pp; /* For looping over sibling connections */
  41955. pDbFd = (winFile*)fd;
  41956. p = pDbFd->pShm;
  41957. if( p==0 ) return SQLITE_OK;
  41958. pShmNode = p->pShmNode;
  41959. /* Remove connection p from the set of connections associated
  41960. ** with pShmNode */
  41961. sqlite3_mutex_enter(pShmNode->mutex);
  41962. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  41963. *pp = p->pNext;
  41964. /* Free the connection p */
  41965. sqlite3_free(p);
  41966. pDbFd->pShm = 0;
  41967. sqlite3_mutex_leave(pShmNode->mutex);
  41968. /* If pShmNode->nRef has reached 0, then close the underlying
  41969. ** shared-memory file, too */
  41970. winShmEnterMutex();
  41971. assert( pShmNode->nRef>0 );
  41972. pShmNode->nRef--;
  41973. if( pShmNode->nRef==0 ){
  41974. winShmPurge(pDbFd->pVfs, deleteFlag);
  41975. }
  41976. winShmLeaveMutex();
  41977. return SQLITE_OK;
  41978. }
  41979. /*
  41980. ** Change the lock state for a shared-memory segment.
  41981. */
  41982. static int winShmLock(
  41983. sqlite3_file *fd, /* Database file holding the shared memory */
  41984. int ofst, /* First lock to acquire or release */
  41985. int n, /* Number of locks to acquire or release */
  41986. int flags /* What to do with the lock */
  41987. ){
  41988. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  41989. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  41990. winShm *pX; /* For looping over all siblings */
  41991. winShmNode *pShmNode = p->pShmNode;
  41992. int rc = SQLITE_OK; /* Result code */
  41993. u16 mask; /* Mask of locks to take or release */
  41994. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  41995. assert( n>=1 );
  41996. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  41997. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  41998. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  41999. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  42000. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  42001. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  42002. assert( n>1 || mask==(1<<ofst) );
  42003. sqlite3_mutex_enter(pShmNode->mutex);
  42004. if( flags & SQLITE_SHM_UNLOCK ){
  42005. u16 allMask = 0; /* Mask of locks held by siblings */
  42006. /* See if any siblings hold this same lock */
  42007. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  42008. if( pX==p ) continue;
  42009. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  42010. allMask |= pX->sharedMask;
  42011. }
  42012. /* Unlock the system-level locks */
  42013. if( (mask & allMask)==0 ){
  42014. rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
  42015. }else{
  42016. rc = SQLITE_OK;
  42017. }
  42018. /* Undo the local locks */
  42019. if( rc==SQLITE_OK ){
  42020. p->exclMask &= ~mask;
  42021. p->sharedMask &= ~mask;
  42022. }
  42023. }else if( flags & SQLITE_SHM_SHARED ){
  42024. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  42025. /* Find out which shared locks are already held by sibling connections.
  42026. ** If any sibling already holds an exclusive lock, go ahead and return
  42027. ** SQLITE_BUSY.
  42028. */
  42029. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  42030. if( (pX->exclMask & mask)!=0 ){
  42031. rc = SQLITE_BUSY;
  42032. break;
  42033. }
  42034. allShared |= pX->sharedMask;
  42035. }
  42036. /* Get shared locks at the system level, if necessary */
  42037. if( rc==SQLITE_OK ){
  42038. if( (allShared & mask)==0 ){
  42039. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
  42040. }else{
  42041. rc = SQLITE_OK;
  42042. }
  42043. }
  42044. /* Get the local shared locks */
  42045. if( rc==SQLITE_OK ){
  42046. p->sharedMask |= mask;
  42047. }
  42048. }else{
  42049. /* Make sure no sibling connections hold locks that will block this
  42050. ** lock. If any do, return SQLITE_BUSY right away.
  42051. */
  42052. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  42053. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  42054. rc = SQLITE_BUSY;
  42055. break;
  42056. }
  42057. }
  42058. /* Get the exclusive locks at the system level. Then if successful
  42059. ** also mark the local connection as being locked.
  42060. */
  42061. if( rc==SQLITE_OK ){
  42062. rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
  42063. if( rc==SQLITE_OK ){
  42064. assert( (p->sharedMask & mask)==0 );
  42065. p->exclMask |= mask;
  42066. }
  42067. }
  42068. }
  42069. sqlite3_mutex_leave(pShmNode->mutex);
  42070. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  42071. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  42072. sqlite3ErrName(rc)));
  42073. return rc;
  42074. }
  42075. /*
  42076. ** Implement a memory barrier or memory fence on shared memory.
  42077. **
  42078. ** All loads and stores begun before the barrier must complete before
  42079. ** any load or store begun after the barrier.
  42080. */
  42081. static void winShmBarrier(
  42082. sqlite3_file *fd /* Database holding the shared memory */
  42083. ){
  42084. UNUSED_PARAMETER(fd);
  42085. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  42086. winShmEnterMutex(); /* Also mutex, for redundancy */
  42087. winShmLeaveMutex();
  42088. }
  42089. /*
  42090. ** This function is called to obtain a pointer to region iRegion of the
  42091. ** shared-memory associated with the database file fd. Shared-memory regions
  42092. ** are numbered starting from zero. Each shared-memory region is szRegion
  42093. ** bytes in size.
  42094. **
  42095. ** If an error occurs, an error code is returned and *pp is set to NULL.
  42096. **
  42097. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  42098. ** region has not been allocated (by any client, including one running in a
  42099. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  42100. ** isWrite is non-zero and the requested shared-memory region has not yet
  42101. ** been allocated, it is allocated by this function.
  42102. **
  42103. ** If the shared-memory region has already been allocated or is allocated by
  42104. ** this call as described above, then it is mapped into this processes
  42105. ** address space (if it is not already), *pp is set to point to the mapped
  42106. ** memory and SQLITE_OK returned.
  42107. */
  42108. static int winShmMap(
  42109. sqlite3_file *fd, /* Handle open on database file */
  42110. int iRegion, /* Region to retrieve */
  42111. int szRegion, /* Size of regions */
  42112. int isWrite, /* True to extend file if necessary */
  42113. void volatile **pp /* OUT: Mapped memory */
  42114. ){
  42115. winFile *pDbFd = (winFile*)fd;
  42116. winShm *pShm = pDbFd->pShm;
  42117. winShmNode *pShmNode;
  42118. DWORD protect = PAGE_READWRITE;
  42119. DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
  42120. int rc = SQLITE_OK;
  42121. if( !pShm ){
  42122. rc = winOpenSharedMemory(pDbFd);
  42123. if( rc!=SQLITE_OK ) return rc;
  42124. pShm = pDbFd->pShm;
  42125. }
  42126. pShmNode = pShm->pShmNode;
  42127. sqlite3_mutex_enter(pShmNode->mutex);
  42128. if( pShmNode->isUnlocked ){
  42129. rc = winLockSharedMemory(pShmNode);
  42130. if( rc!=SQLITE_OK ) goto shmpage_out;
  42131. pShmNode->isUnlocked = 0;
  42132. }
  42133. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  42134. if( pShmNode->nRegion<=iRegion ){
  42135. struct ShmRegion *apNew; /* New aRegion[] array */
  42136. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  42137. sqlite3_int64 sz; /* Current size of wal-index file */
  42138. pShmNode->szRegion = szRegion;
  42139. /* The requested region is not mapped into this processes address space.
  42140. ** Check to see if it has been allocated (i.e. if the wal-index file is
  42141. ** large enough to contain the requested region).
  42142. */
  42143. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  42144. if( rc!=SQLITE_OK ){
  42145. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  42146. "winShmMap1", pDbFd->zPath);
  42147. goto shmpage_out;
  42148. }
  42149. if( sz<nByte ){
  42150. /* The requested memory region does not exist. If isWrite is set to
  42151. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  42152. **
  42153. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  42154. ** the requested memory region.
  42155. */
  42156. if( !isWrite ) goto shmpage_out;
  42157. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  42158. if( rc!=SQLITE_OK ){
  42159. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  42160. "winShmMap2", pDbFd->zPath);
  42161. goto shmpage_out;
  42162. }
  42163. }
  42164. /* Map the requested memory region into this processes address space. */
  42165. apNew = (struct ShmRegion *)sqlite3_realloc64(
  42166. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  42167. );
  42168. if( !apNew ){
  42169. rc = SQLITE_IOERR_NOMEM_BKPT;
  42170. goto shmpage_out;
  42171. }
  42172. pShmNode->aRegion = apNew;
  42173. if( pShmNode->isReadonly ){
  42174. protect = PAGE_READONLY;
  42175. flags = FILE_MAP_READ;
  42176. }
  42177. while( pShmNode->nRegion<=iRegion ){
  42178. HANDLE hMap = NULL; /* file-mapping handle */
  42179. void *pMap = 0; /* Mapped memory region */
  42180. #if SQLITE_OS_WINRT
  42181. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  42182. NULL, protect, nByte, NULL
  42183. );
  42184. #elif defined(SQLITE_WIN32_HAS_WIDE)
  42185. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  42186. NULL, protect, 0, nByte, NULL
  42187. );
  42188. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  42189. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  42190. NULL, protect, 0, nByte, NULL
  42191. );
  42192. #endif
  42193. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  42194. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  42195. hMap ? "ok" : "failed"));
  42196. if( hMap ){
  42197. int iOffset = pShmNode->nRegion*szRegion;
  42198. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  42199. #if SQLITE_OS_WINRT
  42200. pMap = osMapViewOfFileFromApp(hMap, flags,
  42201. iOffset - iOffsetShift, szRegion + iOffsetShift
  42202. );
  42203. #else
  42204. pMap = osMapViewOfFile(hMap, flags,
  42205. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  42206. );
  42207. #endif
  42208. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  42209. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  42210. szRegion, pMap ? "ok" : "failed"));
  42211. }
  42212. if( !pMap ){
  42213. pShmNode->lastErrno = osGetLastError();
  42214. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  42215. "winShmMap3", pDbFd->zPath);
  42216. if( hMap ) osCloseHandle(hMap);
  42217. goto shmpage_out;
  42218. }
  42219. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  42220. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  42221. pShmNode->nRegion++;
  42222. }
  42223. }
  42224. shmpage_out:
  42225. if( pShmNode->nRegion>iRegion ){
  42226. int iOffset = iRegion*szRegion;
  42227. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  42228. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  42229. *pp = (void *)&p[iOffsetShift];
  42230. }else{
  42231. *pp = 0;
  42232. }
  42233. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  42234. sqlite3_mutex_leave(pShmNode->mutex);
  42235. return rc;
  42236. }
  42237. #else
  42238. # define winShmMap 0
  42239. # define winShmLock 0
  42240. # define winShmBarrier 0
  42241. # define winShmUnmap 0
  42242. #endif /* #ifndef SQLITE_OMIT_WAL */
  42243. /*
  42244. ** Cleans up the mapped region of the specified file, if any.
  42245. */
  42246. #if SQLITE_MAX_MMAP_SIZE>0
  42247. static int winUnmapfile(winFile *pFile){
  42248. assert( pFile!=0 );
  42249. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  42250. "mmapSize=%lld, mmapSizeMax=%lld\n",
  42251. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  42252. pFile->mmapSize, pFile->mmapSizeMax));
  42253. if( pFile->pMapRegion ){
  42254. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  42255. pFile->lastErrno = osGetLastError();
  42256. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  42257. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  42258. pFile->pMapRegion));
  42259. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  42260. "winUnmapfile1", pFile->zPath);
  42261. }
  42262. pFile->pMapRegion = 0;
  42263. pFile->mmapSize = 0;
  42264. }
  42265. if( pFile->hMap!=NULL ){
  42266. if( !osCloseHandle(pFile->hMap) ){
  42267. pFile->lastErrno = osGetLastError();
  42268. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  42269. osGetCurrentProcessId(), pFile, pFile->hMap));
  42270. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  42271. "winUnmapfile2", pFile->zPath);
  42272. }
  42273. pFile->hMap = NULL;
  42274. }
  42275. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  42276. osGetCurrentProcessId(), pFile));
  42277. return SQLITE_OK;
  42278. }
  42279. /*
  42280. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  42281. ** is already mapped, the existing mapping is replaced by the new). Or, if
  42282. ** there already exists a mapping for this file, and there are still
  42283. ** outstanding xFetch() references to it, this function is a no-op.
  42284. **
  42285. ** If parameter nByte is non-negative, then it is the requested size of
  42286. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  42287. ** requested size is the size of the file on disk. The actual size of the
  42288. ** created mapping is either the requested size or the value configured
  42289. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  42290. **
  42291. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  42292. ** recreated as a result of outstanding references) or an SQLite error
  42293. ** code otherwise.
  42294. */
  42295. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  42296. sqlite3_int64 nMap = nByte;
  42297. int rc;
  42298. assert( nMap>=0 || pFd->nFetchOut==0 );
  42299. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  42300. osGetCurrentProcessId(), pFd, nByte));
  42301. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  42302. if( nMap<0 ){
  42303. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  42304. if( rc ){
  42305. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  42306. osGetCurrentProcessId(), pFd));
  42307. return SQLITE_IOERR_FSTAT;
  42308. }
  42309. }
  42310. if( nMap>pFd->mmapSizeMax ){
  42311. nMap = pFd->mmapSizeMax;
  42312. }
  42313. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  42314. if( nMap==0 && pFd->mmapSize>0 ){
  42315. winUnmapfile(pFd);
  42316. }
  42317. if( nMap!=pFd->mmapSize ){
  42318. void *pNew = 0;
  42319. DWORD protect = PAGE_READONLY;
  42320. DWORD flags = FILE_MAP_READ;
  42321. winUnmapfile(pFd);
  42322. #ifdef SQLITE_MMAP_READWRITE
  42323. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  42324. protect = PAGE_READWRITE;
  42325. flags |= FILE_MAP_WRITE;
  42326. }
  42327. #endif
  42328. #if SQLITE_OS_WINRT
  42329. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  42330. #elif defined(SQLITE_WIN32_HAS_WIDE)
  42331. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  42332. (DWORD)((nMap>>32) & 0xffffffff),
  42333. (DWORD)(nMap & 0xffffffff), NULL);
  42334. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  42335. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  42336. (DWORD)((nMap>>32) & 0xffffffff),
  42337. (DWORD)(nMap & 0xffffffff), NULL);
  42338. #endif
  42339. if( pFd->hMap==NULL ){
  42340. pFd->lastErrno = osGetLastError();
  42341. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  42342. "winMapfile1", pFd->zPath);
  42343. /* Log the error, but continue normal operation using xRead/xWrite */
  42344. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  42345. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  42346. return SQLITE_OK;
  42347. }
  42348. assert( (nMap % winSysInfo.dwPageSize)==0 );
  42349. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  42350. #if SQLITE_OS_WINRT
  42351. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  42352. #else
  42353. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  42354. #endif
  42355. if( pNew==NULL ){
  42356. osCloseHandle(pFd->hMap);
  42357. pFd->hMap = NULL;
  42358. pFd->lastErrno = osGetLastError();
  42359. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  42360. "winMapfile2", pFd->zPath);
  42361. /* Log the error, but continue normal operation using xRead/xWrite */
  42362. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  42363. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  42364. return SQLITE_OK;
  42365. }
  42366. pFd->pMapRegion = pNew;
  42367. pFd->mmapSize = nMap;
  42368. }
  42369. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  42370. osGetCurrentProcessId(), pFd));
  42371. return SQLITE_OK;
  42372. }
  42373. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  42374. /*
  42375. ** If possible, return a pointer to a mapping of file fd starting at offset
  42376. ** iOff. The mapping must be valid for at least nAmt bytes.
  42377. **
  42378. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  42379. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  42380. ** Finally, if an error does occur, return an SQLite error code. The final
  42381. ** value of *pp is undefined in this case.
  42382. **
  42383. ** If this function does return a pointer, the caller must eventually
  42384. ** release the reference by calling winUnfetch().
  42385. */
  42386. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  42387. #if SQLITE_MAX_MMAP_SIZE>0
  42388. winFile *pFd = (winFile*)fd; /* The underlying database file */
  42389. #endif
  42390. *pp = 0;
  42391. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  42392. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  42393. #if SQLITE_MAX_MMAP_SIZE>0
  42394. if( pFd->mmapSizeMax>0 ){
  42395. if( pFd->pMapRegion==0 ){
  42396. int rc = winMapfile(pFd, -1);
  42397. if( rc!=SQLITE_OK ){
  42398. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  42399. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  42400. return rc;
  42401. }
  42402. }
  42403. if( pFd->mmapSize >= iOff+nAmt ){
  42404. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  42405. pFd->nFetchOut++;
  42406. }
  42407. }
  42408. #endif
  42409. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  42410. osGetCurrentProcessId(), fd, pp, *pp));
  42411. return SQLITE_OK;
  42412. }
  42413. /*
  42414. ** If the third argument is non-NULL, then this function releases a
  42415. ** reference obtained by an earlier call to winFetch(). The second
  42416. ** argument passed to this function must be the same as the corresponding
  42417. ** argument that was passed to the winFetch() invocation.
  42418. **
  42419. ** Or, if the third argument is NULL, then this function is being called
  42420. ** to inform the VFS layer that, according to POSIX, any existing mapping
  42421. ** may now be invalid and should be unmapped.
  42422. */
  42423. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  42424. #if SQLITE_MAX_MMAP_SIZE>0
  42425. winFile *pFd = (winFile*)fd; /* The underlying database file */
  42426. /* If p==0 (unmap the entire file) then there must be no outstanding
  42427. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  42428. ** then there must be at least one outstanding. */
  42429. assert( (p==0)==(pFd->nFetchOut==0) );
  42430. /* If p!=0, it must match the iOff value. */
  42431. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  42432. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  42433. osGetCurrentProcessId(), pFd, iOff, p));
  42434. if( p ){
  42435. pFd->nFetchOut--;
  42436. }else{
  42437. /* FIXME: If Windows truly always prevents truncating or deleting a
  42438. ** file while a mapping is held, then the following winUnmapfile() call
  42439. ** is unnecessary can be omitted - potentially improving
  42440. ** performance. */
  42441. winUnmapfile(pFd);
  42442. }
  42443. assert( pFd->nFetchOut>=0 );
  42444. #endif
  42445. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  42446. osGetCurrentProcessId(), fd));
  42447. return SQLITE_OK;
  42448. }
  42449. /*
  42450. ** Here ends the implementation of all sqlite3_file methods.
  42451. **
  42452. ********************** End sqlite3_file Methods *******************************
  42453. ******************************************************************************/
  42454. /*
  42455. ** This vector defines all the methods that can operate on an
  42456. ** sqlite3_file for win32.
  42457. */
  42458. static const sqlite3_io_methods winIoMethod = {
  42459. 3, /* iVersion */
  42460. winClose, /* xClose */
  42461. winRead, /* xRead */
  42462. winWrite, /* xWrite */
  42463. winTruncate, /* xTruncate */
  42464. winSync, /* xSync */
  42465. winFileSize, /* xFileSize */
  42466. winLock, /* xLock */
  42467. winUnlock, /* xUnlock */
  42468. winCheckReservedLock, /* xCheckReservedLock */
  42469. winFileControl, /* xFileControl */
  42470. winSectorSize, /* xSectorSize */
  42471. winDeviceCharacteristics, /* xDeviceCharacteristics */
  42472. winShmMap, /* xShmMap */
  42473. winShmLock, /* xShmLock */
  42474. winShmBarrier, /* xShmBarrier */
  42475. winShmUnmap, /* xShmUnmap */
  42476. winFetch, /* xFetch */
  42477. winUnfetch /* xUnfetch */
  42478. };
  42479. /*
  42480. ** This vector defines all the methods that can operate on an
  42481. ** sqlite3_file for win32 without performing any locking.
  42482. */
  42483. static const sqlite3_io_methods winIoNolockMethod = {
  42484. 3, /* iVersion */
  42485. winClose, /* xClose */
  42486. winRead, /* xRead */
  42487. winWrite, /* xWrite */
  42488. winTruncate, /* xTruncate */
  42489. winSync, /* xSync */
  42490. winFileSize, /* xFileSize */
  42491. winNolockLock, /* xLock */
  42492. winNolockUnlock, /* xUnlock */
  42493. winNolockCheckReservedLock, /* xCheckReservedLock */
  42494. winFileControl, /* xFileControl */
  42495. winSectorSize, /* xSectorSize */
  42496. winDeviceCharacteristics, /* xDeviceCharacteristics */
  42497. winShmMap, /* xShmMap */
  42498. winShmLock, /* xShmLock */
  42499. winShmBarrier, /* xShmBarrier */
  42500. winShmUnmap, /* xShmUnmap */
  42501. winFetch, /* xFetch */
  42502. winUnfetch /* xUnfetch */
  42503. };
  42504. static winVfsAppData winAppData = {
  42505. &winIoMethod, /* pMethod */
  42506. 0, /* pAppData */
  42507. 0 /* bNoLock */
  42508. };
  42509. static winVfsAppData winNolockAppData = {
  42510. &winIoNolockMethod, /* pMethod */
  42511. 0, /* pAppData */
  42512. 1 /* bNoLock */
  42513. };
  42514. /****************************************************************************
  42515. **************************** sqlite3_vfs methods ****************************
  42516. **
  42517. ** This division contains the implementation of methods on the
  42518. ** sqlite3_vfs object.
  42519. */
  42520. #if defined(__CYGWIN__)
  42521. /*
  42522. ** Convert a filename from whatever the underlying operating system
  42523. ** supports for filenames into UTF-8. Space to hold the result is
  42524. ** obtained from malloc and must be freed by the calling function.
  42525. */
  42526. static char *winConvertToUtf8Filename(const void *zFilename){
  42527. char *zConverted = 0;
  42528. if( osIsNT() ){
  42529. zConverted = winUnicodeToUtf8(zFilename);
  42530. }
  42531. #ifdef SQLITE_WIN32_HAS_ANSI
  42532. else{
  42533. zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
  42534. }
  42535. #endif
  42536. /* caller will handle out of memory */
  42537. return zConverted;
  42538. }
  42539. #endif
  42540. /*
  42541. ** Convert a UTF-8 filename into whatever form the underlying
  42542. ** operating system wants filenames in. Space to hold the result
  42543. ** is obtained from malloc and must be freed by the calling
  42544. ** function.
  42545. */
  42546. static void *winConvertFromUtf8Filename(const char *zFilename){
  42547. void *zConverted = 0;
  42548. if( osIsNT() ){
  42549. zConverted = winUtf8ToUnicode(zFilename);
  42550. }
  42551. #ifdef SQLITE_WIN32_HAS_ANSI
  42552. else{
  42553. zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
  42554. }
  42555. #endif
  42556. /* caller will handle out of memory */
  42557. return zConverted;
  42558. }
  42559. /*
  42560. ** This function returns non-zero if the specified UTF-8 string buffer
  42561. ** ends with a directory separator character or one was successfully
  42562. ** added to it.
  42563. */
  42564. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  42565. if( zBuf ){
  42566. int nLen = sqlite3Strlen30(zBuf);
  42567. if( nLen>0 ){
  42568. if( winIsDirSep(zBuf[nLen-1]) ){
  42569. return 1;
  42570. }else if( nLen+1<nBuf ){
  42571. zBuf[nLen] = winGetDirSep();
  42572. zBuf[nLen+1] = '\0';
  42573. return 1;
  42574. }
  42575. }
  42576. }
  42577. return 0;
  42578. }
  42579. /*
  42580. ** Create a temporary file name and store the resulting pointer into pzBuf.
  42581. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  42582. */
  42583. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  42584. static char zChars[] =
  42585. "abcdefghijklmnopqrstuvwxyz"
  42586. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  42587. "0123456789";
  42588. size_t i, j;
  42589. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  42590. int nMax, nBuf, nDir, nLen;
  42591. char *zBuf;
  42592. /* It's odd to simulate an io-error here, but really this is just
  42593. ** using the io-error infrastructure to test that SQLite handles this
  42594. ** function failing.
  42595. */
  42596. SimulateIOError( return SQLITE_IOERR );
  42597. /* Allocate a temporary buffer to store the fully qualified file
  42598. ** name for the temporary file. If this fails, we cannot continue.
  42599. */
  42600. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  42601. zBuf = sqlite3MallocZero( nBuf );
  42602. if( !zBuf ){
  42603. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42604. return SQLITE_IOERR_NOMEM_BKPT;
  42605. }
  42606. /* Figure out the effective temporary directory. First, check if one
  42607. ** has been explicitly set by the application; otherwise, use the one
  42608. ** configured by the operating system.
  42609. */
  42610. nDir = nMax - (nPre + 15);
  42611. assert( nDir>0 );
  42612. if( sqlite3_temp_directory ){
  42613. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  42614. if( nDirLen>0 ){
  42615. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  42616. nDirLen++;
  42617. }
  42618. if( nDirLen>nDir ){
  42619. sqlite3_free(zBuf);
  42620. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  42621. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  42622. }
  42623. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  42624. }
  42625. }
  42626. #if defined(__CYGWIN__)
  42627. else{
  42628. static const char *azDirs[] = {
  42629. 0, /* getenv("SQLITE_TMPDIR") */
  42630. 0, /* getenv("TMPDIR") */
  42631. 0, /* getenv("TMP") */
  42632. 0, /* getenv("TEMP") */
  42633. 0, /* getenv("USERPROFILE") */
  42634. "/var/tmp",
  42635. "/usr/tmp",
  42636. "/tmp",
  42637. ".",
  42638. 0 /* List terminator */
  42639. };
  42640. unsigned int i;
  42641. const char *zDir = 0;
  42642. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  42643. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  42644. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  42645. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  42646. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  42647. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  42648. void *zConverted;
  42649. if( zDir==0 ) continue;
  42650. /* If the path starts with a drive letter followed by the colon
  42651. ** character, assume it is already a native Win32 path; otherwise,
  42652. ** it must be converted to a native Win32 path via the Cygwin API
  42653. ** prior to using it.
  42654. */
  42655. if( winIsDriveLetterAndColon(zDir) ){
  42656. zConverted = winConvertFromUtf8Filename(zDir);
  42657. if( !zConverted ){
  42658. sqlite3_free(zBuf);
  42659. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42660. return SQLITE_IOERR_NOMEM_BKPT;
  42661. }
  42662. if( winIsDir(zConverted) ){
  42663. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  42664. sqlite3_free(zConverted);
  42665. break;
  42666. }
  42667. sqlite3_free(zConverted);
  42668. }else{
  42669. zConverted = sqlite3MallocZero( nMax+1 );
  42670. if( !zConverted ){
  42671. sqlite3_free(zBuf);
  42672. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42673. return SQLITE_IOERR_NOMEM_BKPT;
  42674. }
  42675. if( cygwin_conv_path(
  42676. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  42677. zConverted, nMax+1)<0 ){
  42678. sqlite3_free(zConverted);
  42679. sqlite3_free(zBuf);
  42680. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  42681. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  42682. "winGetTempname2", zDir);
  42683. }
  42684. if( winIsDir(zConverted) ){
  42685. /* At this point, we know the candidate directory exists and should
  42686. ** be used. However, we may need to convert the string containing
  42687. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  42688. */
  42689. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  42690. if( !zUtf8 ){
  42691. sqlite3_free(zConverted);
  42692. sqlite3_free(zBuf);
  42693. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42694. return SQLITE_IOERR_NOMEM_BKPT;
  42695. }
  42696. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  42697. sqlite3_free(zUtf8);
  42698. sqlite3_free(zConverted);
  42699. break;
  42700. }
  42701. sqlite3_free(zConverted);
  42702. }
  42703. }
  42704. }
  42705. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  42706. else if( osIsNT() ){
  42707. char *zMulti;
  42708. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  42709. if( !zWidePath ){
  42710. sqlite3_free(zBuf);
  42711. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42712. return SQLITE_IOERR_NOMEM_BKPT;
  42713. }
  42714. if( osGetTempPathW(nMax, zWidePath)==0 ){
  42715. sqlite3_free(zWidePath);
  42716. sqlite3_free(zBuf);
  42717. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  42718. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  42719. "winGetTempname2", 0);
  42720. }
  42721. zMulti = winUnicodeToUtf8(zWidePath);
  42722. if( zMulti ){
  42723. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  42724. sqlite3_free(zMulti);
  42725. sqlite3_free(zWidePath);
  42726. }else{
  42727. sqlite3_free(zWidePath);
  42728. sqlite3_free(zBuf);
  42729. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42730. return SQLITE_IOERR_NOMEM_BKPT;
  42731. }
  42732. }
  42733. #ifdef SQLITE_WIN32_HAS_ANSI
  42734. else{
  42735. char *zUtf8;
  42736. char *zMbcsPath = sqlite3MallocZero( nMax );
  42737. if( !zMbcsPath ){
  42738. sqlite3_free(zBuf);
  42739. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42740. return SQLITE_IOERR_NOMEM_BKPT;
  42741. }
  42742. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  42743. sqlite3_free(zBuf);
  42744. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  42745. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  42746. "winGetTempname3", 0);
  42747. }
  42748. zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
  42749. if( zUtf8 ){
  42750. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  42751. sqlite3_free(zUtf8);
  42752. }else{
  42753. sqlite3_free(zBuf);
  42754. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  42755. return SQLITE_IOERR_NOMEM_BKPT;
  42756. }
  42757. }
  42758. #endif /* SQLITE_WIN32_HAS_ANSI */
  42759. #endif /* !SQLITE_OS_WINRT */
  42760. /*
  42761. ** Check to make sure the temporary directory ends with an appropriate
  42762. ** separator. If it does not and there is not enough space left to add
  42763. ** one, fail.
  42764. */
  42765. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  42766. sqlite3_free(zBuf);
  42767. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  42768. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  42769. }
  42770. /*
  42771. ** Check that the output buffer is large enough for the temporary file
  42772. ** name in the following format:
  42773. **
  42774. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  42775. **
  42776. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  42777. ** account for the space used by the 15 character random suffix and the
  42778. ** two trailing NUL characters. The final directory separator character
  42779. ** has already added if it was not already present.
  42780. */
  42781. nLen = sqlite3Strlen30(zBuf);
  42782. if( (nLen + nPre + 17) > nBuf ){
  42783. sqlite3_free(zBuf);
  42784. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  42785. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  42786. }
  42787. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  42788. j = sqlite3Strlen30(zBuf);
  42789. sqlite3_randomness(15, &zBuf[j]);
  42790. for(i=0; i<15; i++, j++){
  42791. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  42792. }
  42793. zBuf[j] = 0;
  42794. zBuf[j+1] = 0;
  42795. *pzBuf = zBuf;
  42796. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  42797. return SQLITE_OK;
  42798. }
  42799. /*
  42800. ** Return TRUE if the named file is really a directory. Return false if
  42801. ** it is something other than a directory, or if there is any kind of memory
  42802. ** allocation failure.
  42803. */
  42804. static int winIsDir(const void *zConverted){
  42805. DWORD attr;
  42806. int rc = 0;
  42807. DWORD lastErrno;
  42808. if( osIsNT() ){
  42809. int cnt = 0;
  42810. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  42811. memset(&sAttrData, 0, sizeof(sAttrData));
  42812. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  42813. GetFileExInfoStandard,
  42814. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  42815. if( !rc ){
  42816. return 0; /* Invalid name? */
  42817. }
  42818. attr = sAttrData.dwFileAttributes;
  42819. #if SQLITE_OS_WINCE==0
  42820. }else{
  42821. attr = osGetFileAttributesA((char*)zConverted);
  42822. #endif
  42823. }
  42824. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  42825. }
  42826. /* forward reference */
  42827. static int winAccess(
  42828. sqlite3_vfs *pVfs, /* Not used on win32 */
  42829. const char *zFilename, /* Name of file to check */
  42830. int flags, /* Type of test to make on this file */
  42831. int *pResOut /* OUT: Result */
  42832. );
  42833. /*
  42834. ** Open a file.
  42835. */
  42836. static int winOpen(
  42837. sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
  42838. const char *zName, /* Name of the file (UTF-8) */
  42839. sqlite3_file *id, /* Write the SQLite file handle here */
  42840. int flags, /* Open mode flags */
  42841. int *pOutFlags /* Status return flags */
  42842. ){
  42843. HANDLE h;
  42844. DWORD lastErrno = 0;
  42845. DWORD dwDesiredAccess;
  42846. DWORD dwShareMode;
  42847. DWORD dwCreationDisposition;
  42848. DWORD dwFlagsAndAttributes = 0;
  42849. #if SQLITE_OS_WINCE
  42850. int isTemp = 0;
  42851. #endif
  42852. winVfsAppData *pAppData;
  42853. winFile *pFile = (winFile*)id;
  42854. void *zConverted; /* Filename in OS encoding */
  42855. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  42856. int cnt = 0;
  42857. /* If argument zPath is a NULL pointer, this function is required to open
  42858. ** a temporary file. Use this buffer to store the file name in.
  42859. */
  42860. char *zTmpname = 0; /* For temporary filename, if necessary. */
  42861. int rc = SQLITE_OK; /* Function Return Code */
  42862. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  42863. int eType = flags&0xFFFFFF00; /* Type of file to open */
  42864. #endif
  42865. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  42866. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  42867. int isCreate = (flags & SQLITE_OPEN_CREATE);
  42868. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  42869. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  42870. #ifndef NDEBUG
  42871. int isOpenJournal = (isCreate && (
  42872. eType==SQLITE_OPEN_MASTER_JOURNAL
  42873. || eType==SQLITE_OPEN_MAIN_JOURNAL
  42874. || eType==SQLITE_OPEN_WAL
  42875. ));
  42876. #endif
  42877. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  42878. zUtf8Name, id, flags, pOutFlags));
  42879. /* Check the following statements are true:
  42880. **
  42881. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  42882. ** (b) if CREATE is set, then READWRITE must also be set, and
  42883. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  42884. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  42885. */
  42886. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  42887. assert(isCreate==0 || isReadWrite);
  42888. assert(isExclusive==0 || isCreate);
  42889. assert(isDelete==0 || isCreate);
  42890. /* The main DB, main journal, WAL file and master journal are never
  42891. ** automatically deleted. Nor are they ever temporary files. */
  42892. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  42893. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  42894. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  42895. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  42896. /* Assert that the upper layer has set one of the "file-type" flags. */
  42897. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  42898. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  42899. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  42900. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  42901. );
  42902. assert( pFile!=0 );
  42903. memset(pFile, 0, sizeof(winFile));
  42904. pFile->h = INVALID_HANDLE_VALUE;
  42905. #if SQLITE_OS_WINRT
  42906. if( !zUtf8Name && !sqlite3_temp_directory ){
  42907. sqlite3_log(SQLITE_ERROR,
  42908. "sqlite3_temp_directory variable should be set for WinRT");
  42909. }
  42910. #endif
  42911. /* If the second argument to this function is NULL, generate a
  42912. ** temporary file name to use
  42913. */
  42914. if( !zUtf8Name ){
  42915. assert( isDelete && !isOpenJournal );
  42916. rc = winGetTempname(pVfs, &zTmpname);
  42917. if( rc!=SQLITE_OK ){
  42918. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  42919. return rc;
  42920. }
  42921. zUtf8Name = zTmpname;
  42922. }
  42923. /* Database filenames are double-zero terminated if they are not
  42924. ** URIs with parameters. Hence, they can always be passed into
  42925. ** sqlite3_uri_parameter().
  42926. */
  42927. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  42928. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  42929. /* Convert the filename to the system encoding. */
  42930. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  42931. if( zConverted==0 ){
  42932. sqlite3_free(zTmpname);
  42933. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  42934. return SQLITE_IOERR_NOMEM_BKPT;
  42935. }
  42936. if( winIsDir(zConverted) ){
  42937. sqlite3_free(zConverted);
  42938. sqlite3_free(zTmpname);
  42939. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  42940. return SQLITE_CANTOPEN_ISDIR;
  42941. }
  42942. if( isReadWrite ){
  42943. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  42944. }else{
  42945. dwDesiredAccess = GENERIC_READ;
  42946. }
  42947. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  42948. ** created. SQLite doesn't use it to indicate "exclusive access"
  42949. ** as it is usually understood.
  42950. */
  42951. if( isExclusive ){
  42952. /* Creates a new file, only if it does not already exist. */
  42953. /* If the file exists, it fails. */
  42954. dwCreationDisposition = CREATE_NEW;
  42955. }else if( isCreate ){
  42956. /* Open existing file, or create if it doesn't exist */
  42957. dwCreationDisposition = OPEN_ALWAYS;
  42958. }else{
  42959. /* Opens a file, only if it exists. */
  42960. dwCreationDisposition = OPEN_EXISTING;
  42961. }
  42962. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  42963. if( isDelete ){
  42964. #if SQLITE_OS_WINCE
  42965. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  42966. isTemp = 1;
  42967. #else
  42968. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  42969. | FILE_ATTRIBUTE_HIDDEN
  42970. | FILE_FLAG_DELETE_ON_CLOSE;
  42971. #endif
  42972. }else{
  42973. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  42974. }
  42975. /* Reports from the internet are that performance is always
  42976. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  42977. #if SQLITE_OS_WINCE
  42978. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  42979. #endif
  42980. if( osIsNT() ){
  42981. #if SQLITE_OS_WINRT
  42982. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  42983. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  42984. extendedParameters.dwFileAttributes =
  42985. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  42986. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  42987. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  42988. extendedParameters.lpSecurityAttributes = NULL;
  42989. extendedParameters.hTemplateFile = NULL;
  42990. do{
  42991. h = osCreateFile2((LPCWSTR)zConverted,
  42992. dwDesiredAccess,
  42993. dwShareMode,
  42994. dwCreationDisposition,
  42995. &extendedParameters);
  42996. if( h!=INVALID_HANDLE_VALUE ) break;
  42997. if( isReadWrite ){
  42998. int rc2, isRO = 0;
  42999. sqlite3BeginBenignMalloc();
  43000. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  43001. sqlite3EndBenignMalloc();
  43002. if( rc2==SQLITE_OK && isRO ) break;
  43003. }
  43004. }while( winRetryIoerr(&cnt, &lastErrno) );
  43005. #else
  43006. do{
  43007. h = osCreateFileW((LPCWSTR)zConverted,
  43008. dwDesiredAccess,
  43009. dwShareMode, NULL,
  43010. dwCreationDisposition,
  43011. dwFlagsAndAttributes,
  43012. NULL);
  43013. if( h!=INVALID_HANDLE_VALUE ) break;
  43014. if( isReadWrite ){
  43015. int rc2, isRO = 0;
  43016. sqlite3BeginBenignMalloc();
  43017. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  43018. sqlite3EndBenignMalloc();
  43019. if( rc2==SQLITE_OK && isRO ) break;
  43020. }
  43021. }while( winRetryIoerr(&cnt, &lastErrno) );
  43022. #endif
  43023. }
  43024. #ifdef SQLITE_WIN32_HAS_ANSI
  43025. else{
  43026. do{
  43027. h = osCreateFileA((LPCSTR)zConverted,
  43028. dwDesiredAccess,
  43029. dwShareMode, NULL,
  43030. dwCreationDisposition,
  43031. dwFlagsAndAttributes,
  43032. NULL);
  43033. if( h!=INVALID_HANDLE_VALUE ) break;
  43034. if( isReadWrite ){
  43035. int rc2, isRO = 0;
  43036. sqlite3BeginBenignMalloc();
  43037. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  43038. sqlite3EndBenignMalloc();
  43039. if( rc2==SQLITE_OK && isRO ) break;
  43040. }
  43041. }while( winRetryIoerr(&cnt, &lastErrno) );
  43042. }
  43043. #endif
  43044. winLogIoerr(cnt, __LINE__);
  43045. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  43046. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  43047. if( h==INVALID_HANDLE_VALUE ){
  43048. sqlite3_free(zConverted);
  43049. sqlite3_free(zTmpname);
  43050. if( isReadWrite && !isExclusive ){
  43051. return winOpen(pVfs, zName, id,
  43052. ((flags|SQLITE_OPEN_READONLY) &
  43053. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  43054. pOutFlags);
  43055. }else{
  43056. pFile->lastErrno = lastErrno;
  43057. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  43058. return SQLITE_CANTOPEN_BKPT;
  43059. }
  43060. }
  43061. if( pOutFlags ){
  43062. if( isReadWrite ){
  43063. *pOutFlags = SQLITE_OPEN_READWRITE;
  43064. }else{
  43065. *pOutFlags = SQLITE_OPEN_READONLY;
  43066. }
  43067. }
  43068. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  43069. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  43070. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  43071. pAppData = (winVfsAppData*)pVfs->pAppData;
  43072. #if SQLITE_OS_WINCE
  43073. {
  43074. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  43075. && ((pAppData==NULL) || !pAppData->bNoLock)
  43076. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  43077. ){
  43078. osCloseHandle(h);
  43079. sqlite3_free(zConverted);
  43080. sqlite3_free(zTmpname);
  43081. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  43082. return rc;
  43083. }
  43084. }
  43085. if( isTemp ){
  43086. pFile->zDeleteOnClose = zConverted;
  43087. }else
  43088. #endif
  43089. {
  43090. sqlite3_free(zConverted);
  43091. }
  43092. sqlite3_free(zTmpname);
  43093. pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
  43094. pFile->pVfs = pVfs;
  43095. pFile->h = h;
  43096. if( isReadonly ){
  43097. pFile->ctrlFlags |= WINFILE_RDONLY;
  43098. }
  43099. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  43100. pFile->ctrlFlags |= WINFILE_PSOW;
  43101. }
  43102. pFile->lastErrno = NO_ERROR;
  43103. pFile->zPath = zName;
  43104. #if SQLITE_MAX_MMAP_SIZE>0
  43105. pFile->hMap = NULL;
  43106. pFile->pMapRegion = 0;
  43107. pFile->mmapSize = 0;
  43108. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  43109. #endif
  43110. OpenCounter(+1);
  43111. return rc;
  43112. }
  43113. /*
  43114. ** Delete the named file.
  43115. **
  43116. ** Note that Windows does not allow a file to be deleted if some other
  43117. ** process has it open. Sometimes a virus scanner or indexing program
  43118. ** will open a journal file shortly after it is created in order to do
  43119. ** whatever it does. While this other process is holding the
  43120. ** file open, we will be unable to delete it. To work around this
  43121. ** problem, we delay 100 milliseconds and try to delete again. Up
  43122. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  43123. ** up and returning an error.
  43124. */
  43125. static int winDelete(
  43126. sqlite3_vfs *pVfs, /* Not used on win32 */
  43127. const char *zFilename, /* Name of file to delete */
  43128. int syncDir /* Not used on win32 */
  43129. ){
  43130. int cnt = 0;
  43131. int rc;
  43132. DWORD attr;
  43133. DWORD lastErrno = 0;
  43134. void *zConverted;
  43135. UNUSED_PARAMETER(pVfs);
  43136. UNUSED_PARAMETER(syncDir);
  43137. SimulateIOError(return SQLITE_IOERR_DELETE);
  43138. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  43139. zConverted = winConvertFromUtf8Filename(zFilename);
  43140. if( zConverted==0 ){
  43141. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  43142. return SQLITE_IOERR_NOMEM_BKPT;
  43143. }
  43144. if( osIsNT() ){
  43145. do {
  43146. #if SQLITE_OS_WINRT
  43147. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  43148. memset(&sAttrData, 0, sizeof(sAttrData));
  43149. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  43150. &sAttrData) ){
  43151. attr = sAttrData.dwFileAttributes;
  43152. }else{
  43153. lastErrno = osGetLastError();
  43154. if( lastErrno==ERROR_FILE_NOT_FOUND
  43155. || lastErrno==ERROR_PATH_NOT_FOUND ){
  43156. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  43157. }else{
  43158. rc = SQLITE_ERROR;
  43159. }
  43160. break;
  43161. }
  43162. #else
  43163. attr = osGetFileAttributesW(zConverted);
  43164. #endif
  43165. if ( attr==INVALID_FILE_ATTRIBUTES ){
  43166. lastErrno = osGetLastError();
  43167. if( lastErrno==ERROR_FILE_NOT_FOUND
  43168. || lastErrno==ERROR_PATH_NOT_FOUND ){
  43169. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  43170. }else{
  43171. rc = SQLITE_ERROR;
  43172. }
  43173. break;
  43174. }
  43175. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  43176. rc = SQLITE_ERROR; /* Files only. */
  43177. break;
  43178. }
  43179. if ( osDeleteFileW(zConverted) ){
  43180. rc = SQLITE_OK; /* Deleted OK. */
  43181. break;
  43182. }
  43183. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  43184. rc = SQLITE_ERROR; /* No more retries. */
  43185. break;
  43186. }
  43187. } while(1);
  43188. }
  43189. #ifdef SQLITE_WIN32_HAS_ANSI
  43190. else{
  43191. do {
  43192. attr = osGetFileAttributesA(zConverted);
  43193. if ( attr==INVALID_FILE_ATTRIBUTES ){
  43194. lastErrno = osGetLastError();
  43195. if( lastErrno==ERROR_FILE_NOT_FOUND
  43196. || lastErrno==ERROR_PATH_NOT_FOUND ){
  43197. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  43198. }else{
  43199. rc = SQLITE_ERROR;
  43200. }
  43201. break;
  43202. }
  43203. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  43204. rc = SQLITE_ERROR; /* Files only. */
  43205. break;
  43206. }
  43207. if ( osDeleteFileA(zConverted) ){
  43208. rc = SQLITE_OK; /* Deleted OK. */
  43209. break;
  43210. }
  43211. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  43212. rc = SQLITE_ERROR; /* No more retries. */
  43213. break;
  43214. }
  43215. } while(1);
  43216. }
  43217. #endif
  43218. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  43219. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  43220. }else{
  43221. winLogIoerr(cnt, __LINE__);
  43222. }
  43223. sqlite3_free(zConverted);
  43224. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  43225. return rc;
  43226. }
  43227. /*
  43228. ** Check the existence and status of a file.
  43229. */
  43230. static int winAccess(
  43231. sqlite3_vfs *pVfs, /* Not used on win32 */
  43232. const char *zFilename, /* Name of file to check */
  43233. int flags, /* Type of test to make on this file */
  43234. int *pResOut /* OUT: Result */
  43235. ){
  43236. DWORD attr;
  43237. int rc = 0;
  43238. DWORD lastErrno = 0;
  43239. void *zConverted;
  43240. UNUSED_PARAMETER(pVfs);
  43241. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  43242. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  43243. zFilename, flags, pResOut));
  43244. zConverted = winConvertFromUtf8Filename(zFilename);
  43245. if( zConverted==0 ){
  43246. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  43247. return SQLITE_IOERR_NOMEM_BKPT;
  43248. }
  43249. if( osIsNT() ){
  43250. int cnt = 0;
  43251. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  43252. memset(&sAttrData, 0, sizeof(sAttrData));
  43253. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  43254. GetFileExInfoStandard,
  43255. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  43256. if( rc ){
  43257. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  43258. ** as if it does not exist.
  43259. */
  43260. if( flags==SQLITE_ACCESS_EXISTS
  43261. && sAttrData.nFileSizeHigh==0
  43262. && sAttrData.nFileSizeLow==0 ){
  43263. attr = INVALID_FILE_ATTRIBUTES;
  43264. }else{
  43265. attr = sAttrData.dwFileAttributes;
  43266. }
  43267. }else{
  43268. winLogIoerr(cnt, __LINE__);
  43269. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  43270. sqlite3_free(zConverted);
  43271. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  43272. zFilename);
  43273. }else{
  43274. attr = INVALID_FILE_ATTRIBUTES;
  43275. }
  43276. }
  43277. }
  43278. #ifdef SQLITE_WIN32_HAS_ANSI
  43279. else{
  43280. attr = osGetFileAttributesA((char*)zConverted);
  43281. }
  43282. #endif
  43283. sqlite3_free(zConverted);
  43284. switch( flags ){
  43285. case SQLITE_ACCESS_READ:
  43286. case SQLITE_ACCESS_EXISTS:
  43287. rc = attr!=INVALID_FILE_ATTRIBUTES;
  43288. break;
  43289. case SQLITE_ACCESS_READWRITE:
  43290. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  43291. (attr & FILE_ATTRIBUTE_READONLY)==0;
  43292. break;
  43293. default:
  43294. assert(!"Invalid flags argument");
  43295. }
  43296. *pResOut = rc;
  43297. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  43298. zFilename, pResOut, *pResOut));
  43299. return SQLITE_OK;
  43300. }
  43301. /*
  43302. ** Returns non-zero if the specified path name starts with a drive letter
  43303. ** followed by a colon character.
  43304. */
  43305. static BOOL winIsDriveLetterAndColon(
  43306. const char *zPathname
  43307. ){
  43308. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  43309. }
  43310. /*
  43311. ** Returns non-zero if the specified path name should be used verbatim. If
  43312. ** non-zero is returned from this function, the calling function must simply
  43313. ** use the provided path name verbatim -OR- resolve it into a full path name
  43314. ** using the GetFullPathName Win32 API function (if available).
  43315. */
  43316. static BOOL winIsVerbatimPathname(
  43317. const char *zPathname
  43318. ){
  43319. /*
  43320. ** If the path name starts with a forward slash or a backslash, it is either
  43321. ** a legal UNC name, a volume relative path, or an absolute path name in the
  43322. ** "Unix" format on Windows. There is no easy way to differentiate between
  43323. ** the final two cases; therefore, we return the safer return value of TRUE
  43324. ** so that callers of this function will simply use it verbatim.
  43325. */
  43326. if ( winIsDirSep(zPathname[0]) ){
  43327. return TRUE;
  43328. }
  43329. /*
  43330. ** If the path name starts with a letter and a colon it is either a volume
  43331. ** relative path or an absolute path. Callers of this function must not
  43332. ** attempt to treat it as a relative path name (i.e. they should simply use
  43333. ** it verbatim).
  43334. */
  43335. if ( winIsDriveLetterAndColon(zPathname) ){
  43336. return TRUE;
  43337. }
  43338. /*
  43339. ** If we get to this point, the path name should almost certainly be a purely
  43340. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  43341. */
  43342. return FALSE;
  43343. }
  43344. /*
  43345. ** Turn a relative pathname into a full pathname. Write the full
  43346. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  43347. ** bytes in size.
  43348. */
  43349. static int winFullPathname(
  43350. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  43351. const char *zRelative, /* Possibly relative input path */
  43352. int nFull, /* Size of output buffer in bytes */
  43353. char *zFull /* Output buffer */
  43354. ){
  43355. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  43356. DWORD nByte;
  43357. void *zConverted;
  43358. char *zOut;
  43359. #endif
  43360. /* If this path name begins with "/X:", where "X" is any alphabetic
  43361. ** character, discard the initial "/" from the pathname.
  43362. */
  43363. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  43364. zRelative++;
  43365. }
  43366. #if defined(__CYGWIN__)
  43367. SimulateIOError( return SQLITE_ERROR );
  43368. UNUSED_PARAMETER(nFull);
  43369. assert( nFull>=pVfs->mxPathname );
  43370. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  43371. /*
  43372. ** NOTE: We are dealing with a relative path name and the data
  43373. ** directory has been set. Therefore, use it as the basis
  43374. ** for converting the relative path name to an absolute
  43375. ** one by prepending the data directory and a slash.
  43376. */
  43377. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  43378. if( !zOut ){
  43379. return SQLITE_IOERR_NOMEM_BKPT;
  43380. }
  43381. if( cygwin_conv_path(
  43382. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  43383. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  43384. sqlite3_free(zOut);
  43385. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  43386. "winFullPathname1", zRelative);
  43387. }else{
  43388. char *zUtf8 = winConvertToUtf8Filename(zOut);
  43389. if( !zUtf8 ){
  43390. sqlite3_free(zOut);
  43391. return SQLITE_IOERR_NOMEM_BKPT;
  43392. }
  43393. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  43394. sqlite3_data_directory, winGetDirSep(), zUtf8);
  43395. sqlite3_free(zUtf8);
  43396. sqlite3_free(zOut);
  43397. }
  43398. }else{
  43399. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  43400. if( !zOut ){
  43401. return SQLITE_IOERR_NOMEM_BKPT;
  43402. }
  43403. if( cygwin_conv_path(
  43404. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  43405. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  43406. sqlite3_free(zOut);
  43407. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  43408. "winFullPathname2", zRelative);
  43409. }else{
  43410. char *zUtf8 = winConvertToUtf8Filename(zOut);
  43411. if( !zUtf8 ){
  43412. sqlite3_free(zOut);
  43413. return SQLITE_IOERR_NOMEM_BKPT;
  43414. }
  43415. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  43416. sqlite3_free(zUtf8);
  43417. sqlite3_free(zOut);
  43418. }
  43419. }
  43420. return SQLITE_OK;
  43421. #endif
  43422. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  43423. SimulateIOError( return SQLITE_ERROR );
  43424. /* WinCE has no concept of a relative pathname, or so I am told. */
  43425. /* WinRT has no way to convert a relative path to an absolute one. */
  43426. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  43427. /*
  43428. ** NOTE: We are dealing with a relative path name and the data
  43429. ** directory has been set. Therefore, use it as the basis
  43430. ** for converting the relative path name to an absolute
  43431. ** one by prepending the data directory and a backslash.
  43432. */
  43433. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  43434. sqlite3_data_directory, winGetDirSep(), zRelative);
  43435. }else{
  43436. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  43437. }
  43438. return SQLITE_OK;
  43439. #endif
  43440. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  43441. /* It's odd to simulate an io-error here, but really this is just
  43442. ** using the io-error infrastructure to test that SQLite handles this
  43443. ** function failing. This function could fail if, for example, the
  43444. ** current working directory has been unlinked.
  43445. */
  43446. SimulateIOError( return SQLITE_ERROR );
  43447. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  43448. /*
  43449. ** NOTE: We are dealing with a relative path name and the data
  43450. ** directory has been set. Therefore, use it as the basis
  43451. ** for converting the relative path name to an absolute
  43452. ** one by prepending the data directory and a backslash.
  43453. */
  43454. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  43455. sqlite3_data_directory, winGetDirSep(), zRelative);
  43456. return SQLITE_OK;
  43457. }
  43458. zConverted = winConvertFromUtf8Filename(zRelative);
  43459. if( zConverted==0 ){
  43460. return SQLITE_IOERR_NOMEM_BKPT;
  43461. }
  43462. if( osIsNT() ){
  43463. LPWSTR zTemp;
  43464. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  43465. if( nByte==0 ){
  43466. sqlite3_free(zConverted);
  43467. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43468. "winFullPathname1", zRelative);
  43469. }
  43470. nByte += 3;
  43471. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  43472. if( zTemp==0 ){
  43473. sqlite3_free(zConverted);
  43474. return SQLITE_IOERR_NOMEM_BKPT;
  43475. }
  43476. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  43477. if( nByte==0 ){
  43478. sqlite3_free(zConverted);
  43479. sqlite3_free(zTemp);
  43480. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43481. "winFullPathname2", zRelative);
  43482. }
  43483. sqlite3_free(zConverted);
  43484. zOut = winUnicodeToUtf8(zTemp);
  43485. sqlite3_free(zTemp);
  43486. }
  43487. #ifdef SQLITE_WIN32_HAS_ANSI
  43488. else{
  43489. char *zTemp;
  43490. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  43491. if( nByte==0 ){
  43492. sqlite3_free(zConverted);
  43493. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43494. "winFullPathname3", zRelative);
  43495. }
  43496. nByte += 3;
  43497. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  43498. if( zTemp==0 ){
  43499. sqlite3_free(zConverted);
  43500. return SQLITE_IOERR_NOMEM_BKPT;
  43501. }
  43502. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  43503. if( nByte==0 ){
  43504. sqlite3_free(zConverted);
  43505. sqlite3_free(zTemp);
  43506. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  43507. "winFullPathname4", zRelative);
  43508. }
  43509. sqlite3_free(zConverted);
  43510. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  43511. sqlite3_free(zTemp);
  43512. }
  43513. #endif
  43514. if( zOut ){
  43515. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  43516. sqlite3_free(zOut);
  43517. return SQLITE_OK;
  43518. }else{
  43519. return SQLITE_IOERR_NOMEM_BKPT;
  43520. }
  43521. #endif
  43522. }
  43523. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  43524. /*
  43525. ** Interfaces for opening a shared library, finding entry points
  43526. ** within the shared library, and closing the shared library.
  43527. */
  43528. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  43529. HANDLE h;
  43530. #if defined(__CYGWIN__)
  43531. int nFull = pVfs->mxPathname+1;
  43532. char *zFull = sqlite3MallocZero( nFull );
  43533. void *zConverted = 0;
  43534. if( zFull==0 ){
  43535. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  43536. return 0;
  43537. }
  43538. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  43539. sqlite3_free(zFull);
  43540. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  43541. return 0;
  43542. }
  43543. zConverted = winConvertFromUtf8Filename(zFull);
  43544. sqlite3_free(zFull);
  43545. #else
  43546. void *zConverted = winConvertFromUtf8Filename(zFilename);
  43547. UNUSED_PARAMETER(pVfs);
  43548. #endif
  43549. if( zConverted==0 ){
  43550. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  43551. return 0;
  43552. }
  43553. if( osIsNT() ){
  43554. #if SQLITE_OS_WINRT
  43555. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  43556. #else
  43557. h = osLoadLibraryW((LPCWSTR)zConverted);
  43558. #endif
  43559. }
  43560. #ifdef SQLITE_WIN32_HAS_ANSI
  43561. else{
  43562. h = osLoadLibraryA((char*)zConverted);
  43563. }
  43564. #endif
  43565. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  43566. sqlite3_free(zConverted);
  43567. return (void*)h;
  43568. }
  43569. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  43570. UNUSED_PARAMETER(pVfs);
  43571. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  43572. }
  43573. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  43574. FARPROC proc;
  43575. UNUSED_PARAMETER(pVfs);
  43576. proc = osGetProcAddressA((HANDLE)pH, zSym);
  43577. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  43578. (void*)pH, zSym, (void*)proc));
  43579. return (void(*)(void))proc;
  43580. }
  43581. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  43582. UNUSED_PARAMETER(pVfs);
  43583. osFreeLibrary((HANDLE)pHandle);
  43584. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  43585. }
  43586. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  43587. #define winDlOpen 0
  43588. #define winDlError 0
  43589. #define winDlSym 0
  43590. #define winDlClose 0
  43591. #endif
  43592. /* State information for the randomness gatherer. */
  43593. typedef struct EntropyGatherer EntropyGatherer;
  43594. struct EntropyGatherer {
  43595. unsigned char *a; /* Gather entropy into this buffer */
  43596. int na; /* Size of a[] in bytes */
  43597. int i; /* XOR next input into a[i] */
  43598. int nXor; /* Number of XOR operations done */
  43599. };
  43600. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  43601. /* Mix sz bytes of entropy into p. */
  43602. static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
  43603. int j, k;
  43604. for(j=0, k=p->i; j<sz; j++){
  43605. p->a[k++] ^= x[j];
  43606. if( k>=p->na ) k = 0;
  43607. }
  43608. p->i = k;
  43609. p->nXor += sz;
  43610. }
  43611. #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
  43612. /*
  43613. ** Write up to nBuf bytes of randomness into zBuf.
  43614. */
  43615. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  43616. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  43617. UNUSED_PARAMETER(pVfs);
  43618. memset(zBuf, 0, nBuf);
  43619. return nBuf;
  43620. #else
  43621. EntropyGatherer e;
  43622. UNUSED_PARAMETER(pVfs);
  43623. memset(zBuf, 0, nBuf);
  43624. e.a = (unsigned char*)zBuf;
  43625. e.na = nBuf;
  43626. e.nXor = 0;
  43627. e.i = 0;
  43628. {
  43629. SYSTEMTIME x;
  43630. osGetSystemTime(&x);
  43631. xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
  43632. }
  43633. {
  43634. DWORD pid = osGetCurrentProcessId();
  43635. xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
  43636. }
  43637. #if SQLITE_OS_WINRT
  43638. {
  43639. ULONGLONG cnt = osGetTickCount64();
  43640. xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
  43641. }
  43642. #else
  43643. {
  43644. DWORD cnt = osGetTickCount();
  43645. xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
  43646. }
  43647. #endif /* SQLITE_OS_WINRT */
  43648. {
  43649. LARGE_INTEGER i;
  43650. osQueryPerformanceCounter(&i);
  43651. xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
  43652. }
  43653. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  43654. {
  43655. UUID id;
  43656. memset(&id, 0, sizeof(UUID));
  43657. osUuidCreate(&id);
  43658. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  43659. memset(&id, 0, sizeof(UUID));
  43660. osUuidCreateSequential(&id);
  43661. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  43662. }
  43663. #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
  43664. return e.nXor>nBuf ? nBuf : e.nXor;
  43665. #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
  43666. }
  43667. /*
  43668. ** Sleep for a little while. Return the amount of time slept.
  43669. */
  43670. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  43671. sqlite3_win32_sleep((microsec+999)/1000);
  43672. UNUSED_PARAMETER(pVfs);
  43673. return ((microsec+999)/1000)*1000;
  43674. }
  43675. /*
  43676. ** The following variable, if set to a non-zero value, is interpreted as
  43677. ** the number of seconds since 1970 and is used to set the result of
  43678. ** sqlite3OsCurrentTime() during testing.
  43679. */
  43680. #ifdef SQLITE_TEST
  43681. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  43682. #endif
  43683. /*
  43684. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  43685. ** the current time and date as a Julian Day number times 86_400_000. In
  43686. ** other words, write into *piNow the number of milliseconds since the Julian
  43687. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  43688. ** proleptic Gregorian calendar.
  43689. **
  43690. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  43691. ** cannot be found.
  43692. */
  43693. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  43694. /* FILETIME structure is a 64-bit value representing the number of
  43695. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  43696. */
  43697. FILETIME ft;
  43698. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  43699. #ifdef SQLITE_TEST
  43700. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  43701. #endif
  43702. /* 2^32 - to avoid use of LL and warnings in gcc */
  43703. static const sqlite3_int64 max32BitValue =
  43704. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  43705. (sqlite3_int64)294967296;
  43706. #if SQLITE_OS_WINCE
  43707. SYSTEMTIME time;
  43708. osGetSystemTime(&time);
  43709. /* if SystemTimeToFileTime() fails, it returns zero. */
  43710. if (!osSystemTimeToFileTime(&time,&ft)){
  43711. return SQLITE_ERROR;
  43712. }
  43713. #else
  43714. osGetSystemTimeAsFileTime( &ft );
  43715. #endif
  43716. *piNow = winFiletimeEpoch +
  43717. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  43718. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  43719. #ifdef SQLITE_TEST
  43720. if( sqlite3_current_time ){
  43721. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  43722. }
  43723. #endif
  43724. UNUSED_PARAMETER(pVfs);
  43725. return SQLITE_OK;
  43726. }
  43727. /*
  43728. ** Find the current time (in Universal Coordinated Time). Write the
  43729. ** current time and date as a Julian Day number into *prNow and
  43730. ** return 0. Return 1 if the time and date cannot be found.
  43731. */
  43732. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  43733. int rc;
  43734. sqlite3_int64 i;
  43735. rc = winCurrentTimeInt64(pVfs, &i);
  43736. if( !rc ){
  43737. *prNow = i/86400000.0;
  43738. }
  43739. return rc;
  43740. }
  43741. /*
  43742. ** The idea is that this function works like a combination of
  43743. ** GetLastError() and FormatMessage() on Windows (or errno and
  43744. ** strerror_r() on Unix). After an error is returned by an OS
  43745. ** function, SQLite calls this function with zBuf pointing to
  43746. ** a buffer of nBuf bytes. The OS layer should populate the
  43747. ** buffer with a nul-terminated UTF-8 encoded error message
  43748. ** describing the last IO error to have occurred within the calling
  43749. ** thread.
  43750. **
  43751. ** If the error message is too large for the supplied buffer,
  43752. ** it should be truncated. The return value of xGetLastError
  43753. ** is zero if the error message fits in the buffer, or non-zero
  43754. ** otherwise (if the message was truncated). If non-zero is returned,
  43755. ** then it is not necessary to include the nul-terminator character
  43756. ** in the output buffer.
  43757. **
  43758. ** Not supplying an error message will have no adverse effect
  43759. ** on SQLite. It is fine to have an implementation that never
  43760. ** returns an error message:
  43761. **
  43762. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  43763. ** assert(zBuf[0]=='\0');
  43764. ** return 0;
  43765. ** }
  43766. **
  43767. ** However if an error message is supplied, it will be incorporated
  43768. ** by sqlite into the error message available to the user using
  43769. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  43770. */
  43771. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  43772. DWORD e = osGetLastError();
  43773. UNUSED_PARAMETER(pVfs);
  43774. if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
  43775. return e;
  43776. }
  43777. /*
  43778. ** Initialize and deinitialize the operating system interface.
  43779. */
  43780. SQLITE_API int sqlite3_os_init(void){
  43781. static sqlite3_vfs winVfs = {
  43782. 3, /* iVersion */
  43783. sizeof(winFile), /* szOsFile */
  43784. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  43785. 0, /* pNext */
  43786. "win32", /* zName */
  43787. &winAppData, /* pAppData */
  43788. winOpen, /* xOpen */
  43789. winDelete, /* xDelete */
  43790. winAccess, /* xAccess */
  43791. winFullPathname, /* xFullPathname */
  43792. winDlOpen, /* xDlOpen */
  43793. winDlError, /* xDlError */
  43794. winDlSym, /* xDlSym */
  43795. winDlClose, /* xDlClose */
  43796. winRandomness, /* xRandomness */
  43797. winSleep, /* xSleep */
  43798. winCurrentTime, /* xCurrentTime */
  43799. winGetLastError, /* xGetLastError */
  43800. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43801. winSetSystemCall, /* xSetSystemCall */
  43802. winGetSystemCall, /* xGetSystemCall */
  43803. winNextSystemCall, /* xNextSystemCall */
  43804. };
  43805. #if defined(SQLITE_WIN32_HAS_WIDE)
  43806. static sqlite3_vfs winLongPathVfs = {
  43807. 3, /* iVersion */
  43808. sizeof(winFile), /* szOsFile */
  43809. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  43810. 0, /* pNext */
  43811. "win32-longpath", /* zName */
  43812. &winAppData, /* pAppData */
  43813. winOpen, /* xOpen */
  43814. winDelete, /* xDelete */
  43815. winAccess, /* xAccess */
  43816. winFullPathname, /* xFullPathname */
  43817. winDlOpen, /* xDlOpen */
  43818. winDlError, /* xDlError */
  43819. winDlSym, /* xDlSym */
  43820. winDlClose, /* xDlClose */
  43821. winRandomness, /* xRandomness */
  43822. winSleep, /* xSleep */
  43823. winCurrentTime, /* xCurrentTime */
  43824. winGetLastError, /* xGetLastError */
  43825. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43826. winSetSystemCall, /* xSetSystemCall */
  43827. winGetSystemCall, /* xGetSystemCall */
  43828. winNextSystemCall, /* xNextSystemCall */
  43829. };
  43830. #endif
  43831. static sqlite3_vfs winNolockVfs = {
  43832. 3, /* iVersion */
  43833. sizeof(winFile), /* szOsFile */
  43834. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  43835. 0, /* pNext */
  43836. "win32-none", /* zName */
  43837. &winNolockAppData, /* pAppData */
  43838. winOpen, /* xOpen */
  43839. winDelete, /* xDelete */
  43840. winAccess, /* xAccess */
  43841. winFullPathname, /* xFullPathname */
  43842. winDlOpen, /* xDlOpen */
  43843. winDlError, /* xDlError */
  43844. winDlSym, /* xDlSym */
  43845. winDlClose, /* xDlClose */
  43846. winRandomness, /* xRandomness */
  43847. winSleep, /* xSleep */
  43848. winCurrentTime, /* xCurrentTime */
  43849. winGetLastError, /* xGetLastError */
  43850. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43851. winSetSystemCall, /* xSetSystemCall */
  43852. winGetSystemCall, /* xGetSystemCall */
  43853. winNextSystemCall, /* xNextSystemCall */
  43854. };
  43855. #if defined(SQLITE_WIN32_HAS_WIDE)
  43856. static sqlite3_vfs winLongPathNolockVfs = {
  43857. 3, /* iVersion */
  43858. sizeof(winFile), /* szOsFile */
  43859. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  43860. 0, /* pNext */
  43861. "win32-longpath-none", /* zName */
  43862. &winNolockAppData, /* pAppData */
  43863. winOpen, /* xOpen */
  43864. winDelete, /* xDelete */
  43865. winAccess, /* xAccess */
  43866. winFullPathname, /* xFullPathname */
  43867. winDlOpen, /* xDlOpen */
  43868. winDlError, /* xDlError */
  43869. winDlSym, /* xDlSym */
  43870. winDlClose, /* xDlClose */
  43871. winRandomness, /* xRandomness */
  43872. winSleep, /* xSleep */
  43873. winCurrentTime, /* xCurrentTime */
  43874. winGetLastError, /* xGetLastError */
  43875. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  43876. winSetSystemCall, /* xSetSystemCall */
  43877. winGetSystemCall, /* xGetSystemCall */
  43878. winNextSystemCall, /* xNextSystemCall */
  43879. };
  43880. #endif
  43881. /* Double-check that the aSyscall[] array has been constructed
  43882. ** correctly. See ticket [bb3a86e890c8e96ab] */
  43883. assert( ArraySize(aSyscall)==80 );
  43884. /* get memory map allocation granularity */
  43885. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  43886. #if SQLITE_OS_WINRT
  43887. osGetNativeSystemInfo(&winSysInfo);
  43888. #else
  43889. osGetSystemInfo(&winSysInfo);
  43890. #endif
  43891. assert( winSysInfo.dwAllocationGranularity>0 );
  43892. assert( winSysInfo.dwPageSize>0 );
  43893. sqlite3_vfs_register(&winVfs, 1);
  43894. #if defined(SQLITE_WIN32_HAS_WIDE)
  43895. sqlite3_vfs_register(&winLongPathVfs, 0);
  43896. #endif
  43897. sqlite3_vfs_register(&winNolockVfs, 0);
  43898. #if defined(SQLITE_WIN32_HAS_WIDE)
  43899. sqlite3_vfs_register(&winLongPathNolockVfs, 0);
  43900. #endif
  43901. #ifndef SQLITE_OMIT_WAL
  43902. winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  43903. #endif
  43904. return SQLITE_OK;
  43905. }
  43906. SQLITE_API int sqlite3_os_end(void){
  43907. #if SQLITE_OS_WINRT
  43908. if( sleepObj!=NULL ){
  43909. osCloseHandle(sleepObj);
  43910. sleepObj = NULL;
  43911. }
  43912. #endif
  43913. #ifndef SQLITE_OMIT_WAL
  43914. winBigLock = 0;
  43915. #endif
  43916. return SQLITE_OK;
  43917. }
  43918. #endif /* SQLITE_OS_WIN */
  43919. /************** End of os_win.c **********************************************/
  43920. /************** Begin file memdb.c *******************************************/
  43921. /*
  43922. ** 2016-09-07
  43923. **
  43924. ** The author disclaims copyright to this source code. In place of
  43925. ** a legal notice, here is a blessing:
  43926. **
  43927. ** May you do good and not evil.
  43928. ** May you find forgiveness for yourself and forgive others.
  43929. ** May you share freely, never taking more than you give.
  43930. **
  43931. ******************************************************************************
  43932. **
  43933. ** This file implements an in-memory VFS. A database is held as a contiguous
  43934. ** block of memory.
  43935. **
  43936. ** This file also implements interface sqlite3_serialize() and
  43937. ** sqlite3_deserialize().
  43938. */
  43939. /* #include "sqliteInt.h" */
  43940. #ifdef SQLITE_ENABLE_DESERIALIZE
  43941. /*
  43942. ** Forward declaration of objects used by this utility
  43943. */
  43944. typedef struct sqlite3_vfs MemVfs;
  43945. typedef struct MemFile MemFile;
  43946. /* Access to a lower-level VFS that (might) implement dynamic loading,
  43947. ** access to randomness, etc.
  43948. */
  43949. #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
  43950. /* An open file */
  43951. struct MemFile {
  43952. sqlite3_file base; /* IO methods */
  43953. sqlite3_int64 sz; /* Size of the file */
  43954. sqlite3_int64 szAlloc; /* Space allocated to aData */
  43955. sqlite3_int64 szMax; /* Maximum allowed size of the file */
  43956. unsigned char *aData; /* content of the file */
  43957. int nMmap; /* Number of memory mapped pages */
  43958. unsigned mFlags; /* Flags */
  43959. int eLock; /* Most recent lock against this file */
  43960. };
  43961. /*
  43962. ** Methods for MemFile
  43963. */
  43964. static int memdbClose(sqlite3_file*);
  43965. static int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  43966. static int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
  43967. static int memdbTruncate(sqlite3_file*, sqlite3_int64 size);
  43968. static int memdbSync(sqlite3_file*, int flags);
  43969. static int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  43970. static int memdbLock(sqlite3_file*, int);
  43971. /* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */
  43972. static int memdbFileControl(sqlite3_file*, int op, void *pArg);
  43973. /* static int memdbSectorSize(sqlite3_file*); // not used */
  43974. static int memdbDeviceCharacteristics(sqlite3_file*);
  43975. static int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  43976. static int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  43977. /*
  43978. ** Methods for MemVfs
  43979. */
  43980. static int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
  43981. /* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */
  43982. static int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *);
  43983. static int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
  43984. static void *memdbDlOpen(sqlite3_vfs*, const char *zFilename);
  43985. static void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
  43986. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
  43987. static void memdbDlClose(sqlite3_vfs*, void*);
  43988. static int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut);
  43989. static int memdbSleep(sqlite3_vfs*, int microseconds);
  43990. /* static int memdbCurrentTime(sqlite3_vfs*, double*); */
  43991. static int memdbGetLastError(sqlite3_vfs*, int, char *);
  43992. static int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
  43993. static sqlite3_vfs memdb_vfs = {
  43994. 2, /* iVersion */
  43995. 0, /* szOsFile (set when registered) */
  43996. 1024, /* mxPathname */
  43997. 0, /* pNext */
  43998. "memdb", /* zName */
  43999. 0, /* pAppData (set when registered) */
  44000. memdbOpen, /* xOpen */
  44001. 0, /* memdbDelete, */ /* xDelete */
  44002. memdbAccess, /* xAccess */
  44003. memdbFullPathname, /* xFullPathname */
  44004. memdbDlOpen, /* xDlOpen */
  44005. memdbDlError, /* xDlError */
  44006. memdbDlSym, /* xDlSym */
  44007. memdbDlClose, /* xDlClose */
  44008. memdbRandomness, /* xRandomness */
  44009. memdbSleep, /* xSleep */
  44010. 0, /* memdbCurrentTime, */ /* xCurrentTime */
  44011. memdbGetLastError, /* xGetLastError */
  44012. memdbCurrentTimeInt64 /* xCurrentTimeInt64 */
  44013. };
  44014. static const sqlite3_io_methods memdb_io_methods = {
  44015. 3, /* iVersion */
  44016. memdbClose, /* xClose */
  44017. memdbRead, /* xRead */
  44018. memdbWrite, /* xWrite */
  44019. memdbTruncate, /* xTruncate */
  44020. memdbSync, /* xSync */
  44021. memdbFileSize, /* xFileSize */
  44022. memdbLock, /* xLock */
  44023. memdbLock, /* xUnlock - same as xLock in this case */
  44024. 0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */
  44025. memdbFileControl, /* xFileControl */
  44026. 0, /* memdbSectorSize,*/ /* xSectorSize */
  44027. memdbDeviceCharacteristics, /* xDeviceCharacteristics */
  44028. 0, /* xShmMap */
  44029. 0, /* xShmLock */
  44030. 0, /* xShmBarrier */
  44031. 0, /* xShmUnmap */
  44032. memdbFetch, /* xFetch */
  44033. memdbUnfetch /* xUnfetch */
  44034. };
  44035. /*
  44036. ** Close an memdb-file.
  44037. **
  44038. ** The pData pointer is owned by the application, so there is nothing
  44039. ** to free.
  44040. */
  44041. static int memdbClose(sqlite3_file *pFile){
  44042. MemFile *p = (MemFile *)pFile;
  44043. if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) sqlite3_free(p->aData);
  44044. return SQLITE_OK;
  44045. }
  44046. /*
  44047. ** Read data from an memdb-file.
  44048. */
  44049. static int memdbRead(
  44050. sqlite3_file *pFile,
  44051. void *zBuf,
  44052. int iAmt,
  44053. sqlite_int64 iOfst
  44054. ){
  44055. MemFile *p = (MemFile *)pFile;
  44056. if( iOfst+iAmt>p->sz ){
  44057. memset(zBuf, 0, iAmt);
  44058. if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
  44059. return SQLITE_IOERR_SHORT_READ;
  44060. }
  44061. memcpy(zBuf, p->aData+iOfst, iAmt);
  44062. return SQLITE_OK;
  44063. }
  44064. /*
  44065. ** Try to enlarge the memory allocation to hold at least sz bytes
  44066. */
  44067. static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
  44068. unsigned char *pNew;
  44069. if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){
  44070. return SQLITE_FULL;
  44071. }
  44072. if( newSz>p->szMax ){
  44073. return SQLITE_FULL;
  44074. }
  44075. newSz *= 2;
  44076. if( newSz>p->szMax ) newSz = p->szMax;
  44077. pNew = sqlite3_realloc64(p->aData, newSz);
  44078. if( pNew==0 ) return SQLITE_NOMEM;
  44079. p->aData = pNew;
  44080. p->szAlloc = newSz;
  44081. return SQLITE_OK;
  44082. }
  44083. /*
  44084. ** Write data to an memdb-file.
  44085. */
  44086. static int memdbWrite(
  44087. sqlite3_file *pFile,
  44088. const void *z,
  44089. int iAmt,
  44090. sqlite_int64 iOfst
  44091. ){
  44092. MemFile *p = (MemFile *)pFile;
  44093. if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ) return SQLITE_READONLY;
  44094. if( iOfst+iAmt>p->sz ){
  44095. int rc;
  44096. if( iOfst+iAmt>p->szAlloc
  44097. && (rc = memdbEnlarge(p, iOfst+iAmt))!=SQLITE_OK
  44098. ){
  44099. return rc;
  44100. }
  44101. if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
  44102. p->sz = iOfst+iAmt;
  44103. }
  44104. memcpy(p->aData+iOfst, z, iAmt);
  44105. return SQLITE_OK;
  44106. }
  44107. /*
  44108. ** Truncate an memdb-file.
  44109. **
  44110. ** In rollback mode (which is always the case for memdb, as it does not
  44111. ** support WAL mode) the truncate() method is only used to reduce
  44112. ** the size of a file, never to increase the size.
  44113. */
  44114. static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
  44115. MemFile *p = (MemFile *)pFile;
  44116. if( NEVER(size>p->sz) ) return SQLITE_FULL;
  44117. p->sz = size;
  44118. return SQLITE_OK;
  44119. }
  44120. /*
  44121. ** Sync an memdb-file.
  44122. */
  44123. static int memdbSync(sqlite3_file *pFile, int flags){
  44124. return SQLITE_OK;
  44125. }
  44126. /*
  44127. ** Return the current file-size of an memdb-file.
  44128. */
  44129. static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  44130. MemFile *p = (MemFile *)pFile;
  44131. *pSize = p->sz;
  44132. return SQLITE_OK;
  44133. }
  44134. /*
  44135. ** Lock an memdb-file.
  44136. */
  44137. static int memdbLock(sqlite3_file *pFile, int eLock){
  44138. MemFile *p = (MemFile *)pFile;
  44139. if( eLock>SQLITE_LOCK_SHARED
  44140. && (p->mFlags & SQLITE_DESERIALIZE_READONLY)!=0
  44141. ){
  44142. return SQLITE_READONLY;
  44143. }
  44144. p->eLock = eLock;
  44145. return SQLITE_OK;
  44146. }
  44147. #if 0 /* Never used because memdbAccess() always returns false */
  44148. /*
  44149. ** Check if another file-handle holds a RESERVED lock on an memdb-file.
  44150. */
  44151. static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  44152. *pResOut = 0;
  44153. return SQLITE_OK;
  44154. }
  44155. #endif
  44156. /*
  44157. ** File control method. For custom operations on an memdb-file.
  44158. */
  44159. static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
  44160. MemFile *p = (MemFile *)pFile;
  44161. int rc = SQLITE_NOTFOUND;
  44162. if( op==SQLITE_FCNTL_VFSNAME ){
  44163. *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
  44164. rc = SQLITE_OK;
  44165. }
  44166. if( op==SQLITE_FCNTL_SIZE_LIMIT ){
  44167. sqlite3_int64 iLimit = *(sqlite3_int64*)pArg;
  44168. if( iLimit<p->sz ){
  44169. if( iLimit<0 ){
  44170. iLimit = p->szMax;
  44171. }else{
  44172. iLimit = p->sz;
  44173. }
  44174. }
  44175. p->szMax = iLimit;
  44176. *(sqlite3_int64*)pArg = iLimit;
  44177. rc = SQLITE_OK;
  44178. }
  44179. return rc;
  44180. }
  44181. #if 0 /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  44182. /*
  44183. ** Return the sector-size in bytes for an memdb-file.
  44184. */
  44185. static int memdbSectorSize(sqlite3_file *pFile){
  44186. return 1024;
  44187. }
  44188. #endif
  44189. /*
  44190. ** Return the device characteristic flags supported by an memdb-file.
  44191. */
  44192. static int memdbDeviceCharacteristics(sqlite3_file *pFile){
  44193. return SQLITE_IOCAP_ATOMIC |
  44194. SQLITE_IOCAP_POWERSAFE_OVERWRITE |
  44195. SQLITE_IOCAP_SAFE_APPEND |
  44196. SQLITE_IOCAP_SEQUENTIAL;
  44197. }
  44198. /* Fetch a page of a memory-mapped file */
  44199. static int memdbFetch(
  44200. sqlite3_file *pFile,
  44201. sqlite3_int64 iOfst,
  44202. int iAmt,
  44203. void **pp
  44204. ){
  44205. MemFile *p = (MemFile *)pFile;
  44206. if( iOfst+iAmt>p->sz ){
  44207. *pp = 0;
  44208. }else{
  44209. p->nMmap++;
  44210. *pp = (void*)(p->aData + iOfst);
  44211. }
  44212. return SQLITE_OK;
  44213. }
  44214. /* Release a memory-mapped page */
  44215. static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
  44216. MemFile *p = (MemFile *)pFile;
  44217. p->nMmap--;
  44218. return SQLITE_OK;
  44219. }
  44220. /*
  44221. ** Open an mem file handle.
  44222. */
  44223. static int memdbOpen(
  44224. sqlite3_vfs *pVfs,
  44225. const char *zName,
  44226. sqlite3_file *pFile,
  44227. int flags,
  44228. int *pOutFlags
  44229. ){
  44230. MemFile *p = (MemFile*)pFile;
  44231. if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
  44232. return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags);
  44233. }
  44234. memset(p, 0, sizeof(*p));
  44235. p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
  44236. assert( pOutFlags!=0 ); /* True because flags==SQLITE_OPEN_MAIN_DB */
  44237. *pOutFlags = flags | SQLITE_OPEN_MEMORY;
  44238. p->base.pMethods = &memdb_io_methods;
  44239. p->szMax = sqlite3GlobalConfig.mxMemdbSize;
  44240. return SQLITE_OK;
  44241. }
  44242. #if 0 /* Only used to delete rollback journals, master journals, and WAL
  44243. ** files, none of which exist in memdb. So this routine is never used */
  44244. /*
  44245. ** Delete the file located at zPath. If the dirSync argument is true,
  44246. ** ensure the file-system modifications are synced to disk before
  44247. ** returning.
  44248. */
  44249. static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  44250. return SQLITE_IOERR_DELETE;
  44251. }
  44252. #endif
  44253. /*
  44254. ** Test for access permissions. Return true if the requested permission
  44255. ** is available, or false otherwise.
  44256. **
  44257. ** With memdb, no files ever exist on disk. So always return false.
  44258. */
  44259. static int memdbAccess(
  44260. sqlite3_vfs *pVfs,
  44261. const char *zPath,
  44262. int flags,
  44263. int *pResOut
  44264. ){
  44265. *pResOut = 0;
  44266. return SQLITE_OK;
  44267. }
  44268. /*
  44269. ** Populate buffer zOut with the full canonical pathname corresponding
  44270. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  44271. ** of at least (INST_MAX_PATHNAME+1) bytes.
  44272. */
  44273. static int memdbFullPathname(
  44274. sqlite3_vfs *pVfs,
  44275. const char *zPath,
  44276. int nOut,
  44277. char *zOut
  44278. ){
  44279. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  44280. return SQLITE_OK;
  44281. }
  44282. /*
  44283. ** Open the dynamic library located at zPath and return a handle.
  44284. */
  44285. static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  44286. return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
  44287. }
  44288. /*
  44289. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  44290. ** utf-8 string describing the most recent error encountered associated
  44291. ** with dynamic libraries.
  44292. */
  44293. static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  44294. ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
  44295. }
  44296. /*
  44297. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  44298. */
  44299. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  44300. return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
  44301. }
  44302. /*
  44303. ** Close the dynamic library handle pHandle.
  44304. */
  44305. static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){
  44306. ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
  44307. }
  44308. /*
  44309. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  44310. ** random data.
  44311. */
  44312. static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  44313. return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
  44314. }
  44315. /*
  44316. ** Sleep for nMicro microseconds. Return the number of microseconds
  44317. ** actually slept.
  44318. */
  44319. static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){
  44320. return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
  44321. }
  44322. #if 0 /* Never used. Modern cores only call xCurrentTimeInt64() */
  44323. /*
  44324. ** Return the current time as a Julian Day number in *pTimeOut.
  44325. */
  44326. static int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  44327. return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
  44328. }
  44329. #endif
  44330. static int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  44331. return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
  44332. }
  44333. static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
  44334. return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
  44335. }
  44336. /*
  44337. ** Translate a database connection pointer and schema name into a
  44338. ** MemFile pointer.
  44339. */
  44340. static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){
  44341. MemFile *p = 0;
  44342. int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);
  44343. if( rc ) return 0;
  44344. if( p->base.pMethods!=&memdb_io_methods ) return 0;
  44345. return p;
  44346. }
  44347. /*
  44348. ** Return the serialization of a database
  44349. */
  44350. SQLITE_API unsigned char *sqlite3_serialize(
  44351. sqlite3 *db, /* The database connection */
  44352. const char *zSchema, /* Which database within the connection */
  44353. sqlite3_int64 *piSize, /* Write size here, if not NULL */
  44354. unsigned int mFlags /* Maybe SQLITE_SERIALIZE_NOCOPY */
  44355. ){
  44356. MemFile *p;
  44357. int iDb;
  44358. Btree *pBt;
  44359. sqlite3_int64 sz;
  44360. int szPage = 0;
  44361. sqlite3_stmt *pStmt = 0;
  44362. unsigned char *pOut;
  44363. char *zSql;
  44364. int rc;
  44365. #ifdef SQLITE_ENABLE_API_ARMOR
  44366. if( !sqlite3SafetyCheckOk(db) ){
  44367. (void)SQLITE_MISUSE_BKPT;
  44368. return 0;
  44369. }
  44370. #endif
  44371. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  44372. p = memdbFromDbSchema(db, zSchema);
  44373. iDb = sqlite3FindDbName(db, zSchema);
  44374. if( piSize ) *piSize = -1;
  44375. if( iDb<0 ) return 0;
  44376. if( p ){
  44377. if( piSize ) *piSize = p->sz;
  44378. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  44379. pOut = p->aData;
  44380. }else{
  44381. pOut = sqlite3_malloc64( p->sz );
  44382. if( pOut ) memcpy(pOut, p->aData, p->sz);
  44383. }
  44384. return pOut;
  44385. }
  44386. pBt = db->aDb[iDb].pBt;
  44387. if( pBt==0 ) return 0;
  44388. szPage = sqlite3BtreeGetPageSize(pBt);
  44389. zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
  44390. rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
  44391. sqlite3_free(zSql);
  44392. if( rc ) return 0;
  44393. rc = sqlite3_step(pStmt);
  44394. if( rc!=SQLITE_ROW ){
  44395. pOut = 0;
  44396. }else{
  44397. sz = sqlite3_column_int64(pStmt, 0)*szPage;
  44398. if( piSize ) *piSize = sz;
  44399. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  44400. pOut = 0;
  44401. }else{
  44402. pOut = sqlite3_malloc64( sz );
  44403. if( pOut ){
  44404. int nPage = sqlite3_column_int(pStmt, 0);
  44405. Pager *pPager = sqlite3BtreePager(pBt);
  44406. int pgno;
  44407. for(pgno=1; pgno<=nPage; pgno++){
  44408. DbPage *pPage = 0;
  44409. unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
  44410. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0);
  44411. if( rc==SQLITE_OK ){
  44412. memcpy(pTo, sqlite3PagerGetData(pPage), szPage);
  44413. }else{
  44414. memset(pTo, 0, szPage);
  44415. }
  44416. sqlite3PagerUnref(pPage);
  44417. }
  44418. }
  44419. }
  44420. }
  44421. sqlite3_finalize(pStmt);
  44422. return pOut;
  44423. }
  44424. /* Convert zSchema to a MemDB and initialize its content.
  44425. */
  44426. SQLITE_API int sqlite3_deserialize(
  44427. sqlite3 *db, /* The database connection */
  44428. const char *zSchema, /* Which DB to reopen with the deserialization */
  44429. unsigned char *pData, /* The serialized database content */
  44430. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  44431. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  44432. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  44433. ){
  44434. MemFile *p;
  44435. char *zSql;
  44436. sqlite3_stmt *pStmt = 0;
  44437. int rc;
  44438. int iDb;
  44439. #ifdef SQLITE_ENABLE_API_ARMOR
  44440. if( !sqlite3SafetyCheckOk(db) ){
  44441. return SQLITE_MISUSE_BKPT;
  44442. }
  44443. if( szDb<0 ) return SQLITE_MISUSE_BKPT;
  44444. if( szBuf<0 ) return SQLITE_MISUSE_BKPT;
  44445. #endif
  44446. sqlite3_mutex_enter(db->mutex);
  44447. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  44448. iDb = sqlite3FindDbName(db, zSchema);
  44449. if( iDb<0 ){
  44450. rc = SQLITE_ERROR;
  44451. goto end_deserialize;
  44452. }
  44453. zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema);
  44454. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  44455. sqlite3_free(zSql);
  44456. if( rc ) goto end_deserialize;
  44457. db->init.iDb = (u8)iDb;
  44458. db->init.reopenMemdb = 1;
  44459. rc = sqlite3_step(pStmt);
  44460. db->init.reopenMemdb = 0;
  44461. if( rc!=SQLITE_DONE ){
  44462. rc = SQLITE_ERROR;
  44463. goto end_deserialize;
  44464. }
  44465. p = memdbFromDbSchema(db, zSchema);
  44466. if( p==0 ){
  44467. rc = SQLITE_ERROR;
  44468. }else{
  44469. p->aData = pData;
  44470. p->sz = szDb;
  44471. p->szAlloc = szBuf;
  44472. p->szMax = szBuf;
  44473. if( p->szMax<sqlite3GlobalConfig.mxMemdbSize ){
  44474. p->szMax = sqlite3GlobalConfig.mxMemdbSize;
  44475. }
  44476. p->mFlags = mFlags;
  44477. rc = SQLITE_OK;
  44478. }
  44479. end_deserialize:
  44480. sqlite3_finalize(pStmt);
  44481. sqlite3_mutex_leave(db->mutex);
  44482. return rc;
  44483. }
  44484. /*
  44485. ** This routine is called when the extension is loaded.
  44486. ** Register the new VFS.
  44487. */
  44488. SQLITE_PRIVATE int sqlite3MemdbInit(void){
  44489. sqlite3_vfs *pLower = sqlite3_vfs_find(0);
  44490. int sz = pLower->szOsFile;
  44491. memdb_vfs.pAppData = pLower;
  44492. /* In all known configurations of SQLite, the size of a default
  44493. ** sqlite3_file is greater than the size of a memdb sqlite3_file.
  44494. ** Should that ever change, remove the following NEVER() */
  44495. if( NEVER(sz<sizeof(MemFile)) ) sz = sizeof(MemFile);
  44496. memdb_vfs.szOsFile = sz;
  44497. return sqlite3_vfs_register(&memdb_vfs, 0);
  44498. }
  44499. #endif /* SQLITE_ENABLE_DESERIALIZE */
  44500. /************** End of memdb.c ***********************************************/
  44501. /************** Begin file bitvec.c ******************************************/
  44502. /*
  44503. ** 2008 February 16
  44504. **
  44505. ** The author disclaims copyright to this source code. In place of
  44506. ** a legal notice, here is a blessing:
  44507. **
  44508. ** May you do good and not evil.
  44509. ** May you find forgiveness for yourself and forgive others.
  44510. ** May you share freely, never taking more than you give.
  44511. **
  44512. *************************************************************************
  44513. ** This file implements an object that represents a fixed-length
  44514. ** bitmap. Bits are numbered starting with 1.
  44515. **
  44516. ** A bitmap is used to record which pages of a database file have been
  44517. ** journalled during a transaction, or which pages have the "dont-write"
  44518. ** property. Usually only a few pages are meet either condition.
  44519. ** So the bitmap is usually sparse and has low cardinality.
  44520. ** But sometimes (for example when during a DROP of a large table) most
  44521. ** or all of the pages in a database can get journalled. In those cases,
  44522. ** the bitmap becomes dense with high cardinality. The algorithm needs
  44523. ** to handle both cases well.
  44524. **
  44525. ** The size of the bitmap is fixed when the object is created.
  44526. **
  44527. ** All bits are clear when the bitmap is created. Individual bits
  44528. ** may be set or cleared one at a time.
  44529. **
  44530. ** Test operations are about 100 times more common that set operations.
  44531. ** Clear operations are exceedingly rare. There are usually between
  44532. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  44533. ** sometimes grow into tens of thousands or larger. The size of the
  44534. ** Bitvec object is the number of pages in the database file at the
  44535. ** start of a transaction, and is thus usually less than a few thousand,
  44536. ** but can be as large as 2 billion for a really big database.
  44537. */
  44538. /* #include "sqliteInt.h" */
  44539. /* Size of the Bitvec structure in bytes. */
  44540. #define BITVEC_SZ 512
  44541. /* Round the union size down to the nearest pointer boundary, since that's how
  44542. ** it will be aligned within the Bitvec struct. */
  44543. #define BITVEC_USIZE \
  44544. (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  44545. /* Type of the array "element" for the bitmap representation.
  44546. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  44547. ** Setting this to the "natural word" size of your CPU may improve
  44548. ** performance. */
  44549. #define BITVEC_TELEM u8
  44550. /* Size, in bits, of the bitmap element. */
  44551. #define BITVEC_SZELEM 8
  44552. /* Number of elements in a bitmap array. */
  44553. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  44554. /* Number of bits in the bitmap array. */
  44555. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  44556. /* Number of u32 values in hash table. */
  44557. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  44558. /* Maximum number of entries in hash table before
  44559. ** sub-dividing and re-hashing. */
  44560. #define BITVEC_MXHASH (BITVEC_NINT/2)
  44561. /* Hashing function for the aHash representation.
  44562. ** Empirical testing showed that the *37 multiplier
  44563. ** (an arbitrary prime)in the hash function provided
  44564. ** no fewer collisions than the no-op *1. */
  44565. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  44566. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  44567. /*
  44568. ** A bitmap is an instance of the following structure.
  44569. **
  44570. ** This bitmap records the existence of zero or more bits
  44571. ** with values between 1 and iSize, inclusive.
  44572. **
  44573. ** There are three possible representations of the bitmap.
  44574. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  44575. ** bitmap. The least significant bit is bit 1.
  44576. **
  44577. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  44578. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  44579. **
  44580. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  44581. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  44582. ** handles up to iDivisor separate values of i. apSub[0] holds
  44583. ** values between 1 and iDivisor. apSub[1] holds values between
  44584. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  44585. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  44586. ** to hold deal with values between 1 and iDivisor.
  44587. */
  44588. struct Bitvec {
  44589. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  44590. u32 nSet; /* Number of bits that are set - only valid for aHash
  44591. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  44592. ** this would be 125. */
  44593. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  44594. /* Should >=0 for apSub element. */
  44595. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  44596. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  44597. union {
  44598. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  44599. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  44600. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  44601. } u;
  44602. };
  44603. /*
  44604. ** Create a new bitmap object able to handle bits between 0 and iSize,
  44605. ** inclusive. Return a pointer to the new object. Return NULL if
  44606. ** malloc fails.
  44607. */
  44608. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  44609. Bitvec *p;
  44610. assert( sizeof(*p)==BITVEC_SZ );
  44611. p = sqlite3MallocZero( sizeof(*p) );
  44612. if( p ){
  44613. p->iSize = iSize;
  44614. }
  44615. return p;
  44616. }
  44617. /*
  44618. ** Check to see if the i-th bit is set. Return true or false.
  44619. ** If p is NULL (if the bitmap has not been created) or if
  44620. ** i is out of range, then return false.
  44621. */
  44622. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  44623. assert( p!=0 );
  44624. i--;
  44625. if( i>=p->iSize ) return 0;
  44626. while( p->iDivisor ){
  44627. u32 bin = i/p->iDivisor;
  44628. i = i%p->iDivisor;
  44629. p = p->u.apSub[bin];
  44630. if (!p) {
  44631. return 0;
  44632. }
  44633. }
  44634. if( p->iSize<=BITVEC_NBIT ){
  44635. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  44636. } else{
  44637. u32 h = BITVEC_HASH(i++);
  44638. while( p->u.aHash[h] ){
  44639. if( p->u.aHash[h]==i ) return 1;
  44640. h = (h+1) % BITVEC_NINT;
  44641. }
  44642. return 0;
  44643. }
  44644. }
  44645. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  44646. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  44647. }
  44648. /*
  44649. ** Set the i-th bit. Return 0 on success and an error code if
  44650. ** anything goes wrong.
  44651. **
  44652. ** This routine might cause sub-bitmaps to be allocated. Failing
  44653. ** to get the memory needed to hold the sub-bitmap is the only
  44654. ** that can go wrong with an insert, assuming p and i are valid.
  44655. **
  44656. ** The calling function must ensure that p is a valid Bitvec object
  44657. ** and that the value for "i" is within range of the Bitvec object.
  44658. ** Otherwise the behavior is undefined.
  44659. */
  44660. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  44661. u32 h;
  44662. if( p==0 ) return SQLITE_OK;
  44663. assert( i>0 );
  44664. assert( i<=p->iSize );
  44665. i--;
  44666. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  44667. u32 bin = i/p->iDivisor;
  44668. i = i%p->iDivisor;
  44669. if( p->u.apSub[bin]==0 ){
  44670. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  44671. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
  44672. }
  44673. p = p->u.apSub[bin];
  44674. }
  44675. if( p->iSize<=BITVEC_NBIT ){
  44676. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  44677. return SQLITE_OK;
  44678. }
  44679. h = BITVEC_HASH(i++);
  44680. /* if there wasn't a hash collision, and this doesn't */
  44681. /* completely fill the hash, then just add it without */
  44682. /* worring about sub-dividing and re-hashing. */
  44683. if( !p->u.aHash[h] ){
  44684. if (p->nSet<(BITVEC_NINT-1)) {
  44685. goto bitvec_set_end;
  44686. } else {
  44687. goto bitvec_set_rehash;
  44688. }
  44689. }
  44690. /* there was a collision, check to see if it's already */
  44691. /* in hash, if not, try to find a spot for it */
  44692. do {
  44693. if( p->u.aHash[h]==i ) return SQLITE_OK;
  44694. h++;
  44695. if( h>=BITVEC_NINT ) h = 0;
  44696. } while( p->u.aHash[h] );
  44697. /* we didn't find it in the hash. h points to the first */
  44698. /* available free spot. check to see if this is going to */
  44699. /* make our hash too "full". */
  44700. bitvec_set_rehash:
  44701. if( p->nSet>=BITVEC_MXHASH ){
  44702. unsigned int j;
  44703. int rc;
  44704. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  44705. if( aiValues==0 ){
  44706. return SQLITE_NOMEM_BKPT;
  44707. }else{
  44708. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  44709. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  44710. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  44711. rc = sqlite3BitvecSet(p, i);
  44712. for(j=0; j<BITVEC_NINT; j++){
  44713. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  44714. }
  44715. sqlite3StackFree(0, aiValues);
  44716. return rc;
  44717. }
  44718. }
  44719. bitvec_set_end:
  44720. p->nSet++;
  44721. p->u.aHash[h] = i;
  44722. return SQLITE_OK;
  44723. }
  44724. /*
  44725. ** Clear the i-th bit.
  44726. **
  44727. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  44728. ** that BitvecClear can use to rebuilt its hash table.
  44729. */
  44730. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  44731. if( p==0 ) return;
  44732. assert( i>0 );
  44733. i--;
  44734. while( p->iDivisor ){
  44735. u32 bin = i/p->iDivisor;
  44736. i = i%p->iDivisor;
  44737. p = p->u.apSub[bin];
  44738. if (!p) {
  44739. return;
  44740. }
  44741. }
  44742. if( p->iSize<=BITVEC_NBIT ){
  44743. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  44744. }else{
  44745. unsigned int j;
  44746. u32 *aiValues = pBuf;
  44747. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  44748. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  44749. p->nSet = 0;
  44750. for(j=0; j<BITVEC_NINT; j++){
  44751. if( aiValues[j] && aiValues[j]!=(i+1) ){
  44752. u32 h = BITVEC_HASH(aiValues[j]-1);
  44753. p->nSet++;
  44754. while( p->u.aHash[h] ){
  44755. h++;
  44756. if( h>=BITVEC_NINT ) h = 0;
  44757. }
  44758. p->u.aHash[h] = aiValues[j];
  44759. }
  44760. }
  44761. }
  44762. }
  44763. /*
  44764. ** Destroy a bitmap object. Reclaim all memory used.
  44765. */
  44766. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  44767. if( p==0 ) return;
  44768. if( p->iDivisor ){
  44769. unsigned int i;
  44770. for(i=0; i<BITVEC_NPTR; i++){
  44771. sqlite3BitvecDestroy(p->u.apSub[i]);
  44772. }
  44773. }
  44774. sqlite3_free(p);
  44775. }
  44776. /*
  44777. ** Return the value of the iSize parameter specified when Bitvec *p
  44778. ** was created.
  44779. */
  44780. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  44781. return p->iSize;
  44782. }
  44783. #ifndef SQLITE_UNTESTABLE
  44784. /*
  44785. ** Let V[] be an array of unsigned characters sufficient to hold
  44786. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  44787. ** Then the following macros can be used to set, clear, or test
  44788. ** individual bits within V.
  44789. */
  44790. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  44791. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  44792. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  44793. /*
  44794. ** This routine runs an extensive test of the Bitvec code.
  44795. **
  44796. ** The input is an array of integers that acts as a program
  44797. ** to test the Bitvec. The integers are opcodes followed
  44798. ** by 0, 1, or 3 operands, depending on the opcode. Another
  44799. ** opcode follows immediately after the last operand.
  44800. **
  44801. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  44802. ** "halt" opcode and causes the test to end.
  44803. **
  44804. ** 0 Halt and return the number of errors
  44805. ** 1 N S X Set N bits beginning with S and incrementing by X
  44806. ** 2 N S X Clear N bits beginning with S and incrementing by X
  44807. ** 3 N Set N randomly chosen bits
  44808. ** 4 N Clear N randomly chosen bits
  44809. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  44810. **
  44811. ** The opcodes 1 through 4 perform set and clear operations are performed
  44812. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  44813. ** Opcode 5 works on the linear array only, not on the Bitvec.
  44814. ** Opcode 5 is used to deliberately induce a fault in order to
  44815. ** confirm that error detection works.
  44816. **
  44817. ** At the conclusion of the test the linear array is compared
  44818. ** against the Bitvec object. If there are any differences,
  44819. ** an error is returned. If they are the same, zero is returned.
  44820. **
  44821. ** If a memory allocation error occurs, return -1.
  44822. */
  44823. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  44824. Bitvec *pBitvec = 0;
  44825. unsigned char *pV = 0;
  44826. int rc = -1;
  44827. int i, nx, pc, op;
  44828. void *pTmpSpace;
  44829. /* Allocate the Bitvec to be tested and a linear array of
  44830. ** bits to act as the reference */
  44831. pBitvec = sqlite3BitvecCreate( sz );
  44832. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  44833. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  44834. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  44835. /* NULL pBitvec tests */
  44836. sqlite3BitvecSet(0, 1);
  44837. sqlite3BitvecClear(0, 1, pTmpSpace);
  44838. /* Run the program */
  44839. pc = 0;
  44840. while( (op = aOp[pc])!=0 ){
  44841. switch( op ){
  44842. case 1:
  44843. case 2:
  44844. case 5: {
  44845. nx = 4;
  44846. i = aOp[pc+2] - 1;
  44847. aOp[pc+2] += aOp[pc+3];
  44848. break;
  44849. }
  44850. case 3:
  44851. case 4:
  44852. default: {
  44853. nx = 2;
  44854. sqlite3_randomness(sizeof(i), &i);
  44855. break;
  44856. }
  44857. }
  44858. if( (--aOp[pc+1]) > 0 ) nx = 0;
  44859. pc += nx;
  44860. i = (i & 0x7fffffff)%sz;
  44861. if( (op & 1)!=0 ){
  44862. SETBIT(pV, (i+1));
  44863. if( op!=5 ){
  44864. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  44865. }
  44866. }else{
  44867. CLEARBIT(pV, (i+1));
  44868. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  44869. }
  44870. }
  44871. /* Test to make sure the linear array exactly matches the
  44872. ** Bitvec object. Start with the assumption that they do
  44873. ** match (rc==0). Change rc to non-zero if a discrepancy
  44874. ** is found.
  44875. */
  44876. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  44877. + sqlite3BitvecTest(pBitvec, 0)
  44878. + (sqlite3BitvecSize(pBitvec) - sz);
  44879. for(i=1; i<=sz; i++){
  44880. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  44881. rc = i;
  44882. break;
  44883. }
  44884. }
  44885. /* Free allocated structure */
  44886. bitvec_end:
  44887. sqlite3_free(pTmpSpace);
  44888. sqlite3_free(pV);
  44889. sqlite3BitvecDestroy(pBitvec);
  44890. return rc;
  44891. }
  44892. #endif /* SQLITE_UNTESTABLE */
  44893. /************** End of bitvec.c **********************************************/
  44894. /************** Begin file pcache.c ******************************************/
  44895. /*
  44896. ** 2008 August 05
  44897. **
  44898. ** The author disclaims copyright to this source code. In place of
  44899. ** a legal notice, here is a blessing:
  44900. **
  44901. ** May you do good and not evil.
  44902. ** May you find forgiveness for yourself and forgive others.
  44903. ** May you share freely, never taking more than you give.
  44904. **
  44905. *************************************************************************
  44906. ** This file implements that page cache.
  44907. */
  44908. /* #include "sqliteInt.h" */
  44909. /*
  44910. ** A complete page cache is an instance of this structure. Every
  44911. ** entry in the cache holds a single page of the database file. The
  44912. ** btree layer only operates on the cached copy of the database pages.
  44913. **
  44914. ** A page cache entry is "clean" if it exactly matches what is currently
  44915. ** on disk. A page is "dirty" if it has been modified and needs to be
  44916. ** persisted to disk.
  44917. **
  44918. ** pDirty, pDirtyTail, pSynced:
  44919. ** All dirty pages are linked into the doubly linked list using
  44920. ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
  44921. ** such that p was added to the list more recently than p->pDirtyNext.
  44922. ** PCache.pDirty points to the first (newest) element in the list and
  44923. ** pDirtyTail to the last (oldest).
  44924. **
  44925. ** The PCache.pSynced variable is used to optimize searching for a dirty
  44926. ** page to eject from the cache mid-transaction. It is better to eject
  44927. ** a page that does not require a journal sync than one that does.
  44928. ** Therefore, pSynced is maintained so that it *almost* always points
  44929. ** to either the oldest page in the pDirty/pDirtyTail list that has a
  44930. ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
  44931. ** (so that the right page to eject can be found by following pDirtyPrev
  44932. ** pointers).
  44933. */
  44934. struct PCache {
  44935. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  44936. PgHdr *pSynced; /* Last synced page in dirty page list */
  44937. int nRefSum; /* Sum of ref counts over all pages */
  44938. int szCache; /* Configured cache size */
  44939. int szSpill; /* Size before spilling occurs */
  44940. int szPage; /* Size of every page in this cache */
  44941. int szExtra; /* Size of extra space for each page */
  44942. u8 bPurgeable; /* True if pages are on backing store */
  44943. u8 eCreate; /* eCreate value for for xFetch() */
  44944. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  44945. void *pStress; /* Argument to xStress */
  44946. sqlite3_pcache *pCache; /* Pluggable cache module */
  44947. };
  44948. /********************************** Test and Debug Logic **********************/
  44949. /*
  44950. ** Debug tracing macros. Enable by by changing the "0" to "1" and
  44951. ** recompiling.
  44952. **
  44953. ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
  44954. ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
  44955. ** is displayed for many operations, resulting in a lot of output.
  44956. */
  44957. #if defined(SQLITE_DEBUG) && 0
  44958. int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
  44959. int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
  44960. # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
  44961. void pcacheDump(PCache *pCache){
  44962. int N;
  44963. int i, j;
  44964. sqlite3_pcache_page *pLower;
  44965. PgHdr *pPg;
  44966. unsigned char *a;
  44967. if( sqlite3PcacheTrace<2 ) return;
  44968. if( pCache->pCache==0 ) return;
  44969. N = sqlite3PcachePagecount(pCache);
  44970. if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
  44971. for(i=1; i<=N; i++){
  44972. pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
  44973. if( pLower==0 ) continue;
  44974. pPg = (PgHdr*)pLower->pExtra;
  44975. printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
  44976. a = (unsigned char *)pLower->pBuf;
  44977. for(j=0; j<12; j++) printf("%02x", a[j]);
  44978. printf("\n");
  44979. if( pPg->pPage==0 ){
  44980. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
  44981. }
  44982. }
  44983. }
  44984. #else
  44985. # define pcacheTrace(X)
  44986. # define pcacheDump(X)
  44987. #endif
  44988. /*
  44989. ** Check invariants on a PgHdr entry. Return true if everything is OK.
  44990. ** Return false if any invariant is violated.
  44991. **
  44992. ** This routine is for use inside of assert() statements only. For
  44993. ** example:
  44994. **
  44995. ** assert( sqlite3PcachePageSanity(pPg) );
  44996. */
  44997. #ifdef SQLITE_DEBUG
  44998. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
  44999. PCache *pCache;
  45000. assert( pPg!=0 );
  45001. assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
  45002. pCache = pPg->pCache;
  45003. assert( pCache!=0 ); /* Every page has an associated PCache */
  45004. if( pPg->flags & PGHDR_CLEAN ){
  45005. assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
  45006. assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
  45007. assert( pCache->pDirtyTail!=pPg );
  45008. }
  45009. /* WRITEABLE pages must also be DIRTY */
  45010. if( pPg->flags & PGHDR_WRITEABLE ){
  45011. assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
  45012. }
  45013. /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
  45014. ** for example, when using the sqlite3PagerDontWrite() optimization:
  45015. ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
  45016. ** (2) Page X moved to freelist, WRITEABLE is cleared
  45017. ** (3) Page X reused, WRITEABLE is set again
  45018. ** If NEED_SYNC had been cleared in step 2, then it would not be reset
  45019. ** in step 3, and page might be written into the database without first
  45020. ** syncing the rollback journal, which might cause corruption on a power
  45021. ** loss.
  45022. **
  45023. ** Another example is when the database page size is smaller than the
  45024. ** disk sector size. When any page of a sector is journalled, all pages
  45025. ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
  45026. ** in case they are later modified, since all pages in the same sector
  45027. ** must be journalled and synced before any of those pages can be safely
  45028. ** written.
  45029. */
  45030. return 1;
  45031. }
  45032. #endif /* SQLITE_DEBUG */
  45033. /********************************** Linked List Management ********************/
  45034. /* Allowed values for second argument to pcacheManageDirtyList() */
  45035. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  45036. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  45037. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  45038. /*
  45039. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  45040. ** argument determines what operation to do. The 0x01 bit means first
  45041. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  45042. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  45043. */
  45044. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  45045. PCache *p = pPage->pCache;
  45046. pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
  45047. addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
  45048. pPage->pgno));
  45049. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  45050. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  45051. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  45052. /* Update the PCache1.pSynced variable if necessary. */
  45053. if( p->pSynced==pPage ){
  45054. p->pSynced = pPage->pDirtyPrev;
  45055. }
  45056. if( pPage->pDirtyNext ){
  45057. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  45058. }else{
  45059. assert( pPage==p->pDirtyTail );
  45060. p->pDirtyTail = pPage->pDirtyPrev;
  45061. }
  45062. if( pPage->pDirtyPrev ){
  45063. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  45064. }else{
  45065. /* If there are now no dirty pages in the cache, set eCreate to 2.
  45066. ** This is an optimization that allows sqlite3PcacheFetch() to skip
  45067. ** searching for a dirty page to eject from the cache when it might
  45068. ** otherwise have to. */
  45069. assert( pPage==p->pDirty );
  45070. p->pDirty = pPage->pDirtyNext;
  45071. assert( p->bPurgeable || p->eCreate==2 );
  45072. if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
  45073. assert( p->bPurgeable==0 || p->eCreate==1 );
  45074. p->eCreate = 2;
  45075. }
  45076. }
  45077. }
  45078. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  45079. pPage->pDirtyPrev = 0;
  45080. pPage->pDirtyNext = p->pDirty;
  45081. if( pPage->pDirtyNext ){
  45082. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  45083. pPage->pDirtyNext->pDirtyPrev = pPage;
  45084. }else{
  45085. p->pDirtyTail = pPage;
  45086. if( p->bPurgeable ){
  45087. assert( p->eCreate==2 );
  45088. p->eCreate = 1;
  45089. }
  45090. }
  45091. p->pDirty = pPage;
  45092. /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
  45093. ** pSynced to point to it. Checking the NEED_SYNC flag is an
  45094. ** optimization, as if pSynced points to a page with the NEED_SYNC
  45095. ** flag set sqlite3PcacheFetchStress() searches through all newer
  45096. ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
  45097. if( !p->pSynced
  45098. && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
  45099. ){
  45100. p->pSynced = pPage;
  45101. }
  45102. }
  45103. pcacheDump(p);
  45104. }
  45105. /*
  45106. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  45107. ** being used for an in-memory database, this function is a no-op.
  45108. */
  45109. static void pcacheUnpin(PgHdr *p){
  45110. if( p->pCache->bPurgeable ){
  45111. pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
  45112. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  45113. pcacheDump(p->pCache);
  45114. }
  45115. }
  45116. /*
  45117. ** Compute the number of pages of cache requested. p->szCache is the
  45118. ** cache size requested by the "PRAGMA cache_size" statement.
  45119. */
  45120. static int numberOfCachePages(PCache *p){
  45121. if( p->szCache>=0 ){
  45122. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  45123. ** suggested cache size is set to N. */
  45124. return p->szCache;
  45125. }else{
  45126. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  45127. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  45128. ** bytes of memory. */
  45129. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  45130. }
  45131. }
  45132. /*************************************************** General Interfaces ******
  45133. **
  45134. ** Initialize and shutdown the page cache subsystem. Neither of these
  45135. ** functions are threadsafe.
  45136. */
  45137. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  45138. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  45139. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  45140. ** built-in default page cache is used instead of the application defined
  45141. ** page cache. */
  45142. sqlite3PCacheSetDefault();
  45143. }
  45144. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  45145. }
  45146. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  45147. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  45148. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  45149. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  45150. }
  45151. }
  45152. /*
  45153. ** Return the size in bytes of a PCache object.
  45154. */
  45155. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  45156. /*
  45157. ** Create a new PCache object. Storage space to hold the object
  45158. ** has already been allocated and is passed in as the p pointer.
  45159. ** The caller discovers how much space needs to be allocated by
  45160. ** calling sqlite3PcacheSize().
  45161. **
  45162. ** szExtra is some extra space allocated for each page. The first
  45163. ** 8 bytes of the extra space will be zeroed as the page is allocated,
  45164. ** but remaining content will be uninitialized. Though it is opaque
  45165. ** to this module, the extra space really ends up being the MemPage
  45166. ** structure in the pager.
  45167. */
  45168. SQLITE_PRIVATE int sqlite3PcacheOpen(
  45169. int szPage, /* Size of every page */
  45170. int szExtra, /* Extra space associated with each page */
  45171. int bPurgeable, /* True if pages are on backing store */
  45172. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  45173. void *pStress, /* Argument to xStress */
  45174. PCache *p /* Preallocated space for the PCache */
  45175. ){
  45176. memset(p, 0, sizeof(PCache));
  45177. p->szPage = 1;
  45178. p->szExtra = szExtra;
  45179. assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
  45180. p->bPurgeable = bPurgeable;
  45181. p->eCreate = 2;
  45182. p->xStress = xStress;
  45183. p->pStress = pStress;
  45184. p->szCache = 100;
  45185. p->szSpill = 1;
  45186. pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
  45187. return sqlite3PcacheSetPageSize(p, szPage);
  45188. }
  45189. /*
  45190. ** Change the page size for PCache object. The caller must ensure that there
  45191. ** are no outstanding page references when this function is called.
  45192. */
  45193. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  45194. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  45195. if( pCache->szPage ){
  45196. sqlite3_pcache *pNew;
  45197. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  45198. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  45199. pCache->bPurgeable
  45200. );
  45201. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  45202. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  45203. if( pCache->pCache ){
  45204. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  45205. }
  45206. pCache->pCache = pNew;
  45207. pCache->szPage = szPage;
  45208. pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
  45209. }
  45210. return SQLITE_OK;
  45211. }
  45212. /*
  45213. ** Try to obtain a page from the cache.
  45214. **
  45215. ** This routine returns a pointer to an sqlite3_pcache_page object if
  45216. ** such an object is already in cache, or if a new one is created.
  45217. ** This routine returns a NULL pointer if the object was not in cache
  45218. ** and could not be created.
  45219. **
  45220. ** The createFlags should be 0 to check for existing pages and should
  45221. ** be 3 (not 1, but 3) to try to create a new page.
  45222. **
  45223. ** If the createFlag is 0, then NULL is always returned if the page
  45224. ** is not already in the cache. If createFlag is 1, then a new page
  45225. ** is created only if that can be done without spilling dirty pages
  45226. ** and without exceeding the cache size limit.
  45227. **
  45228. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  45229. ** initialize the sqlite3_pcache_page object and convert it into a
  45230. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  45231. ** routines are split this way for performance reasons. When separated
  45232. ** they can both (usually) operate without having to push values to
  45233. ** the stack on entry and pop them back off on exit, which saves a
  45234. ** lot of pushing and popping.
  45235. */
  45236. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  45237. PCache *pCache, /* Obtain the page from this cache */
  45238. Pgno pgno, /* Page number to obtain */
  45239. int createFlag /* If true, create page if it does not exist already */
  45240. ){
  45241. int eCreate;
  45242. sqlite3_pcache_page *pRes;
  45243. assert( pCache!=0 );
  45244. assert( pCache->pCache!=0 );
  45245. assert( createFlag==3 || createFlag==0 );
  45246. assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
  45247. /* eCreate defines what to do if the page does not exist.
  45248. ** 0 Do not allocate a new page. (createFlag==0)
  45249. ** 1 Allocate a new page if doing so is inexpensive.
  45250. ** (createFlag==1 AND bPurgeable AND pDirty)
  45251. ** 2 Allocate a new page even it doing so is difficult.
  45252. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  45253. */
  45254. eCreate = createFlag & pCache->eCreate;
  45255. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  45256. assert( createFlag==0 || pCache->eCreate==eCreate );
  45257. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  45258. pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  45259. pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
  45260. createFlag?" create":"",pRes));
  45261. return pRes;
  45262. }
  45263. /*
  45264. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  45265. ** page because no clean pages are available for reuse and the cache
  45266. ** size limit has been reached, then this routine can be invoked to
  45267. ** try harder to allocate a page. This routine might invoke the stress
  45268. ** callback to spill dirty pages to the journal. It will then try to
  45269. ** allocate the new page and will only fail to allocate a new page on
  45270. ** an OOM error.
  45271. **
  45272. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  45273. */
  45274. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  45275. PCache *pCache, /* Obtain the page from this cache */
  45276. Pgno pgno, /* Page number to obtain */
  45277. sqlite3_pcache_page **ppPage /* Write result here */
  45278. ){
  45279. PgHdr *pPg;
  45280. if( pCache->eCreate==2 ) return 0;
  45281. if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
  45282. /* Find a dirty page to write-out and recycle. First try to find a
  45283. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  45284. ** cleared), but if that is not possible settle for any other
  45285. ** unreferenced dirty page.
  45286. **
  45287. ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
  45288. ** flag is currently referenced, then the following may leave pSynced
  45289. ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
  45290. ** cleared). This is Ok, as pSynced is just an optimization. */
  45291. for(pPg=pCache->pSynced;
  45292. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  45293. pPg=pPg->pDirtyPrev
  45294. );
  45295. pCache->pSynced = pPg;
  45296. if( !pPg ){
  45297. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  45298. }
  45299. if( pPg ){
  45300. int rc;
  45301. #ifdef SQLITE_LOG_CACHE_SPILL
  45302. sqlite3_log(SQLITE_FULL,
  45303. "spill page %d making room for %d - cache used: %d/%d",
  45304. pPg->pgno, pgno,
  45305. sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
  45306. numberOfCachePages(pCache));
  45307. #endif
  45308. pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
  45309. rc = pCache->xStress(pCache->pStress, pPg);
  45310. pcacheDump(pCache);
  45311. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  45312. return rc;
  45313. }
  45314. }
  45315. }
  45316. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  45317. return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  45318. }
  45319. /*
  45320. ** This is a helper routine for sqlite3PcacheFetchFinish()
  45321. **
  45322. ** In the uncommon case where the page being fetched has not been
  45323. ** initialized, this routine is invoked to do the initialization.
  45324. ** This routine is broken out into a separate function since it
  45325. ** requires extra stack manipulation that can be avoided in the common
  45326. ** case.
  45327. */
  45328. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  45329. PCache *pCache, /* Obtain the page from this cache */
  45330. Pgno pgno, /* Page number obtained */
  45331. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  45332. ){
  45333. PgHdr *pPgHdr;
  45334. assert( pPage!=0 );
  45335. pPgHdr = (PgHdr*)pPage->pExtra;
  45336. assert( pPgHdr->pPage==0 );
  45337. memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
  45338. pPgHdr->pPage = pPage;
  45339. pPgHdr->pData = pPage->pBuf;
  45340. pPgHdr->pExtra = (void *)&pPgHdr[1];
  45341. memset(pPgHdr->pExtra, 0, 8);
  45342. pPgHdr->pCache = pCache;
  45343. pPgHdr->pgno = pgno;
  45344. pPgHdr->flags = PGHDR_CLEAN;
  45345. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  45346. }
  45347. /*
  45348. ** This routine converts the sqlite3_pcache_page object returned by
  45349. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  45350. ** must be called after sqlite3PcacheFetch() in order to get a usable
  45351. ** result.
  45352. */
  45353. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  45354. PCache *pCache, /* Obtain the page from this cache */
  45355. Pgno pgno, /* Page number obtained */
  45356. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  45357. ){
  45358. PgHdr *pPgHdr;
  45359. assert( pPage!=0 );
  45360. pPgHdr = (PgHdr *)pPage->pExtra;
  45361. if( !pPgHdr->pPage ){
  45362. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  45363. }
  45364. pCache->nRefSum++;
  45365. pPgHdr->nRef++;
  45366. assert( sqlite3PcachePageSanity(pPgHdr) );
  45367. return pPgHdr;
  45368. }
  45369. /*
  45370. ** Decrement the reference count on a page. If the page is clean and the
  45371. ** reference count drops to 0, then it is made eligible for recycling.
  45372. */
  45373. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  45374. assert( p->nRef>0 );
  45375. p->pCache->nRefSum--;
  45376. if( (--p->nRef)==0 ){
  45377. if( p->flags&PGHDR_CLEAN ){
  45378. pcacheUnpin(p);
  45379. }else{
  45380. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  45381. }
  45382. }
  45383. }
  45384. /*
  45385. ** Increase the reference count of a supplied page by 1.
  45386. */
  45387. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  45388. assert(p->nRef>0);
  45389. assert( sqlite3PcachePageSanity(p) );
  45390. p->nRef++;
  45391. p->pCache->nRefSum++;
  45392. }
  45393. /*
  45394. ** Drop a page from the cache. There must be exactly one reference to the
  45395. ** page. This function deletes that reference, so after it returns the
  45396. ** page pointed to by p is invalid.
  45397. */
  45398. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  45399. assert( p->nRef==1 );
  45400. assert( sqlite3PcachePageSanity(p) );
  45401. if( p->flags&PGHDR_DIRTY ){
  45402. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  45403. }
  45404. p->pCache->nRefSum--;
  45405. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  45406. }
  45407. /*
  45408. ** Make sure the page is marked as dirty. If it isn't dirty already,
  45409. ** make it so.
  45410. */
  45411. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  45412. assert( p->nRef>0 );
  45413. assert( sqlite3PcachePageSanity(p) );
  45414. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
  45415. p->flags &= ~PGHDR_DONT_WRITE;
  45416. if( p->flags & PGHDR_CLEAN ){
  45417. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  45418. pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
  45419. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  45420. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  45421. }
  45422. assert( sqlite3PcachePageSanity(p) );
  45423. }
  45424. }
  45425. /*
  45426. ** Make sure the page is marked as clean. If it isn't clean already,
  45427. ** make it so.
  45428. */
  45429. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  45430. assert( sqlite3PcachePageSanity(p) );
  45431. assert( (p->flags & PGHDR_DIRTY)!=0 );
  45432. assert( (p->flags & PGHDR_CLEAN)==0 );
  45433. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  45434. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  45435. p->flags |= PGHDR_CLEAN;
  45436. pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
  45437. assert( sqlite3PcachePageSanity(p) );
  45438. if( p->nRef==0 ){
  45439. pcacheUnpin(p);
  45440. }
  45441. }
  45442. /*
  45443. ** Make every page in the cache clean.
  45444. */
  45445. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  45446. PgHdr *p;
  45447. pcacheTrace(("%p.CLEAN-ALL\n",pCache));
  45448. while( (p = pCache->pDirty)!=0 ){
  45449. sqlite3PcacheMakeClean(p);
  45450. }
  45451. }
  45452. /*
  45453. ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
  45454. */
  45455. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
  45456. PgHdr *p;
  45457. pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
  45458. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  45459. p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  45460. }
  45461. pCache->pSynced = pCache->pDirtyTail;
  45462. }
  45463. /*
  45464. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  45465. */
  45466. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  45467. PgHdr *p;
  45468. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  45469. p->flags &= ~PGHDR_NEED_SYNC;
  45470. }
  45471. pCache->pSynced = pCache->pDirtyTail;
  45472. }
  45473. /*
  45474. ** Change the page number of page p to newPgno.
  45475. */
  45476. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  45477. PCache *pCache = p->pCache;
  45478. assert( p->nRef>0 );
  45479. assert( newPgno>0 );
  45480. assert( sqlite3PcachePageSanity(p) );
  45481. pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
  45482. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  45483. p->pgno = newPgno;
  45484. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  45485. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  45486. }
  45487. }
  45488. /*
  45489. ** Drop every cache entry whose page number is greater than "pgno". The
  45490. ** caller must ensure that there are no outstanding references to any pages
  45491. ** other than page 1 with a page number greater than pgno.
  45492. **
  45493. ** If there is a reference to page 1 and the pgno parameter passed to this
  45494. ** function is 0, then the data area associated with page 1 is zeroed, but
  45495. ** the page object is not dropped.
  45496. */
  45497. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  45498. if( pCache->pCache ){
  45499. PgHdr *p;
  45500. PgHdr *pNext;
  45501. pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
  45502. for(p=pCache->pDirty; p; p=pNext){
  45503. pNext = p->pDirtyNext;
  45504. /* This routine never gets call with a positive pgno except right
  45505. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  45506. ** it must be that pgno==0.
  45507. */
  45508. assert( p->pgno>0 );
  45509. if( p->pgno>pgno ){
  45510. assert( p->flags&PGHDR_DIRTY );
  45511. sqlite3PcacheMakeClean(p);
  45512. }
  45513. }
  45514. if( pgno==0 && pCache->nRefSum ){
  45515. sqlite3_pcache_page *pPage1;
  45516. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  45517. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  45518. ** pCache->nRefSum>0 */
  45519. memset(pPage1->pBuf, 0, pCache->szPage);
  45520. pgno = 1;
  45521. }
  45522. }
  45523. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  45524. }
  45525. }
  45526. /*
  45527. ** Close a cache.
  45528. */
  45529. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  45530. assert( pCache->pCache!=0 );
  45531. pcacheTrace(("%p.CLOSE\n",pCache));
  45532. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  45533. }
  45534. /*
  45535. ** Discard the contents of the cache.
  45536. */
  45537. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  45538. sqlite3PcacheTruncate(pCache, 0);
  45539. }
  45540. /*
  45541. ** Merge two lists of pages connected by pDirty and in pgno order.
  45542. ** Do not bother fixing the pDirtyPrev pointers.
  45543. */
  45544. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  45545. PgHdr result, *pTail;
  45546. pTail = &result;
  45547. assert( pA!=0 && pB!=0 );
  45548. for(;;){
  45549. if( pA->pgno<pB->pgno ){
  45550. pTail->pDirty = pA;
  45551. pTail = pA;
  45552. pA = pA->pDirty;
  45553. if( pA==0 ){
  45554. pTail->pDirty = pB;
  45555. break;
  45556. }
  45557. }else{
  45558. pTail->pDirty = pB;
  45559. pTail = pB;
  45560. pB = pB->pDirty;
  45561. if( pB==0 ){
  45562. pTail->pDirty = pA;
  45563. break;
  45564. }
  45565. }
  45566. }
  45567. return result.pDirty;
  45568. }
  45569. /*
  45570. ** Sort the list of pages in accending order by pgno. Pages are
  45571. ** connected by pDirty pointers. The pDirtyPrev pointers are
  45572. ** corrupted by this sort.
  45573. **
  45574. ** Since there cannot be more than 2^31 distinct pages in a database,
  45575. ** there cannot be more than 31 buckets required by the merge sorter.
  45576. ** One extra bucket is added to catch overflow in case something
  45577. ** ever changes to make the previous sentence incorrect.
  45578. */
  45579. #define N_SORT_BUCKET 32
  45580. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  45581. PgHdr *a[N_SORT_BUCKET], *p;
  45582. int i;
  45583. memset(a, 0, sizeof(a));
  45584. while( pIn ){
  45585. p = pIn;
  45586. pIn = p->pDirty;
  45587. p->pDirty = 0;
  45588. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  45589. if( a[i]==0 ){
  45590. a[i] = p;
  45591. break;
  45592. }else{
  45593. p = pcacheMergeDirtyList(a[i], p);
  45594. a[i] = 0;
  45595. }
  45596. }
  45597. if( NEVER(i==N_SORT_BUCKET-1) ){
  45598. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  45599. ** the input list. But that is impossible.
  45600. */
  45601. a[i] = pcacheMergeDirtyList(a[i], p);
  45602. }
  45603. }
  45604. p = a[0];
  45605. for(i=1; i<N_SORT_BUCKET; i++){
  45606. if( a[i]==0 ) continue;
  45607. p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
  45608. }
  45609. return p;
  45610. }
  45611. /*
  45612. ** Return a list of all dirty pages in the cache, sorted by page number.
  45613. */
  45614. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  45615. PgHdr *p;
  45616. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  45617. p->pDirty = p->pDirtyNext;
  45618. }
  45619. return pcacheSortDirtyList(pCache->pDirty);
  45620. }
  45621. /*
  45622. ** Return the total number of references to all pages held by the cache.
  45623. **
  45624. ** This is not the total number of pages referenced, but the sum of the
  45625. ** reference count for all pages.
  45626. */
  45627. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  45628. return pCache->nRefSum;
  45629. }
  45630. /*
  45631. ** Return the number of references to the page supplied as an argument.
  45632. */
  45633. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  45634. return p->nRef;
  45635. }
  45636. /*
  45637. ** Return the total number of pages in the cache.
  45638. */
  45639. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  45640. assert( pCache->pCache!=0 );
  45641. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  45642. }
  45643. #ifdef SQLITE_TEST
  45644. /*
  45645. ** Get the suggested cache-size value.
  45646. */
  45647. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  45648. return numberOfCachePages(pCache);
  45649. }
  45650. #endif
  45651. /*
  45652. ** Set the suggested cache-size value.
  45653. */
  45654. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  45655. assert( pCache->pCache!=0 );
  45656. pCache->szCache = mxPage;
  45657. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  45658. numberOfCachePages(pCache));
  45659. }
  45660. /*
  45661. ** Set the suggested cache-spill value. Make no changes if if the
  45662. ** argument is zero. Return the effective cache-spill size, which will
  45663. ** be the larger of the szSpill and szCache.
  45664. */
  45665. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
  45666. int res;
  45667. assert( p->pCache!=0 );
  45668. if( mxPage ){
  45669. if( mxPage<0 ){
  45670. mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
  45671. }
  45672. p->szSpill = mxPage;
  45673. }
  45674. res = numberOfCachePages(p);
  45675. if( res<p->szSpill ) res = p->szSpill;
  45676. return res;
  45677. }
  45678. /*
  45679. ** Free up as much memory as possible from the page cache.
  45680. */
  45681. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  45682. assert( pCache->pCache!=0 );
  45683. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  45684. }
  45685. /*
  45686. ** Return the size of the header added by this middleware layer
  45687. ** in the page-cache hierarchy.
  45688. */
  45689. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  45690. /*
  45691. ** Return the number of dirty pages currently in the cache, as a percentage
  45692. ** of the configured cache size.
  45693. */
  45694. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
  45695. PgHdr *pDirty;
  45696. int nDirty = 0;
  45697. int nCache = numberOfCachePages(pCache);
  45698. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
  45699. return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
  45700. }
  45701. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  45702. /*
  45703. ** Return true if there are one or more dirty pages in the cache. Else false.
  45704. */
  45705. SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache){
  45706. return (pCache->pDirty!=0);
  45707. }
  45708. #endif
  45709. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  45710. /*
  45711. ** For all dirty pages currently in the cache, invoke the specified
  45712. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  45713. ** defined.
  45714. */
  45715. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  45716. PgHdr *pDirty;
  45717. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  45718. xIter(pDirty);
  45719. }
  45720. }
  45721. #endif
  45722. /************** End of pcache.c **********************************************/
  45723. /************** Begin file pcache1.c *****************************************/
  45724. /*
  45725. ** 2008 November 05
  45726. **
  45727. ** The author disclaims copyright to this source code. In place of
  45728. ** a legal notice, here is a blessing:
  45729. **
  45730. ** May you do good and not evil.
  45731. ** May you find forgiveness for yourself and forgive others.
  45732. ** May you share freely, never taking more than you give.
  45733. **
  45734. *************************************************************************
  45735. **
  45736. ** This file implements the default page cache implementation (the
  45737. ** sqlite3_pcache interface). It also contains part of the implementation
  45738. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  45739. ** If the default page cache implementation is overridden, then neither of
  45740. ** these two features are available.
  45741. **
  45742. ** A Page cache line looks like this:
  45743. **
  45744. ** -------------------------------------------------------------
  45745. ** | database page content | PgHdr1 | MemPage | PgHdr |
  45746. ** -------------------------------------------------------------
  45747. **
  45748. ** The database page content is up front (so that buffer overreads tend to
  45749. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  45750. ** is the extension added by the btree.c module containing information such
  45751. ** as the database page number and how that database page is used. PgHdr
  45752. ** is added by the pcache.c layer and contains information used to keep track
  45753. ** of which pages are "dirty". PgHdr1 is an extension added by this
  45754. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  45755. ** PgHdr1 contains information needed to look up a page by its page number.
  45756. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  45757. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  45758. **
  45759. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  45760. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  45761. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  45762. ** size can vary according to architecture, compile-time options, and
  45763. ** SQLite library version number.
  45764. **
  45765. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  45766. ** using a separate memory allocation from the database page content. This
  45767. ** seeks to overcome the "clownshoe" problem (also called "internal
  45768. ** fragmentation" in academic literature) of allocating a few bytes more
  45769. ** than a power of two with the memory allocator rounding up to the next
  45770. ** power of two, and leaving the rounded-up space unused.
  45771. **
  45772. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  45773. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  45774. **
  45775. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  45776. ** The btree.c module deals with pointers to MemPage objects.
  45777. **
  45778. ** SOURCE OF PAGE CACHE MEMORY:
  45779. **
  45780. ** Memory for a page might come from any of three sources:
  45781. **
  45782. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  45783. ** (2) Global page-cache memory provided using sqlite3_config() with
  45784. ** SQLITE_CONFIG_PAGECACHE.
  45785. ** (3) PCache-local bulk allocation.
  45786. **
  45787. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  45788. ** that is allocated when the page cache is created. The size of the local
  45789. ** bulk allocation can be adjusted using
  45790. **
  45791. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
  45792. **
  45793. ** If N is positive, then N pages worth of memory are allocated using a single
  45794. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  45795. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  45796. ** for as many pages as can be accomodated.
  45797. **
  45798. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  45799. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  45800. ** memory allocator (1).
  45801. **
  45802. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  45803. ** show that method (3) with N==100 provides about a 5% performance boost for
  45804. ** common workloads.
  45805. */
  45806. /* #include "sqliteInt.h" */
  45807. typedef struct PCache1 PCache1;
  45808. typedef struct PgHdr1 PgHdr1;
  45809. typedef struct PgFreeslot PgFreeslot;
  45810. typedef struct PGroup PGroup;
  45811. /*
  45812. ** Each cache entry is represented by an instance of the following
  45813. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  45814. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  45815. ** in memory.
  45816. **
  45817. ** Note: Variables isBulkLocal and isAnchor were once type "u8". That works,
  45818. ** but causes a 2-byte gap in the structure for most architectures (since
  45819. ** pointers must be either 4 or 8-byte aligned). As this structure is located
  45820. ** in memory directly after the associated page data, if the database is
  45821. ** corrupt, code at the b-tree layer may overread the page buffer and
  45822. ** read part of this structure before the corruption is detected. This
  45823. ** can cause a valgrind error if the unitialized gap is accessed. Using u16
  45824. ** ensures there is no such gap, and therefore no bytes of unitialized memory
  45825. ** in the structure.
  45826. */
  45827. struct PgHdr1 {
  45828. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  45829. unsigned int iKey; /* Key value (page number) */
  45830. u16 isBulkLocal; /* This page from bulk local storage */
  45831. u16 isAnchor; /* This is the PGroup.lru element */
  45832. PgHdr1 *pNext; /* Next in hash table chain */
  45833. PCache1 *pCache; /* Cache that currently owns this page */
  45834. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  45835. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  45836. /* NB: pLruPrev is only valid if pLruNext!=0 */
  45837. };
  45838. /*
  45839. ** A page is pinned if it is not on the LRU list. To be "pinned" means
  45840. ** that the page is in active use and must not be deallocated.
  45841. */
  45842. #define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
  45843. #define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
  45844. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  45845. ** of one or more PCaches that are able to recycle each other's unpinned
  45846. ** pages when they are under memory pressure. A PGroup is an instance of
  45847. ** the following object.
  45848. **
  45849. ** This page cache implementation works in one of two modes:
  45850. **
  45851. ** (1) Every PCache is the sole member of its own PGroup. There is
  45852. ** one PGroup per PCache.
  45853. **
  45854. ** (2) There is a single global PGroup that all PCaches are a member
  45855. ** of.
  45856. **
  45857. ** Mode 1 uses more memory (since PCache instances are not able to rob
  45858. ** unused pages from other PCaches) but it also operates without a mutex,
  45859. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  45860. ** threadsafe, but recycles pages more efficiently.
  45861. **
  45862. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  45863. ** PGroup which is the pcache1.grp global variable and its mutex is
  45864. ** SQLITE_MUTEX_STATIC_LRU.
  45865. */
  45866. struct PGroup {
  45867. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  45868. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  45869. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  45870. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  45871. unsigned int nPurgeable; /* Number of purgeable pages allocated */
  45872. PgHdr1 lru; /* The beginning and end of the LRU list */
  45873. };
  45874. /* Each page cache is an instance of the following object. Every
  45875. ** open database file (including each in-memory database and each
  45876. ** temporary or transient database) has a single page cache which
  45877. ** is an instance of this object.
  45878. **
  45879. ** Pointers to structures of this type are cast and returned as
  45880. ** opaque sqlite3_pcache* handles.
  45881. */
  45882. struct PCache1 {
  45883. /* Cache configuration parameters. Page size (szPage) and the purgeable
  45884. ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
  45885. ** cache is created and are never changed thereafter. nMax may be
  45886. ** modified at any time by a call to the pcache1Cachesize() method.
  45887. ** The PGroup mutex must be held when accessing nMax.
  45888. */
  45889. PGroup *pGroup; /* PGroup this cache belongs to */
  45890. unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
  45891. int szPage; /* Size of database content section */
  45892. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  45893. int szAlloc; /* Total size of one pcache line */
  45894. int bPurgeable; /* True if cache is purgeable */
  45895. unsigned int nMin; /* Minimum number of pages reserved */
  45896. unsigned int nMax; /* Configured "cache_size" value */
  45897. unsigned int n90pct; /* nMax*9/10 */
  45898. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  45899. unsigned int nPurgeableDummy; /* pnPurgeable points here when not used*/
  45900. /* Hash table of all pages. The following variables may only be accessed
  45901. ** when the accessor is holding the PGroup mutex.
  45902. */
  45903. unsigned int nRecyclable; /* Number of pages in the LRU list */
  45904. unsigned int nPage; /* Total number of pages in apHash */
  45905. unsigned int nHash; /* Number of slots in apHash[] */
  45906. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  45907. PgHdr1 *pFree; /* List of unused pcache-local pages */
  45908. void *pBulk; /* Bulk memory used by pcache-local */
  45909. };
  45910. /*
  45911. ** Free slots in the allocator used to divide up the global page cache
  45912. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  45913. */
  45914. struct PgFreeslot {
  45915. PgFreeslot *pNext; /* Next free slot */
  45916. };
  45917. /*
  45918. ** Global data used by this cache.
  45919. */
  45920. static SQLITE_WSD struct PCacheGlobal {
  45921. PGroup grp; /* The global PGroup for mode (2) */
  45922. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  45923. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  45924. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  45925. ** The nFreeSlot and pFree values do require mutex protection.
  45926. */
  45927. int isInit; /* True if initialized */
  45928. int separateCache; /* Use a new PGroup for each PCache */
  45929. int nInitPage; /* Initial bulk allocation size */
  45930. int szSlot; /* Size of each free slot */
  45931. int nSlot; /* The number of pcache slots */
  45932. int nReserve; /* Try to keep nFreeSlot above this */
  45933. void *pStart, *pEnd; /* Bounds of global page cache memory */
  45934. /* Above requires no mutex. Use mutex below for variable that follow. */
  45935. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  45936. PgFreeslot *pFree; /* Free page blocks */
  45937. int nFreeSlot; /* Number of unused pcache slots */
  45938. /* The following value requires a mutex to change. We skip the mutex on
  45939. ** reading because (1) most platforms read a 32-bit integer atomically and
  45940. ** (2) even if an incorrect value is read, no great harm is done since this
  45941. ** is really just an optimization. */
  45942. int bUnderPressure; /* True if low on PAGECACHE memory */
  45943. } pcache1_g;
  45944. /*
  45945. ** All code in this file should access the global structure above via the
  45946. ** alias "pcache1". This ensures that the WSD emulation is used when
  45947. ** compiling for systems that do not support real WSD.
  45948. */
  45949. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  45950. /*
  45951. ** Macros to enter and leave the PCache LRU mutex.
  45952. */
  45953. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  45954. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  45955. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  45956. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  45957. #else
  45958. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  45959. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  45960. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  45961. #endif
  45962. /******************************************************************************/
  45963. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  45964. /*
  45965. ** This function is called during initialization if a static buffer is
  45966. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  45967. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  45968. ** enough to contain 'n' buffers of 'sz' bytes each.
  45969. **
  45970. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  45971. ** to be serialized already. There is no need for further mutexing.
  45972. */
  45973. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  45974. if( pcache1.isInit ){
  45975. PgFreeslot *p;
  45976. if( pBuf==0 ) sz = n = 0;
  45977. if( n==0 ) sz = 0;
  45978. sz = ROUNDDOWN8(sz);
  45979. pcache1.szSlot = sz;
  45980. pcache1.nSlot = pcache1.nFreeSlot = n;
  45981. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  45982. pcache1.pStart = pBuf;
  45983. pcache1.pFree = 0;
  45984. pcache1.bUnderPressure = 0;
  45985. while( n-- ){
  45986. p = (PgFreeslot*)pBuf;
  45987. p->pNext = pcache1.pFree;
  45988. pcache1.pFree = p;
  45989. pBuf = (void*)&((char*)pBuf)[sz];
  45990. }
  45991. pcache1.pEnd = pBuf;
  45992. }
  45993. }
  45994. /*
  45995. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  45996. ** true if pCache->pFree ends up containing one or more free pages.
  45997. */
  45998. static int pcache1InitBulk(PCache1 *pCache){
  45999. i64 szBulk;
  46000. char *zBulk;
  46001. if( pcache1.nInitPage==0 ) return 0;
  46002. /* Do not bother with a bulk allocation if the cache size very small */
  46003. if( pCache->nMax<3 ) return 0;
  46004. sqlite3BeginBenignMalloc();
  46005. if( pcache1.nInitPage>0 ){
  46006. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  46007. }else{
  46008. szBulk = -1024 * (i64)pcache1.nInitPage;
  46009. }
  46010. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  46011. szBulk = pCache->szAlloc*(i64)pCache->nMax;
  46012. }
  46013. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  46014. sqlite3EndBenignMalloc();
  46015. if( zBulk ){
  46016. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  46017. do{
  46018. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  46019. pX->page.pBuf = zBulk;
  46020. pX->page.pExtra = &pX[1];
  46021. pX->isBulkLocal = 1;
  46022. pX->isAnchor = 0;
  46023. pX->pNext = pCache->pFree;
  46024. pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
  46025. pCache->pFree = pX;
  46026. zBulk += pCache->szAlloc;
  46027. }while( --nBulk );
  46028. }
  46029. return pCache->pFree!=0;
  46030. }
  46031. /*
  46032. ** Malloc function used within this file to allocate space from the buffer
  46033. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  46034. ** such buffer exists or there is no space left in it, this function falls
  46035. ** back to sqlite3Malloc().
  46036. **
  46037. ** Multiple threads can run this routine at the same time. Global variables
  46038. ** in pcache1 need to be protected via mutex.
  46039. */
  46040. static void *pcache1Alloc(int nByte){
  46041. void *p = 0;
  46042. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  46043. if( nByte<=pcache1.szSlot ){
  46044. sqlite3_mutex_enter(pcache1.mutex);
  46045. p = (PgHdr1 *)pcache1.pFree;
  46046. if( p ){
  46047. pcache1.pFree = pcache1.pFree->pNext;
  46048. pcache1.nFreeSlot--;
  46049. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  46050. assert( pcache1.nFreeSlot>=0 );
  46051. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  46052. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  46053. }
  46054. sqlite3_mutex_leave(pcache1.mutex);
  46055. }
  46056. if( p==0 ){
  46057. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  46058. ** it from sqlite3Malloc instead.
  46059. */
  46060. p = sqlite3Malloc(nByte);
  46061. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  46062. if( p ){
  46063. int sz = sqlite3MallocSize(p);
  46064. sqlite3_mutex_enter(pcache1.mutex);
  46065. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  46066. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  46067. sqlite3_mutex_leave(pcache1.mutex);
  46068. }
  46069. #endif
  46070. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  46071. }
  46072. return p;
  46073. }
  46074. /*
  46075. ** Free an allocated buffer obtained from pcache1Alloc().
  46076. */
  46077. static void pcache1Free(void *p){
  46078. if( p==0 ) return;
  46079. if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
  46080. PgFreeslot *pSlot;
  46081. sqlite3_mutex_enter(pcache1.mutex);
  46082. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  46083. pSlot = (PgFreeslot*)p;
  46084. pSlot->pNext = pcache1.pFree;
  46085. pcache1.pFree = pSlot;
  46086. pcache1.nFreeSlot++;
  46087. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  46088. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  46089. sqlite3_mutex_leave(pcache1.mutex);
  46090. }else{
  46091. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  46092. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  46093. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  46094. {
  46095. int nFreed = 0;
  46096. nFreed = sqlite3MallocSize(p);
  46097. sqlite3_mutex_enter(pcache1.mutex);
  46098. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  46099. sqlite3_mutex_leave(pcache1.mutex);
  46100. }
  46101. #endif
  46102. sqlite3_free(p);
  46103. }
  46104. }
  46105. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  46106. /*
  46107. ** Return the size of a pcache allocation
  46108. */
  46109. static int pcache1MemSize(void *p){
  46110. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  46111. return pcache1.szSlot;
  46112. }else{
  46113. int iSize;
  46114. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  46115. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  46116. iSize = sqlite3MallocSize(p);
  46117. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  46118. return iSize;
  46119. }
  46120. }
  46121. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  46122. /*
  46123. ** Allocate a new page object initially associated with cache pCache.
  46124. */
  46125. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  46126. PgHdr1 *p = 0;
  46127. void *pPg;
  46128. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  46129. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  46130. p = pCache->pFree;
  46131. pCache->pFree = p->pNext;
  46132. p->pNext = 0;
  46133. }else{
  46134. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  46135. /* The group mutex must be released before pcache1Alloc() is called. This
  46136. ** is because it might call sqlite3_release_memory(), which assumes that
  46137. ** this mutex is not held. */
  46138. assert( pcache1.separateCache==0 );
  46139. assert( pCache->pGroup==&pcache1.grp );
  46140. pcache1LeaveMutex(pCache->pGroup);
  46141. #endif
  46142. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  46143. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  46144. pPg = pcache1Alloc(pCache->szPage);
  46145. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  46146. if( !pPg || !p ){
  46147. pcache1Free(pPg);
  46148. sqlite3_free(p);
  46149. pPg = 0;
  46150. }
  46151. #else
  46152. pPg = pcache1Alloc(pCache->szAlloc);
  46153. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  46154. #endif
  46155. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  46156. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  46157. pcache1EnterMutex(pCache->pGroup);
  46158. #endif
  46159. if( pPg==0 ) return 0;
  46160. p->page.pBuf = pPg;
  46161. p->page.pExtra = &p[1];
  46162. p->isBulkLocal = 0;
  46163. p->isAnchor = 0;
  46164. }
  46165. (*pCache->pnPurgeable)++;
  46166. return p;
  46167. }
  46168. /*
  46169. ** Free a page object allocated by pcache1AllocPage().
  46170. */
  46171. static void pcache1FreePage(PgHdr1 *p){
  46172. PCache1 *pCache;
  46173. assert( p!=0 );
  46174. pCache = p->pCache;
  46175. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  46176. if( p->isBulkLocal ){
  46177. p->pNext = pCache->pFree;
  46178. pCache->pFree = p;
  46179. }else{
  46180. pcache1Free(p->page.pBuf);
  46181. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  46182. sqlite3_free(p);
  46183. #endif
  46184. }
  46185. (*pCache->pnPurgeable)--;
  46186. }
  46187. /*
  46188. ** Malloc function used by SQLite to obtain space from the buffer configured
  46189. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  46190. ** exists, this function falls back to sqlite3Malloc().
  46191. */
  46192. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  46193. assert( sz<=65536+8 ); /* These allocations are never very large */
  46194. return pcache1Alloc(sz);
  46195. }
  46196. /*
  46197. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  46198. */
  46199. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  46200. pcache1Free(p);
  46201. }
  46202. /*
  46203. ** Return true if it desirable to avoid allocating a new page cache
  46204. ** entry.
  46205. **
  46206. ** If memory was allocated specifically to the page cache using
  46207. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  46208. ** it is desirable to avoid allocating a new page cache entry because
  46209. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  46210. ** for all page cache needs and we should not need to spill the
  46211. ** allocation onto the heap.
  46212. **
  46213. ** Or, the heap is used for all page cache memory but the heap is
  46214. ** under memory pressure, then again it is desirable to avoid
  46215. ** allocating a new page cache entry in order to avoid stressing
  46216. ** the heap even further.
  46217. */
  46218. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  46219. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  46220. return pcache1.bUnderPressure;
  46221. }else{
  46222. return sqlite3HeapNearlyFull();
  46223. }
  46224. }
  46225. /******************************************************************************/
  46226. /******** General Implementation Functions ************************************/
  46227. /*
  46228. ** This function is used to resize the hash table used by the cache passed
  46229. ** as the first argument.
  46230. **
  46231. ** The PCache mutex must be held when this function is called.
  46232. */
  46233. static void pcache1ResizeHash(PCache1 *p){
  46234. PgHdr1 **apNew;
  46235. unsigned int nNew;
  46236. unsigned int i;
  46237. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  46238. nNew = p->nHash*2;
  46239. if( nNew<256 ){
  46240. nNew = 256;
  46241. }
  46242. pcache1LeaveMutex(p->pGroup);
  46243. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  46244. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  46245. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  46246. pcache1EnterMutex(p->pGroup);
  46247. if( apNew ){
  46248. for(i=0; i<p->nHash; i++){
  46249. PgHdr1 *pPage;
  46250. PgHdr1 *pNext = p->apHash[i];
  46251. while( (pPage = pNext)!=0 ){
  46252. unsigned int h = pPage->iKey % nNew;
  46253. pNext = pPage->pNext;
  46254. pPage->pNext = apNew[h];
  46255. apNew[h] = pPage;
  46256. }
  46257. }
  46258. sqlite3_free(p->apHash);
  46259. p->apHash = apNew;
  46260. p->nHash = nNew;
  46261. }
  46262. }
  46263. /*
  46264. ** This function is used internally to remove the page pPage from the
  46265. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  46266. ** LRU list, then this function is a no-op.
  46267. **
  46268. ** The PGroup mutex must be held when this function is called.
  46269. */
  46270. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  46271. assert( pPage!=0 );
  46272. assert( PAGE_IS_UNPINNED(pPage) );
  46273. assert( pPage->pLruNext );
  46274. assert( pPage->pLruPrev );
  46275. assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
  46276. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  46277. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  46278. pPage->pLruNext = 0;
  46279. /* pPage->pLruPrev = 0;
  46280. ** No need to clear pLruPrev as it is never accessed if pLruNext is 0 */
  46281. assert( pPage->isAnchor==0 );
  46282. assert( pPage->pCache->pGroup->lru.isAnchor==1 );
  46283. pPage->pCache->nRecyclable--;
  46284. return pPage;
  46285. }
  46286. /*
  46287. ** Remove the page supplied as an argument from the hash table
  46288. ** (PCache1.apHash structure) that it is currently stored in.
  46289. ** Also free the page if freePage is true.
  46290. **
  46291. ** The PGroup mutex must be held when this function is called.
  46292. */
  46293. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  46294. unsigned int h;
  46295. PCache1 *pCache = pPage->pCache;
  46296. PgHdr1 **pp;
  46297. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  46298. h = pPage->iKey % pCache->nHash;
  46299. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  46300. *pp = (*pp)->pNext;
  46301. pCache->nPage--;
  46302. if( freeFlag ) pcache1FreePage(pPage);
  46303. }
  46304. /*
  46305. ** If there are currently more than nMaxPage pages allocated, try
  46306. ** to recycle pages to reduce the number allocated to nMaxPage.
  46307. */
  46308. static void pcache1EnforceMaxPage(PCache1 *pCache){
  46309. PGroup *pGroup = pCache->pGroup;
  46310. PgHdr1 *p;
  46311. assert( sqlite3_mutex_held(pGroup->mutex) );
  46312. while( pGroup->nPurgeable>pGroup->nMaxPage
  46313. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  46314. ){
  46315. assert( p->pCache->pGroup==pGroup );
  46316. assert( PAGE_IS_UNPINNED(p) );
  46317. pcache1PinPage(p);
  46318. pcache1RemoveFromHash(p, 1);
  46319. }
  46320. if( pCache->nPage==0 && pCache->pBulk ){
  46321. sqlite3_free(pCache->pBulk);
  46322. pCache->pBulk = pCache->pFree = 0;
  46323. }
  46324. }
  46325. /*
  46326. ** Discard all pages from cache pCache with a page number (key value)
  46327. ** greater than or equal to iLimit. Any pinned pages that meet this
  46328. ** criteria are unpinned before they are discarded.
  46329. **
  46330. ** The PCache mutex must be held when this function is called.
  46331. */
  46332. static void pcache1TruncateUnsafe(
  46333. PCache1 *pCache, /* The cache to truncate */
  46334. unsigned int iLimit /* Drop pages with this pgno or larger */
  46335. ){
  46336. TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
  46337. unsigned int h, iStop;
  46338. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  46339. assert( pCache->iMaxKey >= iLimit );
  46340. assert( pCache->nHash > 0 );
  46341. if( pCache->iMaxKey - iLimit < pCache->nHash ){
  46342. /* If we are just shaving the last few pages off the end of the
  46343. ** cache, then there is no point in scanning the entire hash table.
  46344. ** Only scan those hash slots that might contain pages that need to
  46345. ** be removed. */
  46346. h = iLimit % pCache->nHash;
  46347. iStop = pCache->iMaxKey % pCache->nHash;
  46348. TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
  46349. }else{
  46350. /* This is the general case where many pages are being removed.
  46351. ** It is necessary to scan the entire hash table */
  46352. h = pCache->nHash/2;
  46353. iStop = h - 1;
  46354. }
  46355. for(;;){
  46356. PgHdr1 **pp;
  46357. PgHdr1 *pPage;
  46358. assert( h<pCache->nHash );
  46359. pp = &pCache->apHash[h];
  46360. while( (pPage = *pp)!=0 ){
  46361. if( pPage->iKey>=iLimit ){
  46362. pCache->nPage--;
  46363. *pp = pPage->pNext;
  46364. if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
  46365. pcache1FreePage(pPage);
  46366. }else{
  46367. pp = &pPage->pNext;
  46368. TESTONLY( if( nPage>=0 ) nPage++; )
  46369. }
  46370. }
  46371. if( h==iStop ) break;
  46372. h = (h+1) % pCache->nHash;
  46373. }
  46374. assert( nPage<0 || pCache->nPage==(unsigned)nPage );
  46375. }
  46376. /******************************************************************************/
  46377. /******** sqlite3_pcache Methods **********************************************/
  46378. /*
  46379. ** Implementation of the sqlite3_pcache.xInit method.
  46380. */
  46381. static int pcache1Init(void *NotUsed){
  46382. UNUSED_PARAMETER(NotUsed);
  46383. assert( pcache1.isInit==0 );
  46384. memset(&pcache1, 0, sizeof(pcache1));
  46385. /*
  46386. ** The pcache1.separateCache variable is true if each PCache has its own
  46387. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  46388. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  46389. **
  46390. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  46391. **
  46392. ** * Use a unified cache in single-threaded applications that have
  46393. ** configured a start-time buffer for use as page-cache memory using
  46394. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  46395. ** pBuf argument.
  46396. **
  46397. ** * Otherwise use separate caches (mode-1)
  46398. */
  46399. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  46400. pcache1.separateCache = 0;
  46401. #elif SQLITE_THREADSAFE
  46402. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  46403. || sqlite3GlobalConfig.bCoreMutex>0;
  46404. #else
  46405. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  46406. #endif
  46407. #if SQLITE_THREADSAFE
  46408. if( sqlite3GlobalConfig.bCoreMutex ){
  46409. pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
  46410. pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
  46411. }
  46412. #endif
  46413. if( pcache1.separateCache
  46414. && sqlite3GlobalConfig.nPage!=0
  46415. && sqlite3GlobalConfig.pPage==0
  46416. ){
  46417. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  46418. }else{
  46419. pcache1.nInitPage = 0;
  46420. }
  46421. pcache1.grp.mxPinned = 10;
  46422. pcache1.isInit = 1;
  46423. return SQLITE_OK;
  46424. }
  46425. /*
  46426. ** Implementation of the sqlite3_pcache.xShutdown method.
  46427. ** Note that the static mutex allocated in xInit does
  46428. ** not need to be freed.
  46429. */
  46430. static void pcache1Shutdown(void *NotUsed){
  46431. UNUSED_PARAMETER(NotUsed);
  46432. assert( pcache1.isInit!=0 );
  46433. memset(&pcache1, 0, sizeof(pcache1));
  46434. }
  46435. /* forward declaration */
  46436. static void pcache1Destroy(sqlite3_pcache *p);
  46437. /*
  46438. ** Implementation of the sqlite3_pcache.xCreate method.
  46439. **
  46440. ** Allocate a new cache.
  46441. */
  46442. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  46443. PCache1 *pCache; /* The newly created page cache */
  46444. PGroup *pGroup; /* The group the new page cache will belong to */
  46445. int sz; /* Bytes of memory required to allocate the new cache */
  46446. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  46447. assert( szExtra < 300 );
  46448. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  46449. pCache = (PCache1 *)sqlite3MallocZero(sz);
  46450. if( pCache ){
  46451. if( pcache1.separateCache ){
  46452. pGroup = (PGroup*)&pCache[1];
  46453. pGroup->mxPinned = 10;
  46454. }else{
  46455. pGroup = &pcache1.grp;
  46456. }
  46457. if( pGroup->lru.isAnchor==0 ){
  46458. pGroup->lru.isAnchor = 1;
  46459. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  46460. }
  46461. pCache->pGroup = pGroup;
  46462. pCache->szPage = szPage;
  46463. pCache->szExtra = szExtra;
  46464. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  46465. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  46466. pcache1EnterMutex(pGroup);
  46467. pcache1ResizeHash(pCache);
  46468. if( bPurgeable ){
  46469. pCache->nMin = 10;
  46470. pGroup->nMinPage += pCache->nMin;
  46471. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  46472. pCache->pnPurgeable = &pGroup->nPurgeable;
  46473. }else{
  46474. pCache->pnPurgeable = &pCache->nPurgeableDummy;
  46475. }
  46476. pcache1LeaveMutex(pGroup);
  46477. if( pCache->nHash==0 ){
  46478. pcache1Destroy((sqlite3_pcache*)pCache);
  46479. pCache = 0;
  46480. }
  46481. }
  46482. return (sqlite3_pcache *)pCache;
  46483. }
  46484. /*
  46485. ** Implementation of the sqlite3_pcache.xCachesize method.
  46486. **
  46487. ** Configure the cache_size limit for a cache.
  46488. */
  46489. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  46490. PCache1 *pCache = (PCache1 *)p;
  46491. if( pCache->bPurgeable ){
  46492. PGroup *pGroup = pCache->pGroup;
  46493. pcache1EnterMutex(pGroup);
  46494. pGroup->nMaxPage += (nMax - pCache->nMax);
  46495. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  46496. pCache->nMax = nMax;
  46497. pCache->n90pct = pCache->nMax*9/10;
  46498. pcache1EnforceMaxPage(pCache);
  46499. pcache1LeaveMutex(pGroup);
  46500. }
  46501. }
  46502. /*
  46503. ** Implementation of the sqlite3_pcache.xShrink method.
  46504. **
  46505. ** Free up as much memory as possible.
  46506. */
  46507. static void pcache1Shrink(sqlite3_pcache *p){
  46508. PCache1 *pCache = (PCache1*)p;
  46509. if( pCache->bPurgeable ){
  46510. PGroup *pGroup = pCache->pGroup;
  46511. int savedMaxPage;
  46512. pcache1EnterMutex(pGroup);
  46513. savedMaxPage = pGroup->nMaxPage;
  46514. pGroup->nMaxPage = 0;
  46515. pcache1EnforceMaxPage(pCache);
  46516. pGroup->nMaxPage = savedMaxPage;
  46517. pcache1LeaveMutex(pGroup);
  46518. }
  46519. }
  46520. /*
  46521. ** Implementation of the sqlite3_pcache.xPagecount method.
  46522. */
  46523. static int pcache1Pagecount(sqlite3_pcache *p){
  46524. int n;
  46525. PCache1 *pCache = (PCache1*)p;
  46526. pcache1EnterMutex(pCache->pGroup);
  46527. n = pCache->nPage;
  46528. pcache1LeaveMutex(pCache->pGroup);
  46529. return n;
  46530. }
  46531. /*
  46532. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  46533. ** in the header of the pcache1Fetch() procedure.
  46534. **
  46535. ** This steps are broken out into a separate procedure because they are
  46536. ** usually not needed, and by avoiding the stack initialization required
  46537. ** for these steps, the main pcache1Fetch() procedure can run faster.
  46538. */
  46539. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  46540. PCache1 *pCache,
  46541. unsigned int iKey,
  46542. int createFlag
  46543. ){
  46544. unsigned int nPinned;
  46545. PGroup *pGroup = pCache->pGroup;
  46546. PgHdr1 *pPage = 0;
  46547. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  46548. assert( pCache->nPage >= pCache->nRecyclable );
  46549. nPinned = pCache->nPage - pCache->nRecyclable;
  46550. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  46551. assert( pCache->n90pct == pCache->nMax*9/10 );
  46552. if( createFlag==1 && (
  46553. nPinned>=pGroup->mxPinned
  46554. || nPinned>=pCache->n90pct
  46555. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  46556. )){
  46557. return 0;
  46558. }
  46559. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  46560. assert( pCache->nHash>0 && pCache->apHash );
  46561. /* Step 4. Try to recycle a page. */
  46562. if( pCache->bPurgeable
  46563. && !pGroup->lru.pLruPrev->isAnchor
  46564. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  46565. ){
  46566. PCache1 *pOther;
  46567. pPage = pGroup->lru.pLruPrev;
  46568. assert( PAGE_IS_UNPINNED(pPage) );
  46569. pcache1RemoveFromHash(pPage, 0);
  46570. pcache1PinPage(pPage);
  46571. pOther = pPage->pCache;
  46572. if( pOther->szAlloc != pCache->szAlloc ){
  46573. pcache1FreePage(pPage);
  46574. pPage = 0;
  46575. }else{
  46576. pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
  46577. }
  46578. }
  46579. /* Step 5. If a usable page buffer has still not been found,
  46580. ** attempt to allocate a new one.
  46581. */
  46582. if( !pPage ){
  46583. pPage = pcache1AllocPage(pCache, createFlag==1);
  46584. }
  46585. if( pPage ){
  46586. unsigned int h = iKey % pCache->nHash;
  46587. pCache->nPage++;
  46588. pPage->iKey = iKey;
  46589. pPage->pNext = pCache->apHash[h];
  46590. pPage->pCache = pCache;
  46591. pPage->pLruNext = 0;
  46592. /* pPage->pLruPrev = 0;
  46593. ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */
  46594. *(void **)pPage->page.pExtra = 0;
  46595. pCache->apHash[h] = pPage;
  46596. if( iKey>pCache->iMaxKey ){
  46597. pCache->iMaxKey = iKey;
  46598. }
  46599. }
  46600. return pPage;
  46601. }
  46602. /*
  46603. ** Implementation of the sqlite3_pcache.xFetch method.
  46604. **
  46605. ** Fetch a page by key value.
  46606. **
  46607. ** Whether or not a new page may be allocated by this function depends on
  46608. ** the value of the createFlag argument. 0 means do not allocate a new
  46609. ** page. 1 means allocate a new page if space is easily available. 2
  46610. ** means to try really hard to allocate a new page.
  46611. **
  46612. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  46613. ** database) there is really no difference between createFlag 1 and 2. So
  46614. ** the calling function (pcache.c) will never have a createFlag of 1 on
  46615. ** a non-purgeable cache.
  46616. **
  46617. ** There are three different approaches to obtaining space for a page,
  46618. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  46619. **
  46620. ** 1. Regardless of the value of createFlag, the cache is searched for a
  46621. ** copy of the requested page. If one is found, it is returned.
  46622. **
  46623. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  46624. ** returned.
  46625. **
  46626. ** 3. If createFlag is 1, and the page is not already in the cache, then
  46627. ** return NULL (do not allocate a new page) if any of the following
  46628. ** conditions are true:
  46629. **
  46630. ** (a) the number of pages pinned by the cache is greater than
  46631. ** PCache1.nMax, or
  46632. **
  46633. ** (b) the number of pages pinned by the cache is greater than
  46634. ** the sum of nMax for all purgeable caches, less the sum of
  46635. ** nMin for all other purgeable caches, or
  46636. **
  46637. ** 4. If none of the first three conditions apply and the cache is marked
  46638. ** as purgeable, and if one of the following is true:
  46639. **
  46640. ** (a) The number of pages allocated for the cache is already
  46641. ** PCache1.nMax, or
  46642. **
  46643. ** (b) The number of pages allocated for all purgeable caches is
  46644. ** already equal to or greater than the sum of nMax for all
  46645. ** purgeable caches,
  46646. **
  46647. ** (c) The system is under memory pressure and wants to avoid
  46648. ** unnecessary pages cache entry allocations
  46649. **
  46650. ** then attempt to recycle a page from the LRU list. If it is the right
  46651. ** size, return the recycled buffer. Otherwise, free the buffer and
  46652. ** proceed to step 5.
  46653. **
  46654. ** 5. Otherwise, allocate and return a new page buffer.
  46655. **
  46656. ** There are two versions of this routine. pcache1FetchWithMutex() is
  46657. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  46658. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  46659. ** invokes the appropriate routine.
  46660. */
  46661. static PgHdr1 *pcache1FetchNoMutex(
  46662. sqlite3_pcache *p,
  46663. unsigned int iKey,
  46664. int createFlag
  46665. ){
  46666. PCache1 *pCache = (PCache1 *)p;
  46667. PgHdr1 *pPage = 0;
  46668. /* Step 1: Search the hash table for an existing entry. */
  46669. pPage = pCache->apHash[iKey % pCache->nHash];
  46670. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  46671. /* Step 2: If the page was found in the hash table, then return it.
  46672. ** If the page was not in the hash table and createFlag is 0, abort.
  46673. ** Otherwise (page not in hash and createFlag!=0) continue with
  46674. ** subsequent steps to try to create the page. */
  46675. if( pPage ){
  46676. if( PAGE_IS_UNPINNED(pPage) ){
  46677. return pcache1PinPage(pPage);
  46678. }else{
  46679. return pPage;
  46680. }
  46681. }else if( createFlag ){
  46682. /* Steps 3, 4, and 5 implemented by this subroutine */
  46683. return pcache1FetchStage2(pCache, iKey, createFlag);
  46684. }else{
  46685. return 0;
  46686. }
  46687. }
  46688. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  46689. static PgHdr1 *pcache1FetchWithMutex(
  46690. sqlite3_pcache *p,
  46691. unsigned int iKey,
  46692. int createFlag
  46693. ){
  46694. PCache1 *pCache = (PCache1 *)p;
  46695. PgHdr1 *pPage;
  46696. pcache1EnterMutex(pCache->pGroup);
  46697. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  46698. assert( pPage==0 || pCache->iMaxKey>=iKey );
  46699. pcache1LeaveMutex(pCache->pGroup);
  46700. return pPage;
  46701. }
  46702. #endif
  46703. static sqlite3_pcache_page *pcache1Fetch(
  46704. sqlite3_pcache *p,
  46705. unsigned int iKey,
  46706. int createFlag
  46707. ){
  46708. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  46709. PCache1 *pCache = (PCache1 *)p;
  46710. #endif
  46711. assert( offsetof(PgHdr1,page)==0 );
  46712. assert( pCache->bPurgeable || createFlag!=1 );
  46713. assert( pCache->bPurgeable || pCache->nMin==0 );
  46714. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  46715. assert( pCache->nMin==0 || pCache->bPurgeable );
  46716. assert( pCache->nHash>0 );
  46717. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  46718. if( pCache->pGroup->mutex ){
  46719. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  46720. }else
  46721. #endif
  46722. {
  46723. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  46724. }
  46725. }
  46726. /*
  46727. ** Implementation of the sqlite3_pcache.xUnpin method.
  46728. **
  46729. ** Mark a page as unpinned (eligible for asynchronous recycling).
  46730. */
  46731. static void pcache1Unpin(
  46732. sqlite3_pcache *p,
  46733. sqlite3_pcache_page *pPg,
  46734. int reuseUnlikely
  46735. ){
  46736. PCache1 *pCache = (PCache1 *)p;
  46737. PgHdr1 *pPage = (PgHdr1 *)pPg;
  46738. PGroup *pGroup = pCache->pGroup;
  46739. assert( pPage->pCache==pCache );
  46740. pcache1EnterMutex(pGroup);
  46741. /* It is an error to call this function if the page is already
  46742. ** part of the PGroup LRU list.
  46743. */
  46744. assert( pPage->pLruNext==0 );
  46745. assert( PAGE_IS_PINNED(pPage) );
  46746. if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
  46747. pcache1RemoveFromHash(pPage, 1);
  46748. }else{
  46749. /* Add the page to the PGroup LRU list. */
  46750. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  46751. pPage->pLruPrev = &pGroup->lru;
  46752. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  46753. *ppFirst = pPage;
  46754. pCache->nRecyclable++;
  46755. }
  46756. pcache1LeaveMutex(pCache->pGroup);
  46757. }
  46758. /*
  46759. ** Implementation of the sqlite3_pcache.xRekey method.
  46760. */
  46761. static void pcache1Rekey(
  46762. sqlite3_pcache *p,
  46763. sqlite3_pcache_page *pPg,
  46764. unsigned int iOld,
  46765. unsigned int iNew
  46766. ){
  46767. PCache1 *pCache = (PCache1 *)p;
  46768. PgHdr1 *pPage = (PgHdr1 *)pPg;
  46769. PgHdr1 **pp;
  46770. unsigned int h;
  46771. assert( pPage->iKey==iOld );
  46772. assert( pPage->pCache==pCache );
  46773. pcache1EnterMutex(pCache->pGroup);
  46774. h = iOld%pCache->nHash;
  46775. pp = &pCache->apHash[h];
  46776. while( (*pp)!=pPage ){
  46777. pp = &(*pp)->pNext;
  46778. }
  46779. *pp = pPage->pNext;
  46780. h = iNew%pCache->nHash;
  46781. pPage->iKey = iNew;
  46782. pPage->pNext = pCache->apHash[h];
  46783. pCache->apHash[h] = pPage;
  46784. if( iNew>pCache->iMaxKey ){
  46785. pCache->iMaxKey = iNew;
  46786. }
  46787. pcache1LeaveMutex(pCache->pGroup);
  46788. }
  46789. /*
  46790. ** Implementation of the sqlite3_pcache.xTruncate method.
  46791. **
  46792. ** Discard all unpinned pages in the cache with a page number equal to
  46793. ** or greater than parameter iLimit. Any pinned pages with a page number
  46794. ** equal to or greater than iLimit are implicitly unpinned.
  46795. */
  46796. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  46797. PCache1 *pCache = (PCache1 *)p;
  46798. pcache1EnterMutex(pCache->pGroup);
  46799. if( iLimit<=pCache->iMaxKey ){
  46800. pcache1TruncateUnsafe(pCache, iLimit);
  46801. pCache->iMaxKey = iLimit-1;
  46802. }
  46803. pcache1LeaveMutex(pCache->pGroup);
  46804. }
  46805. /*
  46806. ** Implementation of the sqlite3_pcache.xDestroy method.
  46807. **
  46808. ** Destroy a cache allocated using pcache1Create().
  46809. */
  46810. static void pcache1Destroy(sqlite3_pcache *p){
  46811. PCache1 *pCache = (PCache1 *)p;
  46812. PGroup *pGroup = pCache->pGroup;
  46813. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  46814. pcache1EnterMutex(pGroup);
  46815. if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
  46816. assert( pGroup->nMaxPage >= pCache->nMax );
  46817. pGroup->nMaxPage -= pCache->nMax;
  46818. assert( pGroup->nMinPage >= pCache->nMin );
  46819. pGroup->nMinPage -= pCache->nMin;
  46820. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  46821. pcache1EnforceMaxPage(pCache);
  46822. pcache1LeaveMutex(pGroup);
  46823. sqlite3_free(pCache->pBulk);
  46824. sqlite3_free(pCache->apHash);
  46825. sqlite3_free(pCache);
  46826. }
  46827. /*
  46828. ** This function is called during initialization (sqlite3_initialize()) to
  46829. ** install the default pluggable cache module, assuming the user has not
  46830. ** already provided an alternative.
  46831. */
  46832. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  46833. static const sqlite3_pcache_methods2 defaultMethods = {
  46834. 1, /* iVersion */
  46835. 0, /* pArg */
  46836. pcache1Init, /* xInit */
  46837. pcache1Shutdown, /* xShutdown */
  46838. pcache1Create, /* xCreate */
  46839. pcache1Cachesize, /* xCachesize */
  46840. pcache1Pagecount, /* xPagecount */
  46841. pcache1Fetch, /* xFetch */
  46842. pcache1Unpin, /* xUnpin */
  46843. pcache1Rekey, /* xRekey */
  46844. pcache1Truncate, /* xTruncate */
  46845. pcache1Destroy, /* xDestroy */
  46846. pcache1Shrink /* xShrink */
  46847. };
  46848. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  46849. }
  46850. /*
  46851. ** Return the size of the header on each page of this PCACHE implementation.
  46852. */
  46853. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  46854. /*
  46855. ** Return the global mutex used by this PCACHE implementation. The
  46856. ** sqlite3_status() routine needs access to this mutex.
  46857. */
  46858. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  46859. return pcache1.mutex;
  46860. }
  46861. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  46862. /*
  46863. ** This function is called to free superfluous dynamically allocated memory
  46864. ** held by the pager system. Memory in use by any SQLite pager allocated
  46865. ** by the current thread may be sqlite3_free()ed.
  46866. **
  46867. ** nReq is the number of bytes of memory required. Once this much has
  46868. ** been released, the function returns. The return value is the total number
  46869. ** of bytes of memory released.
  46870. */
  46871. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  46872. int nFree = 0;
  46873. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  46874. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  46875. if( sqlite3GlobalConfig.pPage==0 ){
  46876. PgHdr1 *p;
  46877. pcache1EnterMutex(&pcache1.grp);
  46878. while( (nReq<0 || nFree<nReq)
  46879. && (p=pcache1.grp.lru.pLruPrev)!=0
  46880. && p->isAnchor==0
  46881. ){
  46882. nFree += pcache1MemSize(p->page.pBuf);
  46883. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  46884. nFree += sqlite3MemSize(p);
  46885. #endif
  46886. assert( PAGE_IS_UNPINNED(p) );
  46887. pcache1PinPage(p);
  46888. pcache1RemoveFromHash(p, 1);
  46889. }
  46890. pcache1LeaveMutex(&pcache1.grp);
  46891. }
  46892. return nFree;
  46893. }
  46894. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  46895. #ifdef SQLITE_TEST
  46896. /*
  46897. ** This function is used by test procedures to inspect the internal state
  46898. ** of the global cache.
  46899. */
  46900. SQLITE_PRIVATE void sqlite3PcacheStats(
  46901. int *pnCurrent, /* OUT: Total number of pages cached */
  46902. int *pnMax, /* OUT: Global maximum cache size */
  46903. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  46904. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  46905. ){
  46906. PgHdr1 *p;
  46907. int nRecyclable = 0;
  46908. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  46909. assert( PAGE_IS_UNPINNED(p) );
  46910. nRecyclable++;
  46911. }
  46912. *pnCurrent = pcache1.grp.nPurgeable;
  46913. *pnMax = (int)pcache1.grp.nMaxPage;
  46914. *pnMin = (int)pcache1.grp.nMinPage;
  46915. *pnRecyclable = nRecyclable;
  46916. }
  46917. #endif
  46918. /************** End of pcache1.c *********************************************/
  46919. /************** Begin file rowset.c ******************************************/
  46920. /*
  46921. ** 2008 December 3
  46922. **
  46923. ** The author disclaims copyright to this source code. In place of
  46924. ** a legal notice, here is a blessing:
  46925. **
  46926. ** May you do good and not evil.
  46927. ** May you find forgiveness for yourself and forgive others.
  46928. ** May you share freely, never taking more than you give.
  46929. **
  46930. *************************************************************************
  46931. **
  46932. ** This module implements an object we call a "RowSet".
  46933. **
  46934. ** The RowSet object is a collection of rowids. Rowids
  46935. ** are inserted into the RowSet in an arbitrary order. Inserts
  46936. ** can be intermixed with tests to see if a given rowid has been
  46937. ** previously inserted into the RowSet.
  46938. **
  46939. ** After all inserts are finished, it is possible to extract the
  46940. ** elements of the RowSet in sorted order. Once this extraction
  46941. ** process has started, no new elements may be inserted.
  46942. **
  46943. ** Hence, the primitive operations for a RowSet are:
  46944. **
  46945. ** CREATE
  46946. ** INSERT
  46947. ** TEST
  46948. ** SMALLEST
  46949. ** DESTROY
  46950. **
  46951. ** The CREATE and DESTROY primitives are the constructor and destructor,
  46952. ** obviously. The INSERT primitive adds a new element to the RowSet.
  46953. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  46954. ** extracts the least value from the RowSet.
  46955. **
  46956. ** The INSERT primitive might allocate additional memory. Memory is
  46957. ** allocated in chunks so most INSERTs do no allocation. There is an
  46958. ** upper bound on the size of allocated memory. No memory is freed
  46959. ** until DESTROY.
  46960. **
  46961. ** The TEST primitive includes a "batch" number. The TEST primitive
  46962. ** will only see elements that were inserted before the last change
  46963. ** in the batch number. In other words, if an INSERT occurs between
  46964. ** two TESTs where the TESTs have the same batch nubmer, then the
  46965. ** value added by the INSERT will not be visible to the second TEST.
  46966. ** The initial batch number is zero, so if the very first TEST contains
  46967. ** a non-zero batch number, it will see all prior INSERTs.
  46968. **
  46969. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  46970. ** that is attempted.
  46971. **
  46972. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  46973. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  46974. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  46975. ** The cost of a TEST using the same batch number is O(logN). The cost
  46976. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  46977. ** primitives are constant time. The cost of DESTROY is O(N).
  46978. **
  46979. ** TEST and SMALLEST may not be used by the same RowSet. This used to
  46980. ** be possible, but the feature was not used, so it was removed in order
  46981. ** to simplify the code.
  46982. */
  46983. /* #include "sqliteInt.h" */
  46984. /*
  46985. ** Target size for allocation chunks.
  46986. */
  46987. #define ROWSET_ALLOCATION_SIZE 1024
  46988. /*
  46989. ** The number of rowset entries per allocation chunk.
  46990. */
  46991. #define ROWSET_ENTRY_PER_CHUNK \
  46992. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  46993. /*
  46994. ** Each entry in a RowSet is an instance of the following object.
  46995. **
  46996. ** This same object is reused to store a linked list of trees of RowSetEntry
  46997. ** objects. In that alternative use, pRight points to the next entry
  46998. ** in the list, pLeft points to the tree, and v is unused. The
  46999. ** RowSet.pForest value points to the head of this forest list.
  47000. */
  47001. struct RowSetEntry {
  47002. i64 v; /* ROWID value for this entry */
  47003. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  47004. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  47005. };
  47006. /*
  47007. ** RowSetEntry objects are allocated in large chunks (instances of the
  47008. ** following structure) to reduce memory allocation overhead. The
  47009. ** chunks are kept on a linked list so that they can be deallocated
  47010. ** when the RowSet is destroyed.
  47011. */
  47012. struct RowSetChunk {
  47013. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  47014. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  47015. };
  47016. /*
  47017. ** A RowSet in an instance of the following structure.
  47018. **
  47019. ** A typedef of this structure if found in sqliteInt.h.
  47020. */
  47021. struct RowSet {
  47022. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  47023. sqlite3 *db; /* The database connection */
  47024. struct RowSetEntry *pEntry; /* List of entries using pRight */
  47025. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  47026. struct RowSetEntry *pFresh; /* Source of new entry objects */
  47027. struct RowSetEntry *pForest; /* List of binary trees of entries */
  47028. u16 nFresh; /* Number of objects on pFresh */
  47029. u16 rsFlags; /* Various flags */
  47030. int iBatch; /* Current insert batch */
  47031. };
  47032. /*
  47033. ** Allowed values for RowSet.rsFlags
  47034. */
  47035. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  47036. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  47037. /*
  47038. ** Allocate a RowSet object. Return NULL if a memory allocation
  47039. ** error occurs.
  47040. */
  47041. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db){
  47042. RowSet *p = sqlite3DbMallocRawNN(db, sizeof(*p));
  47043. if( p ){
  47044. int N = sqlite3DbMallocSize(db, p);
  47045. p->pChunk = 0;
  47046. p->db = db;
  47047. p->pEntry = 0;
  47048. p->pLast = 0;
  47049. p->pForest = 0;
  47050. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  47051. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  47052. p->rsFlags = ROWSET_SORTED;
  47053. p->iBatch = 0;
  47054. }
  47055. return p;
  47056. }
  47057. /*
  47058. ** Deallocate all chunks from a RowSet. This frees all memory that
  47059. ** the RowSet has allocated over its lifetime. This routine is
  47060. ** the destructor for the RowSet.
  47061. */
  47062. SQLITE_PRIVATE void sqlite3RowSetClear(void *pArg){
  47063. RowSet *p = (RowSet*)pArg;
  47064. struct RowSetChunk *pChunk, *pNextChunk;
  47065. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  47066. pNextChunk = pChunk->pNextChunk;
  47067. sqlite3DbFree(p->db, pChunk);
  47068. }
  47069. p->pChunk = 0;
  47070. p->nFresh = 0;
  47071. p->pEntry = 0;
  47072. p->pLast = 0;
  47073. p->pForest = 0;
  47074. p->rsFlags = ROWSET_SORTED;
  47075. }
  47076. /*
  47077. ** Deallocate all chunks from a RowSet. This frees all memory that
  47078. ** the RowSet has allocated over its lifetime. This routine is
  47079. ** the destructor for the RowSet.
  47080. */
  47081. SQLITE_PRIVATE void sqlite3RowSetDelete(void *pArg){
  47082. sqlite3RowSetClear(pArg);
  47083. sqlite3DbFree(((RowSet*)pArg)->db, pArg);
  47084. }
  47085. /*
  47086. ** Allocate a new RowSetEntry object that is associated with the
  47087. ** given RowSet. Return a pointer to the new and completely uninitialized
  47088. ** objected.
  47089. **
  47090. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  47091. ** routine returns NULL.
  47092. */
  47093. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  47094. assert( p!=0 );
  47095. if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47096. /* We could allocate a fresh RowSetEntry each time one is needed, but it
  47097. ** is more efficient to pull a preallocated entry from the pool */
  47098. struct RowSetChunk *pNew;
  47099. pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
  47100. if( pNew==0 ){
  47101. return 0;
  47102. }
  47103. pNew->pNextChunk = p->pChunk;
  47104. p->pChunk = pNew;
  47105. p->pFresh = pNew->aEntry;
  47106. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  47107. }
  47108. p->nFresh--;
  47109. return p->pFresh++;
  47110. }
  47111. /*
  47112. ** Insert a new value into a RowSet.
  47113. **
  47114. ** The mallocFailed flag of the database connection is set if a
  47115. ** memory allocation fails.
  47116. */
  47117. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  47118. struct RowSetEntry *pEntry; /* The new entry */
  47119. struct RowSetEntry *pLast; /* The last prior entry */
  47120. /* This routine is never called after sqlite3RowSetNext() */
  47121. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  47122. pEntry = rowSetEntryAlloc(p);
  47123. if( pEntry==0 ) return;
  47124. pEntry->v = rowid;
  47125. pEntry->pRight = 0;
  47126. pLast = p->pLast;
  47127. if( pLast ){
  47128. if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
  47129. /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
  47130. ** where possible */
  47131. p->rsFlags &= ~ROWSET_SORTED;
  47132. }
  47133. pLast->pRight = pEntry;
  47134. }else{
  47135. p->pEntry = pEntry;
  47136. }
  47137. p->pLast = pEntry;
  47138. }
  47139. /*
  47140. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  47141. **
  47142. ** The input lists are connected via pRight pointers and are
  47143. ** assumed to each already be in sorted order.
  47144. */
  47145. static struct RowSetEntry *rowSetEntryMerge(
  47146. struct RowSetEntry *pA, /* First sorted list to be merged */
  47147. struct RowSetEntry *pB /* Second sorted list to be merged */
  47148. ){
  47149. struct RowSetEntry head;
  47150. struct RowSetEntry *pTail;
  47151. pTail = &head;
  47152. assert( pA!=0 && pB!=0 );
  47153. for(;;){
  47154. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  47155. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  47156. if( pA->v<=pB->v ){
  47157. if( pA->v<pB->v ) pTail = pTail->pRight = pA;
  47158. pA = pA->pRight;
  47159. if( pA==0 ){
  47160. pTail->pRight = pB;
  47161. break;
  47162. }
  47163. }else{
  47164. pTail = pTail->pRight = pB;
  47165. pB = pB->pRight;
  47166. if( pB==0 ){
  47167. pTail->pRight = pA;
  47168. break;
  47169. }
  47170. }
  47171. }
  47172. return head.pRight;
  47173. }
  47174. /*
  47175. ** Sort all elements on the list of RowSetEntry objects into order of
  47176. ** increasing v.
  47177. */
  47178. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  47179. unsigned int i;
  47180. struct RowSetEntry *pNext, *aBucket[40];
  47181. memset(aBucket, 0, sizeof(aBucket));
  47182. while( pIn ){
  47183. pNext = pIn->pRight;
  47184. pIn->pRight = 0;
  47185. for(i=0; aBucket[i]; i++){
  47186. pIn = rowSetEntryMerge(aBucket[i], pIn);
  47187. aBucket[i] = 0;
  47188. }
  47189. aBucket[i] = pIn;
  47190. pIn = pNext;
  47191. }
  47192. pIn = aBucket[0];
  47193. for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  47194. if( aBucket[i]==0 ) continue;
  47195. pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
  47196. }
  47197. return pIn;
  47198. }
  47199. /*
  47200. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  47201. ** Convert this tree into a linked list connected by the pRight pointers
  47202. ** and return pointers to the first and last elements of the new list.
  47203. */
  47204. static void rowSetTreeToList(
  47205. struct RowSetEntry *pIn, /* Root of the input tree */
  47206. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  47207. struct RowSetEntry **ppLast /* Write tail of the output list here */
  47208. ){
  47209. assert( pIn!=0 );
  47210. if( pIn->pLeft ){
  47211. struct RowSetEntry *p;
  47212. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  47213. p->pRight = pIn;
  47214. }else{
  47215. *ppFirst = pIn;
  47216. }
  47217. if( pIn->pRight ){
  47218. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  47219. }else{
  47220. *ppLast = pIn;
  47221. }
  47222. assert( (*ppLast)->pRight==0 );
  47223. }
  47224. /*
  47225. ** Convert a sorted list of elements (connected by pRight) into a binary
  47226. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  47227. ** node taken from the head of *ppList. A depth of 2 means a tree with
  47228. ** three nodes. And so forth.
  47229. **
  47230. ** Use as many entries from the input list as required and update the
  47231. ** *ppList to point to the unused elements of the list. If the input
  47232. ** list contains too few elements, then construct an incomplete tree
  47233. ** and leave *ppList set to NULL.
  47234. **
  47235. ** Return a pointer to the root of the constructed binary tree.
  47236. */
  47237. static struct RowSetEntry *rowSetNDeepTree(
  47238. struct RowSetEntry **ppList,
  47239. int iDepth
  47240. ){
  47241. struct RowSetEntry *p; /* Root of the new tree */
  47242. struct RowSetEntry *pLeft; /* Left subtree */
  47243. if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
  47244. /* Prevent unnecessary deep recursion when we run out of entries */
  47245. return 0;
  47246. }
  47247. if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
  47248. /* This branch causes a *balanced* tree to be generated. A valid tree
  47249. ** is still generated without this branch, but the tree is wildly
  47250. ** unbalanced and inefficient. */
  47251. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  47252. p = *ppList;
  47253. if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47254. /* It is safe to always return here, but the resulting tree
  47255. ** would be unbalanced */
  47256. return pLeft;
  47257. }
  47258. p->pLeft = pLeft;
  47259. *ppList = p->pRight;
  47260. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  47261. }else{
  47262. p = *ppList;
  47263. *ppList = p->pRight;
  47264. p->pLeft = p->pRight = 0;
  47265. }
  47266. return p;
  47267. }
  47268. /*
  47269. ** Convert a sorted list of elements into a binary tree. Make the tree
  47270. ** as deep as it needs to be in order to contain the entire list.
  47271. */
  47272. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  47273. int iDepth; /* Depth of the tree so far */
  47274. struct RowSetEntry *p; /* Current tree root */
  47275. struct RowSetEntry *pLeft; /* Left subtree */
  47276. assert( pList!=0 );
  47277. p = pList;
  47278. pList = p->pRight;
  47279. p->pLeft = p->pRight = 0;
  47280. for(iDepth=1; pList; iDepth++){
  47281. pLeft = p;
  47282. p = pList;
  47283. pList = p->pRight;
  47284. p->pLeft = pLeft;
  47285. p->pRight = rowSetNDeepTree(&pList, iDepth);
  47286. }
  47287. return p;
  47288. }
  47289. /*
  47290. ** Extract the smallest element from the RowSet.
  47291. ** Write the element into *pRowid. Return 1 on success. Return
  47292. ** 0 if the RowSet is already empty.
  47293. **
  47294. ** After this routine has been called, the sqlite3RowSetInsert()
  47295. ** routine may not be called again.
  47296. **
  47297. ** This routine may not be called after sqlite3RowSetTest() has
  47298. ** been used. Older versions of RowSet allowed that, but as the
  47299. ** capability was not used by the code generator, it was removed
  47300. ** for code economy.
  47301. */
  47302. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  47303. assert( p!=0 );
  47304. assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
  47305. /* Merge the forest into a single sorted list on first call */
  47306. if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47307. if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47308. p->pEntry = rowSetEntrySort(p->pEntry);
  47309. }
  47310. p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
  47311. }
  47312. /* Return the next entry on the list */
  47313. if( p->pEntry ){
  47314. *pRowid = p->pEntry->v;
  47315. p->pEntry = p->pEntry->pRight;
  47316. if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
  47317. /* Free memory immediately, rather than waiting on sqlite3_finalize() */
  47318. sqlite3RowSetClear(p);
  47319. }
  47320. return 1;
  47321. }else{
  47322. return 0;
  47323. }
  47324. }
  47325. /*
  47326. ** Check to see if element iRowid was inserted into the rowset as
  47327. ** part of any insert batch prior to iBatch. Return 1 or 0.
  47328. **
  47329. ** If this is the first test of a new batch and if there exist entries
  47330. ** on pRowSet->pEntry, then sort those entries into the forest at
  47331. ** pRowSet->pForest so that they can be tested.
  47332. */
  47333. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  47334. struct RowSetEntry *p, *pTree;
  47335. /* This routine is never called after sqlite3RowSetNext() */
  47336. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  47337. /* Sort entries into the forest on the first test of a new batch.
  47338. ** To save unnecessary work, only do this when the batch number changes.
  47339. */
  47340. if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
  47341. p = pRowSet->pEntry;
  47342. if( p ){
  47343. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  47344. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  47345. /* Only sort the current set of entiries if they need it */
  47346. p = rowSetEntrySort(p);
  47347. }
  47348. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  47349. ppPrevTree = &pTree->pRight;
  47350. if( pTree->pLeft==0 ){
  47351. pTree->pLeft = rowSetListToTree(p);
  47352. break;
  47353. }else{
  47354. struct RowSetEntry *pAux, *pTail;
  47355. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  47356. pTree->pLeft = 0;
  47357. p = rowSetEntryMerge(pAux, p);
  47358. }
  47359. }
  47360. if( pTree==0 ){
  47361. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  47362. if( pTree ){
  47363. pTree->v = 0;
  47364. pTree->pRight = 0;
  47365. pTree->pLeft = rowSetListToTree(p);
  47366. }
  47367. }
  47368. pRowSet->pEntry = 0;
  47369. pRowSet->pLast = 0;
  47370. pRowSet->rsFlags |= ROWSET_SORTED;
  47371. }
  47372. pRowSet->iBatch = iBatch;
  47373. }
  47374. /* Test to see if the iRowid value appears anywhere in the forest.
  47375. ** Return 1 if it does and 0 if not.
  47376. */
  47377. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  47378. p = pTree->pLeft;
  47379. while( p ){
  47380. if( p->v<iRowid ){
  47381. p = p->pRight;
  47382. }else if( p->v>iRowid ){
  47383. p = p->pLeft;
  47384. }else{
  47385. return 1;
  47386. }
  47387. }
  47388. }
  47389. return 0;
  47390. }
  47391. /************** End of rowset.c **********************************************/
  47392. /************** Begin file pager.c *******************************************/
  47393. /*
  47394. ** 2001 September 15
  47395. **
  47396. ** The author disclaims copyright to this source code. In place of
  47397. ** a legal notice, here is a blessing:
  47398. **
  47399. ** May you do good and not evil.
  47400. ** May you find forgiveness for yourself and forgive others.
  47401. ** May you share freely, never taking more than you give.
  47402. **
  47403. *************************************************************************
  47404. ** This is the implementation of the page cache subsystem or "pager".
  47405. **
  47406. ** The pager is used to access a database disk file. It implements
  47407. ** atomic commit and rollback through the use of a journal file that
  47408. ** is separate from the database file. The pager also implements file
  47409. ** locking to prevent two processes from writing the same database
  47410. ** file simultaneously, or one process from reading the database while
  47411. ** another is writing.
  47412. */
  47413. #ifndef SQLITE_OMIT_DISKIO
  47414. /* #include "sqliteInt.h" */
  47415. /************** Include wal.h in the middle of pager.c ***********************/
  47416. /************** Begin file wal.h *********************************************/
  47417. /*
  47418. ** 2010 February 1
  47419. **
  47420. ** The author disclaims copyright to this source code. In place of
  47421. ** a legal notice, here is a blessing:
  47422. **
  47423. ** May you do good and not evil.
  47424. ** May you find forgiveness for yourself and forgive others.
  47425. ** May you share freely, never taking more than you give.
  47426. **
  47427. *************************************************************************
  47428. ** This header file defines the interface to the write-ahead logging
  47429. ** system. Refer to the comments below and the header comment attached to
  47430. ** the implementation of each function in log.c for further details.
  47431. */
  47432. #ifndef SQLITE_WAL_H
  47433. #define SQLITE_WAL_H
  47434. /* #include "sqliteInt.h" */
  47435. /* Macros for extracting appropriate sync flags for either transaction
  47436. ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
  47437. */
  47438. #define WAL_SYNC_FLAGS(X) ((X)&0x03)
  47439. #define CKPT_SYNC_FLAGS(X) (((X)>>2)&0x03)
  47440. #ifdef SQLITE_OMIT_WAL
  47441. # define sqlite3WalOpen(x,y,z) 0
  47442. # define sqlite3WalLimit(x,y)
  47443. # define sqlite3WalClose(v,w,x,y,z) 0
  47444. # define sqlite3WalBeginReadTransaction(y,z) 0
  47445. # define sqlite3WalEndReadTransaction(z)
  47446. # define sqlite3WalDbsize(y) 0
  47447. # define sqlite3WalBeginWriteTransaction(y) 0
  47448. # define sqlite3WalEndWriteTransaction(x) 0
  47449. # define sqlite3WalUndo(x,y,z) 0
  47450. # define sqlite3WalSavepoint(y,z)
  47451. # define sqlite3WalSavepointUndo(y,z) 0
  47452. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  47453. # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
  47454. # define sqlite3WalCallback(z) 0
  47455. # define sqlite3WalExclusiveMode(y,z) 0
  47456. # define sqlite3WalHeapMemory(z) 0
  47457. # define sqlite3WalFramesize(z) 0
  47458. # define sqlite3WalFindFrame(x,y,z) 0
  47459. # define sqlite3WalFile(x) 0
  47460. #else
  47461. #define WAL_SAVEPOINT_NDATA 4
  47462. /* Connection to a write-ahead log (WAL) file.
  47463. ** There is one object of this type for each pager.
  47464. */
  47465. typedef struct Wal Wal;
  47466. /* Open and close a connection to a write-ahead log. */
  47467. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  47468. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
  47469. /* Set the limiting size of a WAL file. */
  47470. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  47471. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  47472. ** snapshot is like a read-transaction. It is the state of the database
  47473. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  47474. ** preserves the current state even if the other threads or processes
  47475. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  47476. ** transaction and releases the lock.
  47477. */
  47478. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  47479. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  47480. /* Read a page from the write-ahead log, if it is present. */
  47481. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  47482. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  47483. /* If the WAL is not empty, return the size of the database. */
  47484. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  47485. /* Obtain or release the WRITER lock. */
  47486. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  47487. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  47488. /* Undo any frames written (but not committed) to the log */
  47489. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  47490. /* Return an integer that records the current (uncommitted) write
  47491. ** position in the WAL */
  47492. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  47493. /* Move the write position of the WAL back to iFrame. Called in
  47494. ** response to a ROLLBACK TO command. */
  47495. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  47496. /* Write a frame or frames to the log. */
  47497. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  47498. /* Copy pages from the log to the database file */
  47499. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  47500. Wal *pWal, /* Write-ahead log connection */
  47501. sqlite3 *db, /* Check this handle's interrupt flag */
  47502. int eMode, /* One of PASSIVE, FULL and RESTART */
  47503. int (*xBusy)(void*), /* Function to call when busy */
  47504. void *pBusyArg, /* Context argument for xBusyHandler */
  47505. int sync_flags, /* Flags to sync db file with (or 0) */
  47506. int nBuf, /* Size of buffer nBuf */
  47507. u8 *zBuf, /* Temporary buffer to use */
  47508. int *pnLog, /* OUT: Number of frames in WAL */
  47509. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  47510. );
  47511. /* Return the value to pass to a sqlite3_wal_hook callback, the
  47512. ** number of frames in the WAL at the point of the last commit since
  47513. ** sqlite3WalCallback() was called. If no commits have occurred since
  47514. ** the last call, then return 0.
  47515. */
  47516. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  47517. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  47518. ** by the pager layer on the database file.
  47519. */
  47520. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  47521. /* Return true if the argument is non-NULL and the WAL module is using
  47522. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  47523. ** WAL module is using shared-memory, return false.
  47524. */
  47525. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  47526. #ifdef SQLITE_ENABLE_SNAPSHOT
  47527. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
  47528. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
  47529. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
  47530. SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot);
  47531. SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal);
  47532. #endif
  47533. #ifdef SQLITE_ENABLE_ZIPVFS
  47534. /* If the WAL file is not empty, return the number of bytes of content
  47535. ** stored in each frame (i.e. the db page-size when the WAL was created).
  47536. */
  47537. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  47538. #endif
  47539. /* Return the sqlite3_file object for the WAL file */
  47540. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
  47541. #endif /* ifndef SQLITE_OMIT_WAL */
  47542. #endif /* SQLITE_WAL_H */
  47543. /************** End of wal.h *************************************************/
  47544. /************** Continuing where we left off in pager.c **********************/
  47545. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  47546. **
  47547. ** This comment block describes invariants that hold when using a rollback
  47548. ** journal. These invariants do not apply for journal_mode=WAL,
  47549. ** journal_mode=MEMORY, or journal_mode=OFF.
  47550. **
  47551. ** Within this comment block, a page is deemed to have been synced
  47552. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  47553. ** Otherwise, the page is not synced until the xSync method of the VFS
  47554. ** is called successfully on the file containing the page.
  47555. **
  47556. ** Definition: A page of the database file is said to be "overwriteable" if
  47557. ** one or more of the following are true about the page:
  47558. **
  47559. ** (a) The original content of the page as it was at the beginning of
  47560. ** the transaction has been written into the rollback journal and
  47561. ** synced.
  47562. **
  47563. ** (b) The page was a freelist leaf page at the start of the transaction.
  47564. **
  47565. ** (c) The page number is greater than the largest page that existed in
  47566. ** the database file at the start of the transaction.
  47567. **
  47568. ** (1) A page of the database file is never overwritten unless one of the
  47569. ** following are true:
  47570. **
  47571. ** (a) The page and all other pages on the same sector are overwriteable.
  47572. **
  47573. ** (b) The atomic page write optimization is enabled, and the entire
  47574. ** transaction other than the update of the transaction sequence
  47575. ** number consists of a single page change.
  47576. **
  47577. ** (2) The content of a page written into the rollback journal exactly matches
  47578. ** both the content in the database when the rollback journal was written
  47579. ** and the content in the database at the beginning of the current
  47580. ** transaction.
  47581. **
  47582. ** (3) Writes to the database file are an integer multiple of the page size
  47583. ** in length and are aligned on a page boundary.
  47584. **
  47585. ** (4) Reads from the database file are either aligned on a page boundary and
  47586. ** an integer multiple of the page size in length or are taken from the
  47587. ** first 100 bytes of the database file.
  47588. **
  47589. ** (5) All writes to the database file are synced prior to the rollback journal
  47590. ** being deleted, truncated, or zeroed.
  47591. **
  47592. ** (6) If a master journal file is used, then all writes to the database file
  47593. ** are synced prior to the master journal being deleted.
  47594. **
  47595. ** Definition: Two databases (or the same database at two points it time)
  47596. ** are said to be "logically equivalent" if they give the same answer to
  47597. ** all queries. Note in particular the content of freelist leaf
  47598. ** pages can be changed arbitrarily without affecting the logical equivalence
  47599. ** of the database.
  47600. **
  47601. ** (7) At any time, if any subset, including the empty set and the total set,
  47602. ** of the unsynced changes to a rollback journal are removed and the
  47603. ** journal is rolled back, the resulting database file will be logically
  47604. ** equivalent to the database file at the beginning of the transaction.
  47605. **
  47606. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  47607. ** is called to restore the database file to the same size it was at
  47608. ** the beginning of the transaction. (In some VFSes, the xTruncate
  47609. ** method is a no-op, but that does not change the fact the SQLite will
  47610. ** invoke it.)
  47611. **
  47612. ** (9) Whenever the database file is modified, at least one bit in the range
  47613. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  47614. ** the EXCLUSIVE lock, thus signaling other connections on the same
  47615. ** database to flush their caches.
  47616. **
  47617. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  47618. ** than one billion transactions.
  47619. **
  47620. ** (11) A database file is well-formed at the beginning and at the conclusion
  47621. ** of every transaction.
  47622. **
  47623. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  47624. ** the database file.
  47625. **
  47626. ** (13) A SHARED lock is held on the database file while reading any
  47627. ** content out of the database file.
  47628. **
  47629. ******************************************************************************/
  47630. /*
  47631. ** Macros for troubleshooting. Normally turned off
  47632. */
  47633. #if 0
  47634. int sqlite3PagerTrace=1; /* True to enable tracing */
  47635. #define sqlite3DebugPrintf printf
  47636. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  47637. #else
  47638. #define PAGERTRACE(X)
  47639. #endif
  47640. /*
  47641. ** The following two macros are used within the PAGERTRACE() macros above
  47642. ** to print out file-descriptors.
  47643. **
  47644. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  47645. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  47646. ** struct as its argument.
  47647. */
  47648. #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
  47649. #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
  47650. /*
  47651. ** The Pager.eState variable stores the current 'state' of a pager. A
  47652. ** pager may be in any one of the seven states shown in the following
  47653. ** state diagram.
  47654. **
  47655. ** OPEN <------+------+
  47656. ** | | |
  47657. ** V | |
  47658. ** +---------> READER-------+ |
  47659. ** | | |
  47660. ** | V |
  47661. ** |<-------WRITER_LOCKED------> ERROR
  47662. ** | | ^
  47663. ** | V |
  47664. ** |<------WRITER_CACHEMOD-------->|
  47665. ** | | |
  47666. ** | V |
  47667. ** |<-------WRITER_DBMOD---------->|
  47668. ** | | |
  47669. ** | V |
  47670. ** +<------WRITER_FINISHED-------->+
  47671. **
  47672. **
  47673. ** List of state transitions and the C [function] that performs each:
  47674. **
  47675. ** OPEN -> READER [sqlite3PagerSharedLock]
  47676. ** READER -> OPEN [pager_unlock]
  47677. **
  47678. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  47679. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  47680. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  47681. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  47682. ** WRITER_*** -> READER [pager_end_transaction]
  47683. **
  47684. ** WRITER_*** -> ERROR [pager_error]
  47685. ** ERROR -> OPEN [pager_unlock]
  47686. **
  47687. **
  47688. ** OPEN:
  47689. **
  47690. ** The pager starts up in this state. Nothing is guaranteed in this
  47691. ** state - the file may or may not be locked and the database size is
  47692. ** unknown. The database may not be read or written.
  47693. **
  47694. ** * No read or write transaction is active.
  47695. ** * Any lock, or no lock at all, may be held on the database file.
  47696. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  47697. **
  47698. ** READER:
  47699. **
  47700. ** In this state all the requirements for reading the database in
  47701. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  47702. ** was) in exclusive-locking mode, a user-level read transaction is
  47703. ** open. The database size is known in this state.
  47704. **
  47705. ** A connection running with locking_mode=normal enters this state when
  47706. ** it opens a read-transaction on the database and returns to state
  47707. ** OPEN after the read-transaction is completed. However a connection
  47708. ** running in locking_mode=exclusive (including temp databases) remains in
  47709. ** this state even after the read-transaction is closed. The only way
  47710. ** a locking_mode=exclusive connection can transition from READER to OPEN
  47711. ** is via the ERROR state (see below).
  47712. **
  47713. ** * A read transaction may be active (but a write-transaction cannot).
  47714. ** * A SHARED or greater lock is held on the database file.
  47715. ** * The dbSize variable may be trusted (even if a user-level read
  47716. ** transaction is not active). The dbOrigSize and dbFileSize variables
  47717. ** may not be trusted at this point.
  47718. ** * If the database is a WAL database, then the WAL connection is open.
  47719. ** * Even if a read-transaction is not open, it is guaranteed that
  47720. ** there is no hot-journal in the file-system.
  47721. **
  47722. ** WRITER_LOCKED:
  47723. **
  47724. ** The pager moves to this state from READER when a write-transaction
  47725. ** is first opened on the database. In WRITER_LOCKED state, all locks
  47726. ** required to start a write-transaction are held, but no actual
  47727. ** modifications to the cache or database have taken place.
  47728. **
  47729. ** In rollback mode, a RESERVED or (if the transaction was opened with
  47730. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  47731. ** moving to this state, but the journal file is not written to or opened
  47732. ** to in this state. If the transaction is committed or rolled back while
  47733. ** in WRITER_LOCKED state, all that is required is to unlock the database
  47734. ** file.
  47735. **
  47736. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  47737. ** If the connection is running with locking_mode=exclusive, an attempt
  47738. ** is made to obtain an EXCLUSIVE lock on the database file.
  47739. **
  47740. ** * A write transaction is active.
  47741. ** * If the connection is open in rollback-mode, a RESERVED or greater
  47742. ** lock is held on the database file.
  47743. ** * If the connection is open in WAL-mode, a WAL write transaction
  47744. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  47745. ** called).
  47746. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  47747. ** * The contents of the pager cache have not been modified.
  47748. ** * The journal file may or may not be open.
  47749. ** * Nothing (not even the first header) has been written to the journal.
  47750. **
  47751. ** WRITER_CACHEMOD:
  47752. **
  47753. ** A pager moves from WRITER_LOCKED state to this state when a page is
  47754. ** first modified by the upper layer. In rollback mode the journal file
  47755. ** is opened (if it is not already open) and a header written to the
  47756. ** start of it. The database file on disk has not been modified.
  47757. **
  47758. ** * A write transaction is active.
  47759. ** * A RESERVED or greater lock is held on the database file.
  47760. ** * The journal file is open and the first header has been written
  47761. ** to it, but the header has not been synced to disk.
  47762. ** * The contents of the page cache have been modified.
  47763. **
  47764. ** WRITER_DBMOD:
  47765. **
  47766. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  47767. ** when it modifies the contents of the database file. WAL connections
  47768. ** never enter this state (since they do not modify the database file,
  47769. ** just the log file).
  47770. **
  47771. ** * A write transaction is active.
  47772. ** * An EXCLUSIVE or greater lock is held on the database file.
  47773. ** * The journal file is open and the first header has been written
  47774. ** and synced to disk.
  47775. ** * The contents of the page cache have been modified (and possibly
  47776. ** written to disk).
  47777. **
  47778. ** WRITER_FINISHED:
  47779. **
  47780. ** It is not possible for a WAL connection to enter this state.
  47781. **
  47782. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  47783. ** state after the entire transaction has been successfully written into the
  47784. ** database file. In this state the transaction may be committed simply
  47785. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  47786. ** not possible to modify the database further. At this point, the upper
  47787. ** layer must either commit or rollback the transaction.
  47788. **
  47789. ** * A write transaction is active.
  47790. ** * An EXCLUSIVE or greater lock is held on the database file.
  47791. ** * All writing and syncing of journal and database data has finished.
  47792. ** If no error occurred, all that remains is to finalize the journal to
  47793. ** commit the transaction. If an error did occur, the caller will need
  47794. ** to rollback the transaction.
  47795. **
  47796. ** ERROR:
  47797. **
  47798. ** The ERROR state is entered when an IO or disk-full error (including
  47799. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  47800. ** difficult to be sure that the in-memory pager state (cache contents,
  47801. ** db size etc.) are consistent with the contents of the file-system.
  47802. **
  47803. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  47804. ** cannot.
  47805. **
  47806. ** For example, if an IO error occurs while performing a rollback,
  47807. ** the contents of the page-cache may be left in an inconsistent state.
  47808. ** At this point it would be dangerous to change back to READER state
  47809. ** (as usually happens after a rollback). Any subsequent readers might
  47810. ** report database corruption (due to the inconsistent cache), and if
  47811. ** they upgrade to writers, they may inadvertently corrupt the database
  47812. ** file. To avoid this hazard, the pager switches into the ERROR state
  47813. ** instead of READER following such an error.
  47814. **
  47815. ** Once it has entered the ERROR state, any attempt to use the pager
  47816. ** to read or write data returns an error. Eventually, once all
  47817. ** outstanding transactions have been abandoned, the pager is able to
  47818. ** transition back to OPEN state, discarding the contents of the
  47819. ** page-cache and any other in-memory state at the same time. Everything
  47820. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  47821. ** when a read-transaction is next opened on the pager (transitioning
  47822. ** the pager into READER state). At that point the system has recovered
  47823. ** from the error.
  47824. **
  47825. ** Specifically, the pager jumps into the ERROR state if:
  47826. **
  47827. ** 1. An error occurs while attempting a rollback. This happens in
  47828. ** function sqlite3PagerRollback().
  47829. **
  47830. ** 2. An error occurs while attempting to finalize a journal file
  47831. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  47832. **
  47833. ** 3. An error occurs while attempting to write to the journal or
  47834. ** database file in function pagerStress() in order to free up
  47835. ** memory.
  47836. **
  47837. ** In other cases, the error is returned to the b-tree layer. The b-tree
  47838. ** layer then attempts a rollback operation. If the error condition
  47839. ** persists, the pager enters the ERROR state via condition (1) above.
  47840. **
  47841. ** Condition (3) is necessary because it can be triggered by a read-only
  47842. ** statement executed within a transaction. In this case, if the error
  47843. ** code were simply returned to the user, the b-tree layer would not
  47844. ** automatically attempt a rollback, as it assumes that an error in a
  47845. ** read-only statement cannot leave the pager in an internally inconsistent
  47846. ** state.
  47847. **
  47848. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  47849. ** * There are one or more outstanding references to pages (after the
  47850. ** last reference is dropped the pager should move back to OPEN state).
  47851. ** * The pager is not an in-memory pager.
  47852. **
  47853. **
  47854. ** Notes:
  47855. **
  47856. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  47857. ** connection is open in WAL mode. A WAL connection is always in one
  47858. ** of the first four states.
  47859. **
  47860. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  47861. ** state. There are two exceptions: immediately after exclusive-mode has
  47862. ** been turned on (and before any read or write transactions are
  47863. ** executed), and when the pager is leaving the "error state".
  47864. **
  47865. ** * See also: assert_pager_state().
  47866. */
  47867. #define PAGER_OPEN 0
  47868. #define PAGER_READER 1
  47869. #define PAGER_WRITER_LOCKED 2
  47870. #define PAGER_WRITER_CACHEMOD 3
  47871. #define PAGER_WRITER_DBMOD 4
  47872. #define PAGER_WRITER_FINISHED 5
  47873. #define PAGER_ERROR 6
  47874. /*
  47875. ** The Pager.eLock variable is almost always set to one of the
  47876. ** following locking-states, according to the lock currently held on
  47877. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  47878. ** This variable is kept up to date as locks are taken and released by
  47879. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  47880. **
  47881. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  47882. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  47883. ** the operation was successful. In these circumstances pagerLockDb() and
  47884. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  47885. ** when unlocking the file, and only updated when locking the file if the
  47886. ** VFS call is successful. This way, the Pager.eLock variable may be set
  47887. ** to a less exclusive (lower) value than the lock that is actually held
  47888. ** at the system level, but it is never set to a more exclusive value.
  47889. **
  47890. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  47891. ** be a few redundant xLock() calls or a lock may be held for longer than
  47892. ** required, but nothing really goes wrong.
  47893. **
  47894. ** The exception is when the database file is unlocked as the pager moves
  47895. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  47896. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  47897. ** transition, by the same pager or any other). If the call to xUnlock()
  47898. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  47899. ** can confuse the call to xCheckReservedLock() call made later as part
  47900. ** of hot-journal detection.
  47901. **
  47902. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  47903. ** lock held by this process or any others". So xCheckReservedLock may
  47904. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  47905. ** doesn't know it because of a previous error in xUnlock). If this happens
  47906. ** a hot-journal may be mistaken for a journal being created by an active
  47907. ** transaction in another process, causing SQLite to read from the database
  47908. ** without rolling it back.
  47909. **
  47910. ** To work around this, if a call to xUnlock() fails when unlocking the
  47911. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  47912. ** is only changed back to a real locking state after a successful call
  47913. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  47914. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  47915. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  47916. ** lock on the database file before attempting to roll it back. See function
  47917. ** PagerSharedLock() for more detail.
  47918. **
  47919. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  47920. ** PAGER_OPEN state.
  47921. */
  47922. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  47923. /*
  47924. ** A macro used for invoking the codec if there is one
  47925. */
  47926. #ifdef SQLITE_HAS_CODEC
  47927. # define CODEC1(P,D,N,X,E) \
  47928. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  47929. # define CODEC2(P,D,N,X,E,O) \
  47930. if( P->xCodec==0 ){ O=(char*)D; }else \
  47931. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  47932. #else
  47933. # define CODEC1(P,D,N,X,E) /* NO-OP */
  47934. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  47935. #endif
  47936. /*
  47937. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  47938. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  47939. ** This could conceivably cause corruption following a power failure on
  47940. ** such a system. This is currently an undocumented limit.
  47941. */
  47942. #define MAX_SECTOR_SIZE 0x10000
  47943. /*
  47944. ** An instance of the following structure is allocated for each active
  47945. ** savepoint and statement transaction in the system. All such structures
  47946. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  47947. ** resized using sqlite3Realloc().
  47948. **
  47949. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  47950. ** set to 0. If a journal-header is written into the main journal while
  47951. ** the savepoint is active, then iHdrOffset is set to the byte offset
  47952. ** immediately following the last journal record written into the main
  47953. ** journal before the journal-header. This is required during savepoint
  47954. ** rollback (see pagerPlaybackSavepoint()).
  47955. */
  47956. typedef struct PagerSavepoint PagerSavepoint;
  47957. struct PagerSavepoint {
  47958. i64 iOffset; /* Starting offset in main journal */
  47959. i64 iHdrOffset; /* See above */
  47960. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  47961. Pgno nOrig; /* Original number of pages in file */
  47962. Pgno iSubRec; /* Index of first record in sub-journal */
  47963. #ifndef SQLITE_OMIT_WAL
  47964. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  47965. #endif
  47966. };
  47967. /*
  47968. ** Bits of the Pager.doNotSpill flag. See further description below.
  47969. */
  47970. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  47971. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  47972. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  47973. /*
  47974. ** An open page cache is an instance of struct Pager. A description of
  47975. ** some of the more important member variables follows:
  47976. **
  47977. ** eState
  47978. **
  47979. ** The current 'state' of the pager object. See the comment and state
  47980. ** diagram above for a description of the pager state.
  47981. **
  47982. ** eLock
  47983. **
  47984. ** For a real on-disk database, the current lock held on the database file -
  47985. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  47986. **
  47987. ** For a temporary or in-memory database (neither of which require any
  47988. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  47989. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  47990. ** logic into thinking that it already has all the locks it will ever
  47991. ** need (and no reason to release them).
  47992. **
  47993. ** In some (obscure) circumstances, this variable may also be set to
  47994. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  47995. ** details.
  47996. **
  47997. ** changeCountDone
  47998. **
  47999. ** This boolean variable is used to make sure that the change-counter
  48000. ** (the 4-byte header field at byte offset 24 of the database file) is
  48001. ** not updated more often than necessary.
  48002. **
  48003. ** It is set to true when the change-counter field is updated, which
  48004. ** can only happen if an exclusive lock is held on the database file.
  48005. ** It is cleared (set to false) whenever an exclusive lock is
  48006. ** relinquished on the database file. Each time a transaction is committed,
  48007. ** The changeCountDone flag is inspected. If it is true, the work of
  48008. ** updating the change-counter is omitted for the current transaction.
  48009. **
  48010. ** This mechanism means that when running in exclusive mode, a connection
  48011. ** need only update the change-counter once, for the first transaction
  48012. ** committed.
  48013. **
  48014. ** setMaster
  48015. **
  48016. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  48017. ** (or may not) specify a master-journal name to be written into the
  48018. ** journal file before it is synced to disk.
  48019. **
  48020. ** Whether or not a journal file contains a master-journal pointer affects
  48021. ** the way in which the journal file is finalized after the transaction is
  48022. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  48023. ** If a journal file does not contain a master-journal pointer, it is
  48024. ** finalized by overwriting the first journal header with zeroes. If
  48025. ** it does contain a master-journal pointer the journal file is finalized
  48026. ** by truncating it to zero bytes, just as if the connection were
  48027. ** running in "journal_mode=truncate" mode.
  48028. **
  48029. ** Journal files that contain master journal pointers cannot be finalized
  48030. ** simply by overwriting the first journal-header with zeroes, as the
  48031. ** master journal pointer could interfere with hot-journal rollback of any
  48032. ** subsequently interrupted transaction that reuses the journal file.
  48033. **
  48034. ** The flag is cleared as soon as the journal file is finalized (either
  48035. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  48036. ** journal file from being successfully finalized, the setMaster flag
  48037. ** is cleared anyway (and the pager will move to ERROR state).
  48038. **
  48039. ** doNotSpill
  48040. **
  48041. ** This variables control the behavior of cache-spills (calls made by
  48042. ** the pcache module to the pagerStress() routine to write cached data
  48043. ** to the file-system in order to free up memory).
  48044. **
  48045. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  48046. ** writing to the database from pagerStress() is disabled altogether.
  48047. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  48048. ** comes up during savepoint rollback that requires the pcache module
  48049. ** to allocate a new page to prevent the journal file from being written
  48050. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  48051. ** case is a user preference.
  48052. **
  48053. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  48054. ** pagerStress() is permitted, but syncing the journal file is not.
  48055. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  48056. ** is larger than the database page-size in order to prevent a journal sync
  48057. ** from happening in between the journalling of two pages on the same sector.
  48058. **
  48059. ** subjInMemory
  48060. **
  48061. ** This is a boolean variable. If true, then any required sub-journal
  48062. ** is opened as an in-memory journal file. If false, then in-memory
  48063. ** sub-journals are only used for in-memory pager files.
  48064. **
  48065. ** This variable is updated by the upper layer each time a new
  48066. ** write-transaction is opened.
  48067. **
  48068. ** dbSize, dbOrigSize, dbFileSize
  48069. **
  48070. ** Variable dbSize is set to the number of pages in the database file.
  48071. ** It is valid in PAGER_READER and higher states (all states except for
  48072. ** OPEN and ERROR).
  48073. **
  48074. ** dbSize is set based on the size of the database file, which may be
  48075. ** larger than the size of the database (the value stored at offset
  48076. ** 28 of the database header by the btree). If the size of the file
  48077. ** is not an integer multiple of the page-size, the value stored in
  48078. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  48079. ** Except, any file that is greater than 0 bytes in size is considered
  48080. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  48081. ** to dbSize==1).
  48082. **
  48083. ** During a write-transaction, if pages with page-numbers greater than
  48084. ** dbSize are modified in the cache, dbSize is updated accordingly.
  48085. ** Similarly, if the database is truncated using PagerTruncateImage(),
  48086. ** dbSize is updated.
  48087. **
  48088. ** Variables dbOrigSize and dbFileSize are valid in states
  48089. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  48090. ** variable at the start of the transaction. It is used during rollback,
  48091. ** and to determine whether or not pages need to be journalled before
  48092. ** being modified.
  48093. **
  48094. ** Throughout a write-transaction, dbFileSize contains the size of
  48095. ** the file on disk in pages. It is set to a copy of dbSize when the
  48096. ** write-transaction is first opened, and updated when VFS calls are made
  48097. ** to write or truncate the database file on disk.
  48098. **
  48099. ** The only reason the dbFileSize variable is required is to suppress
  48100. ** unnecessary calls to xTruncate() after committing a transaction. If,
  48101. ** when a transaction is committed, the dbFileSize variable indicates
  48102. ** that the database file is larger than the database image (Pager.dbSize),
  48103. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  48104. ** to measure the database file on disk, and then truncates it if required.
  48105. ** dbFileSize is not used when rolling back a transaction. In this case
  48106. ** pager_truncate() is called unconditionally (which means there may be
  48107. ** a call to xFilesize() that is not strictly required). In either case,
  48108. ** pager_truncate() may cause the file to become smaller or larger.
  48109. **
  48110. ** dbHintSize
  48111. **
  48112. ** The dbHintSize variable is used to limit the number of calls made to
  48113. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  48114. **
  48115. ** dbHintSize is set to a copy of the dbSize variable when a
  48116. ** write-transaction is opened (at the same time as dbFileSize and
  48117. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  48118. ** dbHintSize is increased to the number of pages that correspond to the
  48119. ** size-hint passed to the method call. See pager_write_pagelist() for
  48120. ** details.
  48121. **
  48122. ** errCode
  48123. **
  48124. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  48125. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  48126. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  48127. ** sub-codes.
  48128. **
  48129. ** syncFlags, walSyncFlags
  48130. **
  48131. ** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
  48132. ** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode
  48133. ** and contains the flags used to sync the checkpoint operations in the
  48134. ** lower two bits, and sync flags used for transaction commits in the WAL
  48135. ** file in bits 0x04 and 0x08. In other words, to get the correct sync flags
  48136. ** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
  48137. ** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note
  48138. ** that with synchronous=NORMAL in WAL mode, transaction commit is not synced
  48139. ** meaning that the 0x04 and 0x08 bits are both zero.
  48140. */
  48141. struct Pager {
  48142. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  48143. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  48144. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  48145. u8 useJournal; /* Use a rollback journal on this file */
  48146. u8 noSync; /* Do not sync the journal if true */
  48147. u8 fullSync; /* Do extra syncs of the journal for robustness */
  48148. u8 extraSync; /* sync directory after journal delete */
  48149. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  48150. u8 walSyncFlags; /* See description above */
  48151. u8 tempFile; /* zFilename is a temporary or immutable file */
  48152. u8 noLock; /* Do not lock (except in WAL mode) */
  48153. u8 readOnly; /* True for a read-only database */
  48154. u8 memDb; /* True to inhibit all file I/O */
  48155. /**************************************************************************
  48156. ** The following block contains those class members that change during
  48157. ** routine operation. Class members not in this block are either fixed
  48158. ** when the pager is first created or else only change when there is a
  48159. ** significant mode change (such as changing the page_size, locking_mode,
  48160. ** or the journal_mode). From another view, these class members describe
  48161. ** the "state" of the pager, while other class members describe the
  48162. ** "configuration" of the pager.
  48163. */
  48164. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  48165. u8 eLock; /* Current lock held on database file */
  48166. u8 changeCountDone; /* Set after incrementing the change-counter */
  48167. u8 setMaster; /* True if a m-j name has been written to jrnl */
  48168. u8 doNotSpill; /* Do not spill the cache when non-zero */
  48169. u8 subjInMemory; /* True to use in-memory sub-journals */
  48170. u8 bUseFetch; /* True to use xFetch() */
  48171. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  48172. Pgno dbSize; /* Number of pages in the database */
  48173. Pgno dbOrigSize; /* dbSize before the current transaction */
  48174. Pgno dbFileSize; /* Number of pages in the database file */
  48175. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  48176. int errCode; /* One of several kinds of errors */
  48177. int nRec; /* Pages journalled since last j-header written */
  48178. u32 cksumInit; /* Quasi-random value added to every checksum */
  48179. u32 nSubRec; /* Number of records written to sub-journal */
  48180. Bitvec *pInJournal; /* One bit for each page in the database file */
  48181. sqlite3_file *fd; /* File descriptor for database */
  48182. sqlite3_file *jfd; /* File descriptor for main journal */
  48183. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  48184. i64 journalOff; /* Current write offset in the journal file */
  48185. i64 journalHdr; /* Byte offset to previous journal header */
  48186. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  48187. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  48188. int nSavepoint; /* Number of elements in aSavepoint[] */
  48189. u32 iDataVersion; /* Changes whenever database content changes */
  48190. char dbFileVers[16]; /* Changes whenever database file changes */
  48191. int nMmapOut; /* Number of mmap pages currently outstanding */
  48192. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  48193. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  48194. /*
  48195. ** End of the routinely-changing class members
  48196. ***************************************************************************/
  48197. u16 nExtra; /* Add this many bytes to each in-memory page */
  48198. i16 nReserve; /* Number of unused bytes at end of each page */
  48199. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  48200. u32 sectorSize; /* Assumed sector size during rollback */
  48201. int pageSize; /* Number of bytes in a page */
  48202. Pgno mxPgno; /* Maximum allowed size of the database */
  48203. i64 journalSizeLimit; /* Size limit for persistent journal files */
  48204. char *zFilename; /* Name of the database file */
  48205. char *zJournal; /* Name of the journal file */
  48206. int (*xBusyHandler)(void*); /* Function to call when busy */
  48207. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  48208. int aStat[4]; /* Total cache hits, misses, writes, spills */
  48209. #ifdef SQLITE_TEST
  48210. int nRead; /* Database pages read */
  48211. #endif
  48212. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  48213. int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
  48214. #ifdef SQLITE_HAS_CODEC
  48215. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  48216. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  48217. void (*xCodecFree)(void*); /* Destructor for the codec */
  48218. void *pCodec; /* First argument to xCodec... methods */
  48219. #endif
  48220. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  48221. PCache *pPCache; /* Pointer to page cache object */
  48222. #ifndef SQLITE_OMIT_WAL
  48223. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  48224. char *zWal; /* File name for write-ahead log */
  48225. #endif
  48226. };
  48227. /*
  48228. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  48229. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  48230. ** or CACHE_WRITE to sqlite3_db_status().
  48231. */
  48232. #define PAGER_STAT_HIT 0
  48233. #define PAGER_STAT_MISS 1
  48234. #define PAGER_STAT_WRITE 2
  48235. #define PAGER_STAT_SPILL 3
  48236. /*
  48237. ** The following global variables hold counters used for
  48238. ** testing purposes only. These variables do not exist in
  48239. ** a non-testing build. These variables are not thread-safe.
  48240. */
  48241. #ifdef SQLITE_TEST
  48242. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  48243. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  48244. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  48245. # define PAGER_INCR(v) v++
  48246. #else
  48247. # define PAGER_INCR(v)
  48248. #endif
  48249. /*
  48250. ** Journal files begin with the following magic string. The data
  48251. ** was obtained from /dev/random. It is used only as a sanity check.
  48252. **
  48253. ** Since version 2.8.0, the journal format contains additional sanity
  48254. ** checking information. If the power fails while the journal is being
  48255. ** written, semi-random garbage data might appear in the journal
  48256. ** file after power is restored. If an attempt is then made
  48257. ** to roll the journal back, the database could be corrupted. The additional
  48258. ** sanity checking data is an attempt to discover the garbage in the
  48259. ** journal and ignore it.
  48260. **
  48261. ** The sanity checking information for the new journal format consists
  48262. ** of a 32-bit checksum on each page of data. The checksum covers both
  48263. ** the page number and the pPager->pageSize bytes of data for the page.
  48264. ** This cksum is initialized to a 32-bit random value that appears in the
  48265. ** journal file right after the header. The random initializer is important,
  48266. ** because garbage data that appears at the end of a journal is likely
  48267. ** data that was once in other files that have now been deleted. If the
  48268. ** garbage data came from an obsolete journal file, the checksums might
  48269. ** be correct. But by initializing the checksum to random value which
  48270. ** is different for every journal, we minimize that risk.
  48271. */
  48272. static const unsigned char aJournalMagic[] = {
  48273. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  48274. };
  48275. /*
  48276. ** The size of the of each page record in the journal is given by
  48277. ** the following macro.
  48278. */
  48279. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  48280. /*
  48281. ** The journal header size for this pager. This is usually the same
  48282. ** size as a single disk sector. See also setSectorSize().
  48283. */
  48284. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  48285. /*
  48286. ** The macro MEMDB is true if we are dealing with an in-memory database.
  48287. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  48288. ** the value of MEMDB will be a constant and the compiler will optimize
  48289. ** out code that would never execute.
  48290. */
  48291. #ifdef SQLITE_OMIT_MEMORYDB
  48292. # define MEMDB 0
  48293. #else
  48294. # define MEMDB pPager->memDb
  48295. #endif
  48296. /*
  48297. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  48298. ** interfaces to access the database using memory-mapped I/O.
  48299. */
  48300. #if SQLITE_MAX_MMAP_SIZE>0
  48301. # define USEFETCH(x) ((x)->bUseFetch)
  48302. #else
  48303. # define USEFETCH(x) 0
  48304. #endif
  48305. /*
  48306. ** The maximum legal page number is (2^31 - 1).
  48307. */
  48308. #define PAGER_MAX_PGNO 2147483647
  48309. /*
  48310. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  48311. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  48312. **
  48313. ** This is so that expressions can be written as:
  48314. **
  48315. ** if( isOpen(pPager->jfd) ){ ...
  48316. **
  48317. ** instead of
  48318. **
  48319. ** if( pPager->jfd->pMethods ){ ...
  48320. */
  48321. #define isOpen(pFd) ((pFd)->pMethods!=0)
  48322. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  48323. /*
  48324. ** Return true if page pgno can be read directly from the database file
  48325. ** by the b-tree layer. This is the case if:
  48326. **
  48327. ** * the database file is open,
  48328. ** * there are no dirty pages in the cache, and
  48329. ** * the desired page is not currently in the wal file.
  48330. */
  48331. SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){
  48332. if( pPager->fd->pMethods==0 ) return 0;
  48333. if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
  48334. #ifdef SQLITE_HAS_CODEC
  48335. if( pPager->xCodec!=0 ) return 0;
  48336. #endif
  48337. #ifndef SQLITE_OMIT_WAL
  48338. if( pPager->pWal ){
  48339. u32 iRead = 0;
  48340. int rc;
  48341. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
  48342. return (rc==SQLITE_OK && iRead==0);
  48343. }
  48344. #endif
  48345. return 1;
  48346. }
  48347. #endif
  48348. #ifndef SQLITE_OMIT_WAL
  48349. # define pagerUseWal(x) ((x)->pWal!=0)
  48350. #else
  48351. # define pagerUseWal(x) 0
  48352. # define pagerRollbackWal(x) 0
  48353. # define pagerWalFrames(v,w,x,y) 0
  48354. # define pagerOpenWalIfPresent(z) SQLITE_OK
  48355. # define pagerBeginReadTransaction(z) SQLITE_OK
  48356. #endif
  48357. #ifndef NDEBUG
  48358. /*
  48359. ** Usage:
  48360. **
  48361. ** assert( assert_pager_state(pPager) );
  48362. **
  48363. ** This function runs many asserts to try to find inconsistencies in
  48364. ** the internal state of the Pager object.
  48365. */
  48366. static int assert_pager_state(Pager *p){
  48367. Pager *pPager = p;
  48368. /* State must be valid. */
  48369. assert( p->eState==PAGER_OPEN
  48370. || p->eState==PAGER_READER
  48371. || p->eState==PAGER_WRITER_LOCKED
  48372. || p->eState==PAGER_WRITER_CACHEMOD
  48373. || p->eState==PAGER_WRITER_DBMOD
  48374. || p->eState==PAGER_WRITER_FINISHED
  48375. || p->eState==PAGER_ERROR
  48376. );
  48377. /* Regardless of the current state, a temp-file connection always behaves
  48378. ** as if it has an exclusive lock on the database file. It never updates
  48379. ** the change-counter field, so the changeCountDone flag is always set.
  48380. */
  48381. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  48382. assert( p->tempFile==0 || pPager->changeCountDone );
  48383. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  48384. ** And if the journal-mode is "OFF", the journal file must not be open.
  48385. */
  48386. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  48387. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  48388. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  48389. ** this means an in-memory pager performs no IO at all, it cannot encounter
  48390. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  48391. ** a journal file. (although the in-memory journal implementation may
  48392. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  48393. ** is therefore not possible for an in-memory pager to enter the ERROR
  48394. ** state.
  48395. */
  48396. if( MEMDB ){
  48397. assert( !isOpen(p->fd) );
  48398. assert( p->noSync );
  48399. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  48400. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  48401. );
  48402. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  48403. assert( pagerUseWal(p)==0 );
  48404. }
  48405. /* If changeCountDone is set, a RESERVED lock or greater must be held
  48406. ** on the file.
  48407. */
  48408. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  48409. assert( p->eLock!=PENDING_LOCK );
  48410. switch( p->eState ){
  48411. case PAGER_OPEN:
  48412. assert( !MEMDB );
  48413. assert( pPager->errCode==SQLITE_OK );
  48414. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  48415. break;
  48416. case PAGER_READER:
  48417. assert( pPager->errCode==SQLITE_OK );
  48418. assert( p->eLock!=UNKNOWN_LOCK );
  48419. assert( p->eLock>=SHARED_LOCK );
  48420. break;
  48421. case PAGER_WRITER_LOCKED:
  48422. assert( p->eLock!=UNKNOWN_LOCK );
  48423. assert( pPager->errCode==SQLITE_OK );
  48424. if( !pagerUseWal(pPager) ){
  48425. assert( p->eLock>=RESERVED_LOCK );
  48426. }
  48427. assert( pPager->dbSize==pPager->dbOrigSize );
  48428. assert( pPager->dbOrigSize==pPager->dbFileSize );
  48429. assert( pPager->dbOrigSize==pPager->dbHintSize );
  48430. assert( pPager->setMaster==0 );
  48431. break;
  48432. case PAGER_WRITER_CACHEMOD:
  48433. assert( p->eLock!=UNKNOWN_LOCK );
  48434. assert( pPager->errCode==SQLITE_OK );
  48435. if( !pagerUseWal(pPager) ){
  48436. /* It is possible that if journal_mode=wal here that neither the
  48437. ** journal file nor the WAL file are open. This happens during
  48438. ** a rollback transaction that switches from journal_mode=off
  48439. ** to journal_mode=wal.
  48440. */
  48441. assert( p->eLock>=RESERVED_LOCK );
  48442. assert( isOpen(p->jfd)
  48443. || p->journalMode==PAGER_JOURNALMODE_OFF
  48444. || p->journalMode==PAGER_JOURNALMODE_WAL
  48445. );
  48446. }
  48447. assert( pPager->dbOrigSize==pPager->dbFileSize );
  48448. assert( pPager->dbOrigSize==pPager->dbHintSize );
  48449. break;
  48450. case PAGER_WRITER_DBMOD:
  48451. assert( p->eLock==EXCLUSIVE_LOCK );
  48452. assert( pPager->errCode==SQLITE_OK );
  48453. assert( !pagerUseWal(pPager) );
  48454. assert( p->eLock>=EXCLUSIVE_LOCK );
  48455. assert( isOpen(p->jfd)
  48456. || p->journalMode==PAGER_JOURNALMODE_OFF
  48457. || p->journalMode==PAGER_JOURNALMODE_WAL
  48458. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  48459. );
  48460. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  48461. break;
  48462. case PAGER_WRITER_FINISHED:
  48463. assert( p->eLock==EXCLUSIVE_LOCK );
  48464. assert( pPager->errCode==SQLITE_OK );
  48465. assert( !pagerUseWal(pPager) );
  48466. assert( isOpen(p->jfd)
  48467. || p->journalMode==PAGER_JOURNALMODE_OFF
  48468. || p->journalMode==PAGER_JOURNALMODE_WAL
  48469. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  48470. );
  48471. break;
  48472. case PAGER_ERROR:
  48473. /* There must be at least one outstanding reference to the pager if
  48474. ** in ERROR state. Otherwise the pager should have already dropped
  48475. ** back to OPEN state.
  48476. */
  48477. assert( pPager->errCode!=SQLITE_OK );
  48478. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
  48479. break;
  48480. }
  48481. return 1;
  48482. }
  48483. #endif /* ifndef NDEBUG */
  48484. #ifdef SQLITE_DEBUG
  48485. /*
  48486. ** Return a pointer to a human readable string in a static buffer
  48487. ** containing the state of the Pager object passed as an argument. This
  48488. ** is intended to be used within debuggers. For example, as an alternative
  48489. ** to "print *pPager" in gdb:
  48490. **
  48491. ** (gdb) printf "%s", print_pager_state(pPager)
  48492. **
  48493. ** This routine has external linkage in order to suppress compiler warnings
  48494. ** about an unused function. It is enclosed within SQLITE_DEBUG and so does
  48495. ** not appear in normal builds.
  48496. */
  48497. char *print_pager_state(Pager *p){
  48498. static char zRet[1024];
  48499. sqlite3_snprintf(1024, zRet,
  48500. "Filename: %s\n"
  48501. "State: %s errCode=%d\n"
  48502. "Lock: %s\n"
  48503. "Locking mode: locking_mode=%s\n"
  48504. "Journal mode: journal_mode=%s\n"
  48505. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  48506. "Journal: journalOff=%lld journalHdr=%lld\n"
  48507. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  48508. , p->zFilename
  48509. , p->eState==PAGER_OPEN ? "OPEN" :
  48510. p->eState==PAGER_READER ? "READER" :
  48511. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  48512. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  48513. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  48514. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  48515. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  48516. , (int)p->errCode
  48517. , p->eLock==NO_LOCK ? "NO_LOCK" :
  48518. p->eLock==RESERVED_LOCK ? "RESERVED" :
  48519. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  48520. p->eLock==SHARED_LOCK ? "SHARED" :
  48521. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  48522. , p->exclusiveMode ? "exclusive" : "normal"
  48523. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  48524. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  48525. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  48526. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  48527. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  48528. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  48529. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  48530. , p->journalOff, p->journalHdr
  48531. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  48532. );
  48533. return zRet;
  48534. }
  48535. #endif
  48536. /* Forward references to the various page getters */
  48537. static int getPageNormal(Pager*,Pgno,DbPage**,int);
  48538. static int getPageError(Pager*,Pgno,DbPage**,int);
  48539. #if SQLITE_MAX_MMAP_SIZE>0
  48540. static int getPageMMap(Pager*,Pgno,DbPage**,int);
  48541. #endif
  48542. /*
  48543. ** Set the Pager.xGet method for the appropriate routine used to fetch
  48544. ** content from the pager.
  48545. */
  48546. static void setGetterMethod(Pager *pPager){
  48547. if( pPager->errCode ){
  48548. pPager->xGet = getPageError;
  48549. #if SQLITE_MAX_MMAP_SIZE>0
  48550. }else if( USEFETCH(pPager)
  48551. #ifdef SQLITE_HAS_CODEC
  48552. && pPager->xCodec==0
  48553. #endif
  48554. ){
  48555. pPager->xGet = getPageMMap;
  48556. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  48557. }else{
  48558. pPager->xGet = getPageNormal;
  48559. }
  48560. }
  48561. /*
  48562. ** Return true if it is necessary to write page *pPg into the sub-journal.
  48563. ** A page needs to be written into the sub-journal if there exists one
  48564. ** or more open savepoints for which:
  48565. **
  48566. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  48567. ** * The bit corresponding to the page-number is not set in
  48568. ** PagerSavepoint.pInSavepoint.
  48569. */
  48570. static int subjRequiresPage(PgHdr *pPg){
  48571. Pager *pPager = pPg->pPager;
  48572. PagerSavepoint *p;
  48573. Pgno pgno = pPg->pgno;
  48574. int i;
  48575. for(i=0; i<pPager->nSavepoint; i++){
  48576. p = &pPager->aSavepoint[i];
  48577. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  48578. return 1;
  48579. }
  48580. }
  48581. return 0;
  48582. }
  48583. #ifdef SQLITE_DEBUG
  48584. /*
  48585. ** Return true if the page is already in the journal file.
  48586. */
  48587. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  48588. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  48589. }
  48590. #endif
  48591. /*
  48592. ** Read a 32-bit integer from the given file descriptor. Store the integer
  48593. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  48594. ** error code is something goes wrong.
  48595. **
  48596. ** All values are stored on disk as big-endian.
  48597. */
  48598. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  48599. unsigned char ac[4];
  48600. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  48601. if( rc==SQLITE_OK ){
  48602. *pRes = sqlite3Get4byte(ac);
  48603. }
  48604. return rc;
  48605. }
  48606. /*
  48607. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  48608. */
  48609. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  48610. /*
  48611. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  48612. ** on success or an error code is something goes wrong.
  48613. */
  48614. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  48615. char ac[4];
  48616. put32bits(ac, val);
  48617. return sqlite3OsWrite(fd, ac, 4, offset);
  48618. }
  48619. /*
  48620. ** Unlock the database file to level eLock, which must be either NO_LOCK
  48621. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  48622. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  48623. **
  48624. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  48625. ** called, do not modify it. See the comment above the #define of
  48626. ** UNKNOWN_LOCK for an explanation of this.
  48627. */
  48628. static int pagerUnlockDb(Pager *pPager, int eLock){
  48629. int rc = SQLITE_OK;
  48630. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  48631. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  48632. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  48633. if( isOpen(pPager->fd) ){
  48634. assert( pPager->eLock>=eLock );
  48635. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  48636. if( pPager->eLock!=UNKNOWN_LOCK ){
  48637. pPager->eLock = (u8)eLock;
  48638. }
  48639. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  48640. }
  48641. return rc;
  48642. }
  48643. /*
  48644. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  48645. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  48646. ** Pager.eLock variable to the new locking state.
  48647. **
  48648. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  48649. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  48650. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  48651. ** of this.
  48652. */
  48653. static int pagerLockDb(Pager *pPager, int eLock){
  48654. int rc = SQLITE_OK;
  48655. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  48656. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  48657. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  48658. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  48659. pPager->eLock = (u8)eLock;
  48660. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  48661. }
  48662. }
  48663. return rc;
  48664. }
  48665. /*
  48666. ** This function determines whether or not the atomic-write or
  48667. ** atomic-batch-write optimizations can be used with this pager. The
  48668. ** atomic-write optimization can be used if:
  48669. **
  48670. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  48671. ** a database page may be written atomically, and
  48672. ** (b) the value returned by OsSectorSize() is less than or equal
  48673. ** to the page size.
  48674. **
  48675. ** If it can be used, then the value returned is the size of the journal
  48676. ** file when it contains rollback data for exactly one page.
  48677. **
  48678. ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
  48679. ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
  48680. ** returned in this case.
  48681. **
  48682. ** If neither optimization can be used, 0 is returned.
  48683. */
  48684. static int jrnlBufferSize(Pager *pPager){
  48685. assert( !MEMDB );
  48686. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  48687. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  48688. int dc; /* Device characteristics */
  48689. assert( isOpen(pPager->fd) );
  48690. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  48691. #else
  48692. UNUSED_PARAMETER(pPager);
  48693. #endif
  48694. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  48695. if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
  48696. return -1;
  48697. }
  48698. #endif
  48699. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  48700. {
  48701. int nSector = pPager->sectorSize;
  48702. int szPage = pPager->pageSize;
  48703. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  48704. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  48705. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  48706. return 0;
  48707. }
  48708. }
  48709. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  48710. #endif
  48711. return 0;
  48712. }
  48713. /*
  48714. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  48715. ** on the cache using a hash function. This is used for testing
  48716. ** and debugging only.
  48717. */
  48718. #ifdef SQLITE_CHECK_PAGES
  48719. /*
  48720. ** Return a 32-bit hash of the page data for pPage.
  48721. */
  48722. static u32 pager_datahash(int nByte, unsigned char *pData){
  48723. u32 hash = 0;
  48724. int i;
  48725. for(i=0; i<nByte; i++){
  48726. hash = (hash*1039) + pData[i];
  48727. }
  48728. return hash;
  48729. }
  48730. static u32 pager_pagehash(PgHdr *pPage){
  48731. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  48732. }
  48733. static void pager_set_pagehash(PgHdr *pPage){
  48734. pPage->pageHash = pager_pagehash(pPage);
  48735. }
  48736. /*
  48737. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  48738. ** is defined, and NDEBUG is not defined, an assert() statement checks
  48739. ** that the page is either dirty or still matches the calculated page-hash.
  48740. */
  48741. #define CHECK_PAGE(x) checkPage(x)
  48742. static void checkPage(PgHdr *pPg){
  48743. Pager *pPager = pPg->pPager;
  48744. assert( pPager->eState!=PAGER_ERROR );
  48745. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  48746. }
  48747. #else
  48748. #define pager_datahash(X,Y) 0
  48749. #define pager_pagehash(X) 0
  48750. #define pager_set_pagehash(X)
  48751. #define CHECK_PAGE(x)
  48752. #endif /* SQLITE_CHECK_PAGES */
  48753. /*
  48754. ** When this is called the journal file for pager pPager must be open.
  48755. ** This function attempts to read a master journal file name from the
  48756. ** end of the file and, if successful, copies it into memory supplied
  48757. ** by the caller. See comments above writeMasterJournal() for the format
  48758. ** used to store a master journal file name at the end of a journal file.
  48759. **
  48760. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  48761. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  48762. ** enough space to write the master journal name). If the master journal
  48763. ** name in the journal is longer than nMaster bytes (including a
  48764. ** nul-terminator), then this is handled as if no master journal name
  48765. ** were present in the journal.
  48766. **
  48767. ** If a master journal file name is present at the end of the journal
  48768. ** file, then it is copied into the buffer pointed to by zMaster. A
  48769. ** nul-terminator byte is appended to the buffer following the master
  48770. ** journal file name.
  48771. **
  48772. ** If it is determined that no master journal file name is present
  48773. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  48774. **
  48775. ** If an error occurs while reading from the journal file, an SQLite
  48776. ** error code is returned.
  48777. */
  48778. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  48779. int rc; /* Return code */
  48780. u32 len; /* Length in bytes of master journal name */
  48781. i64 szJ; /* Total size in bytes of journal file pJrnl */
  48782. u32 cksum; /* MJ checksum value read from journal */
  48783. u32 u; /* Unsigned loop counter */
  48784. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  48785. zMaster[0] = '\0';
  48786. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  48787. || szJ<16
  48788. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  48789. || len>=nMaster
  48790. || len>szJ-16
  48791. || len==0
  48792. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  48793. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  48794. || memcmp(aMagic, aJournalMagic, 8)
  48795. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  48796. ){
  48797. return rc;
  48798. }
  48799. /* See if the checksum matches the master journal name */
  48800. for(u=0; u<len; u++){
  48801. cksum -= zMaster[u];
  48802. }
  48803. if( cksum ){
  48804. /* If the checksum doesn't add up, then one or more of the disk sectors
  48805. ** containing the master journal filename is corrupted. This means
  48806. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  48807. ** master-journal filename.
  48808. */
  48809. len = 0;
  48810. }
  48811. zMaster[len] = '\0';
  48812. return SQLITE_OK;
  48813. }
  48814. /*
  48815. ** Return the offset of the sector boundary at or immediately
  48816. ** following the value in pPager->journalOff, assuming a sector
  48817. ** size of pPager->sectorSize bytes.
  48818. **
  48819. ** i.e for a sector size of 512:
  48820. **
  48821. ** Pager.journalOff Return value
  48822. ** ---------------------------------------
  48823. ** 0 0
  48824. ** 512 512
  48825. ** 100 512
  48826. ** 2000 2048
  48827. **
  48828. */
  48829. static i64 journalHdrOffset(Pager *pPager){
  48830. i64 offset = 0;
  48831. i64 c = pPager->journalOff;
  48832. if( c ){
  48833. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  48834. }
  48835. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  48836. assert( offset>=c );
  48837. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  48838. return offset;
  48839. }
  48840. /*
  48841. ** The journal file must be open when this function is called.
  48842. **
  48843. ** This function is a no-op if the journal file has not been written to
  48844. ** within the current transaction (i.e. if Pager.journalOff==0).
  48845. **
  48846. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  48847. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  48848. ** zero the 28-byte header at the start of the journal file. In either case,
  48849. ** if the pager is not in no-sync mode, sync the journal file immediately
  48850. ** after writing or truncating it.
  48851. **
  48852. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  48853. ** following the truncation or zeroing described above the size of the
  48854. ** journal file in bytes is larger than this value, then truncate the
  48855. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  48856. ** not need to be synced following this operation.
  48857. **
  48858. ** If an IO error occurs, abandon processing and return the IO error code.
  48859. ** Otherwise, return SQLITE_OK.
  48860. */
  48861. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  48862. int rc = SQLITE_OK; /* Return code */
  48863. assert( isOpen(pPager->jfd) );
  48864. assert( !sqlite3JournalIsInMemory(pPager->jfd) );
  48865. if( pPager->journalOff ){
  48866. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  48867. IOTRACE(("JZEROHDR %p\n", pPager))
  48868. if( doTruncate || iLimit==0 ){
  48869. rc = sqlite3OsTruncate(pPager->jfd, 0);
  48870. }else{
  48871. static const char zeroHdr[28] = {0};
  48872. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  48873. }
  48874. if( rc==SQLITE_OK && !pPager->noSync ){
  48875. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  48876. }
  48877. /* At this point the transaction is committed but the write lock
  48878. ** is still held on the file. If there is a size limit configured for
  48879. ** the persistent journal and the journal file currently consumes more
  48880. ** space than that limit allows for, truncate it now. There is no need
  48881. ** to sync the file following this operation.
  48882. */
  48883. if( rc==SQLITE_OK && iLimit>0 ){
  48884. i64 sz;
  48885. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  48886. if( rc==SQLITE_OK && sz>iLimit ){
  48887. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  48888. }
  48889. }
  48890. }
  48891. return rc;
  48892. }
  48893. /*
  48894. ** The journal file must be open when this routine is called. A journal
  48895. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  48896. ** current location.
  48897. **
  48898. ** The format for the journal header is as follows:
  48899. ** - 8 bytes: Magic identifying journal format.
  48900. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  48901. ** - 4 bytes: Random number used for page hash.
  48902. ** - 4 bytes: Initial database page count.
  48903. ** - 4 bytes: Sector size used by the process that wrote this journal.
  48904. ** - 4 bytes: Database page size.
  48905. **
  48906. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  48907. */
  48908. static int writeJournalHdr(Pager *pPager){
  48909. int rc = SQLITE_OK; /* Return code */
  48910. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  48911. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  48912. u32 nWrite; /* Bytes of header sector written */
  48913. int ii; /* Loop counter */
  48914. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  48915. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  48916. nHeader = JOURNAL_HDR_SZ(pPager);
  48917. }
  48918. /* If there are active savepoints and any of them were created
  48919. ** since the most recent journal header was written, update the
  48920. ** PagerSavepoint.iHdrOffset fields now.
  48921. */
  48922. for(ii=0; ii<pPager->nSavepoint; ii++){
  48923. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  48924. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  48925. }
  48926. }
  48927. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  48928. /*
  48929. ** Write the nRec Field - the number of page records that follow this
  48930. ** journal header. Normally, zero is written to this value at this time.
  48931. ** After the records are added to the journal (and the journal synced,
  48932. ** if in full-sync mode), the zero is overwritten with the true number
  48933. ** of records (see syncJournal()).
  48934. **
  48935. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  48936. ** reading the journal this value tells SQLite to assume that the
  48937. ** rest of the journal file contains valid page records. This assumption
  48938. ** is dangerous, as if a failure occurred whilst writing to the journal
  48939. ** file it may contain some garbage data. There are two scenarios
  48940. ** where this risk can be ignored:
  48941. **
  48942. ** * When the pager is in no-sync mode. Corruption can follow a
  48943. ** power failure in this case anyway.
  48944. **
  48945. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  48946. ** that garbage data is never appended to the journal file.
  48947. */
  48948. assert( isOpen(pPager->fd) || pPager->noSync );
  48949. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  48950. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  48951. ){
  48952. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  48953. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  48954. }else{
  48955. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  48956. }
  48957. /* The random check-hash initializer */
  48958. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  48959. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  48960. /* The initial database size */
  48961. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  48962. /* The assumed sector size for this process */
  48963. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  48964. /* The page size */
  48965. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  48966. /* Initializing the tail of the buffer is not necessary. Everything
  48967. ** works find if the following memset() is omitted. But initializing
  48968. ** the memory prevents valgrind from complaining, so we are willing to
  48969. ** take the performance hit.
  48970. */
  48971. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  48972. nHeader-(sizeof(aJournalMagic)+20));
  48973. /* In theory, it is only necessary to write the 28 bytes that the
  48974. ** journal header consumes to the journal file here. Then increment the
  48975. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  48976. ** record is written to the following sector (leaving a gap in the file
  48977. ** that will be implicitly filled in by the OS).
  48978. **
  48979. ** However it has been discovered that on some systems this pattern can
  48980. ** be significantly slower than contiguously writing data to the file,
  48981. ** even if that means explicitly writing data to the block of
  48982. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  48983. ** is done.
  48984. **
  48985. ** The loop is required here in case the sector-size is larger than the
  48986. ** database page size. Since the zHeader buffer is only Pager.pageSize
  48987. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  48988. ** to populate the entire journal header sector.
  48989. */
  48990. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  48991. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  48992. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  48993. assert( pPager->journalHdr <= pPager->journalOff );
  48994. pPager->journalOff += nHeader;
  48995. }
  48996. return rc;
  48997. }
  48998. /*
  48999. ** The journal file must be open when this is called. A journal header file
  49000. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  49001. ** file. The current location in the journal file is given by
  49002. ** pPager->journalOff. See comments above function writeJournalHdr() for
  49003. ** a description of the journal header format.
  49004. **
  49005. ** If the header is read successfully, *pNRec is set to the number of
  49006. ** page records following this header and *pDbSize is set to the size of the
  49007. ** database before the transaction began, in pages. Also, pPager->cksumInit
  49008. ** is set to the value read from the journal header. SQLITE_OK is returned
  49009. ** in this case.
  49010. **
  49011. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  49012. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  49013. ** cannot be read from the journal file an error code is returned.
  49014. */
  49015. static int readJournalHdr(
  49016. Pager *pPager, /* Pager object */
  49017. int isHot,
  49018. i64 journalSize, /* Size of the open journal file in bytes */
  49019. u32 *pNRec, /* OUT: Value read from the nRec field */
  49020. u32 *pDbSize /* OUT: Value of original database size field */
  49021. ){
  49022. int rc; /* Return code */
  49023. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  49024. i64 iHdrOff; /* Offset of journal header being read */
  49025. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  49026. /* Advance Pager.journalOff to the start of the next sector. If the
  49027. ** journal file is too small for there to be a header stored at this
  49028. ** point, return SQLITE_DONE.
  49029. */
  49030. pPager->journalOff = journalHdrOffset(pPager);
  49031. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  49032. return SQLITE_DONE;
  49033. }
  49034. iHdrOff = pPager->journalOff;
  49035. /* Read in the first 8 bytes of the journal header. If they do not match
  49036. ** the magic string found at the start of each journal header, return
  49037. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  49038. ** proceed.
  49039. */
  49040. if( isHot || iHdrOff!=pPager->journalHdr ){
  49041. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  49042. if( rc ){
  49043. return rc;
  49044. }
  49045. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  49046. return SQLITE_DONE;
  49047. }
  49048. }
  49049. /* Read the first three 32-bit fields of the journal header: The nRec
  49050. ** field, the checksum-initializer and the database size at the start
  49051. ** of the transaction. Return an error code if anything goes wrong.
  49052. */
  49053. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  49054. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  49055. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  49056. ){
  49057. return rc;
  49058. }
  49059. if( pPager->journalOff==0 ){
  49060. u32 iPageSize; /* Page-size field of journal header */
  49061. u32 iSectorSize; /* Sector-size field of journal header */
  49062. /* Read the page-size and sector-size journal header fields. */
  49063. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  49064. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  49065. ){
  49066. return rc;
  49067. }
  49068. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  49069. ** journal header to zero. In this case, assume that the Pager.pageSize
  49070. ** variable is already set to the correct page size.
  49071. */
  49072. if( iPageSize==0 ){
  49073. iPageSize = pPager->pageSize;
  49074. }
  49075. /* Check that the values read from the page-size and sector-size fields
  49076. ** are within range. To be 'in range', both values need to be a power
  49077. ** of two greater than or equal to 512 or 32, and not greater than their
  49078. ** respective compile time maximum limits.
  49079. */
  49080. if( iPageSize<512 || iSectorSize<32
  49081. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  49082. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  49083. ){
  49084. /* If the either the page-size or sector-size in the journal-header is
  49085. ** invalid, then the process that wrote the journal-header must have
  49086. ** crashed before the header was synced. In this case stop reading
  49087. ** the journal file here.
  49088. */
  49089. return SQLITE_DONE;
  49090. }
  49091. /* Update the page-size to match the value read from the journal.
  49092. ** Use a testcase() macro to make sure that malloc failure within
  49093. ** PagerSetPagesize() is tested.
  49094. */
  49095. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  49096. testcase( rc!=SQLITE_OK );
  49097. /* Update the assumed sector-size to match the value used by
  49098. ** the process that created this journal. If this journal was
  49099. ** created by a process other than this one, then this routine
  49100. ** is being called from within pager_playback(). The local value
  49101. ** of Pager.sectorSize is restored at the end of that routine.
  49102. */
  49103. pPager->sectorSize = iSectorSize;
  49104. }
  49105. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  49106. return rc;
  49107. }
  49108. /*
  49109. ** Write the supplied master journal name into the journal file for pager
  49110. ** pPager at the current location. The master journal name must be the last
  49111. ** thing written to a journal file. If the pager is in full-sync mode, the
  49112. ** journal file descriptor is advanced to the next sector boundary before
  49113. ** anything is written. The format is:
  49114. **
  49115. ** + 4 bytes: PAGER_MJ_PGNO.
  49116. ** + N bytes: Master journal filename in utf-8.
  49117. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  49118. ** + 4 bytes: Master journal name checksum.
  49119. ** + 8 bytes: aJournalMagic[].
  49120. **
  49121. ** The master journal page checksum is the sum of the bytes in the master
  49122. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  49123. **
  49124. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  49125. ** this call is a no-op.
  49126. */
  49127. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  49128. int rc; /* Return code */
  49129. int nMaster; /* Length of string zMaster */
  49130. i64 iHdrOff; /* Offset of header in journal file */
  49131. i64 jrnlSize; /* Size of journal file on disk */
  49132. u32 cksum = 0; /* Checksum of string zMaster */
  49133. assert( pPager->setMaster==0 );
  49134. assert( !pagerUseWal(pPager) );
  49135. if( !zMaster
  49136. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  49137. || !isOpen(pPager->jfd)
  49138. ){
  49139. return SQLITE_OK;
  49140. }
  49141. pPager->setMaster = 1;
  49142. assert( pPager->journalHdr <= pPager->journalOff );
  49143. /* Calculate the length in bytes and the checksum of zMaster */
  49144. for(nMaster=0; zMaster[nMaster]; nMaster++){
  49145. cksum += zMaster[nMaster];
  49146. }
  49147. /* If in full-sync mode, advance to the next disk sector before writing
  49148. ** the master journal name. This is in case the previous page written to
  49149. ** the journal has already been synced.
  49150. */
  49151. if( pPager->fullSync ){
  49152. pPager->journalOff = journalHdrOffset(pPager);
  49153. }
  49154. iHdrOff = pPager->journalOff;
  49155. /* Write the master journal data to the end of the journal file. If
  49156. ** an error occurs, return the error code to the caller.
  49157. */
  49158. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  49159. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  49160. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  49161. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  49162. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  49163. iHdrOff+4+nMaster+8)))
  49164. ){
  49165. return rc;
  49166. }
  49167. pPager->journalOff += (nMaster+20);
  49168. /* If the pager is in peristent-journal mode, then the physical
  49169. ** journal-file may extend past the end of the master-journal name
  49170. ** and 8 bytes of magic data just written to the file. This is
  49171. ** dangerous because the code to rollback a hot-journal file
  49172. ** will not be able to find the master-journal name to determine
  49173. ** whether or not the journal is hot.
  49174. **
  49175. ** Easiest thing to do in this scenario is to truncate the journal
  49176. ** file to the required size.
  49177. */
  49178. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  49179. && jrnlSize>pPager->journalOff
  49180. ){
  49181. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  49182. }
  49183. return rc;
  49184. }
  49185. /*
  49186. ** Discard the entire contents of the in-memory page-cache.
  49187. */
  49188. static void pager_reset(Pager *pPager){
  49189. pPager->iDataVersion++;
  49190. sqlite3BackupRestart(pPager->pBackup);
  49191. sqlite3PcacheClear(pPager->pPCache);
  49192. }
  49193. /*
  49194. ** Return the pPager->iDataVersion value
  49195. */
  49196. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  49197. return pPager->iDataVersion;
  49198. }
  49199. /*
  49200. ** Free all structures in the Pager.aSavepoint[] array and set both
  49201. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  49202. ** if it is open and the pager is not in exclusive mode.
  49203. */
  49204. static void releaseAllSavepoints(Pager *pPager){
  49205. int ii; /* Iterator for looping through Pager.aSavepoint */
  49206. for(ii=0; ii<pPager->nSavepoint; ii++){
  49207. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  49208. }
  49209. if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
  49210. sqlite3OsClose(pPager->sjfd);
  49211. }
  49212. sqlite3_free(pPager->aSavepoint);
  49213. pPager->aSavepoint = 0;
  49214. pPager->nSavepoint = 0;
  49215. pPager->nSubRec = 0;
  49216. }
  49217. /*
  49218. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  49219. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  49220. ** or SQLITE_NOMEM if a malloc failure occurs.
  49221. */
  49222. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  49223. int ii; /* Loop counter */
  49224. int rc = SQLITE_OK; /* Result code */
  49225. for(ii=0; ii<pPager->nSavepoint; ii++){
  49226. PagerSavepoint *p = &pPager->aSavepoint[ii];
  49227. if( pgno<=p->nOrig ){
  49228. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  49229. testcase( rc==SQLITE_NOMEM );
  49230. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  49231. }
  49232. }
  49233. return rc;
  49234. }
  49235. /*
  49236. ** This function is a no-op if the pager is in exclusive mode and not
  49237. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  49238. ** state.
  49239. **
  49240. ** If the pager is not in exclusive-access mode, the database file is
  49241. ** completely unlocked. If the file is unlocked and the file-system does
  49242. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  49243. ** closed (if it is open).
  49244. **
  49245. ** If the pager is in ERROR state when this function is called, the
  49246. ** contents of the pager cache are discarded before switching back to
  49247. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  49248. ** or not, any journal file left in the file-system will be treated
  49249. ** as a hot-journal and rolled back the next time a read-transaction
  49250. ** is opened (by this or by any other connection).
  49251. */
  49252. static void pager_unlock(Pager *pPager){
  49253. assert( pPager->eState==PAGER_READER
  49254. || pPager->eState==PAGER_OPEN
  49255. || pPager->eState==PAGER_ERROR
  49256. );
  49257. sqlite3BitvecDestroy(pPager->pInJournal);
  49258. pPager->pInJournal = 0;
  49259. releaseAllSavepoints(pPager);
  49260. if( pagerUseWal(pPager) ){
  49261. assert( !isOpen(pPager->jfd) );
  49262. sqlite3WalEndReadTransaction(pPager->pWal);
  49263. pPager->eState = PAGER_OPEN;
  49264. }else if( !pPager->exclusiveMode ){
  49265. int rc; /* Error code returned by pagerUnlockDb() */
  49266. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  49267. /* If the operating system support deletion of open files, then
  49268. ** close the journal file when dropping the database lock. Otherwise
  49269. ** another connection with journal_mode=delete might delete the file
  49270. ** out from under us.
  49271. */
  49272. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  49273. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  49274. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  49275. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  49276. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  49277. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  49278. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  49279. || 1!=(pPager->journalMode & 5)
  49280. ){
  49281. sqlite3OsClose(pPager->jfd);
  49282. }
  49283. /* If the pager is in the ERROR state and the call to unlock the database
  49284. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  49285. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  49286. ** is necessary.
  49287. */
  49288. rc = pagerUnlockDb(pPager, NO_LOCK);
  49289. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  49290. pPager->eLock = UNKNOWN_LOCK;
  49291. }
  49292. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  49293. ** without clearing the error code. This is intentional - the error
  49294. ** code is cleared and the cache reset in the block below.
  49295. */
  49296. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  49297. pPager->changeCountDone = 0;
  49298. pPager->eState = PAGER_OPEN;
  49299. }
  49300. /* If Pager.errCode is set, the contents of the pager cache cannot be
  49301. ** trusted. Now that there are no outstanding references to the pager,
  49302. ** it can safely move back to PAGER_OPEN state. This happens in both
  49303. ** normal and exclusive-locking mode.
  49304. */
  49305. assert( pPager->errCode==SQLITE_OK || !MEMDB );
  49306. if( pPager->errCode ){
  49307. if( pPager->tempFile==0 ){
  49308. pager_reset(pPager);
  49309. pPager->changeCountDone = 0;
  49310. pPager->eState = PAGER_OPEN;
  49311. }else{
  49312. pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
  49313. }
  49314. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  49315. pPager->errCode = SQLITE_OK;
  49316. setGetterMethod(pPager);
  49317. }
  49318. pPager->journalOff = 0;
  49319. pPager->journalHdr = 0;
  49320. pPager->setMaster = 0;
  49321. }
  49322. /*
  49323. ** This function is called whenever an IOERR or FULL error that requires
  49324. ** the pager to transition into the ERROR state may ahve occurred.
  49325. ** The first argument is a pointer to the pager structure, the second
  49326. ** the error-code about to be returned by a pager API function. The
  49327. ** value returned is a copy of the second argument to this function.
  49328. **
  49329. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  49330. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  49331. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  49332. ** all major API calls on the Pager will immediately return Pager.errCode.
  49333. **
  49334. ** The ERROR state indicates that the contents of the pager-cache
  49335. ** cannot be trusted. This state can be cleared by completely discarding
  49336. ** the contents of the pager-cache. If a transaction was active when
  49337. ** the persistent error occurred, then the rollback journal may need
  49338. ** to be replayed to restore the contents of the database file (as if
  49339. ** it were a hot-journal).
  49340. */
  49341. static int pager_error(Pager *pPager, int rc){
  49342. int rc2 = rc & 0xff;
  49343. assert( rc==SQLITE_OK || !MEMDB );
  49344. assert(
  49345. pPager->errCode==SQLITE_FULL ||
  49346. pPager->errCode==SQLITE_OK ||
  49347. (pPager->errCode & 0xff)==SQLITE_IOERR
  49348. );
  49349. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  49350. pPager->errCode = rc;
  49351. pPager->eState = PAGER_ERROR;
  49352. setGetterMethod(pPager);
  49353. }
  49354. return rc;
  49355. }
  49356. static int pager_truncate(Pager *pPager, Pgno nPage);
  49357. /*
  49358. ** The write transaction open on pPager is being committed (bCommit==1)
  49359. ** or rolled back (bCommit==0).
  49360. **
  49361. ** Return TRUE if and only if all dirty pages should be flushed to disk.
  49362. **
  49363. ** Rules:
  49364. **
  49365. ** * For non-TEMP databases, always sync to disk. This is necessary
  49366. ** for transactions to be durable.
  49367. **
  49368. ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
  49369. ** file has been created already (via a spill on pagerStress()) and
  49370. ** when the number of dirty pages in memory exceeds 25% of the total
  49371. ** cache size.
  49372. */
  49373. static int pagerFlushOnCommit(Pager *pPager, int bCommit){
  49374. if( pPager->tempFile==0 ) return 1;
  49375. if( !bCommit ) return 0;
  49376. if( !isOpen(pPager->fd) ) return 0;
  49377. return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
  49378. }
  49379. /*
  49380. ** This routine ends a transaction. A transaction is usually ended by
  49381. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  49382. ** after rollback of a hot-journal, or if an error occurs while opening
  49383. ** the journal file or writing the very first journal-header of a
  49384. ** database transaction.
  49385. **
  49386. ** This routine is never called in PAGER_ERROR state. If it is called
  49387. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  49388. ** exclusive than a RESERVED lock, it is a no-op.
  49389. **
  49390. ** Otherwise, any active savepoints are released.
  49391. **
  49392. ** If the journal file is open, then it is "finalized". Once a journal
  49393. ** file has been finalized it is not possible to use it to roll back a
  49394. ** transaction. Nor will it be considered to be a hot-journal by this
  49395. ** or any other database connection. Exactly how a journal is finalized
  49396. ** depends on whether or not the pager is running in exclusive mode and
  49397. ** the current journal-mode (Pager.journalMode value), as follows:
  49398. **
  49399. ** journalMode==MEMORY
  49400. ** Journal file descriptor is simply closed. This destroys an
  49401. ** in-memory journal.
  49402. **
  49403. ** journalMode==TRUNCATE
  49404. ** Journal file is truncated to zero bytes in size.
  49405. **
  49406. ** journalMode==PERSIST
  49407. ** The first 28 bytes of the journal file are zeroed. This invalidates
  49408. ** the first journal header in the file, and hence the entire journal
  49409. ** file. An invalid journal file cannot be rolled back.
  49410. **
  49411. ** journalMode==DELETE
  49412. ** The journal file is closed and deleted using sqlite3OsDelete().
  49413. **
  49414. ** If the pager is running in exclusive mode, this method of finalizing
  49415. ** the journal file is never used. Instead, if the journalMode is
  49416. ** DELETE and the pager is in exclusive mode, the method described under
  49417. ** journalMode==PERSIST is used instead.
  49418. **
  49419. ** After the journal is finalized, the pager moves to PAGER_READER state.
  49420. ** If running in non-exclusive rollback mode, the lock on the file is
  49421. ** downgraded to a SHARED_LOCK.
  49422. **
  49423. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  49424. ** any of the IO operations to finalize the journal file or unlock the
  49425. ** database then the IO error code is returned to the user. If the
  49426. ** operation to finalize the journal file fails, then the code still
  49427. ** tries to unlock the database file if not in exclusive mode. If the
  49428. ** unlock operation fails as well, then the first error code related
  49429. ** to the first error encountered (the journal finalization one) is
  49430. ** returned.
  49431. */
  49432. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  49433. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  49434. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  49435. /* Do nothing if the pager does not have an open write transaction
  49436. ** or at least a RESERVED lock. This function may be called when there
  49437. ** is no write-transaction active but a RESERVED or greater lock is
  49438. ** held under two circumstances:
  49439. **
  49440. ** 1. After a successful hot-journal rollback, it is called with
  49441. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  49442. **
  49443. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  49444. ** lock switches back to locking_mode=normal and then executes a
  49445. ** read-transaction, this function is called with eState==PAGER_READER
  49446. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  49447. */
  49448. assert( assert_pager_state(pPager) );
  49449. assert( pPager->eState!=PAGER_ERROR );
  49450. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  49451. return SQLITE_OK;
  49452. }
  49453. releaseAllSavepoints(pPager);
  49454. assert( isOpen(pPager->jfd) || pPager->pInJournal==0
  49455. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  49456. );
  49457. if( isOpen(pPager->jfd) ){
  49458. assert( !pagerUseWal(pPager) );
  49459. /* Finalize the journal file. */
  49460. if( sqlite3JournalIsInMemory(pPager->jfd) ){
  49461. /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
  49462. sqlite3OsClose(pPager->jfd);
  49463. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  49464. if( pPager->journalOff==0 ){
  49465. rc = SQLITE_OK;
  49466. }else{
  49467. rc = sqlite3OsTruncate(pPager->jfd, 0);
  49468. if( rc==SQLITE_OK && pPager->fullSync ){
  49469. /* Make sure the new file size is written into the inode right away.
  49470. ** Otherwise the journal might resurrect following a power loss and
  49471. ** cause the last transaction to roll back. See
  49472. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  49473. */
  49474. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  49475. }
  49476. }
  49477. pPager->journalOff = 0;
  49478. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  49479. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  49480. ){
  49481. rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
  49482. pPager->journalOff = 0;
  49483. }else{
  49484. /* This branch may be executed with Pager.journalMode==MEMORY if
  49485. ** a hot-journal was just rolled back. In this case the journal
  49486. ** file should be closed and deleted. If this connection writes to
  49487. ** the database file, it will do so using an in-memory journal.
  49488. */
  49489. int bDelete = !pPager->tempFile;
  49490. assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
  49491. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  49492. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  49493. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  49494. );
  49495. sqlite3OsClose(pPager->jfd);
  49496. if( bDelete ){
  49497. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
  49498. }
  49499. }
  49500. }
  49501. #ifdef SQLITE_CHECK_PAGES
  49502. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  49503. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  49504. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  49505. if( p ){
  49506. p->pageHash = 0;
  49507. sqlite3PagerUnrefNotNull(p);
  49508. }
  49509. }
  49510. #endif
  49511. sqlite3BitvecDestroy(pPager->pInJournal);
  49512. pPager->pInJournal = 0;
  49513. pPager->nRec = 0;
  49514. if( rc==SQLITE_OK ){
  49515. if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
  49516. sqlite3PcacheCleanAll(pPager->pPCache);
  49517. }else{
  49518. sqlite3PcacheClearWritable(pPager->pPCache);
  49519. }
  49520. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  49521. }
  49522. if( pagerUseWal(pPager) ){
  49523. /* Drop the WAL write-lock, if any. Also, if the connection was in
  49524. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  49525. ** lock held on the database file.
  49526. */
  49527. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  49528. assert( rc2==SQLITE_OK );
  49529. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  49530. /* This branch is taken when committing a transaction in rollback-journal
  49531. ** mode if the database file on disk is larger than the database image.
  49532. ** At this point the journal has been finalized and the transaction
  49533. ** successfully committed, but the EXCLUSIVE lock is still held on the
  49534. ** file. So it is safe to truncate the database file to its minimum
  49535. ** required size. */
  49536. assert( pPager->eLock==EXCLUSIVE_LOCK );
  49537. rc = pager_truncate(pPager, pPager->dbSize);
  49538. }
  49539. if( rc==SQLITE_OK && bCommit ){
  49540. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  49541. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  49542. }
  49543. if( !pPager->exclusiveMode
  49544. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  49545. ){
  49546. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  49547. pPager->changeCountDone = 0;
  49548. }
  49549. pPager->eState = PAGER_READER;
  49550. pPager->setMaster = 0;
  49551. return (rc==SQLITE_OK?rc2:rc);
  49552. }
  49553. /*
  49554. ** Execute a rollback if a transaction is active and unlock the
  49555. ** database file.
  49556. **
  49557. ** If the pager has already entered the ERROR state, do not attempt
  49558. ** the rollback at this time. Instead, pager_unlock() is called. The
  49559. ** call to pager_unlock() will discard all in-memory pages, unlock
  49560. ** the database file and move the pager back to OPEN state. If this
  49561. ** means that there is a hot-journal left in the file-system, the next
  49562. ** connection to obtain a shared lock on the pager (which may be this one)
  49563. ** will roll it back.
  49564. **
  49565. ** If the pager has not already entered the ERROR state, but an IO or
  49566. ** malloc error occurs during a rollback, then this will itself cause
  49567. ** the pager to enter the ERROR state. Which will be cleared by the
  49568. ** call to pager_unlock(), as described above.
  49569. */
  49570. static void pagerUnlockAndRollback(Pager *pPager){
  49571. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  49572. assert( assert_pager_state(pPager) );
  49573. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  49574. sqlite3BeginBenignMalloc();
  49575. sqlite3PagerRollback(pPager);
  49576. sqlite3EndBenignMalloc();
  49577. }else if( !pPager->exclusiveMode ){
  49578. assert( pPager->eState==PAGER_READER );
  49579. pager_end_transaction(pPager, 0, 0);
  49580. }
  49581. }
  49582. pager_unlock(pPager);
  49583. }
  49584. /*
  49585. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  49586. ** of data. Compute and return a checksum based ont the contents of the
  49587. ** page of data and the current value of pPager->cksumInit.
  49588. **
  49589. ** This is not a real checksum. It is really just the sum of the
  49590. ** random initial value (pPager->cksumInit) and every 200th byte
  49591. ** of the page data, starting with byte offset (pPager->pageSize%200).
  49592. ** Each byte is interpreted as an 8-bit unsigned integer.
  49593. **
  49594. ** Changing the formula used to compute this checksum results in an
  49595. ** incompatible journal file format.
  49596. **
  49597. ** If journal corruption occurs due to a power failure, the most likely
  49598. ** scenario is that one end or the other of the record will be changed.
  49599. ** It is much less likely that the two ends of the journal record will be
  49600. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  49601. ** though fast and simple, catches the mostly likely kind of corruption.
  49602. */
  49603. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  49604. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  49605. int i = pPager->pageSize-200; /* Loop counter */
  49606. while( i>0 ){
  49607. cksum += aData[i];
  49608. i -= 200;
  49609. }
  49610. return cksum;
  49611. }
  49612. /*
  49613. ** Report the current page size and number of reserved bytes back
  49614. ** to the codec.
  49615. */
  49616. #ifdef SQLITE_HAS_CODEC
  49617. static void pagerReportSize(Pager *pPager){
  49618. if( pPager->xCodecSizeChng ){
  49619. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  49620. (int)pPager->nReserve);
  49621. }
  49622. }
  49623. #else
  49624. # define pagerReportSize(X) /* No-op if we do not support a codec */
  49625. #endif
  49626. #ifdef SQLITE_HAS_CODEC
  49627. /*
  49628. ** Make sure the number of reserved bits is the same in the destination
  49629. ** pager as it is in the source. This comes up when a VACUUM changes the
  49630. ** number of reserved bits to the "optimal" amount.
  49631. */
  49632. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
  49633. if( pDest->nReserve!=pSrc->nReserve ){
  49634. pDest->nReserve = pSrc->nReserve;
  49635. pagerReportSize(pDest);
  49636. }
  49637. }
  49638. #endif
  49639. /*
  49640. ** Read a single page from either the journal file (if isMainJrnl==1) or
  49641. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  49642. ** The page begins at offset *pOffset into the file. The *pOffset
  49643. ** value is increased to the start of the next page in the journal.
  49644. **
  49645. ** The main rollback journal uses checksums - the statement journal does
  49646. ** not.
  49647. **
  49648. ** If the page number of the page record read from the (sub-)journal file
  49649. ** is greater than the current value of Pager.dbSize, then playback is
  49650. ** skipped and SQLITE_OK is returned.
  49651. **
  49652. ** If pDone is not NULL, then it is a record of pages that have already
  49653. ** been played back. If the page at *pOffset has already been played back
  49654. ** (if the corresponding pDone bit is set) then skip the playback.
  49655. ** Make sure the pDone bit corresponding to the *pOffset page is set
  49656. ** prior to returning.
  49657. **
  49658. ** If the page record is successfully read from the (sub-)journal file
  49659. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  49660. ** while reading the record from the (sub-)journal file or while writing
  49661. ** to the database file, then the IO error code is returned. If data
  49662. ** is successfully read from the (sub-)journal file but appears to be
  49663. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  49664. ** two circumstances:
  49665. **
  49666. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  49667. ** * If the record is being rolled back from the main journal file
  49668. ** and the checksum field does not match the record content.
  49669. **
  49670. ** Neither of these two scenarios are possible during a savepoint rollback.
  49671. **
  49672. ** If this is a savepoint rollback, then memory may have to be dynamically
  49673. ** allocated by this function. If this is the case and an allocation fails,
  49674. ** SQLITE_NOMEM is returned.
  49675. */
  49676. static int pager_playback_one_page(
  49677. Pager *pPager, /* The pager being played back */
  49678. i64 *pOffset, /* Offset of record to playback */
  49679. Bitvec *pDone, /* Bitvec of pages already played back */
  49680. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  49681. int isSavepnt /* True for a savepoint rollback */
  49682. ){
  49683. int rc;
  49684. PgHdr *pPg; /* An existing page in the cache */
  49685. Pgno pgno; /* The page number of a page in journal */
  49686. u32 cksum; /* Checksum used for sanity checking */
  49687. char *aData; /* Temporary storage for the page */
  49688. sqlite3_file *jfd; /* The file descriptor for the journal file */
  49689. int isSynced; /* True if journal page is synced */
  49690. #ifdef SQLITE_HAS_CODEC
  49691. /* The jrnlEnc flag is true if Journal pages should be passed through
  49692. ** the codec. It is false for pure in-memory journals. */
  49693. const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
  49694. #endif
  49695. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  49696. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  49697. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  49698. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  49699. aData = pPager->pTmpSpace;
  49700. assert( aData ); /* Temp storage must have already been allocated */
  49701. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  49702. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  49703. ** or savepoint rollback done at the request of the caller) or this is
  49704. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  49705. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  49706. ** only reads from the main journal, not the sub-journal.
  49707. */
  49708. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  49709. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  49710. );
  49711. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  49712. /* Read the page number and page data from the journal or sub-journal
  49713. ** file. Return an error code to the caller if an IO error occurs.
  49714. */
  49715. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  49716. rc = read32bits(jfd, *pOffset, &pgno);
  49717. if( rc!=SQLITE_OK ) return rc;
  49718. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  49719. if( rc!=SQLITE_OK ) return rc;
  49720. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  49721. /* Sanity checking on the page. This is more important that I originally
  49722. ** thought. If a power failure occurs while the journal is being written,
  49723. ** it could cause invalid data to be written into the journal. We need to
  49724. ** detect this invalid data (with high probability) and ignore it.
  49725. */
  49726. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  49727. assert( !isSavepnt );
  49728. return SQLITE_DONE;
  49729. }
  49730. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  49731. return SQLITE_OK;
  49732. }
  49733. if( isMainJrnl ){
  49734. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  49735. if( rc ) return rc;
  49736. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  49737. return SQLITE_DONE;
  49738. }
  49739. }
  49740. /* If this page has already been played back before during the current
  49741. ** rollback, then don't bother to play it back again.
  49742. */
  49743. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  49744. return rc;
  49745. }
  49746. /* When playing back page 1, restore the nReserve setting
  49747. */
  49748. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  49749. pPager->nReserve = ((u8*)aData)[20];
  49750. pagerReportSize(pPager);
  49751. }
  49752. /* If the pager is in CACHEMOD state, then there must be a copy of this
  49753. ** page in the pager cache. In this case just update the pager cache,
  49754. ** not the database file. The page is left marked dirty in this case.
  49755. **
  49756. ** An exception to the above rule: If the database is in no-sync mode
  49757. ** and a page is moved during an incremental vacuum then the page may
  49758. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  49759. ** during a Movepage() call, then the page may not be in the cache
  49760. ** either. So the condition described in the above paragraph is not
  49761. ** assert()able.
  49762. **
  49763. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  49764. ** pager cache if it exists and the main file. The page is then marked
  49765. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  49766. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  49767. ** if the pager is in OPEN state.
  49768. **
  49769. ** Ticket #1171: The statement journal might contain page content that is
  49770. ** different from the page content at the start of the transaction.
  49771. ** This occurs when a page is changed prior to the start of a statement
  49772. ** then changed again within the statement. When rolling back such a
  49773. ** statement we must not write to the original database unless we know
  49774. ** for certain that original page contents are synced into the main rollback
  49775. ** journal. Otherwise, a power loss might leave modified data in the
  49776. ** database file without an entry in the rollback journal that can
  49777. ** restore the database to its original form. Two conditions must be
  49778. ** met before writing to the database files. (1) the database must be
  49779. ** locked. (2) we know that the original page content is fully synced
  49780. ** in the main journal either because the page is not in cache or else
  49781. ** the page is marked as needSync==0.
  49782. **
  49783. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  49784. ** is possible to fail a statement on a database that does not yet exist.
  49785. ** Do not attempt to write if database file has never been opened.
  49786. */
  49787. if( pagerUseWal(pPager) ){
  49788. pPg = 0;
  49789. }else{
  49790. pPg = sqlite3PagerLookup(pPager, pgno);
  49791. }
  49792. assert( pPg || !MEMDB );
  49793. assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
  49794. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  49795. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  49796. (isMainJrnl?"main-journal":"sub-journal")
  49797. ));
  49798. if( isMainJrnl ){
  49799. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  49800. }else{
  49801. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  49802. }
  49803. if( isOpen(pPager->fd)
  49804. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  49805. && isSynced
  49806. ){
  49807. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  49808. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  49809. assert( !pagerUseWal(pPager) );
  49810. /* Write the data read from the journal back into the database file.
  49811. ** This is usually safe even for an encrypted database - as the data
  49812. ** was encrypted before it was written to the journal file. The exception
  49813. ** is if the data was just read from an in-memory sub-journal. In that
  49814. ** case it must be encrypted here before it is copied into the database
  49815. ** file. */
  49816. #ifdef SQLITE_HAS_CODEC
  49817. if( !jrnlEnc ){
  49818. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
  49819. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  49820. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  49821. }else
  49822. #endif
  49823. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  49824. if( pgno>pPager->dbFileSize ){
  49825. pPager->dbFileSize = pgno;
  49826. }
  49827. if( pPager->pBackup ){
  49828. #ifdef SQLITE_HAS_CODEC
  49829. if( jrnlEnc ){
  49830. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  49831. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  49832. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
  49833. }else
  49834. #endif
  49835. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  49836. }
  49837. }else if( !isMainJrnl && pPg==0 ){
  49838. /* If this is a rollback of a savepoint and data was not written to
  49839. ** the database and the page is not in-memory, there is a potential
  49840. ** problem. When the page is next fetched by the b-tree layer, it
  49841. ** will be read from the database file, which may or may not be
  49842. ** current.
  49843. **
  49844. ** There are a couple of different ways this can happen. All are quite
  49845. ** obscure. When running in synchronous mode, this can only happen
  49846. ** if the page is on the free-list at the start of the transaction, then
  49847. ** populated, then moved using sqlite3PagerMovepage().
  49848. **
  49849. ** The solution is to add an in-memory page to the cache containing
  49850. ** the data just read from the sub-journal. Mark the page as dirty
  49851. ** and if the pager requires a journal-sync, then mark the page as
  49852. ** requiring a journal-sync before it is written.
  49853. */
  49854. assert( isSavepnt );
  49855. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  49856. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  49857. rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
  49858. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  49859. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  49860. if( rc!=SQLITE_OK ) return rc;
  49861. sqlite3PcacheMakeDirty(pPg);
  49862. }
  49863. if( pPg ){
  49864. /* No page should ever be explicitly rolled back that is in use, except
  49865. ** for page 1 which is held in use in order to keep the lock on the
  49866. ** database active. However such a page may be rolled back as a result
  49867. ** of an internal error resulting in an automatic call to
  49868. ** sqlite3PagerRollback().
  49869. */
  49870. void *pData;
  49871. pData = pPg->pData;
  49872. memcpy(pData, (u8*)aData, pPager->pageSize);
  49873. pPager->xReiniter(pPg);
  49874. /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
  49875. ** that call was dangerous and had no detectable benefit since the cache
  49876. ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
  49877. ** has been removed. */
  49878. pager_set_pagehash(pPg);
  49879. /* If this was page 1, then restore the value of Pager.dbFileVers.
  49880. ** Do this before any decoding. */
  49881. if( pgno==1 ){
  49882. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  49883. }
  49884. /* Decode the page just read from disk */
  49885. #if SQLITE_HAS_CODEC
  49886. if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
  49887. #endif
  49888. sqlite3PcacheRelease(pPg);
  49889. }
  49890. return rc;
  49891. }
  49892. /*
  49893. ** Parameter zMaster is the name of a master journal file. A single journal
  49894. ** file that referred to the master journal file has just been rolled back.
  49895. ** This routine checks if it is possible to delete the master journal file,
  49896. ** and does so if it is.
  49897. **
  49898. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  49899. ** available for use within this function.
  49900. **
  49901. ** When a master journal file is created, it is populated with the names
  49902. ** of all of its child journals, one after another, formatted as utf-8
  49903. ** encoded text. The end of each child journal file is marked with a
  49904. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  49905. ** file for a transaction involving two databases might be:
  49906. **
  49907. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  49908. **
  49909. ** A master journal file may only be deleted once all of its child
  49910. ** journals have been rolled back.
  49911. **
  49912. ** This function reads the contents of the master-journal file into
  49913. ** memory and loops through each of the child journal names. For
  49914. ** each child journal, it checks if:
  49915. **
  49916. ** * if the child journal exists, and if so
  49917. ** * if the child journal contains a reference to master journal
  49918. ** file zMaster
  49919. **
  49920. ** If a child journal can be found that matches both of the criteria
  49921. ** above, this function returns without doing anything. Otherwise, if
  49922. ** no such child journal can be found, file zMaster is deleted from
  49923. ** the file-system using sqlite3OsDelete().
  49924. **
  49925. ** If an IO error within this function, an error code is returned. This
  49926. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  49927. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  49928. ** occur, SQLITE_OK is returned.
  49929. **
  49930. ** TODO: This function allocates a single block of memory to load
  49931. ** the entire contents of the master journal file. This could be
  49932. ** a couple of kilobytes or so - potentially larger than the page
  49933. ** size.
  49934. */
  49935. static int pager_delmaster(Pager *pPager, const char *zMaster){
  49936. sqlite3_vfs *pVfs = pPager->pVfs;
  49937. int rc; /* Return code */
  49938. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  49939. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  49940. char *zMasterJournal = 0; /* Contents of master journal file */
  49941. i64 nMasterJournal; /* Size of master journal file */
  49942. char *zJournal; /* Pointer to one journal within MJ file */
  49943. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  49944. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  49945. /* Allocate space for both the pJournal and pMaster file descriptors.
  49946. ** If successful, open the master journal file for reading.
  49947. */
  49948. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  49949. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  49950. if( !pMaster ){
  49951. rc = SQLITE_NOMEM_BKPT;
  49952. }else{
  49953. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  49954. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  49955. }
  49956. if( rc!=SQLITE_OK ) goto delmaster_out;
  49957. /* Load the entire master journal file into space obtained from
  49958. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  49959. ** sufficient space (in zMasterPtr) to hold the names of master
  49960. ** journal files extracted from regular rollback-journals.
  49961. */
  49962. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  49963. if( rc!=SQLITE_OK ) goto delmaster_out;
  49964. nMasterPtr = pVfs->mxPathname+1;
  49965. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  49966. if( !zMasterJournal ){
  49967. rc = SQLITE_NOMEM_BKPT;
  49968. goto delmaster_out;
  49969. }
  49970. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  49971. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  49972. if( rc!=SQLITE_OK ) goto delmaster_out;
  49973. zMasterJournal[nMasterJournal] = 0;
  49974. zJournal = zMasterJournal;
  49975. while( (zJournal-zMasterJournal)<nMasterJournal ){
  49976. int exists;
  49977. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  49978. if( rc!=SQLITE_OK ){
  49979. goto delmaster_out;
  49980. }
  49981. if( exists ){
  49982. /* One of the journals pointed to by the master journal exists.
  49983. ** Open it and check if it points at the master journal. If
  49984. ** so, return without deleting the master journal file.
  49985. */
  49986. int c;
  49987. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  49988. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  49989. if( rc!=SQLITE_OK ){
  49990. goto delmaster_out;
  49991. }
  49992. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  49993. sqlite3OsClose(pJournal);
  49994. if( rc!=SQLITE_OK ){
  49995. goto delmaster_out;
  49996. }
  49997. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  49998. if( c ){
  49999. /* We have a match. Do not delete the master journal file. */
  50000. goto delmaster_out;
  50001. }
  50002. }
  50003. zJournal += (sqlite3Strlen30(zJournal)+1);
  50004. }
  50005. sqlite3OsClose(pMaster);
  50006. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  50007. delmaster_out:
  50008. sqlite3_free(zMasterJournal);
  50009. if( pMaster ){
  50010. sqlite3OsClose(pMaster);
  50011. assert( !isOpen(pJournal) );
  50012. sqlite3_free(pMaster);
  50013. }
  50014. return rc;
  50015. }
  50016. /*
  50017. ** This function is used to change the actual size of the database
  50018. ** file in the file-system. This only happens when committing a transaction,
  50019. ** or rolling back a transaction (including rolling back a hot-journal).
  50020. **
  50021. ** If the main database file is not open, or the pager is not in either
  50022. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  50023. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  50024. ** If the file on disk is currently larger than nPage pages, then use the VFS
  50025. ** xTruncate() method to truncate it.
  50026. **
  50027. ** Or, it might be the case that the file on disk is smaller than
  50028. ** nPage pages. Some operating system implementations can get confused if
  50029. ** you try to truncate a file to some size that is larger than it
  50030. ** currently is, so detect this case and write a single zero byte to
  50031. ** the end of the new file instead.
  50032. **
  50033. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  50034. ** the database file, return the error code to the caller.
  50035. */
  50036. static int pager_truncate(Pager *pPager, Pgno nPage){
  50037. int rc = SQLITE_OK;
  50038. assert( pPager->eState!=PAGER_ERROR );
  50039. assert( pPager->eState!=PAGER_READER );
  50040. if( isOpen(pPager->fd)
  50041. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  50042. ){
  50043. i64 currentSize, newSize;
  50044. int szPage = pPager->pageSize;
  50045. assert( pPager->eLock==EXCLUSIVE_LOCK );
  50046. /* TODO: Is it safe to use Pager.dbFileSize here? */
  50047. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  50048. newSize = szPage*(i64)nPage;
  50049. if( rc==SQLITE_OK && currentSize!=newSize ){
  50050. if( currentSize>newSize ){
  50051. rc = sqlite3OsTruncate(pPager->fd, newSize);
  50052. }else if( (currentSize+szPage)<=newSize ){
  50053. char *pTmp = pPager->pTmpSpace;
  50054. memset(pTmp, 0, szPage);
  50055. testcase( (newSize-szPage) == currentSize );
  50056. testcase( (newSize-szPage) > currentSize );
  50057. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  50058. }
  50059. if( rc==SQLITE_OK ){
  50060. pPager->dbFileSize = nPage;
  50061. }
  50062. }
  50063. }
  50064. return rc;
  50065. }
  50066. /*
  50067. ** Return a sanitized version of the sector-size of OS file pFile. The
  50068. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  50069. */
  50070. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  50071. int iRet = sqlite3OsSectorSize(pFile);
  50072. if( iRet<32 ){
  50073. iRet = 512;
  50074. }else if( iRet>MAX_SECTOR_SIZE ){
  50075. assert( MAX_SECTOR_SIZE>=512 );
  50076. iRet = MAX_SECTOR_SIZE;
  50077. }
  50078. return iRet;
  50079. }
  50080. /*
  50081. ** Set the value of the Pager.sectorSize variable for the given
  50082. ** pager based on the value returned by the xSectorSize method
  50083. ** of the open database file. The sector size will be used
  50084. ** to determine the size and alignment of journal header and
  50085. ** master journal pointers within created journal files.
  50086. **
  50087. ** For temporary files the effective sector size is always 512 bytes.
  50088. **
  50089. ** Otherwise, for non-temporary files, the effective sector size is
  50090. ** the value returned by the xSectorSize() method rounded up to 32 if
  50091. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  50092. ** is greater than MAX_SECTOR_SIZE.
  50093. **
  50094. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  50095. ** the effective sector size to its minimum value (512). The purpose of
  50096. ** pPager->sectorSize is to define the "blast radius" of bytes that
  50097. ** might change if a crash occurs while writing to a single byte in
  50098. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  50099. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  50100. ** size. For backwards compatibility of the rollback journal file format,
  50101. ** we cannot reduce the effective sector size below 512.
  50102. */
  50103. static void setSectorSize(Pager *pPager){
  50104. assert( isOpen(pPager->fd) || pPager->tempFile );
  50105. if( pPager->tempFile
  50106. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  50107. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  50108. ){
  50109. /* Sector size doesn't matter for temporary files. Also, the file
  50110. ** may not have been opened yet, in which case the OsSectorSize()
  50111. ** call will segfault. */
  50112. pPager->sectorSize = 512;
  50113. }else{
  50114. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  50115. }
  50116. }
  50117. /*
  50118. ** Playback the journal and thus restore the database file to
  50119. ** the state it was in before we started making changes.
  50120. **
  50121. ** The journal file format is as follows:
  50122. **
  50123. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  50124. ** (2) 4 byte big-endian integer which is the number of valid page records
  50125. ** in the journal. If this value is 0xffffffff, then compute the
  50126. ** number of page records from the journal size.
  50127. ** (3) 4 byte big-endian integer which is the initial value for the
  50128. ** sanity checksum.
  50129. ** (4) 4 byte integer which is the number of pages to truncate the
  50130. ** database to during a rollback.
  50131. ** (5) 4 byte big-endian integer which is the sector size. The header
  50132. ** is this many bytes in size.
  50133. ** (6) 4 byte big-endian integer which is the page size.
  50134. ** (7) zero padding out to the next sector size.
  50135. ** (8) Zero or more pages instances, each as follows:
  50136. ** + 4 byte page number.
  50137. ** + pPager->pageSize bytes of data.
  50138. ** + 4 byte checksum
  50139. **
  50140. ** When we speak of the journal header, we mean the first 7 items above.
  50141. ** Each entry in the journal is an instance of the 8th item.
  50142. **
  50143. ** Call the value from the second bullet "nRec". nRec is the number of
  50144. ** valid page entries in the journal. In most cases, you can compute the
  50145. ** value of nRec from the size of the journal file. But if a power
  50146. ** failure occurred while the journal was being written, it could be the
  50147. ** case that the size of the journal file had already been increased but
  50148. ** the extra entries had not yet made it safely to disk. In such a case,
  50149. ** the value of nRec computed from the file size would be too large. For
  50150. ** that reason, we always use the nRec value in the header.
  50151. **
  50152. ** If the nRec value is 0xffffffff it means that nRec should be computed
  50153. ** from the file size. This value is used when the user selects the
  50154. ** no-sync option for the journal. A power failure could lead to corruption
  50155. ** in this case. But for things like temporary table (which will be
  50156. ** deleted when the power is restored) we don't care.
  50157. **
  50158. ** If the file opened as the journal file is not a well-formed
  50159. ** journal file then all pages up to the first corrupted page are rolled
  50160. ** back (or no pages if the journal header is corrupted). The journal file
  50161. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  50162. ** been encountered.
  50163. **
  50164. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  50165. ** and an error code is returned.
  50166. **
  50167. ** The isHot parameter indicates that we are trying to rollback a journal
  50168. ** that might be a hot journal. Or, it could be that the journal is
  50169. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  50170. ** If the journal really is hot, reset the pager cache prior rolling
  50171. ** back any content. If the journal is merely persistent, no reset is
  50172. ** needed.
  50173. */
  50174. static int pager_playback(Pager *pPager, int isHot){
  50175. sqlite3_vfs *pVfs = pPager->pVfs;
  50176. i64 szJ; /* Size of the journal file in bytes */
  50177. u32 nRec; /* Number of Records in the journal */
  50178. u32 u; /* Unsigned loop counter */
  50179. Pgno mxPg = 0; /* Size of the original file in pages */
  50180. int rc; /* Result code of a subroutine */
  50181. int res = 1; /* Value returned by sqlite3OsAccess() */
  50182. char *zMaster = 0; /* Name of master journal file if any */
  50183. int needPagerReset; /* True to reset page prior to first page rollback */
  50184. int nPlayback = 0; /* Total number of pages restored from journal */
  50185. u32 savedPageSize = pPager->pageSize;
  50186. /* Figure out how many records are in the journal. Abort early if
  50187. ** the journal is empty.
  50188. */
  50189. assert( isOpen(pPager->jfd) );
  50190. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  50191. if( rc!=SQLITE_OK ){
  50192. goto end_playback;
  50193. }
  50194. /* Read the master journal name from the journal, if it is present.
  50195. ** If a master journal file name is specified, but the file is not
  50196. ** present on disk, then the journal is not hot and does not need to be
  50197. ** played back.
  50198. **
  50199. ** TODO: Technically the following is an error because it assumes that
  50200. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  50201. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  50202. ** mxPathname is 512, which is the same as the minimum allowable value
  50203. ** for pageSize.
  50204. */
  50205. zMaster = pPager->pTmpSpace;
  50206. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  50207. if( rc==SQLITE_OK && zMaster[0] ){
  50208. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  50209. }
  50210. zMaster = 0;
  50211. if( rc!=SQLITE_OK || !res ){
  50212. goto end_playback;
  50213. }
  50214. pPager->journalOff = 0;
  50215. needPagerReset = isHot;
  50216. /* This loop terminates either when a readJournalHdr() or
  50217. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  50218. ** occurs.
  50219. */
  50220. while( 1 ){
  50221. /* Read the next journal header from the journal file. If there are
  50222. ** not enough bytes left in the journal file for a complete header, or
  50223. ** it is corrupted, then a process must have failed while writing it.
  50224. ** This indicates nothing more needs to be rolled back.
  50225. */
  50226. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  50227. if( rc!=SQLITE_OK ){
  50228. if( rc==SQLITE_DONE ){
  50229. rc = SQLITE_OK;
  50230. }
  50231. goto end_playback;
  50232. }
  50233. /* If nRec is 0xffffffff, then this journal was created by a process
  50234. ** working in no-sync mode. This means that the rest of the journal
  50235. ** file consists of pages, there are no more journal headers. Compute
  50236. ** the value of nRec based on this assumption.
  50237. */
  50238. if( nRec==0xffffffff ){
  50239. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  50240. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  50241. }
  50242. /* If nRec is 0 and this rollback is of a transaction created by this
  50243. ** process and if this is the final header in the journal, then it means
  50244. ** that this part of the journal was being filled but has not yet been
  50245. ** synced to disk. Compute the number of pages based on the remaining
  50246. ** size of the file.
  50247. **
  50248. ** The third term of the test was added to fix ticket #2565.
  50249. ** When rolling back a hot journal, nRec==0 always means that the next
  50250. ** chunk of the journal contains zero pages to be rolled back. But
  50251. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  50252. ** the journal, it means that the journal might contain additional
  50253. ** pages that need to be rolled back and that the number of pages
  50254. ** should be computed based on the journal file size.
  50255. */
  50256. if( nRec==0 && !isHot &&
  50257. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  50258. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  50259. }
  50260. /* If this is the first header read from the journal, truncate the
  50261. ** database file back to its original size.
  50262. */
  50263. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  50264. rc = pager_truncate(pPager, mxPg);
  50265. if( rc!=SQLITE_OK ){
  50266. goto end_playback;
  50267. }
  50268. pPager->dbSize = mxPg;
  50269. }
  50270. /* Copy original pages out of the journal and back into the
  50271. ** database file and/or page cache.
  50272. */
  50273. for(u=0; u<nRec; u++){
  50274. if( needPagerReset ){
  50275. pager_reset(pPager);
  50276. needPagerReset = 0;
  50277. }
  50278. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  50279. if( rc==SQLITE_OK ){
  50280. nPlayback++;
  50281. }else{
  50282. if( rc==SQLITE_DONE ){
  50283. pPager->journalOff = szJ;
  50284. break;
  50285. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  50286. /* If the journal has been truncated, simply stop reading and
  50287. ** processing the journal. This might happen if the journal was
  50288. ** not completely written and synced prior to a crash. In that
  50289. ** case, the database should have never been written in the
  50290. ** first place so it is OK to simply abandon the rollback. */
  50291. rc = SQLITE_OK;
  50292. goto end_playback;
  50293. }else{
  50294. /* If we are unable to rollback, quit and return the error
  50295. ** code. This will cause the pager to enter the error state
  50296. ** so that no further harm will be done. Perhaps the next
  50297. ** process to come along will be able to rollback the database.
  50298. */
  50299. goto end_playback;
  50300. }
  50301. }
  50302. }
  50303. }
  50304. /*NOTREACHED*/
  50305. assert( 0 );
  50306. end_playback:
  50307. if( rc==SQLITE_OK ){
  50308. rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
  50309. }
  50310. /* Following a rollback, the database file should be back in its original
  50311. ** state prior to the start of the transaction, so invoke the
  50312. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  50313. ** assertion that the transaction counter was modified.
  50314. */
  50315. #ifdef SQLITE_DEBUG
  50316. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  50317. #endif
  50318. /* If this playback is happening automatically as a result of an IO or
  50319. ** malloc error that occurred after the change-counter was updated but
  50320. ** before the transaction was committed, then the change-counter
  50321. ** modification may just have been reverted. If this happens in exclusive
  50322. ** mode, then subsequent transactions performed by the connection will not
  50323. ** update the change-counter at all. This may lead to cache inconsistency
  50324. ** problems for other processes at some point in the future. So, just
  50325. ** in case this has happened, clear the changeCountDone flag now.
  50326. */
  50327. pPager->changeCountDone = pPager->tempFile;
  50328. if( rc==SQLITE_OK ){
  50329. zMaster = pPager->pTmpSpace;
  50330. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  50331. testcase( rc!=SQLITE_OK );
  50332. }
  50333. if( rc==SQLITE_OK
  50334. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  50335. ){
  50336. rc = sqlite3PagerSync(pPager, 0);
  50337. }
  50338. if( rc==SQLITE_OK ){
  50339. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  50340. testcase( rc!=SQLITE_OK );
  50341. }
  50342. if( rc==SQLITE_OK && zMaster[0] && res ){
  50343. /* If there was a master journal and this routine will return success,
  50344. ** see if it is possible to delete the master journal.
  50345. */
  50346. rc = pager_delmaster(pPager, zMaster);
  50347. testcase( rc!=SQLITE_OK );
  50348. }
  50349. if( isHot && nPlayback ){
  50350. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  50351. nPlayback, pPager->zJournal);
  50352. }
  50353. /* The Pager.sectorSize variable may have been updated while rolling
  50354. ** back a journal created by a process with a different sector size
  50355. ** value. Reset it to the correct value for this process.
  50356. */
  50357. setSectorSize(pPager);
  50358. return rc;
  50359. }
  50360. /*
  50361. ** Read the content for page pPg out of the database file (or out of
  50362. ** the WAL if that is where the most recent copy if found) into
  50363. ** pPg->pData. A shared lock or greater must be held on the database
  50364. ** file before this function is called.
  50365. **
  50366. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  50367. ** the value read from the database file.
  50368. **
  50369. ** If an IO error occurs, then the IO error is returned to the caller.
  50370. ** Otherwise, SQLITE_OK is returned.
  50371. */
  50372. static int readDbPage(PgHdr *pPg){
  50373. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  50374. int rc = SQLITE_OK; /* Return code */
  50375. #ifndef SQLITE_OMIT_WAL
  50376. u32 iFrame = 0; /* Frame of WAL containing pgno */
  50377. assert( pPager->eState>=PAGER_READER && !MEMDB );
  50378. assert( isOpen(pPager->fd) );
  50379. if( pagerUseWal(pPager) ){
  50380. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  50381. if( rc ) return rc;
  50382. }
  50383. if( iFrame ){
  50384. rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
  50385. }else
  50386. #endif
  50387. {
  50388. i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
  50389. rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
  50390. if( rc==SQLITE_IOERR_SHORT_READ ){
  50391. rc = SQLITE_OK;
  50392. }
  50393. }
  50394. if( pPg->pgno==1 ){
  50395. if( rc ){
  50396. /* If the read is unsuccessful, set the dbFileVers[] to something
  50397. ** that will never be a valid file version. dbFileVers[] is a copy
  50398. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  50399. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  50400. ** should be page numbers which are never 0xffffffff. So filling
  50401. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  50402. **
  50403. ** For an encrypted database, the situation is more complex: bytes
  50404. ** 24..39 of the database are white noise. But the probability of
  50405. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  50406. ** we should still be ok.
  50407. */
  50408. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  50409. }else{
  50410. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  50411. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  50412. }
  50413. }
  50414. CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
  50415. PAGER_INCR(sqlite3_pager_readdb_count);
  50416. PAGER_INCR(pPager->nRead);
  50417. IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
  50418. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  50419. PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
  50420. return rc;
  50421. }
  50422. /*
  50423. ** Update the value of the change-counter at offsets 24 and 92 in
  50424. ** the header and the sqlite version number at offset 96.
  50425. **
  50426. ** This is an unconditional update. See also the pager_incr_changecounter()
  50427. ** routine which only updates the change-counter if the update is actually
  50428. ** needed, as determined by the pPager->changeCountDone state variable.
  50429. */
  50430. static void pager_write_changecounter(PgHdr *pPg){
  50431. u32 change_counter;
  50432. /* Increment the value just read and write it back to byte 24. */
  50433. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  50434. put32bits(((char*)pPg->pData)+24, change_counter);
  50435. /* Also store the SQLite version number in bytes 96..99 and in
  50436. ** bytes 92..95 store the change counter for which the version number
  50437. ** is valid. */
  50438. put32bits(((char*)pPg->pData)+92, change_counter);
  50439. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  50440. }
  50441. #ifndef SQLITE_OMIT_WAL
  50442. /*
  50443. ** This function is invoked once for each page that has already been
  50444. ** written into the log file when a WAL transaction is rolled back.
  50445. ** Parameter iPg is the page number of said page. The pCtx argument
  50446. ** is actually a pointer to the Pager structure.
  50447. **
  50448. ** If page iPg is present in the cache, and has no outstanding references,
  50449. ** it is discarded. Otherwise, if there are one or more outstanding
  50450. ** references, the page content is reloaded from the database. If the
  50451. ** attempt to reload content from the database is required and fails,
  50452. ** return an SQLite error code. Otherwise, SQLITE_OK.
  50453. */
  50454. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  50455. int rc = SQLITE_OK;
  50456. Pager *pPager = (Pager *)pCtx;
  50457. PgHdr *pPg;
  50458. assert( pagerUseWal(pPager) );
  50459. pPg = sqlite3PagerLookup(pPager, iPg);
  50460. if( pPg ){
  50461. if( sqlite3PcachePageRefcount(pPg)==1 ){
  50462. sqlite3PcacheDrop(pPg);
  50463. }else{
  50464. rc = readDbPage(pPg);
  50465. if( rc==SQLITE_OK ){
  50466. pPager->xReiniter(pPg);
  50467. }
  50468. sqlite3PagerUnrefNotNull(pPg);
  50469. }
  50470. }
  50471. /* Normally, if a transaction is rolled back, any backup processes are
  50472. ** updated as data is copied out of the rollback journal and into the
  50473. ** database. This is not generally possible with a WAL database, as
  50474. ** rollback involves simply truncating the log file. Therefore, if one
  50475. ** or more frames have already been written to the log (and therefore
  50476. ** also copied into the backup databases) as part of this transaction,
  50477. ** the backups must be restarted.
  50478. */
  50479. sqlite3BackupRestart(pPager->pBackup);
  50480. return rc;
  50481. }
  50482. /*
  50483. ** This function is called to rollback a transaction on a WAL database.
  50484. */
  50485. static int pagerRollbackWal(Pager *pPager){
  50486. int rc; /* Return Code */
  50487. PgHdr *pList; /* List of dirty pages to revert */
  50488. /* For all pages in the cache that are currently dirty or have already
  50489. ** been written (but not committed) to the log file, do one of the
  50490. ** following:
  50491. **
  50492. ** + Discard the cached page (if refcount==0), or
  50493. ** + Reload page content from the database (if refcount>0).
  50494. */
  50495. pPager->dbSize = pPager->dbOrigSize;
  50496. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  50497. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  50498. while( pList && rc==SQLITE_OK ){
  50499. PgHdr *pNext = pList->pDirty;
  50500. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  50501. pList = pNext;
  50502. }
  50503. return rc;
  50504. }
  50505. /*
  50506. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  50507. ** the contents of the list of pages headed by pList (connected by pDirty),
  50508. ** this function notifies any active backup processes that the pages have
  50509. ** changed.
  50510. **
  50511. ** The list of pages passed into this routine is always sorted by page number.
  50512. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  50513. */
  50514. static int pagerWalFrames(
  50515. Pager *pPager, /* Pager object */
  50516. PgHdr *pList, /* List of frames to log */
  50517. Pgno nTruncate, /* Database size after this commit */
  50518. int isCommit /* True if this is a commit */
  50519. ){
  50520. int rc; /* Return code */
  50521. int nList; /* Number of pages in pList */
  50522. PgHdr *p; /* For looping over pages */
  50523. assert( pPager->pWal );
  50524. assert( pList );
  50525. #ifdef SQLITE_DEBUG
  50526. /* Verify that the page list is in accending order */
  50527. for(p=pList; p && p->pDirty; p=p->pDirty){
  50528. assert( p->pgno < p->pDirty->pgno );
  50529. }
  50530. #endif
  50531. assert( pList->pDirty==0 || isCommit );
  50532. if( isCommit ){
  50533. /* If a WAL transaction is being committed, there is no point in writing
  50534. ** any pages with page numbers greater than nTruncate into the WAL file.
  50535. ** They will never be read by any client. So remove them from the pDirty
  50536. ** list here. */
  50537. PgHdr **ppNext = &pList;
  50538. nList = 0;
  50539. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  50540. if( p->pgno<=nTruncate ){
  50541. ppNext = &p->pDirty;
  50542. nList++;
  50543. }
  50544. }
  50545. assert( pList );
  50546. }else{
  50547. nList = 1;
  50548. }
  50549. pPager->aStat[PAGER_STAT_WRITE] += nList;
  50550. if( pList->pgno==1 ) pager_write_changecounter(pList);
  50551. rc = sqlite3WalFrames(pPager->pWal,
  50552. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  50553. );
  50554. if( rc==SQLITE_OK && pPager->pBackup ){
  50555. for(p=pList; p; p=p->pDirty){
  50556. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  50557. }
  50558. }
  50559. #ifdef SQLITE_CHECK_PAGES
  50560. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  50561. for(p=pList; p; p=p->pDirty){
  50562. pager_set_pagehash(p);
  50563. }
  50564. #endif
  50565. return rc;
  50566. }
  50567. /*
  50568. ** Begin a read transaction on the WAL.
  50569. **
  50570. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  50571. ** makes a snapshot of the database at the current point in time and preserves
  50572. ** that snapshot for use by the reader in spite of concurrently changes by
  50573. ** other writers or checkpointers.
  50574. */
  50575. static int pagerBeginReadTransaction(Pager *pPager){
  50576. int rc; /* Return code */
  50577. int changed = 0; /* True if cache must be reset */
  50578. assert( pagerUseWal(pPager) );
  50579. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  50580. /* sqlite3WalEndReadTransaction() was not called for the previous
  50581. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  50582. ** are in locking_mode=NORMAL and EndRead() was previously called,
  50583. ** the duplicate call is harmless.
  50584. */
  50585. sqlite3WalEndReadTransaction(pPager->pWal);
  50586. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  50587. if( rc!=SQLITE_OK || changed ){
  50588. pager_reset(pPager);
  50589. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  50590. }
  50591. return rc;
  50592. }
  50593. #endif
  50594. /*
  50595. ** This function is called as part of the transition from PAGER_OPEN
  50596. ** to PAGER_READER state to determine the size of the database file
  50597. ** in pages (assuming the page size currently stored in Pager.pageSize).
  50598. **
  50599. ** If no error occurs, SQLITE_OK is returned and the size of the database
  50600. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  50601. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  50602. */
  50603. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  50604. Pgno nPage; /* Value to return via *pnPage */
  50605. /* Query the WAL sub-system for the database size. The WalDbsize()
  50606. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  50607. ** if the database size is not available. The database size is not
  50608. ** available from the WAL sub-system if the log file is empty or
  50609. ** contains no valid committed transactions.
  50610. */
  50611. assert( pPager->eState==PAGER_OPEN );
  50612. assert( pPager->eLock>=SHARED_LOCK );
  50613. assert( isOpen(pPager->fd) );
  50614. assert( pPager->tempFile==0 );
  50615. nPage = sqlite3WalDbsize(pPager->pWal);
  50616. /* If the number of pages in the database is not available from the
  50617. ** WAL sub-system, determine the page count based on the size of
  50618. ** the database file. If the size of the database file is not an
  50619. ** integer multiple of the page-size, round up the result.
  50620. */
  50621. if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
  50622. i64 n = 0; /* Size of db file in bytes */
  50623. int rc = sqlite3OsFileSize(pPager->fd, &n);
  50624. if( rc!=SQLITE_OK ){
  50625. return rc;
  50626. }
  50627. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  50628. }
  50629. /* If the current number of pages in the file is greater than the
  50630. ** configured maximum pager number, increase the allowed limit so
  50631. ** that the file can be read.
  50632. */
  50633. if( nPage>pPager->mxPgno ){
  50634. pPager->mxPgno = (Pgno)nPage;
  50635. }
  50636. *pnPage = nPage;
  50637. return SQLITE_OK;
  50638. }
  50639. #ifndef SQLITE_OMIT_WAL
  50640. /*
  50641. ** Check if the *-wal file that corresponds to the database opened by pPager
  50642. ** exists if the database is not empy, or verify that the *-wal file does
  50643. ** not exist (by deleting it) if the database file is empty.
  50644. **
  50645. ** If the database is not empty and the *-wal file exists, open the pager
  50646. ** in WAL mode. If the database is empty or if no *-wal file exists and
  50647. ** if no error occurs, make sure Pager.journalMode is not set to
  50648. ** PAGER_JOURNALMODE_WAL.
  50649. **
  50650. ** Return SQLITE_OK or an error code.
  50651. **
  50652. ** The caller must hold a SHARED lock on the database file to call this
  50653. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  50654. ** a WAL on a none-empty database, this ensures there is no race condition
  50655. ** between the xAccess() below and an xDelete() being executed by some
  50656. ** other connection.
  50657. */
  50658. static int pagerOpenWalIfPresent(Pager *pPager){
  50659. int rc = SQLITE_OK;
  50660. assert( pPager->eState==PAGER_OPEN );
  50661. assert( pPager->eLock>=SHARED_LOCK );
  50662. if( !pPager->tempFile ){
  50663. int isWal; /* True if WAL file exists */
  50664. rc = sqlite3OsAccess(
  50665. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  50666. );
  50667. if( rc==SQLITE_OK ){
  50668. if( isWal ){
  50669. Pgno nPage; /* Size of the database file */
  50670. rc = pagerPagecount(pPager, &nPage);
  50671. if( rc ) return rc;
  50672. if( nPage==0 ){
  50673. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  50674. }else{
  50675. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  50676. rc = sqlite3PagerOpenWal(pPager, 0);
  50677. }
  50678. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  50679. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  50680. }
  50681. }
  50682. }
  50683. return rc;
  50684. }
  50685. #endif
  50686. /*
  50687. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  50688. ** the entire master journal file. The case pSavepoint==NULL occurs when
  50689. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  50690. ** savepoint.
  50691. **
  50692. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  50693. ** being rolled back), then the rollback consists of up to three stages,
  50694. ** performed in the order specified:
  50695. **
  50696. ** * Pages are played back from the main journal starting at byte
  50697. ** offset PagerSavepoint.iOffset and continuing to
  50698. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  50699. ** file if PagerSavepoint.iHdrOffset is zero.
  50700. **
  50701. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  50702. ** back starting from the journal header immediately following
  50703. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  50704. **
  50705. ** * Pages are then played back from the sub-journal file, starting
  50706. ** with the PagerSavepoint.iSubRec and continuing to the end of
  50707. ** the journal file.
  50708. **
  50709. ** Throughout the rollback process, each time a page is rolled back, the
  50710. ** corresponding bit is set in a bitvec structure (variable pDone in the
  50711. ** implementation below). This is used to ensure that a page is only
  50712. ** rolled back the first time it is encountered in either journal.
  50713. **
  50714. ** If pSavepoint is NULL, then pages are only played back from the main
  50715. ** journal file. There is no need for a bitvec in this case.
  50716. **
  50717. ** In either case, before playback commences the Pager.dbSize variable
  50718. ** is reset to the value that it held at the start of the savepoint
  50719. ** (or transaction). No page with a page-number greater than this value
  50720. ** is played back. If one is encountered it is simply skipped.
  50721. */
  50722. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  50723. i64 szJ; /* Effective size of the main journal */
  50724. i64 iHdrOff; /* End of first segment of main-journal records */
  50725. int rc = SQLITE_OK; /* Return code */
  50726. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  50727. assert( pPager->eState!=PAGER_ERROR );
  50728. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  50729. /* Allocate a bitvec to use to store the set of pages rolled back */
  50730. if( pSavepoint ){
  50731. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  50732. if( !pDone ){
  50733. return SQLITE_NOMEM_BKPT;
  50734. }
  50735. }
  50736. /* Set the database size back to the value it was before the savepoint
  50737. ** being reverted was opened.
  50738. */
  50739. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  50740. pPager->changeCountDone = pPager->tempFile;
  50741. if( !pSavepoint && pagerUseWal(pPager) ){
  50742. return pagerRollbackWal(pPager);
  50743. }
  50744. /* Use pPager->journalOff as the effective size of the main rollback
  50745. ** journal. The actual file might be larger than this in
  50746. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  50747. ** past pPager->journalOff is off-limits to us.
  50748. */
  50749. szJ = pPager->journalOff;
  50750. assert( pagerUseWal(pPager)==0 || szJ==0 );
  50751. /* Begin by rolling back records from the main journal starting at
  50752. ** PagerSavepoint.iOffset and continuing to the next journal header.
  50753. ** There might be records in the main journal that have a page number
  50754. ** greater than the current database size (pPager->dbSize) but those
  50755. ** will be skipped automatically. Pages are added to pDone as they
  50756. ** are played back.
  50757. */
  50758. if( pSavepoint && !pagerUseWal(pPager) ){
  50759. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  50760. pPager->journalOff = pSavepoint->iOffset;
  50761. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  50762. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  50763. }
  50764. assert( rc!=SQLITE_DONE );
  50765. }else{
  50766. pPager->journalOff = 0;
  50767. }
  50768. /* Continue rolling back records out of the main journal starting at
  50769. ** the first journal header seen and continuing until the effective end
  50770. ** of the main journal file. Continue to skip out-of-range pages and
  50771. ** continue adding pages rolled back to pDone.
  50772. */
  50773. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  50774. u32 ii; /* Loop counter */
  50775. u32 nJRec = 0; /* Number of Journal Records */
  50776. u32 dummy;
  50777. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  50778. assert( rc!=SQLITE_DONE );
  50779. /*
  50780. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  50781. ** test is related to ticket #2565. See the discussion in the
  50782. ** pager_playback() function for additional information.
  50783. */
  50784. if( nJRec==0
  50785. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  50786. ){
  50787. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  50788. }
  50789. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  50790. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  50791. }
  50792. assert( rc!=SQLITE_DONE );
  50793. }
  50794. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  50795. /* Finally, rollback pages from the sub-journal. Page that were
  50796. ** previously rolled back out of the main journal (and are hence in pDone)
  50797. ** will be skipped. Out-of-range pages are also skipped.
  50798. */
  50799. if( pSavepoint ){
  50800. u32 ii; /* Loop counter */
  50801. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  50802. if( pagerUseWal(pPager) ){
  50803. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  50804. }
  50805. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  50806. assert( offset==(i64)ii*(4+pPager->pageSize) );
  50807. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  50808. }
  50809. assert( rc!=SQLITE_DONE );
  50810. }
  50811. sqlite3BitvecDestroy(pDone);
  50812. if( rc==SQLITE_OK ){
  50813. pPager->journalOff = szJ;
  50814. }
  50815. return rc;
  50816. }
  50817. /*
  50818. ** Change the maximum number of in-memory pages that are allowed
  50819. ** before attempting to recycle clean and unused pages.
  50820. */
  50821. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  50822. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  50823. }
  50824. /*
  50825. ** Change the maximum number of in-memory pages that are allowed
  50826. ** before attempting to spill pages to journal.
  50827. */
  50828. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
  50829. return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
  50830. }
  50831. /*
  50832. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  50833. */
  50834. static void pagerFixMaplimit(Pager *pPager){
  50835. #if SQLITE_MAX_MMAP_SIZE>0
  50836. sqlite3_file *fd = pPager->fd;
  50837. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  50838. sqlite3_int64 sz;
  50839. sz = pPager->szMmap;
  50840. pPager->bUseFetch = (sz>0);
  50841. setGetterMethod(pPager);
  50842. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  50843. }
  50844. #endif
  50845. }
  50846. /*
  50847. ** Change the maximum size of any memory mapping made of the database file.
  50848. */
  50849. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  50850. pPager->szMmap = szMmap;
  50851. pagerFixMaplimit(pPager);
  50852. }
  50853. /*
  50854. ** Free as much memory as possible from the pager.
  50855. */
  50856. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  50857. sqlite3PcacheShrink(pPager->pPCache);
  50858. }
  50859. /*
  50860. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  50861. **
  50862. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  50863. ** of the database to damage due to OS crashes or power failures by
  50864. ** changing the number of syncs()s when writing the journals.
  50865. ** There are four levels:
  50866. **
  50867. ** OFF sqlite3OsSync() is never called. This is the default
  50868. ** for temporary and transient files.
  50869. **
  50870. ** NORMAL The journal is synced once before writes begin on the
  50871. ** database. This is normally adequate protection, but
  50872. ** it is theoretically possible, though very unlikely,
  50873. ** that an inopertune power failure could leave the journal
  50874. ** in a state which would cause damage to the database
  50875. ** when it is rolled back.
  50876. **
  50877. ** FULL The journal is synced twice before writes begin on the
  50878. ** database (with some additional information - the nRec field
  50879. ** of the journal header - being written in between the two
  50880. ** syncs). If we assume that writing a
  50881. ** single disk sector is atomic, then this mode provides
  50882. ** assurance that the journal will not be corrupted to the
  50883. ** point of causing damage to the database during rollback.
  50884. **
  50885. ** EXTRA This is like FULL except that is also syncs the directory
  50886. ** that contains the rollback journal after the rollback
  50887. ** journal is unlinked.
  50888. **
  50889. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  50890. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  50891. ** prior to the start of checkpoint and that the database file is synced
  50892. ** at the conclusion of the checkpoint if the entire content of the WAL
  50893. ** was written back into the database. But no sync operations occur for
  50894. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  50895. ** file is synced following each commit operation, in addition to the
  50896. ** syncs associated with NORMAL. There is no difference between FULL
  50897. ** and EXTRA for WAL mode.
  50898. **
  50899. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  50900. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  50901. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  50902. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  50903. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  50904. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  50905. ** the xSync primitive is called and is relevant to all platforms.
  50906. **
  50907. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  50908. ** and FULL=3.
  50909. */
  50910. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  50911. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  50912. Pager *pPager, /* The pager to set safety level for */
  50913. unsigned pgFlags /* Various flags */
  50914. ){
  50915. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  50916. if( pPager->tempFile ){
  50917. pPager->noSync = 1;
  50918. pPager->fullSync = 0;
  50919. pPager->extraSync = 0;
  50920. }else{
  50921. pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
  50922. pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
  50923. pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
  50924. }
  50925. if( pPager->noSync ){
  50926. pPager->syncFlags = 0;
  50927. }else if( pgFlags & PAGER_FULLFSYNC ){
  50928. pPager->syncFlags = SQLITE_SYNC_FULL;
  50929. }else{
  50930. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  50931. }
  50932. pPager->walSyncFlags = (pPager->syncFlags<<2);
  50933. if( pPager->fullSync ){
  50934. pPager->walSyncFlags |= pPager->syncFlags;
  50935. }
  50936. if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
  50937. pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
  50938. }
  50939. if( pgFlags & PAGER_CACHESPILL ){
  50940. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  50941. }else{
  50942. pPager->doNotSpill |= SPILLFLAG_OFF;
  50943. }
  50944. }
  50945. #endif
  50946. /*
  50947. ** The following global variable is incremented whenever the library
  50948. ** attempts to open a temporary file. This information is used for
  50949. ** testing and analysis only.
  50950. */
  50951. #ifdef SQLITE_TEST
  50952. SQLITE_API int sqlite3_opentemp_count = 0;
  50953. #endif
  50954. /*
  50955. ** Open a temporary file.
  50956. **
  50957. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  50958. ** or some other error code if we fail. The OS will automatically
  50959. ** delete the temporary file when it is closed.
  50960. **
  50961. ** The flags passed to the VFS layer xOpen() call are those specified
  50962. ** by parameter vfsFlags ORed with the following:
  50963. **
  50964. ** SQLITE_OPEN_READWRITE
  50965. ** SQLITE_OPEN_CREATE
  50966. ** SQLITE_OPEN_EXCLUSIVE
  50967. ** SQLITE_OPEN_DELETEONCLOSE
  50968. */
  50969. static int pagerOpentemp(
  50970. Pager *pPager, /* The pager object */
  50971. sqlite3_file *pFile, /* Write the file descriptor here */
  50972. int vfsFlags /* Flags passed through to the VFS */
  50973. ){
  50974. int rc; /* Return code */
  50975. #ifdef SQLITE_TEST
  50976. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  50977. #endif
  50978. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  50979. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  50980. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  50981. assert( rc!=SQLITE_OK || isOpen(pFile) );
  50982. return rc;
  50983. }
  50984. /*
  50985. ** Set the busy handler function.
  50986. **
  50987. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  50988. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  50989. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  50990. ** lock. It does *not* invoke the busy handler when upgrading from
  50991. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  50992. ** (which occurs during hot-journal rollback). Summary:
  50993. **
  50994. ** Transition | Invokes xBusyHandler
  50995. ** --------------------------------------------------------
  50996. ** NO_LOCK -> SHARED_LOCK | Yes
  50997. ** SHARED_LOCK -> RESERVED_LOCK | No
  50998. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  50999. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  51000. **
  51001. ** If the busy-handler callback returns non-zero, the lock is
  51002. ** retried. If it returns zero, then the SQLITE_BUSY error is
  51003. ** returned to the caller of the pager API function.
  51004. */
  51005. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(
  51006. Pager *pPager, /* Pager object */
  51007. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  51008. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  51009. ){
  51010. void **ap;
  51011. pPager->xBusyHandler = xBusyHandler;
  51012. pPager->pBusyHandlerArg = pBusyHandlerArg;
  51013. ap = (void **)&pPager->xBusyHandler;
  51014. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  51015. assert( ap[1]==pBusyHandlerArg );
  51016. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  51017. }
  51018. /*
  51019. ** Change the page size used by the Pager object. The new page size
  51020. ** is passed in *pPageSize.
  51021. **
  51022. ** If the pager is in the error state when this function is called, it
  51023. ** is a no-op. The value returned is the error state error code (i.e.
  51024. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  51025. **
  51026. ** Otherwise, if all of the following are true:
  51027. **
  51028. ** * the new page size (value of *pPageSize) is valid (a power
  51029. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  51030. **
  51031. ** * there are no outstanding page references, and
  51032. **
  51033. ** * the database is either not an in-memory database or it is
  51034. ** an in-memory database that currently consists of zero pages.
  51035. **
  51036. ** then the pager object page size is set to *pPageSize.
  51037. **
  51038. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  51039. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  51040. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  51041. ** In all other cases, SQLITE_OK is returned.
  51042. **
  51043. ** If the page size is not changed, either because one of the enumerated
  51044. ** conditions above is not true, the pager was in error state when this
  51045. ** function was called, or because the memory allocation attempt failed,
  51046. ** then *pPageSize is set to the old, retained page size before returning.
  51047. */
  51048. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  51049. int rc = SQLITE_OK;
  51050. /* It is not possible to do a full assert_pager_state() here, as this
  51051. ** function may be called from within PagerOpen(), before the state
  51052. ** of the Pager object is internally consistent.
  51053. **
  51054. ** At one point this function returned an error if the pager was in
  51055. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  51056. ** there is at least one outstanding page reference, this function
  51057. ** is a no-op for that case anyhow.
  51058. */
  51059. u32 pageSize = *pPageSize;
  51060. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  51061. if( (pPager->memDb==0 || pPager->dbSize==0)
  51062. && sqlite3PcacheRefCount(pPager->pPCache)==0
  51063. && pageSize && pageSize!=(u32)pPager->pageSize
  51064. ){
  51065. char *pNew = NULL; /* New temp space */
  51066. i64 nByte = 0;
  51067. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  51068. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  51069. }
  51070. if( rc==SQLITE_OK ){
  51071. /* 8 bytes of zeroed overrun space is sufficient so that the b-tree
  51072. * cell header parser will never run off the end of the allocation */
  51073. pNew = (char *)sqlite3PageMalloc(pageSize+8);
  51074. if( !pNew ){
  51075. rc = SQLITE_NOMEM_BKPT;
  51076. }else{
  51077. memset(pNew+pageSize, 0, 8);
  51078. }
  51079. }
  51080. if( rc==SQLITE_OK ){
  51081. pager_reset(pPager);
  51082. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  51083. }
  51084. if( rc==SQLITE_OK ){
  51085. sqlite3PageFree(pPager->pTmpSpace);
  51086. pPager->pTmpSpace = pNew;
  51087. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  51088. pPager->pageSize = pageSize;
  51089. }else{
  51090. sqlite3PageFree(pNew);
  51091. }
  51092. }
  51093. *pPageSize = pPager->pageSize;
  51094. if( rc==SQLITE_OK ){
  51095. if( nReserve<0 ) nReserve = pPager->nReserve;
  51096. assert( nReserve>=0 && nReserve<1000 );
  51097. pPager->nReserve = (i16)nReserve;
  51098. pagerReportSize(pPager);
  51099. pagerFixMaplimit(pPager);
  51100. }
  51101. return rc;
  51102. }
  51103. /*
  51104. ** Return a pointer to the "temporary page" buffer held internally
  51105. ** by the pager. This is a buffer that is big enough to hold the
  51106. ** entire content of a database page. This buffer is used internally
  51107. ** during rollback and will be overwritten whenever a rollback
  51108. ** occurs. But other modules are free to use it too, as long as
  51109. ** no rollbacks are happening.
  51110. */
  51111. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  51112. return pPager->pTmpSpace;
  51113. }
  51114. /*
  51115. ** Attempt to set the maximum database page count if mxPage is positive.
  51116. ** Make no changes if mxPage is zero or negative. And never reduce the
  51117. ** maximum page count below the current size of the database.
  51118. **
  51119. ** Regardless of mxPage, return the current maximum page count.
  51120. */
  51121. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  51122. if( mxPage>0 ){
  51123. pPager->mxPgno = mxPage;
  51124. }
  51125. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  51126. /* assert( pPager->mxPgno>=pPager->dbSize ); */
  51127. /* OP_MaxPgcnt ensures that the parameter passed to this function is not
  51128. ** less than the total number of valid pages in the database. But this
  51129. ** may be less than Pager.dbSize, and so the assert() above is not valid */
  51130. return pPager->mxPgno;
  51131. }
  51132. /*
  51133. ** The following set of routines are used to disable the simulated
  51134. ** I/O error mechanism. These routines are used to avoid simulated
  51135. ** errors in places where we do not care about errors.
  51136. **
  51137. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  51138. ** and generate no code.
  51139. */
  51140. #ifdef SQLITE_TEST
  51141. SQLITE_API extern int sqlite3_io_error_pending;
  51142. SQLITE_API extern int sqlite3_io_error_hit;
  51143. static int saved_cnt;
  51144. void disable_simulated_io_errors(void){
  51145. saved_cnt = sqlite3_io_error_pending;
  51146. sqlite3_io_error_pending = -1;
  51147. }
  51148. void enable_simulated_io_errors(void){
  51149. sqlite3_io_error_pending = saved_cnt;
  51150. }
  51151. #else
  51152. # define disable_simulated_io_errors()
  51153. # define enable_simulated_io_errors()
  51154. #endif
  51155. /*
  51156. ** Read the first N bytes from the beginning of the file into memory
  51157. ** that pDest points to.
  51158. **
  51159. ** If the pager was opened on a transient file (zFilename==""), or
  51160. ** opened on a file less than N bytes in size, the output buffer is
  51161. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  51162. ** function is used to read database headers, and a new transient or
  51163. ** zero sized database has a header than consists entirely of zeroes.
  51164. **
  51165. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  51166. ** the error code is returned to the caller and the contents of the
  51167. ** output buffer undefined.
  51168. */
  51169. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  51170. int rc = SQLITE_OK;
  51171. memset(pDest, 0, N);
  51172. assert( isOpen(pPager->fd) || pPager->tempFile );
  51173. /* This routine is only called by btree immediately after creating
  51174. ** the Pager object. There has not been an opportunity to transition
  51175. ** to WAL mode yet.
  51176. */
  51177. assert( !pagerUseWal(pPager) );
  51178. if( isOpen(pPager->fd) ){
  51179. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  51180. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  51181. if( rc==SQLITE_IOERR_SHORT_READ ){
  51182. rc = SQLITE_OK;
  51183. }
  51184. }
  51185. return rc;
  51186. }
  51187. /*
  51188. ** This function may only be called when a read-transaction is open on
  51189. ** the pager. It returns the total number of pages in the database.
  51190. **
  51191. ** However, if the file is between 1 and <page-size> bytes in size, then
  51192. ** this is considered a 1 page file.
  51193. */
  51194. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  51195. assert( pPager->eState>=PAGER_READER );
  51196. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  51197. *pnPage = (int)pPager->dbSize;
  51198. }
  51199. /*
  51200. ** Try to obtain a lock of type locktype on the database file. If
  51201. ** a similar or greater lock is already held, this function is a no-op
  51202. ** (returning SQLITE_OK immediately).
  51203. **
  51204. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  51205. ** the busy callback if the lock is currently not available. Repeat
  51206. ** until the busy callback returns false or until the attempt to
  51207. ** obtain the lock succeeds.
  51208. **
  51209. ** Return SQLITE_OK on success and an error code if we cannot obtain
  51210. ** the lock. If the lock is obtained successfully, set the Pager.state
  51211. ** variable to locktype before returning.
  51212. */
  51213. static int pager_wait_on_lock(Pager *pPager, int locktype){
  51214. int rc; /* Return code */
  51215. /* Check that this is either a no-op (because the requested lock is
  51216. ** already held), or one of the transitions that the busy-handler
  51217. ** may be invoked during, according to the comment above
  51218. ** sqlite3PagerSetBusyhandler().
  51219. */
  51220. assert( (pPager->eLock>=locktype)
  51221. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  51222. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  51223. );
  51224. do {
  51225. rc = pagerLockDb(pPager, locktype);
  51226. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  51227. return rc;
  51228. }
  51229. /*
  51230. ** Function assertTruncateConstraint(pPager) checks that one of the
  51231. ** following is true for all dirty pages currently in the page-cache:
  51232. **
  51233. ** a) The page number is less than or equal to the size of the
  51234. ** current database image, in pages, OR
  51235. **
  51236. ** b) if the page content were written at this time, it would not
  51237. ** be necessary to write the current content out to the sub-journal
  51238. ** (as determined by function subjRequiresPage()).
  51239. **
  51240. ** If the condition asserted by this function were not true, and the
  51241. ** dirty page were to be discarded from the cache via the pagerStress()
  51242. ** routine, pagerStress() would not write the current page content to
  51243. ** the database file. If a savepoint transaction were rolled back after
  51244. ** this happened, the correct behavior would be to restore the current
  51245. ** content of the page. However, since this content is not present in either
  51246. ** the database file or the portion of the rollback journal and
  51247. ** sub-journal rolled back the content could not be restored and the
  51248. ** database image would become corrupt. It is therefore fortunate that
  51249. ** this circumstance cannot arise.
  51250. */
  51251. #if defined(SQLITE_DEBUG)
  51252. static void assertTruncateConstraintCb(PgHdr *pPg){
  51253. assert( pPg->flags&PGHDR_DIRTY );
  51254. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  51255. }
  51256. static void assertTruncateConstraint(Pager *pPager){
  51257. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  51258. }
  51259. #else
  51260. # define assertTruncateConstraint(pPager)
  51261. #endif
  51262. /*
  51263. ** Truncate the in-memory database file image to nPage pages. This
  51264. ** function does not actually modify the database file on disk. It
  51265. ** just sets the internal state of the pager object so that the
  51266. ** truncation will be done when the current transaction is committed.
  51267. **
  51268. ** This function is only called right before committing a transaction.
  51269. ** Once this function has been called, the transaction must either be
  51270. ** rolled back or committed. It is not safe to call this function and
  51271. ** then continue writing to the database.
  51272. */
  51273. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  51274. assert( pPager->dbSize>=nPage );
  51275. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  51276. pPager->dbSize = nPage;
  51277. /* At one point the code here called assertTruncateConstraint() to
  51278. ** ensure that all pages being truncated away by this operation are,
  51279. ** if one or more savepoints are open, present in the savepoint
  51280. ** journal so that they can be restored if the savepoint is rolled
  51281. ** back. This is no longer necessary as this function is now only
  51282. ** called right before committing a transaction. So although the
  51283. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  51284. ** they cannot be rolled back. So the assertTruncateConstraint() call
  51285. ** is no longer correct. */
  51286. }
  51287. /*
  51288. ** This function is called before attempting a hot-journal rollback. It
  51289. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  51290. ** size of the journal file so that the pager_playback() routine knows
  51291. ** that the entire journal file has been synced.
  51292. **
  51293. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  51294. ** that if a power-failure occurs during the rollback, the process that
  51295. ** attempts rollback following system recovery sees the same journal
  51296. ** content as this process.
  51297. **
  51298. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  51299. ** an SQLite error code.
  51300. */
  51301. static int pagerSyncHotJournal(Pager *pPager){
  51302. int rc = SQLITE_OK;
  51303. if( !pPager->noSync ){
  51304. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  51305. }
  51306. if( rc==SQLITE_OK ){
  51307. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  51308. }
  51309. return rc;
  51310. }
  51311. #if SQLITE_MAX_MMAP_SIZE>0
  51312. /*
  51313. ** Obtain a reference to a memory mapped page object for page number pgno.
  51314. ** The new object will use the pointer pData, obtained from xFetch().
  51315. ** If successful, set *ppPage to point to the new page reference
  51316. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  51317. ** *ppPage to zero.
  51318. **
  51319. ** Page references obtained by calling this function should be released
  51320. ** by calling pagerReleaseMapPage().
  51321. */
  51322. static int pagerAcquireMapPage(
  51323. Pager *pPager, /* Pager object */
  51324. Pgno pgno, /* Page number */
  51325. void *pData, /* xFetch()'d data for this page */
  51326. PgHdr **ppPage /* OUT: Acquired page object */
  51327. ){
  51328. PgHdr *p; /* Memory mapped page to return */
  51329. if( pPager->pMmapFreelist ){
  51330. *ppPage = p = pPager->pMmapFreelist;
  51331. pPager->pMmapFreelist = p->pDirty;
  51332. p->pDirty = 0;
  51333. assert( pPager->nExtra>=8 );
  51334. memset(p->pExtra, 0, 8);
  51335. }else{
  51336. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  51337. if( p==0 ){
  51338. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  51339. return SQLITE_NOMEM_BKPT;
  51340. }
  51341. p->pExtra = (void *)&p[1];
  51342. p->flags = PGHDR_MMAP;
  51343. p->nRef = 1;
  51344. p->pPager = pPager;
  51345. }
  51346. assert( p->pExtra==(void *)&p[1] );
  51347. assert( p->pPage==0 );
  51348. assert( p->flags==PGHDR_MMAP );
  51349. assert( p->pPager==pPager );
  51350. assert( p->nRef==1 );
  51351. p->pgno = pgno;
  51352. p->pData = pData;
  51353. pPager->nMmapOut++;
  51354. return SQLITE_OK;
  51355. }
  51356. #endif
  51357. /*
  51358. ** Release a reference to page pPg. pPg must have been returned by an
  51359. ** earlier call to pagerAcquireMapPage().
  51360. */
  51361. static void pagerReleaseMapPage(PgHdr *pPg){
  51362. Pager *pPager = pPg->pPager;
  51363. pPager->nMmapOut--;
  51364. pPg->pDirty = pPager->pMmapFreelist;
  51365. pPager->pMmapFreelist = pPg;
  51366. assert( pPager->fd->pMethods->iVersion>=3 );
  51367. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  51368. }
  51369. /*
  51370. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  51371. */
  51372. static void pagerFreeMapHdrs(Pager *pPager){
  51373. PgHdr *p;
  51374. PgHdr *pNext;
  51375. for(p=pPager->pMmapFreelist; p; p=pNext){
  51376. pNext = p->pDirty;
  51377. sqlite3_free(p);
  51378. }
  51379. }
  51380. /* Verify that the database file has not be deleted or renamed out from
  51381. ** under the pager. Return SQLITE_OK if the database is still where it ought
  51382. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  51383. ** code from sqlite3OsAccess()) if the database has gone missing.
  51384. */
  51385. static int databaseIsUnmoved(Pager *pPager){
  51386. int bHasMoved = 0;
  51387. int rc;
  51388. if( pPager->tempFile ) return SQLITE_OK;
  51389. if( pPager->dbSize==0 ) return SQLITE_OK;
  51390. assert( pPager->zFilename && pPager->zFilename[0] );
  51391. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  51392. if( rc==SQLITE_NOTFOUND ){
  51393. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  51394. ** has not been moved. That is the historical behavior of SQLite: prior to
  51395. ** version 3.8.3, it never checked */
  51396. rc = SQLITE_OK;
  51397. }else if( rc==SQLITE_OK && bHasMoved ){
  51398. rc = SQLITE_READONLY_DBMOVED;
  51399. }
  51400. return rc;
  51401. }
  51402. /*
  51403. ** Shutdown the page cache. Free all memory and close all files.
  51404. **
  51405. ** If a transaction was in progress when this routine is called, that
  51406. ** transaction is rolled back. All outstanding pages are invalidated
  51407. ** and their memory is freed. Any attempt to use a page associated
  51408. ** with this page cache after this function returns will likely
  51409. ** result in a coredump.
  51410. **
  51411. ** This function always succeeds. If a transaction is active an attempt
  51412. ** is made to roll it back. If an error occurs during the rollback
  51413. ** a hot journal may be left in the filesystem but no error is returned
  51414. ** to the caller.
  51415. */
  51416. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
  51417. u8 *pTmp = (u8*)pPager->pTmpSpace;
  51418. assert( db || pagerUseWal(pPager)==0 );
  51419. assert( assert_pager_state(pPager) );
  51420. disable_simulated_io_errors();
  51421. sqlite3BeginBenignMalloc();
  51422. pagerFreeMapHdrs(pPager);
  51423. /* pPager->errCode = 0; */
  51424. pPager->exclusiveMode = 0;
  51425. #ifndef SQLITE_OMIT_WAL
  51426. {
  51427. u8 *a = 0;
  51428. assert( db || pPager->pWal==0 );
  51429. if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
  51430. && SQLITE_OK==databaseIsUnmoved(pPager)
  51431. ){
  51432. a = pTmp;
  51433. }
  51434. sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
  51435. pPager->pWal = 0;
  51436. }
  51437. #endif
  51438. pager_reset(pPager);
  51439. if( MEMDB ){
  51440. pager_unlock(pPager);
  51441. }else{
  51442. /* If it is open, sync the journal file before calling UnlockAndRollback.
  51443. ** If this is not done, then an unsynced portion of the open journal
  51444. ** file may be played back into the database. If a power failure occurs
  51445. ** while this is happening, the database could become corrupt.
  51446. **
  51447. ** If an error occurs while trying to sync the journal, shift the pager
  51448. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  51449. ** database and close the journal file without attempting to roll it
  51450. ** back or finalize it. The next database user will have to do hot-journal
  51451. ** rollback before accessing the database file.
  51452. */
  51453. if( isOpen(pPager->jfd) ){
  51454. pager_error(pPager, pagerSyncHotJournal(pPager));
  51455. }
  51456. pagerUnlockAndRollback(pPager);
  51457. }
  51458. sqlite3EndBenignMalloc();
  51459. enable_simulated_io_errors();
  51460. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  51461. IOTRACE(("CLOSE %p\n", pPager))
  51462. sqlite3OsClose(pPager->jfd);
  51463. sqlite3OsClose(pPager->fd);
  51464. sqlite3PageFree(pTmp);
  51465. sqlite3PcacheClose(pPager->pPCache);
  51466. #ifdef SQLITE_HAS_CODEC
  51467. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  51468. #endif
  51469. assert( !pPager->aSavepoint && !pPager->pInJournal );
  51470. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  51471. sqlite3_free(pPager);
  51472. return SQLITE_OK;
  51473. }
  51474. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  51475. /*
  51476. ** Return the page number for page pPg.
  51477. */
  51478. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  51479. return pPg->pgno;
  51480. }
  51481. #endif
  51482. /*
  51483. ** Increment the reference count for page pPg.
  51484. */
  51485. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  51486. sqlite3PcacheRef(pPg);
  51487. }
  51488. /*
  51489. ** Sync the journal. In other words, make sure all the pages that have
  51490. ** been written to the journal have actually reached the surface of the
  51491. ** disk and can be restored in the event of a hot-journal rollback.
  51492. **
  51493. ** If the Pager.noSync flag is set, then this function is a no-op.
  51494. ** Otherwise, the actions required depend on the journal-mode and the
  51495. ** device characteristics of the file-system, as follows:
  51496. **
  51497. ** * If the journal file is an in-memory journal file, no action need
  51498. ** be taken.
  51499. **
  51500. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  51501. ** then the nRec field of the most recently written journal header
  51502. ** is updated to contain the number of journal records that have
  51503. ** been written following it. If the pager is operating in full-sync
  51504. ** mode, then the journal file is synced before this field is updated.
  51505. **
  51506. ** * If the device does not support the SEQUENTIAL property, then
  51507. ** journal file is synced.
  51508. **
  51509. ** Or, in pseudo-code:
  51510. **
  51511. ** if( NOT <in-memory journal> ){
  51512. ** if( NOT SAFE_APPEND ){
  51513. ** if( <full-sync mode> ) xSync(<journal file>);
  51514. ** <update nRec field>
  51515. ** }
  51516. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  51517. ** }
  51518. **
  51519. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  51520. ** page currently held in memory before returning SQLITE_OK. If an IO
  51521. ** error is encountered, then the IO error code is returned to the caller.
  51522. */
  51523. static int syncJournal(Pager *pPager, int newHdr){
  51524. int rc; /* Return code */
  51525. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  51526. || pPager->eState==PAGER_WRITER_DBMOD
  51527. );
  51528. assert( assert_pager_state(pPager) );
  51529. assert( !pagerUseWal(pPager) );
  51530. rc = sqlite3PagerExclusiveLock(pPager);
  51531. if( rc!=SQLITE_OK ) return rc;
  51532. if( !pPager->noSync ){
  51533. assert( !pPager->tempFile );
  51534. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  51535. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  51536. assert( isOpen(pPager->jfd) );
  51537. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  51538. /* This block deals with an obscure problem. If the last connection
  51539. ** that wrote to this database was operating in persistent-journal
  51540. ** mode, then the journal file may at this point actually be larger
  51541. ** than Pager.journalOff bytes. If the next thing in the journal
  51542. ** file happens to be a journal-header (written as part of the
  51543. ** previous connection's transaction), and a crash or power-failure
  51544. ** occurs after nRec is updated but before this connection writes
  51545. ** anything else to the journal file (or commits/rolls back its
  51546. ** transaction), then SQLite may become confused when doing the
  51547. ** hot-journal rollback following recovery. It may roll back all
  51548. ** of this connections data, then proceed to rolling back the old,
  51549. ** out-of-date data that follows it. Database corruption.
  51550. **
  51551. ** To work around this, if the journal file does appear to contain
  51552. ** a valid header following Pager.journalOff, then write a 0x00
  51553. ** byte to the start of it to prevent it from being recognized.
  51554. **
  51555. ** Variable iNextHdrOffset is set to the offset at which this
  51556. ** problematic header will occur, if it exists. aMagic is used
  51557. ** as a temporary buffer to inspect the first couple of bytes of
  51558. ** the potential journal header.
  51559. */
  51560. i64 iNextHdrOffset;
  51561. u8 aMagic[8];
  51562. u8 zHeader[sizeof(aJournalMagic)+4];
  51563. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  51564. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  51565. iNextHdrOffset = journalHdrOffset(pPager);
  51566. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  51567. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  51568. static const u8 zerobyte = 0;
  51569. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  51570. }
  51571. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  51572. return rc;
  51573. }
  51574. /* Write the nRec value into the journal file header. If in
  51575. ** full-synchronous mode, sync the journal first. This ensures that
  51576. ** all data has really hit the disk before nRec is updated to mark
  51577. ** it as a candidate for rollback.
  51578. **
  51579. ** This is not required if the persistent media supports the
  51580. ** SAFE_APPEND property. Because in this case it is not possible
  51581. ** for garbage data to be appended to the file, the nRec field
  51582. ** is populated with 0xFFFFFFFF when the journal header is written
  51583. ** and never needs to be updated.
  51584. */
  51585. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  51586. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  51587. IOTRACE(("JSYNC %p\n", pPager))
  51588. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  51589. if( rc!=SQLITE_OK ) return rc;
  51590. }
  51591. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  51592. rc = sqlite3OsWrite(
  51593. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  51594. );
  51595. if( rc!=SQLITE_OK ) return rc;
  51596. }
  51597. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  51598. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  51599. IOTRACE(("JSYNC %p\n", pPager))
  51600. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  51601. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  51602. );
  51603. if( rc!=SQLITE_OK ) return rc;
  51604. }
  51605. pPager->journalHdr = pPager->journalOff;
  51606. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  51607. pPager->nRec = 0;
  51608. rc = writeJournalHdr(pPager);
  51609. if( rc!=SQLITE_OK ) return rc;
  51610. }
  51611. }else{
  51612. pPager->journalHdr = pPager->journalOff;
  51613. }
  51614. }
  51615. /* Unless the pager is in noSync mode, the journal file was just
  51616. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  51617. ** all pages.
  51618. */
  51619. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  51620. pPager->eState = PAGER_WRITER_DBMOD;
  51621. assert( assert_pager_state(pPager) );
  51622. return SQLITE_OK;
  51623. }
  51624. /*
  51625. ** The argument is the first in a linked list of dirty pages connected
  51626. ** by the PgHdr.pDirty pointer. This function writes each one of the
  51627. ** in-memory pages in the list to the database file. The argument may
  51628. ** be NULL, representing an empty list. In this case this function is
  51629. ** a no-op.
  51630. **
  51631. ** The pager must hold at least a RESERVED lock when this function
  51632. ** is called. Before writing anything to the database file, this lock
  51633. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  51634. ** SQLITE_BUSY is returned and no data is written to the database file.
  51635. **
  51636. ** If the pager is a temp-file pager and the actual file-system file
  51637. ** is not yet open, it is created and opened before any data is
  51638. ** written out.
  51639. **
  51640. ** Once the lock has been upgraded and, if necessary, the file opened,
  51641. ** the pages are written out to the database file in list order. Writing
  51642. ** a page is skipped if it meets either of the following criteria:
  51643. **
  51644. ** * The page number is greater than Pager.dbSize, or
  51645. ** * The PGHDR_DONT_WRITE flag is set on the page.
  51646. **
  51647. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  51648. ** is updated accordingly. If page 1 is written out, then the value cached
  51649. ** in Pager.dbFileVers[] is updated to match the new value stored in
  51650. ** the database file.
  51651. **
  51652. ** If everything is successful, SQLITE_OK is returned. If an IO error
  51653. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  51654. ** be obtained, SQLITE_BUSY is returned.
  51655. */
  51656. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  51657. int rc = SQLITE_OK; /* Return code */
  51658. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  51659. assert( !pagerUseWal(pPager) );
  51660. assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
  51661. assert( pPager->eLock==EXCLUSIVE_LOCK );
  51662. assert( isOpen(pPager->fd) || pList->pDirty==0 );
  51663. /* If the file is a temp-file has not yet been opened, open it now. It
  51664. ** is not possible for rc to be other than SQLITE_OK if this branch
  51665. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  51666. */
  51667. if( !isOpen(pPager->fd) ){
  51668. assert( pPager->tempFile && rc==SQLITE_OK );
  51669. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  51670. }
  51671. /* Before the first write, give the VFS a hint of what the final
  51672. ** file size will be.
  51673. */
  51674. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  51675. if( rc==SQLITE_OK
  51676. && pPager->dbHintSize<pPager->dbSize
  51677. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  51678. ){
  51679. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  51680. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  51681. pPager->dbHintSize = pPager->dbSize;
  51682. }
  51683. while( rc==SQLITE_OK && pList ){
  51684. Pgno pgno = pList->pgno;
  51685. /* If there are dirty pages in the page cache with page numbers greater
  51686. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  51687. ** make the file smaller (presumably by auto-vacuum code). Do not write
  51688. ** any such pages to the file.
  51689. **
  51690. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  51691. ** set (set by sqlite3PagerDontWrite()).
  51692. */
  51693. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  51694. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  51695. char *pData; /* Data to write */
  51696. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  51697. if( pList->pgno==1 ) pager_write_changecounter(pList);
  51698. /* Encode the database */
  51699. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
  51700. /* Write out the page data. */
  51701. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  51702. /* If page 1 was just written, update Pager.dbFileVers to match
  51703. ** the value now stored in the database file. If writing this
  51704. ** page caused the database file to grow, update dbFileSize.
  51705. */
  51706. if( pgno==1 ){
  51707. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  51708. }
  51709. if( pgno>pPager->dbFileSize ){
  51710. pPager->dbFileSize = pgno;
  51711. }
  51712. pPager->aStat[PAGER_STAT_WRITE]++;
  51713. /* Update any backup objects copying the contents of this pager. */
  51714. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  51715. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  51716. PAGERID(pPager), pgno, pager_pagehash(pList)));
  51717. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  51718. PAGER_INCR(sqlite3_pager_writedb_count);
  51719. }else{
  51720. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  51721. }
  51722. pager_set_pagehash(pList);
  51723. pList = pList->pDirty;
  51724. }
  51725. return rc;
  51726. }
  51727. /*
  51728. ** Ensure that the sub-journal file is open. If it is already open, this
  51729. ** function is a no-op.
  51730. **
  51731. ** SQLITE_OK is returned if everything goes according to plan. An
  51732. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  51733. ** fails.
  51734. */
  51735. static int openSubJournal(Pager *pPager){
  51736. int rc = SQLITE_OK;
  51737. if( !isOpen(pPager->sjfd) ){
  51738. const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
  51739. | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
  51740. | SQLITE_OPEN_DELETEONCLOSE;
  51741. int nStmtSpill = sqlite3Config.nStmtSpill;
  51742. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  51743. nStmtSpill = -1;
  51744. }
  51745. rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
  51746. }
  51747. return rc;
  51748. }
  51749. /*
  51750. ** Append a record of the current state of page pPg to the sub-journal.
  51751. **
  51752. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  51753. ** for all open savepoints before returning.
  51754. **
  51755. ** This function returns SQLITE_OK if everything is successful, an IO
  51756. ** error code if the attempt to write to the sub-journal fails, or
  51757. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  51758. ** bitvec.
  51759. */
  51760. static int subjournalPage(PgHdr *pPg){
  51761. int rc = SQLITE_OK;
  51762. Pager *pPager = pPg->pPager;
  51763. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  51764. /* Open the sub-journal, if it has not already been opened */
  51765. assert( pPager->useJournal );
  51766. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  51767. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  51768. assert( pagerUseWal(pPager)
  51769. || pageInJournal(pPager, pPg)
  51770. || pPg->pgno>pPager->dbOrigSize
  51771. );
  51772. rc = openSubJournal(pPager);
  51773. /* If the sub-journal was opened successfully (or was already open),
  51774. ** write the journal record into the file. */
  51775. if( rc==SQLITE_OK ){
  51776. void *pData = pPg->pData;
  51777. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  51778. char *pData2;
  51779. #if SQLITE_HAS_CODEC
  51780. if( !pPager->subjInMemory ){
  51781. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  51782. }else
  51783. #endif
  51784. pData2 = pData;
  51785. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  51786. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  51787. if( rc==SQLITE_OK ){
  51788. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  51789. }
  51790. }
  51791. }
  51792. if( rc==SQLITE_OK ){
  51793. pPager->nSubRec++;
  51794. assert( pPager->nSavepoint>0 );
  51795. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  51796. }
  51797. return rc;
  51798. }
  51799. static int subjournalPageIfRequired(PgHdr *pPg){
  51800. if( subjRequiresPage(pPg) ){
  51801. return subjournalPage(pPg);
  51802. }else{
  51803. return SQLITE_OK;
  51804. }
  51805. }
  51806. /*
  51807. ** This function is called by the pcache layer when it has reached some
  51808. ** soft memory limit. The first argument is a pointer to a Pager object
  51809. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  51810. ** database). The second argument is a reference to a page that is
  51811. ** currently dirty but has no outstanding references. The page
  51812. ** is always associated with the Pager object passed as the first
  51813. ** argument.
  51814. **
  51815. ** The job of this function is to make pPg clean by writing its contents
  51816. ** out to the database file, if possible. This may involve syncing the
  51817. ** journal file.
  51818. **
  51819. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  51820. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  51821. ** page clean, the IO error code is returned. If the page cannot be
  51822. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  51823. ** is returned by sqlite3PcacheMakeClean() is not called.
  51824. */
  51825. static int pagerStress(void *p, PgHdr *pPg){
  51826. Pager *pPager = (Pager *)p;
  51827. int rc = SQLITE_OK;
  51828. assert( pPg->pPager==pPager );
  51829. assert( pPg->flags&PGHDR_DIRTY );
  51830. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  51831. ** journal (and adding a new header) is not allowed. This occurs
  51832. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  51833. ** pages belonging to the same sector.
  51834. **
  51835. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  51836. ** regardless of whether or not a sync is required. This is set during
  51837. ** a rollback or by user request, respectively.
  51838. **
  51839. ** Spilling is also prohibited when in an error state since that could
  51840. ** lead to database corruption. In the current implementation it
  51841. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  51842. ** while in the error state, hence it is impossible for this routine to
  51843. ** be called in the error state. Nevertheless, we include a NEVER()
  51844. ** test for the error state as a safeguard against future changes.
  51845. */
  51846. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  51847. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  51848. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  51849. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  51850. if( pPager->doNotSpill
  51851. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  51852. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  51853. ){
  51854. return SQLITE_OK;
  51855. }
  51856. pPager->aStat[PAGER_STAT_SPILL]++;
  51857. pPg->pDirty = 0;
  51858. if( pagerUseWal(pPager) ){
  51859. /* Write a single frame for this page to the log. */
  51860. rc = subjournalPageIfRequired(pPg);
  51861. if( rc==SQLITE_OK ){
  51862. rc = pagerWalFrames(pPager, pPg, 0, 0);
  51863. }
  51864. }else{
  51865. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  51866. if( pPager->tempFile==0 ){
  51867. rc = sqlite3JournalCreate(pPager->jfd);
  51868. if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
  51869. }
  51870. #endif
  51871. /* Sync the journal file if required. */
  51872. if( pPg->flags&PGHDR_NEED_SYNC
  51873. || pPager->eState==PAGER_WRITER_CACHEMOD
  51874. ){
  51875. rc = syncJournal(pPager, 1);
  51876. }
  51877. /* Write the contents of the page out to the database file. */
  51878. if( rc==SQLITE_OK ){
  51879. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  51880. rc = pager_write_pagelist(pPager, pPg);
  51881. }
  51882. }
  51883. /* Mark the page as clean. */
  51884. if( rc==SQLITE_OK ){
  51885. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  51886. sqlite3PcacheMakeClean(pPg);
  51887. }
  51888. return pager_error(pPager, rc);
  51889. }
  51890. /*
  51891. ** Flush all unreferenced dirty pages to disk.
  51892. */
  51893. SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
  51894. int rc = pPager->errCode;
  51895. if( !MEMDB ){
  51896. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  51897. assert( assert_pager_state(pPager) );
  51898. while( rc==SQLITE_OK && pList ){
  51899. PgHdr *pNext = pList->pDirty;
  51900. if( pList->nRef==0 ){
  51901. rc = pagerStress((void*)pPager, pList);
  51902. }
  51903. pList = pNext;
  51904. }
  51905. }
  51906. return rc;
  51907. }
  51908. /*
  51909. ** Allocate and initialize a new Pager object and put a pointer to it
  51910. ** in *ppPager. The pager should eventually be freed by passing it
  51911. ** to sqlite3PagerClose().
  51912. **
  51913. ** The zFilename argument is the path to the database file to open.
  51914. ** If zFilename is NULL then a randomly-named temporary file is created
  51915. ** and used as the file to be cached. Temporary files are be deleted
  51916. ** automatically when they are closed. If zFilename is ":memory:" then
  51917. ** all information is held in cache. It is never written to disk.
  51918. ** This can be used to implement an in-memory database.
  51919. **
  51920. ** The nExtra parameter specifies the number of bytes of space allocated
  51921. ** along with each page reference. This space is available to the user
  51922. ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the
  51923. ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
  51924. ** (The extra space is used by btree as the MemPage object.)
  51925. **
  51926. ** The flags argument is used to specify properties that affect the
  51927. ** operation of the pager. It should be passed some bitwise combination
  51928. ** of the PAGER_* flags.
  51929. **
  51930. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  51931. ** of the xOpen() method of the supplied VFS when opening files.
  51932. **
  51933. ** If the pager object is allocated and the specified file opened
  51934. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  51935. ** the new pager object. If an error occurs, *ppPager is set to NULL
  51936. ** and error code returned. This function may return SQLITE_NOMEM
  51937. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  51938. ** various SQLITE_IO_XXX errors.
  51939. */
  51940. SQLITE_PRIVATE int sqlite3PagerOpen(
  51941. sqlite3_vfs *pVfs, /* The virtual file system to use */
  51942. Pager **ppPager, /* OUT: Return the Pager structure here */
  51943. const char *zFilename, /* Name of the database file to open */
  51944. int nExtra, /* Extra bytes append to each in-memory page */
  51945. int flags, /* flags controlling this file */
  51946. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  51947. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  51948. ){
  51949. u8 *pPtr;
  51950. Pager *pPager = 0; /* Pager object to allocate and return */
  51951. int rc = SQLITE_OK; /* Return code */
  51952. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  51953. int memDb = 0; /* True if this is an in-memory file */
  51954. #ifdef SQLITE_ENABLE_DESERIALIZE
  51955. int memJM = 0; /* Memory journal mode */
  51956. #else
  51957. # define memJM 0
  51958. #endif
  51959. int readOnly = 0; /* True if this is a read-only file */
  51960. int journalFileSize; /* Bytes to allocate for each journal fd */
  51961. char *zPathname = 0; /* Full path to database file */
  51962. int nPathname = 0; /* Number of bytes in zPathname */
  51963. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  51964. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  51965. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  51966. const char *zUri = 0; /* URI args to copy */
  51967. int nUri = 0; /* Number of bytes of URI args at *zUri */
  51968. /* Figure out how much space is required for each journal file-handle
  51969. ** (there are two of them, the main journal and the sub-journal). */
  51970. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  51971. /* Set the output variable to NULL in case an error occurs. */
  51972. *ppPager = 0;
  51973. #ifndef SQLITE_OMIT_MEMORYDB
  51974. if( flags & PAGER_MEMORY ){
  51975. memDb = 1;
  51976. if( zFilename && zFilename[0] ){
  51977. zPathname = sqlite3DbStrDup(0, zFilename);
  51978. if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
  51979. nPathname = sqlite3Strlen30(zPathname);
  51980. zFilename = 0;
  51981. }
  51982. }
  51983. #endif
  51984. /* Compute and store the full pathname in an allocated buffer pointed
  51985. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  51986. ** leave both nPathname and zPathname set to 0.
  51987. */
  51988. if( zFilename && zFilename[0] ){
  51989. const char *z;
  51990. nPathname = pVfs->mxPathname+1;
  51991. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  51992. if( zPathname==0 ){
  51993. return SQLITE_NOMEM_BKPT;
  51994. }
  51995. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  51996. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  51997. nPathname = sqlite3Strlen30(zPathname);
  51998. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  51999. while( *z ){
  52000. z += sqlite3Strlen30(z)+1;
  52001. z += sqlite3Strlen30(z)+1;
  52002. }
  52003. nUri = (int)(&z[1] - zUri);
  52004. assert( nUri>=0 );
  52005. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  52006. /* This branch is taken when the journal path required by
  52007. ** the database being opened will be more than pVfs->mxPathname
  52008. ** bytes in length. This means the database cannot be opened,
  52009. ** as it will not be possible to open the journal file or even
  52010. ** check for a hot-journal before reading.
  52011. */
  52012. rc = SQLITE_CANTOPEN_BKPT;
  52013. }
  52014. if( rc!=SQLITE_OK ){
  52015. sqlite3DbFree(0, zPathname);
  52016. return rc;
  52017. }
  52018. }
  52019. /* Allocate memory for the Pager structure, PCache object, the
  52020. ** three file descriptors, the database file name and the journal
  52021. ** file name. The layout in memory is as follows:
  52022. **
  52023. ** Pager object (sizeof(Pager) bytes)
  52024. ** PCache object (sqlite3PcacheSize() bytes)
  52025. ** Database file handle (pVfs->szOsFile bytes)
  52026. ** Sub-journal file handle (journalFileSize bytes)
  52027. ** Main journal file handle (journalFileSize bytes)
  52028. ** Database file name (nPathname+1 bytes)
  52029. ** Journal file name (nPathname+8+1 bytes)
  52030. */
  52031. pPtr = (u8 *)sqlite3MallocZero(
  52032. ROUND8(sizeof(*pPager)) + /* Pager structure */
  52033. ROUND8(pcacheSize) + /* PCache object */
  52034. ROUND8(pVfs->szOsFile) + /* The main db file */
  52035. journalFileSize * 2 + /* The two journal files */
  52036. nPathname + 1 + nUri + /* zFilename */
  52037. nPathname + 8 + 2 /* zJournal */
  52038. #ifndef SQLITE_OMIT_WAL
  52039. + nPathname + 4 + 2 /* zWal */
  52040. #endif
  52041. );
  52042. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  52043. if( !pPtr ){
  52044. sqlite3DbFree(0, zPathname);
  52045. return SQLITE_NOMEM_BKPT;
  52046. }
  52047. pPager = (Pager*)(pPtr);
  52048. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  52049. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  52050. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  52051. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  52052. pPager->zFilename = (char*)(pPtr += journalFileSize);
  52053. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  52054. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  52055. if( zPathname ){
  52056. assert( nPathname>0 );
  52057. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  52058. memcpy(pPager->zFilename, zPathname, nPathname);
  52059. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  52060. memcpy(pPager->zJournal, zPathname, nPathname);
  52061. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  52062. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  52063. #ifndef SQLITE_OMIT_WAL
  52064. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  52065. memcpy(pPager->zWal, zPathname, nPathname);
  52066. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  52067. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  52068. #endif
  52069. sqlite3DbFree(0, zPathname);
  52070. }
  52071. pPager->pVfs = pVfs;
  52072. pPager->vfsFlags = vfsFlags;
  52073. /* Open the pager file.
  52074. */
  52075. if( zFilename && zFilename[0] ){
  52076. int fout = 0; /* VFS flags returned by xOpen() */
  52077. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  52078. assert( !memDb );
  52079. #ifdef SQLITE_ENABLE_DESERIALIZE
  52080. memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
  52081. #endif
  52082. readOnly = (fout&SQLITE_OPEN_READONLY)!=0;
  52083. /* If the file was successfully opened for read/write access,
  52084. ** choose a default page size in case we have to create the
  52085. ** database file. The default page size is the maximum of:
  52086. **
  52087. ** + SQLITE_DEFAULT_PAGE_SIZE,
  52088. ** + The value returned by sqlite3OsSectorSize()
  52089. ** + The largest page size that can be written atomically.
  52090. */
  52091. if( rc==SQLITE_OK ){
  52092. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  52093. if( !readOnly ){
  52094. setSectorSize(pPager);
  52095. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  52096. if( szPageDflt<pPager->sectorSize ){
  52097. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  52098. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  52099. }else{
  52100. szPageDflt = (u32)pPager->sectorSize;
  52101. }
  52102. }
  52103. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  52104. {
  52105. int ii;
  52106. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  52107. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  52108. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  52109. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  52110. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  52111. szPageDflt = ii;
  52112. }
  52113. }
  52114. }
  52115. #endif
  52116. }
  52117. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  52118. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  52119. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  52120. vfsFlags |= SQLITE_OPEN_READONLY;
  52121. goto act_like_temp_file;
  52122. }
  52123. }
  52124. }else{
  52125. /* If a temporary file is requested, it is not opened immediately.
  52126. ** In this case we accept the default page size and delay actually
  52127. ** opening the file until the first call to OsWrite().
  52128. **
  52129. ** This branch is also run for an in-memory database. An in-memory
  52130. ** database is the same as a temp-file that is never written out to
  52131. ** disk and uses an in-memory rollback journal.
  52132. **
  52133. ** This branch also runs for files marked as immutable.
  52134. */
  52135. act_like_temp_file:
  52136. tempFile = 1;
  52137. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  52138. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  52139. pPager->noLock = 1; /* Do no locking */
  52140. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  52141. }
  52142. /* The following call to PagerSetPagesize() serves to set the value of
  52143. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  52144. */
  52145. if( rc==SQLITE_OK ){
  52146. assert( pPager->memDb==0 );
  52147. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  52148. testcase( rc!=SQLITE_OK );
  52149. }
  52150. /* Initialize the PCache object. */
  52151. if( rc==SQLITE_OK ){
  52152. nExtra = ROUND8(nExtra);
  52153. assert( nExtra>=8 && nExtra<1000 );
  52154. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  52155. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  52156. }
  52157. /* If an error occurred above, free the Pager structure and close the file.
  52158. */
  52159. if( rc!=SQLITE_OK ){
  52160. sqlite3OsClose(pPager->fd);
  52161. sqlite3PageFree(pPager->pTmpSpace);
  52162. sqlite3_free(pPager);
  52163. return rc;
  52164. }
  52165. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  52166. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  52167. pPager->useJournal = (u8)useJournal;
  52168. /* pPager->stmtOpen = 0; */
  52169. /* pPager->stmtInUse = 0; */
  52170. /* pPager->nRef = 0; */
  52171. /* pPager->stmtSize = 0; */
  52172. /* pPager->stmtJSize = 0; */
  52173. /* pPager->nPage = 0; */
  52174. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  52175. /* pPager->state = PAGER_UNLOCK; */
  52176. /* pPager->errMask = 0; */
  52177. pPager->tempFile = (u8)tempFile;
  52178. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  52179. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  52180. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  52181. pPager->exclusiveMode = (u8)tempFile;
  52182. pPager->changeCountDone = pPager->tempFile;
  52183. pPager->memDb = (u8)memDb;
  52184. pPager->readOnly = (u8)readOnly;
  52185. assert( useJournal || pPager->tempFile );
  52186. pPager->noSync = pPager->tempFile;
  52187. if( pPager->noSync ){
  52188. assert( pPager->fullSync==0 );
  52189. assert( pPager->extraSync==0 );
  52190. assert( pPager->syncFlags==0 );
  52191. assert( pPager->walSyncFlags==0 );
  52192. }else{
  52193. pPager->fullSync = 1;
  52194. pPager->extraSync = 0;
  52195. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  52196. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
  52197. }
  52198. /* pPager->pFirst = 0; */
  52199. /* pPager->pFirstSynced = 0; */
  52200. /* pPager->pLast = 0; */
  52201. pPager->nExtra = (u16)nExtra;
  52202. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  52203. assert( isOpen(pPager->fd) || tempFile );
  52204. setSectorSize(pPager);
  52205. if( !useJournal ){
  52206. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  52207. }else if( memDb || memJM ){
  52208. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  52209. }
  52210. /* pPager->xBusyHandler = 0; */
  52211. /* pPager->pBusyHandlerArg = 0; */
  52212. pPager->xReiniter = xReinit;
  52213. setGetterMethod(pPager);
  52214. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  52215. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  52216. *ppPager = pPager;
  52217. return SQLITE_OK;
  52218. }
  52219. /*
  52220. ** This function is called after transitioning from PAGER_UNLOCK to
  52221. ** PAGER_SHARED state. It tests if there is a hot journal present in
  52222. ** the file-system for the given pager. A hot journal is one that
  52223. ** needs to be played back. According to this function, a hot-journal
  52224. ** file exists if the following criteria are met:
  52225. **
  52226. ** * The journal file exists in the file system, and
  52227. ** * No process holds a RESERVED or greater lock on the database file, and
  52228. ** * The database file itself is greater than 0 bytes in size, and
  52229. ** * The first byte of the journal file exists and is not 0x00.
  52230. **
  52231. ** If the current size of the database file is 0 but a journal file
  52232. ** exists, that is probably an old journal left over from a prior
  52233. ** database with the same name. In this case the journal file is
  52234. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  52235. ** is returned.
  52236. **
  52237. ** This routine does not check if there is a master journal filename
  52238. ** at the end of the file. If there is, and that master journal file
  52239. ** does not exist, then the journal file is not really hot. In this
  52240. ** case this routine will return a false-positive. The pager_playback()
  52241. ** routine will discover that the journal file is not really hot and
  52242. ** will not roll it back.
  52243. **
  52244. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  52245. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  52246. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  52247. ** to determine whether or not a hot-journal file exists, the IO error
  52248. ** code is returned and the value of *pExists is undefined.
  52249. */
  52250. static int hasHotJournal(Pager *pPager, int *pExists){
  52251. sqlite3_vfs * const pVfs = pPager->pVfs;
  52252. int rc = SQLITE_OK; /* Return code */
  52253. int exists = 1; /* True if a journal file is present */
  52254. int jrnlOpen = !!isOpen(pPager->jfd);
  52255. assert( pPager->useJournal );
  52256. assert( isOpen(pPager->fd) );
  52257. assert( pPager->eState==PAGER_OPEN );
  52258. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  52259. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  52260. ));
  52261. *pExists = 0;
  52262. if( !jrnlOpen ){
  52263. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  52264. }
  52265. if( rc==SQLITE_OK && exists ){
  52266. int locked = 0; /* True if some process holds a RESERVED lock */
  52267. /* Race condition here: Another process might have been holding the
  52268. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  52269. ** call above, but then delete the journal and drop the lock before
  52270. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  52271. ** is the case, this routine might think there is a hot journal when
  52272. ** in fact there is none. This results in a false-positive which will
  52273. ** be dealt with by the playback routine. Ticket #3883.
  52274. */
  52275. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  52276. if( rc==SQLITE_OK && !locked ){
  52277. Pgno nPage; /* Number of pages in database file */
  52278. assert( pPager->tempFile==0 );
  52279. rc = pagerPagecount(pPager, &nPage);
  52280. if( rc==SQLITE_OK ){
  52281. /* If the database is zero pages in size, that means that either (1) the
  52282. ** journal is a remnant from a prior database with the same name where
  52283. ** the database file but not the journal was deleted, or (2) the initial
  52284. ** transaction that populates a new database is being rolled back.
  52285. ** In either case, the journal file can be deleted. However, take care
  52286. ** not to delete the journal file if it is already open due to
  52287. ** journal_mode=PERSIST.
  52288. */
  52289. if( nPage==0 && !jrnlOpen ){
  52290. sqlite3BeginBenignMalloc();
  52291. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  52292. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  52293. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  52294. }
  52295. sqlite3EndBenignMalloc();
  52296. }else{
  52297. /* The journal file exists and no other connection has a reserved
  52298. ** or greater lock on the database file. Now check that there is
  52299. ** at least one non-zero bytes at the start of the journal file.
  52300. ** If there is, then we consider this journal to be hot. If not,
  52301. ** it can be ignored.
  52302. */
  52303. if( !jrnlOpen ){
  52304. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  52305. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  52306. }
  52307. if( rc==SQLITE_OK ){
  52308. u8 first = 0;
  52309. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  52310. if( rc==SQLITE_IOERR_SHORT_READ ){
  52311. rc = SQLITE_OK;
  52312. }
  52313. if( !jrnlOpen ){
  52314. sqlite3OsClose(pPager->jfd);
  52315. }
  52316. *pExists = (first!=0);
  52317. }else if( rc==SQLITE_CANTOPEN ){
  52318. /* If we cannot open the rollback journal file in order to see if
  52319. ** it has a zero header, that might be due to an I/O error, or
  52320. ** it might be due to the race condition described above and in
  52321. ** ticket #3883. Either way, assume that the journal is hot.
  52322. ** This might be a false positive. But if it is, then the
  52323. ** automatic journal playback and recovery mechanism will deal
  52324. ** with it under an EXCLUSIVE lock where we do not need to
  52325. ** worry so much with race conditions.
  52326. */
  52327. *pExists = 1;
  52328. rc = SQLITE_OK;
  52329. }
  52330. }
  52331. }
  52332. }
  52333. }
  52334. return rc;
  52335. }
  52336. /*
  52337. ** This function is called to obtain a shared lock on the database file.
  52338. ** It is illegal to call sqlite3PagerGet() until after this function
  52339. ** has been successfully called. If a shared-lock is already held when
  52340. ** this function is called, it is a no-op.
  52341. **
  52342. ** The following operations are also performed by this function.
  52343. **
  52344. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  52345. ** on the database file), then an attempt is made to obtain a
  52346. ** SHARED lock on the database file. Immediately after obtaining
  52347. ** the SHARED lock, the file-system is checked for a hot-journal,
  52348. ** which is played back if present. Following any hot-journal
  52349. ** rollback, the contents of the cache are validated by checking
  52350. ** the 'change-counter' field of the database file header and
  52351. ** discarded if they are found to be invalid.
  52352. **
  52353. ** 2) If the pager is running in exclusive-mode, and there are currently
  52354. ** no outstanding references to any pages, and is in the error state,
  52355. ** then an attempt is made to clear the error state by discarding
  52356. ** the contents of the page cache and rolling back any open journal
  52357. ** file.
  52358. **
  52359. ** If everything is successful, SQLITE_OK is returned. If an IO error
  52360. ** occurs while locking the database, checking for a hot-journal file or
  52361. ** rolling back a journal file, the IO error code is returned.
  52362. */
  52363. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  52364. int rc = SQLITE_OK; /* Return code */
  52365. /* This routine is only called from b-tree and only when there are no
  52366. ** outstanding pages. This implies that the pager state should either
  52367. ** be OPEN or READER. READER is only possible if the pager is or was in
  52368. ** exclusive access mode. */
  52369. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  52370. assert( assert_pager_state(pPager) );
  52371. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  52372. assert( pPager->errCode==SQLITE_OK );
  52373. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  52374. int bHotJournal = 1; /* True if there exists a hot journal-file */
  52375. assert( !MEMDB );
  52376. assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
  52377. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  52378. if( rc!=SQLITE_OK ){
  52379. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  52380. goto failed;
  52381. }
  52382. /* If a journal file exists, and there is no RESERVED lock on the
  52383. ** database file, then it either needs to be played back or deleted.
  52384. */
  52385. if( pPager->eLock<=SHARED_LOCK ){
  52386. rc = hasHotJournal(pPager, &bHotJournal);
  52387. }
  52388. if( rc!=SQLITE_OK ){
  52389. goto failed;
  52390. }
  52391. if( bHotJournal ){
  52392. if( pPager->readOnly ){
  52393. rc = SQLITE_READONLY_ROLLBACK;
  52394. goto failed;
  52395. }
  52396. /* Get an EXCLUSIVE lock on the database file. At this point it is
  52397. ** important that a RESERVED lock is not obtained on the way to the
  52398. ** EXCLUSIVE lock. If it were, another process might open the
  52399. ** database file, detect the RESERVED lock, and conclude that the
  52400. ** database is safe to read while this process is still rolling the
  52401. ** hot-journal back.
  52402. **
  52403. ** Because the intermediate RESERVED lock is not requested, any
  52404. ** other process attempting to access the database file will get to
  52405. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  52406. ** on the database file.
  52407. **
  52408. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  52409. ** downgraded to SHARED_LOCK before this function returns.
  52410. */
  52411. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  52412. if( rc!=SQLITE_OK ){
  52413. goto failed;
  52414. }
  52415. /* If it is not already open and the file exists on disk, open the
  52416. ** journal for read/write access. Write access is required because
  52417. ** in exclusive-access mode the file descriptor will be kept open
  52418. ** and possibly used for a transaction later on. Also, write-access
  52419. ** is usually required to finalize the journal in journal_mode=persist
  52420. ** mode (and also for journal_mode=truncate on some systems).
  52421. **
  52422. ** If the journal does not exist, it usually means that some
  52423. ** other connection managed to get in and roll it back before
  52424. ** this connection obtained the exclusive lock above. Or, it
  52425. ** may mean that the pager was in the error-state when this
  52426. ** function was called and the journal file does not exist.
  52427. */
  52428. if( !isOpen(pPager->jfd) ){
  52429. sqlite3_vfs * const pVfs = pPager->pVfs;
  52430. int bExists; /* True if journal file exists */
  52431. rc = sqlite3OsAccess(
  52432. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  52433. if( rc==SQLITE_OK && bExists ){
  52434. int fout = 0;
  52435. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  52436. assert( !pPager->tempFile );
  52437. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  52438. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  52439. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  52440. rc = SQLITE_CANTOPEN_BKPT;
  52441. sqlite3OsClose(pPager->jfd);
  52442. }
  52443. }
  52444. }
  52445. /* Playback and delete the journal. Drop the database write
  52446. ** lock and reacquire the read lock. Purge the cache before
  52447. ** playing back the hot-journal so that we don't end up with
  52448. ** an inconsistent cache. Sync the hot journal before playing
  52449. ** it back since the process that crashed and left the hot journal
  52450. ** probably did not sync it and we are required to always sync
  52451. ** the journal before playing it back.
  52452. */
  52453. if( isOpen(pPager->jfd) ){
  52454. assert( rc==SQLITE_OK );
  52455. rc = pagerSyncHotJournal(pPager);
  52456. if( rc==SQLITE_OK ){
  52457. rc = pager_playback(pPager, !pPager->tempFile);
  52458. pPager->eState = PAGER_OPEN;
  52459. }
  52460. }else if( !pPager->exclusiveMode ){
  52461. pagerUnlockDb(pPager, SHARED_LOCK);
  52462. }
  52463. if( rc!=SQLITE_OK ){
  52464. /* This branch is taken if an error occurs while trying to open
  52465. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  52466. ** pager_unlock() routine will be called before returning to unlock
  52467. ** the file. If the unlock attempt fails, then Pager.eLock must be
  52468. ** set to UNKNOWN_LOCK (see the comment above the #define for
  52469. ** UNKNOWN_LOCK above for an explanation).
  52470. **
  52471. ** In order to get pager_unlock() to do this, set Pager.eState to
  52472. ** PAGER_ERROR now. This is not actually counted as a transition
  52473. ** to ERROR state in the state diagram at the top of this file,
  52474. ** since we know that the same call to pager_unlock() will very
  52475. ** shortly transition the pager object to the OPEN state. Calling
  52476. ** assert_pager_state() would fail now, as it should not be possible
  52477. ** to be in ERROR state when there are zero outstanding page
  52478. ** references.
  52479. */
  52480. pager_error(pPager, rc);
  52481. goto failed;
  52482. }
  52483. assert( pPager->eState==PAGER_OPEN );
  52484. assert( (pPager->eLock==SHARED_LOCK)
  52485. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  52486. );
  52487. }
  52488. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  52489. /* The shared-lock has just been acquired then check to
  52490. ** see if the database has been modified. If the database has changed,
  52491. ** flush the cache. The hasHeldSharedLock flag prevents this from
  52492. ** occurring on the very first access to a file, in order to save a
  52493. ** single unnecessary sqlite3OsRead() call at the start-up.
  52494. **
  52495. ** Database changes are detected by looking at 15 bytes beginning
  52496. ** at offset 24 into the file. The first 4 of these 16 bytes are
  52497. ** a 32-bit counter that is incremented with each change. The
  52498. ** other bytes change randomly with each file change when
  52499. ** a codec is in use.
  52500. **
  52501. ** There is a vanishingly small chance that a change will not be
  52502. ** detected. The chance of an undetected change is so small that
  52503. ** it can be neglected.
  52504. */
  52505. char dbFileVers[sizeof(pPager->dbFileVers)];
  52506. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  52507. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  52508. if( rc!=SQLITE_OK ){
  52509. if( rc!=SQLITE_IOERR_SHORT_READ ){
  52510. goto failed;
  52511. }
  52512. memset(dbFileVers, 0, sizeof(dbFileVers));
  52513. }
  52514. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  52515. pager_reset(pPager);
  52516. /* Unmap the database file. It is possible that external processes
  52517. ** may have truncated the database file and then extended it back
  52518. ** to its original size while this process was not holding a lock.
  52519. ** In this case there may exist a Pager.pMap mapping that appears
  52520. ** to be the right size but is not actually valid. Avoid this
  52521. ** possibility by unmapping the db here. */
  52522. if( USEFETCH(pPager) ){
  52523. sqlite3OsUnfetch(pPager->fd, 0, 0);
  52524. }
  52525. }
  52526. }
  52527. /* If there is a WAL file in the file-system, open this database in WAL
  52528. ** mode. Otherwise, the following function call is a no-op.
  52529. */
  52530. rc = pagerOpenWalIfPresent(pPager);
  52531. #ifndef SQLITE_OMIT_WAL
  52532. assert( pPager->pWal==0 || rc==SQLITE_OK );
  52533. #endif
  52534. }
  52535. if( pagerUseWal(pPager) ){
  52536. assert( rc==SQLITE_OK );
  52537. rc = pagerBeginReadTransaction(pPager);
  52538. }
  52539. if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  52540. rc = pagerPagecount(pPager, &pPager->dbSize);
  52541. }
  52542. failed:
  52543. if( rc!=SQLITE_OK ){
  52544. assert( !MEMDB );
  52545. pager_unlock(pPager);
  52546. assert( pPager->eState==PAGER_OPEN );
  52547. }else{
  52548. pPager->eState = PAGER_READER;
  52549. pPager->hasHeldSharedLock = 1;
  52550. }
  52551. return rc;
  52552. }
  52553. /*
  52554. ** If the reference count has reached zero, rollback any active
  52555. ** transaction and unlock the pager.
  52556. **
  52557. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  52558. ** the rollback journal, the unlock is not performed and there is
  52559. ** nothing to rollback, so this routine is a no-op.
  52560. */
  52561. static void pagerUnlockIfUnused(Pager *pPager){
  52562. if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
  52563. assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
  52564. pagerUnlockAndRollback(pPager);
  52565. }
  52566. }
  52567. /*
  52568. ** The page getter methods each try to acquire a reference to a
  52569. ** page with page number pgno. If the requested reference is
  52570. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  52571. **
  52572. ** There are different implementations of the getter method depending
  52573. ** on the current state of the pager.
  52574. **
  52575. ** getPageNormal() -- The normal getter
  52576. ** getPageError() -- Used if the pager is in an error state
  52577. ** getPageMmap() -- Used if memory-mapped I/O is enabled
  52578. **
  52579. ** If the requested page is already in the cache, it is returned.
  52580. ** Otherwise, a new page object is allocated and populated with data
  52581. ** read from the database file. In some cases, the pcache module may
  52582. ** choose not to allocate a new page object and may reuse an existing
  52583. ** object with no outstanding references.
  52584. **
  52585. ** The extra data appended to a page is always initialized to zeros the
  52586. ** first time a page is loaded into memory. If the page requested is
  52587. ** already in the cache when this function is called, then the extra
  52588. ** data is left as it was when the page object was last used.
  52589. **
  52590. ** If the database image is smaller than the requested page or if
  52591. ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
  52592. ** requested page is not already stored in the cache, then no
  52593. ** actual disk read occurs. In this case the memory image of the
  52594. ** page is initialized to all zeros.
  52595. **
  52596. ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
  52597. ** the contents of the page. This occurs in two scenarios:
  52598. **
  52599. ** a) When reading a free-list leaf page from the database, and
  52600. **
  52601. ** b) When a savepoint is being rolled back and we need to load
  52602. ** a new page into the cache to be filled with the data read
  52603. ** from the savepoint journal.
  52604. **
  52605. ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
  52606. ** of being read from the database. Additionally, the bits corresponding
  52607. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  52608. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  52609. ** savepoints are set. This means if the page is made writable at any
  52610. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  52611. ** will not be journaled. This saves IO.
  52612. **
  52613. ** The acquisition might fail for several reasons. In all cases,
  52614. ** an appropriate error code is returned and *ppPage is set to NULL.
  52615. **
  52616. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  52617. ** to find a page in the in-memory cache first. If the page is not already
  52618. ** in memory, this routine goes to disk to read it in whereas Lookup()
  52619. ** just returns 0. This routine acquires a read-lock the first time it
  52620. ** has to go to disk, and could also playback an old journal if necessary.
  52621. ** Since Lookup() never goes to disk, it never has to deal with locks
  52622. ** or journal files.
  52623. */
  52624. static int getPageNormal(
  52625. Pager *pPager, /* The pager open on the database file */
  52626. Pgno pgno, /* Page number to fetch */
  52627. DbPage **ppPage, /* Write a pointer to the page here */
  52628. int flags /* PAGER_GET_XXX flags */
  52629. ){
  52630. int rc = SQLITE_OK;
  52631. PgHdr *pPg;
  52632. u8 noContent; /* True if PAGER_GET_NOCONTENT is set */
  52633. sqlite3_pcache_page *pBase;
  52634. assert( pPager->errCode==SQLITE_OK );
  52635. assert( pPager->eState>=PAGER_READER );
  52636. assert( assert_pager_state(pPager) );
  52637. assert( pPager->hasHeldSharedLock==1 );
  52638. if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
  52639. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  52640. if( pBase==0 ){
  52641. pPg = 0;
  52642. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  52643. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  52644. if( pBase==0 ){
  52645. rc = SQLITE_NOMEM_BKPT;
  52646. goto pager_acquire_err;
  52647. }
  52648. }
  52649. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  52650. assert( pPg==(*ppPage) );
  52651. assert( pPg->pgno==pgno );
  52652. assert( pPg->pPager==pPager || pPg->pPager==0 );
  52653. noContent = (flags & PAGER_GET_NOCONTENT)!=0;
  52654. if( pPg->pPager && !noContent ){
  52655. /* In this case the pcache already contains an initialized copy of
  52656. ** the page. Return without further ado. */
  52657. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  52658. pPager->aStat[PAGER_STAT_HIT]++;
  52659. return SQLITE_OK;
  52660. }else{
  52661. /* The pager cache has created a new page. Its content needs to
  52662. ** be initialized. But first some error checks:
  52663. **
  52664. ** (1) The maximum page number is 2^31
  52665. ** (2) Never try to fetch the locking page
  52666. */
  52667. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  52668. rc = SQLITE_CORRUPT_BKPT;
  52669. goto pager_acquire_err;
  52670. }
  52671. pPg->pPager = pPager;
  52672. assert( !isOpen(pPager->fd) || !MEMDB );
  52673. if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
  52674. if( pgno>pPager->mxPgno ){
  52675. rc = SQLITE_FULL;
  52676. goto pager_acquire_err;
  52677. }
  52678. if( noContent ){
  52679. /* Failure to set the bits in the InJournal bit-vectors is benign.
  52680. ** It merely means that we might do some extra work to journal a
  52681. ** page that does not need to be journaled. Nevertheless, be sure
  52682. ** to test the case where a malloc error occurs while trying to set
  52683. ** a bit in a bit vector.
  52684. */
  52685. sqlite3BeginBenignMalloc();
  52686. if( pgno<=pPager->dbOrigSize ){
  52687. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  52688. testcase( rc==SQLITE_NOMEM );
  52689. }
  52690. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  52691. testcase( rc==SQLITE_NOMEM );
  52692. sqlite3EndBenignMalloc();
  52693. }
  52694. memset(pPg->pData, 0, pPager->pageSize);
  52695. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  52696. }else{
  52697. assert( pPg->pPager==pPager );
  52698. pPager->aStat[PAGER_STAT_MISS]++;
  52699. rc = readDbPage(pPg);
  52700. if( rc!=SQLITE_OK ){
  52701. goto pager_acquire_err;
  52702. }
  52703. }
  52704. pager_set_pagehash(pPg);
  52705. }
  52706. return SQLITE_OK;
  52707. pager_acquire_err:
  52708. assert( rc!=SQLITE_OK );
  52709. if( pPg ){
  52710. sqlite3PcacheDrop(pPg);
  52711. }
  52712. pagerUnlockIfUnused(pPager);
  52713. *ppPage = 0;
  52714. return rc;
  52715. }
  52716. #if SQLITE_MAX_MMAP_SIZE>0
  52717. /* The page getter for when memory-mapped I/O is enabled */
  52718. static int getPageMMap(
  52719. Pager *pPager, /* The pager open on the database file */
  52720. Pgno pgno, /* Page number to fetch */
  52721. DbPage **ppPage, /* Write a pointer to the page here */
  52722. int flags /* PAGER_GET_XXX flags */
  52723. ){
  52724. int rc = SQLITE_OK;
  52725. PgHdr *pPg = 0;
  52726. u32 iFrame = 0; /* Frame to read from WAL file */
  52727. /* It is acceptable to use a read-only (mmap) page for any page except
  52728. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  52729. ** flag was specified by the caller. And so long as the db is not a
  52730. ** temporary or in-memory database. */
  52731. const int bMmapOk = (pgno>1
  52732. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  52733. );
  52734. assert( USEFETCH(pPager) );
  52735. #ifdef SQLITE_HAS_CODEC
  52736. assert( pPager->xCodec==0 );
  52737. #endif
  52738. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  52739. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  52740. ** test in the previous statement, and avoid testing pgno==0 in the
  52741. ** common case where pgno is large. */
  52742. if( pgno<=1 && pgno==0 ){
  52743. return SQLITE_CORRUPT_BKPT;
  52744. }
  52745. assert( pPager->eState>=PAGER_READER );
  52746. assert( assert_pager_state(pPager) );
  52747. assert( pPager->hasHeldSharedLock==1 );
  52748. assert( pPager->errCode==SQLITE_OK );
  52749. if( bMmapOk && pagerUseWal(pPager) ){
  52750. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  52751. if( rc!=SQLITE_OK ){
  52752. *ppPage = 0;
  52753. return rc;
  52754. }
  52755. }
  52756. if( bMmapOk && iFrame==0 ){
  52757. void *pData = 0;
  52758. rc = sqlite3OsFetch(pPager->fd,
  52759. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  52760. );
  52761. if( rc==SQLITE_OK && pData ){
  52762. if( pPager->eState>PAGER_READER || pPager->tempFile ){
  52763. pPg = sqlite3PagerLookup(pPager, pgno);
  52764. }
  52765. if( pPg==0 ){
  52766. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  52767. }else{
  52768. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  52769. }
  52770. if( pPg ){
  52771. assert( rc==SQLITE_OK );
  52772. *ppPage = pPg;
  52773. return SQLITE_OK;
  52774. }
  52775. }
  52776. if( rc!=SQLITE_OK ){
  52777. *ppPage = 0;
  52778. return rc;
  52779. }
  52780. }
  52781. return getPageNormal(pPager, pgno, ppPage, flags);
  52782. }
  52783. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  52784. /* The page getter method for when the pager is an error state */
  52785. static int getPageError(
  52786. Pager *pPager, /* The pager open on the database file */
  52787. Pgno pgno, /* Page number to fetch */
  52788. DbPage **ppPage, /* Write a pointer to the page here */
  52789. int flags /* PAGER_GET_XXX flags */
  52790. ){
  52791. UNUSED_PARAMETER(pgno);
  52792. UNUSED_PARAMETER(flags);
  52793. assert( pPager->errCode!=SQLITE_OK );
  52794. *ppPage = 0;
  52795. return pPager->errCode;
  52796. }
  52797. /* Dispatch all page fetch requests to the appropriate getter method.
  52798. */
  52799. SQLITE_PRIVATE int sqlite3PagerGet(
  52800. Pager *pPager, /* The pager open on the database file */
  52801. Pgno pgno, /* Page number to fetch */
  52802. DbPage **ppPage, /* Write a pointer to the page here */
  52803. int flags /* PAGER_GET_XXX flags */
  52804. ){
  52805. return pPager->xGet(pPager, pgno, ppPage, flags);
  52806. }
  52807. /*
  52808. ** Acquire a page if it is already in the in-memory cache. Do
  52809. ** not read the page from disk. Return a pointer to the page,
  52810. ** or 0 if the page is not in cache.
  52811. **
  52812. ** See also sqlite3PagerGet(). The difference between this routine
  52813. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  52814. ** in the page if the page is not already in cache. This routine
  52815. ** returns NULL if the page is not in cache or if a disk I/O error
  52816. ** has ever happened.
  52817. */
  52818. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  52819. sqlite3_pcache_page *pPage;
  52820. assert( pPager!=0 );
  52821. assert( pgno!=0 );
  52822. assert( pPager->pPCache!=0 );
  52823. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  52824. assert( pPage==0 || pPager->hasHeldSharedLock );
  52825. if( pPage==0 ) return 0;
  52826. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  52827. }
  52828. /*
  52829. ** Release a page reference.
  52830. **
  52831. ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
  52832. ** used if we know that the page being released is not the last page.
  52833. ** The btree layer always holds page1 open until the end, so these first
  52834. ** to routines can be used to release any page other than BtShared.pPage1.
  52835. **
  52836. ** Use sqlite3PagerUnrefPageOne() to release page1. This latter routine
  52837. ** checks the total number of outstanding pages and if the number of
  52838. ** pages reaches zero it drops the database lock.
  52839. */
  52840. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  52841. TESTONLY( Pager *pPager = pPg->pPager; )
  52842. assert( pPg!=0 );
  52843. if( pPg->flags & PGHDR_MMAP ){
  52844. assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */
  52845. pagerReleaseMapPage(pPg);
  52846. }else{
  52847. sqlite3PcacheRelease(pPg);
  52848. }
  52849. /* Do not use this routine to release the last reference to page1 */
  52850. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  52851. }
  52852. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  52853. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  52854. }
  52855. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
  52856. Pager *pPager;
  52857. assert( pPg!=0 );
  52858. assert( pPg->pgno==1 );
  52859. assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
  52860. pPager = pPg->pPager;
  52861. sqlite3PagerResetLockTimeout(pPager);
  52862. sqlite3PcacheRelease(pPg);
  52863. pagerUnlockIfUnused(pPager);
  52864. }
  52865. /*
  52866. ** This function is called at the start of every write transaction.
  52867. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  52868. ** file when this routine is called.
  52869. **
  52870. ** Open the journal file for pager pPager and write a journal header
  52871. ** to the start of it. If there are active savepoints, open the sub-journal
  52872. ** as well. This function is only used when the journal file is being
  52873. ** opened to write a rollback log for a transaction. It is not used
  52874. ** when opening a hot journal file to roll it back.
  52875. **
  52876. ** If the journal file is already open (as it may be in exclusive mode),
  52877. ** then this function just writes a journal header to the start of the
  52878. ** already open file.
  52879. **
  52880. ** Whether or not the journal file is opened by this function, the
  52881. ** Pager.pInJournal bitvec structure is allocated.
  52882. **
  52883. ** Return SQLITE_OK if everything is successful. Otherwise, return
  52884. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  52885. ** an IO error code if opening or writing the journal file fails.
  52886. */
  52887. static int pager_open_journal(Pager *pPager){
  52888. int rc = SQLITE_OK; /* Return code */
  52889. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  52890. assert( pPager->eState==PAGER_WRITER_LOCKED );
  52891. assert( assert_pager_state(pPager) );
  52892. assert( pPager->pInJournal==0 );
  52893. /* If already in the error state, this function is a no-op. But on
  52894. ** the other hand, this routine is never called if we are already in
  52895. ** an error state. */
  52896. if( NEVER(pPager->errCode) ) return pPager->errCode;
  52897. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  52898. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  52899. if( pPager->pInJournal==0 ){
  52900. return SQLITE_NOMEM_BKPT;
  52901. }
  52902. /* Open the journal file if it is not already open. */
  52903. if( !isOpen(pPager->jfd) ){
  52904. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  52905. sqlite3MemJournalOpen(pPager->jfd);
  52906. }else{
  52907. int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  52908. int nSpill;
  52909. if( pPager->tempFile ){
  52910. flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
  52911. nSpill = sqlite3Config.nStmtSpill;
  52912. }else{
  52913. flags |= SQLITE_OPEN_MAIN_JOURNAL;
  52914. nSpill = jrnlBufferSize(pPager);
  52915. }
  52916. /* Verify that the database still has the same name as it did when
  52917. ** it was originally opened. */
  52918. rc = databaseIsUnmoved(pPager);
  52919. if( rc==SQLITE_OK ){
  52920. rc = sqlite3JournalOpen (
  52921. pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
  52922. );
  52923. }
  52924. }
  52925. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  52926. }
  52927. /* Write the first journal header to the journal file and open
  52928. ** the sub-journal if necessary.
  52929. */
  52930. if( rc==SQLITE_OK ){
  52931. /* TODO: Check if all of these are really required. */
  52932. pPager->nRec = 0;
  52933. pPager->journalOff = 0;
  52934. pPager->setMaster = 0;
  52935. pPager->journalHdr = 0;
  52936. rc = writeJournalHdr(pPager);
  52937. }
  52938. }
  52939. if( rc!=SQLITE_OK ){
  52940. sqlite3BitvecDestroy(pPager->pInJournal);
  52941. pPager->pInJournal = 0;
  52942. }else{
  52943. assert( pPager->eState==PAGER_WRITER_LOCKED );
  52944. pPager->eState = PAGER_WRITER_CACHEMOD;
  52945. }
  52946. return rc;
  52947. }
  52948. /*
  52949. ** Begin a write-transaction on the specified pager object. If a
  52950. ** write-transaction has already been opened, this function is a no-op.
  52951. **
  52952. ** If the exFlag argument is false, then acquire at least a RESERVED
  52953. ** lock on the database file. If exFlag is true, then acquire at least
  52954. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  52955. ** functions need be called.
  52956. **
  52957. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  52958. ** within this transaction will be opened as an in-memory file. This
  52959. ** has no effect if the sub-journal is already opened (as it may be when
  52960. ** running in exclusive mode) or if the transaction does not require a
  52961. ** sub-journal. If the subjInMemory argument is zero, then any required
  52962. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  52963. ** or using a temporary file otherwise.
  52964. */
  52965. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  52966. int rc = SQLITE_OK;
  52967. if( pPager->errCode ) return pPager->errCode;
  52968. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  52969. pPager->subjInMemory = (u8)subjInMemory;
  52970. if( ALWAYS(pPager->eState==PAGER_READER) ){
  52971. assert( pPager->pInJournal==0 );
  52972. if( pagerUseWal(pPager) ){
  52973. /* If the pager is configured to use locking_mode=exclusive, and an
  52974. ** exclusive lock on the database is not already held, obtain it now.
  52975. */
  52976. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  52977. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  52978. if( rc!=SQLITE_OK ){
  52979. return rc;
  52980. }
  52981. (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
  52982. }
  52983. /* Grab the write lock on the log file. If successful, upgrade to
  52984. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  52985. ** The busy-handler is not invoked if another connection already
  52986. ** holds the write-lock. If possible, the upper layer will call it.
  52987. */
  52988. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  52989. }else{
  52990. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  52991. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  52992. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  52993. ** lock, but not when obtaining the RESERVED lock.
  52994. */
  52995. rc = pagerLockDb(pPager, RESERVED_LOCK);
  52996. if( rc==SQLITE_OK && exFlag ){
  52997. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  52998. }
  52999. }
  53000. if( rc==SQLITE_OK ){
  53001. /* Change to WRITER_LOCKED state.
  53002. **
  53003. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  53004. ** when it has an open transaction, but never to DBMOD or FINISHED.
  53005. ** This is because in those states the code to roll back savepoint
  53006. ** transactions may copy data from the sub-journal into the database
  53007. ** file as well as into the page cache. Which would be incorrect in
  53008. ** WAL mode.
  53009. */
  53010. pPager->eState = PAGER_WRITER_LOCKED;
  53011. pPager->dbHintSize = pPager->dbSize;
  53012. pPager->dbFileSize = pPager->dbSize;
  53013. pPager->dbOrigSize = pPager->dbSize;
  53014. pPager->journalOff = 0;
  53015. }
  53016. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  53017. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  53018. assert( assert_pager_state(pPager) );
  53019. }
  53020. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  53021. return rc;
  53022. }
  53023. /*
  53024. ** Write page pPg onto the end of the rollback journal.
  53025. */
  53026. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  53027. Pager *pPager = pPg->pPager;
  53028. int rc;
  53029. u32 cksum;
  53030. char *pData2;
  53031. i64 iOff = pPager->journalOff;
  53032. /* We should never write to the journal file the page that
  53033. ** contains the database locks. The following assert verifies
  53034. ** that we do not. */
  53035. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  53036. assert( pPager->journalHdr<=pPager->journalOff );
  53037. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  53038. cksum = pager_cksum(pPager, (u8*)pData2);
  53039. /* Even if an IO or diskfull error occurs while journalling the
  53040. ** page in the block above, set the need-sync flag for the page.
  53041. ** Otherwise, when the transaction is rolled back, the logic in
  53042. ** playback_one_page() will think that the page needs to be restored
  53043. ** in the database file. And if an IO error occurs while doing so,
  53044. ** then corruption may follow.
  53045. */
  53046. pPg->flags |= PGHDR_NEED_SYNC;
  53047. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  53048. if( rc!=SQLITE_OK ) return rc;
  53049. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  53050. if( rc!=SQLITE_OK ) return rc;
  53051. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  53052. if( rc!=SQLITE_OK ) return rc;
  53053. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  53054. pPager->journalOff, pPager->pageSize));
  53055. PAGER_INCR(sqlite3_pager_writej_count);
  53056. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  53057. PAGERID(pPager), pPg->pgno,
  53058. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  53059. pPager->journalOff += 8 + pPager->pageSize;
  53060. pPager->nRec++;
  53061. assert( pPager->pInJournal!=0 );
  53062. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  53063. testcase( rc==SQLITE_NOMEM );
  53064. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  53065. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  53066. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  53067. return rc;
  53068. }
  53069. /*
  53070. ** Mark a single data page as writeable. The page is written into the
  53071. ** main journal or sub-journal as required. If the page is written into
  53072. ** one of the journals, the corresponding bit is set in the
  53073. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  53074. ** of any open savepoints as appropriate.
  53075. */
  53076. static int pager_write(PgHdr *pPg){
  53077. Pager *pPager = pPg->pPager;
  53078. int rc = SQLITE_OK;
  53079. /* This routine is not called unless a write-transaction has already
  53080. ** been started. The journal file may or may not be open at this point.
  53081. ** It is never called in the ERROR state.
  53082. */
  53083. assert( pPager->eState==PAGER_WRITER_LOCKED
  53084. || pPager->eState==PAGER_WRITER_CACHEMOD
  53085. || pPager->eState==PAGER_WRITER_DBMOD
  53086. );
  53087. assert( assert_pager_state(pPager) );
  53088. assert( pPager->errCode==0 );
  53089. assert( pPager->readOnly==0 );
  53090. CHECK_PAGE(pPg);
  53091. /* The journal file needs to be opened. Higher level routines have already
  53092. ** obtained the necessary locks to begin the write-transaction, but the
  53093. ** rollback journal might not yet be open. Open it now if this is the case.
  53094. **
  53095. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  53096. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  53097. ** an error might occur and the pager would end up in WRITER_LOCKED state
  53098. ** with pages marked as dirty in the cache.
  53099. */
  53100. if( pPager->eState==PAGER_WRITER_LOCKED ){
  53101. rc = pager_open_journal(pPager);
  53102. if( rc!=SQLITE_OK ) return rc;
  53103. }
  53104. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  53105. assert( assert_pager_state(pPager) );
  53106. /* Mark the page that is about to be modified as dirty. */
  53107. sqlite3PcacheMakeDirty(pPg);
  53108. /* If a rollback journal is in use, them make sure the page that is about
  53109. ** to change is in the rollback journal, or if the page is a new page off
  53110. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  53111. */
  53112. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  53113. if( pPager->pInJournal!=0
  53114. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  53115. ){
  53116. assert( pagerUseWal(pPager)==0 );
  53117. if( pPg->pgno<=pPager->dbOrigSize ){
  53118. rc = pagerAddPageToRollbackJournal(pPg);
  53119. if( rc!=SQLITE_OK ){
  53120. return rc;
  53121. }
  53122. }else{
  53123. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  53124. pPg->flags |= PGHDR_NEED_SYNC;
  53125. }
  53126. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  53127. PAGERID(pPager), pPg->pgno,
  53128. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  53129. }
  53130. }
  53131. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  53132. ** and before writing the page into the rollback journal. Wait until now,
  53133. ** after the page has been successfully journalled, before setting the
  53134. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  53135. */
  53136. pPg->flags |= PGHDR_WRITEABLE;
  53137. /* If the statement journal is open and the page is not in it,
  53138. ** then write the page into the statement journal.
  53139. */
  53140. if( pPager->nSavepoint>0 ){
  53141. rc = subjournalPageIfRequired(pPg);
  53142. }
  53143. /* Update the database size and return. */
  53144. if( pPager->dbSize<pPg->pgno ){
  53145. pPager->dbSize = pPg->pgno;
  53146. }
  53147. return rc;
  53148. }
  53149. /*
  53150. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  53151. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  53152. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  53153. ** a sector need to be journalled in case of a power loss in the middle of
  53154. ** a write.
  53155. **
  53156. ** Usually, the sector size is less than or equal to the page size, in which
  53157. ** case pages can be individually written. This routine only runs in the
  53158. ** exceptional case where the page size is smaller than the sector size.
  53159. */
  53160. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  53161. int rc = SQLITE_OK; /* Return code */
  53162. Pgno nPageCount; /* Total number of pages in database file */
  53163. Pgno pg1; /* First page of the sector pPg is located on. */
  53164. int nPage = 0; /* Number of pages starting at pg1 to journal */
  53165. int ii; /* Loop counter */
  53166. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  53167. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  53168. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  53169. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  53170. ** a journal header to be written between the pages journaled by
  53171. ** this function.
  53172. */
  53173. assert( !MEMDB );
  53174. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  53175. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  53176. /* This trick assumes that both the page-size and sector-size are
  53177. ** an integer power of 2. It sets variable pg1 to the identifier
  53178. ** of the first page of the sector pPg is located on.
  53179. */
  53180. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  53181. nPageCount = pPager->dbSize;
  53182. if( pPg->pgno>nPageCount ){
  53183. nPage = (pPg->pgno - pg1)+1;
  53184. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  53185. nPage = nPageCount+1-pg1;
  53186. }else{
  53187. nPage = nPagePerSector;
  53188. }
  53189. assert(nPage>0);
  53190. assert(pg1<=pPg->pgno);
  53191. assert((pg1+nPage)>pPg->pgno);
  53192. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  53193. Pgno pg = pg1+ii;
  53194. PgHdr *pPage;
  53195. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  53196. if( pg!=PAGER_MJ_PGNO(pPager) ){
  53197. rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
  53198. if( rc==SQLITE_OK ){
  53199. rc = pager_write(pPage);
  53200. if( pPage->flags&PGHDR_NEED_SYNC ){
  53201. needSync = 1;
  53202. }
  53203. sqlite3PagerUnrefNotNull(pPage);
  53204. }
  53205. }
  53206. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  53207. if( pPage->flags&PGHDR_NEED_SYNC ){
  53208. needSync = 1;
  53209. }
  53210. sqlite3PagerUnrefNotNull(pPage);
  53211. }
  53212. }
  53213. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  53214. ** starting at pg1, then it needs to be set for all of them. Because
  53215. ** writing to any of these nPage pages may damage the others, the
  53216. ** journal file must contain sync()ed copies of all of them
  53217. ** before any of them can be written out to the database file.
  53218. */
  53219. if( rc==SQLITE_OK && needSync ){
  53220. assert( !MEMDB );
  53221. for(ii=0; ii<nPage; ii++){
  53222. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  53223. if( pPage ){
  53224. pPage->flags |= PGHDR_NEED_SYNC;
  53225. sqlite3PagerUnrefNotNull(pPage);
  53226. }
  53227. }
  53228. }
  53229. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  53230. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  53231. return rc;
  53232. }
  53233. /*
  53234. ** Mark a data page as writeable. This routine must be called before
  53235. ** making changes to a page. The caller must check the return value
  53236. ** of this function and be careful not to change any page data unless
  53237. ** this routine returns SQLITE_OK.
  53238. **
  53239. ** The difference between this function and pager_write() is that this
  53240. ** function also deals with the special case where 2 or more pages
  53241. ** fit on a single disk sector. In this case all co-resident pages
  53242. ** must have been written to the journal file before returning.
  53243. **
  53244. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  53245. ** as appropriate. Otherwise, SQLITE_OK.
  53246. */
  53247. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  53248. Pager *pPager = pPg->pPager;
  53249. assert( (pPg->flags & PGHDR_MMAP)==0 );
  53250. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  53251. assert( assert_pager_state(pPager) );
  53252. if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  53253. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  53254. return SQLITE_OK;
  53255. }else if( pPager->errCode ){
  53256. return pPager->errCode;
  53257. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  53258. assert( pPager->tempFile==0 );
  53259. return pagerWriteLargeSector(pPg);
  53260. }else{
  53261. return pager_write(pPg);
  53262. }
  53263. }
  53264. /*
  53265. ** Return TRUE if the page given in the argument was previously passed
  53266. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  53267. ** to change the content of the page.
  53268. */
  53269. #ifndef NDEBUG
  53270. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  53271. return pPg->flags & PGHDR_WRITEABLE;
  53272. }
  53273. #endif
  53274. /*
  53275. ** A call to this routine tells the pager that it is not necessary to
  53276. ** write the information on page pPg back to the disk, even though
  53277. ** that page might be marked as dirty. This happens, for example, when
  53278. ** the page has been added as a leaf of the freelist and so its
  53279. ** content no longer matters.
  53280. **
  53281. ** The overlying software layer calls this routine when all of the data
  53282. ** on the given page is unused. The pager marks the page as clean so
  53283. ** that it does not get written to disk.
  53284. **
  53285. ** Tests show that this optimization can quadruple the speed of large
  53286. ** DELETE operations.
  53287. **
  53288. ** This optimization cannot be used with a temp-file, as the page may
  53289. ** have been dirty at the start of the transaction. In that case, if
  53290. ** memory pressure forces page pPg out of the cache, the data does need
  53291. ** to be written out to disk so that it may be read back in if the
  53292. ** current transaction is rolled back.
  53293. */
  53294. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  53295. Pager *pPager = pPg->pPager;
  53296. if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  53297. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  53298. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  53299. pPg->flags |= PGHDR_DONT_WRITE;
  53300. pPg->flags &= ~PGHDR_WRITEABLE;
  53301. testcase( pPg->flags & PGHDR_NEED_SYNC );
  53302. pager_set_pagehash(pPg);
  53303. }
  53304. }
  53305. /*
  53306. ** This routine is called to increment the value of the database file
  53307. ** change-counter, stored as a 4-byte big-endian integer starting at
  53308. ** byte offset 24 of the pager file. The secondary change counter at
  53309. ** 92 is also updated, as is the SQLite version number at offset 96.
  53310. **
  53311. ** But this only happens if the pPager->changeCountDone flag is false.
  53312. ** To avoid excess churning of page 1, the update only happens once.
  53313. ** See also the pager_write_changecounter() routine that does an
  53314. ** unconditional update of the change counters.
  53315. **
  53316. ** If the isDirectMode flag is zero, then this is done by calling
  53317. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  53318. ** page data. In this case the file will be updated when the current
  53319. ** transaction is committed.
  53320. **
  53321. ** The isDirectMode flag may only be non-zero if the library was compiled
  53322. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  53323. ** if isDirect is non-zero, then the database file is updated directly
  53324. ** by writing an updated version of page 1 using a call to the
  53325. ** sqlite3OsWrite() function.
  53326. */
  53327. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  53328. int rc = SQLITE_OK;
  53329. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  53330. || pPager->eState==PAGER_WRITER_DBMOD
  53331. );
  53332. assert( assert_pager_state(pPager) );
  53333. /* Declare and initialize constant integer 'isDirect'. If the
  53334. ** atomic-write optimization is enabled in this build, then isDirect
  53335. ** is initialized to the value passed as the isDirectMode parameter
  53336. ** to this function. Otherwise, it is always set to zero.
  53337. **
  53338. ** The idea is that if the atomic-write optimization is not
  53339. ** enabled at compile time, the compiler can omit the tests of
  53340. ** 'isDirect' below, as well as the block enclosed in the
  53341. ** "if( isDirect )" condition.
  53342. */
  53343. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  53344. # define DIRECT_MODE 0
  53345. assert( isDirectMode==0 );
  53346. UNUSED_PARAMETER(isDirectMode);
  53347. #else
  53348. # define DIRECT_MODE isDirectMode
  53349. #endif
  53350. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  53351. PgHdr *pPgHdr; /* Reference to page 1 */
  53352. assert( !pPager->tempFile && isOpen(pPager->fd) );
  53353. /* Open page 1 of the file for writing. */
  53354. rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
  53355. assert( pPgHdr==0 || rc==SQLITE_OK );
  53356. /* If page one was fetched successfully, and this function is not
  53357. ** operating in direct-mode, make page 1 writable. When not in
  53358. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  53359. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  53360. */
  53361. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  53362. rc = sqlite3PagerWrite(pPgHdr);
  53363. }
  53364. if( rc==SQLITE_OK ){
  53365. /* Actually do the update of the change counter */
  53366. pager_write_changecounter(pPgHdr);
  53367. /* If running in direct mode, write the contents of page 1 to the file. */
  53368. if( DIRECT_MODE ){
  53369. const void *zBuf;
  53370. assert( pPager->dbFileSize>0 );
  53371. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
  53372. if( rc==SQLITE_OK ){
  53373. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  53374. pPager->aStat[PAGER_STAT_WRITE]++;
  53375. }
  53376. if( rc==SQLITE_OK ){
  53377. /* Update the pager's copy of the change-counter. Otherwise, the
  53378. ** next time a read transaction is opened the cache will be
  53379. ** flushed (as the change-counter values will not match). */
  53380. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  53381. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  53382. pPager->changeCountDone = 1;
  53383. }
  53384. }else{
  53385. pPager->changeCountDone = 1;
  53386. }
  53387. }
  53388. /* Release the page reference. */
  53389. sqlite3PagerUnref(pPgHdr);
  53390. }
  53391. return rc;
  53392. }
  53393. /*
  53394. ** Sync the database file to disk. This is a no-op for in-memory databases
  53395. ** or pages with the Pager.noSync flag set.
  53396. **
  53397. ** If successful, or if called on a pager for which it is a no-op, this
  53398. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  53399. */
  53400. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  53401. int rc = SQLITE_OK;
  53402. void *pArg = (void*)zMaster;
  53403. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  53404. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  53405. if( rc==SQLITE_OK && !pPager->noSync ){
  53406. assert( !MEMDB );
  53407. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  53408. }
  53409. return rc;
  53410. }
  53411. /*
  53412. ** This function may only be called while a write-transaction is active in
  53413. ** rollback. If the connection is in WAL mode, this call is a no-op.
  53414. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  53415. ** the database file, an attempt is made to obtain one.
  53416. **
  53417. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  53418. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  53419. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  53420. ** returned.
  53421. */
  53422. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  53423. int rc = pPager->errCode;
  53424. assert( assert_pager_state(pPager) );
  53425. if( rc==SQLITE_OK ){
  53426. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  53427. || pPager->eState==PAGER_WRITER_DBMOD
  53428. || pPager->eState==PAGER_WRITER_LOCKED
  53429. );
  53430. assert( assert_pager_state(pPager) );
  53431. if( 0==pagerUseWal(pPager) ){
  53432. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  53433. }
  53434. }
  53435. return rc;
  53436. }
  53437. /*
  53438. ** Sync the database file for the pager pPager. zMaster points to the name
  53439. ** of a master journal file that should be written into the individual
  53440. ** journal file. zMaster may be NULL, which is interpreted as no master
  53441. ** journal (a single database transaction).
  53442. **
  53443. ** This routine ensures that:
  53444. **
  53445. ** * The database file change-counter is updated,
  53446. ** * the journal is synced (unless the atomic-write optimization is used),
  53447. ** * all dirty pages are written to the database file,
  53448. ** * the database file is truncated (if required), and
  53449. ** * the database file synced.
  53450. **
  53451. ** The only thing that remains to commit the transaction is to finalize
  53452. ** (delete, truncate or zero the first part of) the journal file (or
  53453. ** delete the master journal file if specified).
  53454. **
  53455. ** Note that if zMaster==NULL, this does not overwrite a previous value
  53456. ** passed to an sqlite3PagerCommitPhaseOne() call.
  53457. **
  53458. ** If the final parameter - noSync - is true, then the database file itself
  53459. ** is not synced. The caller must call sqlite3PagerSync() directly to
  53460. ** sync the database file before calling CommitPhaseTwo() to delete the
  53461. ** journal file in this case.
  53462. */
  53463. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  53464. Pager *pPager, /* Pager object */
  53465. const char *zMaster, /* If not NULL, the master journal name */
  53466. int noSync /* True to omit the xSync on the db file */
  53467. ){
  53468. int rc = SQLITE_OK; /* Return code */
  53469. assert( pPager->eState==PAGER_WRITER_LOCKED
  53470. || pPager->eState==PAGER_WRITER_CACHEMOD
  53471. || pPager->eState==PAGER_WRITER_DBMOD
  53472. || pPager->eState==PAGER_ERROR
  53473. );
  53474. assert( assert_pager_state(pPager) );
  53475. /* If a prior error occurred, report that error again. */
  53476. if( NEVER(pPager->errCode) ) return pPager->errCode;
  53477. /* Provide the ability to easily simulate an I/O error during testing */
  53478. if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
  53479. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  53480. pPager->zFilename, zMaster, pPager->dbSize));
  53481. /* If no database changes have been made, return early. */
  53482. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  53483. assert( MEMDB==0 || pPager->tempFile );
  53484. assert( isOpen(pPager->fd) || pPager->tempFile );
  53485. if( 0==pagerFlushOnCommit(pPager, 1) ){
  53486. /* If this is an in-memory db, or no pages have been written to, or this
  53487. ** function has already been called, it is mostly a no-op. However, any
  53488. ** backup in progress needs to be restarted. */
  53489. sqlite3BackupRestart(pPager->pBackup);
  53490. }else{
  53491. PgHdr *pList;
  53492. if( pagerUseWal(pPager) ){
  53493. PgHdr *pPageOne = 0;
  53494. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  53495. if( pList==0 ){
  53496. /* Must have at least one page for the WAL commit flag.
  53497. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  53498. rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
  53499. pList = pPageOne;
  53500. pList->pDirty = 0;
  53501. }
  53502. assert( rc==SQLITE_OK );
  53503. if( ALWAYS(pList) ){
  53504. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  53505. }
  53506. sqlite3PagerUnref(pPageOne);
  53507. if( rc==SQLITE_OK ){
  53508. sqlite3PcacheCleanAll(pPager->pPCache);
  53509. }
  53510. }else{
  53511. /* The bBatch boolean is true if the batch-atomic-write commit method
  53512. ** should be used. No rollback journal is created if batch-atomic-write
  53513. ** is enabled.
  53514. */
  53515. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  53516. sqlite3_file *fd = pPager->fd;
  53517. int bBatch = zMaster==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
  53518. && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
  53519. && !pPager->noSync
  53520. && sqlite3JournalIsInMemory(pPager->jfd);
  53521. #else
  53522. # define bBatch 0
  53523. #endif
  53524. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  53525. /* The following block updates the change-counter. Exactly how it
  53526. ** does this depends on whether or not the atomic-update optimization
  53527. ** was enabled at compile time, and if this transaction meets the
  53528. ** runtime criteria to use the operation:
  53529. **
  53530. ** * The file-system supports the atomic-write property for
  53531. ** blocks of size page-size, and
  53532. ** * This commit is not part of a multi-file transaction, and
  53533. ** * Exactly one page has been modified and store in the journal file.
  53534. **
  53535. ** If the optimization was not enabled at compile time, then the
  53536. ** pager_incr_changecounter() function is called to update the change
  53537. ** counter in 'indirect-mode'. If the optimization is compiled in but
  53538. ** is not applicable to this transaction, call sqlite3JournalCreate()
  53539. ** to make sure the journal file has actually been created, then call
  53540. ** pager_incr_changecounter() to update the change-counter in indirect
  53541. ** mode.
  53542. **
  53543. ** Otherwise, if the optimization is both enabled and applicable,
  53544. ** then call pager_incr_changecounter() to update the change-counter
  53545. ** in 'direct' mode. In this case the journal file will never be
  53546. ** created for this transaction.
  53547. */
  53548. if( bBatch==0 ){
  53549. PgHdr *pPg;
  53550. assert( isOpen(pPager->jfd)
  53551. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  53552. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  53553. );
  53554. if( !zMaster && isOpen(pPager->jfd)
  53555. && pPager->journalOff==jrnlBufferSize(pPager)
  53556. && pPager->dbSize>=pPager->dbOrigSize
  53557. && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  53558. ){
  53559. /* Update the db file change counter via the direct-write method. The
  53560. ** following call will modify the in-memory representation of page 1
  53561. ** to include the updated change counter and then write page 1
  53562. ** directly to the database file. Because of the atomic-write
  53563. ** property of the host file-system, this is safe.
  53564. */
  53565. rc = pager_incr_changecounter(pPager, 1);
  53566. }else{
  53567. rc = sqlite3JournalCreate(pPager->jfd);
  53568. if( rc==SQLITE_OK ){
  53569. rc = pager_incr_changecounter(pPager, 0);
  53570. }
  53571. }
  53572. }
  53573. #else /* SQLITE_ENABLE_ATOMIC_WRITE */
  53574. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  53575. if( zMaster ){
  53576. rc = sqlite3JournalCreate(pPager->jfd);
  53577. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53578. assert( bBatch==0 );
  53579. }
  53580. #endif
  53581. rc = pager_incr_changecounter(pPager, 0);
  53582. #endif /* !SQLITE_ENABLE_ATOMIC_WRITE */
  53583. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53584. /* Write the master journal name into the journal file. If a master
  53585. ** journal file name has already been written to the journal file,
  53586. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  53587. */
  53588. rc = writeMasterJournal(pPager, zMaster);
  53589. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53590. /* Sync the journal file and write all dirty pages to the database.
  53591. ** If the atomic-update optimization is being used, this sync will not
  53592. ** create the journal file or perform any real IO.
  53593. **
  53594. ** Because the change-counter page was just modified, unless the
  53595. ** atomic-update optimization is used it is almost certain that the
  53596. ** journal requires a sync here. However, in locking_mode=exclusive
  53597. ** on a system under memory pressure it is just possible that this is
  53598. ** not the case. In this case it is likely enough that the redundant
  53599. ** xSync() call will be changed to a no-op by the OS anyhow.
  53600. */
  53601. rc = syncJournal(pPager, 0);
  53602. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53603. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  53604. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  53605. if( bBatch ){
  53606. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
  53607. if( rc==SQLITE_OK ){
  53608. rc = pager_write_pagelist(pPager, pList);
  53609. if( rc==SQLITE_OK ){
  53610. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
  53611. }
  53612. if( rc!=SQLITE_OK ){
  53613. sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
  53614. }
  53615. }
  53616. if( (rc&0xFF)==SQLITE_IOERR && rc!=SQLITE_IOERR_NOMEM ){
  53617. rc = sqlite3JournalCreate(pPager->jfd);
  53618. if( rc!=SQLITE_OK ){
  53619. sqlite3OsClose(pPager->jfd);
  53620. goto commit_phase_one_exit;
  53621. }
  53622. bBatch = 0;
  53623. }else{
  53624. sqlite3OsClose(pPager->jfd);
  53625. }
  53626. }
  53627. #endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  53628. if( bBatch==0 ){
  53629. rc = pager_write_pagelist(pPager, pList);
  53630. }
  53631. if( rc!=SQLITE_OK ){
  53632. assert( rc!=SQLITE_IOERR_BLOCKED );
  53633. goto commit_phase_one_exit;
  53634. }
  53635. sqlite3PcacheCleanAll(pPager->pPCache);
  53636. /* If the file on disk is smaller than the database image, use
  53637. ** pager_truncate to grow the file here. This can happen if the database
  53638. ** image was extended as part of the current transaction and then the
  53639. ** last page in the db image moved to the free-list. In this case the
  53640. ** last page is never written out to disk, leaving the database file
  53641. ** undersized. Fix this now if it is the case. */
  53642. if( pPager->dbSize>pPager->dbFileSize ){
  53643. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  53644. assert( pPager->eState==PAGER_WRITER_DBMOD );
  53645. rc = pager_truncate(pPager, nNew);
  53646. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  53647. }
  53648. /* Finally, sync the database file. */
  53649. if( !noSync ){
  53650. rc = sqlite3PagerSync(pPager, zMaster);
  53651. }
  53652. IOTRACE(("DBSYNC %p\n", pPager))
  53653. }
  53654. }
  53655. commit_phase_one_exit:
  53656. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  53657. pPager->eState = PAGER_WRITER_FINISHED;
  53658. }
  53659. return rc;
  53660. }
  53661. /*
  53662. ** When this function is called, the database file has been completely
  53663. ** updated to reflect the changes made by the current transaction and
  53664. ** synced to disk. The journal file still exists in the file-system
  53665. ** though, and if a failure occurs at this point it will eventually
  53666. ** be used as a hot-journal and the current transaction rolled back.
  53667. **
  53668. ** This function finalizes the journal file, either by deleting,
  53669. ** truncating or partially zeroing it, so that it cannot be used
  53670. ** for hot-journal rollback. Once this is done the transaction is
  53671. ** irrevocably committed.
  53672. **
  53673. ** If an error occurs, an IO error code is returned and the pager
  53674. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  53675. */
  53676. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  53677. int rc = SQLITE_OK; /* Return code */
  53678. /* This routine should not be called if a prior error has occurred.
  53679. ** But if (due to a coding error elsewhere in the system) it does get
  53680. ** called, just return the same error code without doing anything. */
  53681. if( NEVER(pPager->errCode) ) return pPager->errCode;
  53682. assert( pPager->eState==PAGER_WRITER_LOCKED
  53683. || pPager->eState==PAGER_WRITER_FINISHED
  53684. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  53685. );
  53686. assert( assert_pager_state(pPager) );
  53687. /* An optimization. If the database was not actually modified during
  53688. ** this transaction, the pager is running in exclusive-mode and is
  53689. ** using persistent journals, then this function is a no-op.
  53690. **
  53691. ** The start of the journal file currently contains a single journal
  53692. ** header with the nRec field set to 0. If such a journal is used as
  53693. ** a hot-journal during hot-journal rollback, 0 changes will be made
  53694. ** to the database file. So there is no need to zero the journal
  53695. ** header. Since the pager is in exclusive mode, there is no need
  53696. ** to drop any locks either.
  53697. */
  53698. if( pPager->eState==PAGER_WRITER_LOCKED
  53699. && pPager->exclusiveMode
  53700. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  53701. ){
  53702. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  53703. pPager->eState = PAGER_READER;
  53704. return SQLITE_OK;
  53705. }
  53706. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  53707. pPager->iDataVersion++;
  53708. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  53709. return pager_error(pPager, rc);
  53710. }
  53711. /*
  53712. ** If a write transaction is open, then all changes made within the
  53713. ** transaction are reverted and the current write-transaction is closed.
  53714. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  53715. ** state if an error occurs.
  53716. **
  53717. ** If the pager is already in PAGER_ERROR state when this function is called,
  53718. ** it returns Pager.errCode immediately. No work is performed in this case.
  53719. **
  53720. ** Otherwise, in rollback mode, this function performs two functions:
  53721. **
  53722. ** 1) It rolls back the journal file, restoring all database file and
  53723. ** in-memory cache pages to the state they were in when the transaction
  53724. ** was opened, and
  53725. **
  53726. ** 2) It finalizes the journal file, so that it is not used for hot
  53727. ** rollback at any point in the future.
  53728. **
  53729. ** Finalization of the journal file (task 2) is only performed if the
  53730. ** rollback is successful.
  53731. **
  53732. ** In WAL mode, all cache-entries containing data modified within the
  53733. ** current transaction are either expelled from the cache or reverted to
  53734. ** their pre-transaction state by re-reading data from the database or
  53735. ** WAL files. The WAL transaction is then closed.
  53736. */
  53737. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  53738. int rc = SQLITE_OK; /* Return code */
  53739. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  53740. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  53741. ** the pager is already in the ERROR state, the rollback is not
  53742. ** attempted here. Instead, the error code is returned to the caller.
  53743. */
  53744. assert( assert_pager_state(pPager) );
  53745. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  53746. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  53747. if( pagerUseWal(pPager) ){
  53748. int rc2;
  53749. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  53750. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  53751. if( rc==SQLITE_OK ) rc = rc2;
  53752. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  53753. int eState = pPager->eState;
  53754. rc = pager_end_transaction(pPager, 0, 0);
  53755. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  53756. /* This can happen using journal_mode=off. Move the pager to the error
  53757. ** state to indicate that the contents of the cache may not be trusted.
  53758. ** Any active readers will get SQLITE_ABORT.
  53759. */
  53760. pPager->errCode = SQLITE_ABORT;
  53761. pPager->eState = PAGER_ERROR;
  53762. setGetterMethod(pPager);
  53763. return rc;
  53764. }
  53765. }else{
  53766. rc = pager_playback(pPager, 0);
  53767. }
  53768. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  53769. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  53770. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  53771. || rc==SQLITE_CANTOPEN
  53772. );
  53773. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  53774. ** cache. So call pager_error() on the way out to make any error persistent.
  53775. */
  53776. return pager_error(pPager, rc);
  53777. }
  53778. /*
  53779. ** Return TRUE if the database file is opened read-only. Return FALSE
  53780. ** if the database is (in theory) writable.
  53781. */
  53782. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  53783. return pPager->readOnly;
  53784. }
  53785. #ifdef SQLITE_DEBUG
  53786. /*
  53787. ** Return the sum of the reference counts for all pages held by pPager.
  53788. */
  53789. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  53790. return sqlite3PcacheRefCount(pPager->pPCache);
  53791. }
  53792. #endif
  53793. /*
  53794. ** Return the approximate number of bytes of memory currently
  53795. ** used by the pager and its associated cache.
  53796. */
  53797. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  53798. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  53799. + 5*sizeof(void*);
  53800. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  53801. + sqlite3MallocSize(pPager)
  53802. + pPager->pageSize;
  53803. }
  53804. /*
  53805. ** Return the number of references to the specified page.
  53806. */
  53807. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  53808. return sqlite3PcachePageRefcount(pPage);
  53809. }
  53810. #ifdef SQLITE_TEST
  53811. /*
  53812. ** This routine is used for testing and analysis only.
  53813. */
  53814. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  53815. static int a[11];
  53816. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  53817. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  53818. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  53819. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  53820. a[4] = pPager->eState;
  53821. a[5] = pPager->errCode;
  53822. a[6] = pPager->aStat[PAGER_STAT_HIT];
  53823. a[7] = pPager->aStat[PAGER_STAT_MISS];
  53824. a[8] = 0; /* Used to be pPager->nOvfl */
  53825. a[9] = pPager->nRead;
  53826. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  53827. return a;
  53828. }
  53829. #endif
  53830. /*
  53831. ** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE,
  53832. ** or _WRITE+1. The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation
  53833. ** of SQLITE_DBSTATUS_CACHE_SPILL. The _SPILL case is not contiguous because
  53834. ** it was added later.
  53835. **
  53836. ** Before returning, *pnVal is incremented by the
  53837. ** current cache hit or miss count, according to the value of eStat. If the
  53838. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  53839. ** returning.
  53840. */
  53841. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  53842. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  53843. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  53844. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  53845. || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1
  53846. );
  53847. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  53848. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  53849. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1
  53850. && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 );
  53851. eStat -= SQLITE_DBSTATUS_CACHE_HIT;
  53852. *pnVal += pPager->aStat[eStat];
  53853. if( reset ){
  53854. pPager->aStat[eStat] = 0;
  53855. }
  53856. }
  53857. /*
  53858. ** Return true if this is an in-memory or temp-file backed pager.
  53859. */
  53860. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  53861. return pPager->tempFile;
  53862. }
  53863. /*
  53864. ** Check that there are at least nSavepoint savepoints open. If there are
  53865. ** currently less than nSavepoints open, then open one or more savepoints
  53866. ** to make up the difference. If the number of savepoints is already
  53867. ** equal to nSavepoint, then this function is a no-op.
  53868. **
  53869. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  53870. ** occurs while opening the sub-journal file, then an IO error code is
  53871. ** returned. Otherwise, SQLITE_OK.
  53872. */
  53873. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  53874. int rc = SQLITE_OK; /* Return code */
  53875. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  53876. int ii; /* Iterator variable */
  53877. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  53878. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  53879. assert( assert_pager_state(pPager) );
  53880. assert( nSavepoint>nCurrent && pPager->useJournal );
  53881. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  53882. ** if the allocation fails. Otherwise, zero the new portion in case a
  53883. ** malloc failure occurs while populating it in the for(...) loop below.
  53884. */
  53885. aNew = (PagerSavepoint *)sqlite3Realloc(
  53886. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  53887. );
  53888. if( !aNew ){
  53889. return SQLITE_NOMEM_BKPT;
  53890. }
  53891. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  53892. pPager->aSavepoint = aNew;
  53893. /* Populate the PagerSavepoint structures just allocated. */
  53894. for(ii=nCurrent; ii<nSavepoint; ii++){
  53895. aNew[ii].nOrig = pPager->dbSize;
  53896. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  53897. aNew[ii].iOffset = pPager->journalOff;
  53898. }else{
  53899. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  53900. }
  53901. aNew[ii].iSubRec = pPager->nSubRec;
  53902. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  53903. if( !aNew[ii].pInSavepoint ){
  53904. return SQLITE_NOMEM_BKPT;
  53905. }
  53906. if( pagerUseWal(pPager) ){
  53907. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  53908. }
  53909. pPager->nSavepoint = ii+1;
  53910. }
  53911. assert( pPager->nSavepoint==nSavepoint );
  53912. assertTruncateConstraint(pPager);
  53913. return rc;
  53914. }
  53915. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  53916. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  53917. assert( assert_pager_state(pPager) );
  53918. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  53919. return pagerOpenSavepoint(pPager, nSavepoint);
  53920. }else{
  53921. return SQLITE_OK;
  53922. }
  53923. }
  53924. /*
  53925. ** This function is called to rollback or release (commit) a savepoint.
  53926. ** The savepoint to release or rollback need not be the most recently
  53927. ** created savepoint.
  53928. **
  53929. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  53930. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  53931. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  53932. ** that have occurred since the specified savepoint was created.
  53933. **
  53934. ** The savepoint to rollback or release is identified by parameter
  53935. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  53936. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  53937. ** on the most recently created savepoint. If iSavepoint is greater than
  53938. ** (Pager.nSavepoint-1), then this function is a no-op.
  53939. **
  53940. ** If a negative value is passed to this function, then the current
  53941. ** transaction is rolled back. This is different to calling
  53942. ** sqlite3PagerRollback() because this function does not terminate
  53943. ** the transaction or unlock the database, it just restores the
  53944. ** contents of the database to its original state.
  53945. **
  53946. ** In any case, all savepoints with an index greater than iSavepoint
  53947. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  53948. ** then savepoint iSavepoint is also destroyed.
  53949. **
  53950. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  53951. ** or an IO error code if an IO error occurs while rolling back a
  53952. ** savepoint. If no errors occur, SQLITE_OK is returned.
  53953. */
  53954. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  53955. int rc = pPager->errCode;
  53956. #ifdef SQLITE_ENABLE_ZIPVFS
  53957. if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
  53958. #endif
  53959. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  53960. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  53961. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  53962. int ii; /* Iterator variable */
  53963. int nNew; /* Number of remaining savepoints after this op. */
  53964. /* Figure out how many savepoints will still be active after this
  53965. ** operation. Store this value in nNew. Then free resources associated
  53966. ** with any savepoints that are destroyed by this operation.
  53967. */
  53968. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  53969. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  53970. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  53971. }
  53972. pPager->nSavepoint = nNew;
  53973. /* If this is a release of the outermost savepoint, truncate
  53974. ** the sub-journal to zero bytes in size. */
  53975. if( op==SAVEPOINT_RELEASE ){
  53976. if( nNew==0 && isOpen(pPager->sjfd) ){
  53977. /* Only truncate if it is an in-memory sub-journal. */
  53978. if( sqlite3JournalIsInMemory(pPager->sjfd) ){
  53979. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  53980. assert( rc==SQLITE_OK );
  53981. }
  53982. pPager->nSubRec = 0;
  53983. }
  53984. }
  53985. /* Else this is a rollback operation, playback the specified savepoint.
  53986. ** If this is a temp-file, it is possible that the journal file has
  53987. ** not yet been opened. In this case there have been no changes to
  53988. ** the database file, so the playback operation can be skipped.
  53989. */
  53990. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  53991. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  53992. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  53993. assert(rc!=SQLITE_DONE);
  53994. }
  53995. #ifdef SQLITE_ENABLE_ZIPVFS
  53996. /* If the cache has been modified but the savepoint cannot be rolled
  53997. ** back journal_mode=off, put the pager in the error state. This way,
  53998. ** if the VFS used by this pager includes ZipVFS, the entire transaction
  53999. ** can be rolled back at the ZipVFS level. */
  54000. else if(
  54001. pPager->journalMode==PAGER_JOURNALMODE_OFF
  54002. && pPager->eState>=PAGER_WRITER_CACHEMOD
  54003. ){
  54004. pPager->errCode = SQLITE_ABORT;
  54005. pPager->eState = PAGER_ERROR;
  54006. setGetterMethod(pPager);
  54007. }
  54008. #endif
  54009. }
  54010. return rc;
  54011. }
  54012. /*
  54013. ** Return the full pathname of the database file.
  54014. **
  54015. ** Except, if the pager is in-memory only, then return an empty string if
  54016. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  54017. ** used to report the filename to the user, for compatibility with legacy
  54018. ** behavior. But when the Btree needs to know the filename for matching to
  54019. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  54020. ** participate in shared-cache.
  54021. */
  54022. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  54023. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  54024. }
  54025. /*
  54026. ** Return the VFS structure for the pager.
  54027. */
  54028. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  54029. return pPager->pVfs;
  54030. }
  54031. /*
  54032. ** Return the file handle for the database file associated
  54033. ** with the pager. This might return NULL if the file has
  54034. ** not yet been opened.
  54035. */
  54036. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  54037. return pPager->fd;
  54038. }
  54039. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  54040. /*
  54041. ** Reset the lock timeout for pager.
  54042. */
  54043. SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager){
  54044. int x = 0;
  54045. sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_LOCK_TIMEOUT, &x);
  54046. }
  54047. #endif
  54048. /*
  54049. ** Return the file handle for the journal file (if it exists).
  54050. ** This will be either the rollback journal or the WAL file.
  54051. */
  54052. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
  54053. #if SQLITE_OMIT_WAL
  54054. return pPager->jfd;
  54055. #else
  54056. return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
  54057. #endif
  54058. }
  54059. /*
  54060. ** Return the full pathname of the journal file.
  54061. */
  54062. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  54063. return pPager->zJournal;
  54064. }
  54065. #ifdef SQLITE_HAS_CODEC
  54066. /*
  54067. ** Set or retrieve the codec for this pager
  54068. */
  54069. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  54070. Pager *pPager,
  54071. void *(*xCodec)(void*,void*,Pgno,int),
  54072. void (*xCodecSizeChng)(void*,int,int),
  54073. void (*xCodecFree)(void*),
  54074. void *pCodec
  54075. ){
  54076. if( pPager->xCodecFree ){
  54077. pPager->xCodecFree(pPager->pCodec);
  54078. }else{
  54079. pager_reset(pPager);
  54080. }
  54081. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  54082. pPager->xCodecSizeChng = xCodecSizeChng;
  54083. pPager->xCodecFree = xCodecFree;
  54084. pPager->pCodec = pCodec;
  54085. setGetterMethod(pPager);
  54086. pagerReportSize(pPager);
  54087. }
  54088. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  54089. return pPager->pCodec;
  54090. }
  54091. /*
  54092. ** This function is called by the wal module when writing page content
  54093. ** into the log file.
  54094. **
  54095. ** This function returns a pointer to a buffer containing the encrypted
  54096. ** page content. If a malloc fails, this function may return NULL.
  54097. */
  54098. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  54099. void *aData = 0;
  54100. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  54101. return aData;
  54102. }
  54103. /*
  54104. ** Return the current pager state
  54105. */
  54106. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  54107. return pPager->eState;
  54108. }
  54109. #endif /* SQLITE_HAS_CODEC */
  54110. #ifndef SQLITE_OMIT_AUTOVACUUM
  54111. /*
  54112. ** Move the page pPg to location pgno in the file.
  54113. **
  54114. ** There must be no references to the page previously located at
  54115. ** pgno (which we call pPgOld) though that page is allowed to be
  54116. ** in cache. If the page previously located at pgno is not already
  54117. ** in the rollback journal, it is not put there by by this routine.
  54118. **
  54119. ** References to the page pPg remain valid. Updating any
  54120. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  54121. ** allocated along with the page) is the responsibility of the caller.
  54122. **
  54123. ** A transaction must be active when this routine is called. It used to be
  54124. ** required that a statement transaction was not active, but this restriction
  54125. ** has been removed (CREATE INDEX needs to move a page when a statement
  54126. ** transaction is active).
  54127. **
  54128. ** If the fourth argument, isCommit, is non-zero, then this page is being
  54129. ** moved as part of a database reorganization just before the transaction
  54130. ** is being committed. In this case, it is guaranteed that the database page
  54131. ** pPg refers to will not be written to again within this transaction.
  54132. **
  54133. ** This function may return SQLITE_NOMEM or an IO error code if an error
  54134. ** occurs. Otherwise, it returns SQLITE_OK.
  54135. */
  54136. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  54137. PgHdr *pPgOld; /* The page being overwritten. */
  54138. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  54139. int rc; /* Return code */
  54140. Pgno origPgno; /* The original page number */
  54141. assert( pPg->nRef>0 );
  54142. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  54143. || pPager->eState==PAGER_WRITER_DBMOD
  54144. );
  54145. assert( assert_pager_state(pPager) );
  54146. /* In order to be able to rollback, an in-memory database must journal
  54147. ** the page we are moving from.
  54148. */
  54149. assert( pPager->tempFile || !MEMDB );
  54150. if( pPager->tempFile ){
  54151. rc = sqlite3PagerWrite(pPg);
  54152. if( rc ) return rc;
  54153. }
  54154. /* If the page being moved is dirty and has not been saved by the latest
  54155. ** savepoint, then save the current contents of the page into the
  54156. ** sub-journal now. This is required to handle the following scenario:
  54157. **
  54158. ** BEGIN;
  54159. ** <journal page X, then modify it in memory>
  54160. ** SAVEPOINT one;
  54161. ** <Move page X to location Y>
  54162. ** ROLLBACK TO one;
  54163. **
  54164. ** If page X were not written to the sub-journal here, it would not
  54165. ** be possible to restore its contents when the "ROLLBACK TO one"
  54166. ** statement were is processed.
  54167. **
  54168. ** subjournalPage() may need to allocate space to store pPg->pgno into
  54169. ** one or more savepoint bitvecs. This is the reason this function
  54170. ** may return SQLITE_NOMEM.
  54171. */
  54172. if( (pPg->flags & PGHDR_DIRTY)!=0
  54173. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  54174. ){
  54175. return rc;
  54176. }
  54177. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  54178. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  54179. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  54180. /* If the journal needs to be sync()ed before page pPg->pgno can
  54181. ** be written to, store pPg->pgno in local variable needSyncPgno.
  54182. **
  54183. ** If the isCommit flag is set, there is no need to remember that
  54184. ** the journal needs to be sync()ed before database page pPg->pgno
  54185. ** can be written to. The caller has already promised not to write to it.
  54186. */
  54187. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  54188. needSyncPgno = pPg->pgno;
  54189. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  54190. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  54191. assert( pPg->flags&PGHDR_DIRTY );
  54192. }
  54193. /* If the cache contains a page with page-number pgno, remove it
  54194. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  54195. ** page pgno before the 'move' operation, it needs to be retained
  54196. ** for the page moved there.
  54197. */
  54198. pPg->flags &= ~PGHDR_NEED_SYNC;
  54199. pPgOld = sqlite3PagerLookup(pPager, pgno);
  54200. assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB );
  54201. if( pPgOld ){
  54202. if( pPgOld->nRef>1 ){
  54203. sqlite3PagerUnrefNotNull(pPgOld);
  54204. return SQLITE_CORRUPT_BKPT;
  54205. }
  54206. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  54207. if( pPager->tempFile ){
  54208. /* Do not discard pages from an in-memory database since we might
  54209. ** need to rollback later. Just move the page out of the way. */
  54210. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  54211. }else{
  54212. sqlite3PcacheDrop(pPgOld);
  54213. }
  54214. }
  54215. origPgno = pPg->pgno;
  54216. sqlite3PcacheMove(pPg, pgno);
  54217. sqlite3PcacheMakeDirty(pPg);
  54218. /* For an in-memory database, make sure the original page continues
  54219. ** to exist, in case the transaction needs to roll back. Use pPgOld
  54220. ** as the original page since it has already been allocated.
  54221. */
  54222. if( pPager->tempFile && pPgOld ){
  54223. sqlite3PcacheMove(pPgOld, origPgno);
  54224. sqlite3PagerUnrefNotNull(pPgOld);
  54225. }
  54226. if( needSyncPgno ){
  54227. /* If needSyncPgno is non-zero, then the journal file needs to be
  54228. ** sync()ed before any data is written to database file page needSyncPgno.
  54229. ** Currently, no such page exists in the page-cache and the
  54230. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  54231. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  54232. ** flag.
  54233. **
  54234. ** If the attempt to load the page into the page-cache fails, (due
  54235. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  54236. ** array. Otherwise, if the page is loaded and written again in
  54237. ** this transaction, it may be written to the database file before
  54238. ** it is synced into the journal file. This way, it may end up in
  54239. ** the journal file twice, but that is not a problem.
  54240. */
  54241. PgHdr *pPgHdr;
  54242. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
  54243. if( rc!=SQLITE_OK ){
  54244. if( needSyncPgno<=pPager->dbOrigSize ){
  54245. assert( pPager->pTmpSpace!=0 );
  54246. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  54247. }
  54248. return rc;
  54249. }
  54250. pPgHdr->flags |= PGHDR_NEED_SYNC;
  54251. sqlite3PcacheMakeDirty(pPgHdr);
  54252. sqlite3PagerUnrefNotNull(pPgHdr);
  54253. }
  54254. return SQLITE_OK;
  54255. }
  54256. #endif
  54257. /*
  54258. ** The page handle passed as the first argument refers to a dirty page
  54259. ** with a page number other than iNew. This function changes the page's
  54260. ** page number to iNew and sets the value of the PgHdr.flags field to
  54261. ** the value passed as the third parameter.
  54262. */
  54263. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  54264. assert( pPg->pgno!=iNew );
  54265. pPg->flags = flags;
  54266. sqlite3PcacheMove(pPg, iNew);
  54267. }
  54268. /*
  54269. ** Return a pointer to the data for the specified page.
  54270. */
  54271. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  54272. assert( pPg->nRef>0 || pPg->pPager->memDb );
  54273. return pPg->pData;
  54274. }
  54275. /*
  54276. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  54277. ** allocated along with the specified page.
  54278. */
  54279. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  54280. return pPg->pExtra;
  54281. }
  54282. /*
  54283. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  54284. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  54285. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  54286. ** the locking-mode is set to the value specified.
  54287. **
  54288. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  54289. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  54290. ** locking-mode.
  54291. */
  54292. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  54293. assert( eMode==PAGER_LOCKINGMODE_QUERY
  54294. || eMode==PAGER_LOCKINGMODE_NORMAL
  54295. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  54296. assert( PAGER_LOCKINGMODE_QUERY<0 );
  54297. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  54298. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  54299. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  54300. pPager->exclusiveMode = (u8)eMode;
  54301. }
  54302. return (int)pPager->exclusiveMode;
  54303. }
  54304. /*
  54305. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  54306. **
  54307. ** PAGER_JOURNALMODE_DELETE
  54308. ** PAGER_JOURNALMODE_TRUNCATE
  54309. ** PAGER_JOURNALMODE_PERSIST
  54310. ** PAGER_JOURNALMODE_OFF
  54311. ** PAGER_JOURNALMODE_MEMORY
  54312. ** PAGER_JOURNALMODE_WAL
  54313. **
  54314. ** The journalmode is set to the value specified if the change is allowed.
  54315. ** The change may be disallowed for the following reasons:
  54316. **
  54317. ** * An in-memory database can only have its journal_mode set to _OFF
  54318. ** or _MEMORY.
  54319. **
  54320. ** * Temporary databases cannot have _WAL journalmode.
  54321. **
  54322. ** The returned indicate the current (possibly updated) journal-mode.
  54323. */
  54324. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  54325. u8 eOld = pPager->journalMode; /* Prior journalmode */
  54326. /* The eMode parameter is always valid */
  54327. assert( eMode==PAGER_JOURNALMODE_DELETE
  54328. || eMode==PAGER_JOURNALMODE_TRUNCATE
  54329. || eMode==PAGER_JOURNALMODE_PERSIST
  54330. || eMode==PAGER_JOURNALMODE_OFF
  54331. || eMode==PAGER_JOURNALMODE_WAL
  54332. || eMode==PAGER_JOURNALMODE_MEMORY );
  54333. /* This routine is only called from the OP_JournalMode opcode, and
  54334. ** the logic there will never allow a temporary file to be changed
  54335. ** to WAL mode.
  54336. */
  54337. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  54338. /* Do allow the journalmode of an in-memory database to be set to
  54339. ** anything other than MEMORY or OFF
  54340. */
  54341. if( MEMDB ){
  54342. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  54343. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  54344. eMode = eOld;
  54345. }
  54346. }
  54347. if( eMode!=eOld ){
  54348. /* Change the journal mode. */
  54349. assert( pPager->eState!=PAGER_ERROR );
  54350. pPager->journalMode = (u8)eMode;
  54351. /* When transistioning from TRUNCATE or PERSIST to any other journal
  54352. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  54353. ** delete the journal file.
  54354. */
  54355. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  54356. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  54357. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  54358. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  54359. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  54360. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  54361. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  54362. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  54363. /* In this case we would like to delete the journal file. If it is
  54364. ** not possible, then that is not a problem. Deleting the journal file
  54365. ** here is an optimization only.
  54366. **
  54367. ** Before deleting the journal file, obtain a RESERVED lock on the
  54368. ** database file. This ensures that the journal file is not deleted
  54369. ** while it is in use by some other client.
  54370. */
  54371. sqlite3OsClose(pPager->jfd);
  54372. if( pPager->eLock>=RESERVED_LOCK ){
  54373. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  54374. }else{
  54375. int rc = SQLITE_OK;
  54376. int state = pPager->eState;
  54377. assert( state==PAGER_OPEN || state==PAGER_READER );
  54378. if( state==PAGER_OPEN ){
  54379. rc = sqlite3PagerSharedLock(pPager);
  54380. }
  54381. if( pPager->eState==PAGER_READER ){
  54382. assert( rc==SQLITE_OK );
  54383. rc = pagerLockDb(pPager, RESERVED_LOCK);
  54384. }
  54385. if( rc==SQLITE_OK ){
  54386. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  54387. }
  54388. if( rc==SQLITE_OK && state==PAGER_READER ){
  54389. pagerUnlockDb(pPager, SHARED_LOCK);
  54390. }else if( state==PAGER_OPEN ){
  54391. pager_unlock(pPager);
  54392. }
  54393. assert( state==pPager->eState );
  54394. }
  54395. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  54396. sqlite3OsClose(pPager->jfd);
  54397. }
  54398. }
  54399. /* Return the new journal mode */
  54400. return (int)pPager->journalMode;
  54401. }
  54402. /*
  54403. ** Return the current journal mode.
  54404. */
  54405. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  54406. return (int)pPager->journalMode;
  54407. }
  54408. /*
  54409. ** Return TRUE if the pager is in a state where it is OK to change the
  54410. ** journalmode. Journalmode changes can only happen when the database
  54411. ** is unmodified.
  54412. */
  54413. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  54414. assert( assert_pager_state(pPager) );
  54415. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  54416. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  54417. return 1;
  54418. }
  54419. /*
  54420. ** Get/set the size-limit used for persistent journal files.
  54421. **
  54422. ** Setting the size limit to -1 means no limit is enforced.
  54423. ** An attempt to set a limit smaller than -1 is a no-op.
  54424. */
  54425. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  54426. if( iLimit>=-1 ){
  54427. pPager->journalSizeLimit = iLimit;
  54428. sqlite3WalLimit(pPager->pWal, iLimit);
  54429. }
  54430. return pPager->journalSizeLimit;
  54431. }
  54432. /*
  54433. ** Return a pointer to the pPager->pBackup variable. The backup module
  54434. ** in backup.c maintains the content of this variable. This module
  54435. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  54436. ** sqlite3BackupUpdate() only.
  54437. */
  54438. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  54439. return &pPager->pBackup;
  54440. }
  54441. #ifndef SQLITE_OMIT_VACUUM
  54442. /*
  54443. ** Unless this is an in-memory or temporary database, clear the pager cache.
  54444. */
  54445. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  54446. assert( MEMDB==0 || pPager->tempFile );
  54447. if( pPager->tempFile==0 ) pager_reset(pPager);
  54448. }
  54449. #endif
  54450. #ifndef SQLITE_OMIT_WAL
  54451. /*
  54452. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  54453. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  54454. ** or wal_blocking_checkpoint() API functions.
  54455. **
  54456. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  54457. */
  54458. SQLITE_PRIVATE int sqlite3PagerCheckpoint(
  54459. Pager *pPager, /* Checkpoint on this pager */
  54460. sqlite3 *db, /* Db handle used to check for interrupts */
  54461. int eMode, /* Type of checkpoint */
  54462. int *pnLog, /* OUT: Final number of frames in log */
  54463. int *pnCkpt /* OUT: Final number of checkpointed frames */
  54464. ){
  54465. int rc = SQLITE_OK;
  54466. if( pPager->pWal ){
  54467. rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
  54468. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  54469. pPager->pBusyHandlerArg,
  54470. pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  54471. pnLog, pnCkpt
  54472. );
  54473. sqlite3PagerResetLockTimeout(pPager);
  54474. }
  54475. return rc;
  54476. }
  54477. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  54478. return sqlite3WalCallback(pPager->pWal);
  54479. }
  54480. /*
  54481. ** Return true if the underlying VFS for the given pager supports the
  54482. ** primitives necessary for write-ahead logging.
  54483. */
  54484. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  54485. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  54486. if( pPager->noLock ) return 0;
  54487. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  54488. }
  54489. /*
  54490. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  54491. ** is obtained instead, immediately release it.
  54492. */
  54493. static int pagerExclusiveLock(Pager *pPager){
  54494. int rc; /* Return code */
  54495. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  54496. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  54497. if( rc!=SQLITE_OK ){
  54498. /* If the attempt to grab the exclusive lock failed, release the
  54499. ** pending lock that may have been obtained instead. */
  54500. pagerUnlockDb(pPager, SHARED_LOCK);
  54501. }
  54502. return rc;
  54503. }
  54504. /*
  54505. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  54506. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  54507. ** lock on the database file and use heap-memory to store the wal-index
  54508. ** in. Otherwise, use the normal shared-memory.
  54509. */
  54510. static int pagerOpenWal(Pager *pPager){
  54511. int rc = SQLITE_OK;
  54512. assert( pPager->pWal==0 && pPager->tempFile==0 );
  54513. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  54514. /* If the pager is already in exclusive-mode, the WAL module will use
  54515. ** heap-memory for the wal-index instead of the VFS shared-memory
  54516. ** implementation. Take the exclusive lock now, before opening the WAL
  54517. ** file, to make sure this is safe.
  54518. */
  54519. if( pPager->exclusiveMode ){
  54520. rc = pagerExclusiveLock(pPager);
  54521. }
  54522. /* Open the connection to the log file. If this operation fails,
  54523. ** (e.g. due to malloc() failure), return an error code.
  54524. */
  54525. if( rc==SQLITE_OK ){
  54526. rc = sqlite3WalOpen(pPager->pVfs,
  54527. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  54528. pPager->journalSizeLimit, &pPager->pWal
  54529. );
  54530. }
  54531. pagerFixMaplimit(pPager);
  54532. return rc;
  54533. }
  54534. /*
  54535. ** The caller must be holding a SHARED lock on the database file to call
  54536. ** this function.
  54537. **
  54538. ** If the pager passed as the first argument is open on a real database
  54539. ** file (not a temp file or an in-memory database), and the WAL file
  54540. ** is not already open, make an attempt to open it now. If successful,
  54541. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  54542. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  54543. ** not modified in either case.
  54544. **
  54545. ** If the pager is open on a temp-file (or in-memory database), or if
  54546. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  54547. ** without doing anything.
  54548. */
  54549. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  54550. Pager *pPager, /* Pager object */
  54551. int *pbOpen /* OUT: Set to true if call is a no-op */
  54552. ){
  54553. int rc = SQLITE_OK; /* Return code */
  54554. assert( assert_pager_state(pPager) );
  54555. assert( pPager->eState==PAGER_OPEN || pbOpen );
  54556. assert( pPager->eState==PAGER_READER || !pbOpen );
  54557. assert( pbOpen==0 || *pbOpen==0 );
  54558. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  54559. if( !pPager->tempFile && !pPager->pWal ){
  54560. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  54561. /* Close any rollback journal previously open */
  54562. sqlite3OsClose(pPager->jfd);
  54563. rc = pagerOpenWal(pPager);
  54564. if( rc==SQLITE_OK ){
  54565. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  54566. pPager->eState = PAGER_OPEN;
  54567. }
  54568. }else{
  54569. *pbOpen = 1;
  54570. }
  54571. return rc;
  54572. }
  54573. /*
  54574. ** This function is called to close the connection to the log file prior
  54575. ** to switching from WAL to rollback mode.
  54576. **
  54577. ** Before closing the log file, this function attempts to take an
  54578. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  54579. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  54580. ** If successful, the EXCLUSIVE lock is not released before returning.
  54581. */
  54582. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
  54583. int rc = SQLITE_OK;
  54584. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  54585. /* If the log file is not already open, but does exist in the file-system,
  54586. ** it may need to be checkpointed before the connection can switch to
  54587. ** rollback mode. Open it now so this can happen.
  54588. */
  54589. if( !pPager->pWal ){
  54590. int logexists = 0;
  54591. rc = pagerLockDb(pPager, SHARED_LOCK);
  54592. if( rc==SQLITE_OK ){
  54593. rc = sqlite3OsAccess(
  54594. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  54595. );
  54596. }
  54597. if( rc==SQLITE_OK && logexists ){
  54598. rc = pagerOpenWal(pPager);
  54599. }
  54600. }
  54601. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  54602. ** the database file, the log and log-summary files will be deleted.
  54603. */
  54604. if( rc==SQLITE_OK && pPager->pWal ){
  54605. rc = pagerExclusiveLock(pPager);
  54606. if( rc==SQLITE_OK ){
  54607. rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
  54608. pPager->pageSize, (u8*)pPager->pTmpSpace);
  54609. pPager->pWal = 0;
  54610. pagerFixMaplimit(pPager);
  54611. if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  54612. }
  54613. }
  54614. return rc;
  54615. }
  54616. #ifdef SQLITE_ENABLE_SNAPSHOT
  54617. /*
  54618. ** If this is a WAL database, obtain a snapshot handle for the snapshot
  54619. ** currently open. Otherwise, return an error.
  54620. */
  54621. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
  54622. int rc = SQLITE_ERROR;
  54623. if( pPager->pWal ){
  54624. rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
  54625. }
  54626. return rc;
  54627. }
  54628. /*
  54629. ** If this is a WAL database, store a pointer to pSnapshot. Next time a
  54630. ** read transaction is opened, attempt to read from the snapshot it
  54631. ** identifies. If this is not a WAL database, return an error.
  54632. */
  54633. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
  54634. int rc = SQLITE_OK;
  54635. if( pPager->pWal ){
  54636. sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
  54637. }else{
  54638. rc = SQLITE_ERROR;
  54639. }
  54640. return rc;
  54641. }
  54642. /*
  54643. ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
  54644. ** is not a WAL database, return an error.
  54645. */
  54646. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
  54647. int rc;
  54648. if( pPager->pWal ){
  54649. rc = sqlite3WalSnapshotRecover(pPager->pWal);
  54650. }else{
  54651. rc = SQLITE_ERROR;
  54652. }
  54653. return rc;
  54654. }
  54655. /*
  54656. ** The caller currently has a read transaction open on the database.
  54657. ** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise,
  54658. ** this function takes a SHARED lock on the CHECKPOINTER slot and then
  54659. ** checks if the snapshot passed as the second argument is still
  54660. ** available. If so, SQLITE_OK is returned.
  54661. **
  54662. ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
  54663. ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
  54664. ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
  54665. ** lock is released before returning.
  54666. */
  54667. SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot){
  54668. int rc;
  54669. if( pPager->pWal ){
  54670. rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot);
  54671. }else{
  54672. rc = SQLITE_ERROR;
  54673. }
  54674. return rc;
  54675. }
  54676. /*
  54677. ** Release a lock obtained by an earlier successful call to
  54678. ** sqlite3PagerSnapshotCheck().
  54679. */
  54680. SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager){
  54681. assert( pPager->pWal );
  54682. sqlite3WalSnapshotUnlock(pPager->pWal);
  54683. }
  54684. #endif /* SQLITE_ENABLE_SNAPSHOT */
  54685. #endif /* !SQLITE_OMIT_WAL */
  54686. #ifdef SQLITE_ENABLE_ZIPVFS
  54687. /*
  54688. ** A read-lock must be held on the pager when this function is called. If
  54689. ** the pager is in WAL mode and the WAL file currently contains one or more
  54690. ** frames, return the size in bytes of the page images stored within the
  54691. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  54692. ** is empty, return 0.
  54693. */
  54694. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  54695. assert( pPager->eState>=PAGER_READER );
  54696. return sqlite3WalFramesize(pPager->pWal);
  54697. }
  54698. #endif
  54699. #endif /* SQLITE_OMIT_DISKIO */
  54700. /************** End of pager.c ***********************************************/
  54701. /************** Begin file wal.c *********************************************/
  54702. /*
  54703. ** 2010 February 1
  54704. **
  54705. ** The author disclaims copyright to this source code. In place of
  54706. ** a legal notice, here is a blessing:
  54707. **
  54708. ** May you do good and not evil.
  54709. ** May you find forgiveness for yourself and forgive others.
  54710. ** May you share freely, never taking more than you give.
  54711. **
  54712. *************************************************************************
  54713. **
  54714. ** This file contains the implementation of a write-ahead log (WAL) used in
  54715. ** "journal_mode=WAL" mode.
  54716. **
  54717. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  54718. **
  54719. ** A WAL file consists of a header followed by zero or more "frames".
  54720. ** Each frame records the revised content of a single page from the
  54721. ** database file. All changes to the database are recorded by writing
  54722. ** frames into the WAL. Transactions commit when a frame is written that
  54723. ** contains a commit marker. A single WAL can and usually does record
  54724. ** multiple transactions. Periodically, the content of the WAL is
  54725. ** transferred back into the database file in an operation called a
  54726. ** "checkpoint".
  54727. **
  54728. ** A single WAL file can be used multiple times. In other words, the
  54729. ** WAL can fill up with frames and then be checkpointed and then new
  54730. ** frames can overwrite the old ones. A WAL always grows from beginning
  54731. ** toward the end. Checksums and counters attached to each frame are
  54732. ** used to determine which frames within the WAL are valid and which
  54733. ** are leftovers from prior checkpoints.
  54734. **
  54735. ** The WAL header is 32 bytes in size and consists of the following eight
  54736. ** big-endian 32-bit unsigned integer values:
  54737. **
  54738. ** 0: Magic number. 0x377f0682 or 0x377f0683
  54739. ** 4: File format version. Currently 3007000
  54740. ** 8: Database page size. Example: 1024
  54741. ** 12: Checkpoint sequence number
  54742. ** 16: Salt-1, random integer incremented with each checkpoint
  54743. ** 20: Salt-2, a different random integer changing with each ckpt
  54744. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  54745. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  54746. **
  54747. ** Immediately following the wal-header are zero or more frames. Each
  54748. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  54749. ** of page data. The frame-header is six big-endian 32-bit unsigned
  54750. ** integer values, as follows:
  54751. **
  54752. ** 0: Page number.
  54753. ** 4: For commit records, the size of the database image in pages
  54754. ** after the commit. For all other records, zero.
  54755. ** 8: Salt-1 (copied from the header)
  54756. ** 12: Salt-2 (copied from the header)
  54757. ** 16: Checksum-1.
  54758. ** 20: Checksum-2.
  54759. **
  54760. ** A frame is considered valid if and only if the following conditions are
  54761. ** true:
  54762. **
  54763. ** (1) The salt-1 and salt-2 values in the frame-header match
  54764. ** salt values in the wal-header
  54765. **
  54766. ** (2) The checksum values in the final 8 bytes of the frame-header
  54767. ** exactly match the checksum computed consecutively on the
  54768. ** WAL header and the first 8 bytes and the content of all frames
  54769. ** up to and including the current frame.
  54770. **
  54771. ** The checksum is computed using 32-bit big-endian integers if the
  54772. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  54773. ** is computed using little-endian if the magic number is 0x377f0682.
  54774. ** The checksum values are always stored in the frame header in a
  54775. ** big-endian format regardless of which byte order is used to compute
  54776. ** the checksum. The checksum is computed by interpreting the input as
  54777. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  54778. ** algorithm used for the checksum is as follows:
  54779. **
  54780. ** for i from 0 to n-1 step 2:
  54781. ** s0 += x[i] + s1;
  54782. ** s1 += x[i+1] + s0;
  54783. ** endfor
  54784. **
  54785. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  54786. ** in reverse order (the largest fibonacci weight occurs on the first element
  54787. ** of the sequence being summed.) The s1 value spans all 32-bit
  54788. ** terms of the sequence whereas s0 omits the final term.
  54789. **
  54790. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  54791. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  54792. ** The VFS.xSync operations serve as write barriers - all writes launched
  54793. ** before the xSync must complete before any write that launches after the
  54794. ** xSync begins.
  54795. **
  54796. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  54797. ** value is randomized. This prevents old and new frames in the WAL from
  54798. ** being considered valid at the same time and being checkpointing together
  54799. ** following a crash.
  54800. **
  54801. ** READER ALGORITHM
  54802. **
  54803. ** To read a page from the database (call it page number P), a reader
  54804. ** first checks the WAL to see if it contains page P. If so, then the
  54805. ** last valid instance of page P that is a followed by a commit frame
  54806. ** or is a commit frame itself becomes the value read. If the WAL
  54807. ** contains no copies of page P that are valid and which are a commit
  54808. ** frame or are followed by a commit frame, then page P is read from
  54809. ** the database file.
  54810. **
  54811. ** To start a read transaction, the reader records the index of the last
  54812. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  54813. ** for all subsequent read operations. New transactions can be appended
  54814. ** to the WAL, but as long as the reader uses its original mxFrame value
  54815. ** and ignores the newly appended content, it will see a consistent snapshot
  54816. ** of the database from a single point in time. This technique allows
  54817. ** multiple concurrent readers to view different versions of the database
  54818. ** content simultaneously.
  54819. **
  54820. ** The reader algorithm in the previous paragraphs works correctly, but
  54821. ** because frames for page P can appear anywhere within the WAL, the
  54822. ** reader has to scan the entire WAL looking for page P frames. If the
  54823. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  54824. ** and read performance suffers. To overcome this problem, a separate
  54825. ** data structure called the wal-index is maintained to expedite the
  54826. ** search for frames of a particular page.
  54827. **
  54828. ** WAL-INDEX FORMAT
  54829. **
  54830. ** Conceptually, the wal-index is shared memory, though VFS implementations
  54831. ** might choose to implement the wal-index using a mmapped file. Because
  54832. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  54833. ** on a network filesystem. All users of the database must be able to
  54834. ** share memory.
  54835. **
  54836. ** In the default unix and windows implementation, the wal-index is a mmapped
  54837. ** file whose name is the database name with a "-shm" suffix added. For that
  54838. ** reason, the wal-index is sometimes called the "shm" file.
  54839. **
  54840. ** The wal-index is transient. After a crash, the wal-index can (and should
  54841. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  54842. ** to either truncate or zero the header of the wal-index when the last
  54843. ** connection to it closes. Because the wal-index is transient, it can
  54844. ** use an architecture-specific format; it does not have to be cross-platform.
  54845. ** Hence, unlike the database and WAL file formats which store all values
  54846. ** as big endian, the wal-index can store multi-byte values in the native
  54847. ** byte order of the host computer.
  54848. **
  54849. ** The purpose of the wal-index is to answer this question quickly: Given
  54850. ** a page number P and a maximum frame index M, return the index of the
  54851. ** last frame in the wal before frame M for page P in the WAL, or return
  54852. ** NULL if there are no frames for page P in the WAL prior to M.
  54853. **
  54854. ** The wal-index consists of a header region, followed by an one or
  54855. ** more index blocks.
  54856. **
  54857. ** The wal-index header contains the total number of frames within the WAL
  54858. ** in the mxFrame field.
  54859. **
  54860. ** Each index block except for the first contains information on
  54861. ** HASHTABLE_NPAGE frames. The first index block contains information on
  54862. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  54863. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  54864. ** first index block are the same size as all other index blocks in the
  54865. ** wal-index.
  54866. **
  54867. ** Each index block contains two sections, a page-mapping that contains the
  54868. ** database page number associated with each wal frame, and a hash-table
  54869. ** that allows readers to query an index block for a specific page number.
  54870. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  54871. ** for the first index block) 32-bit page numbers. The first entry in the
  54872. ** first index-block contains the database page number corresponding to the
  54873. ** first frame in the WAL file. The first entry in the second index block
  54874. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  54875. ** the log, and so on.
  54876. **
  54877. ** The last index block in a wal-index usually contains less than the full
  54878. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  54879. ** depending on the contents of the WAL file. This does not change the
  54880. ** allocated size of the page-mapping array - the page-mapping array merely
  54881. ** contains unused entries.
  54882. **
  54883. ** Even without using the hash table, the last frame for page P
  54884. ** can be found by scanning the page-mapping sections of each index block
  54885. ** starting with the last index block and moving toward the first, and
  54886. ** within each index block, starting at the end and moving toward the
  54887. ** beginning. The first entry that equals P corresponds to the frame
  54888. ** holding the content for that page.
  54889. **
  54890. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  54891. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  54892. ** hash table for each page number in the mapping section, so the hash
  54893. ** table is never more than half full. The expected number of collisions
  54894. ** prior to finding a match is 1. Each entry of the hash table is an
  54895. ** 1-based index of an entry in the mapping section of the same
  54896. ** index block. Let K be the 1-based index of the largest entry in
  54897. ** the mapping section. (For index blocks other than the last, K will
  54898. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  54899. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  54900. ** contain a value of 0.
  54901. **
  54902. ** To look for page P in the hash table, first compute a hash iKey on
  54903. ** P as follows:
  54904. **
  54905. ** iKey = (P * 383) % HASHTABLE_NSLOT
  54906. **
  54907. ** Then start scanning entries of the hash table, starting with iKey
  54908. ** (wrapping around to the beginning when the end of the hash table is
  54909. ** reached) until an unused hash slot is found. Let the first unused slot
  54910. ** be at index iUnused. (iUnused might be less than iKey if there was
  54911. ** wrap-around.) Because the hash table is never more than half full,
  54912. ** the search is guaranteed to eventually hit an unused entry. Let
  54913. ** iMax be the value between iKey and iUnused, closest to iUnused,
  54914. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  54915. ** no hash slot such that aHash[i]==p) then page P is not in the
  54916. ** current index block. Otherwise the iMax-th mapping entry of the
  54917. ** current index block corresponds to the last entry that references
  54918. ** page P.
  54919. **
  54920. ** A hash search begins with the last index block and moves toward the
  54921. ** first index block, looking for entries corresponding to page P. On
  54922. ** average, only two or three slots in each index block need to be
  54923. ** examined in order to either find the last entry for page P, or to
  54924. ** establish that no such entry exists in the block. Each index block
  54925. ** holds over 4000 entries. So two or three index blocks are sufficient
  54926. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  54927. ** comparisons (on average) suffice to either locate a frame in the
  54928. ** WAL or to establish that the frame does not exist in the WAL. This
  54929. ** is much faster than scanning the entire 10MB WAL.
  54930. **
  54931. ** Note that entries are added in order of increasing K. Hence, one
  54932. ** reader might be using some value K0 and a second reader that started
  54933. ** at a later time (after additional transactions were added to the WAL
  54934. ** and to the wal-index) might be using a different value K1, where K1>K0.
  54935. ** Both readers can use the same hash table and mapping section to get
  54936. ** the correct result. There may be entries in the hash table with
  54937. ** K>K0 but to the first reader, those entries will appear to be unused
  54938. ** slots in the hash table and so the first reader will get an answer as
  54939. ** if no values greater than K0 had ever been inserted into the hash table
  54940. ** in the first place - which is what reader one wants. Meanwhile, the
  54941. ** second reader using K1 will see additional values that were inserted
  54942. ** later, which is exactly what reader two wants.
  54943. **
  54944. ** When a rollback occurs, the value of K is decreased. Hash table entries
  54945. ** that correspond to frames greater than the new K value are removed
  54946. ** from the hash table at this point.
  54947. */
  54948. #ifndef SQLITE_OMIT_WAL
  54949. /* #include "wal.h" */
  54950. /*
  54951. ** Trace output macros
  54952. */
  54953. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  54954. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  54955. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  54956. #else
  54957. # define WALTRACE(X)
  54958. #endif
  54959. /*
  54960. ** WAL mode depends on atomic aligned 32-bit loads and stores in a few
  54961. ** places. The following macros try to make this explicit.
  54962. */
  54963. #if GCC_VESRION>=5004000
  54964. # define AtomicLoad(PTR) __atomic_load_n((PTR),__ATOMIC_RELAXED)
  54965. # define AtomicStore(PTR,VAL) __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
  54966. #else
  54967. # define AtomicLoad(PTR) (*(PTR))
  54968. # define AtomicStore(PTR,VAL) (*(PTR) = (VAL))
  54969. #endif
  54970. /*
  54971. ** The maximum (and only) versions of the wal and wal-index formats
  54972. ** that may be interpreted by this version of SQLite.
  54973. **
  54974. ** If a client begins recovering a WAL file and finds that (a) the checksum
  54975. ** values in the wal-header are correct and (b) the version field is not
  54976. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  54977. **
  54978. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  54979. ** checksum test is successful) and finds that the version field is not
  54980. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  54981. ** returns SQLITE_CANTOPEN.
  54982. */
  54983. #define WAL_MAX_VERSION 3007000
  54984. #define WALINDEX_MAX_VERSION 3007000
  54985. /*
  54986. ** Index numbers for various locking bytes. WAL_NREADER is the number
  54987. ** of available reader locks and should be at least 3. The default
  54988. ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
  54989. **
  54990. ** Technically, the various VFSes are free to implement these locks however
  54991. ** they see fit. However, compatibility is encouraged so that VFSes can
  54992. ** interoperate. The standard implemention used on both unix and windows
  54993. ** is for the index number to indicate a byte offset into the
  54994. ** WalCkptInfo.aLock[] array in the wal-index header. In other words, all
  54995. ** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which
  54996. ** should be 120) is the location in the shm file for the first locking
  54997. ** byte.
  54998. */
  54999. #define WAL_WRITE_LOCK 0
  55000. #define WAL_ALL_BUT_WRITE 1
  55001. #define WAL_CKPT_LOCK 1
  55002. #define WAL_RECOVER_LOCK 2
  55003. #define WAL_READ_LOCK(I) (3+(I))
  55004. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  55005. /* Object declarations */
  55006. typedef struct WalIndexHdr WalIndexHdr;
  55007. typedef struct WalIterator WalIterator;
  55008. typedef struct WalCkptInfo WalCkptInfo;
  55009. /*
  55010. ** The following object holds a copy of the wal-index header content.
  55011. **
  55012. ** The actual header in the wal-index consists of two copies of this
  55013. ** object followed by one instance of the WalCkptInfo object.
  55014. ** For all versions of SQLite through 3.10.0 and probably beyond,
  55015. ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
  55016. ** the total header size is 136 bytes.
  55017. **
  55018. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  55019. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  55020. ** added in 3.7.1 when support for 64K pages was added.
  55021. */
  55022. struct WalIndexHdr {
  55023. u32 iVersion; /* Wal-index version */
  55024. u32 unused; /* Unused (padding) field */
  55025. u32 iChange; /* Counter incremented each transaction */
  55026. u8 isInit; /* 1 when initialized */
  55027. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  55028. u16 szPage; /* Database page size in bytes. 1==64K */
  55029. u32 mxFrame; /* Index of last valid frame in the WAL */
  55030. u32 nPage; /* Size of database in pages */
  55031. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  55032. u32 aSalt[2]; /* Two salt values copied from WAL header */
  55033. u32 aCksum[2]; /* Checksum over all prior fields */
  55034. };
  55035. /*
  55036. ** A copy of the following object occurs in the wal-index immediately
  55037. ** following the second copy of the WalIndexHdr. This object stores
  55038. ** information used by checkpoint.
  55039. **
  55040. ** nBackfill is the number of frames in the WAL that have been written
  55041. ** back into the database. (We call the act of moving content from WAL to
  55042. ** database "backfilling".) The nBackfill number is never greater than
  55043. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  55044. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  55045. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  55046. ** mxFrame back to zero when the WAL is reset.
  55047. **
  55048. ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
  55049. ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
  55050. ** the nBackfillAttempted is set before any backfilling is done and the
  55051. ** nBackfill is only set after all backfilling completes. So if a checkpoint
  55052. ** crashes, nBackfillAttempted might be larger than nBackfill. The
  55053. ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
  55054. **
  55055. ** The aLock[] field is a set of bytes used for locking. These bytes should
  55056. ** never be read or written.
  55057. **
  55058. ** There is one entry in aReadMark[] for each reader lock. If a reader
  55059. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  55060. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  55061. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  55062. ** a special case; its value is never used and it exists as a place-holder
  55063. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  55064. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  55065. ** directly from the database.
  55066. **
  55067. ** The value of aReadMark[K] may only be changed by a thread that
  55068. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  55069. ** aReadMark[K] cannot changed while there is a reader is using that mark
  55070. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  55071. **
  55072. ** The checkpointer may only transfer frames from WAL to database where
  55073. ** the frame numbers are less than or equal to every aReadMark[] that is
  55074. ** in use (that is, every aReadMark[j] for which there is a corresponding
  55075. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  55076. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  55077. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  55078. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  55079. ** in the WAL has been backfilled into the database) then new readers
  55080. ** will choose aReadMark[0] which has value 0 and hence such reader will
  55081. ** get all their all content directly from the database file and ignore
  55082. ** the WAL.
  55083. **
  55084. ** Writers normally append new frames to the end of the WAL. However,
  55085. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  55086. ** written back into the database) and if no readers are using the WAL
  55087. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  55088. ** the writer will first "reset" the WAL back to the beginning and start
  55089. ** writing new content beginning at frame 1.
  55090. **
  55091. ** We assume that 32-bit loads are atomic and so no locks are needed in
  55092. ** order to read from any aReadMark[] entries.
  55093. */
  55094. struct WalCkptInfo {
  55095. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  55096. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  55097. u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
  55098. u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
  55099. u32 notUsed0; /* Available for future enhancements */
  55100. };
  55101. #define READMARK_NOT_USED 0xffffffff
  55102. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  55103. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  55104. ** only support mandatory file-locks, we do not read or write data
  55105. ** from the region of the file on which locks are applied.
  55106. */
  55107. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
  55108. #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
  55109. /* Size of header before each frame in wal */
  55110. #define WAL_FRAME_HDRSIZE 24
  55111. /* Size of write ahead log header, including checksum. */
  55112. #define WAL_HDRSIZE 32
  55113. /* WAL magic value. Either this value, or the same value with the least
  55114. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  55115. ** big-endian format in the first 4 bytes of a WAL file.
  55116. **
  55117. ** If the LSB is set, then the checksums for each frame within the WAL
  55118. ** file are calculated by treating all data as an array of 32-bit
  55119. ** big-endian words. Otherwise, they are calculated by interpreting
  55120. ** all data as 32-bit little-endian words.
  55121. */
  55122. #define WAL_MAGIC 0x377f0682
  55123. /*
  55124. ** Return the offset of frame iFrame in the write-ahead log file,
  55125. ** assuming a database page size of szPage bytes. The offset returned
  55126. ** is to the start of the write-ahead log frame-header.
  55127. */
  55128. #define walFrameOffset(iFrame, szPage) ( \
  55129. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  55130. )
  55131. /*
  55132. ** An open write-ahead log file is represented by an instance of the
  55133. ** following object.
  55134. */
  55135. struct Wal {
  55136. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  55137. sqlite3_file *pDbFd; /* File handle for the database file */
  55138. sqlite3_file *pWalFd; /* File handle for WAL file */
  55139. u32 iCallback; /* Value to pass to log callback (or 0) */
  55140. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  55141. int nWiData; /* Size of array apWiData */
  55142. int szFirstBlock; /* Size of first block written to WAL file */
  55143. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  55144. u32 szPage; /* Database page size */
  55145. i16 readLock; /* Which read lock is being held. -1 for none */
  55146. u8 syncFlags; /* Flags to use to sync header writes */
  55147. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  55148. u8 writeLock; /* True if in a write transaction */
  55149. u8 ckptLock; /* True if holding a checkpoint lock */
  55150. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  55151. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  55152. u8 syncHeader; /* Fsync the WAL header if true */
  55153. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  55154. u8 bShmUnreliable; /* SHM content is read-only and unreliable */
  55155. WalIndexHdr hdr; /* Wal-index header for current transaction */
  55156. u32 minFrame; /* Ignore wal frames before this one */
  55157. u32 iReCksum; /* On commit, recalculate checksums from here */
  55158. const char *zWalName; /* Name of WAL file */
  55159. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  55160. #ifdef SQLITE_DEBUG
  55161. u8 lockError; /* True if a locking error has occurred */
  55162. #endif
  55163. #ifdef SQLITE_ENABLE_SNAPSHOT
  55164. WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
  55165. #endif
  55166. };
  55167. /*
  55168. ** Candidate values for Wal.exclusiveMode.
  55169. */
  55170. #define WAL_NORMAL_MODE 0
  55171. #define WAL_EXCLUSIVE_MODE 1
  55172. #define WAL_HEAPMEMORY_MODE 2
  55173. /*
  55174. ** Possible values for WAL.readOnly
  55175. */
  55176. #define WAL_RDWR 0 /* Normal read/write connection */
  55177. #define WAL_RDONLY 1 /* The WAL file is readonly */
  55178. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  55179. /*
  55180. ** Each page of the wal-index mapping contains a hash-table made up of
  55181. ** an array of HASHTABLE_NSLOT elements of the following type.
  55182. */
  55183. typedef u16 ht_slot;
  55184. /*
  55185. ** This structure is used to implement an iterator that loops through
  55186. ** all frames in the WAL in database page order. Where two or more frames
  55187. ** correspond to the same database page, the iterator visits only the
  55188. ** frame most recently written to the WAL (in other words, the frame with
  55189. ** the largest index).
  55190. **
  55191. ** The internals of this structure are only accessed by:
  55192. **
  55193. ** walIteratorInit() - Create a new iterator,
  55194. ** walIteratorNext() - Step an iterator,
  55195. ** walIteratorFree() - Free an iterator.
  55196. **
  55197. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  55198. */
  55199. struct WalIterator {
  55200. int iPrior; /* Last result returned from the iterator */
  55201. int nSegment; /* Number of entries in aSegment[] */
  55202. struct WalSegment {
  55203. int iNext; /* Next slot in aIndex[] not yet returned */
  55204. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  55205. u32 *aPgno; /* Array of page numbers. */
  55206. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  55207. int iZero; /* Frame number associated with aPgno[0] */
  55208. } aSegment[1]; /* One for every 32KB page in the wal-index */
  55209. };
  55210. /*
  55211. ** Define the parameters of the hash tables in the wal-index file. There
  55212. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  55213. ** wal-index.
  55214. **
  55215. ** Changing any of these constants will alter the wal-index format and
  55216. ** create incompatibilities.
  55217. */
  55218. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  55219. #define HASHTABLE_HASH_1 383 /* Should be prime */
  55220. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  55221. /*
  55222. ** The block of page numbers associated with the first hash-table in a
  55223. ** wal-index is smaller than usual. This is so that there is a complete
  55224. ** hash-table on each aligned 32KB page of the wal-index.
  55225. */
  55226. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  55227. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  55228. #define WALINDEX_PGSZ ( \
  55229. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  55230. )
  55231. /*
  55232. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  55233. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  55234. ** numbered from zero.
  55235. **
  55236. ** If the wal-index is currently smaller the iPage pages then the size
  55237. ** of the wal-index might be increased, but only if it is safe to do
  55238. ** so. It is safe to enlarge the wal-index if pWal->writeLock is true
  55239. ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
  55240. **
  55241. ** If this call is successful, *ppPage is set to point to the wal-index
  55242. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  55243. ** then an SQLite error code is returned and *ppPage is set to 0.
  55244. */
  55245. static SQLITE_NOINLINE int walIndexPageRealloc(
  55246. Wal *pWal, /* The WAL context */
  55247. int iPage, /* The page we seek */
  55248. volatile u32 **ppPage /* Write the page pointer here */
  55249. ){
  55250. int rc = SQLITE_OK;
  55251. /* Enlarge the pWal->apWiData[] array if required */
  55252. if( pWal->nWiData<=iPage ){
  55253. sqlite3_int64 nByte = sizeof(u32*)*(iPage+1);
  55254. volatile u32 **apNew;
  55255. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  55256. if( !apNew ){
  55257. *ppPage = 0;
  55258. return SQLITE_NOMEM_BKPT;
  55259. }
  55260. memset((void*)&apNew[pWal->nWiData], 0,
  55261. sizeof(u32*)*(iPage+1-pWal->nWiData));
  55262. pWal->apWiData = apNew;
  55263. pWal->nWiData = iPage+1;
  55264. }
  55265. /* Request a pointer to the required page from the VFS */
  55266. assert( pWal->apWiData[iPage]==0 );
  55267. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  55268. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  55269. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
  55270. }else{
  55271. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  55272. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  55273. );
  55274. assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );
  55275. testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
  55276. if( (rc&0xff)==SQLITE_READONLY ){
  55277. pWal->readOnly |= WAL_SHM_RDONLY;
  55278. if( rc==SQLITE_READONLY ){
  55279. rc = SQLITE_OK;
  55280. }
  55281. }
  55282. }
  55283. *ppPage = pWal->apWiData[iPage];
  55284. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  55285. return rc;
  55286. }
  55287. static int walIndexPage(
  55288. Wal *pWal, /* The WAL context */
  55289. int iPage, /* The page we seek */
  55290. volatile u32 **ppPage /* Write the page pointer here */
  55291. ){
  55292. if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
  55293. return walIndexPageRealloc(pWal, iPage, ppPage);
  55294. }
  55295. return SQLITE_OK;
  55296. }
  55297. /*
  55298. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  55299. */
  55300. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  55301. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  55302. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  55303. }
  55304. /*
  55305. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  55306. */
  55307. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  55308. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  55309. return (volatile WalIndexHdr*)pWal->apWiData[0];
  55310. }
  55311. /*
  55312. ** The argument to this macro must be of type u32. On a little-endian
  55313. ** architecture, it returns the u32 value that results from interpreting
  55314. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  55315. ** returns the value that would be produced by interpreting the 4 bytes
  55316. ** of the input value as a little-endian integer.
  55317. */
  55318. #define BYTESWAP32(x) ( \
  55319. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  55320. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  55321. )
  55322. /*
  55323. ** Generate or extend an 8 byte checksum based on the data in
  55324. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  55325. ** initial values of 0 and 0 if aIn==NULL).
  55326. **
  55327. ** The checksum is written back into aOut[] before returning.
  55328. **
  55329. ** nByte must be a positive multiple of 8.
  55330. */
  55331. static void walChecksumBytes(
  55332. int nativeCksum, /* True for native byte-order, false for non-native */
  55333. u8 *a, /* Content to be checksummed */
  55334. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  55335. const u32 *aIn, /* Initial checksum value input */
  55336. u32 *aOut /* OUT: Final checksum value output */
  55337. ){
  55338. u32 s1, s2;
  55339. u32 *aData = (u32 *)a;
  55340. u32 *aEnd = (u32 *)&a[nByte];
  55341. if( aIn ){
  55342. s1 = aIn[0];
  55343. s2 = aIn[1];
  55344. }else{
  55345. s1 = s2 = 0;
  55346. }
  55347. assert( nByte>=8 );
  55348. assert( (nByte&0x00000007)==0 );
  55349. assert( nByte<=65536 );
  55350. if( nativeCksum ){
  55351. do {
  55352. s1 += *aData++ + s2;
  55353. s2 += *aData++ + s1;
  55354. }while( aData<aEnd );
  55355. }else{
  55356. do {
  55357. s1 += BYTESWAP32(aData[0]) + s2;
  55358. s2 += BYTESWAP32(aData[1]) + s1;
  55359. aData += 2;
  55360. }while( aData<aEnd );
  55361. }
  55362. aOut[0] = s1;
  55363. aOut[1] = s2;
  55364. }
  55365. static void walShmBarrier(Wal *pWal){
  55366. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  55367. sqlite3OsShmBarrier(pWal->pDbFd);
  55368. }
  55369. }
  55370. /*
  55371. ** Write the header information in pWal->hdr into the wal-index.
  55372. **
  55373. ** The checksum on pWal->hdr is updated before it is written.
  55374. */
  55375. static void walIndexWriteHdr(Wal *pWal){
  55376. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  55377. const int nCksum = offsetof(WalIndexHdr, aCksum);
  55378. assert( pWal->writeLock );
  55379. pWal->hdr.isInit = 1;
  55380. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  55381. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  55382. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  55383. walShmBarrier(pWal);
  55384. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  55385. }
  55386. /*
  55387. ** This function encodes a single frame header and writes it to a buffer
  55388. ** supplied by the caller. A frame-header is made up of a series of
  55389. ** 4-byte big-endian integers, as follows:
  55390. **
  55391. ** 0: Page number.
  55392. ** 4: For commit records, the size of the database image in pages
  55393. ** after the commit. For all other records, zero.
  55394. ** 8: Salt-1 (copied from the wal-header)
  55395. ** 12: Salt-2 (copied from the wal-header)
  55396. ** 16: Checksum-1.
  55397. ** 20: Checksum-2.
  55398. */
  55399. static void walEncodeFrame(
  55400. Wal *pWal, /* The write-ahead log */
  55401. u32 iPage, /* Database page number for frame */
  55402. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  55403. u8 *aData, /* Pointer to page data */
  55404. u8 *aFrame /* OUT: Write encoded frame here */
  55405. ){
  55406. int nativeCksum; /* True for native byte-order checksums */
  55407. u32 *aCksum = pWal->hdr.aFrameCksum;
  55408. assert( WAL_FRAME_HDRSIZE==24 );
  55409. sqlite3Put4byte(&aFrame[0], iPage);
  55410. sqlite3Put4byte(&aFrame[4], nTruncate);
  55411. if( pWal->iReCksum==0 ){
  55412. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  55413. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  55414. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  55415. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  55416. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  55417. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  55418. }else{
  55419. memset(&aFrame[8], 0, 16);
  55420. }
  55421. }
  55422. /*
  55423. ** Check to see if the frame with header in aFrame[] and content
  55424. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  55425. ** *pnTruncate and return true. Return if the frame is not valid.
  55426. */
  55427. static int walDecodeFrame(
  55428. Wal *pWal, /* The write-ahead log */
  55429. u32 *piPage, /* OUT: Database page number for frame */
  55430. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  55431. u8 *aData, /* Pointer to page data (for checksum) */
  55432. u8 *aFrame /* Frame data */
  55433. ){
  55434. int nativeCksum; /* True for native byte-order checksums */
  55435. u32 *aCksum = pWal->hdr.aFrameCksum;
  55436. u32 pgno; /* Page number of the frame */
  55437. assert( WAL_FRAME_HDRSIZE==24 );
  55438. /* A frame is only valid if the salt values in the frame-header
  55439. ** match the salt values in the wal-header.
  55440. */
  55441. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  55442. return 0;
  55443. }
  55444. /* A frame is only valid if the page number is creater than zero.
  55445. */
  55446. pgno = sqlite3Get4byte(&aFrame[0]);
  55447. if( pgno==0 ){
  55448. return 0;
  55449. }
  55450. /* A frame is only valid if a checksum of the WAL header,
  55451. ** all prior frams, the first 16 bytes of this frame-header,
  55452. ** and the frame-data matches the checksum in the last 8
  55453. ** bytes of this frame-header.
  55454. */
  55455. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  55456. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  55457. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  55458. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  55459. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  55460. ){
  55461. /* Checksum failed. */
  55462. return 0;
  55463. }
  55464. /* If we reach this point, the frame is valid. Return the page number
  55465. ** and the new database size.
  55466. */
  55467. *piPage = pgno;
  55468. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  55469. return 1;
  55470. }
  55471. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  55472. /*
  55473. ** Names of locks. This routine is used to provide debugging output and is not
  55474. ** a part of an ordinary build.
  55475. */
  55476. static const char *walLockName(int lockIdx){
  55477. if( lockIdx==WAL_WRITE_LOCK ){
  55478. return "WRITE-LOCK";
  55479. }else if( lockIdx==WAL_CKPT_LOCK ){
  55480. return "CKPT-LOCK";
  55481. }else if( lockIdx==WAL_RECOVER_LOCK ){
  55482. return "RECOVER-LOCK";
  55483. }else{
  55484. static char zName[15];
  55485. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  55486. lockIdx-WAL_READ_LOCK(0));
  55487. return zName;
  55488. }
  55489. }
  55490. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  55491. /*
  55492. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  55493. ** A lock cannot be moved directly between shared and exclusive - it must go
  55494. ** through the unlocked state first.
  55495. **
  55496. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  55497. */
  55498. static int walLockShared(Wal *pWal, int lockIdx){
  55499. int rc;
  55500. if( pWal->exclusiveMode ) return SQLITE_OK;
  55501. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  55502. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  55503. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  55504. walLockName(lockIdx), rc ? "failed" : "ok"));
  55505. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  55506. return rc;
  55507. }
  55508. static void walUnlockShared(Wal *pWal, int lockIdx){
  55509. if( pWal->exclusiveMode ) return;
  55510. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  55511. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  55512. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  55513. }
  55514. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  55515. int rc;
  55516. if( pWal->exclusiveMode ) return SQLITE_OK;
  55517. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  55518. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  55519. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  55520. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  55521. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  55522. return rc;
  55523. }
  55524. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  55525. if( pWal->exclusiveMode ) return;
  55526. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  55527. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  55528. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  55529. walLockName(lockIdx), n));
  55530. }
  55531. /*
  55532. ** Compute a hash on a page number. The resulting hash value must land
  55533. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  55534. ** the hash to the next value in the event of a collision.
  55535. */
  55536. static int walHash(u32 iPage){
  55537. assert( iPage>0 );
  55538. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  55539. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  55540. }
  55541. static int walNextHash(int iPriorHash){
  55542. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  55543. }
  55544. /*
  55545. ** An instance of the WalHashLoc object is used to describe the location
  55546. ** of a page hash table in the wal-index. This becomes the return value
  55547. ** from walHashGet().
  55548. */
  55549. typedef struct WalHashLoc WalHashLoc;
  55550. struct WalHashLoc {
  55551. volatile ht_slot *aHash; /* Start of the wal-index hash table */
  55552. volatile u32 *aPgno; /* aPgno[1] is the page of first frame indexed */
  55553. u32 iZero; /* One less than the frame number of first indexed*/
  55554. };
  55555. /*
  55556. ** Return pointers to the hash table and page number array stored on
  55557. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  55558. ** numbered starting from 0.
  55559. **
  55560. ** Set output variable pLoc->aHash to point to the start of the hash table
  55561. ** in the wal-index file. Set pLoc->iZero to one less than the frame
  55562. ** number of the first frame indexed by this hash table. If a
  55563. ** slot in the hash table is set to N, it refers to frame number
  55564. ** (pLoc->iZero+N) in the log.
  55565. **
  55566. ** Finally, set pLoc->aPgno so that pLoc->aPgno[1] is the page number of the
  55567. ** first frame indexed by the hash table, frame (pLoc->iZero+1).
  55568. */
  55569. static int walHashGet(
  55570. Wal *pWal, /* WAL handle */
  55571. int iHash, /* Find the iHash'th table */
  55572. WalHashLoc *pLoc /* OUT: Hash table location */
  55573. ){
  55574. int rc; /* Return code */
  55575. rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
  55576. assert( rc==SQLITE_OK || iHash>0 );
  55577. if( rc==SQLITE_OK ){
  55578. pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
  55579. if( iHash==0 ){
  55580. pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  55581. pLoc->iZero = 0;
  55582. }else{
  55583. pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  55584. }
  55585. pLoc->aPgno = &pLoc->aPgno[-1];
  55586. }
  55587. return rc;
  55588. }
  55589. /*
  55590. ** Return the number of the wal-index page that contains the hash-table
  55591. ** and page-number array that contain entries corresponding to WAL frame
  55592. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  55593. ** are numbered starting from 0.
  55594. */
  55595. static int walFramePage(u32 iFrame){
  55596. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  55597. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  55598. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  55599. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  55600. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  55601. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  55602. );
  55603. return iHash;
  55604. }
  55605. /*
  55606. ** Return the page number associated with frame iFrame in this WAL.
  55607. */
  55608. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  55609. int iHash = walFramePage(iFrame);
  55610. if( iHash==0 ){
  55611. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  55612. }
  55613. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  55614. }
  55615. /*
  55616. ** Remove entries from the hash table that point to WAL slots greater
  55617. ** than pWal->hdr.mxFrame.
  55618. **
  55619. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  55620. ** to a rollback or savepoint.
  55621. **
  55622. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  55623. ** updated. Any later hash tables will be automatically cleared when
  55624. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  55625. ** actually needed.
  55626. */
  55627. static void walCleanupHash(Wal *pWal){
  55628. WalHashLoc sLoc; /* Hash table location */
  55629. int iLimit = 0; /* Zero values greater than this */
  55630. int nByte; /* Number of bytes to zero in aPgno[] */
  55631. int i; /* Used to iterate through aHash[] */
  55632. int rc; /* Return code form walHashGet() */
  55633. assert( pWal->writeLock );
  55634. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  55635. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  55636. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  55637. if( pWal->hdr.mxFrame==0 ) return;
  55638. /* Obtain pointers to the hash-table and page-number array containing
  55639. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  55640. ** that the page said hash-table and array reside on is already mapped.(1)
  55641. */
  55642. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  55643. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  55644. rc = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
  55645. if( NEVER(rc) ) return; /* Defense-in-depth, in case (1) above is wrong */
  55646. /* Zero all hash-table entries that correspond to frame numbers greater
  55647. ** than pWal->hdr.mxFrame.
  55648. */
  55649. iLimit = pWal->hdr.mxFrame - sLoc.iZero;
  55650. assert( iLimit>0 );
  55651. for(i=0; i<HASHTABLE_NSLOT; i++){
  55652. if( sLoc.aHash[i]>iLimit ){
  55653. sLoc.aHash[i] = 0;
  55654. }
  55655. }
  55656. /* Zero the entries in the aPgno array that correspond to frames with
  55657. ** frame numbers greater than pWal->hdr.mxFrame.
  55658. */
  55659. nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]);
  55660. memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte);
  55661. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  55662. /* Verify that the every entry in the mapping region is still reachable
  55663. ** via the hash table even after the cleanup.
  55664. */
  55665. if( iLimit ){
  55666. int j; /* Loop counter */
  55667. int iKey; /* Hash key */
  55668. for(j=1; j<=iLimit; j++){
  55669. for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
  55670. if( sLoc.aHash[iKey]==j ) break;
  55671. }
  55672. assert( sLoc.aHash[iKey]==j );
  55673. }
  55674. }
  55675. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  55676. }
  55677. /*
  55678. ** Set an entry in the wal-index that will map database page number
  55679. ** pPage into WAL frame iFrame.
  55680. */
  55681. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  55682. int rc; /* Return code */
  55683. WalHashLoc sLoc; /* Wal-index hash table location */
  55684. rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
  55685. /* Assuming the wal-index file was successfully mapped, populate the
  55686. ** page number array and hash table entry.
  55687. */
  55688. if( rc==SQLITE_OK ){
  55689. int iKey; /* Hash table key */
  55690. int idx; /* Value to write to hash-table slot */
  55691. int nCollide; /* Number of hash collisions */
  55692. idx = iFrame - sLoc.iZero;
  55693. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  55694. /* If this is the first entry to be added to this hash-table, zero the
  55695. ** entire hash table and aPgno[] array before proceeding.
  55696. */
  55697. if( idx==1 ){
  55698. int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT]
  55699. - (u8 *)&sLoc.aPgno[1]);
  55700. memset((void*)&sLoc.aPgno[1], 0, nByte);
  55701. }
  55702. /* If the entry in aPgno[] is already set, then the previous writer
  55703. ** must have exited unexpectedly in the middle of a transaction (after
  55704. ** writing one or more dirty pages to the WAL to free up memory).
  55705. ** Remove the remnants of that writers uncommitted transaction from
  55706. ** the hash-table before writing any new entries.
  55707. */
  55708. if( sLoc.aPgno[idx] ){
  55709. walCleanupHash(pWal);
  55710. assert( !sLoc.aPgno[idx] );
  55711. }
  55712. /* Write the aPgno[] array entry and the hash-table slot. */
  55713. nCollide = idx;
  55714. for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
  55715. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  55716. }
  55717. sLoc.aPgno[idx] = iPage;
  55718. sLoc.aHash[iKey] = (ht_slot)idx;
  55719. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  55720. /* Verify that the number of entries in the hash table exactly equals
  55721. ** the number of entries in the mapping region.
  55722. */
  55723. {
  55724. int i; /* Loop counter */
  55725. int nEntry = 0; /* Number of entries in the hash table */
  55726. for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }
  55727. assert( nEntry==idx );
  55728. }
  55729. /* Verify that the every entry in the mapping region is reachable
  55730. ** via the hash table. This turns out to be a really, really expensive
  55731. ** thing to check, so only do this occasionally - not on every
  55732. ** iteration.
  55733. */
  55734. if( (idx&0x3ff)==0 ){
  55735. int i; /* Loop counter */
  55736. for(i=1; i<=idx; i++){
  55737. for(iKey=walHash(sLoc.aPgno[i]);
  55738. sLoc.aHash[iKey];
  55739. iKey=walNextHash(iKey)){
  55740. if( sLoc.aHash[iKey]==i ) break;
  55741. }
  55742. assert( sLoc.aHash[iKey]==i );
  55743. }
  55744. }
  55745. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  55746. }
  55747. return rc;
  55748. }
  55749. /*
  55750. ** Recover the wal-index by reading the write-ahead log file.
  55751. **
  55752. ** This routine first tries to establish an exclusive lock on the
  55753. ** wal-index to prevent other threads/processes from doing anything
  55754. ** with the WAL or wal-index while recovery is running. The
  55755. ** WAL_RECOVER_LOCK is also held so that other threads will know
  55756. ** that this thread is running recovery. If unable to establish
  55757. ** the necessary locks, this routine returns SQLITE_BUSY.
  55758. */
  55759. static int walIndexRecover(Wal *pWal){
  55760. int rc; /* Return Code */
  55761. i64 nSize; /* Size of log file */
  55762. u32 aFrameCksum[2] = {0, 0};
  55763. int iLock; /* Lock offset to lock for checkpoint */
  55764. /* Obtain an exclusive lock on all byte in the locking range not already
  55765. ** locked by the caller. The caller is guaranteed to have locked the
  55766. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  55767. ** If successful, the same bytes that are locked here are unlocked before
  55768. ** this function returns.
  55769. */
  55770. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  55771. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  55772. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  55773. assert( pWal->writeLock );
  55774. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  55775. rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  55776. if( rc==SQLITE_OK ){
  55777. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  55778. if( rc!=SQLITE_OK ){
  55779. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  55780. }
  55781. }
  55782. if( rc ){
  55783. return rc;
  55784. }
  55785. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  55786. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  55787. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  55788. if( rc!=SQLITE_OK ){
  55789. goto recovery_error;
  55790. }
  55791. if( nSize>WAL_HDRSIZE ){
  55792. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  55793. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  55794. int szFrame; /* Number of bytes in buffer aFrame[] */
  55795. u8 *aData; /* Pointer to data part of aFrame buffer */
  55796. int iFrame; /* Index of last frame read */
  55797. i64 iOffset; /* Next offset to read from log file */
  55798. int szPage; /* Page size according to the log */
  55799. u32 magic; /* Magic value read from WAL header */
  55800. u32 version; /* Magic value read from WAL header */
  55801. int isValid; /* True if this frame is valid */
  55802. /* Read in the WAL header. */
  55803. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  55804. if( rc!=SQLITE_OK ){
  55805. goto recovery_error;
  55806. }
  55807. /* If the database page size is not a power of two, or is greater than
  55808. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  55809. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  55810. ** WAL file.
  55811. */
  55812. magic = sqlite3Get4byte(&aBuf[0]);
  55813. szPage = sqlite3Get4byte(&aBuf[8]);
  55814. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  55815. || szPage&(szPage-1)
  55816. || szPage>SQLITE_MAX_PAGE_SIZE
  55817. || szPage<512
  55818. ){
  55819. goto finished;
  55820. }
  55821. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  55822. pWal->szPage = szPage;
  55823. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  55824. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  55825. /* Verify that the WAL header checksum is correct */
  55826. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  55827. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  55828. );
  55829. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  55830. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  55831. ){
  55832. goto finished;
  55833. }
  55834. /* Verify that the version number on the WAL format is one that
  55835. ** are able to understand */
  55836. version = sqlite3Get4byte(&aBuf[4]);
  55837. if( version!=WAL_MAX_VERSION ){
  55838. rc = SQLITE_CANTOPEN_BKPT;
  55839. goto finished;
  55840. }
  55841. /* Malloc a buffer to read frames into. */
  55842. szFrame = szPage + WAL_FRAME_HDRSIZE;
  55843. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  55844. if( !aFrame ){
  55845. rc = SQLITE_NOMEM_BKPT;
  55846. goto recovery_error;
  55847. }
  55848. aData = &aFrame[WAL_FRAME_HDRSIZE];
  55849. /* Read all frames from the log file. */
  55850. iFrame = 0;
  55851. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  55852. u32 pgno; /* Database page number for frame */
  55853. u32 nTruncate; /* dbsize field from frame header */
  55854. /* Read and decode the next log frame. */
  55855. iFrame++;
  55856. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  55857. if( rc!=SQLITE_OK ) break;
  55858. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  55859. if( !isValid ) break;
  55860. rc = walIndexAppend(pWal, iFrame, pgno);
  55861. if( rc!=SQLITE_OK ) break;
  55862. /* If nTruncate is non-zero, this is a commit record. */
  55863. if( nTruncate ){
  55864. pWal->hdr.mxFrame = iFrame;
  55865. pWal->hdr.nPage = nTruncate;
  55866. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  55867. testcase( szPage<=32768 );
  55868. testcase( szPage>=65536 );
  55869. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  55870. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  55871. }
  55872. }
  55873. sqlite3_free(aFrame);
  55874. }
  55875. finished:
  55876. if( rc==SQLITE_OK ){
  55877. volatile WalCkptInfo *pInfo;
  55878. int i;
  55879. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  55880. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  55881. walIndexWriteHdr(pWal);
  55882. /* Reset the checkpoint-header. This is safe because this thread is
  55883. ** currently holding locks that exclude all other readers, writers and
  55884. ** checkpointers.
  55885. */
  55886. pInfo = walCkptInfo(pWal);
  55887. pInfo->nBackfill = 0;
  55888. pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
  55889. pInfo->aReadMark[0] = 0;
  55890. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  55891. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  55892. /* If more than one frame was recovered from the log file, report an
  55893. ** event via sqlite3_log(). This is to help with identifying performance
  55894. ** problems caused by applications routinely shutting down without
  55895. ** checkpointing the log file.
  55896. */
  55897. if( pWal->hdr.nPage ){
  55898. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  55899. "recovered %d frames from WAL file %s",
  55900. pWal->hdr.mxFrame, pWal->zWalName
  55901. );
  55902. }
  55903. }
  55904. recovery_error:
  55905. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  55906. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  55907. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  55908. return rc;
  55909. }
  55910. /*
  55911. ** Close an open wal-index.
  55912. */
  55913. static void walIndexClose(Wal *pWal, int isDelete){
  55914. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
  55915. int i;
  55916. for(i=0; i<pWal->nWiData; i++){
  55917. sqlite3_free((void *)pWal->apWiData[i]);
  55918. pWal->apWiData[i] = 0;
  55919. }
  55920. }
  55921. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  55922. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  55923. }
  55924. }
  55925. /*
  55926. ** Open a connection to the WAL file zWalName. The database file must
  55927. ** already be opened on connection pDbFd. The buffer that zWalName points
  55928. ** to must remain valid for the lifetime of the returned Wal* handle.
  55929. **
  55930. ** A SHARED lock should be held on the database file when this function
  55931. ** is called. The purpose of this SHARED lock is to prevent any other
  55932. ** client from unlinking the WAL or wal-index file. If another process
  55933. ** were to do this just after this client opened one of these files, the
  55934. ** system would be badly broken.
  55935. **
  55936. ** If the log file is successfully opened, SQLITE_OK is returned and
  55937. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  55938. ** an SQLite error code is returned and *ppWal is left unmodified.
  55939. */
  55940. SQLITE_PRIVATE int sqlite3WalOpen(
  55941. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  55942. sqlite3_file *pDbFd, /* The open database file */
  55943. const char *zWalName, /* Name of the WAL file */
  55944. int bNoShm, /* True to run in heap-memory mode */
  55945. i64 mxWalSize, /* Truncate WAL to this size on reset */
  55946. Wal **ppWal /* OUT: Allocated Wal handle */
  55947. ){
  55948. int rc; /* Return Code */
  55949. Wal *pRet; /* Object to allocate and return */
  55950. int flags; /* Flags passed to OsOpen() */
  55951. assert( zWalName && zWalName[0] );
  55952. assert( pDbFd );
  55953. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  55954. ** this source file. Verify that the #defines of the locking byte offsets
  55955. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  55956. ** For that matter, if the lock offset ever changes from its initial design
  55957. ** value of 120, we need to know that so there is an assert() to check it.
  55958. */
  55959. assert( 120==WALINDEX_LOCK_OFFSET );
  55960. assert( 136==WALINDEX_HDR_SIZE );
  55961. #ifdef WIN_SHM_BASE
  55962. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  55963. #endif
  55964. #ifdef UNIX_SHM_BASE
  55965. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  55966. #endif
  55967. /* Allocate an instance of struct Wal to return. */
  55968. *ppWal = 0;
  55969. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  55970. if( !pRet ){
  55971. return SQLITE_NOMEM_BKPT;
  55972. }
  55973. pRet->pVfs = pVfs;
  55974. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  55975. pRet->pDbFd = pDbFd;
  55976. pRet->readLock = -1;
  55977. pRet->mxWalSize = mxWalSize;
  55978. pRet->zWalName = zWalName;
  55979. pRet->syncHeader = 1;
  55980. pRet->padToSectorBoundary = 1;
  55981. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  55982. /* Open file handle on the write-ahead log file. */
  55983. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  55984. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  55985. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  55986. pRet->readOnly = WAL_RDONLY;
  55987. }
  55988. if( rc!=SQLITE_OK ){
  55989. walIndexClose(pRet, 0);
  55990. sqlite3OsClose(pRet->pWalFd);
  55991. sqlite3_free(pRet);
  55992. }else{
  55993. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  55994. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  55995. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  55996. pRet->padToSectorBoundary = 0;
  55997. }
  55998. *ppWal = pRet;
  55999. WALTRACE(("WAL%d: opened\n", pRet));
  56000. }
  56001. return rc;
  56002. }
  56003. /*
  56004. ** Change the size to which the WAL file is trucated on each reset.
  56005. */
  56006. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  56007. if( pWal ) pWal->mxWalSize = iLimit;
  56008. }
  56009. /*
  56010. ** Find the smallest page number out of all pages held in the WAL that
  56011. ** has not been returned by any prior invocation of this method on the
  56012. ** same WalIterator object. Write into *piFrame the frame index where
  56013. ** that page was last written into the WAL. Write into *piPage the page
  56014. ** number.
  56015. **
  56016. ** Return 0 on success. If there are no pages in the WAL with a page
  56017. ** number larger than *piPage, then return 1.
  56018. */
  56019. static int walIteratorNext(
  56020. WalIterator *p, /* Iterator */
  56021. u32 *piPage, /* OUT: The page number of the next page */
  56022. u32 *piFrame /* OUT: Wal frame index of next page */
  56023. ){
  56024. u32 iMin; /* Result pgno must be greater than iMin */
  56025. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  56026. int i; /* For looping through segments */
  56027. iMin = p->iPrior;
  56028. assert( iMin<0xffffffff );
  56029. for(i=p->nSegment-1; i>=0; i--){
  56030. struct WalSegment *pSegment = &p->aSegment[i];
  56031. while( pSegment->iNext<pSegment->nEntry ){
  56032. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  56033. if( iPg>iMin ){
  56034. if( iPg<iRet ){
  56035. iRet = iPg;
  56036. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  56037. }
  56038. break;
  56039. }
  56040. pSegment->iNext++;
  56041. }
  56042. }
  56043. *piPage = p->iPrior = iRet;
  56044. return (iRet==0xFFFFFFFF);
  56045. }
  56046. /*
  56047. ** This function merges two sorted lists into a single sorted list.
  56048. **
  56049. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  56050. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  56051. ** is guaranteed for all J<K:
  56052. **
  56053. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  56054. ** aContent[aRight[J]] < aContent[aRight[K]]
  56055. **
  56056. ** This routine overwrites aRight[] with a new (probably longer) sequence
  56057. ** of indices such that the aRight[] contains every index that appears in
  56058. ** either aLeft[] or the old aRight[] and such that the second condition
  56059. ** above is still met.
  56060. **
  56061. ** The aContent[aLeft[X]] values will be unique for all X. And the
  56062. ** aContent[aRight[X]] values will be unique too. But there might be
  56063. ** one or more combinations of X and Y such that
  56064. **
  56065. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  56066. **
  56067. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  56068. */
  56069. static void walMerge(
  56070. const u32 *aContent, /* Pages in wal - keys for the sort */
  56071. ht_slot *aLeft, /* IN: Left hand input list */
  56072. int nLeft, /* IN: Elements in array *paLeft */
  56073. ht_slot **paRight, /* IN/OUT: Right hand input list */
  56074. int *pnRight, /* IN/OUT: Elements in *paRight */
  56075. ht_slot *aTmp /* Temporary buffer */
  56076. ){
  56077. int iLeft = 0; /* Current index in aLeft */
  56078. int iRight = 0; /* Current index in aRight */
  56079. int iOut = 0; /* Current index in output buffer */
  56080. int nRight = *pnRight;
  56081. ht_slot *aRight = *paRight;
  56082. assert( nLeft>0 && nRight>0 );
  56083. while( iRight<nRight || iLeft<nLeft ){
  56084. ht_slot logpage;
  56085. Pgno dbpage;
  56086. if( (iLeft<nLeft)
  56087. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  56088. ){
  56089. logpage = aLeft[iLeft++];
  56090. }else{
  56091. logpage = aRight[iRight++];
  56092. }
  56093. dbpage = aContent[logpage];
  56094. aTmp[iOut++] = logpage;
  56095. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  56096. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  56097. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  56098. }
  56099. *paRight = aLeft;
  56100. *pnRight = iOut;
  56101. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  56102. }
  56103. /*
  56104. ** Sort the elements in list aList using aContent[] as the sort key.
  56105. ** Remove elements with duplicate keys, preferring to keep the
  56106. ** larger aList[] values.
  56107. **
  56108. ** The aList[] entries are indices into aContent[]. The values in
  56109. ** aList[] are to be sorted so that for all J<K:
  56110. **
  56111. ** aContent[aList[J]] < aContent[aList[K]]
  56112. **
  56113. ** For any X and Y such that
  56114. **
  56115. ** aContent[aList[X]] == aContent[aList[Y]]
  56116. **
  56117. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  56118. ** the smaller.
  56119. */
  56120. static void walMergesort(
  56121. const u32 *aContent, /* Pages in wal */
  56122. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  56123. ht_slot *aList, /* IN/OUT: List to sort */
  56124. int *pnList /* IN/OUT: Number of elements in aList[] */
  56125. ){
  56126. struct Sublist {
  56127. int nList; /* Number of elements in aList */
  56128. ht_slot *aList; /* Pointer to sub-list content */
  56129. };
  56130. const int nList = *pnList; /* Size of input list */
  56131. int nMerge = 0; /* Number of elements in list aMerge */
  56132. ht_slot *aMerge = 0; /* List to be merged */
  56133. int iList; /* Index into input list */
  56134. u32 iSub = 0; /* Index into aSub array */
  56135. struct Sublist aSub[13]; /* Array of sub-lists */
  56136. memset(aSub, 0, sizeof(aSub));
  56137. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  56138. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  56139. for(iList=0; iList<nList; iList++){
  56140. nMerge = 1;
  56141. aMerge = &aList[iList];
  56142. for(iSub=0; iList & (1<<iSub); iSub++){
  56143. struct Sublist *p;
  56144. assert( iSub<ArraySize(aSub) );
  56145. p = &aSub[iSub];
  56146. assert( p->aList && p->nList<=(1<<iSub) );
  56147. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  56148. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  56149. }
  56150. aSub[iSub].aList = aMerge;
  56151. aSub[iSub].nList = nMerge;
  56152. }
  56153. for(iSub++; iSub<ArraySize(aSub); iSub++){
  56154. if( nList & (1<<iSub) ){
  56155. struct Sublist *p;
  56156. assert( iSub<ArraySize(aSub) );
  56157. p = &aSub[iSub];
  56158. assert( p->nList<=(1<<iSub) );
  56159. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  56160. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  56161. }
  56162. }
  56163. assert( aMerge==aList );
  56164. *pnList = nMerge;
  56165. #ifdef SQLITE_DEBUG
  56166. {
  56167. int i;
  56168. for(i=1; i<*pnList; i++){
  56169. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  56170. }
  56171. }
  56172. #endif
  56173. }
  56174. /*
  56175. ** Free an iterator allocated by walIteratorInit().
  56176. */
  56177. static void walIteratorFree(WalIterator *p){
  56178. sqlite3_free(p);
  56179. }
  56180. /*
  56181. ** Construct a WalInterator object that can be used to loop over all
  56182. ** pages in the WAL following frame nBackfill in ascending order. Frames
  56183. ** nBackfill or earlier may be included - excluding them is an optimization
  56184. ** only. The caller must hold the checkpoint lock.
  56185. **
  56186. ** On success, make *pp point to the newly allocated WalInterator object
  56187. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  56188. ** returns an error, the value of *pp is undefined.
  56189. **
  56190. ** The calling routine should invoke walIteratorFree() to destroy the
  56191. ** WalIterator object when it has finished with it.
  56192. */
  56193. static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
  56194. WalIterator *p; /* Return value */
  56195. int nSegment; /* Number of segments to merge */
  56196. u32 iLast; /* Last frame in log */
  56197. sqlite3_int64 nByte; /* Number of bytes to allocate */
  56198. int i; /* Iterator variable */
  56199. ht_slot *aTmp; /* Temp space used by merge-sort */
  56200. int rc = SQLITE_OK; /* Return Code */
  56201. /* This routine only runs while holding the checkpoint lock. And
  56202. ** it only runs if there is actually content in the log (mxFrame>0).
  56203. */
  56204. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  56205. iLast = pWal->hdr.mxFrame;
  56206. /* Allocate space for the WalIterator object. */
  56207. nSegment = walFramePage(iLast) + 1;
  56208. nByte = sizeof(WalIterator)
  56209. + (nSegment-1)*sizeof(struct WalSegment)
  56210. + iLast*sizeof(ht_slot);
  56211. p = (WalIterator *)sqlite3_malloc64(nByte);
  56212. if( !p ){
  56213. return SQLITE_NOMEM_BKPT;
  56214. }
  56215. memset(p, 0, nByte);
  56216. p->nSegment = nSegment;
  56217. /* Allocate temporary space used by the merge-sort routine. This block
  56218. ** of memory will be freed before this function returns.
  56219. */
  56220. aTmp = (ht_slot *)sqlite3_malloc64(
  56221. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  56222. );
  56223. if( !aTmp ){
  56224. rc = SQLITE_NOMEM_BKPT;
  56225. }
  56226. for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
  56227. WalHashLoc sLoc;
  56228. rc = walHashGet(pWal, i, &sLoc);
  56229. if( rc==SQLITE_OK ){
  56230. int j; /* Counter variable */
  56231. int nEntry; /* Number of entries in this segment */
  56232. ht_slot *aIndex; /* Sorted index for this segment */
  56233. sLoc.aPgno++;
  56234. if( (i+1)==nSegment ){
  56235. nEntry = (int)(iLast - sLoc.iZero);
  56236. }else{
  56237. nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
  56238. }
  56239. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
  56240. sLoc.iZero++;
  56241. for(j=0; j<nEntry; j++){
  56242. aIndex[j] = (ht_slot)j;
  56243. }
  56244. walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
  56245. p->aSegment[i].iZero = sLoc.iZero;
  56246. p->aSegment[i].nEntry = nEntry;
  56247. p->aSegment[i].aIndex = aIndex;
  56248. p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
  56249. }
  56250. }
  56251. sqlite3_free(aTmp);
  56252. if( rc!=SQLITE_OK ){
  56253. walIteratorFree(p);
  56254. p = 0;
  56255. }
  56256. *pp = p;
  56257. return rc;
  56258. }
  56259. /*
  56260. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  56261. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  56262. ** busy-handler function. Invoke it and retry the lock until either the
  56263. ** lock is successfully obtained or the busy-handler returns 0.
  56264. */
  56265. static int walBusyLock(
  56266. Wal *pWal, /* WAL connection */
  56267. int (*xBusy)(void*), /* Function to call when busy */
  56268. void *pBusyArg, /* Context argument for xBusyHandler */
  56269. int lockIdx, /* Offset of first byte to lock */
  56270. int n /* Number of bytes to lock */
  56271. ){
  56272. int rc;
  56273. do {
  56274. rc = walLockExclusive(pWal, lockIdx, n);
  56275. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  56276. return rc;
  56277. }
  56278. /*
  56279. ** The cache of the wal-index header must be valid to call this function.
  56280. ** Return the page-size in bytes used by the database.
  56281. */
  56282. static int walPagesize(Wal *pWal){
  56283. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  56284. }
  56285. /*
  56286. ** The following is guaranteed when this function is called:
  56287. **
  56288. ** a) the WRITER lock is held,
  56289. ** b) the entire log file has been checkpointed, and
  56290. ** c) any existing readers are reading exclusively from the database
  56291. ** file - there are no readers that may attempt to read a frame from
  56292. ** the log file.
  56293. **
  56294. ** This function updates the shared-memory structures so that the next
  56295. ** client to write to the database (which may be this one) does so by
  56296. ** writing frames into the start of the log file.
  56297. **
  56298. ** The value of parameter salt1 is used as the aSalt[1] value in the
  56299. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  56300. ** one obtained from sqlite3_randomness()).
  56301. */
  56302. static void walRestartHdr(Wal *pWal, u32 salt1){
  56303. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  56304. int i; /* Loop counter */
  56305. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  56306. pWal->nCkpt++;
  56307. pWal->hdr.mxFrame = 0;
  56308. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  56309. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  56310. walIndexWriteHdr(pWal);
  56311. pInfo->nBackfill = 0;
  56312. pInfo->nBackfillAttempted = 0;
  56313. pInfo->aReadMark[1] = 0;
  56314. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  56315. assert( pInfo->aReadMark[0]==0 );
  56316. }
  56317. /*
  56318. ** Copy as much content as we can from the WAL back into the database file
  56319. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  56320. **
  56321. ** The amount of information copies from WAL to database might be limited
  56322. ** by active readers. This routine will never overwrite a database page
  56323. ** that a concurrent reader might be using.
  56324. **
  56325. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  56326. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  56327. ** checkpoints are always run by a background thread or background
  56328. ** process, foreground threads will never block on a lengthy fsync call.
  56329. **
  56330. ** Fsync is called on the WAL before writing content out of the WAL and
  56331. ** into the database. This ensures that if the new content is persistent
  56332. ** in the WAL and can be recovered following a power-loss or hard reset.
  56333. **
  56334. ** Fsync is also called on the database file if (and only if) the entire
  56335. ** WAL content is copied into the database file. This second fsync makes
  56336. ** it safe to delete the WAL since the new content will persist in the
  56337. ** database file.
  56338. **
  56339. ** This routine uses and updates the nBackfill field of the wal-index header.
  56340. ** This is the only routine that will increase the value of nBackfill.
  56341. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  56342. ** its value.)
  56343. **
  56344. ** The caller must be holding sufficient locks to ensure that no other
  56345. ** checkpoint is running (in any other thread or process) at the same
  56346. ** time.
  56347. */
  56348. static int walCheckpoint(
  56349. Wal *pWal, /* Wal connection */
  56350. sqlite3 *db, /* Check for interrupts on this handle */
  56351. int eMode, /* One of PASSIVE, FULL or RESTART */
  56352. int (*xBusy)(void*), /* Function to call when busy */
  56353. void *pBusyArg, /* Context argument for xBusyHandler */
  56354. int sync_flags, /* Flags for OsSync() (or 0) */
  56355. u8 *zBuf /* Temporary buffer to use */
  56356. ){
  56357. int rc = SQLITE_OK; /* Return code */
  56358. int szPage; /* Database page-size */
  56359. WalIterator *pIter = 0; /* Wal iterator context */
  56360. u32 iDbpage = 0; /* Next database page to write */
  56361. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  56362. u32 mxSafeFrame; /* Max frame that can be backfilled */
  56363. u32 mxPage; /* Max database page to write */
  56364. int i; /* Loop counter */
  56365. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  56366. szPage = walPagesize(pWal);
  56367. testcase( szPage<=32768 );
  56368. testcase( szPage>=65536 );
  56369. pInfo = walCkptInfo(pWal);
  56370. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  56371. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  56372. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  56373. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  56374. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  56375. ** safe to write into the database. Frames beyond mxSafeFrame might
  56376. ** overwrite database pages that are in use by active readers and thus
  56377. ** cannot be backfilled from the WAL.
  56378. */
  56379. mxSafeFrame = pWal->hdr.mxFrame;
  56380. mxPage = pWal->hdr.nPage;
  56381. for(i=1; i<WAL_NREADER; i++){
  56382. /* Thread-sanitizer reports that the following is an unsafe read,
  56383. ** as some other thread may be in the process of updating the value
  56384. ** of the aReadMark[] slot. The assumption here is that if that is
  56385. ** happening, the other client may only be increasing the value,
  56386. ** not decreasing it. So assuming either that either the "old" or
  56387. ** "new" version of the value is read, and not some arbitrary value
  56388. ** that would never be written by a real client, things are still
  56389. ** safe. */
  56390. u32 y = pInfo->aReadMark[i];
  56391. if( mxSafeFrame>y ){
  56392. assert( y<=pWal->hdr.mxFrame );
  56393. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  56394. if( rc==SQLITE_OK ){
  56395. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  56396. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  56397. }else if( rc==SQLITE_BUSY ){
  56398. mxSafeFrame = y;
  56399. xBusy = 0;
  56400. }else{
  56401. goto walcheckpoint_out;
  56402. }
  56403. }
  56404. }
  56405. /* Allocate the iterator */
  56406. if( pInfo->nBackfill<mxSafeFrame ){
  56407. rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
  56408. assert( rc==SQLITE_OK || pIter==0 );
  56409. }
  56410. if( pIter
  56411. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  56412. ){
  56413. u32 nBackfill = pInfo->nBackfill;
  56414. pInfo->nBackfillAttempted = mxSafeFrame;
  56415. /* Sync the WAL to disk */
  56416. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  56417. /* If the database may grow as a result of this checkpoint, hint
  56418. ** about the eventual size of the db file to the VFS layer.
  56419. */
  56420. if( rc==SQLITE_OK ){
  56421. i64 nReq = ((i64)mxPage * szPage);
  56422. i64 nSize; /* Current size of database file */
  56423. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  56424. if( rc==SQLITE_OK && nSize<nReq ){
  56425. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  56426. }
  56427. }
  56428. /* Iterate through the contents of the WAL, copying data to the db file */
  56429. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  56430. i64 iOffset;
  56431. assert( walFramePgno(pWal, iFrame)==iDbpage );
  56432. if( db->u1.isInterrupted ){
  56433. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  56434. break;
  56435. }
  56436. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  56437. continue;
  56438. }
  56439. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  56440. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  56441. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  56442. if( rc!=SQLITE_OK ) break;
  56443. iOffset = (iDbpage-1)*(i64)szPage;
  56444. testcase( IS_BIG_INT(iOffset) );
  56445. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  56446. if( rc!=SQLITE_OK ) break;
  56447. }
  56448. /* If work was actually accomplished... */
  56449. if( rc==SQLITE_OK ){
  56450. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  56451. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  56452. testcase( IS_BIG_INT(szDb) );
  56453. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  56454. if( rc==SQLITE_OK ){
  56455. rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
  56456. }
  56457. }
  56458. if( rc==SQLITE_OK ){
  56459. pInfo->nBackfill = mxSafeFrame;
  56460. }
  56461. }
  56462. /* Release the reader lock held while backfilling */
  56463. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  56464. }
  56465. if( rc==SQLITE_BUSY ){
  56466. /* Reset the return code so as not to report a checkpoint failure
  56467. ** just because there are active readers. */
  56468. rc = SQLITE_OK;
  56469. }
  56470. }
  56471. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  56472. ** entire wal file has been copied into the database file, then block
  56473. ** until all readers have finished using the wal file. This ensures that
  56474. ** the next process to write to the database restarts the wal file.
  56475. */
  56476. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  56477. assert( pWal->writeLock );
  56478. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  56479. rc = SQLITE_BUSY;
  56480. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  56481. u32 salt1;
  56482. sqlite3_randomness(4, &salt1);
  56483. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  56484. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  56485. if( rc==SQLITE_OK ){
  56486. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  56487. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  56488. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  56489. ** truncates the log file to zero bytes just prior to a
  56490. ** successful return.
  56491. **
  56492. ** In theory, it might be safe to do this without updating the
  56493. ** wal-index header in shared memory, as all subsequent reader or
  56494. ** writer clients should see that the entire log file has been
  56495. ** checkpointed and behave accordingly. This seems unsafe though,
  56496. ** as it would leave the system in a state where the contents of
  56497. ** the wal-index header do not match the contents of the
  56498. ** file-system. To avoid this, update the wal-index header to
  56499. ** indicate that the log file contains zero valid frames. */
  56500. walRestartHdr(pWal, salt1);
  56501. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  56502. }
  56503. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  56504. }
  56505. }
  56506. }
  56507. walcheckpoint_out:
  56508. walIteratorFree(pIter);
  56509. return rc;
  56510. }
  56511. /*
  56512. ** If the WAL file is currently larger than nMax bytes in size, truncate
  56513. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  56514. */
  56515. static void walLimitSize(Wal *pWal, i64 nMax){
  56516. i64 sz;
  56517. int rx;
  56518. sqlite3BeginBenignMalloc();
  56519. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  56520. if( rx==SQLITE_OK && (sz > nMax ) ){
  56521. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  56522. }
  56523. sqlite3EndBenignMalloc();
  56524. if( rx ){
  56525. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  56526. }
  56527. }
  56528. /*
  56529. ** Close a connection to a log file.
  56530. */
  56531. SQLITE_PRIVATE int sqlite3WalClose(
  56532. Wal *pWal, /* Wal to close */
  56533. sqlite3 *db, /* For interrupt flag */
  56534. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  56535. int nBuf,
  56536. u8 *zBuf /* Buffer of at least nBuf bytes */
  56537. ){
  56538. int rc = SQLITE_OK;
  56539. if( pWal ){
  56540. int isDelete = 0; /* True to unlink wal and wal-index files */
  56541. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  56542. ** ordinary, rollback-mode locking methods, this guarantees that the
  56543. ** connection associated with this log file is the only connection to
  56544. ** the database. In this case checkpoint the database and unlink both
  56545. ** the wal and wal-index files.
  56546. **
  56547. ** The EXCLUSIVE lock is not released before returning.
  56548. */
  56549. if( zBuf!=0
  56550. && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
  56551. ){
  56552. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  56553. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  56554. }
  56555. rc = sqlite3WalCheckpoint(pWal, db,
  56556. SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  56557. );
  56558. if( rc==SQLITE_OK ){
  56559. int bPersist = -1;
  56560. sqlite3OsFileControlHint(
  56561. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  56562. );
  56563. if( bPersist!=1 ){
  56564. /* Try to delete the WAL file if the checkpoint completed and
  56565. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  56566. ** mode (!bPersist) */
  56567. isDelete = 1;
  56568. }else if( pWal->mxWalSize>=0 ){
  56569. /* Try to truncate the WAL file to zero bytes if the checkpoint
  56570. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  56571. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  56572. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  56573. ** to zero bytes as truncating to the journal_size_limit might
  56574. ** leave a corrupt WAL file on disk. */
  56575. walLimitSize(pWal, 0);
  56576. }
  56577. }
  56578. }
  56579. walIndexClose(pWal, isDelete);
  56580. sqlite3OsClose(pWal->pWalFd);
  56581. if( isDelete ){
  56582. sqlite3BeginBenignMalloc();
  56583. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  56584. sqlite3EndBenignMalloc();
  56585. }
  56586. WALTRACE(("WAL%p: closed\n", pWal));
  56587. sqlite3_free((void *)pWal->apWiData);
  56588. sqlite3_free(pWal);
  56589. }
  56590. return rc;
  56591. }
  56592. /*
  56593. ** Try to read the wal-index header. Return 0 on success and 1 if
  56594. ** there is a problem.
  56595. **
  56596. ** The wal-index is in shared memory. Another thread or process might
  56597. ** be writing the header at the same time this procedure is trying to
  56598. ** read it, which might result in inconsistency. A dirty read is detected
  56599. ** by verifying that both copies of the header are the same and also by
  56600. ** a checksum on the header.
  56601. **
  56602. ** If and only if the read is consistent and the header is different from
  56603. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  56604. ** and *pChanged is set to 1.
  56605. **
  56606. ** If the checksum cannot be verified return non-zero. If the header
  56607. ** is read successfully and the checksum verified, return zero.
  56608. */
  56609. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  56610. u32 aCksum[2]; /* Checksum on the header content */
  56611. WalIndexHdr h1, h2; /* Two copies of the header content */
  56612. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  56613. /* The first page of the wal-index must be mapped at this point. */
  56614. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  56615. /* Read the header. This might happen concurrently with a write to the
  56616. ** same area of shared memory on a different CPU in a SMP,
  56617. ** meaning it is possible that an inconsistent snapshot is read
  56618. ** from the file. If this happens, return non-zero.
  56619. **
  56620. ** There are two copies of the header at the beginning of the wal-index.
  56621. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  56622. ** Memory barriers are used to prevent the compiler or the hardware from
  56623. ** reordering the reads and writes.
  56624. */
  56625. aHdr = walIndexHdr(pWal);
  56626. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  56627. walShmBarrier(pWal);
  56628. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  56629. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  56630. return 1; /* Dirty read */
  56631. }
  56632. if( h1.isInit==0 ){
  56633. return 1; /* Malformed header - probably all zeros */
  56634. }
  56635. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  56636. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  56637. return 1; /* Checksum does not match */
  56638. }
  56639. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  56640. *pChanged = 1;
  56641. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  56642. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  56643. testcase( pWal->szPage<=32768 );
  56644. testcase( pWal->szPage>=65536 );
  56645. }
  56646. /* The header was successfully read. Return zero. */
  56647. return 0;
  56648. }
  56649. /*
  56650. ** This is the value that walTryBeginRead returns when it needs to
  56651. ** be retried.
  56652. */
  56653. #define WAL_RETRY (-1)
  56654. /*
  56655. ** Read the wal-index header from the wal-index and into pWal->hdr.
  56656. ** If the wal-header appears to be corrupt, try to reconstruct the
  56657. ** wal-index from the WAL before returning.
  56658. **
  56659. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  56660. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  56661. ** to 0.
  56662. **
  56663. ** If the wal-index header is successfully read, return SQLITE_OK.
  56664. ** Otherwise an SQLite error code.
  56665. */
  56666. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  56667. int rc; /* Return code */
  56668. int badHdr; /* True if a header read failed */
  56669. volatile u32 *page0; /* Chunk of wal-index containing header */
  56670. /* Ensure that page 0 of the wal-index (the page that contains the
  56671. ** wal-index header) is mapped. Return early if an error occurs here.
  56672. */
  56673. assert( pChanged );
  56674. rc = walIndexPage(pWal, 0, &page0);
  56675. if( rc!=SQLITE_OK ){
  56676. assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
  56677. if( rc==SQLITE_READONLY_CANTINIT ){
  56678. /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
  56679. ** was openable but is not writable, and this thread is unable to
  56680. ** confirm that another write-capable connection has the shared-memory
  56681. ** open, and hence the content of the shared-memory is unreliable,
  56682. ** since the shared-memory might be inconsistent with the WAL file
  56683. ** and there is no writer on hand to fix it. */
  56684. assert( page0==0 );
  56685. assert( pWal->writeLock==0 );
  56686. assert( pWal->readOnly & WAL_SHM_RDONLY );
  56687. pWal->bShmUnreliable = 1;
  56688. pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
  56689. *pChanged = 1;
  56690. }else{
  56691. return rc; /* Any other non-OK return is just an error */
  56692. }
  56693. }else{
  56694. /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
  56695. ** is zero, which prevents the SHM from growing */
  56696. testcase( page0!=0 );
  56697. }
  56698. assert( page0!=0 || pWal->writeLock==0 );
  56699. /* If the first page of the wal-index has been mapped, try to read the
  56700. ** wal-index header immediately, without holding any lock. This usually
  56701. ** works, but may fail if the wal-index header is corrupt or currently
  56702. ** being modified by another thread or process.
  56703. */
  56704. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  56705. /* If the first attempt failed, it might have been due to a race
  56706. ** with a writer. So get a WRITE lock and try again.
  56707. */
  56708. assert( badHdr==0 || pWal->writeLock==0 );
  56709. if( badHdr ){
  56710. if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
  56711. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  56712. walUnlockShared(pWal, WAL_WRITE_LOCK);
  56713. rc = SQLITE_READONLY_RECOVERY;
  56714. }
  56715. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  56716. pWal->writeLock = 1;
  56717. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  56718. badHdr = walIndexTryHdr(pWal, pChanged);
  56719. if( badHdr ){
  56720. /* If the wal-index header is still malformed even while holding
  56721. ** a WRITE lock, it can only mean that the header is corrupted and
  56722. ** needs to be reconstructed. So run recovery to do exactly that.
  56723. */
  56724. rc = walIndexRecover(pWal);
  56725. *pChanged = 1;
  56726. }
  56727. }
  56728. pWal->writeLock = 0;
  56729. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  56730. }
  56731. }
  56732. /* If the header is read successfully, check the version number to make
  56733. ** sure the wal-index was not constructed with some future format that
  56734. ** this version of SQLite cannot understand.
  56735. */
  56736. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  56737. rc = SQLITE_CANTOPEN_BKPT;
  56738. }
  56739. if( pWal->bShmUnreliable ){
  56740. if( rc!=SQLITE_OK ){
  56741. walIndexClose(pWal, 0);
  56742. pWal->bShmUnreliable = 0;
  56743. assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
  56744. /* walIndexRecover() might have returned SHORT_READ if a concurrent
  56745. ** writer truncated the WAL out from under it. If that happens, it
  56746. ** indicates that a writer has fixed the SHM file for us, so retry */
  56747. if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
  56748. }
  56749. pWal->exclusiveMode = WAL_NORMAL_MODE;
  56750. }
  56751. return rc;
  56752. }
  56753. /*
  56754. ** Open a transaction in a connection where the shared-memory is read-only
  56755. ** and where we cannot verify that there is a separate write-capable connection
  56756. ** on hand to keep the shared-memory up-to-date with the WAL file.
  56757. **
  56758. ** This can happen, for example, when the shared-memory is implemented by
  56759. ** memory-mapping a *-shm file, where a prior writer has shut down and
  56760. ** left the *-shm file on disk, and now the present connection is trying
  56761. ** to use that database but lacks write permission on the *-shm file.
  56762. ** Other scenarios are also possible, depending on the VFS implementation.
  56763. **
  56764. ** Precondition:
  56765. **
  56766. ** The *-wal file has been read and an appropriate wal-index has been
  56767. ** constructed in pWal->apWiData[] using heap memory instead of shared
  56768. ** memory.
  56769. **
  56770. ** If this function returns SQLITE_OK, then the read transaction has
  56771. ** been successfully opened. In this case output variable (*pChanged)
  56772. ** is set to true before returning if the caller should discard the
  56773. ** contents of the page cache before proceeding. Or, if it returns
  56774. ** WAL_RETRY, then the heap memory wal-index has been discarded and
  56775. ** the caller should retry opening the read transaction from the
  56776. ** beginning (including attempting to map the *-shm file).
  56777. **
  56778. ** If an error occurs, an SQLite error code is returned.
  56779. */
  56780. static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
  56781. i64 szWal; /* Size of wal file on disk in bytes */
  56782. i64 iOffset; /* Current offset when reading wal file */
  56783. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  56784. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  56785. int szFrame; /* Number of bytes in buffer aFrame[] */
  56786. u8 *aData; /* Pointer to data part of aFrame buffer */
  56787. volatile void *pDummy; /* Dummy argument for xShmMap */
  56788. int rc; /* Return code */
  56789. u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */
  56790. assert( pWal->bShmUnreliable );
  56791. assert( pWal->readOnly & WAL_SHM_RDONLY );
  56792. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  56793. /* Take WAL_READ_LOCK(0). This has the effect of preventing any
  56794. ** writers from running a checkpoint, but does not stop them
  56795. ** from running recovery. */
  56796. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  56797. if( rc!=SQLITE_OK ){
  56798. if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
  56799. goto begin_unreliable_shm_out;
  56800. }
  56801. pWal->readLock = 0;
  56802. /* Check to see if a separate writer has attached to the shared-memory area,
  56803. ** thus making the shared-memory "reliable" again. Do this by invoking
  56804. ** the xShmMap() routine of the VFS and looking to see if the return
  56805. ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
  56806. **
  56807. ** If the shared-memory is now "reliable" return WAL_RETRY, which will
  56808. ** cause the heap-memory WAL-index to be discarded and the actual
  56809. ** shared memory to be used in its place.
  56810. **
  56811. ** This step is important because, even though this connection is holding
  56812. ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
  56813. ** have already checkpointed the WAL file and, while the current
  56814. ** is active, wrap the WAL and start overwriting frames that this
  56815. ** process wants to use.
  56816. **
  56817. ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
  56818. ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
  56819. ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
  56820. ** even if some external agent does a "chmod" to make the shared-memory
  56821. ** writable by us, until sqlite3OsShmUnmap() has been called.
  56822. ** This is a requirement on the VFS implementation.
  56823. */
  56824. rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
  56825. assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
  56826. if( rc!=SQLITE_READONLY_CANTINIT ){
  56827. rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
  56828. goto begin_unreliable_shm_out;
  56829. }
  56830. /* We reach this point only if the real shared-memory is still unreliable.
  56831. ** Assume the in-memory WAL-index substitute is correct and load it
  56832. ** into pWal->hdr.
  56833. */
  56834. memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
  56835. /* Make sure some writer hasn't come in and changed the WAL file out
  56836. ** from under us, then disconnected, while we were not looking.
  56837. */
  56838. rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
  56839. if( rc!=SQLITE_OK ){
  56840. goto begin_unreliable_shm_out;
  56841. }
  56842. if( szWal<WAL_HDRSIZE ){
  56843. /* If the wal file is too small to contain a wal-header and the
  56844. ** wal-index header has mxFrame==0, then it must be safe to proceed
  56845. ** reading the database file only. However, the page cache cannot
  56846. ** be trusted, as a read/write connection may have connected, written
  56847. ** the db, run a checkpoint, truncated the wal file and disconnected
  56848. ** since this client's last read transaction. */
  56849. *pChanged = 1;
  56850. rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
  56851. goto begin_unreliable_shm_out;
  56852. }
  56853. /* Check the salt keys at the start of the wal file still match. */
  56854. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  56855. if( rc!=SQLITE_OK ){
  56856. goto begin_unreliable_shm_out;
  56857. }
  56858. if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
  56859. /* Some writer has wrapped the WAL file while we were not looking.
  56860. ** Return WAL_RETRY which will cause the in-memory WAL-index to be
  56861. ** rebuilt. */
  56862. rc = WAL_RETRY;
  56863. goto begin_unreliable_shm_out;
  56864. }
  56865. /* Allocate a buffer to read frames into */
  56866. szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE;
  56867. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  56868. if( aFrame==0 ){
  56869. rc = SQLITE_NOMEM_BKPT;
  56870. goto begin_unreliable_shm_out;
  56871. }
  56872. aData = &aFrame[WAL_FRAME_HDRSIZE];
  56873. /* Check to see if a complete transaction has been appended to the
  56874. ** wal file since the heap-memory wal-index was created. If so, the
  56875. ** heap-memory wal-index is discarded and WAL_RETRY returned to
  56876. ** the caller. */
  56877. aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
  56878. aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
  56879. for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage);
  56880. iOffset+szFrame<=szWal;
  56881. iOffset+=szFrame
  56882. ){
  56883. u32 pgno; /* Database page number for frame */
  56884. u32 nTruncate; /* dbsize field from frame header */
  56885. /* Read and decode the next log frame. */
  56886. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  56887. if( rc!=SQLITE_OK ) break;
  56888. if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
  56889. /* If nTruncate is non-zero, then a complete transaction has been
  56890. ** appended to this wal file. Set rc to WAL_RETRY and break out of
  56891. ** the loop. */
  56892. if( nTruncate ){
  56893. rc = WAL_RETRY;
  56894. break;
  56895. }
  56896. }
  56897. pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
  56898. pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
  56899. begin_unreliable_shm_out:
  56900. sqlite3_free(aFrame);
  56901. if( rc!=SQLITE_OK ){
  56902. int i;
  56903. for(i=0; i<pWal->nWiData; i++){
  56904. sqlite3_free((void*)pWal->apWiData[i]);
  56905. pWal->apWiData[i] = 0;
  56906. }
  56907. pWal->bShmUnreliable = 0;
  56908. sqlite3WalEndReadTransaction(pWal);
  56909. *pChanged = 1;
  56910. }
  56911. return rc;
  56912. }
  56913. /*
  56914. ** Attempt to start a read transaction. This might fail due to a race or
  56915. ** other transient condition. When that happens, it returns WAL_RETRY to
  56916. ** indicate to the caller that it is safe to retry immediately.
  56917. **
  56918. ** On success return SQLITE_OK. On a permanent failure (such an
  56919. ** I/O error or an SQLITE_BUSY because another process is running
  56920. ** recovery) return a positive error code.
  56921. **
  56922. ** The useWal parameter is true to force the use of the WAL and disable
  56923. ** the case where the WAL is bypassed because it has been completely
  56924. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  56925. ** to make a copy of the wal-index header into pWal->hdr. If the
  56926. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  56927. ** to the caller that the local page cache is obsolete and needs to be
  56928. ** flushed.) When useWal==1, the wal-index header is assumed to already
  56929. ** be loaded and the pChanged parameter is unused.
  56930. **
  56931. ** The caller must set the cnt parameter to the number of prior calls to
  56932. ** this routine during the current read attempt that returned WAL_RETRY.
  56933. ** This routine will start taking more aggressive measures to clear the
  56934. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  56935. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  56936. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  56937. ** and is not honoring the locking protocol. There is a vanishingly small
  56938. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  56939. ** bad luck when there is lots of contention for the wal-index, but that
  56940. ** possibility is so small that it can be safely neglected, we believe.
  56941. **
  56942. ** On success, this routine obtains a read lock on
  56943. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  56944. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  56945. ** that means the Wal does not hold any read lock. The reader must not
  56946. ** access any database page that is modified by a WAL frame up to and
  56947. ** including frame number aReadMark[pWal->readLock]. The reader will
  56948. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  56949. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  56950. ** completely and get all content directly from the database file.
  56951. ** If the useWal parameter is 1 then the WAL will never be ignored and
  56952. ** this routine will always set pWal->readLock>0 on success.
  56953. ** When the read transaction is completed, the caller must release the
  56954. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  56955. **
  56956. ** This routine uses the nBackfill and aReadMark[] fields of the header
  56957. ** to select a particular WAL_READ_LOCK() that strives to let the
  56958. ** checkpoint process do as much work as possible. This routine might
  56959. ** update values of the aReadMark[] array in the header, but if it does
  56960. ** so it takes care to hold an exclusive lock on the corresponding
  56961. ** WAL_READ_LOCK() while changing values.
  56962. */
  56963. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  56964. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  56965. u32 mxReadMark; /* Largest aReadMark[] value */
  56966. int mxI; /* Index of largest aReadMark[] value */
  56967. int i; /* Loop counter */
  56968. int rc = SQLITE_OK; /* Return code */
  56969. u32 mxFrame; /* Wal frame to lock to */
  56970. assert( pWal->readLock<0 ); /* Not currently locked */
  56971. /* useWal may only be set for read/write connections */
  56972. assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
  56973. /* Take steps to avoid spinning forever if there is a protocol error.
  56974. **
  56975. ** Circumstances that cause a RETRY should only last for the briefest
  56976. ** instances of time. No I/O or other system calls are done while the
  56977. ** locks are held, so the locks should not be held for very long. But
  56978. ** if we are unlucky, another process that is holding a lock might get
  56979. ** paged out or take a page-fault that is time-consuming to resolve,
  56980. ** during the few nanoseconds that it is holding the lock. In that case,
  56981. ** it might take longer than normal for the lock to free.
  56982. **
  56983. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  56984. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  56985. ** is more of a scheduler yield than an actual delay. But on the 10th
  56986. ** an subsequent retries, the delays start becoming longer and longer,
  56987. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  56988. ** The total delay time before giving up is less than 10 seconds.
  56989. */
  56990. if( cnt>5 ){
  56991. int nDelay = 1; /* Pause time in microseconds */
  56992. if( cnt>100 ){
  56993. VVA_ONLY( pWal->lockError = 1; )
  56994. return SQLITE_PROTOCOL;
  56995. }
  56996. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  56997. sqlite3OsSleep(pWal->pVfs, nDelay);
  56998. }
  56999. if( !useWal ){
  57000. assert( rc==SQLITE_OK );
  57001. if( pWal->bShmUnreliable==0 ){
  57002. rc = walIndexReadHdr(pWal, pChanged);
  57003. }
  57004. if( rc==SQLITE_BUSY ){
  57005. /* If there is not a recovery running in another thread or process
  57006. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  57007. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  57008. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  57009. ** would be technically correct. But the race is benign since with
  57010. ** WAL_RETRY this routine will be called again and will probably be
  57011. ** right on the second iteration.
  57012. */
  57013. if( pWal->apWiData[0]==0 ){
  57014. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  57015. ** We assume this is a transient condition, so return WAL_RETRY. The
  57016. ** xShmMap() implementation used by the default unix and win32 VFS
  57017. ** modules may return SQLITE_BUSY due to a race condition in the
  57018. ** code that determines whether or not the shared-memory region
  57019. ** must be zeroed before the requested page is returned.
  57020. */
  57021. rc = WAL_RETRY;
  57022. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  57023. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  57024. rc = WAL_RETRY;
  57025. }else if( rc==SQLITE_BUSY ){
  57026. rc = SQLITE_BUSY_RECOVERY;
  57027. }
  57028. }
  57029. if( rc!=SQLITE_OK ){
  57030. return rc;
  57031. }
  57032. else if( pWal->bShmUnreliable ){
  57033. return walBeginShmUnreliable(pWal, pChanged);
  57034. }
  57035. }
  57036. assert( pWal->nWiData>0 );
  57037. assert( pWal->apWiData[0]!=0 );
  57038. pInfo = walCkptInfo(pWal);
  57039. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
  57040. #ifdef SQLITE_ENABLE_SNAPSHOT
  57041. && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
  57042. #endif
  57043. ){
  57044. /* The WAL has been completely backfilled (or it is empty).
  57045. ** and can be safely ignored.
  57046. */
  57047. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  57048. walShmBarrier(pWal);
  57049. if( rc==SQLITE_OK ){
  57050. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  57051. /* It is not safe to allow the reader to continue here if frames
  57052. ** may have been appended to the log before READ_LOCK(0) was obtained.
  57053. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  57054. ** which implies that the database file contains a trustworthy
  57055. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  57056. ** happening, this is usually correct.
  57057. **
  57058. ** However, if frames have been appended to the log (or if the log
  57059. ** is wrapped and written for that matter) before the READ_LOCK(0)
  57060. ** is obtained, that is not necessarily true. A checkpointer may
  57061. ** have started to backfill the appended frames but crashed before
  57062. ** it finished. Leaving a corrupt image in the database file.
  57063. */
  57064. walUnlockShared(pWal, WAL_READ_LOCK(0));
  57065. return WAL_RETRY;
  57066. }
  57067. pWal->readLock = 0;
  57068. return SQLITE_OK;
  57069. }else if( rc!=SQLITE_BUSY ){
  57070. return rc;
  57071. }
  57072. }
  57073. /* If we get this far, it means that the reader will want to use
  57074. ** the WAL to get at content from recent commits. The job now is
  57075. ** to select one of the aReadMark[] entries that is closest to
  57076. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  57077. */
  57078. mxReadMark = 0;
  57079. mxI = 0;
  57080. mxFrame = pWal->hdr.mxFrame;
  57081. #ifdef SQLITE_ENABLE_SNAPSHOT
  57082. if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
  57083. mxFrame = pWal->pSnapshot->mxFrame;
  57084. }
  57085. #endif
  57086. for(i=1; i<WAL_NREADER; i++){
  57087. u32 thisMark = AtomicLoad(pInfo->aReadMark+i);
  57088. if( mxReadMark<=thisMark && thisMark<=mxFrame ){
  57089. assert( thisMark!=READMARK_NOT_USED );
  57090. mxReadMark = thisMark;
  57091. mxI = i;
  57092. }
  57093. }
  57094. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  57095. && (mxReadMark<mxFrame || mxI==0)
  57096. ){
  57097. for(i=1; i<WAL_NREADER; i++){
  57098. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  57099. if( rc==SQLITE_OK ){
  57100. mxReadMark = AtomicStore(pInfo->aReadMark+i,mxFrame);
  57101. mxI = i;
  57102. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  57103. break;
  57104. }else if( rc!=SQLITE_BUSY ){
  57105. return rc;
  57106. }
  57107. }
  57108. }
  57109. if( mxI==0 ){
  57110. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  57111. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
  57112. }
  57113. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  57114. if( rc ){
  57115. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  57116. }
  57117. /* Now that the read-lock has been obtained, check that neither the
  57118. ** value in the aReadMark[] array or the contents of the wal-index
  57119. ** header have changed.
  57120. **
  57121. ** It is necessary to check that the wal-index header did not change
  57122. ** between the time it was read and when the shared-lock was obtained
  57123. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  57124. ** that the log file may have been wrapped by a writer, or that frames
  57125. ** that occur later in the log than pWal->hdr.mxFrame may have been
  57126. ** copied into the database by a checkpointer. If either of these things
  57127. ** happened, then reading the database with the current value of
  57128. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  57129. ** instead.
  57130. **
  57131. ** Before checking that the live wal-index header has not changed
  57132. ** since it was read, set Wal.minFrame to the first frame in the wal
  57133. ** file that has not yet been checkpointed. This client will not need
  57134. ** to read any frames earlier than minFrame from the wal file - they
  57135. ** can be safely read directly from the database file.
  57136. **
  57137. ** Because a ShmBarrier() call is made between taking the copy of
  57138. ** nBackfill and checking that the wal-header in shared-memory still
  57139. ** matches the one cached in pWal->hdr, it is guaranteed that the
  57140. ** checkpointer that set nBackfill was not working with a wal-index
  57141. ** header newer than that cached in pWal->hdr. If it were, that could
  57142. ** cause a problem. The checkpointer could omit to checkpoint
  57143. ** a version of page X that lies before pWal->minFrame (call that version
  57144. ** A) on the basis that there is a newer version (version B) of the same
  57145. ** page later in the wal file. But if version B happens to like past
  57146. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  57147. ** that it can read version A from the database file. However, since
  57148. ** we can guarantee that the checkpointer that set nBackfill could not
  57149. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  57150. */
  57151. pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1;
  57152. walShmBarrier(pWal);
  57153. if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
  57154. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  57155. ){
  57156. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  57157. return WAL_RETRY;
  57158. }else{
  57159. assert( mxReadMark<=pWal->hdr.mxFrame );
  57160. pWal->readLock = (i16)mxI;
  57161. }
  57162. return rc;
  57163. }
  57164. #ifdef SQLITE_ENABLE_SNAPSHOT
  57165. /*
  57166. ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
  57167. ** variable so that older snapshots can be accessed. To do this, loop
  57168. ** through all wal frames from nBackfillAttempted to (nBackfill+1),
  57169. ** comparing their content to the corresponding page with the database
  57170. ** file, if any. Set nBackfillAttempted to the frame number of the
  57171. ** first frame for which the wal file content matches the db file.
  57172. **
  57173. ** This is only really safe if the file-system is such that any page
  57174. ** writes made by earlier checkpointers were atomic operations, which
  57175. ** is not always true. It is also possible that nBackfillAttempted
  57176. ** may be left set to a value larger than expected, if a wal frame
  57177. ** contains content that duplicate of an earlier version of the same
  57178. ** page.
  57179. **
  57180. ** SQLITE_OK is returned if successful, or an SQLite error code if an
  57181. ** error occurs. It is not an error if nBackfillAttempted cannot be
  57182. ** decreased at all.
  57183. */
  57184. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
  57185. int rc;
  57186. assert( pWal->readLock>=0 );
  57187. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  57188. if( rc==SQLITE_OK ){
  57189. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  57190. int szPage = (int)pWal->szPage;
  57191. i64 szDb; /* Size of db file in bytes */
  57192. rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
  57193. if( rc==SQLITE_OK ){
  57194. void *pBuf1 = sqlite3_malloc(szPage);
  57195. void *pBuf2 = sqlite3_malloc(szPage);
  57196. if( pBuf1==0 || pBuf2==0 ){
  57197. rc = SQLITE_NOMEM;
  57198. }else{
  57199. u32 i = pInfo->nBackfillAttempted;
  57200. for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
  57201. WalHashLoc sLoc; /* Hash table location */
  57202. u32 pgno; /* Page number in db file */
  57203. i64 iDbOff; /* Offset of db file entry */
  57204. i64 iWalOff; /* Offset of wal file entry */
  57205. rc = walHashGet(pWal, walFramePage(i), &sLoc);
  57206. if( rc!=SQLITE_OK ) break;
  57207. pgno = sLoc.aPgno[i-sLoc.iZero];
  57208. iDbOff = (i64)(pgno-1) * szPage;
  57209. if( iDbOff+szPage<=szDb ){
  57210. iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
  57211. rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
  57212. if( rc==SQLITE_OK ){
  57213. rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
  57214. }
  57215. if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
  57216. break;
  57217. }
  57218. }
  57219. pInfo->nBackfillAttempted = i-1;
  57220. }
  57221. }
  57222. sqlite3_free(pBuf1);
  57223. sqlite3_free(pBuf2);
  57224. }
  57225. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  57226. }
  57227. return rc;
  57228. }
  57229. #endif /* SQLITE_ENABLE_SNAPSHOT */
  57230. /*
  57231. ** Begin a read transaction on the database.
  57232. **
  57233. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  57234. ** it takes a snapshot of the state of the WAL and wal-index for the current
  57235. ** instant in time. The current thread will continue to use this snapshot.
  57236. ** Other threads might append new content to the WAL and wal-index but
  57237. ** that extra content is ignored by the current thread.
  57238. **
  57239. ** If the database contents have changes since the previous read
  57240. ** transaction, then *pChanged is set to 1 before returning. The
  57241. ** Pager layer will use this to know that its cache is stale and
  57242. ** needs to be flushed.
  57243. */
  57244. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  57245. int rc; /* Return code */
  57246. int cnt = 0; /* Number of TryBeginRead attempts */
  57247. #ifdef SQLITE_ENABLE_SNAPSHOT
  57248. int bChanged = 0;
  57249. WalIndexHdr *pSnapshot = pWal->pSnapshot;
  57250. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  57251. bChanged = 1;
  57252. }
  57253. #endif
  57254. do{
  57255. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  57256. }while( rc==WAL_RETRY );
  57257. testcase( (rc&0xff)==SQLITE_BUSY );
  57258. testcase( (rc&0xff)==SQLITE_IOERR );
  57259. testcase( rc==SQLITE_PROTOCOL );
  57260. testcase( rc==SQLITE_OK );
  57261. #ifdef SQLITE_ENABLE_SNAPSHOT
  57262. if( rc==SQLITE_OK ){
  57263. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  57264. /* At this point the client has a lock on an aReadMark[] slot holding
  57265. ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
  57266. ** is populated with the wal-index header corresponding to the head
  57267. ** of the wal file. Verify that pSnapshot is still valid before
  57268. ** continuing. Reasons why pSnapshot might no longer be valid:
  57269. **
  57270. ** (1) The WAL file has been reset since the snapshot was taken.
  57271. ** In this case, the salt will have changed.
  57272. **
  57273. ** (2) A checkpoint as been attempted that wrote frames past
  57274. ** pSnapshot->mxFrame into the database file. Note that the
  57275. ** checkpoint need not have completed for this to cause problems.
  57276. */
  57277. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  57278. assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
  57279. assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
  57280. /* It is possible that there is a checkpointer thread running
  57281. ** concurrent with this code. If this is the case, it may be that the
  57282. ** checkpointer has already determined that it will checkpoint
  57283. ** snapshot X, where X is later in the wal file than pSnapshot, but
  57284. ** has not yet set the pInfo->nBackfillAttempted variable to indicate
  57285. ** its intent. To avoid the race condition this leads to, ensure that
  57286. ** there is no checkpointer process by taking a shared CKPT lock
  57287. ** before checking pInfo->nBackfillAttempted.
  57288. **
  57289. ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
  57290. ** this already?
  57291. */
  57292. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  57293. if( rc==SQLITE_OK ){
  57294. /* Check that the wal file has not been wrapped. Assuming that it has
  57295. ** not, also check that no checkpointer has attempted to checkpoint any
  57296. ** frames beyond pSnapshot->mxFrame. If either of these conditions are
  57297. ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
  57298. ** with *pSnapshot and set *pChanged as appropriate for opening the
  57299. ** snapshot. */
  57300. if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  57301. && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
  57302. ){
  57303. assert( pWal->readLock>0 );
  57304. memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
  57305. *pChanged = bChanged;
  57306. }else{
  57307. rc = SQLITE_ERROR_SNAPSHOT;
  57308. }
  57309. /* Release the shared CKPT lock obtained above. */
  57310. walUnlockShared(pWal, WAL_CKPT_LOCK);
  57311. pWal->minFrame = 1;
  57312. }
  57313. if( rc!=SQLITE_OK ){
  57314. sqlite3WalEndReadTransaction(pWal);
  57315. }
  57316. }
  57317. }
  57318. #endif
  57319. return rc;
  57320. }
  57321. /*
  57322. ** Finish with a read transaction. All this does is release the
  57323. ** read-lock.
  57324. */
  57325. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  57326. sqlite3WalEndWriteTransaction(pWal);
  57327. if( pWal->readLock>=0 ){
  57328. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  57329. pWal->readLock = -1;
  57330. }
  57331. }
  57332. /*
  57333. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  57334. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  57335. ** to zero.
  57336. **
  57337. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  57338. ** error does occur, the final value of *piRead is undefined.
  57339. */
  57340. SQLITE_PRIVATE int sqlite3WalFindFrame(
  57341. Wal *pWal, /* WAL handle */
  57342. Pgno pgno, /* Database page number to read data for */
  57343. u32 *piRead /* OUT: Frame number (or zero) */
  57344. ){
  57345. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  57346. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  57347. int iHash; /* Used to loop through N hash tables */
  57348. int iMinHash;
  57349. /* This routine is only be called from within a read transaction. */
  57350. assert( pWal->readLock>=0 || pWal->lockError );
  57351. /* If the "last page" field of the wal-index header snapshot is 0, then
  57352. ** no data will be read from the wal under any circumstances. Return early
  57353. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  57354. ** then the WAL is ignored by the reader so return early, as if the
  57355. ** WAL were empty.
  57356. */
  57357. if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
  57358. *piRead = 0;
  57359. return SQLITE_OK;
  57360. }
  57361. /* Search the hash table or tables for an entry matching page number
  57362. ** pgno. Each iteration of the following for() loop searches one
  57363. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  57364. **
  57365. ** This code might run concurrently to the code in walIndexAppend()
  57366. ** that adds entries to the wal-index (and possibly to this hash
  57367. ** table). This means the value just read from the hash
  57368. ** slot (aHash[iKey]) may have been added before or after the
  57369. ** current read transaction was opened. Values added after the
  57370. ** read transaction was opened may have been written incorrectly -
  57371. ** i.e. these slots may contain garbage data. However, we assume
  57372. ** that any slots written before the current read transaction was
  57373. ** opened remain unmodified.
  57374. **
  57375. ** For the reasons above, the if(...) condition featured in the inner
  57376. ** loop of the following block is more stringent that would be required
  57377. ** if we had exclusive access to the hash-table:
  57378. **
  57379. ** (aPgno[iFrame]==pgno):
  57380. ** This condition filters out normal hash-table collisions.
  57381. **
  57382. ** (iFrame<=iLast):
  57383. ** This condition filters out entries that were added to the hash
  57384. ** table after the current read-transaction had started.
  57385. */
  57386. iMinHash = walFramePage(pWal->minFrame);
  57387. for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
  57388. WalHashLoc sLoc; /* Hash table location */
  57389. int iKey; /* Hash slot index */
  57390. int nCollide; /* Number of hash collisions remaining */
  57391. int rc; /* Error code */
  57392. rc = walHashGet(pWal, iHash, &sLoc);
  57393. if( rc!=SQLITE_OK ){
  57394. return rc;
  57395. }
  57396. nCollide = HASHTABLE_NSLOT;
  57397. for(iKey=walHash(pgno); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
  57398. u32 iFrame = sLoc.aHash[iKey] + sLoc.iZero;
  57399. if( iFrame<=iLast && iFrame>=pWal->minFrame
  57400. && sLoc.aPgno[sLoc.aHash[iKey]]==pgno ){
  57401. assert( iFrame>iRead || CORRUPT_DB );
  57402. iRead = iFrame;
  57403. }
  57404. if( (nCollide--)==0 ){
  57405. return SQLITE_CORRUPT_BKPT;
  57406. }
  57407. }
  57408. if( iRead ) break;
  57409. }
  57410. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  57411. /* If expensive assert() statements are available, do a linear search
  57412. ** of the wal-index file content. Make sure the results agree with the
  57413. ** result obtained using the hash indexes above. */
  57414. {
  57415. u32 iRead2 = 0;
  57416. u32 iTest;
  57417. assert( pWal->bShmUnreliable || pWal->minFrame>0 );
  57418. for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
  57419. if( walFramePgno(pWal, iTest)==pgno ){
  57420. iRead2 = iTest;
  57421. break;
  57422. }
  57423. }
  57424. assert( iRead==iRead2 );
  57425. }
  57426. #endif
  57427. *piRead = iRead;
  57428. return SQLITE_OK;
  57429. }
  57430. /*
  57431. ** Read the contents of frame iRead from the wal file into buffer pOut
  57432. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  57433. ** error code otherwise.
  57434. */
  57435. SQLITE_PRIVATE int sqlite3WalReadFrame(
  57436. Wal *pWal, /* WAL handle */
  57437. u32 iRead, /* Frame to read */
  57438. int nOut, /* Size of buffer pOut in bytes */
  57439. u8 *pOut /* Buffer to write page data to */
  57440. ){
  57441. int sz;
  57442. i64 iOffset;
  57443. sz = pWal->hdr.szPage;
  57444. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  57445. testcase( sz<=32768 );
  57446. testcase( sz>=65536 );
  57447. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  57448. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  57449. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  57450. }
  57451. /*
  57452. ** Return the size of the database in pages (or zero, if unknown).
  57453. */
  57454. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  57455. if( pWal && ALWAYS(pWal->readLock>=0) ){
  57456. return pWal->hdr.nPage;
  57457. }
  57458. return 0;
  57459. }
  57460. /*
  57461. ** This function starts a write transaction on the WAL.
  57462. **
  57463. ** A read transaction must have already been started by a prior call
  57464. ** to sqlite3WalBeginReadTransaction().
  57465. **
  57466. ** If another thread or process has written into the database since
  57467. ** the read transaction was started, then it is not possible for this
  57468. ** thread to write as doing so would cause a fork. So this routine
  57469. ** returns SQLITE_BUSY in that case and no write transaction is started.
  57470. **
  57471. ** There can only be a single writer active at a time.
  57472. */
  57473. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  57474. int rc;
  57475. /* Cannot start a write transaction without first holding a read
  57476. ** transaction. */
  57477. assert( pWal->readLock>=0 );
  57478. assert( pWal->writeLock==0 && pWal->iReCksum==0 );
  57479. if( pWal->readOnly ){
  57480. return SQLITE_READONLY;
  57481. }
  57482. /* Only one writer allowed at a time. Get the write lock. Return
  57483. ** SQLITE_BUSY if unable.
  57484. */
  57485. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57486. if( rc ){
  57487. return rc;
  57488. }
  57489. pWal->writeLock = 1;
  57490. /* If another connection has written to the database file since the
  57491. ** time the read transaction on this connection was started, then
  57492. ** the write is disallowed.
  57493. */
  57494. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  57495. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57496. pWal->writeLock = 0;
  57497. rc = SQLITE_BUSY_SNAPSHOT;
  57498. }
  57499. return rc;
  57500. }
  57501. /*
  57502. ** End a write transaction. The commit has already been done. This
  57503. ** routine merely releases the lock.
  57504. */
  57505. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  57506. if( pWal->writeLock ){
  57507. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57508. pWal->writeLock = 0;
  57509. pWal->iReCksum = 0;
  57510. pWal->truncateOnCommit = 0;
  57511. }
  57512. return SQLITE_OK;
  57513. }
  57514. /*
  57515. ** If any data has been written (but not committed) to the log file, this
  57516. ** function moves the write-pointer back to the start of the transaction.
  57517. **
  57518. ** Additionally, the callback function is invoked for each frame written
  57519. ** to the WAL since the start of the transaction. If the callback returns
  57520. ** other than SQLITE_OK, it is not invoked again and the error code is
  57521. ** returned to the caller.
  57522. **
  57523. ** Otherwise, if the callback function does not return an error, this
  57524. ** function returns SQLITE_OK.
  57525. */
  57526. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  57527. int rc = SQLITE_OK;
  57528. if( ALWAYS(pWal->writeLock) ){
  57529. Pgno iMax = pWal->hdr.mxFrame;
  57530. Pgno iFrame;
  57531. /* Restore the clients cache of the wal-index header to the state it
  57532. ** was in before the client began writing to the database.
  57533. */
  57534. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  57535. for(iFrame=pWal->hdr.mxFrame+1;
  57536. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  57537. iFrame++
  57538. ){
  57539. /* This call cannot fail. Unless the page for which the page number
  57540. ** is passed as the second argument is (a) in the cache and
  57541. ** (b) has an outstanding reference, then xUndo is either a no-op
  57542. ** (if (a) is false) or simply expels the page from the cache (if (b)
  57543. ** is false).
  57544. **
  57545. ** If the upper layer is doing a rollback, it is guaranteed that there
  57546. ** are no outstanding references to any page other than page 1. And
  57547. ** page 1 is never written to the log until the transaction is
  57548. ** committed. As a result, the call to xUndo may not fail.
  57549. */
  57550. assert( walFramePgno(pWal, iFrame)!=1 );
  57551. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  57552. }
  57553. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  57554. }
  57555. return rc;
  57556. }
  57557. /*
  57558. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  57559. ** values. This function populates the array with values required to
  57560. ** "rollback" the write position of the WAL handle back to the current
  57561. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  57562. */
  57563. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  57564. assert( pWal->writeLock );
  57565. aWalData[0] = pWal->hdr.mxFrame;
  57566. aWalData[1] = pWal->hdr.aFrameCksum[0];
  57567. aWalData[2] = pWal->hdr.aFrameCksum[1];
  57568. aWalData[3] = pWal->nCkpt;
  57569. }
  57570. /*
  57571. ** Move the write position of the WAL back to the point identified by
  57572. ** the values in the aWalData[] array. aWalData must point to an array
  57573. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  57574. ** by a call to WalSavepoint().
  57575. */
  57576. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  57577. int rc = SQLITE_OK;
  57578. assert( pWal->writeLock );
  57579. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  57580. if( aWalData[3]!=pWal->nCkpt ){
  57581. /* This savepoint was opened immediately after the write-transaction
  57582. ** was started. Right after that, the writer decided to wrap around
  57583. ** to the start of the log. Update the savepoint values to match.
  57584. */
  57585. aWalData[0] = 0;
  57586. aWalData[3] = pWal->nCkpt;
  57587. }
  57588. if( aWalData[0]<pWal->hdr.mxFrame ){
  57589. pWal->hdr.mxFrame = aWalData[0];
  57590. pWal->hdr.aFrameCksum[0] = aWalData[1];
  57591. pWal->hdr.aFrameCksum[1] = aWalData[2];
  57592. walCleanupHash(pWal);
  57593. }
  57594. return rc;
  57595. }
  57596. /*
  57597. ** This function is called just before writing a set of frames to the log
  57598. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  57599. ** to the current log file, it is possible to overwrite the start of the
  57600. ** existing log file with the new frames (i.e. "reset" the log). If so,
  57601. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  57602. ** unchanged.
  57603. **
  57604. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  57605. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  57606. ** if an error occurs.
  57607. */
  57608. static int walRestartLog(Wal *pWal){
  57609. int rc = SQLITE_OK;
  57610. int cnt;
  57611. if( pWal->readLock==0 ){
  57612. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  57613. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  57614. if( pInfo->nBackfill>0 ){
  57615. u32 salt1;
  57616. sqlite3_randomness(4, &salt1);
  57617. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  57618. if( rc==SQLITE_OK ){
  57619. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  57620. ** readers are currently using the WAL), then the transactions
  57621. ** frames will overwrite the start of the existing log. Update the
  57622. ** wal-index header to reflect this.
  57623. **
  57624. ** In theory it would be Ok to update the cache of the header only
  57625. ** at this point. But updating the actual wal-index header is also
  57626. ** safe and means there is no special case for sqlite3WalUndo()
  57627. ** to handle if this transaction is rolled back. */
  57628. walRestartHdr(pWal, salt1);
  57629. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  57630. }else if( rc!=SQLITE_BUSY ){
  57631. return rc;
  57632. }
  57633. }
  57634. walUnlockShared(pWal, WAL_READ_LOCK(0));
  57635. pWal->readLock = -1;
  57636. cnt = 0;
  57637. do{
  57638. int notUsed;
  57639. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  57640. }while( rc==WAL_RETRY );
  57641. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  57642. testcase( (rc&0xff)==SQLITE_IOERR );
  57643. testcase( rc==SQLITE_PROTOCOL );
  57644. testcase( rc==SQLITE_OK );
  57645. }
  57646. return rc;
  57647. }
  57648. /*
  57649. ** Information about the current state of the WAL file and where
  57650. ** the next fsync should occur - passed from sqlite3WalFrames() into
  57651. ** walWriteToLog().
  57652. */
  57653. typedef struct WalWriter {
  57654. Wal *pWal; /* The complete WAL information */
  57655. sqlite3_file *pFd; /* The WAL file to which we write */
  57656. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  57657. int syncFlags; /* Flags for the fsync */
  57658. int szPage; /* Size of one page */
  57659. } WalWriter;
  57660. /*
  57661. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  57662. ** Do a sync when crossing the p->iSyncPoint boundary.
  57663. **
  57664. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  57665. ** first write the part before iSyncPoint, then sync, then write the
  57666. ** rest.
  57667. */
  57668. static int walWriteToLog(
  57669. WalWriter *p, /* WAL to write to */
  57670. void *pContent, /* Content to be written */
  57671. int iAmt, /* Number of bytes to write */
  57672. sqlite3_int64 iOffset /* Start writing at this offset */
  57673. ){
  57674. int rc;
  57675. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  57676. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  57677. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  57678. if( rc ) return rc;
  57679. iOffset += iFirstAmt;
  57680. iAmt -= iFirstAmt;
  57681. pContent = (void*)(iFirstAmt + (char*)pContent);
  57682. assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
  57683. rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
  57684. if( iAmt==0 || rc ) return rc;
  57685. }
  57686. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  57687. return rc;
  57688. }
  57689. /*
  57690. ** Write out a single frame of the WAL
  57691. */
  57692. static int walWriteOneFrame(
  57693. WalWriter *p, /* Where to write the frame */
  57694. PgHdr *pPage, /* The page of the frame to be written */
  57695. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  57696. sqlite3_int64 iOffset /* Byte offset at which to write */
  57697. ){
  57698. int rc; /* Result code from subfunctions */
  57699. void *pData; /* Data actually written */
  57700. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  57701. #if defined(SQLITE_HAS_CODEC)
  57702. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
  57703. #else
  57704. pData = pPage->pData;
  57705. #endif
  57706. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  57707. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  57708. if( rc ) return rc;
  57709. /* Write the page data */
  57710. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  57711. return rc;
  57712. }
  57713. /*
  57714. ** This function is called as part of committing a transaction within which
  57715. ** one or more frames have been overwritten. It updates the checksums for
  57716. ** all frames written to the wal file by the current transaction starting
  57717. ** with the earliest to have been overwritten.
  57718. **
  57719. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  57720. */
  57721. static int walRewriteChecksums(Wal *pWal, u32 iLast){
  57722. const int szPage = pWal->szPage;/* Database page size */
  57723. int rc = SQLITE_OK; /* Return code */
  57724. u8 *aBuf; /* Buffer to load data from wal file into */
  57725. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
  57726. u32 iRead; /* Next frame to read from wal file */
  57727. i64 iCksumOff;
  57728. aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
  57729. if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
  57730. /* Find the checksum values to use as input for the recalculating the
  57731. ** first checksum. If the first frame is frame 1 (implying that the current
  57732. ** transaction restarted the wal file), these values must be read from the
  57733. ** wal-file header. Otherwise, read them from the frame header of the
  57734. ** previous frame. */
  57735. assert( pWal->iReCksum>0 );
  57736. if( pWal->iReCksum==1 ){
  57737. iCksumOff = 24;
  57738. }else{
  57739. iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
  57740. }
  57741. rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  57742. pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
  57743. pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
  57744. iRead = pWal->iReCksum;
  57745. pWal->iReCksum = 0;
  57746. for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
  57747. i64 iOff = walFrameOffset(iRead, szPage);
  57748. rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
  57749. if( rc==SQLITE_OK ){
  57750. u32 iPgno, nDbSize;
  57751. iPgno = sqlite3Get4byte(aBuf);
  57752. nDbSize = sqlite3Get4byte(&aBuf[4]);
  57753. walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
  57754. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
  57755. }
  57756. }
  57757. sqlite3_free(aBuf);
  57758. return rc;
  57759. }
  57760. /*
  57761. ** Write a set of frames to the log. The caller must hold the write-lock
  57762. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  57763. */
  57764. SQLITE_PRIVATE int sqlite3WalFrames(
  57765. Wal *pWal, /* Wal handle to write to */
  57766. int szPage, /* Database page-size in bytes */
  57767. PgHdr *pList, /* List of dirty pages to write */
  57768. Pgno nTruncate, /* Database size after this commit */
  57769. int isCommit, /* True if this is a commit */
  57770. int sync_flags /* Flags to pass to OsSync() (or 0) */
  57771. ){
  57772. int rc; /* Used to catch return codes */
  57773. u32 iFrame; /* Next frame address */
  57774. PgHdr *p; /* Iterator to run through pList with. */
  57775. PgHdr *pLast = 0; /* Last frame in list */
  57776. int nExtra = 0; /* Number of extra copies of last page */
  57777. int szFrame; /* The size of a single frame */
  57778. i64 iOffset; /* Next byte to write in WAL file */
  57779. WalWriter w; /* The writer */
  57780. u32 iFirst = 0; /* First frame that may be overwritten */
  57781. WalIndexHdr *pLive; /* Pointer to shared header */
  57782. assert( pList );
  57783. assert( pWal->writeLock );
  57784. /* If this frame set completes a transaction, then nTruncate>0. If
  57785. ** nTruncate==0 then this frame set does not complete the transaction. */
  57786. assert( (isCommit!=0)==(nTruncate!=0) );
  57787. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  57788. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  57789. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  57790. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  57791. }
  57792. #endif
  57793. pLive = (WalIndexHdr*)walIndexHdr(pWal);
  57794. if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
  57795. iFirst = pLive->mxFrame+1;
  57796. }
  57797. /* See if it is possible to write these frames into the start of the
  57798. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  57799. */
  57800. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  57801. return rc;
  57802. }
  57803. /* If this is the first frame written into the log, write the WAL
  57804. ** header to the start of the WAL file. See comments at the top of
  57805. ** this source file for a description of the WAL header format.
  57806. */
  57807. iFrame = pWal->hdr.mxFrame;
  57808. if( iFrame==0 ){
  57809. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  57810. u32 aCksum[2]; /* Checksum for wal-header */
  57811. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  57812. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  57813. sqlite3Put4byte(&aWalHdr[8], szPage);
  57814. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  57815. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  57816. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  57817. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  57818. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  57819. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  57820. pWal->szPage = szPage;
  57821. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  57822. pWal->hdr.aFrameCksum[0] = aCksum[0];
  57823. pWal->hdr.aFrameCksum[1] = aCksum[1];
  57824. pWal->truncateOnCommit = 1;
  57825. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  57826. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  57827. if( rc!=SQLITE_OK ){
  57828. return rc;
  57829. }
  57830. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  57831. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  57832. ** an out-of-order write following a WAL restart could result in
  57833. ** database corruption. See the ticket:
  57834. **
  57835. ** https://sqlite.org/src/info/ff5be73dee
  57836. */
  57837. if( pWal->syncHeader ){
  57838. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  57839. if( rc ) return rc;
  57840. }
  57841. }
  57842. assert( (int)pWal->szPage==szPage );
  57843. /* Setup information needed to write frames into the WAL */
  57844. w.pWal = pWal;
  57845. w.pFd = pWal->pWalFd;
  57846. w.iSyncPoint = 0;
  57847. w.syncFlags = sync_flags;
  57848. w.szPage = szPage;
  57849. iOffset = walFrameOffset(iFrame+1, szPage);
  57850. szFrame = szPage + WAL_FRAME_HDRSIZE;
  57851. /* Write all frames into the log file exactly once */
  57852. for(p=pList; p; p=p->pDirty){
  57853. int nDbSize; /* 0 normally. Positive == commit flag */
  57854. /* Check if this page has already been written into the wal file by
  57855. ** the current transaction. If so, overwrite the existing frame and
  57856. ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
  57857. ** checksums must be recomputed when the transaction is committed. */
  57858. if( iFirst && (p->pDirty || isCommit==0) ){
  57859. u32 iWrite = 0;
  57860. VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
  57861. assert( rc==SQLITE_OK || iWrite==0 );
  57862. if( iWrite>=iFirst ){
  57863. i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
  57864. void *pData;
  57865. if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
  57866. pWal->iReCksum = iWrite;
  57867. }
  57868. #if defined(SQLITE_HAS_CODEC)
  57869. if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
  57870. #else
  57871. pData = p->pData;
  57872. #endif
  57873. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
  57874. if( rc ) return rc;
  57875. p->flags &= ~PGHDR_WAL_APPEND;
  57876. continue;
  57877. }
  57878. }
  57879. iFrame++;
  57880. assert( iOffset==walFrameOffset(iFrame, szPage) );
  57881. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  57882. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  57883. if( rc ) return rc;
  57884. pLast = p;
  57885. iOffset += szFrame;
  57886. p->flags |= PGHDR_WAL_APPEND;
  57887. }
  57888. /* Recalculate checksums within the wal file if required. */
  57889. if( isCommit && pWal->iReCksum ){
  57890. rc = walRewriteChecksums(pWal, iFrame);
  57891. if( rc ) return rc;
  57892. }
  57893. /* If this is the end of a transaction, then we might need to pad
  57894. ** the transaction and/or sync the WAL file.
  57895. **
  57896. ** Padding and syncing only occur if this set of frames complete a
  57897. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  57898. ** or synchronous==OFF, then no padding or syncing are needed.
  57899. **
  57900. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  57901. ** needed and only the sync is done. If padding is needed, then the
  57902. ** final frame is repeated (with its commit mark) until the next sector
  57903. ** boundary is crossed. Only the part of the WAL prior to the last
  57904. ** sector boundary is synced; the part of the last frame that extends
  57905. ** past the sector boundary is written after the sync.
  57906. */
  57907. if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
  57908. int bSync = 1;
  57909. if( pWal->padToSectorBoundary ){
  57910. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  57911. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  57912. bSync = (w.iSyncPoint==iOffset);
  57913. testcase( bSync );
  57914. while( iOffset<w.iSyncPoint ){
  57915. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  57916. if( rc ) return rc;
  57917. iOffset += szFrame;
  57918. nExtra++;
  57919. }
  57920. }
  57921. if( bSync ){
  57922. assert( rc==SQLITE_OK );
  57923. rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
  57924. }
  57925. }
  57926. /* If this frame set completes the first transaction in the WAL and
  57927. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  57928. ** journal size limit, if possible.
  57929. */
  57930. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  57931. i64 sz = pWal->mxWalSize;
  57932. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  57933. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  57934. }
  57935. walLimitSize(pWal, sz);
  57936. pWal->truncateOnCommit = 0;
  57937. }
  57938. /* Append data to the wal-index. It is not necessary to lock the
  57939. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  57940. ** guarantees that there are no other writers, and no data that may
  57941. ** be in use by existing readers is being overwritten.
  57942. */
  57943. iFrame = pWal->hdr.mxFrame;
  57944. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  57945. if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
  57946. iFrame++;
  57947. rc = walIndexAppend(pWal, iFrame, p->pgno);
  57948. }
  57949. while( rc==SQLITE_OK && nExtra>0 ){
  57950. iFrame++;
  57951. nExtra--;
  57952. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  57953. }
  57954. if( rc==SQLITE_OK ){
  57955. /* Update the private copy of the header. */
  57956. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  57957. testcase( szPage<=32768 );
  57958. testcase( szPage>=65536 );
  57959. pWal->hdr.mxFrame = iFrame;
  57960. if( isCommit ){
  57961. pWal->hdr.iChange++;
  57962. pWal->hdr.nPage = nTruncate;
  57963. }
  57964. /* If this is a commit, update the wal-index header too. */
  57965. if( isCommit ){
  57966. walIndexWriteHdr(pWal);
  57967. pWal->iCallback = iFrame;
  57968. }
  57969. }
  57970. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  57971. return rc;
  57972. }
  57973. /*
  57974. ** This routine is called to implement sqlite3_wal_checkpoint() and
  57975. ** related interfaces.
  57976. **
  57977. ** Obtain a CHECKPOINT lock and then backfill as much information as
  57978. ** we can from WAL into the database.
  57979. **
  57980. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  57981. ** callback. In this case this function runs a blocking checkpoint.
  57982. */
  57983. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  57984. Wal *pWal, /* Wal connection */
  57985. sqlite3 *db, /* Check this handle's interrupt flag */
  57986. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  57987. int (*xBusy)(void*), /* Function to call when busy */
  57988. void *pBusyArg, /* Context argument for xBusyHandler */
  57989. int sync_flags, /* Flags to sync db file with (or 0) */
  57990. int nBuf, /* Size of temporary buffer */
  57991. u8 *zBuf, /* Temporary buffer to use */
  57992. int *pnLog, /* OUT: Number of frames in WAL */
  57993. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  57994. ){
  57995. int rc; /* Return code */
  57996. int isChanged = 0; /* True if a new wal-index header is loaded */
  57997. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  57998. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  57999. assert( pWal->ckptLock==0 );
  58000. assert( pWal->writeLock==0 );
  58001. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  58002. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  58003. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  58004. if( pWal->readOnly ) return SQLITE_READONLY;
  58005. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  58006. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  58007. ** "checkpoint" lock on the database file. */
  58008. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  58009. if( rc ){
  58010. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  58011. ** checkpoint operation at the same time, the lock cannot be obtained and
  58012. ** SQLITE_BUSY is returned.
  58013. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  58014. ** it will not be invoked in this case.
  58015. */
  58016. testcase( rc==SQLITE_BUSY );
  58017. testcase( xBusy!=0 );
  58018. return rc;
  58019. }
  58020. pWal->ckptLock = 1;
  58021. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  58022. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  58023. ** file.
  58024. **
  58025. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  58026. ** immediately, and a busy-handler is configured, it is invoked and the
  58027. ** writer lock retried until either the busy-handler returns 0 or the
  58028. ** lock is successfully obtained.
  58029. */
  58030. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  58031. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  58032. if( rc==SQLITE_OK ){
  58033. pWal->writeLock = 1;
  58034. }else if( rc==SQLITE_BUSY ){
  58035. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  58036. xBusy2 = 0;
  58037. rc = SQLITE_OK;
  58038. }
  58039. }
  58040. /* Read the wal-index header. */
  58041. if( rc==SQLITE_OK ){
  58042. rc = walIndexReadHdr(pWal, &isChanged);
  58043. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  58044. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  58045. }
  58046. }
  58047. /* Copy data from the log to the database file. */
  58048. if( rc==SQLITE_OK ){
  58049. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  58050. rc = SQLITE_CORRUPT_BKPT;
  58051. }else{
  58052. rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  58053. }
  58054. /* If no error occurred, set the output variables. */
  58055. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  58056. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  58057. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  58058. }
  58059. }
  58060. if( isChanged ){
  58061. /* If a new wal-index header was loaded before the checkpoint was
  58062. ** performed, then the pager-cache associated with pWal is now
  58063. ** out of date. So zero the cached wal-index header to ensure that
  58064. ** next time the pager opens a snapshot on this database it knows that
  58065. ** the cache needs to be reset.
  58066. */
  58067. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  58068. }
  58069. /* Release the locks. */
  58070. sqlite3WalEndWriteTransaction(pWal);
  58071. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  58072. pWal->ckptLock = 0;
  58073. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  58074. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  58075. }
  58076. /* Return the value to pass to a sqlite3_wal_hook callback, the
  58077. ** number of frames in the WAL at the point of the last commit since
  58078. ** sqlite3WalCallback() was called. If no commits have occurred since
  58079. ** the last call, then return 0.
  58080. */
  58081. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  58082. u32 ret = 0;
  58083. if( pWal ){
  58084. ret = pWal->iCallback;
  58085. pWal->iCallback = 0;
  58086. }
  58087. return (int)ret;
  58088. }
  58089. /*
  58090. ** This function is called to change the WAL subsystem into or out
  58091. ** of locking_mode=EXCLUSIVE.
  58092. **
  58093. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  58094. ** into locking_mode=NORMAL. This means that we must acquire a lock
  58095. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  58096. ** or if the acquisition of the lock fails, then return 0. If the
  58097. ** transition out of exclusive-mode is successful, return 1. This
  58098. ** operation must occur while the pager is still holding the exclusive
  58099. ** lock on the main database file.
  58100. **
  58101. ** If op is one, then change from locking_mode=NORMAL into
  58102. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  58103. ** be released. Return 1 if the transition is made and 0 if the
  58104. ** WAL is already in exclusive-locking mode - meaning that this
  58105. ** routine is a no-op. The pager must already hold the exclusive lock
  58106. ** on the main database file before invoking this operation.
  58107. **
  58108. ** If op is negative, then do a dry-run of the op==1 case but do
  58109. ** not actually change anything. The pager uses this to see if it
  58110. ** should acquire the database exclusive lock prior to invoking
  58111. ** the op==1 case.
  58112. */
  58113. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  58114. int rc;
  58115. assert( pWal->writeLock==0 );
  58116. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  58117. /* pWal->readLock is usually set, but might be -1 if there was a
  58118. ** prior error while attempting to acquire are read-lock. This cannot
  58119. ** happen if the connection is actually in exclusive mode (as no xShmLock
  58120. ** locks are taken in this case). Nor should the pager attempt to
  58121. ** upgrade to exclusive-mode following such an error.
  58122. */
  58123. assert( pWal->readLock>=0 || pWal->lockError );
  58124. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  58125. if( op==0 ){
  58126. if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
  58127. pWal->exclusiveMode = WAL_NORMAL_MODE;
  58128. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  58129. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  58130. }
  58131. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  58132. }else{
  58133. /* Already in locking_mode=NORMAL */
  58134. rc = 0;
  58135. }
  58136. }else if( op>0 ){
  58137. assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
  58138. assert( pWal->readLock>=0 );
  58139. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  58140. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  58141. rc = 1;
  58142. }else{
  58143. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  58144. }
  58145. return rc;
  58146. }
  58147. /*
  58148. ** Return true if the argument is non-NULL and the WAL module is using
  58149. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  58150. ** WAL module is using shared-memory, return false.
  58151. */
  58152. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  58153. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  58154. }
  58155. #ifdef SQLITE_ENABLE_SNAPSHOT
  58156. /* Create a snapshot object. The content of a snapshot is opaque to
  58157. ** every other subsystem, so the WAL module can put whatever it needs
  58158. ** in the object.
  58159. */
  58160. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  58161. int rc = SQLITE_OK;
  58162. WalIndexHdr *pRet;
  58163. static const u32 aZero[4] = { 0, 0, 0, 0 };
  58164. assert( pWal->readLock>=0 && pWal->writeLock==0 );
  58165. if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
  58166. *ppSnapshot = 0;
  58167. return SQLITE_ERROR;
  58168. }
  58169. pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  58170. if( pRet==0 ){
  58171. rc = SQLITE_NOMEM_BKPT;
  58172. }else{
  58173. memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
  58174. *ppSnapshot = (sqlite3_snapshot*)pRet;
  58175. }
  58176. return rc;
  58177. }
  58178. /* Try to open on pSnapshot when the next read-transaction starts
  58179. */
  58180. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
  58181. pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
  58182. }
  58183. /*
  58184. ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
  58185. ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
  58186. */
  58187. SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
  58188. WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
  58189. WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
  58190. /* aSalt[0] is a copy of the value stored in the wal file header. It
  58191. ** is incremented each time the wal file is restarted. */
  58192. if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
  58193. if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
  58194. if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
  58195. if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
  58196. return 0;
  58197. }
  58198. /*
  58199. ** The caller currently has a read transaction open on the database.
  58200. ** This function takes a SHARED lock on the CHECKPOINTER slot and then
  58201. ** checks if the snapshot passed as the second argument is still
  58202. ** available. If so, SQLITE_OK is returned.
  58203. **
  58204. ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
  58205. ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
  58206. ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
  58207. ** lock is released before returning.
  58208. */
  58209. SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
  58210. int rc;
  58211. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  58212. if( rc==SQLITE_OK ){
  58213. WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
  58214. if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  58215. || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
  58216. ){
  58217. rc = SQLITE_ERROR_SNAPSHOT;
  58218. walUnlockShared(pWal, WAL_CKPT_LOCK);
  58219. }
  58220. }
  58221. return rc;
  58222. }
  58223. /*
  58224. ** Release a lock obtained by an earlier successful call to
  58225. ** sqlite3WalSnapshotCheck().
  58226. */
  58227. SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal){
  58228. assert( pWal );
  58229. walUnlockShared(pWal, WAL_CKPT_LOCK);
  58230. }
  58231. #endif /* SQLITE_ENABLE_SNAPSHOT */
  58232. #ifdef SQLITE_ENABLE_ZIPVFS
  58233. /*
  58234. ** If the argument is not NULL, it points to a Wal object that holds a
  58235. ** read-lock. This function returns the database page-size if it is known,
  58236. ** or zero if it is not (or if pWal is NULL).
  58237. */
  58238. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  58239. assert( pWal==0 || pWal->readLock>=0 );
  58240. return (pWal ? pWal->szPage : 0);
  58241. }
  58242. #endif
  58243. /* Return the sqlite3_file object for the WAL file
  58244. */
  58245. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
  58246. return pWal->pWalFd;
  58247. }
  58248. #endif /* #ifndef SQLITE_OMIT_WAL */
  58249. /************** End of wal.c *************************************************/
  58250. /************** Begin file btmutex.c *****************************************/
  58251. /*
  58252. ** 2007 August 27
  58253. **
  58254. ** The author disclaims copyright to this source code. In place of
  58255. ** a legal notice, here is a blessing:
  58256. **
  58257. ** May you do good and not evil.
  58258. ** May you find forgiveness for yourself and forgive others.
  58259. ** May you share freely, never taking more than you give.
  58260. **
  58261. *************************************************************************
  58262. **
  58263. ** This file contains code used to implement mutexes on Btree objects.
  58264. ** This code really belongs in btree.c. But btree.c is getting too
  58265. ** big and we want to break it down some. This packaged seemed like
  58266. ** a good breakout.
  58267. */
  58268. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  58269. /************** Begin file btreeInt.h ****************************************/
  58270. /*
  58271. ** 2004 April 6
  58272. **
  58273. ** The author disclaims copyright to this source code. In place of
  58274. ** a legal notice, here is a blessing:
  58275. **
  58276. ** May you do good and not evil.
  58277. ** May you find forgiveness for yourself and forgive others.
  58278. ** May you share freely, never taking more than you give.
  58279. **
  58280. *************************************************************************
  58281. ** This file implements an external (disk-based) database using BTrees.
  58282. ** For a detailed discussion of BTrees, refer to
  58283. **
  58284. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  58285. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  58286. ** Publishing Company, Reading, Massachusetts.
  58287. **
  58288. ** The basic idea is that each page of the file contains N database
  58289. ** entries and N+1 pointers to subpages.
  58290. **
  58291. ** ----------------------------------------------------------------
  58292. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  58293. ** ----------------------------------------------------------------
  58294. **
  58295. ** All of the keys on the page that Ptr(0) points to have values less
  58296. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  58297. ** values greater than Key(0) and less than Key(1). All of the keys
  58298. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  58299. ** so forth.
  58300. **
  58301. ** Finding a particular key requires reading O(log(M)) pages from the
  58302. ** disk where M is the number of entries in the tree.
  58303. **
  58304. ** In this implementation, a single file can hold one or more separate
  58305. ** BTrees. Each BTree is identified by the index of its root page. The
  58306. ** key and data for any entry are combined to form the "payload". A
  58307. ** fixed amount of payload can be carried directly on the database
  58308. ** page. If the payload is larger than the preset amount then surplus
  58309. ** bytes are stored on overflow pages. The payload for an entry
  58310. ** and the preceding pointer are combined to form a "Cell". Each
  58311. ** page has a small header which contains the Ptr(N) pointer and other
  58312. ** information such as the size of key and data.
  58313. **
  58314. ** FORMAT DETAILS
  58315. **
  58316. ** The file is divided into pages. The first page is called page 1,
  58317. ** the second is page 2, and so forth. A page number of zero indicates
  58318. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  58319. ** Each page can be either a btree page, a freelist page, an overflow
  58320. ** page, or a pointer-map page.
  58321. **
  58322. ** The first page is always a btree page. The first 100 bytes of the first
  58323. ** page contain a special header (the "file header") that describes the file.
  58324. ** The format of the file header is as follows:
  58325. **
  58326. ** OFFSET SIZE DESCRIPTION
  58327. ** 0 16 Header string: "SQLite format 3\000"
  58328. ** 16 2 Page size in bytes. (1 means 65536)
  58329. ** 18 1 File format write version
  58330. ** 19 1 File format read version
  58331. ** 20 1 Bytes of unused space at the end of each page
  58332. ** 21 1 Max embedded payload fraction (must be 64)
  58333. ** 22 1 Min embedded payload fraction (must be 32)
  58334. ** 23 1 Min leaf payload fraction (must be 32)
  58335. ** 24 4 File change counter
  58336. ** 28 4 Reserved for future use
  58337. ** 32 4 First freelist page
  58338. ** 36 4 Number of freelist pages in the file
  58339. ** 40 60 15 4-byte meta values passed to higher layers
  58340. **
  58341. ** 40 4 Schema cookie
  58342. ** 44 4 File format of schema layer
  58343. ** 48 4 Size of page cache
  58344. ** 52 4 Largest root-page (auto/incr_vacuum)
  58345. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  58346. ** 60 4 User version
  58347. ** 64 4 Incremental vacuum mode
  58348. ** 68 4 Application-ID
  58349. ** 72 20 unused
  58350. ** 92 4 The version-valid-for number
  58351. ** 96 4 SQLITE_VERSION_NUMBER
  58352. **
  58353. ** All of the integer values are big-endian (most significant byte first).
  58354. **
  58355. ** The file change counter is incremented when the database is changed
  58356. ** This counter allows other processes to know when the file has changed
  58357. ** and thus when they need to flush their cache.
  58358. **
  58359. ** The max embedded payload fraction is the amount of the total usable
  58360. ** space in a page that can be consumed by a single cell for standard
  58361. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  58362. ** is to limit the maximum cell size so that at least 4 cells will fit
  58363. ** on one page. Thus the default max embedded payload fraction is 64.
  58364. **
  58365. ** If the payload for a cell is larger than the max payload, then extra
  58366. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  58367. ** as many bytes as possible are moved into the overflow pages without letting
  58368. ** the cell size drop below the min embedded payload fraction.
  58369. **
  58370. ** The min leaf payload fraction is like the min embedded payload fraction
  58371. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  58372. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  58373. ** not specified in the header.
  58374. **
  58375. ** Each btree pages is divided into three sections: The header, the
  58376. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  58377. ** file header that occurs before the page header.
  58378. **
  58379. ** |----------------|
  58380. ** | file header | 100 bytes. Page 1 only.
  58381. ** |----------------|
  58382. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  58383. ** |----------------|
  58384. ** | cell pointer | | 2 bytes per cell. Sorted order.
  58385. ** | array | | Grows downward
  58386. ** | | v
  58387. ** |----------------|
  58388. ** | unallocated |
  58389. ** | space |
  58390. ** |----------------| ^ Grows upwards
  58391. ** | cell content | | Arbitrary order interspersed with freeblocks.
  58392. ** | area | | and free space fragments.
  58393. ** |----------------|
  58394. **
  58395. ** The page headers looks like this:
  58396. **
  58397. ** OFFSET SIZE DESCRIPTION
  58398. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  58399. ** 1 2 byte offset to the first freeblock
  58400. ** 3 2 number of cells on this page
  58401. ** 5 2 first byte of the cell content area
  58402. ** 7 1 number of fragmented free bytes
  58403. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  58404. **
  58405. ** The flags define the format of this btree page. The leaf flag means that
  58406. ** this page has no children. The zerodata flag means that this page carries
  58407. ** only keys and no data. The intkey flag means that the key is an integer
  58408. ** which is stored in the key size entry of the cell header rather than in
  58409. ** the payload area.
  58410. **
  58411. ** The cell pointer array begins on the first byte after the page header.
  58412. ** The cell pointer array contains zero or more 2-byte numbers which are
  58413. ** offsets from the beginning of the page to the cell content in the cell
  58414. ** content area. The cell pointers occur in sorted order. The system strives
  58415. ** to keep free space after the last cell pointer so that new cells can
  58416. ** be easily added without having to defragment the page.
  58417. **
  58418. ** Cell content is stored at the very end of the page and grows toward the
  58419. ** beginning of the page.
  58420. **
  58421. ** Unused space within the cell content area is collected into a linked list of
  58422. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  58423. ** to the first freeblock is given in the header. Freeblocks occur in
  58424. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  58425. ** any group of 3 or fewer unused bytes in the cell content area cannot
  58426. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  58427. ** a fragment. The total number of bytes in all fragments is recorded.
  58428. ** in the page header at offset 7.
  58429. **
  58430. ** SIZE DESCRIPTION
  58431. ** 2 Byte offset of the next freeblock
  58432. ** 2 Bytes in this freeblock
  58433. **
  58434. ** Cells are of variable length. Cells are stored in the cell content area at
  58435. ** the end of the page. Pointers to the cells are in the cell pointer array
  58436. ** that immediately follows the page header. Cells is not necessarily
  58437. ** contiguous or in order, but cell pointers are contiguous and in order.
  58438. **
  58439. ** Cell content makes use of variable length integers. A variable
  58440. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  58441. ** byte are used. The integer consists of all bytes that have bit 8 set and
  58442. ** the first byte with bit 8 clear. The most significant byte of the integer
  58443. ** appears first. A variable-length integer may not be more than 9 bytes long.
  58444. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  58445. ** allows a 64-bit integer to be encoded in 9 bytes.
  58446. **
  58447. ** 0x00 becomes 0x00000000
  58448. ** 0x7f becomes 0x0000007f
  58449. ** 0x81 0x00 becomes 0x00000080
  58450. ** 0x82 0x00 becomes 0x00000100
  58451. ** 0x80 0x7f becomes 0x0000007f
  58452. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  58453. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  58454. **
  58455. ** Variable length integers are used for rowids and to hold the number of
  58456. ** bytes of key and data in a btree cell.
  58457. **
  58458. ** The content of a cell looks like this:
  58459. **
  58460. ** SIZE DESCRIPTION
  58461. ** 4 Page number of the left child. Omitted if leaf flag is set.
  58462. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  58463. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  58464. ** * Payload
  58465. ** 4 First page of the overflow chain. Omitted if no overflow
  58466. **
  58467. ** Overflow pages form a linked list. Each page except the last is completely
  58468. ** filled with data (pagesize - 4 bytes). The last page can have as little
  58469. ** as 1 byte of data.
  58470. **
  58471. ** SIZE DESCRIPTION
  58472. ** 4 Page number of next overflow page
  58473. ** * Data
  58474. **
  58475. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  58476. ** file header points to the first in a linked list of trunk page. Each trunk
  58477. ** page points to multiple leaf pages. The content of a leaf page is
  58478. ** unspecified. A trunk page looks like this:
  58479. **
  58480. ** SIZE DESCRIPTION
  58481. ** 4 Page number of next trunk page
  58482. ** 4 Number of leaf pointers on this page
  58483. ** * zero or more pages numbers of leaves
  58484. */
  58485. /* #include "sqliteInt.h" */
  58486. /* The following value is the maximum cell size assuming a maximum page
  58487. ** size give above.
  58488. */
  58489. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  58490. /* The maximum number of cells on a single page of the database. This
  58491. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  58492. ** plus 2 bytes for the index to the cell in the page header). Such
  58493. ** small cells will be rare, but they are possible.
  58494. */
  58495. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  58496. /* Forward declarations */
  58497. typedef struct MemPage MemPage;
  58498. typedef struct BtLock BtLock;
  58499. typedef struct CellInfo CellInfo;
  58500. /*
  58501. ** This is a magic string that appears at the beginning of every
  58502. ** SQLite database in order to identify the file as a real database.
  58503. **
  58504. ** You can change this value at compile-time by specifying a
  58505. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  58506. ** header must be exactly 16 bytes including the zero-terminator so
  58507. ** the string itself should be 15 characters long. If you change
  58508. ** the header, then your custom library will not be able to read
  58509. ** databases generated by the standard tools and the standard tools
  58510. ** will not be able to read databases created by your custom library.
  58511. */
  58512. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  58513. # define SQLITE_FILE_HEADER "SQLite format 3"
  58514. #endif
  58515. /*
  58516. ** Page type flags. An ORed combination of these flags appear as the
  58517. ** first byte of on-disk image of every BTree page.
  58518. */
  58519. #define PTF_INTKEY 0x01
  58520. #define PTF_ZERODATA 0x02
  58521. #define PTF_LEAFDATA 0x04
  58522. #define PTF_LEAF 0x08
  58523. /*
  58524. ** An instance of this object stores information about each a single database
  58525. ** page that has been loaded into memory. The information in this object
  58526. ** is derived from the raw on-disk page content.
  58527. **
  58528. ** As each database page is loaded into memory, the pager allocats an
  58529. ** instance of this object and zeros the first 8 bytes. (This is the
  58530. ** "extra" information associated with each page of the pager.)
  58531. **
  58532. ** Access to all fields of this structure is controlled by the mutex
  58533. ** stored in MemPage.pBt->mutex.
  58534. */
  58535. struct MemPage {
  58536. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  58537. u8 bBusy; /* Prevent endless loops on corrupt database files */
  58538. u8 intKey; /* True if table b-trees. False for index b-trees */
  58539. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  58540. Pgno pgno; /* Page number for this page */
  58541. /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
  58542. ** is allocated. All fields that follow must be initialized before use */
  58543. u8 leaf; /* True if a leaf page */
  58544. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  58545. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  58546. u8 max1bytePayload; /* min(maxLocal,127) */
  58547. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  58548. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  58549. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  58550. u16 cellOffset; /* Index in aData of first cell pointer */
  58551. int nFree; /* Number of free bytes on the page. -1 for unknown */
  58552. u16 nCell; /* Number of cells on this page, local and ovfl */
  58553. u16 maskPage; /* Mask for page offset */
  58554. u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
  58555. ** non-overflow cell */
  58556. u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
  58557. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  58558. u8 *aData; /* Pointer to disk image of the page data */
  58559. u8 *aDataEnd; /* One byte past the end of usable data */
  58560. u8 *aCellIdx; /* The cell index area */
  58561. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  58562. DbPage *pDbPage; /* Pager page handle */
  58563. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  58564. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  58565. };
  58566. /*
  58567. ** A linked list of the following structures is stored at BtShared.pLock.
  58568. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  58569. ** is opened on the table with root page BtShared.iTable. Locks are removed
  58570. ** from this list when a transaction is committed or rolled back, or when
  58571. ** a btree handle is closed.
  58572. */
  58573. struct BtLock {
  58574. Btree *pBtree; /* Btree handle holding this lock */
  58575. Pgno iTable; /* Root page of table */
  58576. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  58577. BtLock *pNext; /* Next in BtShared.pLock list */
  58578. };
  58579. /* Candidate values for BtLock.eLock */
  58580. #define READ_LOCK 1
  58581. #define WRITE_LOCK 2
  58582. /* A Btree handle
  58583. **
  58584. ** A database connection contains a pointer to an instance of
  58585. ** this object for every database file that it has open. This structure
  58586. ** is opaque to the database connection. The database connection cannot
  58587. ** see the internals of this structure and only deals with pointers to
  58588. ** this structure.
  58589. **
  58590. ** For some database files, the same underlying database cache might be
  58591. ** shared between multiple connections. In that case, each connection
  58592. ** has it own instance of this object. But each instance of this object
  58593. ** points to the same BtShared object. The database cache and the
  58594. ** schema associated with the database file are all contained within
  58595. ** the BtShared object.
  58596. **
  58597. ** All fields in this structure are accessed under sqlite3.mutex.
  58598. ** The pBt pointer itself may not be changed while there exists cursors
  58599. ** in the referenced BtShared that point back to this Btree since those
  58600. ** cursors have to go through this Btree to find their BtShared and
  58601. ** they often do so without holding sqlite3.mutex.
  58602. */
  58603. struct Btree {
  58604. sqlite3 *db; /* The database connection holding this btree */
  58605. BtShared *pBt; /* Sharable content of this btree */
  58606. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  58607. u8 sharable; /* True if we can share pBt with another db */
  58608. u8 locked; /* True if db currently has pBt locked */
  58609. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  58610. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  58611. int nBackup; /* Number of backup operations reading this btree */
  58612. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  58613. Btree *pNext; /* List of other sharable Btrees from the same db */
  58614. Btree *pPrev; /* Back pointer of the same list */
  58615. #ifndef SQLITE_OMIT_SHARED_CACHE
  58616. BtLock lock; /* Object used to lock page 1 */
  58617. #endif
  58618. };
  58619. /*
  58620. ** Btree.inTrans may take one of the following values.
  58621. **
  58622. ** If the shared-data extension is enabled, there may be multiple users
  58623. ** of the Btree structure. At most one of these may open a write transaction,
  58624. ** but any number may have active read transactions.
  58625. */
  58626. #define TRANS_NONE 0
  58627. #define TRANS_READ 1
  58628. #define TRANS_WRITE 2
  58629. /*
  58630. ** An instance of this object represents a single database file.
  58631. **
  58632. ** A single database file can be in use at the same time by two
  58633. ** or more database connections. When two or more connections are
  58634. ** sharing the same database file, each connection has it own
  58635. ** private Btree object for the file and each of those Btrees points
  58636. ** to this one BtShared object. BtShared.nRef is the number of
  58637. ** connections currently sharing this database file.
  58638. **
  58639. ** Fields in this structure are accessed under the BtShared.mutex
  58640. ** mutex, except for nRef and pNext which are accessed under the
  58641. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  58642. ** may not be modified once it is initially set as long as nRef>0.
  58643. ** The pSchema field may be set once under BtShared.mutex and
  58644. ** thereafter is unchanged as long as nRef>0.
  58645. **
  58646. ** isPending:
  58647. **
  58648. ** If a BtShared client fails to obtain a write-lock on a database
  58649. ** table (because there exists one or more read-locks on the table),
  58650. ** the shared-cache enters 'pending-lock' state and isPending is
  58651. ** set to true.
  58652. **
  58653. ** The shared-cache leaves the 'pending lock' state when either of
  58654. ** the following occur:
  58655. **
  58656. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  58657. ** 2) The number of locks held by other connections drops to zero.
  58658. **
  58659. ** while in the 'pending-lock' state, no connection may start a new
  58660. ** transaction.
  58661. **
  58662. ** This feature is included to help prevent writer-starvation.
  58663. */
  58664. struct BtShared {
  58665. Pager *pPager; /* The page cache */
  58666. sqlite3 *db; /* Database connection currently using this Btree */
  58667. BtCursor *pCursor; /* A list of all open cursors */
  58668. MemPage *pPage1; /* First page of the database */
  58669. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  58670. #ifndef SQLITE_OMIT_AUTOVACUUM
  58671. u8 autoVacuum; /* True if auto-vacuum is enabled */
  58672. u8 incrVacuum; /* True if incr-vacuum is enabled */
  58673. u8 bDoTruncate; /* True to truncate db on commit */
  58674. #endif
  58675. u8 inTransaction; /* Transaction state */
  58676. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  58677. #ifdef SQLITE_HAS_CODEC
  58678. u8 optimalReserve; /* Desired amount of reserved space per page */
  58679. #endif
  58680. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  58681. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  58682. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  58683. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  58684. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  58685. u32 pageSize; /* Total number of bytes on a page */
  58686. u32 usableSize; /* Number of usable bytes on each page */
  58687. int nTransaction; /* Number of open transactions (read + write) */
  58688. u32 nPage; /* Number of pages in the database */
  58689. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  58690. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  58691. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  58692. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  58693. #ifndef SQLITE_OMIT_SHARED_CACHE
  58694. int nRef; /* Number of references to this structure */
  58695. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  58696. BtLock *pLock; /* List of locks held on this shared-btree struct */
  58697. Btree *pWriter; /* Btree with currently open write transaction */
  58698. #endif
  58699. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  58700. };
  58701. /*
  58702. ** Allowed values for BtShared.btsFlags
  58703. */
  58704. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  58705. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  58706. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  58707. #define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */
  58708. #define BTS_FAST_SECURE 0x000c /* Combination of the previous two */
  58709. #define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */
  58710. #define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
  58711. #define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */
  58712. #define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
  58713. /*
  58714. ** An instance of the following structure is used to hold information
  58715. ** about a cell. The parseCellPtr() function fills in this structure
  58716. ** based on information extract from the raw disk page.
  58717. */
  58718. struct CellInfo {
  58719. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  58720. u8 *pPayload; /* Pointer to the start of payload */
  58721. u32 nPayload; /* Bytes of payload */
  58722. u16 nLocal; /* Amount of payload held locally, not on overflow */
  58723. u16 nSize; /* Size of the cell content on the main b-tree page */
  58724. };
  58725. /*
  58726. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  58727. ** this will be declared corrupt. This value is calculated based on a
  58728. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  58729. ** root-node and 3 for all other internal nodes.
  58730. **
  58731. ** If a tree that appears to be taller than this is encountered, it is
  58732. ** assumed that the database is corrupt.
  58733. */
  58734. #define BTCURSOR_MAX_DEPTH 20
  58735. /*
  58736. ** A cursor is a pointer to a particular entry within a particular
  58737. ** b-tree within a database file.
  58738. **
  58739. ** The entry is identified by its MemPage and the index in
  58740. ** MemPage.aCell[] of the entry.
  58741. **
  58742. ** A single database file can be shared by two more database connections,
  58743. ** but cursors cannot be shared. Each cursor is associated with a
  58744. ** particular database connection identified BtCursor.pBtree.db.
  58745. **
  58746. ** Fields in this structure are accessed under the BtShared.mutex
  58747. ** found at self->pBt->mutex.
  58748. **
  58749. ** skipNext meaning:
  58750. ** The meaning of skipNext depends on the value of eState:
  58751. **
  58752. ** eState Meaning of skipNext
  58753. ** VALID skipNext is meaningless and is ignored
  58754. ** INVALID skipNext is meaningless and is ignored
  58755. ** SKIPNEXT sqlite3BtreeNext() is a no-op if skipNext>0 and
  58756. ** sqlite3BtreePrevious() is no-op if skipNext<0.
  58757. ** REQUIRESEEK restoreCursorPosition() restores the cursor to
  58758. ** eState=SKIPNEXT if skipNext!=0
  58759. ** FAULT skipNext holds the cursor fault error code.
  58760. */
  58761. struct BtCursor {
  58762. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  58763. u8 curFlags; /* zero or more BTCF_* flags defined below */
  58764. u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
  58765. u8 hints; /* As configured by CursorSetHints() */
  58766. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  58767. ** Error code if eState==CURSOR_FAULT */
  58768. Btree *pBtree; /* The Btree to which this cursor belongs */
  58769. Pgno *aOverflow; /* Cache of overflow page locations */
  58770. void *pKey; /* Saved key that was cursor last known position */
  58771. /* All fields above are zeroed when the cursor is allocated. See
  58772. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  58773. ** initialized. */
  58774. #define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */
  58775. BtShared *pBt; /* The BtShared this cursor points to */
  58776. BtCursor *pNext; /* Forms a linked list of all cursors */
  58777. CellInfo info; /* A parse of the cell we are pointing at */
  58778. i64 nKey; /* Size of pKey, or last integer key */
  58779. Pgno pgnoRoot; /* The root page of this tree */
  58780. i8 iPage; /* Index of current page in apPage */
  58781. u8 curIntKey; /* Value of apPage[0]->intKey */
  58782. u16 ix; /* Current index for apPage[iPage] */
  58783. u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
  58784. struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
  58785. MemPage *pPage; /* Current page */
  58786. MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
  58787. };
  58788. /*
  58789. ** Legal values for BtCursor.curFlags
  58790. */
  58791. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  58792. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  58793. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  58794. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  58795. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  58796. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  58797. /*
  58798. ** Potential values for BtCursor.eState.
  58799. **
  58800. ** CURSOR_INVALID:
  58801. ** Cursor does not point to a valid entry. This can happen (for example)
  58802. ** because the table is empty or because BtreeCursorFirst() has not been
  58803. ** called.
  58804. **
  58805. ** CURSOR_VALID:
  58806. ** Cursor points to a valid entry. getPayload() etc. may be called.
  58807. **
  58808. ** CURSOR_SKIPNEXT:
  58809. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  58810. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  58811. ** operation should be a no-op.
  58812. **
  58813. ** CURSOR_REQUIRESEEK:
  58814. ** The table that this cursor was opened on still exists, but has been
  58815. ** modified since the cursor was last used. The cursor position is saved
  58816. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  58817. ** this state, restoreCursorPosition() can be called to attempt to
  58818. ** seek the cursor to the saved position.
  58819. **
  58820. ** CURSOR_FAULT:
  58821. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  58822. ** on a different connection that shares the BtShared cache with this
  58823. ** cursor. The error has left the cache in an inconsistent state.
  58824. ** Do nothing else with this cursor. Any attempt to use the cursor
  58825. ** should return the error code stored in BtCursor.skipNext
  58826. */
  58827. #define CURSOR_VALID 0
  58828. #define CURSOR_INVALID 1
  58829. #define CURSOR_SKIPNEXT 2
  58830. #define CURSOR_REQUIRESEEK 3
  58831. #define CURSOR_FAULT 4
  58832. /*
  58833. ** The database page the PENDING_BYTE occupies. This page is never used.
  58834. */
  58835. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  58836. /*
  58837. ** These macros define the location of the pointer-map entry for a
  58838. ** database page. The first argument to each is the number of usable
  58839. ** bytes on each page of the database (often 1024). The second is the
  58840. ** page number to look up in the pointer map.
  58841. **
  58842. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  58843. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  58844. ** the offset of the requested map entry.
  58845. **
  58846. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  58847. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  58848. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  58849. ** this test.
  58850. */
  58851. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  58852. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  58853. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  58854. /*
  58855. ** The pointer map is a lookup table that identifies the parent page for
  58856. ** each child page in the database file. The parent page is the page that
  58857. ** contains a pointer to the child. Every page in the database contains
  58858. ** 0 or 1 parent pages. (In this context 'database page' refers
  58859. ** to any page that is not part of the pointer map itself.) Each pointer map
  58860. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  58861. ** The PTRMAP_XXX identifiers below are the valid types.
  58862. **
  58863. ** The purpose of the pointer map is to facility moving pages from one
  58864. ** position in the file to another as part of autovacuum. When a page
  58865. ** is moved, the pointer in its parent must be updated to point to the
  58866. ** new location. The pointer map is used to locate the parent page quickly.
  58867. **
  58868. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  58869. ** used in this case.
  58870. **
  58871. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  58872. ** is not used in this case.
  58873. **
  58874. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  58875. ** overflow pages. The page number identifies the page that
  58876. ** contains the cell with a pointer to this overflow page.
  58877. **
  58878. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  58879. ** overflow pages. The page-number identifies the previous
  58880. ** page in the overflow page list.
  58881. **
  58882. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  58883. ** identifies the parent page in the btree.
  58884. */
  58885. #define PTRMAP_ROOTPAGE 1
  58886. #define PTRMAP_FREEPAGE 2
  58887. #define PTRMAP_OVERFLOW1 3
  58888. #define PTRMAP_OVERFLOW2 4
  58889. #define PTRMAP_BTREE 5
  58890. /* A bunch of assert() statements to check the transaction state variables
  58891. ** of handle p (type Btree*) are internally consistent.
  58892. */
  58893. #define btreeIntegrity(p) \
  58894. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  58895. assert( p->pBt->inTransaction>=p->inTrans );
  58896. /*
  58897. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  58898. ** if the database supports auto-vacuum or not. Because it is used
  58899. ** within an expression that is an argument to another macro
  58900. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  58901. ** So, this macro is defined instead.
  58902. */
  58903. #ifndef SQLITE_OMIT_AUTOVACUUM
  58904. #define ISAUTOVACUUM (pBt->autoVacuum)
  58905. #else
  58906. #define ISAUTOVACUUM 0
  58907. #endif
  58908. /*
  58909. ** This structure is passed around through all the sanity checking routines
  58910. ** in order to keep track of some global state information.
  58911. **
  58912. ** The aRef[] array is allocated so that there is 1 bit for each page in
  58913. ** the database. As the integrity-check proceeds, for each page used in
  58914. ** the database the corresponding bit is set. This allows integrity-check to
  58915. ** detect pages that are used twice and orphaned pages (both of which
  58916. ** indicate corruption).
  58917. */
  58918. typedef struct IntegrityCk IntegrityCk;
  58919. struct IntegrityCk {
  58920. BtShared *pBt; /* The tree being checked out */
  58921. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  58922. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  58923. Pgno nPage; /* Number of pages in the database */
  58924. int mxErr; /* Stop accumulating errors when this reaches zero */
  58925. int nErr; /* Number of messages written to zErrMsg so far */
  58926. int mallocFailed; /* A memory allocation error has occurred */
  58927. const char *zPfx; /* Error message prefix */
  58928. int v1, v2; /* Values for up to two %d fields in zPfx */
  58929. StrAccum errMsg; /* Accumulate the error message text here */
  58930. u32 *heap; /* Min-heap used for analyzing cell coverage */
  58931. };
  58932. /*
  58933. ** Routines to read or write a two- and four-byte big-endian integer values.
  58934. */
  58935. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  58936. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  58937. #define get4byte sqlite3Get4byte
  58938. #define put4byte sqlite3Put4byte
  58939. /*
  58940. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  58941. ** two-byte aligned address. get2bytea() is only used for accessing the
  58942. ** cell addresses in a btree header.
  58943. */
  58944. #if SQLITE_BYTEORDER==4321
  58945. # define get2byteAligned(x) (*(u16*)(x))
  58946. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
  58947. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  58948. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  58949. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  58950. #else
  58951. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  58952. #endif
  58953. /************** End of btreeInt.h ********************************************/
  58954. /************** Continuing where we left off in btmutex.c ********************/
  58955. #ifndef SQLITE_OMIT_SHARED_CACHE
  58956. #if SQLITE_THREADSAFE
  58957. /*
  58958. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  58959. ** set BtShared.db to the database handle associated with p and the
  58960. ** p->locked boolean to true.
  58961. */
  58962. static void lockBtreeMutex(Btree *p){
  58963. assert( p->locked==0 );
  58964. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  58965. assert( sqlite3_mutex_held(p->db->mutex) );
  58966. sqlite3_mutex_enter(p->pBt->mutex);
  58967. p->pBt->db = p->db;
  58968. p->locked = 1;
  58969. }
  58970. /*
  58971. ** Release the BtShared mutex associated with B-Tree handle p and
  58972. ** clear the p->locked boolean.
  58973. */
  58974. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  58975. BtShared *pBt = p->pBt;
  58976. assert( p->locked==1 );
  58977. assert( sqlite3_mutex_held(pBt->mutex) );
  58978. assert( sqlite3_mutex_held(p->db->mutex) );
  58979. assert( p->db==pBt->db );
  58980. sqlite3_mutex_leave(pBt->mutex);
  58981. p->locked = 0;
  58982. }
  58983. /* Forward reference */
  58984. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  58985. /*
  58986. ** Enter a mutex on the given BTree object.
  58987. **
  58988. ** If the object is not sharable, then no mutex is ever required
  58989. ** and this routine is a no-op. The underlying mutex is non-recursive.
  58990. ** But we keep a reference count in Btree.wantToLock so the behavior
  58991. ** of this interface is recursive.
  58992. **
  58993. ** To avoid deadlocks, multiple Btrees are locked in the same order
  58994. ** by all database connections. The p->pNext is a list of other
  58995. ** Btrees belonging to the same database connection as the p Btree
  58996. ** which need to be locked after p. If we cannot get a lock on
  58997. ** p, then first unlock all of the others on p->pNext, then wait
  58998. ** for the lock to become available on p, then relock all of the
  58999. ** subsequent Btrees that desire a lock.
  59000. */
  59001. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  59002. /* Some basic sanity checking on the Btree. The list of Btrees
  59003. ** connected by pNext and pPrev should be in sorted order by
  59004. ** Btree.pBt value. All elements of the list should belong to
  59005. ** the same connection. Only shared Btrees are on the list. */
  59006. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  59007. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  59008. assert( p->pNext==0 || p->pNext->db==p->db );
  59009. assert( p->pPrev==0 || p->pPrev->db==p->db );
  59010. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  59011. /* Check for locking consistency */
  59012. assert( !p->locked || p->wantToLock>0 );
  59013. assert( p->sharable || p->wantToLock==0 );
  59014. /* We should already hold a lock on the database connection */
  59015. assert( sqlite3_mutex_held(p->db->mutex) );
  59016. /* Unless the database is sharable and unlocked, then BtShared.db
  59017. ** should already be set correctly. */
  59018. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  59019. if( !p->sharable ) return;
  59020. p->wantToLock++;
  59021. if( p->locked ) return;
  59022. btreeLockCarefully(p);
  59023. }
  59024. /* This is a helper function for sqlite3BtreeLock(). By moving
  59025. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  59026. ** into this routine, we avoid unnecessary stack pointer changes
  59027. ** and thus help the sqlite3BtreeLock() routine to run much faster
  59028. ** in the common case.
  59029. */
  59030. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  59031. Btree *pLater;
  59032. /* In most cases, we should be able to acquire the lock we
  59033. ** want without having to go through the ascending lock
  59034. ** procedure that follows. Just be sure not to block.
  59035. */
  59036. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  59037. p->pBt->db = p->db;
  59038. p->locked = 1;
  59039. return;
  59040. }
  59041. /* To avoid deadlock, first release all locks with a larger
  59042. ** BtShared address. Then acquire our lock. Then reacquire
  59043. ** the other BtShared locks that we used to hold in ascending
  59044. ** order.
  59045. */
  59046. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  59047. assert( pLater->sharable );
  59048. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  59049. assert( !pLater->locked || pLater->wantToLock>0 );
  59050. if( pLater->locked ){
  59051. unlockBtreeMutex(pLater);
  59052. }
  59053. }
  59054. lockBtreeMutex(p);
  59055. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  59056. if( pLater->wantToLock ){
  59057. lockBtreeMutex(pLater);
  59058. }
  59059. }
  59060. }
  59061. /*
  59062. ** Exit the recursive mutex on a Btree.
  59063. */
  59064. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  59065. assert( sqlite3_mutex_held(p->db->mutex) );
  59066. if( p->sharable ){
  59067. assert( p->wantToLock>0 );
  59068. p->wantToLock--;
  59069. if( p->wantToLock==0 ){
  59070. unlockBtreeMutex(p);
  59071. }
  59072. }
  59073. }
  59074. #ifndef NDEBUG
  59075. /*
  59076. ** Return true if the BtShared mutex is held on the btree, or if the
  59077. ** B-Tree is not marked as sharable.
  59078. **
  59079. ** This routine is used only from within assert() statements.
  59080. */
  59081. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  59082. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  59083. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  59084. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  59085. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  59086. return (p->sharable==0 || p->locked);
  59087. }
  59088. #endif
  59089. /*
  59090. ** Enter the mutex on every Btree associated with a database
  59091. ** connection. This is needed (for example) prior to parsing
  59092. ** a statement since we will be comparing table and column names
  59093. ** against all schemas and we do not want those schemas being
  59094. ** reset out from under us.
  59095. **
  59096. ** There is a corresponding leave-all procedures.
  59097. **
  59098. ** Enter the mutexes in accending order by BtShared pointer address
  59099. ** to avoid the possibility of deadlock when two threads with
  59100. ** two or more btrees in common both try to lock all their btrees
  59101. ** at the same instant.
  59102. */
  59103. static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
  59104. int i;
  59105. int skipOk = 1;
  59106. Btree *p;
  59107. assert( sqlite3_mutex_held(db->mutex) );
  59108. for(i=0; i<db->nDb; i++){
  59109. p = db->aDb[i].pBt;
  59110. if( p && p->sharable ){
  59111. sqlite3BtreeEnter(p);
  59112. skipOk = 0;
  59113. }
  59114. }
  59115. db->noSharedCache = skipOk;
  59116. }
  59117. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  59118. if( db->noSharedCache==0 ) btreeEnterAll(db);
  59119. }
  59120. static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
  59121. int i;
  59122. Btree *p;
  59123. assert( sqlite3_mutex_held(db->mutex) );
  59124. for(i=0; i<db->nDb; i++){
  59125. p = db->aDb[i].pBt;
  59126. if( p ) sqlite3BtreeLeave(p);
  59127. }
  59128. }
  59129. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  59130. if( db->noSharedCache==0 ) btreeLeaveAll(db);
  59131. }
  59132. #ifndef NDEBUG
  59133. /*
  59134. ** Return true if the current thread holds the database connection
  59135. ** mutex and all required BtShared mutexes.
  59136. **
  59137. ** This routine is used inside assert() statements only.
  59138. */
  59139. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  59140. int i;
  59141. if( !sqlite3_mutex_held(db->mutex) ){
  59142. return 0;
  59143. }
  59144. for(i=0; i<db->nDb; i++){
  59145. Btree *p;
  59146. p = db->aDb[i].pBt;
  59147. if( p && p->sharable &&
  59148. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  59149. return 0;
  59150. }
  59151. }
  59152. return 1;
  59153. }
  59154. #endif /* NDEBUG */
  59155. #ifndef NDEBUG
  59156. /*
  59157. ** Return true if the correct mutexes are held for accessing the
  59158. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  59159. ** access are:
  59160. **
  59161. ** (1) The mutex on db
  59162. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  59163. **
  59164. ** If pSchema is not NULL, then iDb is computed from pSchema and
  59165. ** db using sqlite3SchemaToIndex().
  59166. */
  59167. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  59168. Btree *p;
  59169. assert( db!=0 );
  59170. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  59171. assert( iDb>=0 && iDb<db->nDb );
  59172. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  59173. if( iDb==1 ) return 1;
  59174. p = db->aDb[iDb].pBt;
  59175. assert( p!=0 );
  59176. return p->sharable==0 || p->locked==1;
  59177. }
  59178. #endif /* NDEBUG */
  59179. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  59180. /*
  59181. ** The following are special cases for mutex enter routines for use
  59182. ** in single threaded applications that use shared cache. Except for
  59183. ** these two routines, all mutex operations are no-ops in that case and
  59184. ** are null #defines in btree.h.
  59185. **
  59186. ** If shared cache is disabled, then all btree mutex routines, including
  59187. ** the ones below, are no-ops and are null #defines in btree.h.
  59188. */
  59189. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  59190. p->pBt->db = p->db;
  59191. }
  59192. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  59193. int i;
  59194. for(i=0; i<db->nDb; i++){
  59195. Btree *p = db->aDb[i].pBt;
  59196. if( p ){
  59197. p->pBt->db = p->db;
  59198. }
  59199. }
  59200. }
  59201. #endif /* if SQLITE_THREADSAFE */
  59202. #ifndef SQLITE_OMIT_INCRBLOB
  59203. /*
  59204. ** Enter a mutex on a Btree given a cursor owned by that Btree.
  59205. **
  59206. ** These entry points are used by incremental I/O only. Enter() is required
  59207. ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
  59208. ** the build is threadsafe. Leave() is only required by threadsafe builds.
  59209. */
  59210. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  59211. sqlite3BtreeEnter(pCur->pBtree);
  59212. }
  59213. # if SQLITE_THREADSAFE
  59214. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  59215. sqlite3BtreeLeave(pCur->pBtree);
  59216. }
  59217. # endif
  59218. #endif /* ifndef SQLITE_OMIT_INCRBLOB */
  59219. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  59220. /************** End of btmutex.c *********************************************/
  59221. /************** Begin file btree.c *******************************************/
  59222. /*
  59223. ** 2004 April 6
  59224. **
  59225. ** The author disclaims copyright to this source code. In place of
  59226. ** a legal notice, here is a blessing:
  59227. **
  59228. ** May you do good and not evil.
  59229. ** May you find forgiveness for yourself and forgive others.
  59230. ** May you share freely, never taking more than you give.
  59231. **
  59232. *************************************************************************
  59233. ** This file implements an external (disk-based) database using BTrees.
  59234. ** See the header comment on "btreeInt.h" for additional information.
  59235. ** Including a description of file format and an overview of operation.
  59236. */
  59237. /* #include "btreeInt.h" */
  59238. /*
  59239. ** The header string that appears at the beginning of every
  59240. ** SQLite database.
  59241. */
  59242. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  59243. /*
  59244. ** Set this global variable to 1 to enable tracing using the TRACE
  59245. ** macro.
  59246. */
  59247. #if 0
  59248. int sqlite3BtreeTrace=1; /* True to enable tracing */
  59249. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  59250. #else
  59251. # define TRACE(X)
  59252. #endif
  59253. /*
  59254. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  59255. ** But if the value is zero, make it 65536.
  59256. **
  59257. ** This routine is used to extract the "offset to cell content area" value
  59258. ** from the header of a btree page. If the page size is 65536 and the page
  59259. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  59260. ** This routine makes the necessary adjustment to 65536.
  59261. */
  59262. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  59263. /*
  59264. ** Values passed as the 5th argument to allocateBtreePage()
  59265. */
  59266. #define BTALLOC_ANY 0 /* Allocate any page */
  59267. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  59268. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  59269. /*
  59270. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  59271. ** defined, or 0 if it is. For example:
  59272. **
  59273. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  59274. */
  59275. #ifndef SQLITE_OMIT_AUTOVACUUM
  59276. #define IfNotOmitAV(expr) (expr)
  59277. #else
  59278. #define IfNotOmitAV(expr) 0
  59279. #endif
  59280. #ifndef SQLITE_OMIT_SHARED_CACHE
  59281. /*
  59282. ** A list of BtShared objects that are eligible for participation
  59283. ** in shared cache. This variable has file scope during normal builds,
  59284. ** but the test harness needs to access it so we make it global for
  59285. ** test builds.
  59286. **
  59287. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  59288. */
  59289. #ifdef SQLITE_TEST
  59290. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  59291. #else
  59292. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  59293. #endif
  59294. #endif /* SQLITE_OMIT_SHARED_CACHE */
  59295. #ifndef SQLITE_OMIT_SHARED_CACHE
  59296. /*
  59297. ** Enable or disable the shared pager and schema features.
  59298. **
  59299. ** This routine has no effect on existing database connections.
  59300. ** The shared cache setting effects only future calls to
  59301. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  59302. */
  59303. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  59304. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  59305. return SQLITE_OK;
  59306. }
  59307. #endif
  59308. #ifdef SQLITE_OMIT_SHARED_CACHE
  59309. /*
  59310. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  59311. ** and clearAllSharedCacheTableLocks()
  59312. ** manipulate entries in the BtShared.pLock linked list used to store
  59313. ** shared-cache table level locks. If the library is compiled with the
  59314. ** shared-cache feature disabled, then there is only ever one user
  59315. ** of each BtShared structure and so this locking is not necessary.
  59316. ** So define the lock related functions as no-ops.
  59317. */
  59318. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  59319. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  59320. #define clearAllSharedCacheTableLocks(a)
  59321. #define downgradeAllSharedCacheTableLocks(a)
  59322. #define hasSharedCacheTableLock(a,b,c,d) 1
  59323. #define hasReadConflicts(a, b) 0
  59324. #endif
  59325. /*
  59326. ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
  59327. ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
  59328. **
  59329. ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
  59330. ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
  59331. ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
  59332. ** with the page number and filename associated with the (MemPage*).
  59333. */
  59334. #ifdef SQLITE_DEBUG
  59335. int corruptPageError(int lineno, MemPage *p){
  59336. char *zMsg;
  59337. sqlite3BeginBenignMalloc();
  59338. zMsg = sqlite3_mprintf("database corruption page %d of %s",
  59339. (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
  59340. );
  59341. sqlite3EndBenignMalloc();
  59342. if( zMsg ){
  59343. sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  59344. }
  59345. sqlite3_free(zMsg);
  59346. return SQLITE_CORRUPT_BKPT;
  59347. }
  59348. # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
  59349. #else
  59350. # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
  59351. #endif
  59352. #ifndef SQLITE_OMIT_SHARED_CACHE
  59353. #ifdef SQLITE_DEBUG
  59354. /*
  59355. **** This function is only used as part of an assert() statement. ***
  59356. **
  59357. ** Check to see if pBtree holds the required locks to read or write to the
  59358. ** table with root page iRoot. Return 1 if it does and 0 if not.
  59359. **
  59360. ** For example, when writing to a table with root-page iRoot via
  59361. ** Btree connection pBtree:
  59362. **
  59363. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  59364. **
  59365. ** When writing to an index that resides in a sharable database, the
  59366. ** caller should have first obtained a lock specifying the root page of
  59367. ** the corresponding table. This makes things a bit more complicated,
  59368. ** as this module treats each table as a separate structure. To determine
  59369. ** the table corresponding to the index being written, this
  59370. ** function has to search through the database schema.
  59371. **
  59372. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  59373. ** hold a write-lock on the schema table (root page 1). This is also
  59374. ** acceptable.
  59375. */
  59376. static int hasSharedCacheTableLock(
  59377. Btree *pBtree, /* Handle that must hold lock */
  59378. Pgno iRoot, /* Root page of b-tree */
  59379. int isIndex, /* True if iRoot is the root of an index b-tree */
  59380. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  59381. ){
  59382. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  59383. Pgno iTab = 0;
  59384. BtLock *pLock;
  59385. /* If this database is not shareable, or if the client is reading
  59386. ** and has the read-uncommitted flag set, then no lock is required.
  59387. ** Return true immediately.
  59388. */
  59389. if( (pBtree->sharable==0)
  59390. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
  59391. ){
  59392. return 1;
  59393. }
  59394. /* If the client is reading or writing an index and the schema is
  59395. ** not loaded, then it is too difficult to actually check to see if
  59396. ** the correct locks are held. So do not bother - just return true.
  59397. ** This case does not come up very often anyhow.
  59398. */
  59399. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  59400. return 1;
  59401. }
  59402. /* Figure out the root-page that the lock should be held on. For table
  59403. ** b-trees, this is just the root page of the b-tree being read or
  59404. ** written. For index b-trees, it is the root page of the associated
  59405. ** table. */
  59406. if( isIndex ){
  59407. HashElem *p;
  59408. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  59409. Index *pIdx = (Index *)sqliteHashData(p);
  59410. if( pIdx->tnum==(int)iRoot ){
  59411. if( iTab ){
  59412. /* Two or more indexes share the same root page. There must
  59413. ** be imposter tables. So just return true. The assert is not
  59414. ** useful in that case. */
  59415. return 1;
  59416. }
  59417. iTab = pIdx->pTable->tnum;
  59418. }
  59419. }
  59420. }else{
  59421. iTab = iRoot;
  59422. }
  59423. /* Search for the required lock. Either a write-lock on root-page iTab, a
  59424. ** write-lock on the schema table, or (if the client is reading) a
  59425. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  59426. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  59427. if( pLock->pBtree==pBtree
  59428. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  59429. && pLock->eLock>=eLockType
  59430. ){
  59431. return 1;
  59432. }
  59433. }
  59434. /* Failed to find the required lock. */
  59435. return 0;
  59436. }
  59437. #endif /* SQLITE_DEBUG */
  59438. #ifdef SQLITE_DEBUG
  59439. /*
  59440. **** This function may be used as part of assert() statements only. ****
  59441. **
  59442. ** Return true if it would be illegal for pBtree to write into the
  59443. ** table or index rooted at iRoot because other shared connections are
  59444. ** simultaneously reading that same table or index.
  59445. **
  59446. ** It is illegal for pBtree to write if some other Btree object that
  59447. ** shares the same BtShared object is currently reading or writing
  59448. ** the iRoot table. Except, if the other Btree object has the
  59449. ** read-uncommitted flag set, then it is OK for the other object to
  59450. ** have a read cursor.
  59451. **
  59452. ** For example, before writing to any part of the table or index
  59453. ** rooted at page iRoot, one should call:
  59454. **
  59455. ** assert( !hasReadConflicts(pBtree, iRoot) );
  59456. */
  59457. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  59458. BtCursor *p;
  59459. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  59460. if( p->pgnoRoot==iRoot
  59461. && p->pBtree!=pBtree
  59462. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
  59463. ){
  59464. return 1;
  59465. }
  59466. }
  59467. return 0;
  59468. }
  59469. #endif /* #ifdef SQLITE_DEBUG */
  59470. /*
  59471. ** Query to see if Btree handle p may obtain a lock of type eLock
  59472. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  59473. ** SQLITE_OK if the lock may be obtained (by calling
  59474. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  59475. */
  59476. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  59477. BtShared *pBt = p->pBt;
  59478. BtLock *pIter;
  59479. assert( sqlite3BtreeHoldsMutex(p) );
  59480. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  59481. assert( p->db!=0 );
  59482. assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
  59483. /* If requesting a write-lock, then the Btree must have an open write
  59484. ** transaction on this file. And, obviously, for this to be so there
  59485. ** must be an open write transaction on the file itself.
  59486. */
  59487. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  59488. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  59489. /* This routine is a no-op if the shared-cache is not enabled */
  59490. if( !p->sharable ){
  59491. return SQLITE_OK;
  59492. }
  59493. /* If some other connection is holding an exclusive lock, the
  59494. ** requested lock may not be obtained.
  59495. */
  59496. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  59497. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  59498. return SQLITE_LOCKED_SHAREDCACHE;
  59499. }
  59500. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  59501. /* The condition (pIter->eLock!=eLock) in the following if(...)
  59502. ** statement is a simplification of:
  59503. **
  59504. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  59505. **
  59506. ** since we know that if eLock==WRITE_LOCK, then no other connection
  59507. ** may hold a WRITE_LOCK on any table in this file (since there can
  59508. ** only be a single writer).
  59509. */
  59510. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  59511. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  59512. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  59513. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  59514. if( eLock==WRITE_LOCK ){
  59515. assert( p==pBt->pWriter );
  59516. pBt->btsFlags |= BTS_PENDING;
  59517. }
  59518. return SQLITE_LOCKED_SHAREDCACHE;
  59519. }
  59520. }
  59521. return SQLITE_OK;
  59522. }
  59523. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  59524. #ifndef SQLITE_OMIT_SHARED_CACHE
  59525. /*
  59526. ** Add a lock on the table with root-page iTable to the shared-btree used
  59527. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  59528. ** WRITE_LOCK.
  59529. **
  59530. ** This function assumes the following:
  59531. **
  59532. ** (a) The specified Btree object p is connected to a sharable
  59533. ** database (one with the BtShared.sharable flag set), and
  59534. **
  59535. ** (b) No other Btree objects hold a lock that conflicts
  59536. ** with the requested lock (i.e. querySharedCacheTableLock() has
  59537. ** already been called and returned SQLITE_OK).
  59538. **
  59539. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  59540. ** is returned if a malloc attempt fails.
  59541. */
  59542. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  59543. BtShared *pBt = p->pBt;
  59544. BtLock *pLock = 0;
  59545. BtLock *pIter;
  59546. assert( sqlite3BtreeHoldsMutex(p) );
  59547. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  59548. assert( p->db!=0 );
  59549. /* A connection with the read-uncommitted flag set will never try to
  59550. ** obtain a read-lock using this function. The only read-lock obtained
  59551. ** by a connection in read-uncommitted mode is on the sqlite_master
  59552. ** table, and that lock is obtained in BtreeBeginTrans(). */
  59553. assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
  59554. /* This function should only be called on a sharable b-tree after it
  59555. ** has been determined that no other b-tree holds a conflicting lock. */
  59556. assert( p->sharable );
  59557. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  59558. /* First search the list for an existing lock on this table. */
  59559. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  59560. if( pIter->iTable==iTable && pIter->pBtree==p ){
  59561. pLock = pIter;
  59562. break;
  59563. }
  59564. }
  59565. /* If the above search did not find a BtLock struct associating Btree p
  59566. ** with table iTable, allocate one and link it into the list.
  59567. */
  59568. if( !pLock ){
  59569. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  59570. if( !pLock ){
  59571. return SQLITE_NOMEM_BKPT;
  59572. }
  59573. pLock->iTable = iTable;
  59574. pLock->pBtree = p;
  59575. pLock->pNext = pBt->pLock;
  59576. pBt->pLock = pLock;
  59577. }
  59578. /* Set the BtLock.eLock variable to the maximum of the current lock
  59579. ** and the requested lock. This means if a write-lock was already held
  59580. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  59581. */
  59582. assert( WRITE_LOCK>READ_LOCK );
  59583. if( eLock>pLock->eLock ){
  59584. pLock->eLock = eLock;
  59585. }
  59586. return SQLITE_OK;
  59587. }
  59588. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  59589. #ifndef SQLITE_OMIT_SHARED_CACHE
  59590. /*
  59591. ** Release all the table locks (locks obtained via calls to
  59592. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  59593. **
  59594. ** This function assumes that Btree p has an open read or write
  59595. ** transaction. If it does not, then the BTS_PENDING flag
  59596. ** may be incorrectly cleared.
  59597. */
  59598. static void clearAllSharedCacheTableLocks(Btree *p){
  59599. BtShared *pBt = p->pBt;
  59600. BtLock **ppIter = &pBt->pLock;
  59601. assert( sqlite3BtreeHoldsMutex(p) );
  59602. assert( p->sharable || 0==*ppIter );
  59603. assert( p->inTrans>0 );
  59604. while( *ppIter ){
  59605. BtLock *pLock = *ppIter;
  59606. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  59607. assert( pLock->pBtree->inTrans>=pLock->eLock );
  59608. if( pLock->pBtree==p ){
  59609. *ppIter = pLock->pNext;
  59610. assert( pLock->iTable!=1 || pLock==&p->lock );
  59611. if( pLock->iTable!=1 ){
  59612. sqlite3_free(pLock);
  59613. }
  59614. }else{
  59615. ppIter = &pLock->pNext;
  59616. }
  59617. }
  59618. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  59619. if( pBt->pWriter==p ){
  59620. pBt->pWriter = 0;
  59621. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  59622. }else if( pBt->nTransaction==2 ){
  59623. /* This function is called when Btree p is concluding its
  59624. ** transaction. If there currently exists a writer, and p is not
  59625. ** that writer, then the number of locks held by connections other
  59626. ** than the writer must be about to drop to zero. In this case
  59627. ** set the BTS_PENDING flag to 0.
  59628. **
  59629. ** If there is not currently a writer, then BTS_PENDING must
  59630. ** be zero already. So this next line is harmless in that case.
  59631. */
  59632. pBt->btsFlags &= ~BTS_PENDING;
  59633. }
  59634. }
  59635. /*
  59636. ** This function changes all write-locks held by Btree p into read-locks.
  59637. */
  59638. static void downgradeAllSharedCacheTableLocks(Btree *p){
  59639. BtShared *pBt = p->pBt;
  59640. if( pBt->pWriter==p ){
  59641. BtLock *pLock;
  59642. pBt->pWriter = 0;
  59643. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  59644. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  59645. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  59646. pLock->eLock = READ_LOCK;
  59647. }
  59648. }
  59649. }
  59650. #endif /* SQLITE_OMIT_SHARED_CACHE */
  59651. static void releasePage(MemPage *pPage); /* Forward reference */
  59652. static void releasePageOne(MemPage *pPage); /* Forward reference */
  59653. static void releasePageNotNull(MemPage *pPage); /* Forward reference */
  59654. /*
  59655. ***** This routine is used inside of assert() only ****
  59656. **
  59657. ** Verify that the cursor holds the mutex on its BtShared
  59658. */
  59659. #ifdef SQLITE_DEBUG
  59660. static int cursorHoldsMutex(BtCursor *p){
  59661. return sqlite3_mutex_held(p->pBt->mutex);
  59662. }
  59663. /* Verify that the cursor and the BtShared agree about what is the current
  59664. ** database connetion. This is important in shared-cache mode. If the database
  59665. ** connection pointers get out-of-sync, it is possible for routines like
  59666. ** btreeInitPage() to reference an stale connection pointer that references a
  59667. ** a connection that has already closed. This routine is used inside assert()
  59668. ** statements only and for the purpose of double-checking that the btree code
  59669. ** does keep the database connection pointers up-to-date.
  59670. */
  59671. static int cursorOwnsBtShared(BtCursor *p){
  59672. assert( cursorHoldsMutex(p) );
  59673. return (p->pBtree->db==p->pBt->db);
  59674. }
  59675. #endif
  59676. /*
  59677. ** Invalidate the overflow cache of the cursor passed as the first argument.
  59678. ** on the shared btree structure pBt.
  59679. */
  59680. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  59681. /*
  59682. ** Invalidate the overflow page-list cache for all cursors opened
  59683. ** on the shared btree structure pBt.
  59684. */
  59685. static void invalidateAllOverflowCache(BtShared *pBt){
  59686. BtCursor *p;
  59687. assert( sqlite3_mutex_held(pBt->mutex) );
  59688. for(p=pBt->pCursor; p; p=p->pNext){
  59689. invalidateOverflowCache(p);
  59690. }
  59691. }
  59692. #ifndef SQLITE_OMIT_INCRBLOB
  59693. /*
  59694. ** This function is called before modifying the contents of a table
  59695. ** to invalidate any incrblob cursors that are open on the
  59696. ** row or one of the rows being modified.
  59697. **
  59698. ** If argument isClearTable is true, then the entire contents of the
  59699. ** table is about to be deleted. In this case invalidate all incrblob
  59700. ** cursors open on any row within the table with root-page pgnoRoot.
  59701. **
  59702. ** Otherwise, if argument isClearTable is false, then the row with
  59703. ** rowid iRow is being replaced or deleted. In this case invalidate
  59704. ** only those incrblob cursors open on that specific row.
  59705. */
  59706. static void invalidateIncrblobCursors(
  59707. Btree *pBtree, /* The database file to check */
  59708. Pgno pgnoRoot, /* The table that might be changing */
  59709. i64 iRow, /* The rowid that might be changing */
  59710. int isClearTable /* True if all rows are being deleted */
  59711. ){
  59712. BtCursor *p;
  59713. if( pBtree->hasIncrblobCur==0 ) return;
  59714. assert( sqlite3BtreeHoldsMutex(pBtree) );
  59715. pBtree->hasIncrblobCur = 0;
  59716. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  59717. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  59718. pBtree->hasIncrblobCur = 1;
  59719. if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
  59720. p->eState = CURSOR_INVALID;
  59721. }
  59722. }
  59723. }
  59724. }
  59725. #else
  59726. /* Stub function when INCRBLOB is omitted */
  59727. #define invalidateIncrblobCursors(w,x,y,z)
  59728. #endif /* SQLITE_OMIT_INCRBLOB */
  59729. /*
  59730. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  59731. ** when a page that previously contained data becomes a free-list leaf
  59732. ** page.
  59733. **
  59734. ** The BtShared.pHasContent bitvec exists to work around an obscure
  59735. ** bug caused by the interaction of two useful IO optimizations surrounding
  59736. ** free-list leaf pages:
  59737. **
  59738. ** 1) When all data is deleted from a page and the page becomes
  59739. ** a free-list leaf page, the page is not written to the database
  59740. ** (as free-list leaf pages contain no meaningful data). Sometimes
  59741. ** such a page is not even journalled (as it will not be modified,
  59742. ** why bother journalling it?).
  59743. **
  59744. ** 2) When a free-list leaf page is reused, its content is not read
  59745. ** from the database or written to the journal file (why should it
  59746. ** be, if it is not at all meaningful?).
  59747. **
  59748. ** By themselves, these optimizations work fine and provide a handy
  59749. ** performance boost to bulk delete or insert operations. However, if
  59750. ** a page is moved to the free-list and then reused within the same
  59751. ** transaction, a problem comes up. If the page is not journalled when
  59752. ** it is moved to the free-list and it is also not journalled when it
  59753. ** is extracted from the free-list and reused, then the original data
  59754. ** may be lost. In the event of a rollback, it may not be possible
  59755. ** to restore the database to its original configuration.
  59756. **
  59757. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  59758. ** moved to become a free-list leaf page, the corresponding bit is
  59759. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  59760. ** optimization 2 above is omitted if the corresponding bit is already
  59761. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  59762. ** at the end of every transaction.
  59763. */
  59764. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  59765. int rc = SQLITE_OK;
  59766. if( !pBt->pHasContent ){
  59767. assert( pgno<=pBt->nPage );
  59768. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  59769. if( !pBt->pHasContent ){
  59770. rc = SQLITE_NOMEM_BKPT;
  59771. }
  59772. }
  59773. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  59774. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  59775. }
  59776. return rc;
  59777. }
  59778. /*
  59779. ** Query the BtShared.pHasContent vector.
  59780. **
  59781. ** This function is called when a free-list leaf page is removed from the
  59782. ** free-list for reuse. It returns false if it is safe to retrieve the
  59783. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  59784. */
  59785. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  59786. Bitvec *p = pBt->pHasContent;
  59787. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  59788. }
  59789. /*
  59790. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  59791. ** invoked at the conclusion of each write-transaction.
  59792. */
  59793. static void btreeClearHasContent(BtShared *pBt){
  59794. sqlite3BitvecDestroy(pBt->pHasContent);
  59795. pBt->pHasContent = 0;
  59796. }
  59797. /*
  59798. ** Release all of the apPage[] pages for a cursor.
  59799. */
  59800. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  59801. int i;
  59802. if( pCur->iPage>=0 ){
  59803. for(i=0; i<pCur->iPage; i++){
  59804. releasePageNotNull(pCur->apPage[i]);
  59805. }
  59806. releasePageNotNull(pCur->pPage);
  59807. pCur->iPage = -1;
  59808. }
  59809. }
  59810. /*
  59811. ** The cursor passed as the only argument must point to a valid entry
  59812. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  59813. ** function saves the current cursor key in variables pCur->nKey and
  59814. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  59815. ** code otherwise.
  59816. **
  59817. ** If the cursor is open on an intkey table, then the integer key
  59818. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  59819. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  59820. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  59821. ** the key.
  59822. */
  59823. static int saveCursorKey(BtCursor *pCur){
  59824. int rc = SQLITE_OK;
  59825. assert( CURSOR_VALID==pCur->eState );
  59826. assert( 0==pCur->pKey );
  59827. assert( cursorHoldsMutex(pCur) );
  59828. if( pCur->curIntKey ){
  59829. /* Only the rowid is required for a table btree */
  59830. pCur->nKey = sqlite3BtreeIntegerKey(pCur);
  59831. }else{
  59832. /* For an index btree, save the complete key content. It is possible
  59833. ** that the current key is corrupt. In that case, it is possible that
  59834. ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
  59835. ** up to the size of 1 varint plus 1 8-byte value when the cursor
  59836. ** position is restored. Hence the 17 bytes of padding allocated
  59837. ** below. */
  59838. void *pKey;
  59839. pCur->nKey = sqlite3BtreePayloadSize(pCur);
  59840. pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
  59841. if( pKey ){
  59842. rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
  59843. if( rc==SQLITE_OK ){
  59844. memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
  59845. pCur->pKey = pKey;
  59846. }else{
  59847. sqlite3_free(pKey);
  59848. }
  59849. }else{
  59850. rc = SQLITE_NOMEM_BKPT;
  59851. }
  59852. }
  59853. assert( !pCur->curIntKey || !pCur->pKey );
  59854. return rc;
  59855. }
  59856. /*
  59857. ** Save the current cursor position in the variables BtCursor.nKey
  59858. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  59859. **
  59860. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  59861. ** prior to calling this routine.
  59862. */
  59863. static int saveCursorPosition(BtCursor *pCur){
  59864. int rc;
  59865. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  59866. assert( 0==pCur->pKey );
  59867. assert( cursorHoldsMutex(pCur) );
  59868. if( pCur->eState==CURSOR_SKIPNEXT ){
  59869. pCur->eState = CURSOR_VALID;
  59870. }else{
  59871. pCur->skipNext = 0;
  59872. }
  59873. rc = saveCursorKey(pCur);
  59874. if( rc==SQLITE_OK ){
  59875. btreeReleaseAllCursorPages(pCur);
  59876. pCur->eState = CURSOR_REQUIRESEEK;
  59877. }
  59878. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  59879. return rc;
  59880. }
  59881. /* Forward reference */
  59882. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  59883. /*
  59884. ** Save the positions of all cursors (except pExcept) that are open on
  59885. ** the table with root-page iRoot. "Saving the cursor position" means that
  59886. ** the location in the btree is remembered in such a way that it can be
  59887. ** moved back to the same spot after the btree has been modified. This
  59888. ** routine is called just before cursor pExcept is used to modify the
  59889. ** table, for example in BtreeDelete() or BtreeInsert().
  59890. **
  59891. ** If there are two or more cursors on the same btree, then all such
  59892. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  59893. ** routine enforces that rule. This routine only needs to be called in
  59894. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  59895. **
  59896. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  59897. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  59898. ** pointless call to this routine.
  59899. **
  59900. ** Implementation note: This routine merely checks to see if any cursors
  59901. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  59902. ** event that cursors are in need to being saved.
  59903. */
  59904. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  59905. BtCursor *p;
  59906. assert( sqlite3_mutex_held(pBt->mutex) );
  59907. assert( pExcept==0 || pExcept->pBt==pBt );
  59908. for(p=pBt->pCursor; p; p=p->pNext){
  59909. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  59910. }
  59911. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  59912. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  59913. return SQLITE_OK;
  59914. }
  59915. /* This helper routine to saveAllCursors does the actual work of saving
  59916. ** the cursors if and when a cursor is found that actually requires saving.
  59917. ** The common case is that no cursors need to be saved, so this routine is
  59918. ** broken out from its caller to avoid unnecessary stack pointer movement.
  59919. */
  59920. static int SQLITE_NOINLINE saveCursorsOnList(
  59921. BtCursor *p, /* The first cursor that needs saving */
  59922. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  59923. BtCursor *pExcept /* Do not save this cursor */
  59924. ){
  59925. do{
  59926. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  59927. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  59928. int rc = saveCursorPosition(p);
  59929. if( SQLITE_OK!=rc ){
  59930. return rc;
  59931. }
  59932. }else{
  59933. testcase( p->iPage>=0 );
  59934. btreeReleaseAllCursorPages(p);
  59935. }
  59936. }
  59937. p = p->pNext;
  59938. }while( p );
  59939. return SQLITE_OK;
  59940. }
  59941. /*
  59942. ** Clear the current cursor position.
  59943. */
  59944. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  59945. assert( cursorHoldsMutex(pCur) );
  59946. sqlite3_free(pCur->pKey);
  59947. pCur->pKey = 0;
  59948. pCur->eState = CURSOR_INVALID;
  59949. }
  59950. /*
  59951. ** In this version of BtreeMoveto, pKey is a packed index record
  59952. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  59953. ** record and then call BtreeMovetoUnpacked() to do the work.
  59954. */
  59955. static int btreeMoveto(
  59956. BtCursor *pCur, /* Cursor open on the btree to be searched */
  59957. const void *pKey, /* Packed key if the btree is an index */
  59958. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  59959. int bias, /* Bias search to the high end */
  59960. int *pRes /* Write search results here */
  59961. ){
  59962. int rc; /* Status code */
  59963. UnpackedRecord *pIdxKey; /* Unpacked index key */
  59964. if( pKey ){
  59965. KeyInfo *pKeyInfo = pCur->pKeyInfo;
  59966. assert( nKey==(i64)(int)nKey );
  59967. pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  59968. if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
  59969. sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
  59970. if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
  59971. rc = SQLITE_CORRUPT_BKPT;
  59972. goto moveto_done;
  59973. }
  59974. }else{
  59975. pIdxKey = 0;
  59976. }
  59977. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  59978. moveto_done:
  59979. if( pIdxKey ){
  59980. sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
  59981. }
  59982. return rc;
  59983. }
  59984. /*
  59985. ** Restore the cursor to the position it was in (or as close to as possible)
  59986. ** when saveCursorPosition() was called. Note that this call deletes the
  59987. ** saved position info stored by saveCursorPosition(), so there can be
  59988. ** at most one effective restoreCursorPosition() call after each
  59989. ** saveCursorPosition().
  59990. */
  59991. static int btreeRestoreCursorPosition(BtCursor *pCur){
  59992. int rc;
  59993. int skipNext = 0;
  59994. assert( cursorOwnsBtShared(pCur) );
  59995. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  59996. if( pCur->eState==CURSOR_FAULT ){
  59997. return pCur->skipNext;
  59998. }
  59999. pCur->eState = CURSOR_INVALID;
  60000. if( sqlite3FaultSim(410) ){
  60001. rc = SQLITE_IOERR;
  60002. }else{
  60003. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  60004. }
  60005. if( rc==SQLITE_OK ){
  60006. sqlite3_free(pCur->pKey);
  60007. pCur->pKey = 0;
  60008. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  60009. if( skipNext ) pCur->skipNext = skipNext;
  60010. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  60011. pCur->eState = CURSOR_SKIPNEXT;
  60012. }
  60013. }
  60014. return rc;
  60015. }
  60016. #define restoreCursorPosition(p) \
  60017. (p->eState>=CURSOR_REQUIRESEEK ? \
  60018. btreeRestoreCursorPosition(p) : \
  60019. SQLITE_OK)
  60020. /*
  60021. ** Determine whether or not a cursor has moved from the position where
  60022. ** it was last placed, or has been invalidated for any other reason.
  60023. ** Cursors can move when the row they are pointing at is deleted out
  60024. ** from under them, for example. Cursor might also move if a btree
  60025. ** is rebalanced.
  60026. **
  60027. ** Calling this routine with a NULL cursor pointer returns false.
  60028. **
  60029. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  60030. ** back to where it ought to be if this routine returns true.
  60031. */
  60032. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  60033. assert( EIGHT_BYTE_ALIGNMENT(pCur)
  60034. || pCur==sqlite3BtreeFakeValidCursor() );
  60035. assert( offsetof(BtCursor, eState)==0 );
  60036. assert( sizeof(pCur->eState)==1 );
  60037. return CURSOR_VALID != *(u8*)pCur;
  60038. }
  60039. /*
  60040. ** Return a pointer to a fake BtCursor object that will always answer
  60041. ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
  60042. ** cursor returned must not be used with any other Btree interface.
  60043. */
  60044. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
  60045. static u8 fakeCursor = CURSOR_VALID;
  60046. assert( offsetof(BtCursor, eState)==0 );
  60047. return (BtCursor*)&fakeCursor;
  60048. }
  60049. /*
  60050. ** This routine restores a cursor back to its original position after it
  60051. ** has been moved by some outside activity (such as a btree rebalance or
  60052. ** a row having been deleted out from under the cursor).
  60053. **
  60054. ** On success, the *pDifferentRow parameter is false if the cursor is left
  60055. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  60056. ** was pointing to has been deleted, forcing the cursor to point to some
  60057. ** nearby row.
  60058. **
  60059. ** This routine should only be called for a cursor that just returned
  60060. ** TRUE from sqlite3BtreeCursorHasMoved().
  60061. */
  60062. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  60063. int rc;
  60064. assert( pCur!=0 );
  60065. assert( pCur->eState!=CURSOR_VALID );
  60066. rc = restoreCursorPosition(pCur);
  60067. if( rc ){
  60068. *pDifferentRow = 1;
  60069. return rc;
  60070. }
  60071. if( pCur->eState!=CURSOR_VALID ){
  60072. *pDifferentRow = 1;
  60073. }else{
  60074. *pDifferentRow = 0;
  60075. }
  60076. return SQLITE_OK;
  60077. }
  60078. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  60079. /*
  60080. ** Provide hints to the cursor. The particular hint given (and the type
  60081. ** and number of the varargs parameters) is determined by the eHintType
  60082. ** parameter. See the definitions of the BTREE_HINT_* macros for details.
  60083. */
  60084. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  60085. /* Used only by system that substitute their own storage engine */
  60086. }
  60087. #endif
  60088. /*
  60089. ** Provide flag hints to the cursor.
  60090. */
  60091. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  60092. assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  60093. pCur->hints = x;
  60094. }
  60095. #ifndef SQLITE_OMIT_AUTOVACUUM
  60096. /*
  60097. ** Given a page number of a regular database page, return the page
  60098. ** number for the pointer-map page that contains the entry for the
  60099. ** input page number.
  60100. **
  60101. ** Return 0 (not a valid page) for pgno==1 since there is
  60102. ** no pointer map associated with page 1. The integrity_check logic
  60103. ** requires that ptrmapPageno(*,1)!=1.
  60104. */
  60105. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  60106. int nPagesPerMapPage;
  60107. Pgno iPtrMap, ret;
  60108. assert( sqlite3_mutex_held(pBt->mutex) );
  60109. if( pgno<2 ) return 0;
  60110. nPagesPerMapPage = (pBt->usableSize/5)+1;
  60111. iPtrMap = (pgno-2)/nPagesPerMapPage;
  60112. ret = (iPtrMap*nPagesPerMapPage) + 2;
  60113. if( ret==PENDING_BYTE_PAGE(pBt) ){
  60114. ret++;
  60115. }
  60116. return ret;
  60117. }
  60118. /*
  60119. ** Write an entry into the pointer map.
  60120. **
  60121. ** This routine updates the pointer map entry for page number 'key'
  60122. ** so that it maps to type 'eType' and parent page number 'pgno'.
  60123. **
  60124. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  60125. ** a no-op. If an error occurs, the appropriate error code is written
  60126. ** into *pRC.
  60127. */
  60128. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  60129. DbPage *pDbPage; /* The pointer map page */
  60130. u8 *pPtrmap; /* The pointer map data */
  60131. Pgno iPtrmap; /* The pointer map page number */
  60132. int offset; /* Offset in pointer map page */
  60133. int rc; /* Return code from subfunctions */
  60134. if( *pRC ) return;
  60135. assert( sqlite3_mutex_held(pBt->mutex) );
  60136. /* The master-journal page number must never be used as a pointer map page */
  60137. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  60138. assert( pBt->autoVacuum );
  60139. if( key==0 ){
  60140. *pRC = SQLITE_CORRUPT_BKPT;
  60141. return;
  60142. }
  60143. iPtrmap = PTRMAP_PAGENO(pBt, key);
  60144. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  60145. if( rc!=SQLITE_OK ){
  60146. *pRC = rc;
  60147. return;
  60148. }
  60149. if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
  60150. /* The first byte of the extra data is the MemPage.isInit byte.
  60151. ** If that byte is set, it means this page is also being used
  60152. ** as a btree page. */
  60153. *pRC = SQLITE_CORRUPT_BKPT;
  60154. goto ptrmap_exit;
  60155. }
  60156. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  60157. if( offset<0 ){
  60158. *pRC = SQLITE_CORRUPT_BKPT;
  60159. goto ptrmap_exit;
  60160. }
  60161. assert( offset <= (int)pBt->usableSize-5 );
  60162. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  60163. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  60164. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  60165. *pRC= rc = sqlite3PagerWrite(pDbPage);
  60166. if( rc==SQLITE_OK ){
  60167. pPtrmap[offset] = eType;
  60168. put4byte(&pPtrmap[offset+1], parent);
  60169. }
  60170. }
  60171. ptrmap_exit:
  60172. sqlite3PagerUnref(pDbPage);
  60173. }
  60174. /*
  60175. ** Read an entry from the pointer map.
  60176. **
  60177. ** This routine retrieves the pointer map entry for page 'key', writing
  60178. ** the type and parent page number to *pEType and *pPgno respectively.
  60179. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  60180. */
  60181. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  60182. DbPage *pDbPage; /* The pointer map page */
  60183. int iPtrmap; /* Pointer map page index */
  60184. u8 *pPtrmap; /* Pointer map page data */
  60185. int offset; /* Offset of entry in pointer map */
  60186. int rc;
  60187. assert( sqlite3_mutex_held(pBt->mutex) );
  60188. iPtrmap = PTRMAP_PAGENO(pBt, key);
  60189. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  60190. if( rc!=0 ){
  60191. return rc;
  60192. }
  60193. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  60194. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  60195. if( offset<0 ){
  60196. sqlite3PagerUnref(pDbPage);
  60197. return SQLITE_CORRUPT_BKPT;
  60198. }
  60199. assert( offset <= (int)pBt->usableSize-5 );
  60200. assert( pEType!=0 );
  60201. *pEType = pPtrmap[offset];
  60202. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  60203. sqlite3PagerUnref(pDbPage);
  60204. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
  60205. return SQLITE_OK;
  60206. }
  60207. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  60208. #define ptrmapPut(w,x,y,z,rc)
  60209. #define ptrmapGet(w,x,y,z) SQLITE_OK
  60210. #define ptrmapPutOvflPtr(x, y, z, rc)
  60211. #endif
  60212. /*
  60213. ** Given a btree page and a cell index (0 means the first cell on
  60214. ** the page, 1 means the second cell, and so forth) return a pointer
  60215. ** to the cell content.
  60216. **
  60217. ** findCellPastPtr() does the same except it skips past the initial
  60218. ** 4-byte child pointer found on interior pages, if there is one.
  60219. **
  60220. ** This routine works only for pages that do not contain overflow cells.
  60221. */
  60222. #define findCell(P,I) \
  60223. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  60224. #define findCellPastPtr(P,I) \
  60225. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  60226. /*
  60227. ** This is common tail processing for btreeParseCellPtr() and
  60228. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  60229. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  60230. ** structure.
  60231. */
  60232. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  60233. MemPage *pPage, /* Page containing the cell */
  60234. u8 *pCell, /* Pointer to the cell text. */
  60235. CellInfo *pInfo /* Fill in this structure */
  60236. ){
  60237. /* If the payload will not fit completely on the local page, we have
  60238. ** to decide how much to store locally and how much to spill onto
  60239. ** overflow pages. The strategy is to minimize the amount of unused
  60240. ** space on overflow pages while keeping the amount of local storage
  60241. ** in between minLocal and maxLocal.
  60242. **
  60243. ** Warning: changing the way overflow payload is distributed in any
  60244. ** way will result in an incompatible file format.
  60245. */
  60246. int minLocal; /* Minimum amount of payload held locally */
  60247. int maxLocal; /* Maximum amount of payload held locally */
  60248. int surplus; /* Overflow payload available for local storage */
  60249. minLocal = pPage->minLocal;
  60250. maxLocal = pPage->maxLocal;
  60251. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  60252. testcase( surplus==maxLocal );
  60253. testcase( surplus==maxLocal+1 );
  60254. if( surplus <= maxLocal ){
  60255. pInfo->nLocal = (u16)surplus;
  60256. }else{
  60257. pInfo->nLocal = (u16)minLocal;
  60258. }
  60259. pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
  60260. }
  60261. /*
  60262. ** The following routines are implementations of the MemPage.xParseCell()
  60263. ** method.
  60264. **
  60265. ** Parse a cell content block and fill in the CellInfo structure.
  60266. **
  60267. ** btreeParseCellPtr() => table btree leaf nodes
  60268. ** btreeParseCellNoPayload() => table btree internal nodes
  60269. ** btreeParseCellPtrIndex() => index btree nodes
  60270. **
  60271. ** There is also a wrapper function btreeParseCell() that works for
  60272. ** all MemPage types and that references the cell by index rather than
  60273. ** by pointer.
  60274. */
  60275. static void btreeParseCellPtrNoPayload(
  60276. MemPage *pPage, /* Page containing the cell */
  60277. u8 *pCell, /* Pointer to the cell text. */
  60278. CellInfo *pInfo /* Fill in this structure */
  60279. ){
  60280. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60281. assert( pPage->leaf==0 );
  60282. assert( pPage->childPtrSize==4 );
  60283. #ifndef SQLITE_DEBUG
  60284. UNUSED_PARAMETER(pPage);
  60285. #endif
  60286. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  60287. pInfo->nPayload = 0;
  60288. pInfo->nLocal = 0;
  60289. pInfo->pPayload = 0;
  60290. return;
  60291. }
  60292. static void btreeParseCellPtr(
  60293. MemPage *pPage, /* Page containing the cell */
  60294. u8 *pCell, /* Pointer to the cell text. */
  60295. CellInfo *pInfo /* Fill in this structure */
  60296. ){
  60297. u8 *pIter; /* For scanning through pCell */
  60298. u32 nPayload; /* Number of bytes of cell payload */
  60299. u64 iKey; /* Extracted Key value */
  60300. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60301. assert( pPage->leaf==0 || pPage->leaf==1 );
  60302. assert( pPage->intKeyLeaf );
  60303. assert( pPage->childPtrSize==0 );
  60304. pIter = pCell;
  60305. /* The next block of code is equivalent to:
  60306. **
  60307. ** pIter += getVarint32(pIter, nPayload);
  60308. **
  60309. ** The code is inlined to avoid a function call.
  60310. */
  60311. nPayload = *pIter;
  60312. if( nPayload>=0x80 ){
  60313. u8 *pEnd = &pIter[8];
  60314. nPayload &= 0x7f;
  60315. do{
  60316. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  60317. }while( (*pIter)>=0x80 && pIter<pEnd );
  60318. }
  60319. pIter++;
  60320. /* The next block of code is equivalent to:
  60321. **
  60322. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  60323. **
  60324. ** The code is inlined to avoid a function call.
  60325. */
  60326. iKey = *pIter;
  60327. if( iKey>=0x80 ){
  60328. u8 *pEnd = &pIter[7];
  60329. iKey &= 0x7f;
  60330. while(1){
  60331. iKey = (iKey<<7) | (*++pIter & 0x7f);
  60332. if( (*pIter)<0x80 ) break;
  60333. if( pIter>=pEnd ){
  60334. iKey = (iKey<<8) | *++pIter;
  60335. break;
  60336. }
  60337. }
  60338. }
  60339. pIter++;
  60340. pInfo->nKey = *(i64*)&iKey;
  60341. pInfo->nPayload = nPayload;
  60342. pInfo->pPayload = pIter;
  60343. testcase( nPayload==pPage->maxLocal );
  60344. testcase( nPayload==pPage->maxLocal+1 );
  60345. if( nPayload<=pPage->maxLocal ){
  60346. /* This is the (easy) common case where the entire payload fits
  60347. ** on the local page. No overflow is required.
  60348. */
  60349. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  60350. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  60351. pInfo->nLocal = (u16)nPayload;
  60352. }else{
  60353. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  60354. }
  60355. }
  60356. static void btreeParseCellPtrIndex(
  60357. MemPage *pPage, /* Page containing the cell */
  60358. u8 *pCell, /* Pointer to the cell text. */
  60359. CellInfo *pInfo /* Fill in this structure */
  60360. ){
  60361. u8 *pIter; /* For scanning through pCell */
  60362. u32 nPayload; /* Number of bytes of cell payload */
  60363. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60364. assert( pPage->leaf==0 || pPage->leaf==1 );
  60365. assert( pPage->intKeyLeaf==0 );
  60366. pIter = pCell + pPage->childPtrSize;
  60367. nPayload = *pIter;
  60368. if( nPayload>=0x80 ){
  60369. u8 *pEnd = &pIter[8];
  60370. nPayload &= 0x7f;
  60371. do{
  60372. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  60373. }while( *(pIter)>=0x80 && pIter<pEnd );
  60374. }
  60375. pIter++;
  60376. pInfo->nKey = nPayload;
  60377. pInfo->nPayload = nPayload;
  60378. pInfo->pPayload = pIter;
  60379. testcase( nPayload==pPage->maxLocal );
  60380. testcase( nPayload==pPage->maxLocal+1 );
  60381. if( nPayload<=pPage->maxLocal ){
  60382. /* This is the (easy) common case where the entire payload fits
  60383. ** on the local page. No overflow is required.
  60384. */
  60385. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  60386. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  60387. pInfo->nLocal = (u16)nPayload;
  60388. }else{
  60389. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  60390. }
  60391. }
  60392. static void btreeParseCell(
  60393. MemPage *pPage, /* Page containing the cell */
  60394. int iCell, /* The cell index. First cell is 0 */
  60395. CellInfo *pInfo /* Fill in this structure */
  60396. ){
  60397. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  60398. }
  60399. /*
  60400. ** The following routines are implementations of the MemPage.xCellSize
  60401. ** method.
  60402. **
  60403. ** Compute the total number of bytes that a Cell needs in the cell
  60404. ** data area of the btree-page. The return number includes the cell
  60405. ** data header and the local payload, but not any overflow page or
  60406. ** the space used by the cell pointer.
  60407. **
  60408. ** cellSizePtrNoPayload() => table internal nodes
  60409. ** cellSizePtr() => all index nodes & table leaf nodes
  60410. */
  60411. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  60412. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  60413. u8 *pEnd; /* End mark for a varint */
  60414. u32 nSize; /* Size value to return */
  60415. #ifdef SQLITE_DEBUG
  60416. /* The value returned by this function should always be the same as
  60417. ** the (CellInfo.nSize) value found by doing a full parse of the
  60418. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  60419. ** this function verifies that this invariant is not violated. */
  60420. CellInfo debuginfo;
  60421. pPage->xParseCell(pPage, pCell, &debuginfo);
  60422. #endif
  60423. nSize = *pIter;
  60424. if( nSize>=0x80 ){
  60425. pEnd = &pIter[8];
  60426. nSize &= 0x7f;
  60427. do{
  60428. nSize = (nSize<<7) | (*++pIter & 0x7f);
  60429. }while( *(pIter)>=0x80 && pIter<pEnd );
  60430. }
  60431. pIter++;
  60432. if( pPage->intKey ){
  60433. /* pIter now points at the 64-bit integer key value, a variable length
  60434. ** integer. The following block moves pIter to point at the first byte
  60435. ** past the end of the key value. */
  60436. pEnd = &pIter[9];
  60437. while( (*pIter++)&0x80 && pIter<pEnd );
  60438. }
  60439. testcase( nSize==pPage->maxLocal );
  60440. testcase( nSize==pPage->maxLocal+1 );
  60441. if( nSize<=pPage->maxLocal ){
  60442. nSize += (u32)(pIter - pCell);
  60443. if( nSize<4 ) nSize = 4;
  60444. }else{
  60445. int minLocal = pPage->minLocal;
  60446. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  60447. testcase( nSize==pPage->maxLocal );
  60448. testcase( nSize==pPage->maxLocal+1 );
  60449. if( nSize>pPage->maxLocal ){
  60450. nSize = minLocal;
  60451. }
  60452. nSize += 4 + (u16)(pIter - pCell);
  60453. }
  60454. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  60455. return (u16)nSize;
  60456. }
  60457. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  60458. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  60459. u8 *pEnd; /* End mark for a varint */
  60460. #ifdef SQLITE_DEBUG
  60461. /* The value returned by this function should always be the same as
  60462. ** the (CellInfo.nSize) value found by doing a full parse of the
  60463. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  60464. ** this function verifies that this invariant is not violated. */
  60465. CellInfo debuginfo;
  60466. pPage->xParseCell(pPage, pCell, &debuginfo);
  60467. #else
  60468. UNUSED_PARAMETER(pPage);
  60469. #endif
  60470. assert( pPage->childPtrSize==4 );
  60471. pEnd = pIter + 9;
  60472. while( (*pIter++)&0x80 && pIter<pEnd );
  60473. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  60474. return (u16)(pIter - pCell);
  60475. }
  60476. #ifdef SQLITE_DEBUG
  60477. /* This variation on cellSizePtr() is used inside of assert() statements
  60478. ** only. */
  60479. static u16 cellSize(MemPage *pPage, int iCell){
  60480. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  60481. }
  60482. #endif
  60483. #ifndef SQLITE_OMIT_AUTOVACUUM
  60484. /*
  60485. ** The cell pCell is currently part of page pSrc but will ultimately be part
  60486. ** of pPage. (pSrc and pPager are often the same.) If pCell contains a
  60487. ** pointer to an overflow page, insert an entry into the pointer-map for
  60488. ** the overflow page that will be valid after pCell has been moved to pPage.
  60489. */
  60490. static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
  60491. CellInfo info;
  60492. if( *pRC ) return;
  60493. assert( pCell!=0 );
  60494. pPage->xParseCell(pPage, pCell, &info);
  60495. if( info.nLocal<info.nPayload ){
  60496. Pgno ovfl;
  60497. if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
  60498. testcase( pSrc!=pPage );
  60499. *pRC = SQLITE_CORRUPT_BKPT;
  60500. return;
  60501. }
  60502. ovfl = get4byte(&pCell[info.nSize-4]);
  60503. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  60504. }
  60505. }
  60506. #endif
  60507. /*
  60508. ** Defragment the page given. This routine reorganizes cells within the
  60509. ** page so that there are no free-blocks on the free-block list.
  60510. **
  60511. ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
  60512. ** present in the page after this routine returns.
  60513. **
  60514. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  60515. ** b-tree page so that there are no freeblocks or fragment bytes, all
  60516. ** unused bytes are contained in the unallocated space region, and all
  60517. ** cells are packed tightly at the end of the page.
  60518. */
  60519. static int defragmentPage(MemPage *pPage, int nMaxFrag){
  60520. int i; /* Loop counter */
  60521. int pc; /* Address of the i-th cell */
  60522. int hdr; /* Offset to the page header */
  60523. int size; /* Size of a cell */
  60524. int usableSize; /* Number of usable bytes on a page */
  60525. int cellOffset; /* Offset to the cell pointer array */
  60526. int cbrk; /* Offset to the cell content area */
  60527. int nCell; /* Number of cells on the page */
  60528. unsigned char *data; /* The page data */
  60529. unsigned char *temp; /* Temp area for cell content */
  60530. unsigned char *src; /* Source of content */
  60531. int iCellFirst; /* First allowable cell index */
  60532. int iCellLast; /* Last possible cell index */
  60533. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60534. assert( pPage->pBt!=0 );
  60535. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  60536. assert( pPage->nOverflow==0 );
  60537. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60538. temp = 0;
  60539. src = data = pPage->aData;
  60540. hdr = pPage->hdrOffset;
  60541. cellOffset = pPage->cellOffset;
  60542. nCell = pPage->nCell;
  60543. assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
  60544. iCellFirst = cellOffset + 2*nCell;
  60545. usableSize = pPage->pBt->usableSize;
  60546. /* This block handles pages with two or fewer free blocks and nMaxFrag
  60547. ** or fewer fragmented bytes. In this case it is faster to move the
  60548. ** two (or one) blocks of cells using memmove() and add the required
  60549. ** offsets to each pointer in the cell-pointer array than it is to
  60550. ** reconstruct the entire page. */
  60551. if( (int)data[hdr+7]<=nMaxFrag ){
  60552. int iFree = get2byte(&data[hdr+1]);
  60553. if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
  60554. if( iFree ){
  60555. int iFree2 = get2byte(&data[iFree]);
  60556. if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
  60557. if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
  60558. u8 *pEnd = &data[cellOffset + nCell*2];
  60559. u8 *pAddr;
  60560. int sz2 = 0;
  60561. int sz = get2byte(&data[iFree+2]);
  60562. int top = get2byte(&data[hdr+5]);
  60563. if( top>=iFree ){
  60564. return SQLITE_CORRUPT_PAGE(pPage);
  60565. }
  60566. if( iFree2 ){
  60567. if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
  60568. sz2 = get2byte(&data[iFree2+2]);
  60569. if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
  60570. memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
  60571. sz += sz2;
  60572. }else if( iFree+sz>usableSize ){
  60573. return SQLITE_CORRUPT_PAGE(pPage);
  60574. }
  60575. cbrk = top+sz;
  60576. assert( cbrk+(iFree-top) <= usableSize );
  60577. memmove(&data[cbrk], &data[top], iFree-top);
  60578. for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
  60579. pc = get2byte(pAddr);
  60580. if( pc<iFree ){ put2byte(pAddr, pc+sz); }
  60581. else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
  60582. }
  60583. goto defragment_out;
  60584. }
  60585. }
  60586. }
  60587. cbrk = usableSize;
  60588. iCellLast = usableSize - 4;
  60589. for(i=0; i<nCell; i++){
  60590. u8 *pAddr; /* The i-th cell pointer */
  60591. pAddr = &data[cellOffset + i*2];
  60592. pc = get2byte(pAddr);
  60593. testcase( pc==iCellFirst );
  60594. testcase( pc==iCellLast );
  60595. /* These conditions have already been verified in btreeInitPage()
  60596. ** if PRAGMA cell_size_check=ON.
  60597. */
  60598. if( pc<iCellFirst || pc>iCellLast ){
  60599. return SQLITE_CORRUPT_PAGE(pPage);
  60600. }
  60601. assert( pc>=iCellFirst && pc<=iCellLast );
  60602. size = pPage->xCellSize(pPage, &src[pc]);
  60603. cbrk -= size;
  60604. if( cbrk<iCellFirst || pc+size>usableSize ){
  60605. return SQLITE_CORRUPT_PAGE(pPage);
  60606. }
  60607. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  60608. testcase( cbrk+size==usableSize );
  60609. testcase( pc+size==usableSize );
  60610. put2byte(pAddr, cbrk);
  60611. if( temp==0 ){
  60612. int x;
  60613. if( cbrk==pc ) continue;
  60614. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  60615. x = get2byte(&data[hdr+5]);
  60616. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  60617. src = temp;
  60618. }
  60619. memcpy(&data[cbrk], &src[pc], size);
  60620. }
  60621. data[hdr+7] = 0;
  60622. defragment_out:
  60623. assert( pPage->nFree>=0 );
  60624. if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
  60625. return SQLITE_CORRUPT_PAGE(pPage);
  60626. }
  60627. assert( cbrk>=iCellFirst );
  60628. put2byte(&data[hdr+5], cbrk);
  60629. data[hdr+1] = 0;
  60630. data[hdr+2] = 0;
  60631. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  60632. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60633. return SQLITE_OK;
  60634. }
  60635. /*
  60636. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  60637. ** size. If one can be found, return a pointer to the space and remove it
  60638. ** from the free-list.
  60639. **
  60640. ** If no suitable space can be found on the free-list, return NULL.
  60641. **
  60642. ** This function may detect corruption within pPg. If corruption is
  60643. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  60644. **
  60645. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  60646. ** will be ignored if adding the extra space to the fragmentation count
  60647. ** causes the fragmentation count to exceed 60.
  60648. */
  60649. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  60650. const int hdr = pPg->hdrOffset; /* Offset to page header */
  60651. u8 * const aData = pPg->aData; /* Page data */
  60652. int iAddr = hdr + 1; /* Address of ptr to pc */
  60653. int pc = get2byte(&aData[iAddr]); /* Address of a free slot */
  60654. int x; /* Excess size of the slot */
  60655. int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
  60656. int size; /* Size of the free slot */
  60657. assert( pc>0 );
  60658. while( pc<=maxPC ){
  60659. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  60660. ** freeblock form a big-endian integer which is the size of the freeblock
  60661. ** in bytes, including the 4-byte header. */
  60662. size = get2byte(&aData[pc+2]);
  60663. if( (x = size - nByte)>=0 ){
  60664. testcase( x==4 );
  60665. testcase( x==3 );
  60666. if( x<4 ){
  60667. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  60668. ** number of bytes in fragments may not exceed 60. */
  60669. if( aData[hdr+7]>57 ) return 0;
  60670. /* Remove the slot from the free-list. Update the number of
  60671. ** fragmented bytes within the page. */
  60672. memcpy(&aData[iAddr], &aData[pc], 2);
  60673. aData[hdr+7] += (u8)x;
  60674. }else if( x+pc > maxPC ){
  60675. /* This slot extends off the end of the usable part of the page */
  60676. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  60677. return 0;
  60678. }else{
  60679. /* The slot remains on the free-list. Reduce its size to account
  60680. ** for the portion used by the new allocation. */
  60681. put2byte(&aData[pc+2], x);
  60682. }
  60683. return &aData[pc + x];
  60684. }
  60685. iAddr = pc;
  60686. pc = get2byte(&aData[pc]);
  60687. if( pc<=iAddr+size ){
  60688. if( pc ){
  60689. /* The next slot in the chain is not past the end of the current slot */
  60690. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  60691. }
  60692. return 0;
  60693. }
  60694. }
  60695. if( pc>maxPC+nByte-4 ){
  60696. /* The free slot chain extends off the end of the page */
  60697. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  60698. }
  60699. return 0;
  60700. }
  60701. /*
  60702. ** Allocate nByte bytes of space from within the B-Tree page passed
  60703. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  60704. ** of the first byte of allocated space. Return either SQLITE_OK or
  60705. ** an error code (usually SQLITE_CORRUPT).
  60706. **
  60707. ** The caller guarantees that there is sufficient space to make the
  60708. ** allocation. This routine might need to defragment in order to bring
  60709. ** all the space together, however. This routine will avoid using
  60710. ** the first two bytes past the cell pointer area since presumably this
  60711. ** allocation is being made in order to insert a new cell, so we will
  60712. ** also end up needing a new cell pointer.
  60713. */
  60714. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  60715. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  60716. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  60717. int top; /* First byte of cell content area */
  60718. int rc = SQLITE_OK; /* Integer return code */
  60719. int gap; /* First byte of gap between cell pointers and cell content */
  60720. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60721. assert( pPage->pBt );
  60722. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60723. assert( nByte>=0 ); /* Minimum cell size is 4 */
  60724. assert( pPage->nFree>=nByte );
  60725. assert( pPage->nOverflow==0 );
  60726. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  60727. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  60728. gap = pPage->cellOffset + 2*pPage->nCell;
  60729. assert( gap<=65536 );
  60730. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  60731. ** and the reserved space is zero (the usual value for reserved space)
  60732. ** then the cell content offset of an empty page wants to be 65536.
  60733. ** However, that integer is too large to be stored in a 2-byte unsigned
  60734. ** integer, so a value of 0 is used in its place. */
  60735. top = get2byte(&data[hdr+5]);
  60736. assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
  60737. if( gap>top ){
  60738. if( top==0 && pPage->pBt->usableSize==65536 ){
  60739. top = 65536;
  60740. }else{
  60741. return SQLITE_CORRUPT_PAGE(pPage);
  60742. }
  60743. }
  60744. /* If there is enough space between gap and top for one more cell pointer,
  60745. ** and if the freelist is not empty, then search the
  60746. ** freelist looking for a slot big enough to satisfy the request.
  60747. */
  60748. testcase( gap+2==top );
  60749. testcase( gap+1==top );
  60750. testcase( gap==top );
  60751. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  60752. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  60753. if( pSpace ){
  60754. assert( pSpace>=data && (pSpace - data)<65536 );
  60755. *pIdx = (int)(pSpace - data);
  60756. return SQLITE_OK;
  60757. }else if( rc ){
  60758. return rc;
  60759. }
  60760. }
  60761. /* The request could not be fulfilled using a freelist slot. Check
  60762. ** to see if defragmentation is necessary.
  60763. */
  60764. testcase( gap+2+nByte==top );
  60765. if( gap+2+nByte>top ){
  60766. assert( pPage->nCell>0 || CORRUPT_DB );
  60767. assert( pPage->nFree>=0 );
  60768. rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
  60769. if( rc ) return rc;
  60770. top = get2byteNotZero(&data[hdr+5]);
  60771. assert( gap+2+nByte<=top );
  60772. }
  60773. /* Allocate memory from the gap in between the cell pointer array
  60774. ** and the cell content area. The btreeComputeFreeSpace() call has already
  60775. ** validated the freelist. Given that the freelist is valid, there
  60776. ** is no way that the allocation can extend off the end of the page.
  60777. ** The assert() below verifies the previous sentence.
  60778. */
  60779. top -= nByte;
  60780. put2byte(&data[hdr+5], top);
  60781. assert( top+nByte <= (int)pPage->pBt->usableSize );
  60782. *pIdx = top;
  60783. return SQLITE_OK;
  60784. }
  60785. /*
  60786. ** Return a section of the pPage->aData to the freelist.
  60787. ** The first byte of the new free block is pPage->aData[iStart]
  60788. ** and the size of the block is iSize bytes.
  60789. **
  60790. ** Adjacent freeblocks are coalesced.
  60791. **
  60792. ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
  60793. ** that routine will not detect overlap between cells or freeblocks. Nor
  60794. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  60795. ** at the end of the page. So do additional corruption checks inside this
  60796. ** routine and return SQLITE_CORRUPT if any problems are found.
  60797. */
  60798. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  60799. u16 iPtr; /* Address of ptr to next freeblock */
  60800. u16 iFreeBlk; /* Address of the next freeblock */
  60801. u8 hdr; /* Page header size. 0 or 100 */
  60802. u8 nFrag = 0; /* Reduction in fragmentation */
  60803. u16 iOrigSize = iSize; /* Original value of iSize */
  60804. u16 x; /* Offset to cell content area */
  60805. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  60806. unsigned char *data = pPage->aData; /* Page content */
  60807. assert( pPage->pBt!=0 );
  60808. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60809. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  60810. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  60811. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60812. assert( iSize>=4 ); /* Minimum cell size is 4 */
  60813. assert( iStart<=pPage->pBt->usableSize-4 );
  60814. /* The list of freeblocks must be in ascending order. Find the
  60815. ** spot on the list where iStart should be inserted.
  60816. */
  60817. hdr = pPage->hdrOffset;
  60818. iPtr = hdr + 1;
  60819. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  60820. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  60821. }else{
  60822. while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
  60823. if( iFreeBlk<iPtr+4 ){
  60824. if( iFreeBlk==0 ) break;
  60825. return SQLITE_CORRUPT_PAGE(pPage);
  60826. }
  60827. iPtr = iFreeBlk;
  60828. }
  60829. if( iFreeBlk>pPage->pBt->usableSize-4 ){
  60830. return SQLITE_CORRUPT_PAGE(pPage);
  60831. }
  60832. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  60833. /* At this point:
  60834. ** iFreeBlk: First freeblock after iStart, or zero if none
  60835. ** iPtr: The address of a pointer to iFreeBlk
  60836. **
  60837. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  60838. */
  60839. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  60840. nFrag = iFreeBlk - iEnd;
  60841. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
  60842. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  60843. if( iEnd > pPage->pBt->usableSize ){
  60844. return SQLITE_CORRUPT_PAGE(pPage);
  60845. }
  60846. iSize = iEnd - iStart;
  60847. iFreeBlk = get2byte(&data[iFreeBlk]);
  60848. }
  60849. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  60850. ** pointer in the page header) then check to see if iStart should be
  60851. ** coalesced onto the end of iPtr.
  60852. */
  60853. if( iPtr>hdr+1 ){
  60854. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  60855. if( iPtrEnd+3>=iStart ){
  60856. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
  60857. nFrag += iStart - iPtrEnd;
  60858. iSize = iEnd - iPtr;
  60859. iStart = iPtr;
  60860. }
  60861. }
  60862. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
  60863. data[hdr+7] -= nFrag;
  60864. }
  60865. x = get2byte(&data[hdr+5]);
  60866. if( iStart<=x ){
  60867. /* The new freeblock is at the beginning of the cell content area,
  60868. ** so just extend the cell content area rather than create another
  60869. ** freelist entry */
  60870. if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
  60871. put2byte(&data[hdr+1], iFreeBlk);
  60872. put2byte(&data[hdr+5], iEnd);
  60873. }else{
  60874. /* Insert the new freeblock into the freelist */
  60875. put2byte(&data[iPtr], iStart);
  60876. }
  60877. if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
  60878. /* Overwrite deleted information with zeros when the secure_delete
  60879. ** option is enabled */
  60880. memset(&data[iStart], 0, iSize);
  60881. }
  60882. put2byte(&data[iStart], iFreeBlk);
  60883. put2byte(&data[iStart+2], iSize);
  60884. pPage->nFree += iOrigSize;
  60885. return SQLITE_OK;
  60886. }
  60887. /*
  60888. ** Decode the flags byte (the first byte of the header) for a page
  60889. ** and initialize fields of the MemPage structure accordingly.
  60890. **
  60891. ** Only the following combinations are supported. Anything different
  60892. ** indicates a corrupt database files:
  60893. **
  60894. ** PTF_ZERODATA
  60895. ** PTF_ZERODATA | PTF_LEAF
  60896. ** PTF_LEAFDATA | PTF_INTKEY
  60897. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  60898. */
  60899. static int decodeFlags(MemPage *pPage, int flagByte){
  60900. BtShared *pBt; /* A copy of pPage->pBt */
  60901. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  60902. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60903. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  60904. flagByte &= ~PTF_LEAF;
  60905. pPage->childPtrSize = 4-4*pPage->leaf;
  60906. pPage->xCellSize = cellSizePtr;
  60907. pBt = pPage->pBt;
  60908. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  60909. /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
  60910. ** interior table b-tree page. */
  60911. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  60912. /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
  60913. ** leaf table b-tree page. */
  60914. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  60915. pPage->intKey = 1;
  60916. if( pPage->leaf ){
  60917. pPage->intKeyLeaf = 1;
  60918. pPage->xParseCell = btreeParseCellPtr;
  60919. }else{
  60920. pPage->intKeyLeaf = 0;
  60921. pPage->xCellSize = cellSizePtrNoPayload;
  60922. pPage->xParseCell = btreeParseCellPtrNoPayload;
  60923. }
  60924. pPage->maxLocal = pBt->maxLeaf;
  60925. pPage->minLocal = pBt->minLeaf;
  60926. }else if( flagByte==PTF_ZERODATA ){
  60927. /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
  60928. ** interior index b-tree page. */
  60929. assert( (PTF_ZERODATA)==2 );
  60930. /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
  60931. ** leaf index b-tree page. */
  60932. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  60933. pPage->intKey = 0;
  60934. pPage->intKeyLeaf = 0;
  60935. pPage->xParseCell = btreeParseCellPtrIndex;
  60936. pPage->maxLocal = pBt->maxLocal;
  60937. pPage->minLocal = pBt->minLocal;
  60938. }else{
  60939. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  60940. ** an error. */
  60941. return SQLITE_CORRUPT_PAGE(pPage);
  60942. }
  60943. pPage->max1bytePayload = pBt->max1bytePayload;
  60944. return SQLITE_OK;
  60945. }
  60946. /*
  60947. ** Compute the amount of freespace on the page. In other words, fill
  60948. ** in the pPage->nFree field.
  60949. */
  60950. static int btreeComputeFreeSpace(MemPage *pPage){
  60951. int pc; /* Address of a freeblock within pPage->aData[] */
  60952. u8 hdr; /* Offset to beginning of page header */
  60953. u8 *data; /* Equal to pPage->aData */
  60954. int usableSize; /* Amount of usable space on each page */
  60955. int nFree; /* Number of unused bytes on the page */
  60956. int top; /* First byte of the cell content area */
  60957. int iCellFirst; /* First allowable cell or freeblock offset */
  60958. int iCellLast; /* Last possible cell or freeblock offset */
  60959. assert( pPage->pBt!=0 );
  60960. assert( pPage->pBt->db!=0 );
  60961. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60962. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  60963. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  60964. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  60965. assert( pPage->isInit==1 );
  60966. assert( pPage->nFree<0 );
  60967. usableSize = pPage->pBt->usableSize;
  60968. hdr = pPage->hdrOffset;
  60969. data = pPage->aData;
  60970. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  60971. ** the start of the cell content area. A zero value for this integer is
  60972. ** interpreted as 65536. */
  60973. top = get2byteNotZero(&data[hdr+5]);
  60974. iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
  60975. iCellLast = usableSize - 4;
  60976. /* Compute the total free space on the page
  60977. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  60978. ** start of the first freeblock on the page, or is zero if there are no
  60979. ** freeblocks. */
  60980. pc = get2byte(&data[hdr+1]);
  60981. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  60982. if( pc>0 ){
  60983. u32 next, size;
  60984. if( pc<iCellFirst ){
  60985. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  60986. ** always be at least one cell before the first freeblock.
  60987. */
  60988. return SQLITE_CORRUPT_PAGE(pPage);
  60989. }
  60990. while( 1 ){
  60991. if( pc>iCellLast ){
  60992. /* Freeblock off the end of the page */
  60993. return SQLITE_CORRUPT_PAGE(pPage);
  60994. }
  60995. next = get2byte(&data[pc]);
  60996. size = get2byte(&data[pc+2]);
  60997. nFree = nFree + size;
  60998. if( next<=pc+size+3 ) break;
  60999. pc = next;
  61000. }
  61001. if( next>0 ){
  61002. /* Freeblock not in ascending order */
  61003. return SQLITE_CORRUPT_PAGE(pPage);
  61004. }
  61005. if( pc+size>(unsigned int)usableSize ){
  61006. /* Last freeblock extends past page end */
  61007. return SQLITE_CORRUPT_PAGE(pPage);
  61008. }
  61009. }
  61010. /* At this point, nFree contains the sum of the offset to the start
  61011. ** of the cell-content area plus the number of free bytes within
  61012. ** the cell-content area. If this is greater than the usable-size
  61013. ** of the page, then the page must be corrupted. This check also
  61014. ** serves to verify that the offset to the start of the cell-content
  61015. ** area, according to the page header, lies within the page.
  61016. */
  61017. if( nFree>usableSize ){
  61018. return SQLITE_CORRUPT_PAGE(pPage);
  61019. }
  61020. pPage->nFree = (u16)(nFree - iCellFirst);
  61021. return SQLITE_OK;
  61022. }
  61023. /*
  61024. ** Do additional sanity check after btreeInitPage() if
  61025. ** PRAGMA cell_size_check=ON
  61026. */
  61027. static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
  61028. int iCellFirst; /* First allowable cell or freeblock offset */
  61029. int iCellLast; /* Last possible cell or freeblock offset */
  61030. int i; /* Index into the cell pointer array */
  61031. int sz; /* Size of a cell */
  61032. int pc; /* Address of a freeblock within pPage->aData[] */
  61033. u8 *data; /* Equal to pPage->aData */
  61034. int usableSize; /* Maximum usable space on the page */
  61035. int cellOffset; /* Start of cell content area */
  61036. iCellFirst = pPage->cellOffset + 2*pPage->nCell;
  61037. usableSize = pPage->pBt->usableSize;
  61038. iCellLast = usableSize - 4;
  61039. data = pPage->aData;
  61040. cellOffset = pPage->cellOffset;
  61041. if( !pPage->leaf ) iCellLast--;
  61042. for(i=0; i<pPage->nCell; i++){
  61043. pc = get2byteAligned(&data[cellOffset+i*2]);
  61044. testcase( pc==iCellFirst );
  61045. testcase( pc==iCellLast );
  61046. if( pc<iCellFirst || pc>iCellLast ){
  61047. return SQLITE_CORRUPT_PAGE(pPage);
  61048. }
  61049. sz = pPage->xCellSize(pPage, &data[pc]);
  61050. testcase( pc+sz==usableSize );
  61051. if( pc+sz>usableSize ){
  61052. return SQLITE_CORRUPT_PAGE(pPage);
  61053. }
  61054. }
  61055. return SQLITE_OK;
  61056. }
  61057. /*
  61058. ** Initialize the auxiliary information for a disk block.
  61059. **
  61060. ** Return SQLITE_OK on success. If we see that the page does
  61061. ** not contain a well-formed database page, then return
  61062. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  61063. ** guarantee that the page is well-formed. It only shows that
  61064. ** we failed to detect any corruption.
  61065. */
  61066. static int btreeInitPage(MemPage *pPage){
  61067. u8 *data; /* Equal to pPage->aData */
  61068. BtShared *pBt; /* The main btree structure */
  61069. assert( pPage->pBt!=0 );
  61070. assert( pPage->pBt->db!=0 );
  61071. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61072. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  61073. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  61074. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  61075. assert( pPage->isInit==0 );
  61076. pBt = pPage->pBt;
  61077. data = pPage->aData + pPage->hdrOffset;
  61078. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  61079. ** the b-tree page type. */
  61080. if( decodeFlags(pPage, data[0]) ){
  61081. return SQLITE_CORRUPT_PAGE(pPage);
  61082. }
  61083. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  61084. pPage->maskPage = (u16)(pBt->pageSize - 1);
  61085. pPage->nOverflow = 0;
  61086. pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
  61087. pPage->aCellIdx = data + pPage->childPtrSize + 8;
  61088. pPage->aDataEnd = pPage->aData + pBt->usableSize;
  61089. pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
  61090. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  61091. ** number of cells on the page. */
  61092. pPage->nCell = get2byte(&data[3]);
  61093. if( pPage->nCell>MX_CELL(pBt) ){
  61094. /* To many cells for a single page. The page must be corrupt */
  61095. return SQLITE_CORRUPT_PAGE(pPage);
  61096. }
  61097. testcase( pPage->nCell==MX_CELL(pBt) );
  61098. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  61099. ** possible for a root page of a table that contains no rows) then the
  61100. ** offset to the cell content area will equal the page size minus the
  61101. ** bytes of reserved space. */
  61102. assert( pPage->nCell>0
  61103. || get2byteNotZero(&data[5])==(int)pBt->usableSize
  61104. || CORRUPT_DB );
  61105. pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
  61106. pPage->isInit = 1;
  61107. if( pBt->db->flags & SQLITE_CellSizeCk ){
  61108. return btreeCellSizeCheck(pPage);
  61109. }
  61110. return SQLITE_OK;
  61111. }
  61112. /*
  61113. ** Set up a raw page so that it looks like a database page holding
  61114. ** no entries.
  61115. */
  61116. static void zeroPage(MemPage *pPage, int flags){
  61117. unsigned char *data = pPage->aData;
  61118. BtShared *pBt = pPage->pBt;
  61119. u8 hdr = pPage->hdrOffset;
  61120. u16 first;
  61121. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  61122. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  61123. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  61124. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61125. assert( sqlite3_mutex_held(pBt->mutex) );
  61126. if( pBt->btsFlags & BTS_FAST_SECURE ){
  61127. memset(&data[hdr], 0, pBt->usableSize - hdr);
  61128. }
  61129. data[hdr] = (char)flags;
  61130. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  61131. memset(&data[hdr+1], 0, 4);
  61132. data[hdr+7] = 0;
  61133. put2byte(&data[hdr+5], pBt->usableSize);
  61134. pPage->nFree = (u16)(pBt->usableSize - first);
  61135. decodeFlags(pPage, flags);
  61136. pPage->cellOffset = first;
  61137. pPage->aDataEnd = &data[pBt->usableSize];
  61138. pPage->aCellIdx = &data[first];
  61139. pPage->aDataOfst = &data[pPage->childPtrSize];
  61140. pPage->nOverflow = 0;
  61141. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  61142. pPage->maskPage = (u16)(pBt->pageSize - 1);
  61143. pPage->nCell = 0;
  61144. pPage->isInit = 1;
  61145. }
  61146. /*
  61147. ** Convert a DbPage obtained from the pager into a MemPage used by
  61148. ** the btree layer.
  61149. */
  61150. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  61151. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  61152. if( pgno!=pPage->pgno ){
  61153. pPage->aData = sqlite3PagerGetData(pDbPage);
  61154. pPage->pDbPage = pDbPage;
  61155. pPage->pBt = pBt;
  61156. pPage->pgno = pgno;
  61157. pPage->hdrOffset = pgno==1 ? 100 : 0;
  61158. }
  61159. assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
  61160. return pPage;
  61161. }
  61162. /*
  61163. ** Get a page from the pager. Initialize the MemPage.pBt and
  61164. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  61165. **
  61166. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  61167. ** about the content of the page at this time. So do not go to the disk
  61168. ** to fetch the content. Just fill in the content with zeros for now.
  61169. ** If in the future we call sqlite3PagerWrite() on this page, that
  61170. ** means we have started to be concerned about content and the disk
  61171. ** read should occur at that point.
  61172. */
  61173. static int btreeGetPage(
  61174. BtShared *pBt, /* The btree */
  61175. Pgno pgno, /* Number of the page to fetch */
  61176. MemPage **ppPage, /* Return the page in this parameter */
  61177. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  61178. ){
  61179. int rc;
  61180. DbPage *pDbPage;
  61181. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  61182. assert( sqlite3_mutex_held(pBt->mutex) );
  61183. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  61184. if( rc ) return rc;
  61185. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  61186. return SQLITE_OK;
  61187. }
  61188. /*
  61189. ** Retrieve a page from the pager cache. If the requested page is not
  61190. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  61191. ** MemPage.aData elements if needed.
  61192. */
  61193. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  61194. DbPage *pDbPage;
  61195. assert( sqlite3_mutex_held(pBt->mutex) );
  61196. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  61197. if( pDbPage ){
  61198. return btreePageFromDbPage(pDbPage, pgno, pBt);
  61199. }
  61200. return 0;
  61201. }
  61202. /*
  61203. ** Return the size of the database file in pages. If there is any kind of
  61204. ** error, return ((unsigned int)-1).
  61205. */
  61206. static Pgno btreePagecount(BtShared *pBt){
  61207. return pBt->nPage;
  61208. }
  61209. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  61210. assert( sqlite3BtreeHoldsMutex(p) );
  61211. assert( ((p->pBt->nPage)&0x80000000)==0 );
  61212. return btreePagecount(p->pBt);
  61213. }
  61214. /*
  61215. ** Get a page from the pager and initialize it.
  61216. **
  61217. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  61218. ** call. Do additional sanity checking on the page in this case.
  61219. ** And if the fetch fails, this routine must decrement pCur->iPage.
  61220. **
  61221. ** The page is fetched as read-write unless pCur is not NULL and is
  61222. ** a read-only cursor.
  61223. **
  61224. ** If an error occurs, then *ppPage is undefined. It
  61225. ** may remain unchanged, or it may be set to an invalid value.
  61226. */
  61227. static int getAndInitPage(
  61228. BtShared *pBt, /* The database file */
  61229. Pgno pgno, /* Number of the page to get */
  61230. MemPage **ppPage, /* Write the page pointer here */
  61231. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  61232. int bReadOnly /* True for a read-only page */
  61233. ){
  61234. int rc;
  61235. DbPage *pDbPage;
  61236. assert( sqlite3_mutex_held(pBt->mutex) );
  61237. assert( pCur==0 || ppPage==&pCur->pPage );
  61238. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  61239. assert( pCur==0 || pCur->iPage>0 );
  61240. if( pgno>btreePagecount(pBt) ){
  61241. rc = SQLITE_CORRUPT_BKPT;
  61242. goto getAndInitPage_error1;
  61243. }
  61244. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  61245. if( rc ){
  61246. goto getAndInitPage_error1;
  61247. }
  61248. *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  61249. if( (*ppPage)->isInit==0 ){
  61250. btreePageFromDbPage(pDbPage, pgno, pBt);
  61251. rc = btreeInitPage(*ppPage);
  61252. if( rc!=SQLITE_OK ){
  61253. goto getAndInitPage_error2;
  61254. }
  61255. }
  61256. assert( (*ppPage)->pgno==pgno );
  61257. assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
  61258. /* If obtaining a child page for a cursor, we must verify that the page is
  61259. ** compatible with the root page. */
  61260. if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
  61261. rc = SQLITE_CORRUPT_PGNO(pgno);
  61262. goto getAndInitPage_error2;
  61263. }
  61264. return SQLITE_OK;
  61265. getAndInitPage_error2:
  61266. releasePage(*ppPage);
  61267. getAndInitPage_error1:
  61268. if( pCur ){
  61269. pCur->iPage--;
  61270. pCur->pPage = pCur->apPage[pCur->iPage];
  61271. }
  61272. testcase( pgno==0 );
  61273. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  61274. return rc;
  61275. }
  61276. /*
  61277. ** Release a MemPage. This should be called once for each prior
  61278. ** call to btreeGetPage.
  61279. **
  61280. ** Page1 is a special case and must be released using releasePageOne().
  61281. */
  61282. static void releasePageNotNull(MemPage *pPage){
  61283. assert( pPage->aData );
  61284. assert( pPage->pBt );
  61285. assert( pPage->pDbPage!=0 );
  61286. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  61287. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  61288. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61289. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  61290. }
  61291. static void releasePage(MemPage *pPage){
  61292. if( pPage ) releasePageNotNull(pPage);
  61293. }
  61294. static void releasePageOne(MemPage *pPage){
  61295. assert( pPage!=0 );
  61296. assert( pPage->aData );
  61297. assert( pPage->pBt );
  61298. assert( pPage->pDbPage!=0 );
  61299. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  61300. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  61301. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61302. sqlite3PagerUnrefPageOne(pPage->pDbPage);
  61303. }
  61304. /*
  61305. ** Get an unused page.
  61306. **
  61307. ** This works just like btreeGetPage() with the addition:
  61308. **
  61309. ** * If the page is already in use for some other purpose, immediately
  61310. ** release it and return an SQLITE_CURRUPT error.
  61311. ** * Make sure the isInit flag is clear
  61312. */
  61313. static int btreeGetUnusedPage(
  61314. BtShared *pBt, /* The btree */
  61315. Pgno pgno, /* Number of the page to fetch */
  61316. MemPage **ppPage, /* Return the page in this parameter */
  61317. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  61318. ){
  61319. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  61320. if( rc==SQLITE_OK ){
  61321. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  61322. releasePage(*ppPage);
  61323. *ppPage = 0;
  61324. return SQLITE_CORRUPT_BKPT;
  61325. }
  61326. (*ppPage)->isInit = 0;
  61327. }else{
  61328. *ppPage = 0;
  61329. }
  61330. return rc;
  61331. }
  61332. /*
  61333. ** During a rollback, when the pager reloads information into the cache
  61334. ** so that the cache is restored to its original state at the start of
  61335. ** the transaction, for each page restored this routine is called.
  61336. **
  61337. ** This routine needs to reset the extra data section at the end of the
  61338. ** page to agree with the restored data.
  61339. */
  61340. static void pageReinit(DbPage *pData){
  61341. MemPage *pPage;
  61342. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  61343. assert( sqlite3PagerPageRefcount(pData)>0 );
  61344. if( pPage->isInit ){
  61345. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61346. pPage->isInit = 0;
  61347. if( sqlite3PagerPageRefcount(pData)>1 ){
  61348. /* pPage might not be a btree page; it might be an overflow page
  61349. ** or ptrmap page or a free page. In those cases, the following
  61350. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  61351. ** But no harm is done by this. And it is very important that
  61352. ** btreeInitPage() be called on every btree page so we make
  61353. ** the call for every page that comes in for re-initing. */
  61354. btreeInitPage(pPage);
  61355. }
  61356. }
  61357. }
  61358. /*
  61359. ** Invoke the busy handler for a btree.
  61360. */
  61361. static int btreeInvokeBusyHandler(void *pArg){
  61362. BtShared *pBt = (BtShared*)pArg;
  61363. assert( pBt->db );
  61364. assert( sqlite3_mutex_held(pBt->db->mutex) );
  61365. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler,
  61366. sqlite3PagerFile(pBt->pPager));
  61367. }
  61368. /*
  61369. ** Open a database file.
  61370. **
  61371. ** zFilename is the name of the database file. If zFilename is NULL
  61372. ** then an ephemeral database is created. The ephemeral database might
  61373. ** be exclusively in memory, or it might use a disk-based memory cache.
  61374. ** Either way, the ephemeral database will be automatically deleted
  61375. ** when sqlite3BtreeClose() is called.
  61376. **
  61377. ** If zFilename is ":memory:" then an in-memory database is created
  61378. ** that is automatically destroyed when it is closed.
  61379. **
  61380. ** The "flags" parameter is a bitmask that might contain bits like
  61381. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  61382. **
  61383. ** If the database is already opened in the same database connection
  61384. ** and we are in shared cache mode, then the open will fail with an
  61385. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  61386. ** objects in the same database connection since doing so will lead
  61387. ** to problems with locking.
  61388. */
  61389. SQLITE_PRIVATE int sqlite3BtreeOpen(
  61390. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  61391. const char *zFilename, /* Name of the file containing the BTree database */
  61392. sqlite3 *db, /* Associated database handle */
  61393. Btree **ppBtree, /* Pointer to new Btree object written here */
  61394. int flags, /* Options */
  61395. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  61396. ){
  61397. BtShared *pBt = 0; /* Shared part of btree structure */
  61398. Btree *p; /* Handle to return */
  61399. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  61400. int rc = SQLITE_OK; /* Result code from this function */
  61401. u8 nReserve; /* Byte of unused space on each page */
  61402. unsigned char zDbHeader[100]; /* Database header content */
  61403. /* True if opening an ephemeral, temporary database */
  61404. const int isTempDb = zFilename==0 || zFilename[0]==0;
  61405. /* Set the variable isMemdb to true for an in-memory database, or
  61406. ** false for a file-based database.
  61407. */
  61408. #ifdef SQLITE_OMIT_MEMORYDB
  61409. const int isMemdb = 0;
  61410. #else
  61411. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  61412. || (isTempDb && sqlite3TempInMemory(db))
  61413. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  61414. #endif
  61415. assert( db!=0 );
  61416. assert( pVfs!=0 );
  61417. assert( sqlite3_mutex_held(db->mutex) );
  61418. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  61419. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  61420. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  61421. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  61422. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  61423. if( isMemdb ){
  61424. flags |= BTREE_MEMORY;
  61425. }
  61426. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  61427. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  61428. }
  61429. p = sqlite3MallocZero(sizeof(Btree));
  61430. if( !p ){
  61431. return SQLITE_NOMEM_BKPT;
  61432. }
  61433. p->inTrans = TRANS_NONE;
  61434. p->db = db;
  61435. #ifndef SQLITE_OMIT_SHARED_CACHE
  61436. p->lock.pBtree = p;
  61437. p->lock.iTable = 1;
  61438. #endif
  61439. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  61440. /*
  61441. ** If this Btree is a candidate for shared cache, try to find an
  61442. ** existing BtShared object that we can share with
  61443. */
  61444. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  61445. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  61446. int nFilename = sqlite3Strlen30(zFilename)+1;
  61447. int nFullPathname = pVfs->mxPathname+1;
  61448. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  61449. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  61450. p->sharable = 1;
  61451. if( !zFullPathname ){
  61452. sqlite3_free(p);
  61453. return SQLITE_NOMEM_BKPT;
  61454. }
  61455. if( isMemdb ){
  61456. memcpy(zFullPathname, zFilename, nFilename);
  61457. }else{
  61458. rc = sqlite3OsFullPathname(pVfs, zFilename,
  61459. nFullPathname, zFullPathname);
  61460. if( rc ){
  61461. sqlite3_free(zFullPathname);
  61462. sqlite3_free(p);
  61463. return rc;
  61464. }
  61465. }
  61466. #if SQLITE_THREADSAFE
  61467. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  61468. sqlite3_mutex_enter(mutexOpen);
  61469. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  61470. sqlite3_mutex_enter(mutexShared);
  61471. #endif
  61472. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  61473. assert( pBt->nRef>0 );
  61474. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  61475. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  61476. int iDb;
  61477. for(iDb=db->nDb-1; iDb>=0; iDb--){
  61478. Btree *pExisting = db->aDb[iDb].pBt;
  61479. if( pExisting && pExisting->pBt==pBt ){
  61480. sqlite3_mutex_leave(mutexShared);
  61481. sqlite3_mutex_leave(mutexOpen);
  61482. sqlite3_free(zFullPathname);
  61483. sqlite3_free(p);
  61484. return SQLITE_CONSTRAINT;
  61485. }
  61486. }
  61487. p->pBt = pBt;
  61488. pBt->nRef++;
  61489. break;
  61490. }
  61491. }
  61492. sqlite3_mutex_leave(mutexShared);
  61493. sqlite3_free(zFullPathname);
  61494. }
  61495. #ifdef SQLITE_DEBUG
  61496. else{
  61497. /* In debug mode, we mark all persistent databases as sharable
  61498. ** even when they are not. This exercises the locking code and
  61499. ** gives more opportunity for asserts(sqlite3_mutex_held())
  61500. ** statements to find locking problems.
  61501. */
  61502. p->sharable = 1;
  61503. }
  61504. #endif
  61505. }
  61506. #endif
  61507. if( pBt==0 ){
  61508. /*
  61509. ** The following asserts make sure that structures used by the btree are
  61510. ** the right size. This is to guard against size changes that result
  61511. ** when compiling on a different architecture.
  61512. */
  61513. assert( sizeof(i64)==8 );
  61514. assert( sizeof(u64)==8 );
  61515. assert( sizeof(u32)==4 );
  61516. assert( sizeof(u16)==2 );
  61517. assert( sizeof(Pgno)==4 );
  61518. pBt = sqlite3MallocZero( sizeof(*pBt) );
  61519. if( pBt==0 ){
  61520. rc = SQLITE_NOMEM_BKPT;
  61521. goto btree_open_out;
  61522. }
  61523. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  61524. sizeof(MemPage), flags, vfsFlags, pageReinit);
  61525. if( rc==SQLITE_OK ){
  61526. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  61527. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  61528. }
  61529. if( rc!=SQLITE_OK ){
  61530. goto btree_open_out;
  61531. }
  61532. pBt->openFlags = (u8)flags;
  61533. pBt->db = db;
  61534. sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  61535. p->pBt = pBt;
  61536. pBt->pCursor = 0;
  61537. pBt->pPage1 = 0;
  61538. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  61539. #if defined(SQLITE_SECURE_DELETE)
  61540. pBt->btsFlags |= BTS_SECURE_DELETE;
  61541. #elif defined(SQLITE_FAST_SECURE_DELETE)
  61542. pBt->btsFlags |= BTS_OVERWRITE;
  61543. #endif
  61544. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  61545. ** determined by the 2-byte integer located at an offset of 16 bytes from
  61546. ** the beginning of the database file. */
  61547. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  61548. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  61549. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  61550. pBt->pageSize = 0;
  61551. #ifndef SQLITE_OMIT_AUTOVACUUM
  61552. /* If the magic name ":memory:" will create an in-memory database, then
  61553. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  61554. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  61555. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  61556. ** regular file-name. In this case the auto-vacuum applies as per normal.
  61557. */
  61558. if( zFilename && !isMemdb ){
  61559. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  61560. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  61561. }
  61562. #endif
  61563. nReserve = 0;
  61564. }else{
  61565. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  61566. ** determined by the one-byte unsigned integer found at an offset of 20
  61567. ** into the database file header. */
  61568. nReserve = zDbHeader[20];
  61569. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  61570. #ifndef SQLITE_OMIT_AUTOVACUUM
  61571. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  61572. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  61573. #endif
  61574. }
  61575. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  61576. if( rc ) goto btree_open_out;
  61577. pBt->usableSize = pBt->pageSize - nReserve;
  61578. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  61579. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  61580. /* Add the new BtShared object to the linked list sharable BtShareds.
  61581. */
  61582. pBt->nRef = 1;
  61583. if( p->sharable ){
  61584. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  61585. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  61586. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  61587. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  61588. if( pBt->mutex==0 ){
  61589. rc = SQLITE_NOMEM_BKPT;
  61590. goto btree_open_out;
  61591. }
  61592. }
  61593. sqlite3_mutex_enter(mutexShared);
  61594. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  61595. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  61596. sqlite3_mutex_leave(mutexShared);
  61597. }
  61598. #endif
  61599. }
  61600. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  61601. /* If the new Btree uses a sharable pBtShared, then link the new
  61602. ** Btree into the list of all sharable Btrees for the same connection.
  61603. ** The list is kept in ascending order by pBt address.
  61604. */
  61605. if( p->sharable ){
  61606. int i;
  61607. Btree *pSib;
  61608. for(i=0; i<db->nDb; i++){
  61609. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  61610. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  61611. if( (uptr)p->pBt<(uptr)pSib->pBt ){
  61612. p->pNext = pSib;
  61613. p->pPrev = 0;
  61614. pSib->pPrev = p;
  61615. }else{
  61616. while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
  61617. pSib = pSib->pNext;
  61618. }
  61619. p->pNext = pSib->pNext;
  61620. p->pPrev = pSib;
  61621. if( p->pNext ){
  61622. p->pNext->pPrev = p;
  61623. }
  61624. pSib->pNext = p;
  61625. }
  61626. break;
  61627. }
  61628. }
  61629. }
  61630. #endif
  61631. *ppBtree = p;
  61632. btree_open_out:
  61633. if( rc!=SQLITE_OK ){
  61634. if( pBt && pBt->pPager ){
  61635. sqlite3PagerClose(pBt->pPager, 0);
  61636. }
  61637. sqlite3_free(pBt);
  61638. sqlite3_free(p);
  61639. *ppBtree = 0;
  61640. }else{
  61641. sqlite3_file *pFile;
  61642. /* If the B-Tree was successfully opened, set the pager-cache size to the
  61643. ** default value. Except, when opening on an existing shared pager-cache,
  61644. ** do not change the pager-cache size.
  61645. */
  61646. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  61647. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  61648. }
  61649. pFile = sqlite3PagerFile(pBt->pPager);
  61650. if( pFile->pMethods ){
  61651. sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
  61652. }
  61653. }
  61654. if( mutexOpen ){
  61655. assert( sqlite3_mutex_held(mutexOpen) );
  61656. sqlite3_mutex_leave(mutexOpen);
  61657. }
  61658. assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
  61659. return rc;
  61660. }
  61661. /*
  61662. ** Decrement the BtShared.nRef counter. When it reaches zero,
  61663. ** remove the BtShared structure from the sharing list. Return
  61664. ** true if the BtShared.nRef counter reaches zero and return
  61665. ** false if it is still positive.
  61666. */
  61667. static int removeFromSharingList(BtShared *pBt){
  61668. #ifndef SQLITE_OMIT_SHARED_CACHE
  61669. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  61670. BtShared *pList;
  61671. int removed = 0;
  61672. assert( sqlite3_mutex_notheld(pBt->mutex) );
  61673. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  61674. sqlite3_mutex_enter(pMaster);
  61675. pBt->nRef--;
  61676. if( pBt->nRef<=0 ){
  61677. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  61678. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  61679. }else{
  61680. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  61681. while( ALWAYS(pList) && pList->pNext!=pBt ){
  61682. pList=pList->pNext;
  61683. }
  61684. if( ALWAYS(pList) ){
  61685. pList->pNext = pBt->pNext;
  61686. }
  61687. }
  61688. if( SQLITE_THREADSAFE ){
  61689. sqlite3_mutex_free(pBt->mutex);
  61690. }
  61691. removed = 1;
  61692. }
  61693. sqlite3_mutex_leave(pMaster);
  61694. return removed;
  61695. #else
  61696. return 1;
  61697. #endif
  61698. }
  61699. /*
  61700. ** Make sure pBt->pTmpSpace points to an allocation of
  61701. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  61702. ** pointer.
  61703. */
  61704. static void allocateTempSpace(BtShared *pBt){
  61705. if( !pBt->pTmpSpace ){
  61706. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  61707. /* One of the uses of pBt->pTmpSpace is to format cells before
  61708. ** inserting them into a leaf page (function fillInCell()). If
  61709. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  61710. ** by the various routines that manipulate binary cells. Which
  61711. ** can mean that fillInCell() only initializes the first 2 or 3
  61712. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  61713. ** it into a database page. This is not actually a problem, but it
  61714. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  61715. ** data is passed to system call write(). So to avoid this error,
  61716. ** zero the first 4 bytes of temp space here.
  61717. **
  61718. ** Also: Provide four bytes of initialized space before the
  61719. ** beginning of pTmpSpace as an area available to prepend the
  61720. ** left-child pointer to the beginning of a cell.
  61721. */
  61722. if( pBt->pTmpSpace ){
  61723. memset(pBt->pTmpSpace, 0, 8);
  61724. pBt->pTmpSpace += 4;
  61725. }
  61726. }
  61727. }
  61728. /*
  61729. ** Free the pBt->pTmpSpace allocation
  61730. */
  61731. static void freeTempSpace(BtShared *pBt){
  61732. if( pBt->pTmpSpace ){
  61733. pBt->pTmpSpace -= 4;
  61734. sqlite3PageFree(pBt->pTmpSpace);
  61735. pBt->pTmpSpace = 0;
  61736. }
  61737. }
  61738. /*
  61739. ** Close an open database and invalidate all cursors.
  61740. */
  61741. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  61742. BtShared *pBt = p->pBt;
  61743. BtCursor *pCur;
  61744. /* Close all cursors opened via this handle. */
  61745. assert( sqlite3_mutex_held(p->db->mutex) );
  61746. sqlite3BtreeEnter(p);
  61747. pCur = pBt->pCursor;
  61748. while( pCur ){
  61749. BtCursor *pTmp = pCur;
  61750. pCur = pCur->pNext;
  61751. if( pTmp->pBtree==p ){
  61752. sqlite3BtreeCloseCursor(pTmp);
  61753. }
  61754. }
  61755. /* Rollback any active transaction and free the handle structure.
  61756. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  61757. ** this handle.
  61758. */
  61759. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  61760. sqlite3BtreeLeave(p);
  61761. /* If there are still other outstanding references to the shared-btree
  61762. ** structure, return now. The remainder of this procedure cleans
  61763. ** up the shared-btree.
  61764. */
  61765. assert( p->wantToLock==0 && p->locked==0 );
  61766. if( !p->sharable || removeFromSharingList(pBt) ){
  61767. /* The pBt is no longer on the sharing list, so we can access
  61768. ** it without having to hold the mutex.
  61769. **
  61770. ** Clean out and delete the BtShared object.
  61771. */
  61772. assert( !pBt->pCursor );
  61773. sqlite3PagerClose(pBt->pPager, p->db);
  61774. if( pBt->xFreeSchema && pBt->pSchema ){
  61775. pBt->xFreeSchema(pBt->pSchema);
  61776. }
  61777. sqlite3DbFree(0, pBt->pSchema);
  61778. freeTempSpace(pBt);
  61779. sqlite3_free(pBt);
  61780. }
  61781. #ifndef SQLITE_OMIT_SHARED_CACHE
  61782. assert( p->wantToLock==0 );
  61783. assert( p->locked==0 );
  61784. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  61785. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  61786. #endif
  61787. sqlite3_free(p);
  61788. return SQLITE_OK;
  61789. }
  61790. /*
  61791. ** Change the "soft" limit on the number of pages in the cache.
  61792. ** Unused and unmodified pages will be recycled when the number of
  61793. ** pages in the cache exceeds this soft limit. But the size of the
  61794. ** cache is allowed to grow larger than this limit if it contains
  61795. ** dirty pages or pages still in active use.
  61796. */
  61797. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  61798. BtShared *pBt = p->pBt;
  61799. assert( sqlite3_mutex_held(p->db->mutex) );
  61800. sqlite3BtreeEnter(p);
  61801. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  61802. sqlite3BtreeLeave(p);
  61803. return SQLITE_OK;
  61804. }
  61805. /*
  61806. ** Change the "spill" limit on the number of pages in the cache.
  61807. ** If the number of pages exceeds this limit during a write transaction,
  61808. ** the pager might attempt to "spill" pages to the journal early in
  61809. ** order to free up memory.
  61810. **
  61811. ** The value returned is the current spill size. If zero is passed
  61812. ** as an argument, no changes are made to the spill size setting, so
  61813. ** using mxPage of 0 is a way to query the current spill size.
  61814. */
  61815. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
  61816. BtShared *pBt = p->pBt;
  61817. int res;
  61818. assert( sqlite3_mutex_held(p->db->mutex) );
  61819. sqlite3BtreeEnter(p);
  61820. res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
  61821. sqlite3BtreeLeave(p);
  61822. return res;
  61823. }
  61824. #if SQLITE_MAX_MMAP_SIZE>0
  61825. /*
  61826. ** Change the limit on the amount of the database file that may be
  61827. ** memory mapped.
  61828. */
  61829. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  61830. BtShared *pBt = p->pBt;
  61831. assert( sqlite3_mutex_held(p->db->mutex) );
  61832. sqlite3BtreeEnter(p);
  61833. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  61834. sqlite3BtreeLeave(p);
  61835. return SQLITE_OK;
  61836. }
  61837. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  61838. /*
  61839. ** Change the way data is synced to disk in order to increase or decrease
  61840. ** how well the database resists damage due to OS crashes and power
  61841. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  61842. ** there is a high probability of damage) Level 2 is the default. There
  61843. ** is a very low but non-zero probability of damage. Level 3 reduces the
  61844. ** probability of damage to near zero but with a write performance reduction.
  61845. */
  61846. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  61847. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  61848. Btree *p, /* The btree to set the safety level on */
  61849. unsigned pgFlags /* Various PAGER_* flags */
  61850. ){
  61851. BtShared *pBt = p->pBt;
  61852. assert( sqlite3_mutex_held(p->db->mutex) );
  61853. sqlite3BtreeEnter(p);
  61854. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  61855. sqlite3BtreeLeave(p);
  61856. return SQLITE_OK;
  61857. }
  61858. #endif
  61859. /*
  61860. ** Change the default pages size and the number of reserved bytes per page.
  61861. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  61862. ** without changing anything.
  61863. **
  61864. ** The page size must be a power of 2 between 512 and 65536. If the page
  61865. ** size supplied does not meet this constraint then the page size is not
  61866. ** changed.
  61867. **
  61868. ** Page sizes are constrained to be a power of two so that the region
  61869. ** of the database file used for locking (beginning at PENDING_BYTE,
  61870. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  61871. ** at the beginning of a page.
  61872. **
  61873. ** If parameter nReserve is less than zero, then the number of reserved
  61874. ** bytes per page is left unchanged.
  61875. **
  61876. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  61877. ** and autovacuum mode can no longer be changed.
  61878. */
  61879. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  61880. int rc = SQLITE_OK;
  61881. BtShared *pBt = p->pBt;
  61882. assert( nReserve>=-1 && nReserve<=255 );
  61883. sqlite3BtreeEnter(p);
  61884. #if SQLITE_HAS_CODEC
  61885. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  61886. #endif
  61887. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  61888. sqlite3BtreeLeave(p);
  61889. return SQLITE_READONLY;
  61890. }
  61891. if( nReserve<0 ){
  61892. nReserve = pBt->pageSize - pBt->usableSize;
  61893. }
  61894. assert( nReserve>=0 && nReserve<=255 );
  61895. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  61896. ((pageSize-1)&pageSize)==0 ){
  61897. assert( (pageSize & 7)==0 );
  61898. assert( !pBt->pCursor );
  61899. pBt->pageSize = (u32)pageSize;
  61900. freeTempSpace(pBt);
  61901. }
  61902. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  61903. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  61904. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  61905. sqlite3BtreeLeave(p);
  61906. return rc;
  61907. }
  61908. /*
  61909. ** Return the currently defined page size
  61910. */
  61911. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  61912. return p->pBt->pageSize;
  61913. }
  61914. /*
  61915. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  61916. ** may only be called if it is guaranteed that the b-tree mutex is already
  61917. ** held.
  61918. **
  61919. ** This is useful in one special case in the backup API code where it is
  61920. ** known that the shared b-tree mutex is held, but the mutex on the
  61921. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  61922. ** were to be called, it might collide with some other operation on the
  61923. ** database handle that owns *p, causing undefined behavior.
  61924. */
  61925. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  61926. int n;
  61927. assert( sqlite3_mutex_held(p->pBt->mutex) );
  61928. n = p->pBt->pageSize - p->pBt->usableSize;
  61929. return n;
  61930. }
  61931. /*
  61932. ** Return the number of bytes of space at the end of every page that
  61933. ** are intentually left unused. This is the "reserved" space that is
  61934. ** sometimes used by extensions.
  61935. **
  61936. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  61937. ** greater of the current reserved space and the maximum requested
  61938. ** reserve space.
  61939. */
  61940. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  61941. int n;
  61942. sqlite3BtreeEnter(p);
  61943. n = sqlite3BtreeGetReserveNoMutex(p);
  61944. #ifdef SQLITE_HAS_CODEC
  61945. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  61946. #endif
  61947. sqlite3BtreeLeave(p);
  61948. return n;
  61949. }
  61950. /*
  61951. ** Set the maximum page count for a database if mxPage is positive.
  61952. ** No changes are made if mxPage is 0 or negative.
  61953. ** Regardless of the value of mxPage, return the maximum page count.
  61954. */
  61955. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  61956. int n;
  61957. sqlite3BtreeEnter(p);
  61958. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  61959. sqlite3BtreeLeave(p);
  61960. return n;
  61961. }
  61962. /*
  61963. ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
  61964. **
  61965. ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
  61966. ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
  61967. ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
  61968. ** newFlag==(-1) No changes
  61969. **
  61970. ** This routine acts as a query if newFlag is less than zero
  61971. **
  61972. ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
  61973. ** freelist leaf pages are not written back to the database. Thus in-page
  61974. ** deleted content is cleared, but freelist deleted content is not.
  61975. **
  61976. ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
  61977. ** that freelist leaf pages are written back into the database, increasing
  61978. ** the amount of disk I/O.
  61979. */
  61980. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  61981. int b;
  61982. if( p==0 ) return 0;
  61983. sqlite3BtreeEnter(p);
  61984. assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
  61985. assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
  61986. if( newFlag>=0 ){
  61987. p->pBt->btsFlags &= ~BTS_FAST_SECURE;
  61988. p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
  61989. }
  61990. b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
  61991. sqlite3BtreeLeave(p);
  61992. return b;
  61993. }
  61994. /*
  61995. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  61996. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  61997. ** is disabled. The default value for the auto-vacuum property is
  61998. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  61999. */
  62000. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  62001. #ifdef SQLITE_OMIT_AUTOVACUUM
  62002. return SQLITE_READONLY;
  62003. #else
  62004. BtShared *pBt = p->pBt;
  62005. int rc = SQLITE_OK;
  62006. u8 av = (u8)autoVacuum;
  62007. sqlite3BtreeEnter(p);
  62008. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  62009. rc = SQLITE_READONLY;
  62010. }else{
  62011. pBt->autoVacuum = av ?1:0;
  62012. pBt->incrVacuum = av==2 ?1:0;
  62013. }
  62014. sqlite3BtreeLeave(p);
  62015. return rc;
  62016. #endif
  62017. }
  62018. /*
  62019. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  62020. ** enabled 1 is returned. Otherwise 0.
  62021. */
  62022. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  62023. #ifdef SQLITE_OMIT_AUTOVACUUM
  62024. return BTREE_AUTOVACUUM_NONE;
  62025. #else
  62026. int rc;
  62027. sqlite3BtreeEnter(p);
  62028. rc = (
  62029. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  62030. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  62031. BTREE_AUTOVACUUM_INCR
  62032. );
  62033. sqlite3BtreeLeave(p);
  62034. return rc;
  62035. #endif
  62036. }
  62037. /*
  62038. ** If the user has not set the safety-level for this database connection
  62039. ** using "PRAGMA synchronous", and if the safety-level is not already
  62040. ** set to the value passed to this function as the second parameter,
  62041. ** set it so.
  62042. */
  62043. #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
  62044. && !defined(SQLITE_OMIT_WAL)
  62045. static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
  62046. sqlite3 *db;
  62047. Db *pDb;
  62048. if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
  62049. while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
  62050. if( pDb->bSyncSet==0
  62051. && pDb->safety_level!=safety_level
  62052. && pDb!=&db->aDb[1]
  62053. ){
  62054. pDb->safety_level = safety_level;
  62055. sqlite3PagerSetFlags(pBt->pPager,
  62056. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
  62057. }
  62058. }
  62059. }
  62060. #else
  62061. # define setDefaultSyncFlag(pBt,safety_level)
  62062. #endif
  62063. /* Forward declaration */
  62064. static int newDatabase(BtShared*);
  62065. /*
  62066. ** Get a reference to pPage1 of the database file. This will
  62067. ** also acquire a readlock on that file.
  62068. **
  62069. ** SQLITE_OK is returned on success. If the file is not a
  62070. ** well-formed database file, then SQLITE_CORRUPT is returned.
  62071. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  62072. ** is returned if we run out of memory.
  62073. */
  62074. static int lockBtree(BtShared *pBt){
  62075. int rc; /* Result code from subfunctions */
  62076. MemPage *pPage1; /* Page 1 of the database file */
  62077. u32 nPage; /* Number of pages in the database */
  62078. u32 nPageFile = 0; /* Number of pages in the database file */
  62079. u32 nPageHeader; /* Number of pages in the database according to hdr */
  62080. assert( sqlite3_mutex_held(pBt->mutex) );
  62081. assert( pBt->pPage1==0 );
  62082. rc = sqlite3PagerSharedLock(pBt->pPager);
  62083. if( rc!=SQLITE_OK ) return rc;
  62084. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  62085. if( rc!=SQLITE_OK ) return rc;
  62086. /* Do some checking to help insure the file we opened really is
  62087. ** a valid database file.
  62088. */
  62089. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  62090. sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
  62091. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  62092. nPage = nPageFile;
  62093. }
  62094. if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
  62095. nPage = 0;
  62096. }
  62097. if( nPage>0 ){
  62098. u32 pageSize;
  62099. u32 usableSize;
  62100. u8 *page1 = pPage1->aData;
  62101. rc = SQLITE_NOTADB;
  62102. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  62103. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  62104. ** 61 74 20 33 00. */
  62105. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  62106. goto page1_init_failed;
  62107. }
  62108. #ifdef SQLITE_OMIT_WAL
  62109. if( page1[18]>1 ){
  62110. pBt->btsFlags |= BTS_READ_ONLY;
  62111. }
  62112. if( page1[19]>1 ){
  62113. goto page1_init_failed;
  62114. }
  62115. #else
  62116. if( page1[18]>2 ){
  62117. pBt->btsFlags |= BTS_READ_ONLY;
  62118. }
  62119. if( page1[19]>2 ){
  62120. goto page1_init_failed;
  62121. }
  62122. /* If the write version is set to 2, this database should be accessed
  62123. ** in WAL mode. If the log is not already open, open it now. Then
  62124. ** return SQLITE_OK and return without populating BtShared.pPage1.
  62125. ** The caller detects this and calls this function again. This is
  62126. ** required as the version of page 1 currently in the page1 buffer
  62127. ** may not be the latest version - there may be a newer one in the log
  62128. ** file.
  62129. */
  62130. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  62131. int isOpen = 0;
  62132. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  62133. if( rc!=SQLITE_OK ){
  62134. goto page1_init_failed;
  62135. }else{
  62136. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
  62137. if( isOpen==0 ){
  62138. releasePageOne(pPage1);
  62139. return SQLITE_OK;
  62140. }
  62141. }
  62142. rc = SQLITE_NOTADB;
  62143. }else{
  62144. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
  62145. }
  62146. #endif
  62147. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  62148. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  62149. **
  62150. ** The original design allowed these amounts to vary, but as of
  62151. ** version 3.6.0, we require them to be fixed.
  62152. */
  62153. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  62154. goto page1_init_failed;
  62155. }
  62156. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  62157. ** determined by the 2-byte integer located at an offset of 16 bytes from
  62158. ** the beginning of the database file. */
  62159. pageSize = (page1[16]<<8) | (page1[17]<<16);
  62160. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  62161. ** between 512 and 65536 inclusive. */
  62162. if( ((pageSize-1)&pageSize)!=0
  62163. || pageSize>SQLITE_MAX_PAGE_SIZE
  62164. || pageSize<=256
  62165. ){
  62166. goto page1_init_failed;
  62167. }
  62168. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  62169. assert( (pageSize & 7)==0 );
  62170. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  62171. ** integer at offset 20 is the number of bytes of space at the end of
  62172. ** each page to reserve for extensions.
  62173. **
  62174. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  62175. ** determined by the one-byte unsigned integer found at an offset of 20
  62176. ** into the database file header. */
  62177. usableSize = pageSize - page1[20];
  62178. if( (u32)pageSize!=pBt->pageSize ){
  62179. /* After reading the first page of the database assuming a page size
  62180. ** of BtShared.pageSize, we have discovered that the page-size is
  62181. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  62182. ** zero and return SQLITE_OK. The caller will call this function
  62183. ** again with the correct page-size.
  62184. */
  62185. releasePageOne(pPage1);
  62186. pBt->usableSize = usableSize;
  62187. pBt->pageSize = pageSize;
  62188. freeTempSpace(pBt);
  62189. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  62190. pageSize-usableSize);
  62191. return rc;
  62192. }
  62193. if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
  62194. rc = SQLITE_CORRUPT_BKPT;
  62195. goto page1_init_failed;
  62196. }
  62197. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  62198. ** be less than 480. In other words, if the page size is 512, then the
  62199. ** reserved space size cannot exceed 32. */
  62200. if( usableSize<480 ){
  62201. goto page1_init_failed;
  62202. }
  62203. pBt->pageSize = pageSize;
  62204. pBt->usableSize = usableSize;
  62205. #ifndef SQLITE_OMIT_AUTOVACUUM
  62206. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  62207. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  62208. #endif
  62209. }
  62210. /* maxLocal is the maximum amount of payload to store locally for
  62211. ** a cell. Make sure it is small enough so that at least minFanout
  62212. ** cells can will fit on one page. We assume a 10-byte page header.
  62213. ** Besides the payload, the cell must store:
  62214. ** 2-byte pointer to the cell
  62215. ** 4-byte child pointer
  62216. ** 9-byte nKey value
  62217. ** 4-byte nData value
  62218. ** 4-byte overflow page pointer
  62219. ** So a cell consists of a 2-byte pointer, a header which is as much as
  62220. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  62221. ** page pointer.
  62222. */
  62223. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  62224. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  62225. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  62226. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  62227. if( pBt->maxLocal>127 ){
  62228. pBt->max1bytePayload = 127;
  62229. }else{
  62230. pBt->max1bytePayload = (u8)pBt->maxLocal;
  62231. }
  62232. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  62233. pBt->pPage1 = pPage1;
  62234. pBt->nPage = nPage;
  62235. return SQLITE_OK;
  62236. page1_init_failed:
  62237. releasePageOne(pPage1);
  62238. pBt->pPage1 = 0;
  62239. return rc;
  62240. }
  62241. #ifndef NDEBUG
  62242. /*
  62243. ** Return the number of cursors open on pBt. This is for use
  62244. ** in assert() expressions, so it is only compiled if NDEBUG is not
  62245. ** defined.
  62246. **
  62247. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  62248. ** false then all cursors are counted.
  62249. **
  62250. ** For the purposes of this routine, a cursor is any cursor that
  62251. ** is capable of reading or writing to the database. Cursors that
  62252. ** have been tripped into the CURSOR_FAULT state are not counted.
  62253. */
  62254. static int countValidCursors(BtShared *pBt, int wrOnly){
  62255. BtCursor *pCur;
  62256. int r = 0;
  62257. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  62258. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  62259. && pCur->eState!=CURSOR_FAULT ) r++;
  62260. }
  62261. return r;
  62262. }
  62263. #endif
  62264. /*
  62265. ** If there are no outstanding cursors and we are not in the middle
  62266. ** of a transaction but there is a read lock on the database, then
  62267. ** this routine unrefs the first page of the database file which
  62268. ** has the effect of releasing the read lock.
  62269. **
  62270. ** If there is a transaction in progress, this routine is a no-op.
  62271. */
  62272. static void unlockBtreeIfUnused(BtShared *pBt){
  62273. assert( sqlite3_mutex_held(pBt->mutex) );
  62274. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  62275. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  62276. MemPage *pPage1 = pBt->pPage1;
  62277. assert( pPage1->aData );
  62278. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  62279. pBt->pPage1 = 0;
  62280. releasePageOne(pPage1);
  62281. }
  62282. }
  62283. /*
  62284. ** If pBt points to an empty file then convert that empty file
  62285. ** into a new empty database by initializing the first page of
  62286. ** the database.
  62287. */
  62288. static int newDatabase(BtShared *pBt){
  62289. MemPage *pP1;
  62290. unsigned char *data;
  62291. int rc;
  62292. assert( sqlite3_mutex_held(pBt->mutex) );
  62293. if( pBt->nPage>0 ){
  62294. return SQLITE_OK;
  62295. }
  62296. pP1 = pBt->pPage1;
  62297. assert( pP1!=0 );
  62298. data = pP1->aData;
  62299. rc = sqlite3PagerWrite(pP1->pDbPage);
  62300. if( rc ) return rc;
  62301. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  62302. assert( sizeof(zMagicHeader)==16 );
  62303. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  62304. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  62305. data[18] = 1;
  62306. data[19] = 1;
  62307. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  62308. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  62309. data[21] = 64;
  62310. data[22] = 32;
  62311. data[23] = 32;
  62312. memset(&data[24], 0, 100-24);
  62313. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  62314. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  62315. #ifndef SQLITE_OMIT_AUTOVACUUM
  62316. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  62317. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  62318. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  62319. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  62320. #endif
  62321. pBt->nPage = 1;
  62322. data[31] = 1;
  62323. return SQLITE_OK;
  62324. }
  62325. /*
  62326. ** Initialize the first page of the database file (creating a database
  62327. ** consisting of a single page and no schema objects). Return SQLITE_OK
  62328. ** if successful, or an SQLite error code otherwise.
  62329. */
  62330. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  62331. int rc;
  62332. sqlite3BtreeEnter(p);
  62333. p->pBt->nPage = 0;
  62334. rc = newDatabase(p->pBt);
  62335. sqlite3BtreeLeave(p);
  62336. return rc;
  62337. }
  62338. /*
  62339. ** Attempt to start a new transaction. A write-transaction
  62340. ** is started if the second argument is nonzero, otherwise a read-
  62341. ** transaction. If the second argument is 2 or more and exclusive
  62342. ** transaction is started, meaning that no other process is allowed
  62343. ** to access the database. A preexisting transaction may not be
  62344. ** upgraded to exclusive by calling this routine a second time - the
  62345. ** exclusivity flag only works for a new transaction.
  62346. **
  62347. ** A write-transaction must be started before attempting any
  62348. ** changes to the database. None of the following routines
  62349. ** will work unless a transaction is started first:
  62350. **
  62351. ** sqlite3BtreeCreateTable()
  62352. ** sqlite3BtreeCreateIndex()
  62353. ** sqlite3BtreeClearTable()
  62354. ** sqlite3BtreeDropTable()
  62355. ** sqlite3BtreeInsert()
  62356. ** sqlite3BtreeDelete()
  62357. ** sqlite3BtreeUpdateMeta()
  62358. **
  62359. ** If an initial attempt to acquire the lock fails because of lock contention
  62360. ** and the database was previously unlocked, then invoke the busy handler
  62361. ** if there is one. But if there was previously a read-lock, do not
  62362. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  62363. ** returned when there is already a read-lock in order to avoid a deadlock.
  62364. **
  62365. ** Suppose there are two processes A and B. A has a read lock and B has
  62366. ** a reserved lock. B tries to promote to exclusive but is blocked because
  62367. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  62368. ** One or the other of the two processes must give way or there can be
  62369. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  62370. ** when A already has a read lock, we encourage A to give up and let B
  62371. ** proceed.
  62372. */
  62373. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
  62374. BtShared *pBt = p->pBt;
  62375. int rc = SQLITE_OK;
  62376. sqlite3BtreeEnter(p);
  62377. btreeIntegrity(p);
  62378. /* If the btree is already in a write-transaction, or it
  62379. ** is already in a read-transaction and a read-transaction
  62380. ** is requested, this is a no-op.
  62381. */
  62382. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  62383. goto trans_begun;
  62384. }
  62385. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  62386. if( (p->db->flags & SQLITE_ResetDatabase)
  62387. && sqlite3PagerIsreadonly(pBt->pPager)==0
  62388. ){
  62389. pBt->btsFlags &= ~BTS_READ_ONLY;
  62390. }
  62391. /* Write transactions are not possible on a read-only database */
  62392. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  62393. rc = SQLITE_READONLY;
  62394. goto trans_begun;
  62395. }
  62396. #ifndef SQLITE_OMIT_SHARED_CACHE
  62397. {
  62398. sqlite3 *pBlock = 0;
  62399. /* If another database handle has already opened a write transaction
  62400. ** on this shared-btree structure and a second write transaction is
  62401. ** requested, return SQLITE_LOCKED.
  62402. */
  62403. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  62404. || (pBt->btsFlags & BTS_PENDING)!=0
  62405. ){
  62406. pBlock = pBt->pWriter->db;
  62407. }else if( wrflag>1 ){
  62408. BtLock *pIter;
  62409. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  62410. if( pIter->pBtree!=p ){
  62411. pBlock = pIter->pBtree->db;
  62412. break;
  62413. }
  62414. }
  62415. }
  62416. if( pBlock ){
  62417. sqlite3ConnectionBlocked(p->db, pBlock);
  62418. rc = SQLITE_LOCKED_SHAREDCACHE;
  62419. goto trans_begun;
  62420. }
  62421. }
  62422. #endif
  62423. /* Any read-only or read-write transaction implies a read-lock on
  62424. ** page 1. So if some other shared-cache client already has a write-lock
  62425. ** on page 1, the transaction cannot be opened. */
  62426. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  62427. if( SQLITE_OK!=rc ) goto trans_begun;
  62428. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  62429. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  62430. do {
  62431. /* Call lockBtree() until either pBt->pPage1 is populated or
  62432. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  62433. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  62434. ** reading page 1 it discovers that the page-size of the database
  62435. ** file is not pBt->pageSize. In this case lockBtree() will update
  62436. ** pBt->pageSize to the page-size of the file on disk.
  62437. */
  62438. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  62439. if( rc==SQLITE_OK && wrflag ){
  62440. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  62441. rc = SQLITE_READONLY;
  62442. }else{
  62443. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  62444. if( rc==SQLITE_OK ){
  62445. rc = newDatabase(pBt);
  62446. }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
  62447. /* if there was no transaction opened when this function was
  62448. ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
  62449. ** code to SQLITE_BUSY. */
  62450. rc = SQLITE_BUSY;
  62451. }
  62452. }
  62453. }
  62454. if( rc!=SQLITE_OK ){
  62455. unlockBtreeIfUnused(pBt);
  62456. }
  62457. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  62458. btreeInvokeBusyHandler(pBt) );
  62459. sqlite3PagerResetLockTimeout(pBt->pPager);
  62460. if( rc==SQLITE_OK ){
  62461. if( p->inTrans==TRANS_NONE ){
  62462. pBt->nTransaction++;
  62463. #ifndef SQLITE_OMIT_SHARED_CACHE
  62464. if( p->sharable ){
  62465. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  62466. p->lock.eLock = READ_LOCK;
  62467. p->lock.pNext = pBt->pLock;
  62468. pBt->pLock = &p->lock;
  62469. }
  62470. #endif
  62471. }
  62472. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  62473. if( p->inTrans>pBt->inTransaction ){
  62474. pBt->inTransaction = p->inTrans;
  62475. }
  62476. if( wrflag ){
  62477. MemPage *pPage1 = pBt->pPage1;
  62478. #ifndef SQLITE_OMIT_SHARED_CACHE
  62479. assert( !pBt->pWriter );
  62480. pBt->pWriter = p;
  62481. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  62482. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  62483. #endif
  62484. /* If the db-size header field is incorrect (as it may be if an old
  62485. ** client has been writing the database file), update it now. Doing
  62486. ** this sooner rather than later means the database size can safely
  62487. ** re-read the database size from page 1 if a savepoint or transaction
  62488. ** rollback occurs within the transaction.
  62489. */
  62490. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  62491. rc = sqlite3PagerWrite(pPage1->pDbPage);
  62492. if( rc==SQLITE_OK ){
  62493. put4byte(&pPage1->aData[28], pBt->nPage);
  62494. }
  62495. }
  62496. }
  62497. }
  62498. trans_begun:
  62499. if( rc==SQLITE_OK ){
  62500. if( pSchemaVersion ){
  62501. *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
  62502. }
  62503. if( wrflag ){
  62504. /* This call makes sure that the pager has the correct number of
  62505. ** open savepoints. If the second parameter is greater than 0 and
  62506. ** the sub-journal is not already open, then it will be opened here.
  62507. */
  62508. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  62509. }
  62510. }
  62511. btreeIntegrity(p);
  62512. sqlite3BtreeLeave(p);
  62513. return rc;
  62514. }
  62515. #ifndef SQLITE_OMIT_AUTOVACUUM
  62516. /*
  62517. ** Set the pointer-map entries for all children of page pPage. Also, if
  62518. ** pPage contains cells that point to overflow pages, set the pointer
  62519. ** map entries for the overflow pages as well.
  62520. */
  62521. static int setChildPtrmaps(MemPage *pPage){
  62522. int i; /* Counter variable */
  62523. int nCell; /* Number of cells in page pPage */
  62524. int rc; /* Return code */
  62525. BtShared *pBt = pPage->pBt;
  62526. Pgno pgno = pPage->pgno;
  62527. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62528. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  62529. if( rc!=SQLITE_OK ) return rc;
  62530. nCell = pPage->nCell;
  62531. for(i=0; i<nCell; i++){
  62532. u8 *pCell = findCell(pPage, i);
  62533. ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
  62534. if( !pPage->leaf ){
  62535. Pgno childPgno = get4byte(pCell);
  62536. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  62537. }
  62538. }
  62539. if( !pPage->leaf ){
  62540. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  62541. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  62542. }
  62543. return rc;
  62544. }
  62545. /*
  62546. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  62547. ** that it points to iTo. Parameter eType describes the type of pointer to
  62548. ** be modified, as follows:
  62549. **
  62550. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  62551. ** page of pPage.
  62552. **
  62553. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  62554. ** page pointed to by one of the cells on pPage.
  62555. **
  62556. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  62557. ** overflow page in the list.
  62558. */
  62559. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  62560. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62561. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  62562. if( eType==PTRMAP_OVERFLOW2 ){
  62563. /* The pointer is always the first 4 bytes of the page in this case. */
  62564. if( get4byte(pPage->aData)!=iFrom ){
  62565. return SQLITE_CORRUPT_PAGE(pPage);
  62566. }
  62567. put4byte(pPage->aData, iTo);
  62568. }else{
  62569. int i;
  62570. int nCell;
  62571. int rc;
  62572. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  62573. if( rc ) return rc;
  62574. nCell = pPage->nCell;
  62575. for(i=0; i<nCell; i++){
  62576. u8 *pCell = findCell(pPage, i);
  62577. if( eType==PTRMAP_OVERFLOW1 ){
  62578. CellInfo info;
  62579. pPage->xParseCell(pPage, pCell, &info);
  62580. if( info.nLocal<info.nPayload ){
  62581. if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
  62582. return SQLITE_CORRUPT_PAGE(pPage);
  62583. }
  62584. if( iFrom==get4byte(pCell+info.nSize-4) ){
  62585. put4byte(pCell+info.nSize-4, iTo);
  62586. break;
  62587. }
  62588. }
  62589. }else{
  62590. if( get4byte(pCell)==iFrom ){
  62591. put4byte(pCell, iTo);
  62592. break;
  62593. }
  62594. }
  62595. }
  62596. if( i==nCell ){
  62597. if( eType!=PTRMAP_BTREE ||
  62598. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  62599. return SQLITE_CORRUPT_PAGE(pPage);
  62600. }
  62601. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  62602. }
  62603. }
  62604. return SQLITE_OK;
  62605. }
  62606. /*
  62607. ** Move the open database page pDbPage to location iFreePage in the
  62608. ** database. The pDbPage reference remains valid.
  62609. **
  62610. ** The isCommit flag indicates that there is no need to remember that
  62611. ** the journal needs to be sync()ed before database page pDbPage->pgno
  62612. ** can be written to. The caller has already promised not to write to that
  62613. ** page.
  62614. */
  62615. static int relocatePage(
  62616. BtShared *pBt, /* Btree */
  62617. MemPage *pDbPage, /* Open page to move */
  62618. u8 eType, /* Pointer map 'type' entry for pDbPage */
  62619. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  62620. Pgno iFreePage, /* The location to move pDbPage to */
  62621. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  62622. ){
  62623. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  62624. Pgno iDbPage = pDbPage->pgno;
  62625. Pager *pPager = pBt->pPager;
  62626. int rc;
  62627. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  62628. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  62629. assert( sqlite3_mutex_held(pBt->mutex) );
  62630. assert( pDbPage->pBt==pBt );
  62631. if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
  62632. /* Move page iDbPage from its current location to page number iFreePage */
  62633. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  62634. iDbPage, iFreePage, iPtrPage, eType));
  62635. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  62636. if( rc!=SQLITE_OK ){
  62637. return rc;
  62638. }
  62639. pDbPage->pgno = iFreePage;
  62640. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  62641. ** that point to overflow pages. The pointer map entries for all these
  62642. ** pages need to be changed.
  62643. **
  62644. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  62645. ** pointer to a subsequent overflow page. If this is the case, then
  62646. ** the pointer map needs to be updated for the subsequent overflow page.
  62647. */
  62648. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  62649. rc = setChildPtrmaps(pDbPage);
  62650. if( rc!=SQLITE_OK ){
  62651. return rc;
  62652. }
  62653. }else{
  62654. Pgno nextOvfl = get4byte(pDbPage->aData);
  62655. if( nextOvfl!=0 ){
  62656. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  62657. if( rc!=SQLITE_OK ){
  62658. return rc;
  62659. }
  62660. }
  62661. }
  62662. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  62663. ** that it points at iFreePage. Also fix the pointer map entry for
  62664. ** iPtrPage.
  62665. */
  62666. if( eType!=PTRMAP_ROOTPAGE ){
  62667. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  62668. if( rc!=SQLITE_OK ){
  62669. return rc;
  62670. }
  62671. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  62672. if( rc!=SQLITE_OK ){
  62673. releasePage(pPtrPage);
  62674. return rc;
  62675. }
  62676. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  62677. releasePage(pPtrPage);
  62678. if( rc==SQLITE_OK ){
  62679. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  62680. }
  62681. }
  62682. return rc;
  62683. }
  62684. /* Forward declaration required by incrVacuumStep(). */
  62685. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  62686. /*
  62687. ** Perform a single step of an incremental-vacuum. If successful, return
  62688. ** SQLITE_OK. If there is no work to do (and therefore no point in
  62689. ** calling this function again), return SQLITE_DONE. Or, if an error
  62690. ** occurs, return some other error code.
  62691. **
  62692. ** More specifically, this function attempts to re-organize the database so
  62693. ** that the last page of the file currently in use is no longer in use.
  62694. **
  62695. ** Parameter nFin is the number of pages that this database would contain
  62696. ** were this function called until it returns SQLITE_DONE.
  62697. **
  62698. ** If the bCommit parameter is non-zero, this function assumes that the
  62699. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  62700. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  62701. ** operation, or false for an incremental vacuum.
  62702. */
  62703. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  62704. Pgno nFreeList; /* Number of pages still on the free-list */
  62705. int rc;
  62706. assert( sqlite3_mutex_held(pBt->mutex) );
  62707. assert( iLastPg>nFin );
  62708. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  62709. u8 eType;
  62710. Pgno iPtrPage;
  62711. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  62712. if( nFreeList==0 ){
  62713. return SQLITE_DONE;
  62714. }
  62715. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  62716. if( rc!=SQLITE_OK ){
  62717. return rc;
  62718. }
  62719. if( eType==PTRMAP_ROOTPAGE ){
  62720. return SQLITE_CORRUPT_BKPT;
  62721. }
  62722. if( eType==PTRMAP_FREEPAGE ){
  62723. if( bCommit==0 ){
  62724. /* Remove the page from the files free-list. This is not required
  62725. ** if bCommit is non-zero. In that case, the free-list will be
  62726. ** truncated to zero after this function returns, so it doesn't
  62727. ** matter if it still contains some garbage entries.
  62728. */
  62729. Pgno iFreePg;
  62730. MemPage *pFreePg;
  62731. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  62732. if( rc!=SQLITE_OK ){
  62733. return rc;
  62734. }
  62735. assert( iFreePg==iLastPg );
  62736. releasePage(pFreePg);
  62737. }
  62738. } else {
  62739. Pgno iFreePg; /* Index of free page to move pLastPg to */
  62740. MemPage *pLastPg;
  62741. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  62742. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  62743. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  62744. if( rc!=SQLITE_OK ){
  62745. return rc;
  62746. }
  62747. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  62748. ** is swapped with the first free page pulled off the free list.
  62749. **
  62750. ** On the other hand, if bCommit is greater than zero, then keep
  62751. ** looping until a free-page located within the first nFin pages
  62752. ** of the file is found.
  62753. */
  62754. if( bCommit==0 ){
  62755. eMode = BTALLOC_LE;
  62756. iNear = nFin;
  62757. }
  62758. do {
  62759. MemPage *pFreePg;
  62760. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  62761. if( rc!=SQLITE_OK ){
  62762. releasePage(pLastPg);
  62763. return rc;
  62764. }
  62765. releasePage(pFreePg);
  62766. }while( bCommit && iFreePg>nFin );
  62767. assert( iFreePg<iLastPg );
  62768. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  62769. releasePage(pLastPg);
  62770. if( rc!=SQLITE_OK ){
  62771. return rc;
  62772. }
  62773. }
  62774. }
  62775. if( bCommit==0 ){
  62776. do {
  62777. iLastPg--;
  62778. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  62779. pBt->bDoTruncate = 1;
  62780. pBt->nPage = iLastPg;
  62781. }
  62782. return SQLITE_OK;
  62783. }
  62784. /*
  62785. ** The database opened by the first argument is an auto-vacuum database
  62786. ** nOrig pages in size containing nFree free pages. Return the expected
  62787. ** size of the database in pages following an auto-vacuum operation.
  62788. */
  62789. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  62790. int nEntry; /* Number of entries on one ptrmap page */
  62791. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  62792. Pgno nFin; /* Return value */
  62793. nEntry = pBt->usableSize/5;
  62794. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  62795. nFin = nOrig - nFree - nPtrmap;
  62796. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  62797. nFin--;
  62798. }
  62799. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  62800. nFin--;
  62801. }
  62802. return nFin;
  62803. }
  62804. /*
  62805. ** A write-transaction must be opened before calling this function.
  62806. ** It performs a single unit of work towards an incremental vacuum.
  62807. **
  62808. ** If the incremental vacuum is finished after this function has run,
  62809. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  62810. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  62811. */
  62812. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  62813. int rc;
  62814. BtShared *pBt = p->pBt;
  62815. sqlite3BtreeEnter(p);
  62816. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  62817. if( !pBt->autoVacuum ){
  62818. rc = SQLITE_DONE;
  62819. }else{
  62820. Pgno nOrig = btreePagecount(pBt);
  62821. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  62822. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  62823. if( nOrig<nFin ){
  62824. rc = SQLITE_CORRUPT_BKPT;
  62825. }else if( nFree>0 ){
  62826. rc = saveAllCursors(pBt, 0, 0);
  62827. if( rc==SQLITE_OK ){
  62828. invalidateAllOverflowCache(pBt);
  62829. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  62830. }
  62831. if( rc==SQLITE_OK ){
  62832. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  62833. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  62834. }
  62835. }else{
  62836. rc = SQLITE_DONE;
  62837. }
  62838. }
  62839. sqlite3BtreeLeave(p);
  62840. return rc;
  62841. }
  62842. /*
  62843. ** This routine is called prior to sqlite3PagerCommit when a transaction
  62844. ** is committed for an auto-vacuum database.
  62845. **
  62846. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  62847. ** the database file should be truncated to during the commit process.
  62848. ** i.e. the database has been reorganized so that only the first *pnTrunc
  62849. ** pages are in use.
  62850. */
  62851. static int autoVacuumCommit(BtShared *pBt){
  62852. int rc = SQLITE_OK;
  62853. Pager *pPager = pBt->pPager;
  62854. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  62855. assert( sqlite3_mutex_held(pBt->mutex) );
  62856. invalidateAllOverflowCache(pBt);
  62857. assert(pBt->autoVacuum);
  62858. if( !pBt->incrVacuum ){
  62859. Pgno nFin; /* Number of pages in database after autovacuuming */
  62860. Pgno nFree; /* Number of pages on the freelist initially */
  62861. Pgno iFree; /* The next page to be freed */
  62862. Pgno nOrig; /* Database size before freeing */
  62863. nOrig = btreePagecount(pBt);
  62864. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  62865. /* It is not possible to create a database for which the final page
  62866. ** is either a pointer-map page or the pending-byte page. If one
  62867. ** is encountered, this indicates corruption.
  62868. */
  62869. return SQLITE_CORRUPT_BKPT;
  62870. }
  62871. nFree = get4byte(&pBt->pPage1->aData[36]);
  62872. nFin = finalDbSize(pBt, nOrig, nFree);
  62873. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  62874. if( nFin<nOrig ){
  62875. rc = saveAllCursors(pBt, 0, 0);
  62876. }
  62877. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  62878. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  62879. }
  62880. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  62881. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  62882. put4byte(&pBt->pPage1->aData[32], 0);
  62883. put4byte(&pBt->pPage1->aData[36], 0);
  62884. put4byte(&pBt->pPage1->aData[28], nFin);
  62885. pBt->bDoTruncate = 1;
  62886. pBt->nPage = nFin;
  62887. }
  62888. if( rc!=SQLITE_OK ){
  62889. sqlite3PagerRollback(pPager);
  62890. }
  62891. }
  62892. assert( nRef>=sqlite3PagerRefcount(pPager) );
  62893. return rc;
  62894. }
  62895. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  62896. # define setChildPtrmaps(x) SQLITE_OK
  62897. #endif
  62898. /*
  62899. ** This routine does the first phase of a two-phase commit. This routine
  62900. ** causes a rollback journal to be created (if it does not already exist)
  62901. ** and populated with enough information so that if a power loss occurs
  62902. ** the database can be restored to its original state by playing back
  62903. ** the journal. Then the contents of the journal are flushed out to
  62904. ** the disk. After the journal is safely on oxide, the changes to the
  62905. ** database are written into the database file and flushed to oxide.
  62906. ** At the end of this call, the rollback journal still exists on the
  62907. ** disk and we are still holding all locks, so the transaction has not
  62908. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  62909. ** commit process.
  62910. **
  62911. ** This call is a no-op if no write-transaction is currently active on pBt.
  62912. **
  62913. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  62914. ** the name of a master journal file that should be written into the
  62915. ** individual journal file, or is NULL, indicating no master journal file
  62916. ** (single database transaction).
  62917. **
  62918. ** When this is called, the master journal should already have been
  62919. ** created, populated with this journal pointer and synced to disk.
  62920. **
  62921. ** Once this is routine has returned, the only thing required to commit
  62922. ** the write-transaction for this database file is to delete the journal.
  62923. */
  62924. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  62925. int rc = SQLITE_OK;
  62926. if( p->inTrans==TRANS_WRITE ){
  62927. BtShared *pBt = p->pBt;
  62928. sqlite3BtreeEnter(p);
  62929. #ifndef SQLITE_OMIT_AUTOVACUUM
  62930. if( pBt->autoVacuum ){
  62931. rc = autoVacuumCommit(pBt);
  62932. if( rc!=SQLITE_OK ){
  62933. sqlite3BtreeLeave(p);
  62934. return rc;
  62935. }
  62936. }
  62937. if( pBt->bDoTruncate ){
  62938. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  62939. }
  62940. #endif
  62941. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  62942. sqlite3BtreeLeave(p);
  62943. }
  62944. return rc;
  62945. }
  62946. /*
  62947. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  62948. ** at the conclusion of a transaction.
  62949. */
  62950. static void btreeEndTransaction(Btree *p){
  62951. BtShared *pBt = p->pBt;
  62952. sqlite3 *db = p->db;
  62953. assert( sqlite3BtreeHoldsMutex(p) );
  62954. #ifndef SQLITE_OMIT_AUTOVACUUM
  62955. pBt->bDoTruncate = 0;
  62956. #endif
  62957. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  62958. /* If there are other active statements that belong to this database
  62959. ** handle, downgrade to a read-only transaction. The other statements
  62960. ** may still be reading from the database. */
  62961. downgradeAllSharedCacheTableLocks(p);
  62962. p->inTrans = TRANS_READ;
  62963. }else{
  62964. /* If the handle had any kind of transaction open, decrement the
  62965. ** transaction count of the shared btree. If the transaction count
  62966. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  62967. ** call below will unlock the pager. */
  62968. if( p->inTrans!=TRANS_NONE ){
  62969. clearAllSharedCacheTableLocks(p);
  62970. pBt->nTransaction--;
  62971. if( 0==pBt->nTransaction ){
  62972. pBt->inTransaction = TRANS_NONE;
  62973. }
  62974. }
  62975. /* Set the current transaction state to TRANS_NONE and unlock the
  62976. ** pager if this call closed the only read or write transaction. */
  62977. p->inTrans = TRANS_NONE;
  62978. unlockBtreeIfUnused(pBt);
  62979. }
  62980. btreeIntegrity(p);
  62981. }
  62982. /*
  62983. ** Commit the transaction currently in progress.
  62984. **
  62985. ** This routine implements the second phase of a 2-phase commit. The
  62986. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  62987. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  62988. ** routine did all the work of writing information out to disk and flushing the
  62989. ** contents so that they are written onto the disk platter. All this
  62990. ** routine has to do is delete or truncate or zero the header in the
  62991. ** the rollback journal (which causes the transaction to commit) and
  62992. ** drop locks.
  62993. **
  62994. ** Normally, if an error occurs while the pager layer is attempting to
  62995. ** finalize the underlying journal file, this function returns an error and
  62996. ** the upper layer will attempt a rollback. However, if the second argument
  62997. ** is non-zero then this b-tree transaction is part of a multi-file
  62998. ** transaction. In this case, the transaction has already been committed
  62999. ** (by deleting a master journal file) and the caller will ignore this
  63000. ** functions return code. So, even if an error occurs in the pager layer,
  63001. ** reset the b-tree objects internal state to indicate that the write
  63002. ** transaction has been closed. This is quite safe, as the pager will have
  63003. ** transitioned to the error state.
  63004. **
  63005. ** This will release the write lock on the database file. If there
  63006. ** are no active cursors, it also releases the read lock.
  63007. */
  63008. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  63009. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  63010. sqlite3BtreeEnter(p);
  63011. btreeIntegrity(p);
  63012. /* If the handle has a write-transaction open, commit the shared-btrees
  63013. ** transaction and set the shared state to TRANS_READ.
  63014. */
  63015. if( p->inTrans==TRANS_WRITE ){
  63016. int rc;
  63017. BtShared *pBt = p->pBt;
  63018. assert( pBt->inTransaction==TRANS_WRITE );
  63019. assert( pBt->nTransaction>0 );
  63020. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  63021. if( rc!=SQLITE_OK && bCleanup==0 ){
  63022. sqlite3BtreeLeave(p);
  63023. return rc;
  63024. }
  63025. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  63026. pBt->inTransaction = TRANS_READ;
  63027. btreeClearHasContent(pBt);
  63028. }
  63029. btreeEndTransaction(p);
  63030. sqlite3BtreeLeave(p);
  63031. return SQLITE_OK;
  63032. }
  63033. /*
  63034. ** Do both phases of a commit.
  63035. */
  63036. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  63037. int rc;
  63038. sqlite3BtreeEnter(p);
  63039. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  63040. if( rc==SQLITE_OK ){
  63041. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  63042. }
  63043. sqlite3BtreeLeave(p);
  63044. return rc;
  63045. }
  63046. /*
  63047. ** This routine sets the state to CURSOR_FAULT and the error
  63048. ** code to errCode for every cursor on any BtShared that pBtree
  63049. ** references. Or if the writeOnly flag is set to 1, then only
  63050. ** trip write cursors and leave read cursors unchanged.
  63051. **
  63052. ** Every cursor is a candidate to be tripped, including cursors
  63053. ** that belong to other database connections that happen to be
  63054. ** sharing the cache with pBtree.
  63055. **
  63056. ** This routine gets called when a rollback occurs. If the writeOnly
  63057. ** flag is true, then only write-cursors need be tripped - read-only
  63058. ** cursors save their current positions so that they may continue
  63059. ** following the rollback. Or, if writeOnly is false, all cursors are
  63060. ** tripped. In general, writeOnly is false if the transaction being
  63061. ** rolled back modified the database schema. In this case b-tree root
  63062. ** pages may be moved or deleted from the database altogether, making
  63063. ** it unsafe for read cursors to continue.
  63064. **
  63065. ** If the writeOnly flag is true and an error is encountered while
  63066. ** saving the current position of a read-only cursor, all cursors,
  63067. ** including all read-cursors are tripped.
  63068. **
  63069. ** SQLITE_OK is returned if successful, or if an error occurs while
  63070. ** saving a cursor position, an SQLite error code.
  63071. */
  63072. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  63073. BtCursor *p;
  63074. int rc = SQLITE_OK;
  63075. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  63076. if( pBtree ){
  63077. sqlite3BtreeEnter(pBtree);
  63078. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  63079. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  63080. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  63081. rc = saveCursorPosition(p);
  63082. if( rc!=SQLITE_OK ){
  63083. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  63084. break;
  63085. }
  63086. }
  63087. }else{
  63088. sqlite3BtreeClearCursor(p);
  63089. p->eState = CURSOR_FAULT;
  63090. p->skipNext = errCode;
  63091. }
  63092. btreeReleaseAllCursorPages(p);
  63093. }
  63094. sqlite3BtreeLeave(pBtree);
  63095. }
  63096. return rc;
  63097. }
  63098. /*
  63099. ** Rollback the transaction in progress.
  63100. **
  63101. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  63102. ** Only write cursors are tripped if writeOnly is true but all cursors are
  63103. ** tripped if writeOnly is false. Any attempt to use
  63104. ** a tripped cursor will result in an error.
  63105. **
  63106. ** This will release the write lock on the database file. If there
  63107. ** are no active cursors, it also releases the read lock.
  63108. */
  63109. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  63110. int rc;
  63111. BtShared *pBt = p->pBt;
  63112. MemPage *pPage1;
  63113. assert( writeOnly==1 || writeOnly==0 );
  63114. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  63115. sqlite3BtreeEnter(p);
  63116. if( tripCode==SQLITE_OK ){
  63117. rc = tripCode = saveAllCursors(pBt, 0, 0);
  63118. if( rc ) writeOnly = 0;
  63119. }else{
  63120. rc = SQLITE_OK;
  63121. }
  63122. if( tripCode ){
  63123. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  63124. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  63125. if( rc2!=SQLITE_OK ) rc = rc2;
  63126. }
  63127. btreeIntegrity(p);
  63128. if( p->inTrans==TRANS_WRITE ){
  63129. int rc2;
  63130. assert( TRANS_WRITE==pBt->inTransaction );
  63131. rc2 = sqlite3PagerRollback(pBt->pPager);
  63132. if( rc2!=SQLITE_OK ){
  63133. rc = rc2;
  63134. }
  63135. /* The rollback may have destroyed the pPage1->aData value. So
  63136. ** call btreeGetPage() on page 1 again to make
  63137. ** sure pPage1->aData is set correctly. */
  63138. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  63139. int nPage = get4byte(28+(u8*)pPage1->aData);
  63140. testcase( nPage==0 );
  63141. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  63142. testcase( pBt->nPage!=nPage );
  63143. pBt->nPage = nPage;
  63144. releasePageOne(pPage1);
  63145. }
  63146. assert( countValidCursors(pBt, 1)==0 );
  63147. pBt->inTransaction = TRANS_READ;
  63148. btreeClearHasContent(pBt);
  63149. }
  63150. btreeEndTransaction(p);
  63151. sqlite3BtreeLeave(p);
  63152. return rc;
  63153. }
  63154. /*
  63155. ** Start a statement subtransaction. The subtransaction can be rolled
  63156. ** back independently of the main transaction. You must start a transaction
  63157. ** before starting a subtransaction. The subtransaction is ended automatically
  63158. ** if the main transaction commits or rolls back.
  63159. **
  63160. ** Statement subtransactions are used around individual SQL statements
  63161. ** that are contained within a BEGIN...COMMIT block. If a constraint
  63162. ** error occurs within the statement, the effect of that one statement
  63163. ** can be rolled back without having to rollback the entire transaction.
  63164. **
  63165. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  63166. ** value passed as the second parameter is the total number of savepoints,
  63167. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  63168. ** are no active savepoints and no other statement-transactions open,
  63169. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  63170. ** using the sqlite3BtreeSavepoint() function.
  63171. */
  63172. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  63173. int rc;
  63174. BtShared *pBt = p->pBt;
  63175. sqlite3BtreeEnter(p);
  63176. assert( p->inTrans==TRANS_WRITE );
  63177. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  63178. assert( iStatement>0 );
  63179. assert( iStatement>p->db->nSavepoint );
  63180. assert( pBt->inTransaction==TRANS_WRITE );
  63181. /* At the pager level, a statement transaction is a savepoint with
  63182. ** an index greater than all savepoints created explicitly using
  63183. ** SQL statements. It is illegal to open, release or rollback any
  63184. ** such savepoints while the statement transaction savepoint is active.
  63185. */
  63186. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  63187. sqlite3BtreeLeave(p);
  63188. return rc;
  63189. }
  63190. /*
  63191. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  63192. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  63193. ** savepoint identified by parameter iSavepoint, depending on the value
  63194. ** of op.
  63195. **
  63196. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  63197. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  63198. ** contents of the entire transaction are rolled back. This is different
  63199. ** from a normal transaction rollback, as no locks are released and the
  63200. ** transaction remains open.
  63201. */
  63202. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  63203. int rc = SQLITE_OK;
  63204. if( p && p->inTrans==TRANS_WRITE ){
  63205. BtShared *pBt = p->pBt;
  63206. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  63207. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  63208. sqlite3BtreeEnter(p);
  63209. if( op==SAVEPOINT_ROLLBACK ){
  63210. rc = saveAllCursors(pBt, 0, 0);
  63211. }
  63212. if( rc==SQLITE_OK ){
  63213. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  63214. }
  63215. if( rc==SQLITE_OK ){
  63216. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  63217. pBt->nPage = 0;
  63218. }
  63219. rc = newDatabase(pBt);
  63220. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  63221. /* The database size was written into the offset 28 of the header
  63222. ** when the transaction started, so we know that the value at offset
  63223. ** 28 is nonzero. */
  63224. assert( pBt->nPage>0 );
  63225. }
  63226. sqlite3BtreeLeave(p);
  63227. }
  63228. return rc;
  63229. }
  63230. /*
  63231. ** Create a new cursor for the BTree whose root is on the page
  63232. ** iTable. If a read-only cursor is requested, it is assumed that
  63233. ** the caller already has at least a read-only transaction open
  63234. ** on the database already. If a write-cursor is requested, then
  63235. ** the caller is assumed to have an open write transaction.
  63236. **
  63237. ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
  63238. ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
  63239. ** can be used for reading or for writing if other conditions for writing
  63240. ** are also met. These are the conditions that must be met in order
  63241. ** for writing to be allowed:
  63242. **
  63243. ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
  63244. **
  63245. ** 2: Other database connections that share the same pager cache
  63246. ** but which are not in the READ_UNCOMMITTED state may not have
  63247. ** cursors open with wrFlag==0 on the same table. Otherwise
  63248. ** the changes made by this write cursor would be visible to
  63249. ** the read cursors in the other database connection.
  63250. **
  63251. ** 3: The database must be writable (not on read-only media)
  63252. **
  63253. ** 4: There must be an active transaction.
  63254. **
  63255. ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
  63256. ** is set. If FORDELETE is set, that is a hint to the implementation that
  63257. ** this cursor will only be used to seek to and delete entries of an index
  63258. ** as part of a larger DELETE statement. The FORDELETE hint is not used by
  63259. ** this implementation. But in a hypothetical alternative storage engine
  63260. ** in which index entries are automatically deleted when corresponding table
  63261. ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
  63262. ** operations on this cursor can be no-ops and all READ operations can
  63263. ** return a null row (2-bytes: 0x01 0x00).
  63264. **
  63265. ** No checking is done to make sure that page iTable really is the
  63266. ** root page of a b-tree. If it is not, then the cursor acquired
  63267. ** will not work correctly.
  63268. **
  63269. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  63270. ** on pCur to initialize the memory space prior to invoking this routine.
  63271. */
  63272. static int btreeCursor(
  63273. Btree *p, /* The btree */
  63274. int iTable, /* Root page of table to open */
  63275. int wrFlag, /* 1 to write. 0 read-only */
  63276. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  63277. BtCursor *pCur /* Space for new cursor */
  63278. ){
  63279. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  63280. BtCursor *pX; /* Looping over other all cursors */
  63281. assert( sqlite3BtreeHoldsMutex(p) );
  63282. assert( wrFlag==0
  63283. || wrFlag==BTREE_WRCSR
  63284. || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
  63285. );
  63286. /* The following assert statements verify that if this is a sharable
  63287. ** b-tree database, the connection is holding the required table locks,
  63288. ** and that no other connection has any open cursor that conflicts with
  63289. ** this lock. */
  63290. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
  63291. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  63292. /* Assert that the caller has opened the required transaction. */
  63293. assert( p->inTrans>TRANS_NONE );
  63294. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  63295. assert( pBt->pPage1 && pBt->pPage1->aData );
  63296. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  63297. if( wrFlag ){
  63298. allocateTempSpace(pBt);
  63299. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
  63300. }
  63301. if( iTable==1 && btreePagecount(pBt)==0 ){
  63302. assert( wrFlag==0 );
  63303. iTable = 0;
  63304. }
  63305. /* Now that no other errors can occur, finish filling in the BtCursor
  63306. ** variables and link the cursor into the BtShared list. */
  63307. pCur->pgnoRoot = (Pgno)iTable;
  63308. pCur->iPage = -1;
  63309. pCur->pKeyInfo = pKeyInfo;
  63310. pCur->pBtree = p;
  63311. pCur->pBt = pBt;
  63312. pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
  63313. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  63314. /* If there are two or more cursors on the same btree, then all such
  63315. ** cursors *must* have the BTCF_Multiple flag set. */
  63316. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  63317. if( pX->pgnoRoot==(Pgno)iTable ){
  63318. pX->curFlags |= BTCF_Multiple;
  63319. pCur->curFlags |= BTCF_Multiple;
  63320. }
  63321. }
  63322. pCur->pNext = pBt->pCursor;
  63323. pBt->pCursor = pCur;
  63324. pCur->eState = CURSOR_INVALID;
  63325. return SQLITE_OK;
  63326. }
  63327. SQLITE_PRIVATE int sqlite3BtreeCursor(
  63328. Btree *p, /* The btree */
  63329. int iTable, /* Root page of table to open */
  63330. int wrFlag, /* 1 to write. 0 read-only */
  63331. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  63332. BtCursor *pCur /* Write new cursor here */
  63333. ){
  63334. int rc;
  63335. if( iTable<1 ){
  63336. rc = SQLITE_CORRUPT_BKPT;
  63337. }else{
  63338. sqlite3BtreeEnter(p);
  63339. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  63340. sqlite3BtreeLeave(p);
  63341. }
  63342. return rc;
  63343. }
  63344. /*
  63345. ** Return the size of a BtCursor object in bytes.
  63346. **
  63347. ** This interfaces is needed so that users of cursors can preallocate
  63348. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  63349. ** to users so they cannot do the sizeof() themselves - they must call
  63350. ** this routine.
  63351. */
  63352. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  63353. return ROUND8(sizeof(BtCursor));
  63354. }
  63355. /*
  63356. ** Initialize memory that will be converted into a BtCursor object.
  63357. **
  63358. ** The simple approach here would be to memset() the entire object
  63359. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  63360. ** do not need to be zeroed and they are large, so we can save a lot
  63361. ** of run-time by skipping the initialization of those elements.
  63362. */
  63363. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  63364. memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
  63365. }
  63366. /*
  63367. ** Close a cursor. The read lock on the database file is released
  63368. ** when the last cursor is closed.
  63369. */
  63370. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  63371. Btree *pBtree = pCur->pBtree;
  63372. if( pBtree ){
  63373. BtShared *pBt = pCur->pBt;
  63374. sqlite3BtreeEnter(pBtree);
  63375. assert( pBt->pCursor!=0 );
  63376. if( pBt->pCursor==pCur ){
  63377. pBt->pCursor = pCur->pNext;
  63378. }else{
  63379. BtCursor *pPrev = pBt->pCursor;
  63380. do{
  63381. if( pPrev->pNext==pCur ){
  63382. pPrev->pNext = pCur->pNext;
  63383. break;
  63384. }
  63385. pPrev = pPrev->pNext;
  63386. }while( ALWAYS(pPrev) );
  63387. }
  63388. btreeReleaseAllCursorPages(pCur);
  63389. unlockBtreeIfUnused(pBt);
  63390. sqlite3_free(pCur->aOverflow);
  63391. sqlite3_free(pCur->pKey);
  63392. sqlite3BtreeLeave(pBtree);
  63393. pCur->pBtree = 0;
  63394. }
  63395. return SQLITE_OK;
  63396. }
  63397. /*
  63398. ** Make sure the BtCursor* given in the argument has a valid
  63399. ** BtCursor.info structure. If it is not already valid, call
  63400. ** btreeParseCell() to fill it in.
  63401. **
  63402. ** BtCursor.info is a cache of the information in the current cell.
  63403. ** Using this cache reduces the number of calls to btreeParseCell().
  63404. */
  63405. #ifndef NDEBUG
  63406. static int cellInfoEqual(CellInfo *a, CellInfo *b){
  63407. if( a->nKey!=b->nKey ) return 0;
  63408. if( a->pPayload!=b->pPayload ) return 0;
  63409. if( a->nPayload!=b->nPayload ) return 0;
  63410. if( a->nLocal!=b->nLocal ) return 0;
  63411. if( a->nSize!=b->nSize ) return 0;
  63412. return 1;
  63413. }
  63414. static void assertCellInfo(BtCursor *pCur){
  63415. CellInfo info;
  63416. memset(&info, 0, sizeof(info));
  63417. btreeParseCell(pCur->pPage, pCur->ix, &info);
  63418. assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
  63419. }
  63420. #else
  63421. #define assertCellInfo(x)
  63422. #endif
  63423. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  63424. if( pCur->info.nSize==0 ){
  63425. pCur->curFlags |= BTCF_ValidNKey;
  63426. btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
  63427. }else{
  63428. assertCellInfo(pCur);
  63429. }
  63430. }
  63431. #ifndef NDEBUG /* The next routine used only within assert() statements */
  63432. /*
  63433. ** Return true if the given BtCursor is valid. A valid cursor is one
  63434. ** that is currently pointing to a row in a (non-empty) table.
  63435. ** This is a verification routine is used only within assert() statements.
  63436. */
  63437. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  63438. return pCur && pCur->eState==CURSOR_VALID;
  63439. }
  63440. #endif /* NDEBUG */
  63441. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
  63442. assert( pCur!=0 );
  63443. return pCur->eState==CURSOR_VALID;
  63444. }
  63445. /*
  63446. ** Return the value of the integer key or "rowid" for a table btree.
  63447. ** This routine is only valid for a cursor that is pointing into a
  63448. ** ordinary table btree. If the cursor points to an index btree or
  63449. ** is invalid, the result of this routine is undefined.
  63450. */
  63451. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
  63452. assert( cursorHoldsMutex(pCur) );
  63453. assert( pCur->eState==CURSOR_VALID );
  63454. assert( pCur->curIntKey );
  63455. getCellInfo(pCur);
  63456. return pCur->info.nKey;
  63457. }
  63458. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  63459. /*
  63460. ** Return the offset into the database file for the start of the
  63461. ** payload to which the cursor is pointing.
  63462. */
  63463. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){
  63464. assert( cursorHoldsMutex(pCur) );
  63465. assert( pCur->eState==CURSOR_VALID );
  63466. getCellInfo(pCur);
  63467. return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
  63468. (i64)(pCur->info.pPayload - pCur->pPage->aData);
  63469. }
  63470. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  63471. /*
  63472. ** Return the number of bytes of payload for the entry that pCur is
  63473. ** currently pointing to. For table btrees, this will be the amount
  63474. ** of data. For index btrees, this will be the size of the key.
  63475. **
  63476. ** The caller must guarantee that the cursor is pointing to a non-NULL
  63477. ** valid entry. In other words, the calling procedure must guarantee
  63478. ** that the cursor has Cursor.eState==CURSOR_VALID.
  63479. */
  63480. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
  63481. assert( cursorHoldsMutex(pCur) );
  63482. assert( pCur->eState==CURSOR_VALID );
  63483. getCellInfo(pCur);
  63484. return pCur->info.nPayload;
  63485. }
  63486. /*
  63487. ** Return an upper bound on the size of any record for the table
  63488. ** that the cursor is pointing into.
  63489. **
  63490. ** This is an optimization. Everything will still work if this
  63491. ** routine always returns 2147483647 (which is the largest record
  63492. ** that SQLite can handle) or more. But returning a smaller value might
  63493. ** prevent large memory allocations when trying to interpret a
  63494. ** corrupt datrabase.
  63495. **
  63496. ** The current implementation merely returns the size of the underlying
  63497. ** database file.
  63498. */
  63499. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
  63500. assert( cursorHoldsMutex(pCur) );
  63501. assert( pCur->eState==CURSOR_VALID );
  63502. return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
  63503. }
  63504. /*
  63505. ** Given the page number of an overflow page in the database (parameter
  63506. ** ovfl), this function finds the page number of the next page in the
  63507. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  63508. ** pointer-map data instead of reading the content of page ovfl to do so.
  63509. **
  63510. ** If an error occurs an SQLite error code is returned. Otherwise:
  63511. **
  63512. ** The page number of the next overflow page in the linked list is
  63513. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  63514. ** list, *pPgnoNext is set to zero.
  63515. **
  63516. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  63517. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  63518. ** reference. It is the responsibility of the caller to call releasePage()
  63519. ** on *ppPage to free the reference. In no reference was obtained (because
  63520. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  63521. ** *ppPage is set to zero.
  63522. */
  63523. static int getOverflowPage(
  63524. BtShared *pBt, /* The database file */
  63525. Pgno ovfl, /* Current overflow page number */
  63526. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  63527. Pgno *pPgnoNext /* OUT: Next overflow page number */
  63528. ){
  63529. Pgno next = 0;
  63530. MemPage *pPage = 0;
  63531. int rc = SQLITE_OK;
  63532. assert( sqlite3_mutex_held(pBt->mutex) );
  63533. assert(pPgnoNext);
  63534. #ifndef SQLITE_OMIT_AUTOVACUUM
  63535. /* Try to find the next page in the overflow list using the
  63536. ** autovacuum pointer-map pages. Guess that the next page in
  63537. ** the overflow list is page number (ovfl+1). If that guess turns
  63538. ** out to be wrong, fall back to loading the data of page
  63539. ** number ovfl to determine the next page number.
  63540. */
  63541. if( pBt->autoVacuum ){
  63542. Pgno pgno;
  63543. Pgno iGuess = ovfl+1;
  63544. u8 eType;
  63545. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  63546. iGuess++;
  63547. }
  63548. if( iGuess<=btreePagecount(pBt) ){
  63549. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  63550. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  63551. next = iGuess;
  63552. rc = SQLITE_DONE;
  63553. }
  63554. }
  63555. }
  63556. #endif
  63557. assert( next==0 || rc==SQLITE_DONE );
  63558. if( rc==SQLITE_OK ){
  63559. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  63560. assert( rc==SQLITE_OK || pPage==0 );
  63561. if( rc==SQLITE_OK ){
  63562. next = get4byte(pPage->aData);
  63563. }
  63564. }
  63565. *pPgnoNext = next;
  63566. if( ppPage ){
  63567. *ppPage = pPage;
  63568. }else{
  63569. releasePage(pPage);
  63570. }
  63571. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  63572. }
  63573. /*
  63574. ** Copy data from a buffer to a page, or from a page to a buffer.
  63575. **
  63576. ** pPayload is a pointer to data stored on database page pDbPage.
  63577. ** If argument eOp is false, then nByte bytes of data are copied
  63578. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  63579. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  63580. ** of data are copied from the buffer pBuf to pPayload.
  63581. **
  63582. ** SQLITE_OK is returned on success, otherwise an error code.
  63583. */
  63584. static int copyPayload(
  63585. void *pPayload, /* Pointer to page data */
  63586. void *pBuf, /* Pointer to buffer */
  63587. int nByte, /* Number of bytes to copy */
  63588. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  63589. DbPage *pDbPage /* Page containing pPayload */
  63590. ){
  63591. if( eOp ){
  63592. /* Copy data from buffer to page (a write operation) */
  63593. int rc = sqlite3PagerWrite(pDbPage);
  63594. if( rc!=SQLITE_OK ){
  63595. return rc;
  63596. }
  63597. memcpy(pPayload, pBuf, nByte);
  63598. }else{
  63599. /* Copy data from page to buffer (a read operation) */
  63600. memcpy(pBuf, pPayload, nByte);
  63601. }
  63602. return SQLITE_OK;
  63603. }
  63604. /*
  63605. ** This function is used to read or overwrite payload information
  63606. ** for the entry that the pCur cursor is pointing to. The eOp
  63607. ** argument is interpreted as follows:
  63608. **
  63609. ** 0: The operation is a read. Populate the overflow cache.
  63610. ** 1: The operation is a write. Populate the overflow cache.
  63611. **
  63612. ** A total of "amt" bytes are read or written beginning at "offset".
  63613. ** Data is read to or from the buffer pBuf.
  63614. **
  63615. ** The content being read or written might appear on the main page
  63616. ** or be scattered out on multiple overflow pages.
  63617. **
  63618. ** If the current cursor entry uses one or more overflow pages
  63619. ** this function may allocate space for and lazily populate
  63620. ** the overflow page-list cache array (BtCursor.aOverflow).
  63621. ** Subsequent calls use this cache to make seeking to the supplied offset
  63622. ** more efficient.
  63623. **
  63624. ** Once an overflow page-list cache has been allocated, it must be
  63625. ** invalidated if some other cursor writes to the same table, or if
  63626. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  63627. ** mode, the following events may invalidate an overflow page-list cache.
  63628. **
  63629. ** * An incremental vacuum,
  63630. ** * A commit in auto_vacuum="full" mode,
  63631. ** * Creating a table (may require moving an overflow page).
  63632. */
  63633. static int accessPayload(
  63634. BtCursor *pCur, /* Cursor pointing to entry to read from */
  63635. u32 offset, /* Begin reading this far into payload */
  63636. u32 amt, /* Read this many bytes */
  63637. unsigned char *pBuf, /* Write the bytes into this buffer */
  63638. int eOp /* zero to read. non-zero to write. */
  63639. ){
  63640. unsigned char *aPayload;
  63641. int rc = SQLITE_OK;
  63642. int iIdx = 0;
  63643. MemPage *pPage = pCur->pPage; /* Btree page of current entry */
  63644. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  63645. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  63646. unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
  63647. #endif
  63648. assert( pPage );
  63649. assert( eOp==0 || eOp==1 );
  63650. assert( pCur->eState==CURSOR_VALID );
  63651. assert( pCur->ix<pPage->nCell );
  63652. assert( cursorHoldsMutex(pCur) );
  63653. getCellInfo(pCur);
  63654. aPayload = pCur->info.pPayload;
  63655. assert( offset+amt <= pCur->info.nPayload );
  63656. assert( aPayload > pPage->aData );
  63657. if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
  63658. /* Trying to read or write past the end of the data is an error. The
  63659. ** conditional above is really:
  63660. ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  63661. ** but is recast into its current form to avoid integer overflow problems
  63662. */
  63663. return SQLITE_CORRUPT_PAGE(pPage);
  63664. }
  63665. /* Check if data must be read/written to/from the btree page itself. */
  63666. if( offset<pCur->info.nLocal ){
  63667. int a = amt;
  63668. if( a+offset>pCur->info.nLocal ){
  63669. a = pCur->info.nLocal - offset;
  63670. }
  63671. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  63672. offset = 0;
  63673. pBuf += a;
  63674. amt -= a;
  63675. }else{
  63676. offset -= pCur->info.nLocal;
  63677. }
  63678. if( rc==SQLITE_OK && amt>0 ){
  63679. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  63680. Pgno nextPage;
  63681. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  63682. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  63683. **
  63684. ** The aOverflow[] array is sized at one entry for each overflow page
  63685. ** in the overflow chain. The page number of the first overflow page is
  63686. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  63687. ** means "not yet known" (the cache is lazily populated).
  63688. */
  63689. if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  63690. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  63691. if( pCur->aOverflow==0
  63692. || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
  63693. ){
  63694. Pgno *aNew = (Pgno*)sqlite3Realloc(
  63695. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  63696. );
  63697. if( aNew==0 ){
  63698. return SQLITE_NOMEM_BKPT;
  63699. }else{
  63700. pCur->aOverflow = aNew;
  63701. }
  63702. }
  63703. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  63704. pCur->curFlags |= BTCF_ValidOvfl;
  63705. }else{
  63706. /* If the overflow page-list cache has been allocated and the
  63707. ** entry for the first required overflow page is valid, skip
  63708. ** directly to it.
  63709. */
  63710. if( pCur->aOverflow[offset/ovflSize] ){
  63711. iIdx = (offset/ovflSize);
  63712. nextPage = pCur->aOverflow[iIdx];
  63713. offset = (offset%ovflSize);
  63714. }
  63715. }
  63716. assert( rc==SQLITE_OK && amt>0 );
  63717. while( nextPage ){
  63718. /* If required, populate the overflow page-list cache. */
  63719. assert( pCur->aOverflow[iIdx]==0
  63720. || pCur->aOverflow[iIdx]==nextPage
  63721. || CORRUPT_DB );
  63722. pCur->aOverflow[iIdx] = nextPage;
  63723. if( offset>=ovflSize ){
  63724. /* The only reason to read this page is to obtain the page
  63725. ** number for the next page in the overflow chain. The page
  63726. ** data is not required. So first try to lookup the overflow
  63727. ** page-list cache, if any, then fall back to the getOverflowPage()
  63728. ** function.
  63729. */
  63730. assert( pCur->curFlags & BTCF_ValidOvfl );
  63731. assert( pCur->pBtree->db==pBt->db );
  63732. if( pCur->aOverflow[iIdx+1] ){
  63733. nextPage = pCur->aOverflow[iIdx+1];
  63734. }else{
  63735. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  63736. }
  63737. offset -= ovflSize;
  63738. }else{
  63739. /* Need to read this page properly. It contains some of the
  63740. ** range of data that is being read (eOp==0) or written (eOp!=0).
  63741. */
  63742. int a = amt;
  63743. if( a + offset > ovflSize ){
  63744. a = ovflSize - offset;
  63745. }
  63746. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  63747. /* If all the following are true:
  63748. **
  63749. ** 1) this is a read operation, and
  63750. ** 2) data is required from the start of this overflow page, and
  63751. ** 3) there are no dirty pages in the page-cache
  63752. ** 4) the database is file-backed, and
  63753. ** 5) the page is not in the WAL file
  63754. ** 6) at least 4 bytes have already been read into the output buffer
  63755. **
  63756. ** then data can be read directly from the database file into the
  63757. ** output buffer, bypassing the page-cache altogether. This speeds
  63758. ** up loading large records that span many overflow pages.
  63759. */
  63760. if( eOp==0 /* (1) */
  63761. && offset==0 /* (2) */
  63762. && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
  63763. && &pBuf[-4]>=pBufStart /* (6) */
  63764. ){
  63765. sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
  63766. u8 aSave[4];
  63767. u8 *aWrite = &pBuf[-4];
  63768. assert( aWrite>=pBufStart ); /* due to (6) */
  63769. memcpy(aSave, aWrite, 4);
  63770. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  63771. nextPage = get4byte(aWrite);
  63772. memcpy(aWrite, aSave, 4);
  63773. }else
  63774. #endif
  63775. {
  63776. DbPage *pDbPage;
  63777. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
  63778. (eOp==0 ? PAGER_GET_READONLY : 0)
  63779. );
  63780. if( rc==SQLITE_OK ){
  63781. aPayload = sqlite3PagerGetData(pDbPage);
  63782. nextPage = get4byte(aPayload);
  63783. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  63784. sqlite3PagerUnref(pDbPage);
  63785. offset = 0;
  63786. }
  63787. }
  63788. amt -= a;
  63789. if( amt==0 ) return rc;
  63790. pBuf += a;
  63791. }
  63792. if( rc ) break;
  63793. iIdx++;
  63794. }
  63795. }
  63796. if( rc==SQLITE_OK && amt>0 ){
  63797. /* Overflow chain ends prematurely */
  63798. return SQLITE_CORRUPT_PAGE(pPage);
  63799. }
  63800. return rc;
  63801. }
  63802. /*
  63803. ** Read part of the payload for the row at which that cursor pCur is currently
  63804. ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
  63805. ** begins at "offset".
  63806. **
  63807. ** pCur can be pointing to either a table or an index b-tree.
  63808. ** If pointing to a table btree, then the content section is read. If
  63809. ** pCur is pointing to an index b-tree then the key section is read.
  63810. **
  63811. ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
  63812. ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
  63813. ** cursor might be invalid or might need to be restored before being read.
  63814. **
  63815. ** Return SQLITE_OK on success or an error code if anything goes
  63816. ** wrong. An error is returned if "offset+amt" is larger than
  63817. ** the available payload.
  63818. */
  63819. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  63820. assert( cursorHoldsMutex(pCur) );
  63821. assert( pCur->eState==CURSOR_VALID );
  63822. assert( pCur->iPage>=0 && pCur->pPage );
  63823. assert( pCur->ix<pCur->pPage->nCell );
  63824. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  63825. }
  63826. /*
  63827. ** This variant of sqlite3BtreePayload() works even if the cursor has not
  63828. ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
  63829. ** interface.
  63830. */
  63831. #ifndef SQLITE_OMIT_INCRBLOB
  63832. static SQLITE_NOINLINE int accessPayloadChecked(
  63833. BtCursor *pCur,
  63834. u32 offset,
  63835. u32 amt,
  63836. void *pBuf
  63837. ){
  63838. int rc;
  63839. if ( pCur->eState==CURSOR_INVALID ){
  63840. return SQLITE_ABORT;
  63841. }
  63842. assert( cursorOwnsBtShared(pCur) );
  63843. rc = btreeRestoreCursorPosition(pCur);
  63844. return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
  63845. }
  63846. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  63847. if( pCur->eState==CURSOR_VALID ){
  63848. assert( cursorOwnsBtShared(pCur) );
  63849. return accessPayload(pCur, offset, amt, pBuf, 0);
  63850. }else{
  63851. return accessPayloadChecked(pCur, offset, amt, pBuf);
  63852. }
  63853. }
  63854. #endif /* SQLITE_OMIT_INCRBLOB */
  63855. /*
  63856. ** Return a pointer to payload information from the entry that the
  63857. ** pCur cursor is pointing to. The pointer is to the beginning of
  63858. ** the key if index btrees (pPage->intKey==0) and is the data for
  63859. ** table btrees (pPage->intKey==1). The number of bytes of available
  63860. ** key/data is written into *pAmt. If *pAmt==0, then the value
  63861. ** returned will not be a valid pointer.
  63862. **
  63863. ** This routine is an optimization. It is common for the entire key
  63864. ** and data to fit on the local page and for there to be no overflow
  63865. ** pages. When that is so, this routine can be used to access the
  63866. ** key and data without making a copy. If the key and/or data spills
  63867. ** onto overflow pages, then accessPayload() must be used to reassemble
  63868. ** the key/data and copy it into a preallocated buffer.
  63869. **
  63870. ** The pointer returned by this routine looks directly into the cached
  63871. ** page of the database. The data might change or move the next time
  63872. ** any btree routine is called.
  63873. */
  63874. static const void *fetchPayload(
  63875. BtCursor *pCur, /* Cursor pointing to entry to read from */
  63876. u32 *pAmt /* Write the number of available bytes here */
  63877. ){
  63878. int amt;
  63879. assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
  63880. assert( pCur->eState==CURSOR_VALID );
  63881. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  63882. assert( cursorOwnsBtShared(pCur) );
  63883. assert( pCur->ix<pCur->pPage->nCell );
  63884. assert( pCur->info.nSize>0 );
  63885. assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
  63886. assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
  63887. amt = pCur->info.nLocal;
  63888. if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
  63889. /* There is too little space on the page for the expected amount
  63890. ** of local content. Database must be corrupt. */
  63891. assert( CORRUPT_DB );
  63892. amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
  63893. }
  63894. *pAmt = (u32)amt;
  63895. return (void*)pCur->info.pPayload;
  63896. }
  63897. /*
  63898. ** For the entry that cursor pCur is point to, return as
  63899. ** many bytes of the key or data as are available on the local
  63900. ** b-tree page. Write the number of available bytes into *pAmt.
  63901. **
  63902. ** The pointer returned is ephemeral. The key/data may move
  63903. ** or be destroyed on the next call to any Btree routine,
  63904. ** including calls from other threads against the same cache.
  63905. ** Hence, a mutex on the BtShared should be held prior to calling
  63906. ** this routine.
  63907. **
  63908. ** These routines is used to get quick access to key and data
  63909. ** in the common case where no overflow pages are used.
  63910. */
  63911. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
  63912. return fetchPayload(pCur, pAmt);
  63913. }
  63914. /*
  63915. ** Move the cursor down to a new child page. The newPgno argument is the
  63916. ** page number of the child page to move to.
  63917. **
  63918. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  63919. ** the new child page does not match the flags field of the parent (i.e.
  63920. ** if an intkey page appears to be the parent of a non-intkey page, or
  63921. ** vice-versa).
  63922. */
  63923. static int moveToChild(BtCursor *pCur, u32 newPgno){
  63924. BtShared *pBt = pCur->pBt;
  63925. assert( cursorOwnsBtShared(pCur) );
  63926. assert( pCur->eState==CURSOR_VALID );
  63927. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  63928. assert( pCur->iPage>=0 );
  63929. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  63930. return SQLITE_CORRUPT_BKPT;
  63931. }
  63932. pCur->info.nSize = 0;
  63933. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  63934. pCur->aiIdx[pCur->iPage] = pCur->ix;
  63935. pCur->apPage[pCur->iPage] = pCur->pPage;
  63936. pCur->ix = 0;
  63937. pCur->iPage++;
  63938. return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
  63939. }
  63940. #ifdef SQLITE_DEBUG
  63941. /*
  63942. ** Page pParent is an internal (non-leaf) tree page. This function
  63943. ** asserts that page number iChild is the left-child if the iIdx'th
  63944. ** cell in page pParent. Or, if iIdx is equal to the total number of
  63945. ** cells in pParent, that page number iChild is the right-child of
  63946. ** the page.
  63947. */
  63948. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  63949. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  63950. ** in a corrupt database */
  63951. assert( iIdx<=pParent->nCell );
  63952. if( iIdx==pParent->nCell ){
  63953. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  63954. }else{
  63955. assert( get4byte(findCell(pParent, iIdx))==iChild );
  63956. }
  63957. }
  63958. #else
  63959. # define assertParentIndex(x,y,z)
  63960. #endif
  63961. /*
  63962. ** Move the cursor up to the parent page.
  63963. **
  63964. ** pCur->idx is set to the cell index that contains the pointer
  63965. ** to the page we are coming from. If we are coming from the
  63966. ** right-most child page then pCur->idx is set to one more than
  63967. ** the largest cell index.
  63968. */
  63969. static void moveToParent(BtCursor *pCur){
  63970. MemPage *pLeaf;
  63971. assert( cursorOwnsBtShared(pCur) );
  63972. assert( pCur->eState==CURSOR_VALID );
  63973. assert( pCur->iPage>0 );
  63974. assert( pCur->pPage );
  63975. assertParentIndex(
  63976. pCur->apPage[pCur->iPage-1],
  63977. pCur->aiIdx[pCur->iPage-1],
  63978. pCur->pPage->pgno
  63979. );
  63980. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  63981. pCur->info.nSize = 0;
  63982. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  63983. pCur->ix = pCur->aiIdx[pCur->iPage-1];
  63984. pLeaf = pCur->pPage;
  63985. pCur->pPage = pCur->apPage[--pCur->iPage];
  63986. releasePageNotNull(pLeaf);
  63987. }
  63988. /*
  63989. ** Move the cursor to point to the root page of its b-tree structure.
  63990. **
  63991. ** If the table has a virtual root page, then the cursor is moved to point
  63992. ** to the virtual root page instead of the actual root page. A table has a
  63993. ** virtual root page when the actual root page contains no cells and a
  63994. ** single child page. This can only happen with the table rooted at page 1.
  63995. **
  63996. ** If the b-tree structure is empty, the cursor state is set to
  63997. ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
  63998. ** the cursor is set to point to the first cell located on the root
  63999. ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
  64000. **
  64001. ** If this function returns successfully, it may be assumed that the
  64002. ** page-header flags indicate that the [virtual] root-page is the expected
  64003. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  64004. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  64005. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  64006. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  64007. ** b-tree).
  64008. */
  64009. static int moveToRoot(BtCursor *pCur){
  64010. MemPage *pRoot;
  64011. int rc = SQLITE_OK;
  64012. assert( cursorOwnsBtShared(pCur) );
  64013. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  64014. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  64015. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  64016. assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
  64017. assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
  64018. if( pCur->iPage>=0 ){
  64019. if( pCur->iPage ){
  64020. releasePageNotNull(pCur->pPage);
  64021. while( --pCur->iPage ){
  64022. releasePageNotNull(pCur->apPage[pCur->iPage]);
  64023. }
  64024. pCur->pPage = pCur->apPage[0];
  64025. goto skip_init;
  64026. }
  64027. }else if( pCur->pgnoRoot==0 ){
  64028. pCur->eState = CURSOR_INVALID;
  64029. return SQLITE_EMPTY;
  64030. }else{
  64031. assert( pCur->iPage==(-1) );
  64032. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  64033. if( pCur->eState==CURSOR_FAULT ){
  64034. assert( pCur->skipNext!=SQLITE_OK );
  64035. return pCur->skipNext;
  64036. }
  64037. sqlite3BtreeClearCursor(pCur);
  64038. }
  64039. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
  64040. 0, pCur->curPagerFlags);
  64041. if( rc!=SQLITE_OK ){
  64042. pCur->eState = CURSOR_INVALID;
  64043. return rc;
  64044. }
  64045. pCur->iPage = 0;
  64046. pCur->curIntKey = pCur->pPage->intKey;
  64047. }
  64048. pRoot = pCur->pPage;
  64049. assert( pRoot->pgno==pCur->pgnoRoot );
  64050. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  64051. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  64052. ** NULL, the caller expects a table b-tree. If this is not the case,
  64053. ** return an SQLITE_CORRUPT error.
  64054. **
  64055. ** Earlier versions of SQLite assumed that this test could not fail
  64056. ** if the root page was already loaded when this function was called (i.e.
  64057. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  64058. ** in such a way that page pRoot is linked into a second b-tree table
  64059. ** (or the freelist). */
  64060. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  64061. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  64062. return SQLITE_CORRUPT_PAGE(pCur->pPage);
  64063. }
  64064. skip_init:
  64065. pCur->ix = 0;
  64066. pCur->info.nSize = 0;
  64067. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  64068. pRoot = pCur->pPage;
  64069. if( pRoot->nCell>0 ){
  64070. pCur->eState = CURSOR_VALID;
  64071. }else if( !pRoot->leaf ){
  64072. Pgno subpage;
  64073. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  64074. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  64075. pCur->eState = CURSOR_VALID;
  64076. rc = moveToChild(pCur, subpage);
  64077. }else{
  64078. pCur->eState = CURSOR_INVALID;
  64079. rc = SQLITE_EMPTY;
  64080. }
  64081. return rc;
  64082. }
  64083. /*
  64084. ** Move the cursor down to the left-most leaf entry beneath the
  64085. ** entry to which it is currently pointing.
  64086. **
  64087. ** The left-most leaf is the one with the smallest key - the first
  64088. ** in ascending order.
  64089. */
  64090. static int moveToLeftmost(BtCursor *pCur){
  64091. Pgno pgno;
  64092. int rc = SQLITE_OK;
  64093. MemPage *pPage;
  64094. assert( cursorOwnsBtShared(pCur) );
  64095. assert( pCur->eState==CURSOR_VALID );
  64096. while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
  64097. assert( pCur->ix<pPage->nCell );
  64098. pgno = get4byte(findCell(pPage, pCur->ix));
  64099. rc = moveToChild(pCur, pgno);
  64100. }
  64101. return rc;
  64102. }
  64103. /*
  64104. ** Move the cursor down to the right-most leaf entry beneath the
  64105. ** page to which it is currently pointing. Notice the difference
  64106. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  64107. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  64108. ** finds the right-most entry beneath the *page*.
  64109. **
  64110. ** The right-most entry is the one with the largest key - the last
  64111. ** key in ascending order.
  64112. */
  64113. static int moveToRightmost(BtCursor *pCur){
  64114. Pgno pgno;
  64115. int rc = SQLITE_OK;
  64116. MemPage *pPage = 0;
  64117. assert( cursorOwnsBtShared(pCur) );
  64118. assert( pCur->eState==CURSOR_VALID );
  64119. while( !(pPage = pCur->pPage)->leaf ){
  64120. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  64121. pCur->ix = pPage->nCell;
  64122. rc = moveToChild(pCur, pgno);
  64123. if( rc ) return rc;
  64124. }
  64125. pCur->ix = pPage->nCell-1;
  64126. assert( pCur->info.nSize==0 );
  64127. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  64128. return SQLITE_OK;
  64129. }
  64130. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  64131. ** on success. Set *pRes to 0 if the cursor actually points to something
  64132. ** or set *pRes to 1 if the table is empty.
  64133. */
  64134. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  64135. int rc;
  64136. assert( cursorOwnsBtShared(pCur) );
  64137. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  64138. rc = moveToRoot(pCur);
  64139. if( rc==SQLITE_OK ){
  64140. assert( pCur->pPage->nCell>0 );
  64141. *pRes = 0;
  64142. rc = moveToLeftmost(pCur);
  64143. }else if( rc==SQLITE_EMPTY ){
  64144. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  64145. *pRes = 1;
  64146. rc = SQLITE_OK;
  64147. }
  64148. return rc;
  64149. }
  64150. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  64151. ** on success. Set *pRes to 0 if the cursor actually points to something
  64152. ** or set *pRes to 1 if the table is empty.
  64153. */
  64154. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  64155. int rc;
  64156. assert( cursorOwnsBtShared(pCur) );
  64157. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  64158. /* If the cursor already points to the last entry, this is a no-op. */
  64159. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  64160. #ifdef SQLITE_DEBUG
  64161. /* This block serves to assert() that the cursor really does point
  64162. ** to the last entry in the b-tree. */
  64163. int ii;
  64164. for(ii=0; ii<pCur->iPage; ii++){
  64165. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  64166. }
  64167. assert( pCur->ix==pCur->pPage->nCell-1 );
  64168. assert( pCur->pPage->leaf );
  64169. #endif
  64170. return SQLITE_OK;
  64171. }
  64172. rc = moveToRoot(pCur);
  64173. if( rc==SQLITE_OK ){
  64174. assert( pCur->eState==CURSOR_VALID );
  64175. *pRes = 0;
  64176. rc = moveToRightmost(pCur);
  64177. if( rc==SQLITE_OK ){
  64178. pCur->curFlags |= BTCF_AtLast;
  64179. }else{
  64180. pCur->curFlags &= ~BTCF_AtLast;
  64181. }
  64182. }else if( rc==SQLITE_EMPTY ){
  64183. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  64184. *pRes = 1;
  64185. rc = SQLITE_OK;
  64186. }
  64187. return rc;
  64188. }
  64189. /* Move the cursor so that it points to an entry near the key
  64190. ** specified by pIdxKey or intKey. Return a success code.
  64191. **
  64192. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  64193. ** must be NULL. For index tables, pIdxKey is used and intKey
  64194. ** is ignored.
  64195. **
  64196. ** If an exact match is not found, then the cursor is always
  64197. ** left pointing at a leaf page which would hold the entry if it
  64198. ** were present. The cursor might point to an entry that comes
  64199. ** before or after the key.
  64200. **
  64201. ** An integer is written into *pRes which is the result of
  64202. ** comparing the key with the entry to which the cursor is
  64203. ** pointing. The meaning of the integer written into
  64204. ** *pRes is as follows:
  64205. **
  64206. ** *pRes<0 The cursor is left pointing at an entry that
  64207. ** is smaller than intKey/pIdxKey or if the table is empty
  64208. ** and the cursor is therefore left point to nothing.
  64209. **
  64210. ** *pRes==0 The cursor is left pointing at an entry that
  64211. ** exactly matches intKey/pIdxKey.
  64212. **
  64213. ** *pRes>0 The cursor is left pointing at an entry that
  64214. ** is larger than intKey/pIdxKey.
  64215. **
  64216. ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
  64217. ** exists an entry in the table that exactly matches pIdxKey.
  64218. */
  64219. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  64220. BtCursor *pCur, /* The cursor to be moved */
  64221. UnpackedRecord *pIdxKey, /* Unpacked index key */
  64222. i64 intKey, /* The table key */
  64223. int biasRight, /* If true, bias the search to the high end */
  64224. int *pRes /* Write search results here */
  64225. ){
  64226. int rc;
  64227. RecordCompare xRecordCompare;
  64228. assert( cursorOwnsBtShared(pCur) );
  64229. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  64230. assert( pRes );
  64231. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  64232. assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
  64233. /* If the cursor is already positioned at the point we are trying
  64234. ** to move to, then just return without doing any work */
  64235. if( pIdxKey==0
  64236. && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  64237. ){
  64238. if( pCur->info.nKey==intKey ){
  64239. *pRes = 0;
  64240. return SQLITE_OK;
  64241. }
  64242. if( pCur->info.nKey<intKey ){
  64243. if( (pCur->curFlags & BTCF_AtLast)!=0 ){
  64244. *pRes = -1;
  64245. return SQLITE_OK;
  64246. }
  64247. /* If the requested key is one more than the previous key, then
  64248. ** try to get there using sqlite3BtreeNext() rather than a full
  64249. ** binary search. This is an optimization only. The correct answer
  64250. ** is still obtained without this case, only a little more slowely */
  64251. if( pCur->info.nKey+1==intKey ){
  64252. *pRes = 0;
  64253. rc = sqlite3BtreeNext(pCur, 0);
  64254. if( rc==SQLITE_OK ){
  64255. getCellInfo(pCur);
  64256. if( pCur->info.nKey==intKey ){
  64257. return SQLITE_OK;
  64258. }
  64259. }else if( rc==SQLITE_DONE ){
  64260. rc = SQLITE_OK;
  64261. }else{
  64262. return rc;
  64263. }
  64264. }
  64265. }
  64266. }
  64267. if( pIdxKey ){
  64268. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  64269. pIdxKey->errCode = 0;
  64270. assert( pIdxKey->default_rc==1
  64271. || pIdxKey->default_rc==0
  64272. || pIdxKey->default_rc==-1
  64273. );
  64274. }else{
  64275. xRecordCompare = 0; /* All keys are integers */
  64276. }
  64277. rc = moveToRoot(pCur);
  64278. if( rc ){
  64279. if( rc==SQLITE_EMPTY ){
  64280. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  64281. *pRes = -1;
  64282. return SQLITE_OK;
  64283. }
  64284. return rc;
  64285. }
  64286. assert( pCur->pPage );
  64287. assert( pCur->pPage->isInit );
  64288. assert( pCur->eState==CURSOR_VALID );
  64289. assert( pCur->pPage->nCell > 0 );
  64290. assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
  64291. assert( pCur->curIntKey || pIdxKey );
  64292. for(;;){
  64293. int lwr, upr, idx, c;
  64294. Pgno chldPg;
  64295. MemPage *pPage = pCur->pPage;
  64296. u8 *pCell; /* Pointer to current cell in pPage */
  64297. /* pPage->nCell must be greater than zero. If this is the root-page
  64298. ** the cursor would have been INVALID above and this for(;;) loop
  64299. ** not run. If this is not the root-page, then the moveToChild() routine
  64300. ** would have already detected db corruption. Similarly, pPage must
  64301. ** be the right kind (index or table) of b-tree page. Otherwise
  64302. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  64303. assert( pPage->nCell>0 );
  64304. assert( pPage->intKey==(pIdxKey==0) );
  64305. lwr = 0;
  64306. upr = pPage->nCell-1;
  64307. assert( biasRight==0 || biasRight==1 );
  64308. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  64309. pCur->ix = (u16)idx;
  64310. if( xRecordCompare==0 ){
  64311. for(;;){
  64312. i64 nCellKey;
  64313. pCell = findCellPastPtr(pPage, idx);
  64314. if( pPage->intKeyLeaf ){
  64315. while( 0x80 <= *(pCell++) ){
  64316. if( pCell>=pPage->aDataEnd ){
  64317. return SQLITE_CORRUPT_PAGE(pPage);
  64318. }
  64319. }
  64320. }
  64321. getVarint(pCell, (u64*)&nCellKey);
  64322. if( nCellKey<intKey ){
  64323. lwr = idx+1;
  64324. if( lwr>upr ){ c = -1; break; }
  64325. }else if( nCellKey>intKey ){
  64326. upr = idx-1;
  64327. if( lwr>upr ){ c = +1; break; }
  64328. }else{
  64329. assert( nCellKey==intKey );
  64330. pCur->ix = (u16)idx;
  64331. if( !pPage->leaf ){
  64332. lwr = idx;
  64333. goto moveto_next_layer;
  64334. }else{
  64335. pCur->curFlags |= BTCF_ValidNKey;
  64336. pCur->info.nKey = nCellKey;
  64337. pCur->info.nSize = 0;
  64338. *pRes = 0;
  64339. return SQLITE_OK;
  64340. }
  64341. }
  64342. assert( lwr+upr>=0 );
  64343. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  64344. }
  64345. }else{
  64346. for(;;){
  64347. int nCell; /* Size of the pCell cell in bytes */
  64348. pCell = findCellPastPtr(pPage, idx);
  64349. /* The maximum supported page-size is 65536 bytes. This means that
  64350. ** the maximum number of record bytes stored on an index B-Tree
  64351. ** page is less than 16384 bytes and may be stored as a 2-byte
  64352. ** varint. This information is used to attempt to avoid parsing
  64353. ** the entire cell by checking for the cases where the record is
  64354. ** stored entirely within the b-tree page by inspecting the first
  64355. ** 2 bytes of the cell.
  64356. */
  64357. nCell = pCell[0];
  64358. if( nCell<=pPage->max1bytePayload ){
  64359. /* This branch runs if the record-size field of the cell is a
  64360. ** single byte varint and the record fits entirely on the main
  64361. ** b-tree page. */
  64362. testcase( pCell+nCell+1==pPage->aDataEnd );
  64363. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  64364. }else if( !(pCell[1] & 0x80)
  64365. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  64366. ){
  64367. /* The record-size field is a 2 byte varint and the record
  64368. ** fits entirely on the main b-tree page. */
  64369. testcase( pCell+nCell+2==pPage->aDataEnd );
  64370. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  64371. }else{
  64372. /* The record flows over onto one or more overflow pages. In
  64373. ** this case the whole cell needs to be parsed, a buffer allocated
  64374. ** and accessPayload() used to retrieve the record into the
  64375. ** buffer before VdbeRecordCompare() can be called.
  64376. **
  64377. ** If the record is corrupt, the xRecordCompare routine may read
  64378. ** up to two varints past the end of the buffer. An extra 18
  64379. ** bytes of padding is allocated at the end of the buffer in
  64380. ** case this happens. */
  64381. void *pCellKey;
  64382. u8 * const pCellBody = pCell - pPage->childPtrSize;
  64383. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  64384. nCell = (int)pCur->info.nKey;
  64385. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  64386. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  64387. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  64388. testcase( nCell==2 ); /* Minimum legal index key size */
  64389. if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
  64390. rc = SQLITE_CORRUPT_PAGE(pPage);
  64391. goto moveto_finish;
  64392. }
  64393. pCellKey = sqlite3Malloc( nCell+18 );
  64394. if( pCellKey==0 ){
  64395. rc = SQLITE_NOMEM_BKPT;
  64396. goto moveto_finish;
  64397. }
  64398. pCur->ix = (u16)idx;
  64399. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  64400. pCur->curFlags &= ~BTCF_ValidOvfl;
  64401. if( rc ){
  64402. sqlite3_free(pCellKey);
  64403. goto moveto_finish;
  64404. }
  64405. c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
  64406. sqlite3_free(pCellKey);
  64407. }
  64408. assert(
  64409. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  64410. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  64411. );
  64412. if( c<0 ){
  64413. lwr = idx+1;
  64414. }else if( c>0 ){
  64415. upr = idx-1;
  64416. }else{
  64417. assert( c==0 );
  64418. *pRes = 0;
  64419. rc = SQLITE_OK;
  64420. pCur->ix = (u16)idx;
  64421. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
  64422. goto moveto_finish;
  64423. }
  64424. if( lwr>upr ) break;
  64425. assert( lwr+upr>=0 );
  64426. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  64427. }
  64428. }
  64429. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  64430. assert( pPage->isInit );
  64431. if( pPage->leaf ){
  64432. assert( pCur->ix<pCur->pPage->nCell );
  64433. pCur->ix = (u16)idx;
  64434. *pRes = c;
  64435. rc = SQLITE_OK;
  64436. goto moveto_finish;
  64437. }
  64438. moveto_next_layer:
  64439. if( lwr>=pPage->nCell ){
  64440. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  64441. }else{
  64442. chldPg = get4byte(findCell(pPage, lwr));
  64443. }
  64444. pCur->ix = (u16)lwr;
  64445. rc = moveToChild(pCur, chldPg);
  64446. if( rc ) break;
  64447. }
  64448. moveto_finish:
  64449. pCur->info.nSize = 0;
  64450. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  64451. return rc;
  64452. }
  64453. /*
  64454. ** Return TRUE if the cursor is not pointing at an entry of the table.
  64455. **
  64456. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  64457. ** past the last entry in the table or sqlite3BtreePrev() moves past
  64458. ** the first entry. TRUE is also returned if the table is empty.
  64459. */
  64460. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  64461. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  64462. ** have been deleted? This API will need to change to return an error code
  64463. ** as well as the boolean result value.
  64464. */
  64465. return (CURSOR_VALID!=pCur->eState);
  64466. }
  64467. /*
  64468. ** Return an estimate for the number of rows in the table that pCur is
  64469. ** pointing to. Return a negative number if no estimate is currently
  64470. ** available.
  64471. */
  64472. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
  64473. i64 n;
  64474. u8 i;
  64475. assert( cursorOwnsBtShared(pCur) );
  64476. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  64477. /* Currently this interface is only called by the OP_IfSmaller
  64478. ** opcode, and it that case the cursor will always be valid and
  64479. ** will always point to a leaf node. */
  64480. if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
  64481. if( NEVER(pCur->pPage->leaf==0) ) return -1;
  64482. n = pCur->pPage->nCell;
  64483. for(i=0; i<pCur->iPage; i++){
  64484. n *= pCur->apPage[i]->nCell;
  64485. }
  64486. return n;
  64487. }
  64488. /*
  64489. ** Advance the cursor to the next entry in the database.
  64490. ** Return value:
  64491. **
  64492. ** SQLITE_OK success
  64493. ** SQLITE_DONE cursor is already pointing at the last element
  64494. ** otherwise some kind of error occurred
  64495. **
  64496. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  64497. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  64498. ** to the next cell on the current page. The (slower) btreeNext() helper
  64499. ** routine is called when it is necessary to move to a different page or
  64500. ** to restore the cursor.
  64501. **
  64502. ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
  64503. ** cursor corresponds to an SQL index and this routine could have been
  64504. ** skipped if the SQL index had been a unique index. The F argument
  64505. ** is a hint to the implement. SQLite btree implementation does not use
  64506. ** this hint, but COMDB2 does.
  64507. */
  64508. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
  64509. int rc;
  64510. int idx;
  64511. MemPage *pPage;
  64512. assert( cursorOwnsBtShared(pCur) );
  64513. if( pCur->eState!=CURSOR_VALID ){
  64514. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  64515. rc = restoreCursorPosition(pCur);
  64516. if( rc!=SQLITE_OK ){
  64517. return rc;
  64518. }
  64519. if( CURSOR_INVALID==pCur->eState ){
  64520. return SQLITE_DONE;
  64521. }
  64522. if( pCur->eState==CURSOR_SKIPNEXT ){
  64523. pCur->eState = CURSOR_VALID;
  64524. if( pCur->skipNext>0 ) return SQLITE_OK;
  64525. }
  64526. }
  64527. pPage = pCur->pPage;
  64528. idx = ++pCur->ix;
  64529. if( !pPage->isInit ){
  64530. /* The only known way for this to happen is for there to be a
  64531. ** recursive SQL function that does a DELETE operation as part of a
  64532. ** SELECT which deletes content out from under an active cursor
  64533. ** in a corrupt database file where the table being DELETE-ed from
  64534. ** has pages in common with the table being queried. See TH3
  64535. ** module cov1/btree78.test testcase 220 (2018-06-08) for an
  64536. ** example. */
  64537. return SQLITE_CORRUPT_BKPT;
  64538. }
  64539. /* If the database file is corrupt, it is possible for the value of idx
  64540. ** to be invalid here. This can only occur if a second cursor modifies
  64541. ** the page while cursor pCur is holding a reference to it. Which can
  64542. ** only happen if the database is corrupt in such a way as to link the
  64543. ** page into more than one b-tree structure. */
  64544. testcase( idx>pPage->nCell );
  64545. if( idx>=pPage->nCell ){
  64546. if( !pPage->leaf ){
  64547. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  64548. if( rc ) return rc;
  64549. return moveToLeftmost(pCur);
  64550. }
  64551. do{
  64552. if( pCur->iPage==0 ){
  64553. pCur->eState = CURSOR_INVALID;
  64554. return SQLITE_DONE;
  64555. }
  64556. moveToParent(pCur);
  64557. pPage = pCur->pPage;
  64558. }while( pCur->ix>=pPage->nCell );
  64559. if( pPage->intKey ){
  64560. return sqlite3BtreeNext(pCur, 0);
  64561. }else{
  64562. return SQLITE_OK;
  64563. }
  64564. }
  64565. if( pPage->leaf ){
  64566. return SQLITE_OK;
  64567. }else{
  64568. return moveToLeftmost(pCur);
  64569. }
  64570. }
  64571. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
  64572. MemPage *pPage;
  64573. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  64574. assert( cursorOwnsBtShared(pCur) );
  64575. assert( flags==0 || flags==1 );
  64576. pCur->info.nSize = 0;
  64577. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  64578. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
  64579. pPage = pCur->pPage;
  64580. if( (++pCur->ix)>=pPage->nCell ){
  64581. pCur->ix--;
  64582. return btreeNext(pCur);
  64583. }
  64584. if( pPage->leaf ){
  64585. return SQLITE_OK;
  64586. }else{
  64587. return moveToLeftmost(pCur);
  64588. }
  64589. }
  64590. /*
  64591. ** Step the cursor to the back to the previous entry in the database.
  64592. ** Return values:
  64593. **
  64594. ** SQLITE_OK success
  64595. ** SQLITE_DONE the cursor is already on the first element of the table
  64596. ** otherwise some kind of error occurred
  64597. **
  64598. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  64599. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  64600. ** to the previous cell on the current page. The (slower) btreePrevious()
  64601. ** helper routine is called when it is necessary to move to a different page
  64602. ** or to restore the cursor.
  64603. **
  64604. ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
  64605. ** the cursor corresponds to an SQL index and this routine could have been
  64606. ** skipped if the SQL index had been a unique index. The F argument is a
  64607. ** hint to the implement. The native SQLite btree implementation does not
  64608. ** use this hint, but COMDB2 does.
  64609. */
  64610. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
  64611. int rc;
  64612. MemPage *pPage;
  64613. assert( cursorOwnsBtShared(pCur) );
  64614. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  64615. assert( pCur->info.nSize==0 );
  64616. if( pCur->eState!=CURSOR_VALID ){
  64617. rc = restoreCursorPosition(pCur);
  64618. if( rc!=SQLITE_OK ){
  64619. return rc;
  64620. }
  64621. if( CURSOR_INVALID==pCur->eState ){
  64622. return SQLITE_DONE;
  64623. }
  64624. if( CURSOR_SKIPNEXT==pCur->eState ){
  64625. pCur->eState = CURSOR_VALID;
  64626. if( pCur->skipNext<0 ) return SQLITE_OK;
  64627. }
  64628. }
  64629. pPage = pCur->pPage;
  64630. assert( pPage->isInit );
  64631. if( !pPage->leaf ){
  64632. int idx = pCur->ix;
  64633. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  64634. if( rc ) return rc;
  64635. rc = moveToRightmost(pCur);
  64636. }else{
  64637. while( pCur->ix==0 ){
  64638. if( pCur->iPage==0 ){
  64639. pCur->eState = CURSOR_INVALID;
  64640. return SQLITE_DONE;
  64641. }
  64642. moveToParent(pCur);
  64643. }
  64644. assert( pCur->info.nSize==0 );
  64645. assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
  64646. pCur->ix--;
  64647. pPage = pCur->pPage;
  64648. if( pPage->intKey && !pPage->leaf ){
  64649. rc = sqlite3BtreePrevious(pCur, 0);
  64650. }else{
  64651. rc = SQLITE_OK;
  64652. }
  64653. }
  64654. return rc;
  64655. }
  64656. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
  64657. assert( cursorOwnsBtShared(pCur) );
  64658. assert( flags==0 || flags==1 );
  64659. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  64660. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  64661. pCur->info.nSize = 0;
  64662. if( pCur->eState!=CURSOR_VALID
  64663. || pCur->ix==0
  64664. || pCur->pPage->leaf==0
  64665. ){
  64666. return btreePrevious(pCur);
  64667. }
  64668. pCur->ix--;
  64669. return SQLITE_OK;
  64670. }
  64671. /*
  64672. ** Allocate a new page from the database file.
  64673. **
  64674. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  64675. ** has already been called on the new page.) The new page has also
  64676. ** been referenced and the calling routine is responsible for calling
  64677. ** sqlite3PagerUnref() on the new page when it is done.
  64678. **
  64679. ** SQLITE_OK is returned on success. Any other return value indicates
  64680. ** an error. *ppPage is set to NULL in the event of an error.
  64681. **
  64682. ** If the "nearby" parameter is not 0, then an effort is made to
  64683. ** locate a page close to the page number "nearby". This can be used in an
  64684. ** attempt to keep related pages close to each other in the database file,
  64685. ** which in turn can make database access faster.
  64686. **
  64687. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  64688. ** anywhere on the free-list, then it is guaranteed to be returned. If
  64689. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  64690. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  64691. ** are no restrictions on which page is returned.
  64692. */
  64693. static int allocateBtreePage(
  64694. BtShared *pBt, /* The btree */
  64695. MemPage **ppPage, /* Store pointer to the allocated page here */
  64696. Pgno *pPgno, /* Store the page number here */
  64697. Pgno nearby, /* Search for a page near this one */
  64698. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  64699. ){
  64700. MemPage *pPage1;
  64701. int rc;
  64702. u32 n; /* Number of pages on the freelist */
  64703. u32 k; /* Number of leaves on the trunk of the freelist */
  64704. MemPage *pTrunk = 0;
  64705. MemPage *pPrevTrunk = 0;
  64706. Pgno mxPage; /* Total size of the database file */
  64707. assert( sqlite3_mutex_held(pBt->mutex) );
  64708. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  64709. pPage1 = pBt->pPage1;
  64710. mxPage = btreePagecount(pBt);
  64711. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  64712. ** stores stores the total number of pages on the freelist. */
  64713. n = get4byte(&pPage1->aData[36]);
  64714. testcase( n==mxPage-1 );
  64715. if( n>=mxPage ){
  64716. return SQLITE_CORRUPT_BKPT;
  64717. }
  64718. if( n>0 ){
  64719. /* There are pages on the freelist. Reuse one of those pages. */
  64720. Pgno iTrunk;
  64721. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  64722. u32 nSearch = 0; /* Count of the number of search attempts */
  64723. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  64724. ** shows that the page 'nearby' is somewhere on the free-list, then
  64725. ** the entire-list will be searched for that page.
  64726. */
  64727. #ifndef SQLITE_OMIT_AUTOVACUUM
  64728. if( eMode==BTALLOC_EXACT ){
  64729. if( nearby<=mxPage ){
  64730. u8 eType;
  64731. assert( nearby>0 );
  64732. assert( pBt->autoVacuum );
  64733. rc = ptrmapGet(pBt, nearby, &eType, 0);
  64734. if( rc ) return rc;
  64735. if( eType==PTRMAP_FREEPAGE ){
  64736. searchList = 1;
  64737. }
  64738. }
  64739. }else if( eMode==BTALLOC_LE ){
  64740. searchList = 1;
  64741. }
  64742. #endif
  64743. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  64744. ** first free-list trunk page. iPrevTrunk is initially 1.
  64745. */
  64746. rc = sqlite3PagerWrite(pPage1->pDbPage);
  64747. if( rc ) return rc;
  64748. put4byte(&pPage1->aData[36], n-1);
  64749. /* The code within this loop is run only once if the 'searchList' variable
  64750. ** is not true. Otherwise, it runs once for each trunk-page on the
  64751. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  64752. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  64753. */
  64754. do {
  64755. pPrevTrunk = pTrunk;
  64756. if( pPrevTrunk ){
  64757. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  64758. ** is the page number of the next freelist trunk page in the list or
  64759. ** zero if this is the last freelist trunk page. */
  64760. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  64761. }else{
  64762. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  64763. ** stores the page number of the first page of the freelist, or zero if
  64764. ** the freelist is empty. */
  64765. iTrunk = get4byte(&pPage1->aData[32]);
  64766. }
  64767. testcase( iTrunk==mxPage );
  64768. if( iTrunk>mxPage || nSearch++ > n ){
  64769. rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
  64770. }else{
  64771. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  64772. }
  64773. if( rc ){
  64774. pTrunk = 0;
  64775. goto end_allocate_page;
  64776. }
  64777. assert( pTrunk!=0 );
  64778. assert( pTrunk->aData!=0 );
  64779. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  64780. ** is the number of leaf page pointers to follow. */
  64781. k = get4byte(&pTrunk->aData[4]);
  64782. if( k==0 && !searchList ){
  64783. /* The trunk has no leaves and the list is not being searched.
  64784. ** So extract the trunk page itself and use it as the newly
  64785. ** allocated page */
  64786. assert( pPrevTrunk==0 );
  64787. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  64788. if( rc ){
  64789. goto end_allocate_page;
  64790. }
  64791. *pPgno = iTrunk;
  64792. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  64793. *ppPage = pTrunk;
  64794. pTrunk = 0;
  64795. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  64796. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  64797. /* Value of k is out of range. Database corruption */
  64798. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  64799. goto end_allocate_page;
  64800. #ifndef SQLITE_OMIT_AUTOVACUUM
  64801. }else if( searchList
  64802. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  64803. ){
  64804. /* The list is being searched and this trunk page is the page
  64805. ** to allocate, regardless of whether it has leaves.
  64806. */
  64807. *pPgno = iTrunk;
  64808. *ppPage = pTrunk;
  64809. searchList = 0;
  64810. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  64811. if( rc ){
  64812. goto end_allocate_page;
  64813. }
  64814. if( k==0 ){
  64815. if( !pPrevTrunk ){
  64816. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  64817. }else{
  64818. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  64819. if( rc!=SQLITE_OK ){
  64820. goto end_allocate_page;
  64821. }
  64822. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  64823. }
  64824. }else{
  64825. /* The trunk page is required by the caller but it contains
  64826. ** pointers to free-list leaves. The first leaf becomes a trunk
  64827. ** page in this case.
  64828. */
  64829. MemPage *pNewTrunk;
  64830. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  64831. if( iNewTrunk>mxPage ){
  64832. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  64833. goto end_allocate_page;
  64834. }
  64835. testcase( iNewTrunk==mxPage );
  64836. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  64837. if( rc!=SQLITE_OK ){
  64838. goto end_allocate_page;
  64839. }
  64840. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  64841. if( rc!=SQLITE_OK ){
  64842. releasePage(pNewTrunk);
  64843. goto end_allocate_page;
  64844. }
  64845. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  64846. put4byte(&pNewTrunk->aData[4], k-1);
  64847. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  64848. releasePage(pNewTrunk);
  64849. if( !pPrevTrunk ){
  64850. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  64851. put4byte(&pPage1->aData[32], iNewTrunk);
  64852. }else{
  64853. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  64854. if( rc ){
  64855. goto end_allocate_page;
  64856. }
  64857. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  64858. }
  64859. }
  64860. pTrunk = 0;
  64861. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  64862. #endif
  64863. }else if( k>0 ){
  64864. /* Extract a leaf from the trunk */
  64865. u32 closest;
  64866. Pgno iPage;
  64867. unsigned char *aData = pTrunk->aData;
  64868. if( nearby>0 ){
  64869. u32 i;
  64870. closest = 0;
  64871. if( eMode==BTALLOC_LE ){
  64872. for(i=0; i<k; i++){
  64873. iPage = get4byte(&aData[8+i*4]);
  64874. if( iPage<=nearby ){
  64875. closest = i;
  64876. break;
  64877. }
  64878. }
  64879. }else{
  64880. int dist;
  64881. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  64882. for(i=1; i<k; i++){
  64883. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  64884. if( d2<dist ){
  64885. closest = i;
  64886. dist = d2;
  64887. }
  64888. }
  64889. }
  64890. }else{
  64891. closest = 0;
  64892. }
  64893. iPage = get4byte(&aData[8+closest*4]);
  64894. testcase( iPage==mxPage );
  64895. if( iPage>mxPage ){
  64896. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  64897. goto end_allocate_page;
  64898. }
  64899. testcase( iPage==mxPage );
  64900. if( !searchList
  64901. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  64902. ){
  64903. int noContent;
  64904. *pPgno = iPage;
  64905. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  64906. ": %d more free pages\n",
  64907. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  64908. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  64909. if( rc ) goto end_allocate_page;
  64910. if( closest<k-1 ){
  64911. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  64912. }
  64913. put4byte(&aData[4], k-1);
  64914. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  64915. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  64916. if( rc==SQLITE_OK ){
  64917. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  64918. if( rc!=SQLITE_OK ){
  64919. releasePage(*ppPage);
  64920. *ppPage = 0;
  64921. }
  64922. }
  64923. searchList = 0;
  64924. }
  64925. }
  64926. releasePage(pPrevTrunk);
  64927. pPrevTrunk = 0;
  64928. }while( searchList );
  64929. }else{
  64930. /* There are no pages on the freelist, so append a new page to the
  64931. ** database image.
  64932. **
  64933. ** Normally, new pages allocated by this block can be requested from the
  64934. ** pager layer with the 'no-content' flag set. This prevents the pager
  64935. ** from trying to read the pages content from disk. However, if the
  64936. ** current transaction has already run one or more incremental-vacuum
  64937. ** steps, then the page we are about to allocate may contain content
  64938. ** that is required in the event of a rollback. In this case, do
  64939. ** not set the no-content flag. This causes the pager to load and journal
  64940. ** the current page content before overwriting it.
  64941. **
  64942. ** Note that the pager will not actually attempt to load or journal
  64943. ** content for any page that really does lie past the end of the database
  64944. ** file on disk. So the effects of disabling the no-content optimization
  64945. ** here are confined to those pages that lie between the end of the
  64946. ** database image and the end of the database file.
  64947. */
  64948. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  64949. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  64950. if( rc ) return rc;
  64951. pBt->nPage++;
  64952. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  64953. #ifndef SQLITE_OMIT_AUTOVACUUM
  64954. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  64955. /* If *pPgno refers to a pointer-map page, allocate two new pages
  64956. ** at the end of the file instead of one. The first allocated page
  64957. ** becomes a new pointer-map page, the second is used by the caller.
  64958. */
  64959. MemPage *pPg = 0;
  64960. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  64961. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  64962. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  64963. if( rc==SQLITE_OK ){
  64964. rc = sqlite3PagerWrite(pPg->pDbPage);
  64965. releasePage(pPg);
  64966. }
  64967. if( rc ) return rc;
  64968. pBt->nPage++;
  64969. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  64970. }
  64971. #endif
  64972. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  64973. *pPgno = pBt->nPage;
  64974. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  64975. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  64976. if( rc ) return rc;
  64977. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  64978. if( rc!=SQLITE_OK ){
  64979. releasePage(*ppPage);
  64980. *ppPage = 0;
  64981. }
  64982. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  64983. }
  64984. assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
  64985. end_allocate_page:
  64986. releasePage(pTrunk);
  64987. releasePage(pPrevTrunk);
  64988. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  64989. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  64990. return rc;
  64991. }
  64992. /*
  64993. ** This function is used to add page iPage to the database file free-list.
  64994. ** It is assumed that the page is not already a part of the free-list.
  64995. **
  64996. ** The value passed as the second argument to this function is optional.
  64997. ** If the caller happens to have a pointer to the MemPage object
  64998. ** corresponding to page iPage handy, it may pass it as the second value.
  64999. ** Otherwise, it may pass NULL.
  65000. **
  65001. ** If a pointer to a MemPage object is passed as the second argument,
  65002. ** its reference count is not altered by this function.
  65003. */
  65004. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  65005. MemPage *pTrunk = 0; /* Free-list trunk page */
  65006. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  65007. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  65008. MemPage *pPage; /* Page being freed. May be NULL. */
  65009. int rc; /* Return Code */
  65010. u32 nFree; /* Initial number of pages on free-list */
  65011. assert( sqlite3_mutex_held(pBt->mutex) );
  65012. assert( CORRUPT_DB || iPage>1 );
  65013. assert( !pMemPage || pMemPage->pgno==iPage );
  65014. if( iPage<2 || iPage>pBt->nPage ){
  65015. return SQLITE_CORRUPT_BKPT;
  65016. }
  65017. if( pMemPage ){
  65018. pPage = pMemPage;
  65019. sqlite3PagerRef(pPage->pDbPage);
  65020. }else{
  65021. pPage = btreePageLookup(pBt, iPage);
  65022. }
  65023. /* Increment the free page count on pPage1 */
  65024. rc = sqlite3PagerWrite(pPage1->pDbPage);
  65025. if( rc ) goto freepage_out;
  65026. nFree = get4byte(&pPage1->aData[36]);
  65027. put4byte(&pPage1->aData[36], nFree+1);
  65028. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  65029. /* If the secure_delete option is enabled, then
  65030. ** always fully overwrite deleted information with zeros.
  65031. */
  65032. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  65033. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  65034. ){
  65035. goto freepage_out;
  65036. }
  65037. memset(pPage->aData, 0, pPage->pBt->pageSize);
  65038. }
  65039. /* If the database supports auto-vacuum, write an entry in the pointer-map
  65040. ** to indicate that the page is free.
  65041. */
  65042. if( ISAUTOVACUUM ){
  65043. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  65044. if( rc ) goto freepage_out;
  65045. }
  65046. /* Now manipulate the actual database free-list structure. There are two
  65047. ** possibilities. If the free-list is currently empty, or if the first
  65048. ** trunk page in the free-list is full, then this page will become a
  65049. ** new free-list trunk page. Otherwise, it will become a leaf of the
  65050. ** first trunk page in the current free-list. This block tests if it
  65051. ** is possible to add the page as a new free-list leaf.
  65052. */
  65053. if( nFree!=0 ){
  65054. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  65055. iTrunk = get4byte(&pPage1->aData[32]);
  65056. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  65057. if( rc!=SQLITE_OK ){
  65058. goto freepage_out;
  65059. }
  65060. nLeaf = get4byte(&pTrunk->aData[4]);
  65061. assert( pBt->usableSize>32 );
  65062. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  65063. rc = SQLITE_CORRUPT_BKPT;
  65064. goto freepage_out;
  65065. }
  65066. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  65067. /* In this case there is room on the trunk page to insert the page
  65068. ** being freed as a new leaf.
  65069. **
  65070. ** Note that the trunk page is not really full until it contains
  65071. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  65072. ** coded. But due to a coding error in versions of SQLite prior to
  65073. ** 3.6.0, databases with freelist trunk pages holding more than
  65074. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  65075. ** to maintain backwards compatibility with older versions of SQLite,
  65076. ** we will continue to restrict the number of entries to usableSize/4 - 8
  65077. ** for now. At some point in the future (once everyone has upgraded
  65078. ** to 3.6.0 or later) we should consider fixing the conditional above
  65079. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  65080. **
  65081. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  65082. ** avoid using the last six entries in the freelist trunk page array in
  65083. ** order that database files created by newer versions of SQLite can be
  65084. ** read by older versions of SQLite.
  65085. */
  65086. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  65087. if( rc==SQLITE_OK ){
  65088. put4byte(&pTrunk->aData[4], nLeaf+1);
  65089. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  65090. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  65091. sqlite3PagerDontWrite(pPage->pDbPage);
  65092. }
  65093. rc = btreeSetHasContent(pBt, iPage);
  65094. }
  65095. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  65096. goto freepage_out;
  65097. }
  65098. }
  65099. /* If control flows to this point, then it was not possible to add the
  65100. ** the page being freed as a leaf page of the first trunk in the free-list.
  65101. ** Possibly because the free-list is empty, or possibly because the
  65102. ** first trunk in the free-list is full. Either way, the page being freed
  65103. ** will become the new first trunk page in the free-list.
  65104. */
  65105. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  65106. goto freepage_out;
  65107. }
  65108. rc = sqlite3PagerWrite(pPage->pDbPage);
  65109. if( rc!=SQLITE_OK ){
  65110. goto freepage_out;
  65111. }
  65112. put4byte(pPage->aData, iTrunk);
  65113. put4byte(&pPage->aData[4], 0);
  65114. put4byte(&pPage1->aData[32], iPage);
  65115. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  65116. freepage_out:
  65117. if( pPage ){
  65118. pPage->isInit = 0;
  65119. }
  65120. releasePage(pPage);
  65121. releasePage(pTrunk);
  65122. return rc;
  65123. }
  65124. static void freePage(MemPage *pPage, int *pRC){
  65125. if( (*pRC)==SQLITE_OK ){
  65126. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  65127. }
  65128. }
  65129. /*
  65130. ** Free any overflow pages associated with the given Cell. Store
  65131. ** size information about the cell in pInfo.
  65132. */
  65133. static int clearCell(
  65134. MemPage *pPage, /* The page that contains the Cell */
  65135. unsigned char *pCell, /* First byte of the Cell */
  65136. CellInfo *pInfo /* Size information about the cell */
  65137. ){
  65138. BtShared *pBt;
  65139. Pgno ovflPgno;
  65140. int rc;
  65141. int nOvfl;
  65142. u32 ovflPageSize;
  65143. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65144. pPage->xParseCell(pPage, pCell, pInfo);
  65145. if( pInfo->nLocal==pInfo->nPayload ){
  65146. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  65147. }
  65148. testcase( pCell + pInfo->nSize == pPage->aDataEnd );
  65149. testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
  65150. if( pCell + pInfo->nSize > pPage->aDataEnd ){
  65151. /* Cell extends past end of page */
  65152. return SQLITE_CORRUPT_PAGE(pPage);
  65153. }
  65154. ovflPgno = get4byte(pCell + pInfo->nSize - 4);
  65155. pBt = pPage->pBt;
  65156. assert( pBt->usableSize > 4 );
  65157. ovflPageSize = pBt->usableSize - 4;
  65158. nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
  65159. assert( nOvfl>0 ||
  65160. (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
  65161. );
  65162. while( nOvfl-- ){
  65163. Pgno iNext = 0;
  65164. MemPage *pOvfl = 0;
  65165. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  65166. /* 0 is not a legal page number and page 1 cannot be an
  65167. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  65168. ** file the database must be corrupt. */
  65169. return SQLITE_CORRUPT_BKPT;
  65170. }
  65171. if( nOvfl ){
  65172. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  65173. if( rc ) return rc;
  65174. }
  65175. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  65176. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  65177. ){
  65178. /* There is no reason any cursor should have an outstanding reference
  65179. ** to an overflow page belonging to a cell that is being deleted/updated.
  65180. ** So if there exists more than one reference to this page, then it
  65181. ** must not really be an overflow page and the database must be corrupt.
  65182. ** It is helpful to detect this before calling freePage2(), as
  65183. ** freePage2() may zero the page contents if secure-delete mode is
  65184. ** enabled. If this 'overflow' page happens to be a page that the
  65185. ** caller is iterating through or using in some other way, this
  65186. ** can be problematic.
  65187. */
  65188. rc = SQLITE_CORRUPT_BKPT;
  65189. }else{
  65190. rc = freePage2(pBt, pOvfl, ovflPgno);
  65191. }
  65192. if( pOvfl ){
  65193. sqlite3PagerUnref(pOvfl->pDbPage);
  65194. }
  65195. if( rc ) return rc;
  65196. ovflPgno = iNext;
  65197. }
  65198. return SQLITE_OK;
  65199. }
  65200. /*
  65201. ** Create the byte sequence used to represent a cell on page pPage
  65202. ** and write that byte sequence into pCell[]. Overflow pages are
  65203. ** allocated and filled in as necessary. The calling procedure
  65204. ** is responsible for making sure sufficient space has been allocated
  65205. ** for pCell[].
  65206. **
  65207. ** Note that pCell does not necessary need to point to the pPage->aData
  65208. ** area. pCell might point to some temporary storage. The cell will
  65209. ** be constructed in this temporary area then copied into pPage->aData
  65210. ** later.
  65211. */
  65212. static int fillInCell(
  65213. MemPage *pPage, /* The page that contains the cell */
  65214. unsigned char *pCell, /* Complete text of the cell */
  65215. const BtreePayload *pX, /* Payload with which to construct the cell */
  65216. int *pnSize /* Write cell size here */
  65217. ){
  65218. int nPayload;
  65219. const u8 *pSrc;
  65220. int nSrc, n, rc, mn;
  65221. int spaceLeft;
  65222. MemPage *pToRelease;
  65223. unsigned char *pPrior;
  65224. unsigned char *pPayload;
  65225. BtShared *pBt;
  65226. Pgno pgnoOvfl;
  65227. int nHeader;
  65228. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65229. /* pPage is not necessarily writeable since pCell might be auxiliary
  65230. ** buffer space that is separate from the pPage buffer area */
  65231. assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
  65232. || sqlite3PagerIswriteable(pPage->pDbPage) );
  65233. /* Fill in the header. */
  65234. nHeader = pPage->childPtrSize;
  65235. if( pPage->intKey ){
  65236. nPayload = pX->nData + pX->nZero;
  65237. pSrc = pX->pData;
  65238. nSrc = pX->nData;
  65239. assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
  65240. nHeader += putVarint32(&pCell[nHeader], nPayload);
  65241. nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
  65242. }else{
  65243. assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
  65244. nSrc = nPayload = (int)pX->nKey;
  65245. pSrc = pX->pKey;
  65246. nHeader += putVarint32(&pCell[nHeader], nPayload);
  65247. }
  65248. /* Fill in the payload */
  65249. pPayload = &pCell[nHeader];
  65250. if( nPayload<=pPage->maxLocal ){
  65251. /* This is the common case where everything fits on the btree page
  65252. ** and no overflow pages are required. */
  65253. n = nHeader + nPayload;
  65254. testcase( n==3 );
  65255. testcase( n==4 );
  65256. if( n<4 ) n = 4;
  65257. *pnSize = n;
  65258. assert( nSrc<=nPayload );
  65259. testcase( nSrc<nPayload );
  65260. memcpy(pPayload, pSrc, nSrc);
  65261. memset(pPayload+nSrc, 0, nPayload-nSrc);
  65262. return SQLITE_OK;
  65263. }
  65264. /* If we reach this point, it means that some of the content will need
  65265. ** to spill onto overflow pages.
  65266. */
  65267. mn = pPage->minLocal;
  65268. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  65269. testcase( n==pPage->maxLocal );
  65270. testcase( n==pPage->maxLocal+1 );
  65271. if( n > pPage->maxLocal ) n = mn;
  65272. spaceLeft = n;
  65273. *pnSize = n + nHeader + 4;
  65274. pPrior = &pCell[nHeader+n];
  65275. pToRelease = 0;
  65276. pgnoOvfl = 0;
  65277. pBt = pPage->pBt;
  65278. /* At this point variables should be set as follows:
  65279. **
  65280. ** nPayload Total payload size in bytes
  65281. ** pPayload Begin writing payload here
  65282. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  65283. ** that means content must spill into overflow pages.
  65284. ** *pnSize Size of the local cell (not counting overflow pages)
  65285. ** pPrior Where to write the pgno of the first overflow page
  65286. **
  65287. ** Use a call to btreeParseCellPtr() to verify that the values above
  65288. ** were computed correctly.
  65289. */
  65290. #ifdef SQLITE_DEBUG
  65291. {
  65292. CellInfo info;
  65293. pPage->xParseCell(pPage, pCell, &info);
  65294. assert( nHeader==(int)(info.pPayload - pCell) );
  65295. assert( info.nKey==pX->nKey );
  65296. assert( *pnSize == info.nSize );
  65297. assert( spaceLeft == info.nLocal );
  65298. }
  65299. #endif
  65300. /* Write the payload into the local Cell and any extra into overflow pages */
  65301. while( 1 ){
  65302. n = nPayload;
  65303. if( n>spaceLeft ) n = spaceLeft;
  65304. /* If pToRelease is not zero than pPayload points into the data area
  65305. ** of pToRelease. Make sure pToRelease is still writeable. */
  65306. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  65307. /* If pPayload is part of the data area of pPage, then make sure pPage
  65308. ** is still writeable */
  65309. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  65310. || sqlite3PagerIswriteable(pPage->pDbPage) );
  65311. if( nSrc>=n ){
  65312. memcpy(pPayload, pSrc, n);
  65313. }else if( nSrc>0 ){
  65314. n = nSrc;
  65315. memcpy(pPayload, pSrc, n);
  65316. }else{
  65317. memset(pPayload, 0, n);
  65318. }
  65319. nPayload -= n;
  65320. if( nPayload<=0 ) break;
  65321. pPayload += n;
  65322. pSrc += n;
  65323. nSrc -= n;
  65324. spaceLeft -= n;
  65325. if( spaceLeft==0 ){
  65326. MemPage *pOvfl = 0;
  65327. #ifndef SQLITE_OMIT_AUTOVACUUM
  65328. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  65329. if( pBt->autoVacuum ){
  65330. do{
  65331. pgnoOvfl++;
  65332. } while(
  65333. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  65334. );
  65335. }
  65336. #endif
  65337. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  65338. #ifndef SQLITE_OMIT_AUTOVACUUM
  65339. /* If the database supports auto-vacuum, and the second or subsequent
  65340. ** overflow page is being allocated, add an entry to the pointer-map
  65341. ** for that page now.
  65342. **
  65343. ** If this is the first overflow page, then write a partial entry
  65344. ** to the pointer-map. If we write nothing to this pointer-map slot,
  65345. ** then the optimistic overflow chain processing in clearCell()
  65346. ** may misinterpret the uninitialized values and delete the
  65347. ** wrong pages from the database.
  65348. */
  65349. if( pBt->autoVacuum && rc==SQLITE_OK ){
  65350. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  65351. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  65352. if( rc ){
  65353. releasePage(pOvfl);
  65354. }
  65355. }
  65356. #endif
  65357. if( rc ){
  65358. releasePage(pToRelease);
  65359. return rc;
  65360. }
  65361. /* If pToRelease is not zero than pPrior points into the data area
  65362. ** of pToRelease. Make sure pToRelease is still writeable. */
  65363. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  65364. /* If pPrior is part of the data area of pPage, then make sure pPage
  65365. ** is still writeable */
  65366. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  65367. || sqlite3PagerIswriteable(pPage->pDbPage) );
  65368. put4byte(pPrior, pgnoOvfl);
  65369. releasePage(pToRelease);
  65370. pToRelease = pOvfl;
  65371. pPrior = pOvfl->aData;
  65372. put4byte(pPrior, 0);
  65373. pPayload = &pOvfl->aData[4];
  65374. spaceLeft = pBt->usableSize - 4;
  65375. }
  65376. }
  65377. releasePage(pToRelease);
  65378. return SQLITE_OK;
  65379. }
  65380. /*
  65381. ** Remove the i-th cell from pPage. This routine effects pPage only.
  65382. ** The cell content is not freed or deallocated. It is assumed that
  65383. ** the cell content has been copied someplace else. This routine just
  65384. ** removes the reference to the cell from pPage.
  65385. **
  65386. ** "sz" must be the number of bytes in the cell.
  65387. */
  65388. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  65389. u32 pc; /* Offset to cell content of cell being deleted */
  65390. u8 *data; /* pPage->aData */
  65391. u8 *ptr; /* Used to move bytes around within data[] */
  65392. int rc; /* The return code */
  65393. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  65394. if( *pRC ) return;
  65395. assert( idx>=0 && idx<pPage->nCell );
  65396. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  65397. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  65398. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65399. assert( pPage->nFree>=0 );
  65400. data = pPage->aData;
  65401. ptr = &pPage->aCellIdx[2*idx];
  65402. pc = get2byte(ptr);
  65403. hdr = pPage->hdrOffset;
  65404. testcase( pc==get2byte(&data[hdr+5]) );
  65405. testcase( pc+sz==pPage->pBt->usableSize );
  65406. if( pc+sz > pPage->pBt->usableSize ){
  65407. *pRC = SQLITE_CORRUPT_BKPT;
  65408. return;
  65409. }
  65410. rc = freeSpace(pPage, pc, sz);
  65411. if( rc ){
  65412. *pRC = rc;
  65413. return;
  65414. }
  65415. pPage->nCell--;
  65416. if( pPage->nCell==0 ){
  65417. memset(&data[hdr+1], 0, 4);
  65418. data[hdr+7] = 0;
  65419. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  65420. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  65421. - pPage->childPtrSize - 8;
  65422. }else{
  65423. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  65424. put2byte(&data[hdr+3], pPage->nCell);
  65425. pPage->nFree += 2;
  65426. }
  65427. }
  65428. /*
  65429. ** Insert a new cell on pPage at cell index "i". pCell points to the
  65430. ** content of the cell.
  65431. **
  65432. ** If the cell content will fit on the page, then put it there. If it
  65433. ** will not fit, then make a copy of the cell content into pTemp if
  65434. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  65435. ** in pPage->apOvfl[] and make it point to the cell content (either
  65436. ** in pTemp or the original pCell) and also record its index.
  65437. ** Allocating a new entry in pPage->aCell[] implies that
  65438. ** pPage->nOverflow is incremented.
  65439. **
  65440. ** *pRC must be SQLITE_OK when this routine is called.
  65441. */
  65442. static void insertCell(
  65443. MemPage *pPage, /* Page into which we are copying */
  65444. int i, /* New cell becomes the i-th cell of the page */
  65445. u8 *pCell, /* Content of the new cell */
  65446. int sz, /* Bytes of content in pCell */
  65447. u8 *pTemp, /* Temp storage space for pCell, if needed */
  65448. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  65449. int *pRC /* Read and write return code from here */
  65450. ){
  65451. int idx = 0; /* Where to write new cell content in data[] */
  65452. int j; /* Loop counter */
  65453. u8 *data; /* The content of the whole page */
  65454. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  65455. assert( *pRC==SQLITE_OK );
  65456. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  65457. assert( MX_CELL(pPage->pBt)<=10921 );
  65458. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  65459. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  65460. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  65461. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65462. /* The cell should normally be sized correctly. However, when moving a
  65463. ** malformed cell from a leaf page to an interior page, if the cell size
  65464. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  65465. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  65466. ** the term after the || in the following assert(). */
  65467. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  65468. assert( pPage->nFree>=0 );
  65469. if( pPage->nOverflow || sz+2>pPage->nFree ){
  65470. if( pTemp ){
  65471. memcpy(pTemp, pCell, sz);
  65472. pCell = pTemp;
  65473. }
  65474. if( iChild ){
  65475. put4byte(pCell, iChild);
  65476. }
  65477. j = pPage->nOverflow++;
  65478. /* Comparison against ArraySize-1 since we hold back one extra slot
  65479. ** as a contingency. In other words, never need more than 3 overflow
  65480. ** slots but 4 are allocated, just to be safe. */
  65481. assert( j < ArraySize(pPage->apOvfl)-1 );
  65482. pPage->apOvfl[j] = pCell;
  65483. pPage->aiOvfl[j] = (u16)i;
  65484. /* When multiple overflows occur, they are always sequential and in
  65485. ** sorted order. This invariants arise because multiple overflows can
  65486. ** only occur when inserting divider cells into the parent page during
  65487. ** balancing, and the dividers are adjacent and sorted.
  65488. */
  65489. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  65490. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  65491. }else{
  65492. int rc = sqlite3PagerWrite(pPage->pDbPage);
  65493. if( rc!=SQLITE_OK ){
  65494. *pRC = rc;
  65495. return;
  65496. }
  65497. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  65498. data = pPage->aData;
  65499. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  65500. rc = allocateSpace(pPage, sz, &idx);
  65501. if( rc ){ *pRC = rc; return; }
  65502. /* The allocateSpace() routine guarantees the following properties
  65503. ** if it returns successfully */
  65504. assert( idx >= 0 );
  65505. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  65506. assert( idx+sz <= (int)pPage->pBt->usableSize );
  65507. pPage->nFree -= (u16)(2 + sz);
  65508. if( iChild ){
  65509. /* In a corrupt database where an entry in the cell index section of
  65510. ** a btree page has a value of 3 or less, the pCell value might point
  65511. ** as many as 4 bytes in front of the start of the aData buffer for
  65512. ** the source page. Make sure this does not cause problems by not
  65513. ** reading the first 4 bytes */
  65514. memcpy(&data[idx+4], pCell+4, sz-4);
  65515. put4byte(&data[idx], iChild);
  65516. }else{
  65517. memcpy(&data[idx], pCell, sz);
  65518. }
  65519. pIns = pPage->aCellIdx + i*2;
  65520. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  65521. put2byte(pIns, idx);
  65522. pPage->nCell++;
  65523. /* increment the cell count */
  65524. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  65525. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
  65526. #ifndef SQLITE_OMIT_AUTOVACUUM
  65527. if( pPage->pBt->autoVacuum ){
  65528. /* The cell may contain a pointer to an overflow page. If so, write
  65529. ** the entry for the overflow page into the pointer map.
  65530. */
  65531. ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
  65532. }
  65533. #endif
  65534. }
  65535. }
  65536. /*
  65537. ** The following parameters determine how many adjacent pages get involved
  65538. ** in a balancing operation. NN is the number of neighbors on either side
  65539. ** of the page that participate in the balancing operation. NB is the
  65540. ** total number of pages that participate, including the target page and
  65541. ** NN neighbors on either side.
  65542. **
  65543. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  65544. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  65545. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  65546. ** The value of NN appears to give the best results overall.
  65547. **
  65548. ** (Later:) The description above makes it seem as if these values are
  65549. ** tunable - as if you could change them and recompile and it would all work.
  65550. ** But that is unlikely. NB has been 3 since the inception of SQLite and
  65551. ** we have never tested any other value.
  65552. */
  65553. #define NN 1 /* Number of neighbors on either side of pPage */
  65554. #define NB 3 /* (NN*2+1): Total pages involved in the balance */
  65555. /*
  65556. ** A CellArray object contains a cache of pointers and sizes for a
  65557. ** consecutive sequence of cells that might be held on multiple pages.
  65558. **
  65559. ** The cells in this array are the divider cell or cells from the pParent
  65560. ** page plus up to three child pages. There are a total of nCell cells.
  65561. **
  65562. ** pRef is a pointer to one of the pages that contributes cells. This is
  65563. ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
  65564. ** which should be common to all pages that contribute cells to this array.
  65565. **
  65566. ** apCell[] and szCell[] hold, respectively, pointers to the start of each
  65567. ** cell and the size of each cell. Some of the apCell[] pointers might refer
  65568. ** to overflow cells. In other words, some apCel[] pointers might not point
  65569. ** to content area of the pages.
  65570. **
  65571. ** A szCell[] of zero means the size of that cell has not yet been computed.
  65572. **
  65573. ** The cells come from as many as four different pages:
  65574. **
  65575. ** -----------
  65576. ** | Parent |
  65577. ** -----------
  65578. ** / | \
  65579. ** / | \
  65580. ** --------- --------- ---------
  65581. ** |Child-1| |Child-2| |Child-3|
  65582. ** --------- --------- ---------
  65583. **
  65584. ** The order of cells is in the array is for an index btree is:
  65585. **
  65586. ** 1. All cells from Child-1 in order
  65587. ** 2. The first divider cell from Parent
  65588. ** 3. All cells from Child-2 in order
  65589. ** 4. The second divider cell from Parent
  65590. ** 5. All cells from Child-3 in order
  65591. **
  65592. ** For a table-btree (with rowids) the items 2 and 4 are empty because
  65593. ** content exists only in leaves and there are no divider cells.
  65594. **
  65595. ** For an index btree, the apEnd[] array holds pointer to the end of page
  65596. ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
  65597. ** respectively. The ixNx[] array holds the number of cells contained in
  65598. ** each of these 5 stages, and all stages to the left. Hence:
  65599. **
  65600. ** ixNx[0] = Number of cells in Child-1.
  65601. ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
  65602. ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
  65603. ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
  65604. ** ixNx[4] = Total number of cells.
  65605. **
  65606. ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
  65607. ** are used and they point to the leaf pages only, and the ixNx value are:
  65608. **
  65609. ** ixNx[0] = Number of cells in Child-1.
  65610. ** ixNx[1] = Number of cells in Child-1 and Child-2.
  65611. ** ixNx[2] = Total number of cells.
  65612. **
  65613. ** Sometimes when deleting, a child page can have zero cells. In those
  65614. ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
  65615. ** entries, shift down. The end result is that each ixNx[] entry should
  65616. ** be larger than the previous
  65617. */
  65618. typedef struct CellArray CellArray;
  65619. struct CellArray {
  65620. int nCell; /* Number of cells in apCell[] */
  65621. MemPage *pRef; /* Reference page */
  65622. u8 **apCell; /* All cells begin balanced */
  65623. u16 *szCell; /* Local size of all cells in apCell[] */
  65624. u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
  65625. int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
  65626. };
  65627. /*
  65628. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  65629. ** computed.
  65630. */
  65631. static void populateCellCache(CellArray *p, int idx, int N){
  65632. assert( idx>=0 && idx+N<=p->nCell );
  65633. while( N>0 ){
  65634. assert( p->apCell[idx]!=0 );
  65635. if( p->szCell[idx]==0 ){
  65636. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  65637. }else{
  65638. assert( CORRUPT_DB ||
  65639. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  65640. }
  65641. idx++;
  65642. N--;
  65643. }
  65644. }
  65645. /*
  65646. ** Return the size of the Nth element of the cell array
  65647. */
  65648. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  65649. assert( N>=0 && N<p->nCell );
  65650. assert( p->szCell[N]==0 );
  65651. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  65652. return p->szCell[N];
  65653. }
  65654. static u16 cachedCellSize(CellArray *p, int N){
  65655. assert( N>=0 && N<p->nCell );
  65656. if( p->szCell[N] ) return p->szCell[N];
  65657. return computeCellSize(p, N);
  65658. }
  65659. /*
  65660. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  65661. ** szCell[] array contains the size in bytes of each cell. This function
  65662. ** replaces the current contents of page pPg with the contents of the cell
  65663. ** array.
  65664. **
  65665. ** Some of the cells in apCell[] may currently be stored in pPg. This
  65666. ** function works around problems caused by this by making a copy of any
  65667. ** such cells before overwriting the page data.
  65668. **
  65669. ** The MemPage.nFree field is invalidated by this function. It is the
  65670. ** responsibility of the caller to set it correctly.
  65671. */
  65672. static int rebuildPage(
  65673. CellArray *pCArray, /* Content to be added to page pPg */
  65674. int iFirst, /* First cell in pCArray to use */
  65675. int nCell, /* Final number of cells on page */
  65676. MemPage *pPg /* The page to be reconstructed */
  65677. ){
  65678. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  65679. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  65680. const int usableSize = pPg->pBt->usableSize;
  65681. u8 * const pEnd = &aData[usableSize];
  65682. int i = iFirst; /* Which cell to copy from pCArray*/
  65683. u32 j; /* Start of cell content area */
  65684. int iEnd = i+nCell; /* Loop terminator */
  65685. u8 *pCellptr = pPg->aCellIdx;
  65686. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  65687. u8 *pData;
  65688. int k; /* Current slot in pCArray->apEnd[] */
  65689. u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
  65690. assert( i<iEnd );
  65691. j = get2byte(&aData[hdr+5]);
  65692. if( NEVER(j>(u32)usableSize) ){ j = 0; }
  65693. memcpy(&pTmp[j], &aData[j], usableSize - j);
  65694. for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
  65695. pSrcEnd = pCArray->apEnd[k];
  65696. pData = pEnd;
  65697. while( 1/*exit by break*/ ){
  65698. u8 *pCell = pCArray->apCell[i];
  65699. u16 sz = pCArray->szCell[i];
  65700. assert( sz>0 );
  65701. if( SQLITE_WITHIN(pCell,aData,pEnd) ){
  65702. if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
  65703. pCell = &pTmp[pCell - aData];
  65704. }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
  65705. && (uptr)(pCell)<(uptr)pSrcEnd
  65706. ){
  65707. return SQLITE_CORRUPT_BKPT;
  65708. }
  65709. pData -= sz;
  65710. put2byte(pCellptr, (pData - aData));
  65711. pCellptr += 2;
  65712. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  65713. memcpy(pData, pCell, sz);
  65714. assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  65715. testcase( sz!=pPg->xCellSize(pPg,pCell) );
  65716. i++;
  65717. if( i>=iEnd ) break;
  65718. if( pCArray->ixNx[k]<=i ){
  65719. k++;
  65720. pSrcEnd = pCArray->apEnd[k];
  65721. }
  65722. }
  65723. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  65724. pPg->nCell = nCell;
  65725. pPg->nOverflow = 0;
  65726. put2byte(&aData[hdr+1], 0);
  65727. put2byte(&aData[hdr+3], pPg->nCell);
  65728. put2byte(&aData[hdr+5], pData - aData);
  65729. aData[hdr+7] = 0x00;
  65730. return SQLITE_OK;
  65731. }
  65732. /*
  65733. ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
  65734. ** This function attempts to add the cells stored in the array to page pPg.
  65735. ** If it cannot (because the page needs to be defragmented before the cells
  65736. ** will fit), non-zero is returned. Otherwise, if the cells are added
  65737. ** successfully, zero is returned.
  65738. **
  65739. ** Argument pCellptr points to the first entry in the cell-pointer array
  65740. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  65741. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  65742. ** cell in the array. It is the responsibility of the caller to ensure
  65743. ** that it is safe to overwrite this part of the cell-pointer array.
  65744. **
  65745. ** When this function is called, *ppData points to the start of the
  65746. ** content area on page pPg. If the size of the content area is extended,
  65747. ** *ppData is updated to point to the new start of the content area
  65748. ** before returning.
  65749. **
  65750. ** Finally, argument pBegin points to the byte immediately following the
  65751. ** end of the space required by this page for the cell-pointer area (for
  65752. ** all cells - not just those inserted by the current call). If the content
  65753. ** area must be extended to before this point in order to accomodate all
  65754. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  65755. */
  65756. static int pageInsertArray(
  65757. MemPage *pPg, /* Page to add cells to */
  65758. u8 *pBegin, /* End of cell-pointer array */
  65759. u8 **ppData, /* IN/OUT: Page content-area pointer */
  65760. u8 *pCellptr, /* Pointer to cell-pointer area */
  65761. int iFirst, /* Index of first cell to add */
  65762. int nCell, /* Number of cells to add to pPg */
  65763. CellArray *pCArray /* Array of cells */
  65764. ){
  65765. int i = iFirst; /* Loop counter - cell index to insert */
  65766. u8 *aData = pPg->aData; /* Complete page */
  65767. u8 *pData = *ppData; /* Content area. A subset of aData[] */
  65768. int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
  65769. int k; /* Current slot in pCArray->apEnd[] */
  65770. u8 *pEnd; /* Maximum extent of cell data */
  65771. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  65772. if( iEnd<=iFirst ) return 0;
  65773. for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
  65774. pEnd = pCArray->apEnd[k];
  65775. while( 1 /*Exit by break*/ ){
  65776. int sz, rc;
  65777. u8 *pSlot;
  65778. sz = cachedCellSize(pCArray, i);
  65779. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  65780. if( (pData - pBegin)<sz ) return 1;
  65781. pData -= sz;
  65782. pSlot = pData;
  65783. }
  65784. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  65785. ** database. But they might for a corrupt database. Hence use memmove()
  65786. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  65787. assert( (pSlot+sz)<=pCArray->apCell[i]
  65788. || pSlot>=(pCArray->apCell[i]+sz)
  65789. || CORRUPT_DB );
  65790. if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
  65791. && (uptr)(pCArray->apCell[i])<(uptr)pEnd
  65792. ){
  65793. assert( CORRUPT_DB );
  65794. (void)SQLITE_CORRUPT_BKPT;
  65795. return 1;
  65796. }
  65797. memmove(pSlot, pCArray->apCell[i], sz);
  65798. put2byte(pCellptr, (pSlot - aData));
  65799. pCellptr += 2;
  65800. i++;
  65801. if( i>=iEnd ) break;
  65802. if( pCArray->ixNx[k]<=i ){
  65803. k++;
  65804. pEnd = pCArray->apEnd[k];
  65805. }
  65806. }
  65807. *ppData = pData;
  65808. return 0;
  65809. }
  65810. /*
  65811. ** The pCArray object contains pointers to b-tree cells and their sizes.
  65812. **
  65813. ** This function adds the space associated with each cell in the array
  65814. ** that is currently stored within the body of pPg to the pPg free-list.
  65815. ** The cell-pointers and other fields of the page are not updated.
  65816. **
  65817. ** This function returns the total number of cells added to the free-list.
  65818. */
  65819. static int pageFreeArray(
  65820. MemPage *pPg, /* Page to edit */
  65821. int iFirst, /* First cell to delete */
  65822. int nCell, /* Cells to delete */
  65823. CellArray *pCArray /* Array of cells */
  65824. ){
  65825. u8 * const aData = pPg->aData;
  65826. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  65827. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  65828. int nRet = 0;
  65829. int i;
  65830. int iEnd = iFirst + nCell;
  65831. u8 *pFree = 0;
  65832. int szFree = 0;
  65833. for(i=iFirst; i<iEnd; i++){
  65834. u8 *pCell = pCArray->apCell[i];
  65835. if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
  65836. int sz;
  65837. /* No need to use cachedCellSize() here. The sizes of all cells that
  65838. ** are to be freed have already been computing while deciding which
  65839. ** cells need freeing */
  65840. sz = pCArray->szCell[i]; assert( sz>0 );
  65841. if( pFree!=(pCell + sz) ){
  65842. if( pFree ){
  65843. assert( pFree>aData && (pFree - aData)<65536 );
  65844. freeSpace(pPg, (u16)(pFree - aData), szFree);
  65845. }
  65846. pFree = pCell;
  65847. szFree = sz;
  65848. if( pFree+sz>pEnd ) return 0;
  65849. }else{
  65850. pFree = pCell;
  65851. szFree += sz;
  65852. }
  65853. nRet++;
  65854. }
  65855. }
  65856. if( pFree ){
  65857. assert( pFree>aData && (pFree - aData)<65536 );
  65858. freeSpace(pPg, (u16)(pFree - aData), szFree);
  65859. }
  65860. return nRet;
  65861. }
  65862. /*
  65863. ** pCArray contains pointers to and sizes of all cells in the page being
  65864. ** balanced. The current page, pPg, has pPg->nCell cells starting with
  65865. ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
  65866. ** starting at apCell[iNew].
  65867. **
  65868. ** This routine makes the necessary adjustments to pPg so that it contains
  65869. ** the correct cells after being balanced.
  65870. **
  65871. ** The pPg->nFree field is invalid when this function returns. It is the
  65872. ** responsibility of the caller to set it correctly.
  65873. */
  65874. static int editPage(
  65875. MemPage *pPg, /* Edit this page */
  65876. int iOld, /* Index of first cell currently on page */
  65877. int iNew, /* Index of new first cell on page */
  65878. int nNew, /* Final number of cells on page */
  65879. CellArray *pCArray /* Array of cells and sizes */
  65880. ){
  65881. u8 * const aData = pPg->aData;
  65882. const int hdr = pPg->hdrOffset;
  65883. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  65884. int nCell = pPg->nCell; /* Cells stored on pPg */
  65885. u8 *pData;
  65886. u8 *pCellptr;
  65887. int i;
  65888. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  65889. int iNewEnd = iNew + nNew;
  65890. #ifdef SQLITE_DEBUG
  65891. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  65892. memcpy(pTmp, aData, pPg->pBt->usableSize);
  65893. #endif
  65894. /* Remove cells from the start and end of the page */
  65895. assert( nCell>=0 );
  65896. if( iOld<iNew ){
  65897. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  65898. if( nShift>nCell ) return SQLITE_CORRUPT_BKPT;
  65899. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  65900. nCell -= nShift;
  65901. }
  65902. if( iNewEnd < iOldEnd ){
  65903. int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  65904. assert( nCell>=nTail );
  65905. nCell -= nTail;
  65906. }
  65907. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  65908. if( pData<pBegin ) goto editpage_fail;
  65909. /* Add cells to the start of the page */
  65910. if( iNew<iOld ){
  65911. int nAdd = MIN(nNew,iOld-iNew);
  65912. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  65913. assert( nAdd>=0 );
  65914. pCellptr = pPg->aCellIdx;
  65915. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  65916. if( pageInsertArray(
  65917. pPg, pBegin, &pData, pCellptr,
  65918. iNew, nAdd, pCArray
  65919. ) ) goto editpage_fail;
  65920. nCell += nAdd;
  65921. }
  65922. /* Add any overflow cells */
  65923. for(i=0; i<pPg->nOverflow; i++){
  65924. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  65925. if( iCell>=0 && iCell<nNew ){
  65926. pCellptr = &pPg->aCellIdx[iCell * 2];
  65927. if( nCell>iCell ){
  65928. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  65929. }
  65930. nCell++;
  65931. if( pageInsertArray(
  65932. pPg, pBegin, &pData, pCellptr,
  65933. iCell+iNew, 1, pCArray
  65934. ) ) goto editpage_fail;
  65935. }
  65936. }
  65937. /* Append cells to the end of the page */
  65938. assert( nCell>=0 );
  65939. pCellptr = &pPg->aCellIdx[nCell*2];
  65940. if( pageInsertArray(
  65941. pPg, pBegin, &pData, pCellptr,
  65942. iNew+nCell, nNew-nCell, pCArray
  65943. ) ) goto editpage_fail;
  65944. pPg->nCell = nNew;
  65945. pPg->nOverflow = 0;
  65946. put2byte(&aData[hdr+3], pPg->nCell);
  65947. put2byte(&aData[hdr+5], pData - aData);
  65948. #ifdef SQLITE_DEBUG
  65949. for(i=0; i<nNew && !CORRUPT_DB; i++){
  65950. u8 *pCell = pCArray->apCell[i+iNew];
  65951. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  65952. if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
  65953. pCell = &pTmp[pCell - aData];
  65954. }
  65955. assert( 0==memcmp(pCell, &aData[iOff],
  65956. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  65957. }
  65958. #endif
  65959. return SQLITE_OK;
  65960. editpage_fail:
  65961. /* Unable to edit this page. Rebuild it from scratch instead. */
  65962. populateCellCache(pCArray, iNew, nNew);
  65963. return rebuildPage(pCArray, iNew, nNew, pPg);
  65964. }
  65965. #ifndef SQLITE_OMIT_QUICKBALANCE
  65966. /*
  65967. ** This version of balance() handles the common special case where
  65968. ** a new entry is being inserted on the extreme right-end of the
  65969. ** tree, in other words, when the new entry will become the largest
  65970. ** entry in the tree.
  65971. **
  65972. ** Instead of trying to balance the 3 right-most leaf pages, just add
  65973. ** a new page to the right-hand side and put the one new entry in
  65974. ** that page. This leaves the right side of the tree somewhat
  65975. ** unbalanced. But odds are that we will be inserting new entries
  65976. ** at the end soon afterwards so the nearly empty page will quickly
  65977. ** fill up. On average.
  65978. **
  65979. ** pPage is the leaf page which is the right-most page in the tree.
  65980. ** pParent is its parent. pPage must have a single overflow entry
  65981. ** which is also the right-most entry on the page.
  65982. **
  65983. ** The pSpace buffer is used to store a temporary copy of the divider
  65984. ** cell that will be inserted into pParent. Such a cell consists of a 4
  65985. ** byte page number followed by a variable length integer. In other
  65986. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  65987. ** least 13 bytes in size.
  65988. */
  65989. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  65990. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  65991. MemPage *pNew; /* Newly allocated page */
  65992. int rc; /* Return Code */
  65993. Pgno pgnoNew; /* Page number of pNew */
  65994. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  65995. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  65996. assert( pPage->nOverflow==1 );
  65997. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
  65998. assert( pPage->nFree>=0 );
  65999. assert( pParent->nFree>=0 );
  66000. /* Allocate a new page. This page will become the right-sibling of
  66001. ** pPage. Make the parent page writable, so that the new divider cell
  66002. ** may be inserted. If both these operations are successful, proceed.
  66003. */
  66004. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  66005. if( rc==SQLITE_OK ){
  66006. u8 *pOut = &pSpace[4];
  66007. u8 *pCell = pPage->apOvfl[0];
  66008. u16 szCell = pPage->xCellSize(pPage, pCell);
  66009. u8 *pStop;
  66010. CellArray b;
  66011. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  66012. assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  66013. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  66014. b.nCell = 1;
  66015. b.pRef = pPage;
  66016. b.apCell = &pCell;
  66017. b.szCell = &szCell;
  66018. b.apEnd[0] = pPage->aDataEnd;
  66019. b.ixNx[0] = 2;
  66020. rc = rebuildPage(&b, 0, 1, pNew);
  66021. if( NEVER(rc) ){
  66022. releasePage(pNew);
  66023. return rc;
  66024. }
  66025. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  66026. /* If this is an auto-vacuum database, update the pointer map
  66027. ** with entries for the new page, and any pointer from the
  66028. ** cell on the page to an overflow page. If either of these
  66029. ** operations fails, the return code is set, but the contents
  66030. ** of the parent page are still manipulated by thh code below.
  66031. ** That is Ok, at this point the parent page is guaranteed to
  66032. ** be marked as dirty. Returning an error code will cause a
  66033. ** rollback, undoing any changes made to the parent page.
  66034. */
  66035. if( ISAUTOVACUUM ){
  66036. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  66037. if( szCell>pNew->minLocal ){
  66038. ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
  66039. }
  66040. }
  66041. /* Create a divider cell to insert into pParent. The divider cell
  66042. ** consists of a 4-byte page number (the page number of pPage) and
  66043. ** a variable length key value (which must be the same value as the
  66044. ** largest key on pPage).
  66045. **
  66046. ** To find the largest key value on pPage, first find the right-most
  66047. ** cell on pPage. The first two fields of this cell are the
  66048. ** record-length (a variable length integer at most 32-bits in size)
  66049. ** and the key value (a variable length integer, may have any value).
  66050. ** The first of the while(...) loops below skips over the record-length
  66051. ** field. The second while(...) loop copies the key value from the
  66052. ** cell on pPage into the pSpace buffer.
  66053. */
  66054. pCell = findCell(pPage, pPage->nCell-1);
  66055. pStop = &pCell[9];
  66056. while( (*(pCell++)&0x80) && pCell<pStop );
  66057. pStop = &pCell[9];
  66058. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  66059. /* Insert the new divider cell into pParent. */
  66060. if( rc==SQLITE_OK ){
  66061. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  66062. 0, pPage->pgno, &rc);
  66063. }
  66064. /* Set the right-child pointer of pParent to point to the new page. */
  66065. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  66066. /* Release the reference to the new page. */
  66067. releasePage(pNew);
  66068. }
  66069. return rc;
  66070. }
  66071. #endif /* SQLITE_OMIT_QUICKBALANCE */
  66072. #if 0
  66073. /*
  66074. ** This function does not contribute anything to the operation of SQLite.
  66075. ** it is sometimes activated temporarily while debugging code responsible
  66076. ** for setting pointer-map entries.
  66077. */
  66078. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  66079. int i, j;
  66080. for(i=0; i<nPage; i++){
  66081. Pgno n;
  66082. u8 e;
  66083. MemPage *pPage = apPage[i];
  66084. BtShared *pBt = pPage->pBt;
  66085. assert( pPage->isInit );
  66086. for(j=0; j<pPage->nCell; j++){
  66087. CellInfo info;
  66088. u8 *z;
  66089. z = findCell(pPage, j);
  66090. pPage->xParseCell(pPage, z, &info);
  66091. if( info.nLocal<info.nPayload ){
  66092. Pgno ovfl = get4byte(&z[info.nSize-4]);
  66093. ptrmapGet(pBt, ovfl, &e, &n);
  66094. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  66095. }
  66096. if( !pPage->leaf ){
  66097. Pgno child = get4byte(z);
  66098. ptrmapGet(pBt, child, &e, &n);
  66099. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  66100. }
  66101. }
  66102. if( !pPage->leaf ){
  66103. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  66104. ptrmapGet(pBt, child, &e, &n);
  66105. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  66106. }
  66107. }
  66108. return 1;
  66109. }
  66110. #endif
  66111. /*
  66112. ** This function is used to copy the contents of the b-tree node stored
  66113. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  66114. ** the pointer-map entries for each child page are updated so that the
  66115. ** parent page stored in the pointer map is page pTo. If pFrom contained
  66116. ** any cells with overflow page pointers, then the corresponding pointer
  66117. ** map entries are also updated so that the parent page is page pTo.
  66118. **
  66119. ** If pFrom is currently carrying any overflow cells (entries in the
  66120. ** MemPage.apOvfl[] array), they are not copied to pTo.
  66121. **
  66122. ** Before returning, page pTo is reinitialized using btreeInitPage().
  66123. **
  66124. ** The performance of this function is not critical. It is only used by
  66125. ** the balance_shallower() and balance_deeper() procedures, neither of
  66126. ** which are called often under normal circumstances.
  66127. */
  66128. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  66129. if( (*pRC)==SQLITE_OK ){
  66130. BtShared * const pBt = pFrom->pBt;
  66131. u8 * const aFrom = pFrom->aData;
  66132. u8 * const aTo = pTo->aData;
  66133. int const iFromHdr = pFrom->hdrOffset;
  66134. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  66135. int rc;
  66136. int iData;
  66137. assert( pFrom->isInit );
  66138. assert( pFrom->nFree>=iToHdr );
  66139. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  66140. /* Copy the b-tree node content from page pFrom to page pTo. */
  66141. iData = get2byte(&aFrom[iFromHdr+5]);
  66142. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  66143. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  66144. /* Reinitialize page pTo so that the contents of the MemPage structure
  66145. ** match the new data. The initialization of pTo can actually fail under
  66146. ** fairly obscure circumstances, even though it is a copy of initialized
  66147. ** page pFrom.
  66148. */
  66149. pTo->isInit = 0;
  66150. rc = btreeInitPage(pTo);
  66151. if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
  66152. if( rc!=SQLITE_OK ){
  66153. *pRC = rc;
  66154. return;
  66155. }
  66156. /* If this is an auto-vacuum database, update the pointer-map entries
  66157. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  66158. */
  66159. if( ISAUTOVACUUM ){
  66160. *pRC = setChildPtrmaps(pTo);
  66161. }
  66162. }
  66163. }
  66164. /*
  66165. ** This routine redistributes cells on the iParentIdx'th child of pParent
  66166. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  66167. ** same amount of free space. Usually a single sibling on either side of the
  66168. ** page are used in the balancing, though both siblings might come from one
  66169. ** side if the page is the first or last child of its parent. If the page
  66170. ** has fewer than 2 siblings (something which can only happen if the page
  66171. ** is a root page or a child of a root page) then all available siblings
  66172. ** participate in the balancing.
  66173. **
  66174. ** The number of siblings of the page might be increased or decreased by
  66175. ** one or two in an effort to keep pages nearly full but not over full.
  66176. **
  66177. ** Note that when this routine is called, some of the cells on the page
  66178. ** might not actually be stored in MemPage.aData[]. This can happen
  66179. ** if the page is overfull. This routine ensures that all cells allocated
  66180. ** to the page and its siblings fit into MemPage.aData[] before returning.
  66181. **
  66182. ** In the course of balancing the page and its siblings, cells may be
  66183. ** inserted into or removed from the parent page (pParent). Doing so
  66184. ** may cause the parent page to become overfull or underfull. If this
  66185. ** happens, it is the responsibility of the caller to invoke the correct
  66186. ** balancing routine to fix this problem (see the balance() routine).
  66187. **
  66188. ** If this routine fails for any reason, it might leave the database
  66189. ** in a corrupted state. So if this routine fails, the database should
  66190. ** be rolled back.
  66191. **
  66192. ** The third argument to this function, aOvflSpace, is a pointer to a
  66193. ** buffer big enough to hold one page. If while inserting cells into the parent
  66194. ** page (pParent) the parent page becomes overfull, this buffer is
  66195. ** used to store the parent's overflow cells. Because this function inserts
  66196. ** a maximum of four divider cells into the parent page, and the maximum
  66197. ** size of a cell stored within an internal node is always less than 1/4
  66198. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  66199. ** enough for all overflow cells.
  66200. **
  66201. ** If aOvflSpace is set to a null pointer, this function returns
  66202. ** SQLITE_NOMEM.
  66203. */
  66204. static int balance_nonroot(
  66205. MemPage *pParent, /* Parent page of siblings being balanced */
  66206. int iParentIdx, /* Index of "the page" in pParent */
  66207. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  66208. int isRoot, /* True if pParent is a root-page */
  66209. int bBulk /* True if this call is part of a bulk load */
  66210. ){
  66211. BtShared *pBt; /* The whole database */
  66212. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  66213. int nNew = 0; /* Number of pages in apNew[] */
  66214. int nOld; /* Number of pages in apOld[] */
  66215. int i, j, k; /* Loop counters */
  66216. int nxDiv; /* Next divider slot in pParent->aCell[] */
  66217. int rc = SQLITE_OK; /* The return code */
  66218. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  66219. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  66220. int usableSpace; /* Bytes in pPage beyond the header */
  66221. int pageFlags; /* Value of pPage->aData[0] */
  66222. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  66223. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  66224. int szScratch; /* Size of scratch memory requested */
  66225. MemPage *apOld[NB]; /* pPage and up to two siblings */
  66226. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  66227. u8 *pRight; /* Location in parent of right-sibling pointer */
  66228. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  66229. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  66230. int cntOld[NB+2]; /* Old index in b.apCell[] */
  66231. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  66232. u8 *aSpace1; /* Space for copies of dividers cells */
  66233. Pgno pgno; /* Temp var to store a page number in */
  66234. u8 abDone[NB+2]; /* True after i'th new page is populated */
  66235. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  66236. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  66237. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  66238. CellArray b; /* Parsed information on cells being balanced */
  66239. memset(abDone, 0, sizeof(abDone));
  66240. b.nCell = 0;
  66241. b.apCell = 0;
  66242. pBt = pParent->pBt;
  66243. assert( sqlite3_mutex_held(pBt->mutex) );
  66244. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  66245. /* At this point pParent may have at most one overflow cell. And if
  66246. ** this overflow cell is present, it must be the cell with
  66247. ** index iParentIdx. This scenario comes about when this function
  66248. ** is called (indirectly) from sqlite3BtreeDelete().
  66249. */
  66250. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  66251. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  66252. if( !aOvflSpace ){
  66253. return SQLITE_NOMEM_BKPT;
  66254. }
  66255. assert( pParent->nFree>=0 );
  66256. /* Find the sibling pages to balance. Also locate the cells in pParent
  66257. ** that divide the siblings. An attempt is made to find NN siblings on
  66258. ** either side of pPage. More siblings are taken from one side, however,
  66259. ** if there are fewer than NN siblings on the other side. If pParent
  66260. ** has NB or fewer children then all children of pParent are taken.
  66261. **
  66262. ** This loop also drops the divider cells from the parent page. This
  66263. ** way, the remainder of the function does not have to deal with any
  66264. ** overflow cells in the parent page, since if any existed they will
  66265. ** have already been removed.
  66266. */
  66267. i = pParent->nOverflow + pParent->nCell;
  66268. if( i<2 ){
  66269. nxDiv = 0;
  66270. }else{
  66271. assert( bBulk==0 || bBulk==1 );
  66272. if( iParentIdx==0 ){
  66273. nxDiv = 0;
  66274. }else if( iParentIdx==i ){
  66275. nxDiv = i-2+bBulk;
  66276. }else{
  66277. nxDiv = iParentIdx-1;
  66278. }
  66279. i = 2-bBulk;
  66280. }
  66281. nOld = i+1;
  66282. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  66283. pRight = &pParent->aData[pParent->hdrOffset+8];
  66284. }else{
  66285. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  66286. }
  66287. pgno = get4byte(pRight);
  66288. while( 1 ){
  66289. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  66290. if( rc ){
  66291. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  66292. goto balance_cleanup;
  66293. }
  66294. if( apOld[i]->nFree<0 ){
  66295. rc = btreeComputeFreeSpace(apOld[i]);
  66296. if( rc ){
  66297. memset(apOld, 0, (i)*sizeof(MemPage*));
  66298. goto balance_cleanup;
  66299. }
  66300. }
  66301. if( (i--)==0 ) break;
  66302. if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
  66303. apDiv[i] = pParent->apOvfl[0];
  66304. pgno = get4byte(apDiv[i]);
  66305. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  66306. pParent->nOverflow = 0;
  66307. }else{
  66308. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  66309. pgno = get4byte(apDiv[i]);
  66310. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  66311. /* Drop the cell from the parent page. apDiv[i] still points to
  66312. ** the cell within the parent, even though it has been dropped.
  66313. ** This is safe because dropping a cell only overwrites the first
  66314. ** four bytes of it, and this function does not need the first
  66315. ** four bytes of the divider cell. So the pointer is safe to use
  66316. ** later on.
  66317. **
  66318. ** But not if we are in secure-delete mode. In secure-delete mode,
  66319. ** the dropCell() routine will overwrite the entire cell with zeroes.
  66320. ** In this case, temporarily copy the cell into the aOvflSpace[]
  66321. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  66322. ** is allocated. */
  66323. if( pBt->btsFlags & BTS_FAST_SECURE ){
  66324. int iOff;
  66325. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  66326. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  66327. rc = SQLITE_CORRUPT_BKPT;
  66328. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  66329. goto balance_cleanup;
  66330. }else{
  66331. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  66332. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  66333. }
  66334. }
  66335. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  66336. }
  66337. }
  66338. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  66339. ** alignment */
  66340. nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl));
  66341. nMaxCells = (nMaxCells + 3)&~3;
  66342. /*
  66343. ** Allocate space for memory structures
  66344. */
  66345. szScratch =
  66346. nMaxCells*sizeof(u8*) /* b.apCell */
  66347. + nMaxCells*sizeof(u16) /* b.szCell */
  66348. + pBt->pageSize; /* aSpace1 */
  66349. assert( szScratch<=7*(int)pBt->pageSize );
  66350. b.apCell = sqlite3StackAllocRaw(0, szScratch );
  66351. if( b.apCell==0 ){
  66352. rc = SQLITE_NOMEM_BKPT;
  66353. goto balance_cleanup;
  66354. }
  66355. b.szCell = (u16*)&b.apCell[nMaxCells];
  66356. aSpace1 = (u8*)&b.szCell[nMaxCells];
  66357. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  66358. /*
  66359. ** Load pointers to all cells on sibling pages and the divider cells
  66360. ** into the local b.apCell[] array. Make copies of the divider cells
  66361. ** into space obtained from aSpace1[]. The divider cells have already
  66362. ** been removed from pParent.
  66363. **
  66364. ** If the siblings are on leaf pages, then the child pointers of the
  66365. ** divider cells are stripped from the cells before they are copied
  66366. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  66367. ** child pointers. If siblings are not leaves, then all cell in
  66368. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  66369. ** are alike.
  66370. **
  66371. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  66372. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  66373. */
  66374. b.pRef = apOld[0];
  66375. leafCorrection = b.pRef->leaf*4;
  66376. leafData = b.pRef->intKeyLeaf;
  66377. for(i=0; i<nOld; i++){
  66378. MemPage *pOld = apOld[i];
  66379. int limit = pOld->nCell;
  66380. u8 *aData = pOld->aData;
  66381. u16 maskPage = pOld->maskPage;
  66382. u8 *piCell = aData + pOld->cellOffset;
  66383. u8 *piEnd;
  66384. /* Verify that all sibling pages are of the same "type" (table-leaf,
  66385. ** table-interior, index-leaf, or index-interior).
  66386. */
  66387. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  66388. rc = SQLITE_CORRUPT_BKPT;
  66389. goto balance_cleanup;
  66390. }
  66391. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  66392. ** contains overflow cells, include them in the b.apCell[] array
  66393. ** in the correct spot.
  66394. **
  66395. ** Note that when there are multiple overflow cells, it is always the
  66396. ** case that they are sequential and adjacent. This invariant arises
  66397. ** because multiple overflows can only occurs when inserting divider
  66398. ** cells into a parent on a prior balance, and divider cells are always
  66399. ** adjacent and are inserted in order. There is an assert() tagged
  66400. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  66401. ** invariant.
  66402. **
  66403. ** This must be done in advance. Once the balance starts, the cell
  66404. ** offset section of the btree page will be overwritten and we will no
  66405. ** long be able to find the cells if a pointer to each cell is not saved
  66406. ** first.
  66407. */
  66408. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
  66409. if( pOld->nOverflow>0 ){
  66410. limit = pOld->aiOvfl[0];
  66411. for(j=0; j<limit; j++){
  66412. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  66413. piCell += 2;
  66414. b.nCell++;
  66415. }
  66416. for(k=0; k<pOld->nOverflow; k++){
  66417. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  66418. b.apCell[b.nCell] = pOld->apOvfl[k];
  66419. b.nCell++;
  66420. }
  66421. }
  66422. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  66423. while( piCell<piEnd ){
  66424. assert( b.nCell<nMaxCells );
  66425. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  66426. piCell += 2;
  66427. b.nCell++;
  66428. }
  66429. cntOld[i] = b.nCell;
  66430. if( i<nOld-1 && !leafData){
  66431. u16 sz = (u16)szNew[i];
  66432. u8 *pTemp;
  66433. assert( b.nCell<nMaxCells );
  66434. b.szCell[b.nCell] = sz;
  66435. pTemp = &aSpace1[iSpace1];
  66436. iSpace1 += sz;
  66437. assert( sz<=pBt->maxLocal+23 );
  66438. assert( iSpace1 <= (int)pBt->pageSize );
  66439. memcpy(pTemp, apDiv[i], sz);
  66440. b.apCell[b.nCell] = pTemp+leafCorrection;
  66441. assert( leafCorrection==0 || leafCorrection==4 );
  66442. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  66443. if( !pOld->leaf ){
  66444. assert( leafCorrection==0 );
  66445. assert( pOld->hdrOffset==0 );
  66446. /* The right pointer of the child page pOld becomes the left
  66447. ** pointer of the divider cell */
  66448. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  66449. }else{
  66450. assert( leafCorrection==4 );
  66451. while( b.szCell[b.nCell]<4 ){
  66452. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  66453. ** does exist, pad it with 0x00 bytes. */
  66454. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  66455. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  66456. aSpace1[iSpace1++] = 0x00;
  66457. b.szCell[b.nCell]++;
  66458. }
  66459. }
  66460. b.nCell++;
  66461. }
  66462. }
  66463. /*
  66464. ** Figure out the number of pages needed to hold all b.nCell cells.
  66465. ** Store this number in "k". Also compute szNew[] which is the total
  66466. ** size of all cells on the i-th page and cntNew[] which is the index
  66467. ** in b.apCell[] of the cell that divides page i from page i+1.
  66468. ** cntNew[k] should equal b.nCell.
  66469. **
  66470. ** Values computed by this block:
  66471. **
  66472. ** k: The total number of sibling pages
  66473. ** szNew[i]: Spaced used on the i-th sibling page.
  66474. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  66475. ** the right of the i-th sibling page.
  66476. ** usableSpace: Number of bytes of space available on each sibling.
  66477. **
  66478. */
  66479. usableSpace = pBt->usableSize - 12 + leafCorrection;
  66480. for(i=k=0; i<nOld; i++, k++){
  66481. MemPage *p = apOld[i];
  66482. b.apEnd[k] = p->aDataEnd;
  66483. b.ixNx[k] = cntOld[i];
  66484. if( k && b.ixNx[k]==b.ixNx[k-1] ){
  66485. k--; /* Omit b.ixNx[] entry for child pages with no cells */
  66486. }
  66487. if( !leafData ){
  66488. k++;
  66489. b.apEnd[k] = pParent->aDataEnd;
  66490. b.ixNx[k] = cntOld[i]+1;
  66491. }
  66492. assert( p->nFree>=0 );
  66493. szNew[i] = usableSpace - p->nFree;
  66494. for(j=0; j<p->nOverflow; j++){
  66495. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  66496. }
  66497. cntNew[i] = cntOld[i];
  66498. }
  66499. k = nOld;
  66500. for(i=0; i<k; i++){
  66501. int sz;
  66502. while( szNew[i]>usableSpace ){
  66503. if( i+1>=k ){
  66504. k = i+2;
  66505. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  66506. szNew[k-1] = 0;
  66507. cntNew[k-1] = b.nCell;
  66508. }
  66509. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  66510. szNew[i] -= sz;
  66511. if( !leafData ){
  66512. if( cntNew[i]<b.nCell ){
  66513. sz = 2 + cachedCellSize(&b, cntNew[i]);
  66514. }else{
  66515. sz = 0;
  66516. }
  66517. }
  66518. szNew[i+1] += sz;
  66519. cntNew[i]--;
  66520. }
  66521. while( cntNew[i]<b.nCell ){
  66522. sz = 2 + cachedCellSize(&b, cntNew[i]);
  66523. if( szNew[i]+sz>usableSpace ) break;
  66524. szNew[i] += sz;
  66525. cntNew[i]++;
  66526. if( !leafData ){
  66527. if( cntNew[i]<b.nCell ){
  66528. sz = 2 + cachedCellSize(&b, cntNew[i]);
  66529. }else{
  66530. sz = 0;
  66531. }
  66532. }
  66533. szNew[i+1] -= sz;
  66534. }
  66535. if( cntNew[i]>=b.nCell ){
  66536. k = i+1;
  66537. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  66538. rc = SQLITE_CORRUPT_BKPT;
  66539. goto balance_cleanup;
  66540. }
  66541. }
  66542. /*
  66543. ** The packing computed by the previous block is biased toward the siblings
  66544. ** on the left side (siblings with smaller keys). The left siblings are
  66545. ** always nearly full, while the right-most sibling might be nearly empty.
  66546. ** The next block of code attempts to adjust the packing of siblings to
  66547. ** get a better balance.
  66548. **
  66549. ** This adjustment is more than an optimization. The packing above might
  66550. ** be so out of balance as to be illegal. For example, the right-most
  66551. ** sibling might be completely empty. This adjustment is not optional.
  66552. */
  66553. for(i=k-1; i>0; i--){
  66554. int szRight = szNew[i]; /* Size of sibling on the right */
  66555. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  66556. int r; /* Index of right-most cell in left sibling */
  66557. int d; /* Index of first cell to the left of right sibling */
  66558. r = cntNew[i-1] - 1;
  66559. d = r + 1 - leafData;
  66560. (void)cachedCellSize(&b, d);
  66561. do{
  66562. assert( d<nMaxCells );
  66563. assert( r<nMaxCells );
  66564. (void)cachedCellSize(&b, r);
  66565. if( szRight!=0
  66566. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
  66567. break;
  66568. }
  66569. szRight += b.szCell[d] + 2;
  66570. szLeft -= b.szCell[r] + 2;
  66571. cntNew[i-1] = r;
  66572. r--;
  66573. d--;
  66574. }while( r>=0 );
  66575. szNew[i] = szRight;
  66576. szNew[i-1] = szLeft;
  66577. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  66578. rc = SQLITE_CORRUPT_BKPT;
  66579. goto balance_cleanup;
  66580. }
  66581. }
  66582. /* Sanity check: For a non-corrupt database file one of the follwing
  66583. ** must be true:
  66584. ** (1) We found one or more cells (cntNew[0])>0), or
  66585. ** (2) pPage is a virtual root page. A virtual root page is when
  66586. ** the real root page is page 1 and we are the only child of
  66587. ** that page.
  66588. */
  66589. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  66590. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  66591. apOld[0]->pgno, apOld[0]->nCell,
  66592. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  66593. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  66594. ));
  66595. /*
  66596. ** Allocate k new pages. Reuse old pages where possible.
  66597. */
  66598. pageFlags = apOld[0]->aData[0];
  66599. for(i=0; i<k; i++){
  66600. MemPage *pNew;
  66601. if( i<nOld ){
  66602. pNew = apNew[i] = apOld[i];
  66603. apOld[i] = 0;
  66604. rc = sqlite3PagerWrite(pNew->pDbPage);
  66605. nNew++;
  66606. if( rc ) goto balance_cleanup;
  66607. }else{
  66608. assert( i>0 );
  66609. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  66610. if( rc ) goto balance_cleanup;
  66611. zeroPage(pNew, pageFlags);
  66612. apNew[i] = pNew;
  66613. nNew++;
  66614. cntOld[i] = b.nCell;
  66615. /* Set the pointer-map entry for the new sibling page. */
  66616. if( ISAUTOVACUUM ){
  66617. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  66618. if( rc!=SQLITE_OK ){
  66619. goto balance_cleanup;
  66620. }
  66621. }
  66622. }
  66623. }
  66624. /*
  66625. ** Reassign page numbers so that the new pages are in ascending order.
  66626. ** This helps to keep entries in the disk file in order so that a scan
  66627. ** of the table is closer to a linear scan through the file. That in turn
  66628. ** helps the operating system to deliver pages from the disk more rapidly.
  66629. **
  66630. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  66631. ** than (NB+2) (a small constant), that should not be a problem.
  66632. **
  66633. ** When NB==3, this one optimization makes the database about 25% faster
  66634. ** for large insertions and deletions.
  66635. */
  66636. for(i=0; i<nNew; i++){
  66637. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  66638. aPgFlags[i] = apNew[i]->pDbPage->flags;
  66639. for(j=0; j<i; j++){
  66640. if( aPgno[j]==aPgno[i] ){
  66641. /* This branch is taken if the set of sibling pages somehow contains
  66642. ** duplicate entries. This can happen if the database is corrupt.
  66643. ** It would be simpler to detect this as part of the loop below, but
  66644. ** we do the detection here in order to avoid populating the pager
  66645. ** cache with two separate objects associated with the same
  66646. ** page number. */
  66647. assert( CORRUPT_DB );
  66648. rc = SQLITE_CORRUPT_BKPT;
  66649. goto balance_cleanup;
  66650. }
  66651. }
  66652. }
  66653. for(i=0; i<nNew; i++){
  66654. int iBest = 0; /* aPgno[] index of page number to use */
  66655. for(j=1; j<nNew; j++){
  66656. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  66657. }
  66658. pgno = aPgOrder[iBest];
  66659. aPgOrder[iBest] = 0xffffffff;
  66660. if( iBest!=i ){
  66661. if( iBest>i ){
  66662. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  66663. }
  66664. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  66665. apNew[i]->pgno = pgno;
  66666. }
  66667. }
  66668. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  66669. "%d(%d nc=%d) %d(%d nc=%d)\n",
  66670. apNew[0]->pgno, szNew[0], cntNew[0],
  66671. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  66672. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  66673. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  66674. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  66675. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  66676. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  66677. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  66678. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  66679. ));
  66680. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  66681. put4byte(pRight, apNew[nNew-1]->pgno);
  66682. /* If the sibling pages are not leaves, ensure that the right-child pointer
  66683. ** of the right-most new sibling page is set to the value that was
  66684. ** originally in the same field of the right-most old sibling page. */
  66685. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  66686. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  66687. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  66688. }
  66689. /* Make any required updates to pointer map entries associated with
  66690. ** cells stored on sibling pages following the balance operation. Pointer
  66691. ** map entries associated with divider cells are set by the insertCell()
  66692. ** routine. The associated pointer map entries are:
  66693. **
  66694. ** a) if the cell contains a reference to an overflow chain, the
  66695. ** entry associated with the first page in the overflow chain, and
  66696. **
  66697. ** b) if the sibling pages are not leaves, the child page associated
  66698. ** with the cell.
  66699. **
  66700. ** If the sibling pages are not leaves, then the pointer map entry
  66701. ** associated with the right-child of each sibling may also need to be
  66702. ** updated. This happens below, after the sibling pages have been
  66703. ** populated, not here.
  66704. */
  66705. if( ISAUTOVACUUM ){
  66706. MemPage *pOld;
  66707. MemPage *pNew = pOld = apNew[0];
  66708. int cntOldNext = pNew->nCell + pNew->nOverflow;
  66709. int iNew = 0;
  66710. int iOld = 0;
  66711. for(i=0; i<b.nCell; i++){
  66712. u8 *pCell = b.apCell[i];
  66713. while( i==cntOldNext ){
  66714. iOld++;
  66715. assert( iOld<nNew || iOld<nOld );
  66716. pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
  66717. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  66718. }
  66719. if( i==cntNew[iNew] ){
  66720. pNew = apNew[++iNew];
  66721. if( !leafData ) continue;
  66722. }
  66723. /* Cell pCell is destined for new sibling page pNew. Originally, it
  66724. ** was either part of sibling page iOld (possibly an overflow cell),
  66725. ** or else the divider cell to the left of sibling page iOld. So,
  66726. ** if sibling page iOld had the same page number as pNew, and if
  66727. ** pCell really was a part of sibling page iOld (not a divider or
  66728. ** overflow cell), we can skip updating the pointer map entries. */
  66729. if( iOld>=nNew
  66730. || pNew->pgno!=aPgno[iOld]
  66731. || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
  66732. ){
  66733. if( !leafCorrection ){
  66734. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  66735. }
  66736. if( cachedCellSize(&b,i)>pNew->minLocal ){
  66737. ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
  66738. }
  66739. if( rc ) goto balance_cleanup;
  66740. }
  66741. }
  66742. }
  66743. /* Insert new divider cells into pParent. */
  66744. for(i=0; i<nNew-1; i++){
  66745. u8 *pCell;
  66746. u8 *pTemp;
  66747. int sz;
  66748. MemPage *pNew = apNew[i];
  66749. j = cntNew[i];
  66750. assert( j<nMaxCells );
  66751. assert( b.apCell[j]!=0 );
  66752. pCell = b.apCell[j];
  66753. sz = b.szCell[j] + leafCorrection;
  66754. pTemp = &aOvflSpace[iOvflSpace];
  66755. if( !pNew->leaf ){
  66756. memcpy(&pNew->aData[8], pCell, 4);
  66757. }else if( leafData ){
  66758. /* If the tree is a leaf-data tree, and the siblings are leaves,
  66759. ** then there is no divider cell in b.apCell[]. Instead, the divider
  66760. ** cell consists of the integer key for the right-most cell of
  66761. ** the sibling-page assembled above only.
  66762. */
  66763. CellInfo info;
  66764. j--;
  66765. pNew->xParseCell(pNew, b.apCell[j], &info);
  66766. pCell = pTemp;
  66767. sz = 4 + putVarint(&pCell[4], info.nKey);
  66768. pTemp = 0;
  66769. }else{
  66770. pCell -= 4;
  66771. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  66772. ** previously stored on a leaf node, and its reported size was 4
  66773. ** bytes, then it may actually be smaller than this
  66774. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  66775. ** any cell). But it is important to pass the correct size to
  66776. ** insertCell(), so reparse the cell now.
  66777. **
  66778. ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
  66779. ** and WITHOUT ROWID tables with exactly one column which is the
  66780. ** primary key.
  66781. */
  66782. if( b.szCell[j]==4 ){
  66783. assert(leafCorrection==4);
  66784. sz = pParent->xCellSize(pParent, pCell);
  66785. }
  66786. }
  66787. iOvflSpace += sz;
  66788. assert( sz<=pBt->maxLocal+23 );
  66789. assert( iOvflSpace <= (int)pBt->pageSize );
  66790. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  66791. if( rc!=SQLITE_OK ) goto balance_cleanup;
  66792. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  66793. }
  66794. /* Now update the actual sibling pages. The order in which they are updated
  66795. ** is important, as this code needs to avoid disrupting any page from which
  66796. ** cells may still to be read. In practice, this means:
  66797. **
  66798. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  66799. ** then it is not safe to update page apNew[iPg] until after
  66800. ** the left-hand sibling apNew[iPg-1] has been updated.
  66801. **
  66802. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  66803. ** then it is not safe to update page apNew[iPg] until after
  66804. ** the right-hand sibling apNew[iPg+1] has been updated.
  66805. **
  66806. ** If neither of the above apply, the page is safe to update.
  66807. **
  66808. ** The iPg value in the following loop starts at nNew-1 goes down
  66809. ** to 0, then back up to nNew-1 again, thus making two passes over
  66810. ** the pages. On the initial downward pass, only condition (1) above
  66811. ** needs to be tested because (2) will always be true from the previous
  66812. ** step. On the upward pass, both conditions are always true, so the
  66813. ** upwards pass simply processes pages that were missed on the downward
  66814. ** pass.
  66815. */
  66816. for(i=1-nNew; i<nNew; i++){
  66817. int iPg = i<0 ? -i : i;
  66818. assert( iPg>=0 && iPg<nNew );
  66819. if( abDone[iPg] ) continue; /* Skip pages already processed */
  66820. if( i>=0 /* On the upwards pass, or... */
  66821. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  66822. ){
  66823. int iNew;
  66824. int iOld;
  66825. int nNewCell;
  66826. /* Verify condition (1): If cells are moving left, update iPg
  66827. ** only after iPg-1 has already been updated. */
  66828. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  66829. /* Verify condition (2): If cells are moving right, update iPg
  66830. ** only after iPg+1 has already been updated. */
  66831. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  66832. if( iPg==0 ){
  66833. iNew = iOld = 0;
  66834. nNewCell = cntNew[0];
  66835. }else{
  66836. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  66837. iNew = cntNew[iPg-1] + !leafData;
  66838. nNewCell = cntNew[iPg] - iNew;
  66839. }
  66840. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  66841. if( rc ) goto balance_cleanup;
  66842. abDone[iPg]++;
  66843. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  66844. assert( apNew[iPg]->nOverflow==0 );
  66845. assert( apNew[iPg]->nCell==nNewCell );
  66846. }
  66847. }
  66848. /* All pages have been processed exactly once */
  66849. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  66850. assert( nOld>0 );
  66851. assert( nNew>0 );
  66852. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  66853. /* The root page of the b-tree now contains no cells. The only sibling
  66854. ** page is the right-child of the parent. Copy the contents of the
  66855. ** child page into the parent, decreasing the overall height of the
  66856. ** b-tree structure by one. This is described as the "balance-shallower"
  66857. ** sub-algorithm in some documentation.
  66858. **
  66859. ** If this is an auto-vacuum database, the call to copyNodeContent()
  66860. ** sets all pointer-map entries corresponding to database image pages
  66861. ** for which the pointer is stored within the content being copied.
  66862. **
  66863. ** It is critical that the child page be defragmented before being
  66864. ** copied into the parent, because if the parent is page 1 then it will
  66865. ** by smaller than the child due to the database header, and so all the
  66866. ** free space needs to be up front.
  66867. */
  66868. assert( nNew==1 || CORRUPT_DB );
  66869. rc = defragmentPage(apNew[0], -1);
  66870. testcase( rc!=SQLITE_OK );
  66871. assert( apNew[0]->nFree ==
  66872. (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
  66873. - apNew[0]->nCell*2)
  66874. || rc!=SQLITE_OK
  66875. );
  66876. copyNodeContent(apNew[0], pParent, &rc);
  66877. freePage(apNew[0], &rc);
  66878. }else if( ISAUTOVACUUM && !leafCorrection ){
  66879. /* Fix the pointer map entries associated with the right-child of each
  66880. ** sibling page. All other pointer map entries have already been taken
  66881. ** care of. */
  66882. for(i=0; i<nNew; i++){
  66883. u32 key = get4byte(&apNew[i]->aData[8]);
  66884. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  66885. }
  66886. }
  66887. assert( pParent->isInit );
  66888. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  66889. nOld, nNew, b.nCell));
  66890. /* Free any old pages that were not reused as new pages.
  66891. */
  66892. for(i=nNew; i<nOld; i++){
  66893. freePage(apOld[i], &rc);
  66894. }
  66895. #if 0
  66896. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  66897. /* The ptrmapCheckPages() contains assert() statements that verify that
  66898. ** all pointer map pages are set correctly. This is helpful while
  66899. ** debugging. This is usually disabled because a corrupt database may
  66900. ** cause an assert() statement to fail. */
  66901. ptrmapCheckPages(apNew, nNew);
  66902. ptrmapCheckPages(&pParent, 1);
  66903. }
  66904. #endif
  66905. /*
  66906. ** Cleanup before returning.
  66907. */
  66908. balance_cleanup:
  66909. sqlite3StackFree(0, b.apCell);
  66910. for(i=0; i<nOld; i++){
  66911. releasePage(apOld[i]);
  66912. }
  66913. for(i=0; i<nNew; i++){
  66914. releasePage(apNew[i]);
  66915. }
  66916. return rc;
  66917. }
  66918. /*
  66919. ** This function is called when the root page of a b-tree structure is
  66920. ** overfull (has one or more overflow pages).
  66921. **
  66922. ** A new child page is allocated and the contents of the current root
  66923. ** page, including overflow cells, are copied into the child. The root
  66924. ** page is then overwritten to make it an empty page with the right-child
  66925. ** pointer pointing to the new page.
  66926. **
  66927. ** Before returning, all pointer-map entries corresponding to pages
  66928. ** that the new child-page now contains pointers to are updated. The
  66929. ** entry corresponding to the new right-child pointer of the root
  66930. ** page is also updated.
  66931. **
  66932. ** If successful, *ppChild is set to contain a reference to the child
  66933. ** page and SQLITE_OK is returned. In this case the caller is required
  66934. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  66935. ** an error code is returned and *ppChild is set to 0.
  66936. */
  66937. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  66938. int rc; /* Return value from subprocedures */
  66939. MemPage *pChild = 0; /* Pointer to a new child page */
  66940. Pgno pgnoChild = 0; /* Page number of the new child page */
  66941. BtShared *pBt = pRoot->pBt; /* The BTree */
  66942. assert( pRoot->nOverflow>0 );
  66943. assert( sqlite3_mutex_held(pBt->mutex) );
  66944. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  66945. ** page that will become the new right-child of pPage. Copy the contents
  66946. ** of the node stored on pRoot into the new child page.
  66947. */
  66948. rc = sqlite3PagerWrite(pRoot->pDbPage);
  66949. if( rc==SQLITE_OK ){
  66950. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  66951. copyNodeContent(pRoot, pChild, &rc);
  66952. if( ISAUTOVACUUM ){
  66953. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  66954. }
  66955. }
  66956. if( rc ){
  66957. *ppChild = 0;
  66958. releasePage(pChild);
  66959. return rc;
  66960. }
  66961. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  66962. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  66963. assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
  66964. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  66965. /* Copy the overflow cells from pRoot to pChild */
  66966. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  66967. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  66968. memcpy(pChild->apOvfl, pRoot->apOvfl,
  66969. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  66970. pChild->nOverflow = pRoot->nOverflow;
  66971. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  66972. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  66973. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  66974. *ppChild = pChild;
  66975. return SQLITE_OK;
  66976. }
  66977. /*
  66978. ** The page that pCur currently points to has just been modified in
  66979. ** some way. This function figures out if this modification means the
  66980. ** tree needs to be balanced, and if so calls the appropriate balancing
  66981. ** routine. Balancing routines are:
  66982. **
  66983. ** balance_quick()
  66984. ** balance_deeper()
  66985. ** balance_nonroot()
  66986. */
  66987. static int balance(BtCursor *pCur){
  66988. int rc = SQLITE_OK;
  66989. const int nMin = pCur->pBt->usableSize * 2 / 3;
  66990. u8 aBalanceQuickSpace[13];
  66991. u8 *pFree = 0;
  66992. VVA_ONLY( int balance_quick_called = 0 );
  66993. VVA_ONLY( int balance_deeper_called = 0 );
  66994. do {
  66995. int iPage = pCur->iPage;
  66996. MemPage *pPage = pCur->pPage;
  66997. if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
  66998. if( iPage==0 ){
  66999. if( pPage->nOverflow ){
  67000. /* The root page of the b-tree is overfull. In this case call the
  67001. ** balance_deeper() function to create a new child for the root-page
  67002. ** and copy the current contents of the root-page to it. The
  67003. ** next iteration of the do-loop will balance the child page.
  67004. */
  67005. assert( balance_deeper_called==0 );
  67006. VVA_ONLY( balance_deeper_called++ );
  67007. rc = balance_deeper(pPage, &pCur->apPage[1]);
  67008. if( rc==SQLITE_OK ){
  67009. pCur->iPage = 1;
  67010. pCur->ix = 0;
  67011. pCur->aiIdx[0] = 0;
  67012. pCur->apPage[0] = pPage;
  67013. pCur->pPage = pCur->apPage[1];
  67014. assert( pCur->pPage->nOverflow );
  67015. }
  67016. }else{
  67017. break;
  67018. }
  67019. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  67020. break;
  67021. }else{
  67022. MemPage * const pParent = pCur->apPage[iPage-1];
  67023. int const iIdx = pCur->aiIdx[iPage-1];
  67024. rc = sqlite3PagerWrite(pParent->pDbPage);
  67025. if( rc==SQLITE_OK && pParent->nFree<0 ){
  67026. rc = btreeComputeFreeSpace(pParent);
  67027. }
  67028. if( rc==SQLITE_OK ){
  67029. #ifndef SQLITE_OMIT_QUICKBALANCE
  67030. if( pPage->intKeyLeaf
  67031. && pPage->nOverflow==1
  67032. && pPage->aiOvfl[0]==pPage->nCell
  67033. && pParent->pgno!=1
  67034. && pParent->nCell==iIdx
  67035. ){
  67036. /* Call balance_quick() to create a new sibling of pPage on which
  67037. ** to store the overflow cell. balance_quick() inserts a new cell
  67038. ** into pParent, which may cause pParent overflow. If this
  67039. ** happens, the next iteration of the do-loop will balance pParent
  67040. ** use either balance_nonroot() or balance_deeper(). Until this
  67041. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  67042. ** buffer.
  67043. **
  67044. ** The purpose of the following assert() is to check that only a
  67045. ** single call to balance_quick() is made for each call to this
  67046. ** function. If this were not verified, a subtle bug involving reuse
  67047. ** of the aBalanceQuickSpace[] might sneak in.
  67048. */
  67049. assert( balance_quick_called==0 );
  67050. VVA_ONLY( balance_quick_called++ );
  67051. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  67052. }else
  67053. #endif
  67054. {
  67055. /* In this case, call balance_nonroot() to redistribute cells
  67056. ** between pPage and up to 2 of its sibling pages. This involves
  67057. ** modifying the contents of pParent, which may cause pParent to
  67058. ** become overfull or underfull. The next iteration of the do-loop
  67059. ** will balance the parent page to correct this.
  67060. **
  67061. ** If the parent page becomes overfull, the overflow cell or cells
  67062. ** are stored in the pSpace buffer allocated immediately below.
  67063. ** A subsequent iteration of the do-loop will deal with this by
  67064. ** calling balance_nonroot() (balance_deeper() may be called first,
  67065. ** but it doesn't deal with overflow cells - just moves them to a
  67066. ** different page). Once this subsequent call to balance_nonroot()
  67067. ** has completed, it is safe to release the pSpace buffer used by
  67068. ** the previous call, as the overflow cell data will have been
  67069. ** copied either into the body of a database page or into the new
  67070. ** pSpace buffer passed to the latter call to balance_nonroot().
  67071. */
  67072. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  67073. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  67074. pCur->hints&BTREE_BULKLOAD);
  67075. if( pFree ){
  67076. /* If pFree is not NULL, it points to the pSpace buffer used
  67077. ** by a previous call to balance_nonroot(). Its contents are
  67078. ** now stored either on real database pages or within the
  67079. ** new pSpace buffer, so it may be safely freed here. */
  67080. sqlite3PageFree(pFree);
  67081. }
  67082. /* The pSpace buffer will be freed after the next call to
  67083. ** balance_nonroot(), or just before this function returns, whichever
  67084. ** comes first. */
  67085. pFree = pSpace;
  67086. }
  67087. }
  67088. pPage->nOverflow = 0;
  67089. /* The next iteration of the do-loop balances the parent page. */
  67090. releasePage(pPage);
  67091. pCur->iPage--;
  67092. assert( pCur->iPage>=0 );
  67093. pCur->pPage = pCur->apPage[pCur->iPage];
  67094. }
  67095. }while( rc==SQLITE_OK );
  67096. if( pFree ){
  67097. sqlite3PageFree(pFree);
  67098. }
  67099. return rc;
  67100. }
  67101. /* Overwrite content from pX into pDest. Only do the write if the
  67102. ** content is different from what is already there.
  67103. */
  67104. static int btreeOverwriteContent(
  67105. MemPage *pPage, /* MemPage on which writing will occur */
  67106. u8 *pDest, /* Pointer to the place to start writing */
  67107. const BtreePayload *pX, /* Source of data to write */
  67108. int iOffset, /* Offset of first byte to write */
  67109. int iAmt /* Number of bytes to be written */
  67110. ){
  67111. int nData = pX->nData - iOffset;
  67112. if( nData<=0 ){
  67113. /* Overwritting with zeros */
  67114. int i;
  67115. for(i=0; i<iAmt && pDest[i]==0; i++){}
  67116. if( i<iAmt ){
  67117. int rc = sqlite3PagerWrite(pPage->pDbPage);
  67118. if( rc ) return rc;
  67119. memset(pDest + i, 0, iAmt - i);
  67120. }
  67121. }else{
  67122. if( nData<iAmt ){
  67123. /* Mixed read data and zeros at the end. Make a recursive call
  67124. ** to write the zeros then fall through to write the real data */
  67125. int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
  67126. iAmt-nData);
  67127. if( rc ) return rc;
  67128. iAmt = nData;
  67129. }
  67130. if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
  67131. int rc = sqlite3PagerWrite(pPage->pDbPage);
  67132. if( rc ) return rc;
  67133. /* In a corrupt database, it is possible for the source and destination
  67134. ** buffers to overlap. This is harmless since the database is already
  67135. ** corrupt but it does cause valgrind and ASAN warnings. So use
  67136. ** memmove(). */
  67137. memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
  67138. }
  67139. }
  67140. return SQLITE_OK;
  67141. }
  67142. /*
  67143. ** Overwrite the cell that cursor pCur is pointing to with fresh content
  67144. ** contained in pX.
  67145. */
  67146. static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
  67147. int iOffset; /* Next byte of pX->pData to write */
  67148. int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
  67149. int rc; /* Return code */
  67150. MemPage *pPage = pCur->pPage; /* Page being written */
  67151. BtShared *pBt; /* Btree */
  67152. Pgno ovflPgno; /* Next overflow page to write */
  67153. u32 ovflPageSize; /* Size to write on overflow page */
  67154. if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd ){
  67155. return SQLITE_CORRUPT_BKPT;
  67156. }
  67157. /* Overwrite the local portion first */
  67158. rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
  67159. 0, pCur->info.nLocal);
  67160. if( rc ) return rc;
  67161. if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
  67162. /* Now overwrite the overflow pages */
  67163. iOffset = pCur->info.nLocal;
  67164. assert( nTotal>=0 );
  67165. assert( iOffset>=0 );
  67166. ovflPgno = get4byte(pCur->info.pPayload + iOffset);
  67167. pBt = pPage->pBt;
  67168. ovflPageSize = pBt->usableSize - 4;
  67169. do{
  67170. rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
  67171. if( rc ) return rc;
  67172. if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
  67173. rc = SQLITE_CORRUPT_BKPT;
  67174. }else{
  67175. if( iOffset+ovflPageSize<(u32)nTotal ){
  67176. ovflPgno = get4byte(pPage->aData);
  67177. }else{
  67178. ovflPageSize = nTotal - iOffset;
  67179. }
  67180. rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
  67181. iOffset, ovflPageSize);
  67182. }
  67183. sqlite3PagerUnref(pPage->pDbPage);
  67184. if( rc ) return rc;
  67185. iOffset += ovflPageSize;
  67186. }while( iOffset<nTotal );
  67187. return SQLITE_OK;
  67188. }
  67189. /*
  67190. ** Insert a new record into the BTree. The content of the new record
  67191. ** is described by the pX object. The pCur cursor is used only to
  67192. ** define what table the record should be inserted into, and is left
  67193. ** pointing at a random location.
  67194. **
  67195. ** For a table btree (used for rowid tables), only the pX.nKey value of
  67196. ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
  67197. ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
  67198. ** hold the content of the row.
  67199. **
  67200. ** For an index btree (used for indexes and WITHOUT ROWID tables), the
  67201. ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
  67202. ** pX.pData,nData,nZero fields must be zero.
  67203. **
  67204. ** If the seekResult parameter is non-zero, then a successful call to
  67205. ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
  67206. ** been performed. In other words, if seekResult!=0 then the cursor
  67207. ** is currently pointing to a cell that will be adjacent to the cell
  67208. ** to be inserted. If seekResult<0 then pCur points to a cell that is
  67209. ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
  67210. ** that is larger than (pKey,nKey).
  67211. **
  67212. ** If seekResult==0, that means pCur is pointing at some unknown location.
  67213. ** In that case, this routine must seek the cursor to the correct insertion
  67214. ** point for (pKey,nKey) before doing the insertion. For index btrees,
  67215. ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
  67216. ** key values and pX->aMem can be used instead of pX->pKey to avoid having
  67217. ** to decode the key.
  67218. */
  67219. SQLITE_PRIVATE int sqlite3BtreeInsert(
  67220. BtCursor *pCur, /* Insert data into the table of this cursor */
  67221. const BtreePayload *pX, /* Content of the row to be inserted */
  67222. int flags, /* True if this is likely an append */
  67223. int seekResult /* Result of prior MovetoUnpacked() call */
  67224. ){
  67225. int rc;
  67226. int loc = seekResult; /* -1: before desired location +1: after */
  67227. int szNew = 0;
  67228. int idx;
  67229. MemPage *pPage;
  67230. Btree *p = pCur->pBtree;
  67231. BtShared *pBt = p->pBt;
  67232. unsigned char *oldCell;
  67233. unsigned char *newCell = 0;
  67234. assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
  67235. if( pCur->eState==CURSOR_FAULT ){
  67236. assert( pCur->skipNext!=SQLITE_OK );
  67237. return pCur->skipNext;
  67238. }
  67239. assert( cursorOwnsBtShared(pCur) );
  67240. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  67241. && pBt->inTransaction==TRANS_WRITE
  67242. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  67243. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  67244. /* Assert that the caller has been consistent. If this cursor was opened
  67245. ** expecting an index b-tree, then the caller should be inserting blob
  67246. ** keys with no associated data. If the cursor was opened expecting an
  67247. ** intkey table, the caller should be inserting integer keys with a
  67248. ** blob of associated data. */
  67249. assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
  67250. /* Save the positions of any other cursors open on this table.
  67251. **
  67252. ** In some cases, the call to btreeMoveto() below is a no-op. For
  67253. ** example, when inserting data into a table with auto-generated integer
  67254. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  67255. ** integer key to use. It then calls this function to actually insert the
  67256. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  67257. ** that the cursor is already where it needs to be and returns without
  67258. ** doing any work. To avoid thwarting these optimizations, it is important
  67259. ** not to clear the cursor here.
  67260. */
  67261. if( pCur->curFlags & BTCF_Multiple ){
  67262. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  67263. if( rc ) return rc;
  67264. }
  67265. if( pCur->pKeyInfo==0 ){
  67266. assert( pX->pKey==0 );
  67267. /* If this is an insert into a table b-tree, invalidate any incrblob
  67268. ** cursors open on the row being replaced */
  67269. invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
  67270. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  67271. ** to a row with the same key as the new entry being inserted.
  67272. */
  67273. #ifdef SQLITE_DEBUG
  67274. if( flags & BTREE_SAVEPOSITION ){
  67275. assert( pCur->curFlags & BTCF_ValidNKey );
  67276. assert( pX->nKey==pCur->info.nKey );
  67277. assert( pCur->info.nSize!=0 );
  67278. assert( loc==0 );
  67279. }
  67280. #endif
  67281. /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
  67282. ** that the cursor is not pointing to a row to be overwritten.
  67283. ** So do a complete check.
  67284. */
  67285. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
  67286. /* The cursor is pointing to the entry that is to be
  67287. ** overwritten */
  67288. assert( pX->nData>=0 && pX->nZero>=0 );
  67289. if( pCur->info.nSize!=0
  67290. && pCur->info.nPayload==(u32)pX->nData+pX->nZero
  67291. ){
  67292. /* New entry is the same size as the old. Do an overwrite */
  67293. return btreeOverwriteCell(pCur, pX);
  67294. }
  67295. assert( loc==0 );
  67296. }else if( loc==0 ){
  67297. /* The cursor is *not* pointing to the cell to be overwritten, nor
  67298. ** to an adjacent cell. Move the cursor so that it is pointing either
  67299. ** to the cell to be overwritten or an adjacent cell.
  67300. */
  67301. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
  67302. if( rc ) return rc;
  67303. }
  67304. }else{
  67305. /* This is an index or a WITHOUT ROWID table */
  67306. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  67307. ** to a row with the same key as the new entry being inserted.
  67308. */
  67309. assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
  67310. /* If the cursor is not already pointing either to the cell to be
  67311. ** overwritten, or if a new cell is being inserted, if the cursor is
  67312. ** not pointing to an immediately adjacent cell, then move the cursor
  67313. ** so that it does.
  67314. */
  67315. if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
  67316. if( pX->nMem ){
  67317. UnpackedRecord r;
  67318. r.pKeyInfo = pCur->pKeyInfo;
  67319. r.aMem = pX->aMem;
  67320. r.nField = pX->nMem;
  67321. r.default_rc = 0;
  67322. r.errCode = 0;
  67323. r.r1 = 0;
  67324. r.r2 = 0;
  67325. r.eqSeen = 0;
  67326. rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
  67327. }else{
  67328. rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
  67329. }
  67330. if( rc ) return rc;
  67331. }
  67332. /* If the cursor is currently pointing to an entry to be overwritten
  67333. ** and the new content is the same as as the old, then use the
  67334. ** overwrite optimization.
  67335. */
  67336. if( loc==0 ){
  67337. getCellInfo(pCur);
  67338. if( pCur->info.nKey==pX->nKey ){
  67339. BtreePayload x2;
  67340. x2.pData = pX->pKey;
  67341. x2.nData = pX->nKey;
  67342. x2.nZero = 0;
  67343. return btreeOverwriteCell(pCur, &x2);
  67344. }
  67345. }
  67346. }
  67347. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  67348. pPage = pCur->pPage;
  67349. assert( pPage->intKey || pX->nKey>=0 );
  67350. assert( pPage->leaf || !pPage->intKey );
  67351. if( pPage->nFree<0 ){
  67352. rc = btreeComputeFreeSpace(pPage);
  67353. if( rc ) return rc;
  67354. }
  67355. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  67356. pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
  67357. loc==0 ? "overwrite" : "new entry"));
  67358. assert( pPage->isInit );
  67359. newCell = pBt->pTmpSpace;
  67360. assert( newCell!=0 );
  67361. rc = fillInCell(pPage, newCell, pX, &szNew);
  67362. if( rc ) goto end_insert;
  67363. assert( szNew==pPage->xCellSize(pPage, newCell) );
  67364. assert( szNew <= MX_CELL_SIZE(pBt) );
  67365. idx = pCur->ix;
  67366. if( loc==0 ){
  67367. CellInfo info;
  67368. assert( idx<pPage->nCell );
  67369. rc = sqlite3PagerWrite(pPage->pDbPage);
  67370. if( rc ){
  67371. goto end_insert;
  67372. }
  67373. oldCell = findCell(pPage, idx);
  67374. if( !pPage->leaf ){
  67375. memcpy(newCell, oldCell, 4);
  67376. }
  67377. rc = clearCell(pPage, oldCell, &info);
  67378. if( info.nSize==szNew && info.nLocal==info.nPayload
  67379. && (!ISAUTOVACUUM || szNew<pPage->minLocal)
  67380. ){
  67381. /* Overwrite the old cell with the new if they are the same size.
  67382. ** We could also try to do this if the old cell is smaller, then add
  67383. ** the leftover space to the free list. But experiments show that
  67384. ** doing that is no faster then skipping this optimization and just
  67385. ** calling dropCell() and insertCell().
  67386. **
  67387. ** This optimization cannot be used on an autovacuum database if the
  67388. ** new entry uses overflow pages, as the insertCell() call below is
  67389. ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
  67390. assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
  67391. if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  67392. memcpy(oldCell, newCell, szNew);
  67393. return SQLITE_OK;
  67394. }
  67395. dropCell(pPage, idx, info.nSize, &rc);
  67396. if( rc ) goto end_insert;
  67397. }else if( loc<0 && pPage->nCell>0 ){
  67398. assert( pPage->leaf );
  67399. idx = ++pCur->ix;
  67400. pCur->curFlags &= ~BTCF_ValidNKey;
  67401. }else{
  67402. assert( pPage->leaf );
  67403. }
  67404. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  67405. assert( pPage->nOverflow==0 || rc==SQLITE_OK );
  67406. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  67407. /* If no error has occurred and pPage has an overflow cell, call balance()
  67408. ** to redistribute the cells within the tree. Since balance() may move
  67409. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  67410. ** variables.
  67411. **
  67412. ** Previous versions of SQLite called moveToRoot() to move the cursor
  67413. ** back to the root page as balance() used to invalidate the contents
  67414. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  67415. ** set the cursor state to "invalid". This makes common insert operations
  67416. ** slightly faster.
  67417. **
  67418. ** There is a subtle but important optimization here too. When inserting
  67419. ** multiple records into an intkey b-tree using a single cursor (as can
  67420. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  67421. ** is advantageous to leave the cursor pointing to the last entry in
  67422. ** the b-tree if possible. If the cursor is left pointing to the last
  67423. ** entry in the table, and the next row inserted has an integer key
  67424. ** larger than the largest existing key, it is possible to insert the
  67425. ** row without seeking the cursor. This can be a big performance boost.
  67426. */
  67427. pCur->info.nSize = 0;
  67428. if( pPage->nOverflow ){
  67429. assert( rc==SQLITE_OK );
  67430. pCur->curFlags &= ~(BTCF_ValidNKey);
  67431. rc = balance(pCur);
  67432. /* Must make sure nOverflow is reset to zero even if the balance()
  67433. ** fails. Internal data structure corruption will result otherwise.
  67434. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  67435. ** from trying to save the current position of the cursor. */
  67436. pCur->pPage->nOverflow = 0;
  67437. pCur->eState = CURSOR_INVALID;
  67438. if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
  67439. btreeReleaseAllCursorPages(pCur);
  67440. if( pCur->pKeyInfo ){
  67441. assert( pCur->pKey==0 );
  67442. pCur->pKey = sqlite3Malloc( pX->nKey );
  67443. if( pCur->pKey==0 ){
  67444. rc = SQLITE_NOMEM;
  67445. }else{
  67446. memcpy(pCur->pKey, pX->pKey, pX->nKey);
  67447. }
  67448. }
  67449. pCur->eState = CURSOR_REQUIRESEEK;
  67450. pCur->nKey = pX->nKey;
  67451. }
  67452. }
  67453. assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
  67454. end_insert:
  67455. return rc;
  67456. }
  67457. /*
  67458. ** Delete the entry that the cursor is pointing to.
  67459. **
  67460. ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
  67461. ** the cursor is left pointing at an arbitrary location after the delete.
  67462. ** But if that bit is set, then the cursor is left in a state such that
  67463. ** the next call to BtreeNext() or BtreePrev() moves it to the same row
  67464. ** as it would have been on if the call to BtreeDelete() had been omitted.
  67465. **
  67466. ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
  67467. ** associated with a single table entry and its indexes. Only one of those
  67468. ** deletes is considered the "primary" delete. The primary delete occurs
  67469. ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
  67470. ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
  67471. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
  67472. ** but which might be used by alternative storage engines.
  67473. */
  67474. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
  67475. Btree *p = pCur->pBtree;
  67476. BtShared *pBt = p->pBt;
  67477. int rc; /* Return code */
  67478. MemPage *pPage; /* Page to delete cell from */
  67479. unsigned char *pCell; /* Pointer to cell to delete */
  67480. int iCellIdx; /* Index of cell to delete */
  67481. int iCellDepth; /* Depth of node containing pCell */
  67482. CellInfo info; /* Size of the cell being deleted */
  67483. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  67484. u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
  67485. assert( cursorOwnsBtShared(pCur) );
  67486. assert( pBt->inTransaction==TRANS_WRITE );
  67487. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  67488. assert( pCur->curFlags & BTCF_WriteFlag );
  67489. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  67490. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  67491. assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
  67492. if( pCur->eState==CURSOR_REQUIRESEEK ){
  67493. rc = btreeRestoreCursorPosition(pCur);
  67494. if( rc ) return rc;
  67495. }
  67496. assert( pCur->eState==CURSOR_VALID );
  67497. iCellDepth = pCur->iPage;
  67498. iCellIdx = pCur->ix;
  67499. pPage = pCur->pPage;
  67500. pCell = findCell(pPage, iCellIdx);
  67501. if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT;
  67502. /* If the bPreserve flag is set to true, then the cursor position must
  67503. ** be preserved following this delete operation. If the current delete
  67504. ** will cause a b-tree rebalance, then this is done by saving the cursor
  67505. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  67506. ** returning.
  67507. **
  67508. ** Or, if the current delete will not cause a rebalance, then the cursor
  67509. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  67510. ** before or after the deleted entry. In this case set bSkipnext to true. */
  67511. if( bPreserve ){
  67512. if( !pPage->leaf
  67513. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  67514. || pPage->nCell==1 /* See dbfuzz001.test for a test case */
  67515. ){
  67516. /* A b-tree rebalance will be required after deleting this entry.
  67517. ** Save the cursor key. */
  67518. rc = saveCursorKey(pCur);
  67519. if( rc ) return rc;
  67520. }else{
  67521. bSkipnext = 1;
  67522. }
  67523. }
  67524. /* If the page containing the entry to delete is not a leaf page, move
  67525. ** the cursor to the largest entry in the tree that is smaller than
  67526. ** the entry being deleted. This cell will replace the cell being deleted
  67527. ** from the internal node. The 'previous' entry is used for this instead
  67528. ** of the 'next' entry, as the previous entry is always a part of the
  67529. ** sub-tree headed by the child page of the cell being deleted. This makes
  67530. ** balancing the tree following the delete operation easier. */
  67531. if( !pPage->leaf ){
  67532. rc = sqlite3BtreePrevious(pCur, 0);
  67533. assert( rc!=SQLITE_DONE );
  67534. if( rc ) return rc;
  67535. }
  67536. /* Save the positions of any other cursors open on this table before
  67537. ** making any modifications. */
  67538. if( pCur->curFlags & BTCF_Multiple ){
  67539. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  67540. if( rc ) return rc;
  67541. }
  67542. /* If this is a delete operation to remove a row from a table b-tree,
  67543. ** invalidate any incrblob cursors open on the row being deleted. */
  67544. if( pCur->pKeyInfo==0 ){
  67545. invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
  67546. }
  67547. /* Make the page containing the entry to be deleted writable. Then free any
  67548. ** overflow pages associated with the entry and finally remove the cell
  67549. ** itself from within the page. */
  67550. rc = sqlite3PagerWrite(pPage->pDbPage);
  67551. if( rc ) return rc;
  67552. rc = clearCell(pPage, pCell, &info);
  67553. dropCell(pPage, iCellIdx, info.nSize, &rc);
  67554. if( rc ) return rc;
  67555. /* If the cell deleted was not located on a leaf page, then the cursor
  67556. ** is currently pointing to the largest entry in the sub-tree headed
  67557. ** by the child-page of the cell that was just deleted from an internal
  67558. ** node. The cell from the leaf node needs to be moved to the internal
  67559. ** node to replace the deleted cell. */
  67560. if( !pPage->leaf ){
  67561. MemPage *pLeaf = pCur->pPage;
  67562. int nCell;
  67563. Pgno n;
  67564. unsigned char *pTmp;
  67565. if( pLeaf->nFree<0 ){
  67566. rc = btreeComputeFreeSpace(pLeaf);
  67567. if( rc ) return rc;
  67568. }
  67569. if( iCellDepth<pCur->iPage-1 ){
  67570. n = pCur->apPage[iCellDepth+1]->pgno;
  67571. }else{
  67572. n = pCur->pPage->pgno;
  67573. }
  67574. pCell = findCell(pLeaf, pLeaf->nCell-1);
  67575. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  67576. nCell = pLeaf->xCellSize(pLeaf, pCell);
  67577. assert( MX_CELL_SIZE(pBt) >= nCell );
  67578. pTmp = pBt->pTmpSpace;
  67579. assert( pTmp!=0 );
  67580. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  67581. if( rc==SQLITE_OK ){
  67582. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  67583. }
  67584. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  67585. if( rc ) return rc;
  67586. }
  67587. /* Balance the tree. If the entry deleted was located on a leaf page,
  67588. ** then the cursor still points to that page. In this case the first
  67589. ** call to balance() repairs the tree, and the if(...) condition is
  67590. ** never true.
  67591. **
  67592. ** Otherwise, if the entry deleted was on an internal node page, then
  67593. ** pCur is pointing to the leaf page from which a cell was removed to
  67594. ** replace the cell deleted from the internal node. This is slightly
  67595. ** tricky as the leaf node may be underfull, and the internal node may
  67596. ** be either under or overfull. In this case run the balancing algorithm
  67597. ** on the leaf node first. If the balance proceeds far enough up the
  67598. ** tree that we can be sure that any problem in the internal node has
  67599. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  67600. ** walk the cursor up the tree to the internal node and balance it as
  67601. ** well. */
  67602. rc = balance(pCur);
  67603. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  67604. releasePageNotNull(pCur->pPage);
  67605. pCur->iPage--;
  67606. while( pCur->iPage>iCellDepth ){
  67607. releasePage(pCur->apPage[pCur->iPage--]);
  67608. }
  67609. pCur->pPage = pCur->apPage[pCur->iPage];
  67610. rc = balance(pCur);
  67611. }
  67612. if( rc==SQLITE_OK ){
  67613. if( bSkipnext ){
  67614. assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
  67615. assert( pPage==pCur->pPage || CORRUPT_DB );
  67616. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  67617. pCur->eState = CURSOR_SKIPNEXT;
  67618. if( iCellIdx>=pPage->nCell ){
  67619. pCur->skipNext = -1;
  67620. pCur->ix = pPage->nCell-1;
  67621. }else{
  67622. pCur->skipNext = 1;
  67623. }
  67624. }else{
  67625. rc = moveToRoot(pCur);
  67626. if( bPreserve ){
  67627. btreeReleaseAllCursorPages(pCur);
  67628. pCur->eState = CURSOR_REQUIRESEEK;
  67629. }
  67630. if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
  67631. }
  67632. }
  67633. return rc;
  67634. }
  67635. /*
  67636. ** Create a new BTree table. Write into *piTable the page
  67637. ** number for the root page of the new table.
  67638. **
  67639. ** The type of type is determined by the flags parameter. Only the
  67640. ** following values of flags are currently in use. Other values for
  67641. ** flags might not work:
  67642. **
  67643. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  67644. ** BTREE_ZERODATA Used for SQL indices
  67645. */
  67646. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  67647. BtShared *pBt = p->pBt;
  67648. MemPage *pRoot;
  67649. Pgno pgnoRoot;
  67650. int rc;
  67651. int ptfFlags; /* Page-type flage for the root page of new table */
  67652. assert( sqlite3BtreeHoldsMutex(p) );
  67653. assert( pBt->inTransaction==TRANS_WRITE );
  67654. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  67655. #ifdef SQLITE_OMIT_AUTOVACUUM
  67656. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  67657. if( rc ){
  67658. return rc;
  67659. }
  67660. #else
  67661. if( pBt->autoVacuum ){
  67662. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  67663. MemPage *pPageMove; /* The page to move to. */
  67664. /* Creating a new table may probably require moving an existing database
  67665. ** to make room for the new tables root page. In case this page turns
  67666. ** out to be an overflow page, delete all overflow page-map caches
  67667. ** held by open cursors.
  67668. */
  67669. invalidateAllOverflowCache(pBt);
  67670. /* Read the value of meta[3] from the database to determine where the
  67671. ** root page of the new table should go. meta[3] is the largest root-page
  67672. ** created so far, so the new root-page is (meta[3]+1).
  67673. */
  67674. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  67675. pgnoRoot++;
  67676. /* The new root-page may not be allocated on a pointer-map page, or the
  67677. ** PENDING_BYTE page.
  67678. */
  67679. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  67680. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  67681. pgnoRoot++;
  67682. }
  67683. assert( pgnoRoot>=3 || CORRUPT_DB );
  67684. testcase( pgnoRoot<3 );
  67685. /* Allocate a page. The page that currently resides at pgnoRoot will
  67686. ** be moved to the allocated page (unless the allocated page happens
  67687. ** to reside at pgnoRoot).
  67688. */
  67689. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  67690. if( rc!=SQLITE_OK ){
  67691. return rc;
  67692. }
  67693. if( pgnoMove!=pgnoRoot ){
  67694. /* pgnoRoot is the page that will be used for the root-page of
  67695. ** the new table (assuming an error did not occur). But we were
  67696. ** allocated pgnoMove. If required (i.e. if it was not allocated
  67697. ** by extending the file), the current page at position pgnoMove
  67698. ** is already journaled.
  67699. */
  67700. u8 eType = 0;
  67701. Pgno iPtrPage = 0;
  67702. /* Save the positions of any open cursors. This is required in
  67703. ** case they are holding a reference to an xFetch reference
  67704. ** corresponding to page pgnoRoot. */
  67705. rc = saveAllCursors(pBt, 0, 0);
  67706. releasePage(pPageMove);
  67707. if( rc!=SQLITE_OK ){
  67708. return rc;
  67709. }
  67710. /* Move the page currently at pgnoRoot to pgnoMove. */
  67711. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  67712. if( rc!=SQLITE_OK ){
  67713. return rc;
  67714. }
  67715. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  67716. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  67717. rc = SQLITE_CORRUPT_BKPT;
  67718. }
  67719. if( rc!=SQLITE_OK ){
  67720. releasePage(pRoot);
  67721. return rc;
  67722. }
  67723. assert( eType!=PTRMAP_ROOTPAGE );
  67724. assert( eType!=PTRMAP_FREEPAGE );
  67725. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  67726. releasePage(pRoot);
  67727. /* Obtain the page at pgnoRoot */
  67728. if( rc!=SQLITE_OK ){
  67729. return rc;
  67730. }
  67731. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  67732. if( rc!=SQLITE_OK ){
  67733. return rc;
  67734. }
  67735. rc = sqlite3PagerWrite(pRoot->pDbPage);
  67736. if( rc!=SQLITE_OK ){
  67737. releasePage(pRoot);
  67738. return rc;
  67739. }
  67740. }else{
  67741. pRoot = pPageMove;
  67742. }
  67743. /* Update the pointer-map and meta-data with the new root-page number. */
  67744. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  67745. if( rc ){
  67746. releasePage(pRoot);
  67747. return rc;
  67748. }
  67749. /* When the new root page was allocated, page 1 was made writable in
  67750. ** order either to increase the database filesize, or to decrement the
  67751. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  67752. */
  67753. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  67754. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  67755. if( NEVER(rc) ){
  67756. releasePage(pRoot);
  67757. return rc;
  67758. }
  67759. }else{
  67760. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  67761. if( rc ) return rc;
  67762. }
  67763. #endif
  67764. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  67765. if( createTabFlags & BTREE_INTKEY ){
  67766. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  67767. }else{
  67768. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  67769. }
  67770. zeroPage(pRoot, ptfFlags);
  67771. sqlite3PagerUnref(pRoot->pDbPage);
  67772. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  67773. *piTable = (int)pgnoRoot;
  67774. return SQLITE_OK;
  67775. }
  67776. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  67777. int rc;
  67778. sqlite3BtreeEnter(p);
  67779. rc = btreeCreateTable(p, piTable, flags);
  67780. sqlite3BtreeLeave(p);
  67781. return rc;
  67782. }
  67783. /*
  67784. ** Erase the given database page and all its children. Return
  67785. ** the page to the freelist.
  67786. */
  67787. static int clearDatabasePage(
  67788. BtShared *pBt, /* The BTree that contains the table */
  67789. Pgno pgno, /* Page number to clear */
  67790. int freePageFlag, /* Deallocate page if true */
  67791. int *pnChange /* Add number of Cells freed to this counter */
  67792. ){
  67793. MemPage *pPage;
  67794. int rc;
  67795. unsigned char *pCell;
  67796. int i;
  67797. int hdr;
  67798. CellInfo info;
  67799. assert( sqlite3_mutex_held(pBt->mutex) );
  67800. if( pgno>btreePagecount(pBt) ){
  67801. return SQLITE_CORRUPT_BKPT;
  67802. }
  67803. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  67804. if( rc ) return rc;
  67805. if( pPage->bBusy ){
  67806. rc = SQLITE_CORRUPT_BKPT;
  67807. goto cleardatabasepage_out;
  67808. }
  67809. pPage->bBusy = 1;
  67810. hdr = pPage->hdrOffset;
  67811. for(i=0; i<pPage->nCell; i++){
  67812. pCell = findCell(pPage, i);
  67813. if( !pPage->leaf ){
  67814. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  67815. if( rc ) goto cleardatabasepage_out;
  67816. }
  67817. rc = clearCell(pPage, pCell, &info);
  67818. if( rc ) goto cleardatabasepage_out;
  67819. }
  67820. if( !pPage->leaf ){
  67821. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  67822. if( rc ) goto cleardatabasepage_out;
  67823. }else if( pnChange ){
  67824. assert( pPage->intKey || CORRUPT_DB );
  67825. testcase( !pPage->intKey );
  67826. *pnChange += pPage->nCell;
  67827. }
  67828. if( freePageFlag ){
  67829. freePage(pPage, &rc);
  67830. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  67831. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  67832. }
  67833. cleardatabasepage_out:
  67834. pPage->bBusy = 0;
  67835. releasePage(pPage);
  67836. return rc;
  67837. }
  67838. /*
  67839. ** Delete all information from a single table in the database. iTable is
  67840. ** the page number of the root of the table. After this routine returns,
  67841. ** the root page is empty, but still exists.
  67842. **
  67843. ** This routine will fail with SQLITE_LOCKED if there are any open
  67844. ** read cursors on the table. Open write cursors are moved to the
  67845. ** root of the table.
  67846. **
  67847. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  67848. ** integer value pointed to by pnChange is incremented by the number of
  67849. ** entries in the table.
  67850. */
  67851. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  67852. int rc;
  67853. BtShared *pBt = p->pBt;
  67854. sqlite3BtreeEnter(p);
  67855. assert( p->inTrans==TRANS_WRITE );
  67856. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  67857. if( SQLITE_OK==rc ){
  67858. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  67859. ** is the root of a table b-tree - if it is not, the following call is
  67860. ** a no-op). */
  67861. invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
  67862. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  67863. }
  67864. sqlite3BtreeLeave(p);
  67865. return rc;
  67866. }
  67867. /*
  67868. ** Delete all information from the single table that pCur is open on.
  67869. **
  67870. ** This routine only work for pCur on an ephemeral table.
  67871. */
  67872. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  67873. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  67874. }
  67875. /*
  67876. ** Erase all information in a table and add the root of the table to
  67877. ** the freelist. Except, the root of the principle table (the one on
  67878. ** page 1) is never added to the freelist.
  67879. **
  67880. ** This routine will fail with SQLITE_LOCKED if there are any open
  67881. ** cursors on the table.
  67882. **
  67883. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  67884. ** root page in the database file, then the last root page
  67885. ** in the database file is moved into the slot formerly occupied by
  67886. ** iTable and that last slot formerly occupied by the last root page
  67887. ** is added to the freelist instead of iTable. In this say, all
  67888. ** root pages are kept at the beginning of the database file, which
  67889. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  67890. ** page number that used to be the last root page in the file before
  67891. ** the move. If no page gets moved, *piMoved is set to 0.
  67892. ** The last root page is recorded in meta[3] and the value of
  67893. ** meta[3] is updated by this procedure.
  67894. */
  67895. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  67896. int rc;
  67897. MemPage *pPage = 0;
  67898. BtShared *pBt = p->pBt;
  67899. assert( sqlite3BtreeHoldsMutex(p) );
  67900. assert( p->inTrans==TRANS_WRITE );
  67901. assert( iTable>=2 );
  67902. if( iTable>btreePagecount(pBt) ){
  67903. return SQLITE_CORRUPT_BKPT;
  67904. }
  67905. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  67906. if( rc ) return rc;
  67907. rc = sqlite3BtreeClearTable(p, iTable, 0);
  67908. if( rc ){
  67909. releasePage(pPage);
  67910. return rc;
  67911. }
  67912. *piMoved = 0;
  67913. #ifdef SQLITE_OMIT_AUTOVACUUM
  67914. freePage(pPage, &rc);
  67915. releasePage(pPage);
  67916. #else
  67917. if( pBt->autoVacuum ){
  67918. Pgno maxRootPgno;
  67919. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  67920. if( iTable==maxRootPgno ){
  67921. /* If the table being dropped is the table with the largest root-page
  67922. ** number in the database, put the root page on the free list.
  67923. */
  67924. freePage(pPage, &rc);
  67925. releasePage(pPage);
  67926. if( rc!=SQLITE_OK ){
  67927. return rc;
  67928. }
  67929. }else{
  67930. /* The table being dropped does not have the largest root-page
  67931. ** number in the database. So move the page that does into the
  67932. ** gap left by the deleted root-page.
  67933. */
  67934. MemPage *pMove;
  67935. releasePage(pPage);
  67936. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  67937. if( rc!=SQLITE_OK ){
  67938. return rc;
  67939. }
  67940. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  67941. releasePage(pMove);
  67942. if( rc!=SQLITE_OK ){
  67943. return rc;
  67944. }
  67945. pMove = 0;
  67946. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  67947. freePage(pMove, &rc);
  67948. releasePage(pMove);
  67949. if( rc!=SQLITE_OK ){
  67950. return rc;
  67951. }
  67952. *piMoved = maxRootPgno;
  67953. }
  67954. /* Set the new 'max-root-page' value in the database header. This
  67955. ** is the old value less one, less one more if that happens to
  67956. ** be a root-page number, less one again if that is the
  67957. ** PENDING_BYTE_PAGE.
  67958. */
  67959. maxRootPgno--;
  67960. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  67961. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  67962. maxRootPgno--;
  67963. }
  67964. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  67965. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  67966. }else{
  67967. freePage(pPage, &rc);
  67968. releasePage(pPage);
  67969. }
  67970. #endif
  67971. return rc;
  67972. }
  67973. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  67974. int rc;
  67975. sqlite3BtreeEnter(p);
  67976. rc = btreeDropTable(p, iTable, piMoved);
  67977. sqlite3BtreeLeave(p);
  67978. return rc;
  67979. }
  67980. /*
  67981. ** This function may only be called if the b-tree connection already
  67982. ** has a read or write transaction open on the database.
  67983. **
  67984. ** Read the meta-information out of a database file. Meta[0]
  67985. ** is the number of free pages currently in the database. Meta[1]
  67986. ** through meta[15] are available for use by higher layers. Meta[0]
  67987. ** is read-only, the others are read/write.
  67988. **
  67989. ** The schema layer numbers meta values differently. At the schema
  67990. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  67991. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  67992. **
  67993. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  67994. ** of reading the value out of the header, it instead loads the "DataVersion"
  67995. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  67996. ** database file. It is a number computed by the pager. But its access
  67997. ** pattern is the same as header meta values, and so it is convenient to
  67998. ** read it from this routine.
  67999. */
  68000. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  68001. BtShared *pBt = p->pBt;
  68002. sqlite3BtreeEnter(p);
  68003. assert( p->inTrans>TRANS_NONE );
  68004. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  68005. assert( pBt->pPage1 );
  68006. assert( idx>=0 && idx<=15 );
  68007. if( idx==BTREE_DATA_VERSION ){
  68008. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  68009. }else{
  68010. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  68011. }
  68012. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  68013. ** database, mark the database as read-only. */
  68014. #ifdef SQLITE_OMIT_AUTOVACUUM
  68015. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  68016. pBt->btsFlags |= BTS_READ_ONLY;
  68017. }
  68018. #endif
  68019. sqlite3BtreeLeave(p);
  68020. }
  68021. /*
  68022. ** Write meta-information back into the database. Meta[0] is
  68023. ** read-only and may not be written.
  68024. */
  68025. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  68026. BtShared *pBt = p->pBt;
  68027. unsigned char *pP1;
  68028. int rc;
  68029. assert( idx>=1 && idx<=15 );
  68030. sqlite3BtreeEnter(p);
  68031. assert( p->inTrans==TRANS_WRITE );
  68032. assert( pBt->pPage1!=0 );
  68033. pP1 = pBt->pPage1->aData;
  68034. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  68035. if( rc==SQLITE_OK ){
  68036. put4byte(&pP1[36 + idx*4], iMeta);
  68037. #ifndef SQLITE_OMIT_AUTOVACUUM
  68038. if( idx==BTREE_INCR_VACUUM ){
  68039. assert( pBt->autoVacuum || iMeta==0 );
  68040. assert( iMeta==0 || iMeta==1 );
  68041. pBt->incrVacuum = (u8)iMeta;
  68042. }
  68043. #endif
  68044. }
  68045. sqlite3BtreeLeave(p);
  68046. return rc;
  68047. }
  68048. #ifndef SQLITE_OMIT_BTREECOUNT
  68049. /*
  68050. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  68051. ** number of entries in the b-tree and write the result to *pnEntry.
  68052. **
  68053. ** SQLITE_OK is returned if the operation is successfully executed.
  68054. ** Otherwise, if an error is encountered (i.e. an IO error or database
  68055. ** corruption) an SQLite error code is returned.
  68056. */
  68057. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  68058. i64 nEntry = 0; /* Value to return in *pnEntry */
  68059. int rc; /* Return code */
  68060. rc = moveToRoot(pCur);
  68061. if( rc==SQLITE_EMPTY ){
  68062. *pnEntry = 0;
  68063. return SQLITE_OK;
  68064. }
  68065. /* Unless an error occurs, the following loop runs one iteration for each
  68066. ** page in the B-Tree structure (not including overflow pages).
  68067. */
  68068. while( rc==SQLITE_OK ){
  68069. int iIdx; /* Index of child node in parent */
  68070. MemPage *pPage; /* Current page of the b-tree */
  68071. /* If this is a leaf page or the tree is not an int-key tree, then
  68072. ** this page contains countable entries. Increment the entry counter
  68073. ** accordingly.
  68074. */
  68075. pPage = pCur->pPage;
  68076. if( pPage->leaf || !pPage->intKey ){
  68077. nEntry += pPage->nCell;
  68078. }
  68079. /* pPage is a leaf node. This loop navigates the cursor so that it
  68080. ** points to the first interior cell that it points to the parent of
  68081. ** the next page in the tree that has not yet been visited. The
  68082. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  68083. ** of the page, or to the number of cells in the page if the next page
  68084. ** to visit is the right-child of its parent.
  68085. **
  68086. ** If all pages in the tree have been visited, return SQLITE_OK to the
  68087. ** caller.
  68088. */
  68089. if( pPage->leaf ){
  68090. do {
  68091. if( pCur->iPage==0 ){
  68092. /* All pages of the b-tree have been visited. Return successfully. */
  68093. *pnEntry = nEntry;
  68094. return moveToRoot(pCur);
  68095. }
  68096. moveToParent(pCur);
  68097. }while ( pCur->ix>=pCur->pPage->nCell );
  68098. pCur->ix++;
  68099. pPage = pCur->pPage;
  68100. }
  68101. /* Descend to the child node of the cell that the cursor currently
  68102. ** points at. This is the right-child if (iIdx==pPage->nCell).
  68103. */
  68104. iIdx = pCur->ix;
  68105. if( iIdx==pPage->nCell ){
  68106. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  68107. }else{
  68108. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  68109. }
  68110. }
  68111. /* An error has occurred. Return an error code. */
  68112. return rc;
  68113. }
  68114. #endif
  68115. /*
  68116. ** Return the pager associated with a BTree. This routine is used for
  68117. ** testing and debugging only.
  68118. */
  68119. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  68120. return p->pBt->pPager;
  68121. }
  68122. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  68123. /*
  68124. ** Append a message to the error message string.
  68125. */
  68126. static void checkAppendMsg(
  68127. IntegrityCk *pCheck,
  68128. const char *zFormat,
  68129. ...
  68130. ){
  68131. va_list ap;
  68132. if( !pCheck->mxErr ) return;
  68133. pCheck->mxErr--;
  68134. pCheck->nErr++;
  68135. va_start(ap, zFormat);
  68136. if( pCheck->errMsg.nChar ){
  68137. sqlite3_str_append(&pCheck->errMsg, "\n", 1);
  68138. }
  68139. if( pCheck->zPfx ){
  68140. sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
  68141. }
  68142. sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
  68143. va_end(ap);
  68144. if( pCheck->errMsg.accError==SQLITE_NOMEM ){
  68145. pCheck->mallocFailed = 1;
  68146. }
  68147. }
  68148. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  68149. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  68150. /*
  68151. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  68152. ** corresponds to page iPg is already set.
  68153. */
  68154. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  68155. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  68156. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  68157. }
  68158. /*
  68159. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  68160. */
  68161. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  68162. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  68163. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  68164. }
  68165. /*
  68166. ** Add 1 to the reference count for page iPage. If this is the second
  68167. ** reference to the page, add an error message to pCheck->zErrMsg.
  68168. ** Return 1 if there are 2 or more references to the page and 0 if
  68169. ** if this is the first reference to the page.
  68170. **
  68171. ** Also check that the page number is in bounds.
  68172. */
  68173. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  68174. if( iPage>pCheck->nPage || iPage==0 ){
  68175. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  68176. return 1;
  68177. }
  68178. if( getPageReferenced(pCheck, iPage) ){
  68179. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  68180. return 1;
  68181. }
  68182. setPageReferenced(pCheck, iPage);
  68183. return 0;
  68184. }
  68185. #ifndef SQLITE_OMIT_AUTOVACUUM
  68186. /*
  68187. ** Check that the entry in the pointer-map for page iChild maps to
  68188. ** page iParent, pointer type ptrType. If not, append an error message
  68189. ** to pCheck.
  68190. */
  68191. static void checkPtrmap(
  68192. IntegrityCk *pCheck, /* Integrity check context */
  68193. Pgno iChild, /* Child page number */
  68194. u8 eType, /* Expected pointer map type */
  68195. Pgno iParent /* Expected pointer map parent page number */
  68196. ){
  68197. int rc;
  68198. u8 ePtrmapType;
  68199. Pgno iPtrmapParent;
  68200. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  68201. if( rc!=SQLITE_OK ){
  68202. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  68203. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  68204. return;
  68205. }
  68206. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  68207. checkAppendMsg(pCheck,
  68208. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  68209. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  68210. }
  68211. }
  68212. #endif
  68213. /*
  68214. ** Check the integrity of the freelist or of an overflow page list.
  68215. ** Verify that the number of pages on the list is N.
  68216. */
  68217. static void checkList(
  68218. IntegrityCk *pCheck, /* Integrity checking context */
  68219. int isFreeList, /* True for a freelist. False for overflow page list */
  68220. int iPage, /* Page number for first page in the list */
  68221. u32 N /* Expected number of pages in the list */
  68222. ){
  68223. int i;
  68224. u32 expected = N;
  68225. int nErrAtStart = pCheck->nErr;
  68226. while( iPage!=0 && pCheck->mxErr ){
  68227. DbPage *pOvflPage;
  68228. unsigned char *pOvflData;
  68229. if( checkRef(pCheck, iPage) ) break;
  68230. N--;
  68231. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
  68232. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  68233. break;
  68234. }
  68235. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  68236. if( isFreeList ){
  68237. u32 n = (u32)get4byte(&pOvflData[4]);
  68238. #ifndef SQLITE_OMIT_AUTOVACUUM
  68239. if( pCheck->pBt->autoVacuum ){
  68240. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  68241. }
  68242. #endif
  68243. if( n>pCheck->pBt->usableSize/4-2 ){
  68244. checkAppendMsg(pCheck,
  68245. "freelist leaf count too big on page %d", iPage);
  68246. N--;
  68247. }else{
  68248. for(i=0; i<(int)n; i++){
  68249. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  68250. #ifndef SQLITE_OMIT_AUTOVACUUM
  68251. if( pCheck->pBt->autoVacuum ){
  68252. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  68253. }
  68254. #endif
  68255. checkRef(pCheck, iFreePage);
  68256. }
  68257. N -= n;
  68258. }
  68259. }
  68260. #ifndef SQLITE_OMIT_AUTOVACUUM
  68261. else{
  68262. /* If this database supports auto-vacuum and iPage is not the last
  68263. ** page in this overflow list, check that the pointer-map entry for
  68264. ** the following page matches iPage.
  68265. */
  68266. if( pCheck->pBt->autoVacuum && N>0 ){
  68267. i = get4byte(pOvflData);
  68268. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  68269. }
  68270. }
  68271. #endif
  68272. iPage = get4byte(pOvflData);
  68273. sqlite3PagerUnref(pOvflPage);
  68274. }
  68275. if( N && nErrAtStart==pCheck->nErr ){
  68276. checkAppendMsg(pCheck,
  68277. "%s is %d but should be %d",
  68278. isFreeList ? "size" : "overflow list length",
  68279. expected-N, expected);
  68280. }
  68281. }
  68282. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  68283. /*
  68284. ** An implementation of a min-heap.
  68285. **
  68286. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  68287. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  68288. ** and aHeap[N*2+1].
  68289. **
  68290. ** The heap property is this: Every node is less than or equal to both
  68291. ** of its daughter nodes. A consequence of the heap property is that the
  68292. ** root node aHeap[1] is always the minimum value currently in the heap.
  68293. **
  68294. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  68295. ** the heap, preserving the heap property. The btreeHeapPull() routine
  68296. ** removes the root element from the heap (the minimum value in the heap)
  68297. ** and then moves other nodes around as necessary to preserve the heap
  68298. ** property.
  68299. **
  68300. ** This heap is used for cell overlap and coverage testing. Each u32
  68301. ** entry represents the span of a cell or freeblock on a btree page.
  68302. ** The upper 16 bits are the index of the first byte of a range and the
  68303. ** lower 16 bits are the index of the last byte of that range.
  68304. */
  68305. static void btreeHeapInsert(u32 *aHeap, u32 x){
  68306. u32 j, i = ++aHeap[0];
  68307. aHeap[i] = x;
  68308. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  68309. x = aHeap[j];
  68310. aHeap[j] = aHeap[i];
  68311. aHeap[i] = x;
  68312. i = j;
  68313. }
  68314. }
  68315. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  68316. u32 j, i, x;
  68317. if( (x = aHeap[0])==0 ) return 0;
  68318. *pOut = aHeap[1];
  68319. aHeap[1] = aHeap[x];
  68320. aHeap[x] = 0xffffffff;
  68321. aHeap[0]--;
  68322. i = 1;
  68323. while( (j = i*2)<=aHeap[0] ){
  68324. if( aHeap[j]>aHeap[j+1] ) j++;
  68325. if( aHeap[i]<aHeap[j] ) break;
  68326. x = aHeap[i];
  68327. aHeap[i] = aHeap[j];
  68328. aHeap[j] = x;
  68329. i = j;
  68330. }
  68331. return 1;
  68332. }
  68333. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  68334. /*
  68335. ** Do various sanity checks on a single page of a tree. Return
  68336. ** the tree depth. Root pages return 0. Parents of root pages
  68337. ** return 1, and so forth.
  68338. **
  68339. ** These checks are done:
  68340. **
  68341. ** 1. Make sure that cells and freeblocks do not overlap
  68342. ** but combine to completely cover the page.
  68343. ** 2. Make sure integer cell keys are in order.
  68344. ** 3. Check the integrity of overflow pages.
  68345. ** 4. Recursively call checkTreePage on all children.
  68346. ** 5. Verify that the depth of all children is the same.
  68347. */
  68348. static int checkTreePage(
  68349. IntegrityCk *pCheck, /* Context for the sanity check */
  68350. int iPage, /* Page number of the page to check */
  68351. i64 *piMinKey, /* Write minimum integer primary key here */
  68352. i64 maxKey /* Error if integer primary key greater than this */
  68353. ){
  68354. MemPage *pPage = 0; /* The page being analyzed */
  68355. int i; /* Loop counter */
  68356. int rc; /* Result code from subroutine call */
  68357. int depth = -1, d2; /* Depth of a subtree */
  68358. int pgno; /* Page number */
  68359. int nFrag; /* Number of fragmented bytes on the page */
  68360. int hdr; /* Offset to the page header */
  68361. int cellStart; /* Offset to the start of the cell pointer array */
  68362. int nCell; /* Number of cells */
  68363. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  68364. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  68365. ** False if IPK must be strictly less than maxKey */
  68366. u8 *data; /* Page content */
  68367. u8 *pCell; /* Cell content */
  68368. u8 *pCellIdx; /* Next element of the cell pointer array */
  68369. BtShared *pBt; /* The BtShared object that owns pPage */
  68370. u32 pc; /* Address of a cell */
  68371. u32 usableSize; /* Usable size of the page */
  68372. u32 contentOffset; /* Offset to the start of the cell content area */
  68373. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  68374. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  68375. const char *saved_zPfx = pCheck->zPfx;
  68376. int saved_v1 = pCheck->v1;
  68377. int saved_v2 = pCheck->v2;
  68378. u8 savedIsInit = 0;
  68379. /* Check that the page exists
  68380. */
  68381. pBt = pCheck->pBt;
  68382. usableSize = pBt->usableSize;
  68383. if( iPage==0 ) return 0;
  68384. if( checkRef(pCheck, iPage) ) return 0;
  68385. pCheck->zPfx = "Page %d: ";
  68386. pCheck->v1 = iPage;
  68387. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  68388. checkAppendMsg(pCheck,
  68389. "unable to get the page. error code=%d", rc);
  68390. goto end_of_check;
  68391. }
  68392. /* Clear MemPage.isInit to make sure the corruption detection code in
  68393. ** btreeInitPage() is executed. */
  68394. savedIsInit = pPage->isInit;
  68395. pPage->isInit = 0;
  68396. if( (rc = btreeInitPage(pPage))!=0 ){
  68397. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  68398. checkAppendMsg(pCheck,
  68399. "btreeInitPage() returns error code %d", rc);
  68400. goto end_of_check;
  68401. }
  68402. if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
  68403. assert( rc==SQLITE_CORRUPT );
  68404. checkAppendMsg(pCheck, "free space corruption", rc);
  68405. goto end_of_check;
  68406. }
  68407. data = pPage->aData;
  68408. hdr = pPage->hdrOffset;
  68409. /* Set up for cell analysis */
  68410. pCheck->zPfx = "On tree page %d cell %d: ";
  68411. contentOffset = get2byteNotZero(&data[hdr+5]);
  68412. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  68413. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  68414. ** number of cells on the page. */
  68415. nCell = get2byte(&data[hdr+3]);
  68416. assert( pPage->nCell==nCell );
  68417. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  68418. ** immediately follows the b-tree page header. */
  68419. cellStart = hdr + 12 - 4*pPage->leaf;
  68420. assert( pPage->aCellIdx==&data[cellStart] );
  68421. pCellIdx = &data[cellStart + 2*(nCell-1)];
  68422. if( !pPage->leaf ){
  68423. /* Analyze the right-child page of internal pages */
  68424. pgno = get4byte(&data[hdr+8]);
  68425. #ifndef SQLITE_OMIT_AUTOVACUUM
  68426. if( pBt->autoVacuum ){
  68427. pCheck->zPfx = "On page %d at right child: ";
  68428. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  68429. }
  68430. #endif
  68431. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  68432. keyCanBeEqual = 0;
  68433. }else{
  68434. /* For leaf pages, the coverage check will occur in the same loop
  68435. ** as the other cell checks, so initialize the heap. */
  68436. heap = pCheck->heap;
  68437. heap[0] = 0;
  68438. }
  68439. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  68440. ** integer offsets to the cell contents. */
  68441. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  68442. CellInfo info;
  68443. /* Check cell size */
  68444. pCheck->v2 = i;
  68445. assert( pCellIdx==&data[cellStart + i*2] );
  68446. pc = get2byteAligned(pCellIdx);
  68447. pCellIdx -= 2;
  68448. if( pc<contentOffset || pc>usableSize-4 ){
  68449. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  68450. pc, contentOffset, usableSize-4);
  68451. doCoverageCheck = 0;
  68452. continue;
  68453. }
  68454. pCell = &data[pc];
  68455. pPage->xParseCell(pPage, pCell, &info);
  68456. if( pc+info.nSize>usableSize ){
  68457. checkAppendMsg(pCheck, "Extends off end of page");
  68458. doCoverageCheck = 0;
  68459. continue;
  68460. }
  68461. /* Check for integer primary key out of range */
  68462. if( pPage->intKey ){
  68463. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  68464. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  68465. }
  68466. maxKey = info.nKey;
  68467. keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
  68468. }
  68469. /* Check the content overflow list */
  68470. if( info.nPayload>info.nLocal ){
  68471. u32 nPage; /* Number of pages on the overflow chain */
  68472. Pgno pgnoOvfl; /* First page of the overflow chain */
  68473. assert( pc + info.nSize - 4 <= usableSize );
  68474. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  68475. pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
  68476. #ifndef SQLITE_OMIT_AUTOVACUUM
  68477. if( pBt->autoVacuum ){
  68478. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  68479. }
  68480. #endif
  68481. checkList(pCheck, 0, pgnoOvfl, nPage);
  68482. }
  68483. if( !pPage->leaf ){
  68484. /* Check sanity of left child page for internal pages */
  68485. pgno = get4byte(pCell);
  68486. #ifndef SQLITE_OMIT_AUTOVACUUM
  68487. if( pBt->autoVacuum ){
  68488. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  68489. }
  68490. #endif
  68491. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  68492. keyCanBeEqual = 0;
  68493. if( d2!=depth ){
  68494. checkAppendMsg(pCheck, "Child page depth differs");
  68495. depth = d2;
  68496. }
  68497. }else{
  68498. /* Populate the coverage-checking heap for leaf pages */
  68499. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  68500. }
  68501. }
  68502. *piMinKey = maxKey;
  68503. /* Check for complete coverage of the page
  68504. */
  68505. pCheck->zPfx = 0;
  68506. if( doCoverageCheck && pCheck->mxErr>0 ){
  68507. /* For leaf pages, the min-heap has already been initialized and the
  68508. ** cells have already been inserted. But for internal pages, that has
  68509. ** not yet been done, so do it now */
  68510. if( !pPage->leaf ){
  68511. heap = pCheck->heap;
  68512. heap[0] = 0;
  68513. for(i=nCell-1; i>=0; i--){
  68514. u32 size;
  68515. pc = get2byteAligned(&data[cellStart+i*2]);
  68516. size = pPage->xCellSize(pPage, &data[pc]);
  68517. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  68518. }
  68519. }
  68520. /* Add the freeblocks to the min-heap
  68521. **
  68522. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  68523. ** is the offset of the first freeblock, or zero if there are no
  68524. ** freeblocks on the page.
  68525. */
  68526. i = get2byte(&data[hdr+1]);
  68527. while( i>0 ){
  68528. int size, j;
  68529. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
  68530. size = get2byte(&data[i+2]);
  68531. assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
  68532. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  68533. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  68534. ** big-endian integer which is the offset in the b-tree page of the next
  68535. ** freeblock in the chain, or zero if the freeblock is the last on the
  68536. ** chain. */
  68537. j = get2byte(&data[i]);
  68538. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  68539. ** increasing offset. */
  68540. assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
  68541. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
  68542. i = j;
  68543. }
  68544. /* Analyze the min-heap looking for overlap between cells and/or
  68545. ** freeblocks, and counting the number of untracked bytes in nFrag.
  68546. **
  68547. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  68548. ** There is an implied first entry the covers the page header, the cell
  68549. ** pointer index, and the gap between the cell pointer index and the start
  68550. ** of cell content.
  68551. **
  68552. ** The loop below pulls entries from the min-heap in order and compares
  68553. ** the start_address against the previous end_address. If there is an
  68554. ** overlap, that means bytes are used multiple times. If there is a gap,
  68555. ** that gap is added to the fragmentation count.
  68556. */
  68557. nFrag = 0;
  68558. prev = contentOffset - 1; /* Implied first min-heap entry */
  68559. while( btreeHeapPull(heap,&x) ){
  68560. if( (prev&0xffff)>=(x>>16) ){
  68561. checkAppendMsg(pCheck,
  68562. "Multiple uses for byte %u of page %d", x>>16, iPage);
  68563. break;
  68564. }else{
  68565. nFrag += (x>>16) - (prev&0xffff) - 1;
  68566. prev = x;
  68567. }
  68568. }
  68569. nFrag += usableSize - (prev&0xffff) - 1;
  68570. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  68571. ** is stored in the fifth field of the b-tree page header.
  68572. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  68573. ** number of fragmented free bytes within the cell content area.
  68574. */
  68575. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  68576. checkAppendMsg(pCheck,
  68577. "Fragmentation of %d bytes reported as %d on page %d",
  68578. nFrag, data[hdr+7], iPage);
  68579. }
  68580. }
  68581. end_of_check:
  68582. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  68583. releasePage(pPage);
  68584. pCheck->zPfx = saved_zPfx;
  68585. pCheck->v1 = saved_v1;
  68586. pCheck->v2 = saved_v2;
  68587. return depth+1;
  68588. }
  68589. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  68590. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  68591. /*
  68592. ** This routine does a complete check of the given BTree file. aRoot[] is
  68593. ** an array of pages numbers were each page number is the root page of
  68594. ** a table. nRoot is the number of entries in aRoot.
  68595. **
  68596. ** A read-only or read-write transaction must be opened before calling
  68597. ** this function.
  68598. **
  68599. ** Write the number of error seen in *pnErr. Except for some memory
  68600. ** allocation errors, an error message held in memory obtained from
  68601. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  68602. ** returned. If a memory allocation error occurs, NULL is returned.
  68603. */
  68604. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  68605. Btree *p, /* The btree to be checked */
  68606. int *aRoot, /* An array of root pages numbers for individual trees */
  68607. int nRoot, /* Number of entries in aRoot[] */
  68608. int mxErr, /* Stop reporting errors after this many */
  68609. int *pnErr /* Write number of errors seen to this variable */
  68610. ){
  68611. Pgno i;
  68612. IntegrityCk sCheck;
  68613. BtShared *pBt = p->pBt;
  68614. u64 savedDbFlags = pBt->db->flags;
  68615. char zErr[100];
  68616. VVA_ONLY( int nRef );
  68617. sqlite3BtreeEnter(p);
  68618. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  68619. VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
  68620. assert( nRef>=0 );
  68621. sCheck.pBt = pBt;
  68622. sCheck.pPager = pBt->pPager;
  68623. sCheck.nPage = btreePagecount(sCheck.pBt);
  68624. sCheck.mxErr = mxErr;
  68625. sCheck.nErr = 0;
  68626. sCheck.mallocFailed = 0;
  68627. sCheck.zPfx = 0;
  68628. sCheck.v1 = 0;
  68629. sCheck.v2 = 0;
  68630. sCheck.aPgRef = 0;
  68631. sCheck.heap = 0;
  68632. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  68633. sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
  68634. if( sCheck.nPage==0 ){
  68635. goto integrity_ck_cleanup;
  68636. }
  68637. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  68638. if( !sCheck.aPgRef ){
  68639. sCheck.mallocFailed = 1;
  68640. goto integrity_ck_cleanup;
  68641. }
  68642. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  68643. if( sCheck.heap==0 ){
  68644. sCheck.mallocFailed = 1;
  68645. goto integrity_ck_cleanup;
  68646. }
  68647. i = PENDING_BYTE_PAGE(pBt);
  68648. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  68649. /* Check the integrity of the freelist
  68650. */
  68651. sCheck.zPfx = "Main freelist: ";
  68652. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  68653. get4byte(&pBt->pPage1->aData[36]));
  68654. sCheck.zPfx = 0;
  68655. /* Check all the tables.
  68656. */
  68657. #ifndef SQLITE_OMIT_AUTOVACUUM
  68658. if( pBt->autoVacuum ){
  68659. int mx = 0;
  68660. int mxInHdr;
  68661. for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
  68662. mxInHdr = get4byte(&pBt->pPage1->aData[52]);
  68663. if( mx!=mxInHdr ){
  68664. checkAppendMsg(&sCheck,
  68665. "max rootpage (%d) disagrees with header (%d)",
  68666. mx, mxInHdr
  68667. );
  68668. }
  68669. }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
  68670. checkAppendMsg(&sCheck,
  68671. "incremental_vacuum enabled with a max rootpage of zero"
  68672. );
  68673. }
  68674. #endif
  68675. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  68676. pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
  68677. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  68678. i64 notUsed;
  68679. if( aRoot[i]==0 ) continue;
  68680. #ifndef SQLITE_OMIT_AUTOVACUUM
  68681. if( pBt->autoVacuum && aRoot[i]>1 ){
  68682. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  68683. }
  68684. #endif
  68685. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  68686. }
  68687. pBt->db->flags = savedDbFlags;
  68688. /* Make sure every page in the file is referenced
  68689. */
  68690. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  68691. #ifdef SQLITE_OMIT_AUTOVACUUM
  68692. if( getPageReferenced(&sCheck, i)==0 ){
  68693. checkAppendMsg(&sCheck, "Page %d is never used", i);
  68694. }
  68695. #else
  68696. /* If the database supports auto-vacuum, make sure no tables contain
  68697. ** references to pointer-map pages.
  68698. */
  68699. if( getPageReferenced(&sCheck, i)==0 &&
  68700. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  68701. checkAppendMsg(&sCheck, "Page %d is never used", i);
  68702. }
  68703. if( getPageReferenced(&sCheck, i)!=0 &&
  68704. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  68705. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  68706. }
  68707. #endif
  68708. }
  68709. /* Clean up and report errors.
  68710. */
  68711. integrity_ck_cleanup:
  68712. sqlite3PageFree(sCheck.heap);
  68713. sqlite3_free(sCheck.aPgRef);
  68714. if( sCheck.mallocFailed ){
  68715. sqlite3_str_reset(&sCheck.errMsg);
  68716. sCheck.nErr++;
  68717. }
  68718. *pnErr = sCheck.nErr;
  68719. if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
  68720. /* Make sure this analysis did not leave any unref() pages. */
  68721. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  68722. sqlite3BtreeLeave(p);
  68723. return sqlite3StrAccumFinish(&sCheck.errMsg);
  68724. }
  68725. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  68726. /*
  68727. ** Return the full pathname of the underlying database file. Return
  68728. ** an empty string if the database is in-memory or a TEMP database.
  68729. **
  68730. ** The pager filename is invariant as long as the pager is
  68731. ** open so it is safe to access without the BtShared mutex.
  68732. */
  68733. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  68734. assert( p->pBt->pPager!=0 );
  68735. return sqlite3PagerFilename(p->pBt->pPager, 1);
  68736. }
  68737. /*
  68738. ** Return the pathname of the journal file for this database. The return
  68739. ** value of this routine is the same regardless of whether the journal file
  68740. ** has been created or not.
  68741. **
  68742. ** The pager journal filename is invariant as long as the pager is
  68743. ** open so it is safe to access without the BtShared mutex.
  68744. */
  68745. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  68746. assert( p->pBt->pPager!=0 );
  68747. return sqlite3PagerJournalname(p->pBt->pPager);
  68748. }
  68749. /*
  68750. ** Return non-zero if a transaction is active.
  68751. */
  68752. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  68753. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  68754. return (p && (p->inTrans==TRANS_WRITE));
  68755. }
  68756. #ifndef SQLITE_OMIT_WAL
  68757. /*
  68758. ** Run a checkpoint on the Btree passed as the first argument.
  68759. **
  68760. ** Return SQLITE_LOCKED if this or any other connection has an open
  68761. ** transaction on the shared-cache the argument Btree is connected to.
  68762. **
  68763. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  68764. */
  68765. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  68766. int rc = SQLITE_OK;
  68767. if( p ){
  68768. BtShared *pBt = p->pBt;
  68769. sqlite3BtreeEnter(p);
  68770. if( pBt->inTransaction!=TRANS_NONE ){
  68771. rc = SQLITE_LOCKED;
  68772. }else{
  68773. rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
  68774. }
  68775. sqlite3BtreeLeave(p);
  68776. }
  68777. return rc;
  68778. }
  68779. #endif
  68780. /*
  68781. ** Return non-zero if a read (or write) transaction is active.
  68782. */
  68783. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  68784. assert( p );
  68785. assert( sqlite3_mutex_held(p->db->mutex) );
  68786. return p->inTrans!=TRANS_NONE;
  68787. }
  68788. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  68789. assert( p );
  68790. assert( sqlite3_mutex_held(p->db->mutex) );
  68791. return p->nBackup!=0;
  68792. }
  68793. /*
  68794. ** This function returns a pointer to a blob of memory associated with
  68795. ** a single shared-btree. The memory is used by client code for its own
  68796. ** purposes (for example, to store a high-level schema associated with
  68797. ** the shared-btree). The btree layer manages reference counting issues.
  68798. **
  68799. ** The first time this is called on a shared-btree, nBytes bytes of memory
  68800. ** are allocated, zeroed, and returned to the caller. For each subsequent
  68801. ** call the nBytes parameter is ignored and a pointer to the same blob
  68802. ** of memory returned.
  68803. **
  68804. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  68805. ** allocated, a null pointer is returned. If the blob has already been
  68806. ** allocated, it is returned as normal.
  68807. **
  68808. ** Just before the shared-btree is closed, the function passed as the
  68809. ** xFree argument when the memory allocation was made is invoked on the
  68810. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  68811. ** on the memory, the btree layer does that.
  68812. */
  68813. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  68814. BtShared *pBt = p->pBt;
  68815. sqlite3BtreeEnter(p);
  68816. if( !pBt->pSchema && nBytes ){
  68817. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  68818. pBt->xFreeSchema = xFree;
  68819. }
  68820. sqlite3BtreeLeave(p);
  68821. return pBt->pSchema;
  68822. }
  68823. /*
  68824. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  68825. ** btree as the argument handle holds an exclusive lock on the
  68826. ** sqlite_master table. Otherwise SQLITE_OK.
  68827. */
  68828. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  68829. int rc;
  68830. assert( sqlite3_mutex_held(p->db->mutex) );
  68831. sqlite3BtreeEnter(p);
  68832. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  68833. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  68834. sqlite3BtreeLeave(p);
  68835. return rc;
  68836. }
  68837. #ifndef SQLITE_OMIT_SHARED_CACHE
  68838. /*
  68839. ** Obtain a lock on the table whose root page is iTab. The
  68840. ** lock is a write lock if isWritelock is true or a read lock
  68841. ** if it is false.
  68842. */
  68843. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  68844. int rc = SQLITE_OK;
  68845. assert( p->inTrans!=TRANS_NONE );
  68846. if( p->sharable ){
  68847. u8 lockType = READ_LOCK + isWriteLock;
  68848. assert( READ_LOCK+1==WRITE_LOCK );
  68849. assert( isWriteLock==0 || isWriteLock==1 );
  68850. sqlite3BtreeEnter(p);
  68851. rc = querySharedCacheTableLock(p, iTab, lockType);
  68852. if( rc==SQLITE_OK ){
  68853. rc = setSharedCacheTableLock(p, iTab, lockType);
  68854. }
  68855. sqlite3BtreeLeave(p);
  68856. }
  68857. return rc;
  68858. }
  68859. #endif
  68860. #ifndef SQLITE_OMIT_INCRBLOB
  68861. /*
  68862. ** Argument pCsr must be a cursor opened for writing on an
  68863. ** INTKEY table currently pointing at a valid table entry.
  68864. ** This function modifies the data stored as part of that entry.
  68865. **
  68866. ** Only the data content may only be modified, it is not possible to
  68867. ** change the length of the data stored. If this function is called with
  68868. ** parameters that attempt to write past the end of the existing data,
  68869. ** no modifications are made and SQLITE_CORRUPT is returned.
  68870. */
  68871. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  68872. int rc;
  68873. assert( cursorOwnsBtShared(pCsr) );
  68874. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  68875. assert( pCsr->curFlags & BTCF_Incrblob );
  68876. rc = restoreCursorPosition(pCsr);
  68877. if( rc!=SQLITE_OK ){
  68878. return rc;
  68879. }
  68880. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  68881. if( pCsr->eState!=CURSOR_VALID ){
  68882. return SQLITE_ABORT;
  68883. }
  68884. /* Save the positions of all other cursors open on this table. This is
  68885. ** required in case any of them are holding references to an xFetch
  68886. ** version of the b-tree page modified by the accessPayload call below.
  68887. **
  68888. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  68889. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  68890. ** saveAllCursors can only return SQLITE_OK.
  68891. */
  68892. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  68893. assert( rc==SQLITE_OK );
  68894. /* Check some assumptions:
  68895. ** (a) the cursor is open for writing,
  68896. ** (b) there is a read/write transaction open,
  68897. ** (c) the connection holds a write-lock on the table (if required),
  68898. ** (d) there are no conflicting read-locks, and
  68899. ** (e) the cursor points at a valid row of an intKey table.
  68900. */
  68901. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  68902. return SQLITE_READONLY;
  68903. }
  68904. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  68905. && pCsr->pBt->inTransaction==TRANS_WRITE );
  68906. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  68907. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  68908. assert( pCsr->pPage->intKey );
  68909. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  68910. }
  68911. /*
  68912. ** Mark this cursor as an incremental blob cursor.
  68913. */
  68914. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  68915. pCur->curFlags |= BTCF_Incrblob;
  68916. pCur->pBtree->hasIncrblobCur = 1;
  68917. }
  68918. #endif
  68919. /*
  68920. ** Set both the "read version" (single byte at byte offset 18) and
  68921. ** "write version" (single byte at byte offset 19) fields in the database
  68922. ** header to iVersion.
  68923. */
  68924. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  68925. BtShared *pBt = pBtree->pBt;
  68926. int rc; /* Return code */
  68927. assert( iVersion==1 || iVersion==2 );
  68928. /* If setting the version fields to 1, do not automatically open the
  68929. ** WAL connection, even if the version fields are currently set to 2.
  68930. */
  68931. pBt->btsFlags &= ~BTS_NO_WAL;
  68932. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  68933. rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
  68934. if( rc==SQLITE_OK ){
  68935. u8 *aData = pBt->pPage1->aData;
  68936. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  68937. rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
  68938. if( rc==SQLITE_OK ){
  68939. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  68940. if( rc==SQLITE_OK ){
  68941. aData[18] = (u8)iVersion;
  68942. aData[19] = (u8)iVersion;
  68943. }
  68944. }
  68945. }
  68946. }
  68947. pBt->btsFlags &= ~BTS_NO_WAL;
  68948. return rc;
  68949. }
  68950. /*
  68951. ** Return true if the cursor has a hint specified. This routine is
  68952. ** only used from within assert() statements
  68953. */
  68954. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  68955. return (pCsr->hints & mask)!=0;
  68956. }
  68957. /*
  68958. ** Return true if the given Btree is read-only.
  68959. */
  68960. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  68961. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  68962. }
  68963. /*
  68964. ** Return the size of the header added to each page by this module.
  68965. */
  68966. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  68967. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  68968. /*
  68969. ** Return true if the Btree passed as the only argument is sharable.
  68970. */
  68971. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  68972. return p->sharable;
  68973. }
  68974. /*
  68975. ** Return the number of connections to the BtShared object accessed by
  68976. ** the Btree handle passed as the only argument. For private caches
  68977. ** this is always 1. For shared caches it may be 1 or greater.
  68978. */
  68979. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
  68980. testcase( p->sharable );
  68981. return p->pBt->nRef;
  68982. }
  68983. #endif
  68984. /************** End of btree.c ***********************************************/
  68985. /************** Begin file backup.c ******************************************/
  68986. /*
  68987. ** 2009 January 28
  68988. **
  68989. ** The author disclaims copyright to this source code. In place of
  68990. ** a legal notice, here is a blessing:
  68991. **
  68992. ** May you do good and not evil.
  68993. ** May you find forgiveness for yourself and forgive others.
  68994. ** May you share freely, never taking more than you give.
  68995. **
  68996. *************************************************************************
  68997. ** This file contains the implementation of the sqlite3_backup_XXX()
  68998. ** API functions and the related features.
  68999. */
  69000. /* #include "sqliteInt.h" */
  69001. /* #include "btreeInt.h" */
  69002. /*
  69003. ** Structure allocated for each backup operation.
  69004. */
  69005. struct sqlite3_backup {
  69006. sqlite3* pDestDb; /* Destination database handle */
  69007. Btree *pDest; /* Destination b-tree file */
  69008. u32 iDestSchema; /* Original schema cookie in destination */
  69009. int bDestLocked; /* True once a write-transaction is open on pDest */
  69010. Pgno iNext; /* Page number of the next source page to copy */
  69011. sqlite3* pSrcDb; /* Source database handle */
  69012. Btree *pSrc; /* Source b-tree file */
  69013. int rc; /* Backup process error code */
  69014. /* These two variables are set by every call to backup_step(). They are
  69015. ** read by calls to backup_remaining() and backup_pagecount().
  69016. */
  69017. Pgno nRemaining; /* Number of pages left to copy */
  69018. Pgno nPagecount; /* Total number of pages to copy */
  69019. int isAttached; /* True once backup has been registered with pager */
  69020. sqlite3_backup *pNext; /* Next backup associated with source pager */
  69021. };
  69022. /*
  69023. ** THREAD SAFETY NOTES:
  69024. **
  69025. ** Once it has been created using backup_init(), a single sqlite3_backup
  69026. ** structure may be accessed via two groups of thread-safe entry points:
  69027. **
  69028. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  69029. ** backup_finish(). Both these functions obtain the source database
  69030. ** handle mutex and the mutex associated with the source BtShared
  69031. ** structure, in that order.
  69032. **
  69033. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  69034. ** invoked by the pager layer to report various state changes in
  69035. ** the page cache associated with the source database. The mutex
  69036. ** associated with the source database BtShared structure will always
  69037. ** be held when either of these functions are invoked.
  69038. **
  69039. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  69040. ** backup_pagecount() are not thread-safe functions. If they are called
  69041. ** while some other thread is calling backup_step() or backup_finish(),
  69042. ** the values returned may be invalid. There is no way for a call to
  69043. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  69044. ** or backup_pagecount().
  69045. **
  69046. ** Depending on the SQLite configuration, the database handles and/or
  69047. ** the Btree objects may have their own mutexes that require locking.
  69048. ** Non-sharable Btrees (in-memory databases for example), do not have
  69049. ** associated mutexes.
  69050. */
  69051. /*
  69052. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  69053. ** in connection handle pDb. If such a database cannot be found, return
  69054. ** a NULL pointer and write an error message to pErrorDb.
  69055. **
  69056. ** If the "temp" database is requested, it may need to be opened by this
  69057. ** function. If an error occurs while doing so, return 0 and write an
  69058. ** error message to pErrorDb.
  69059. */
  69060. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  69061. int i = sqlite3FindDbName(pDb, zDb);
  69062. if( i==1 ){
  69063. Parse sParse;
  69064. int rc = 0;
  69065. memset(&sParse, 0, sizeof(sParse));
  69066. sParse.db = pDb;
  69067. if( sqlite3OpenTempDatabase(&sParse) ){
  69068. sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
  69069. rc = SQLITE_ERROR;
  69070. }
  69071. sqlite3DbFree(pErrorDb, sParse.zErrMsg);
  69072. sqlite3ParserReset(&sParse);
  69073. if( rc ){
  69074. return 0;
  69075. }
  69076. }
  69077. if( i<0 ){
  69078. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  69079. return 0;
  69080. }
  69081. return pDb->aDb[i].pBt;
  69082. }
  69083. /*
  69084. ** Attempt to set the page size of the destination to match the page size
  69085. ** of the source.
  69086. */
  69087. static int setDestPgsz(sqlite3_backup *p){
  69088. int rc;
  69089. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  69090. return rc;
  69091. }
  69092. /*
  69093. ** Check that there is no open read-transaction on the b-tree passed as the
  69094. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  69095. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  69096. ** message in database handle db.
  69097. */
  69098. static int checkReadTransaction(sqlite3 *db, Btree *p){
  69099. if( sqlite3BtreeIsInReadTrans(p) ){
  69100. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  69101. return SQLITE_ERROR;
  69102. }
  69103. return SQLITE_OK;
  69104. }
  69105. /*
  69106. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  69107. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  69108. ** a pointer to the new sqlite3_backup object.
  69109. **
  69110. ** If an error occurs, NULL is returned and an error code and error message
  69111. ** stored in database handle pDestDb.
  69112. */
  69113. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  69114. sqlite3* pDestDb, /* Database to write to */
  69115. const char *zDestDb, /* Name of database within pDestDb */
  69116. sqlite3* pSrcDb, /* Database connection to read from */
  69117. const char *zSrcDb /* Name of database within pSrcDb */
  69118. ){
  69119. sqlite3_backup *p; /* Value to return */
  69120. #ifdef SQLITE_ENABLE_API_ARMOR
  69121. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  69122. (void)SQLITE_MISUSE_BKPT;
  69123. return 0;
  69124. }
  69125. #endif
  69126. /* Lock the source database handle. The destination database
  69127. ** handle is not locked in this routine, but it is locked in
  69128. ** sqlite3_backup_step(). The user is required to ensure that no
  69129. ** other thread accesses the destination handle for the duration
  69130. ** of the backup operation. Any attempt to use the destination
  69131. ** database connection while a backup is in progress may cause
  69132. ** a malfunction or a deadlock.
  69133. */
  69134. sqlite3_mutex_enter(pSrcDb->mutex);
  69135. sqlite3_mutex_enter(pDestDb->mutex);
  69136. if( pSrcDb==pDestDb ){
  69137. sqlite3ErrorWithMsg(
  69138. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  69139. );
  69140. p = 0;
  69141. }else {
  69142. /* Allocate space for a new sqlite3_backup object...
  69143. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  69144. ** call to sqlite3_backup_init() and is destroyed by a call to
  69145. ** sqlite3_backup_finish(). */
  69146. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  69147. if( !p ){
  69148. sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
  69149. }
  69150. }
  69151. /* If the allocation succeeded, populate the new object. */
  69152. if( p ){
  69153. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  69154. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  69155. p->pDestDb = pDestDb;
  69156. p->pSrcDb = pSrcDb;
  69157. p->iNext = 1;
  69158. p->isAttached = 0;
  69159. if( 0==p->pSrc || 0==p->pDest
  69160. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  69161. ){
  69162. /* One (or both) of the named databases did not exist or an OOM
  69163. ** error was hit. Or there is a transaction open on the destination
  69164. ** database. The error has already been written into the pDestDb
  69165. ** handle. All that is left to do here is free the sqlite3_backup
  69166. ** structure. */
  69167. sqlite3_free(p);
  69168. p = 0;
  69169. }
  69170. }
  69171. if( p ){
  69172. p->pSrc->nBackup++;
  69173. }
  69174. sqlite3_mutex_leave(pDestDb->mutex);
  69175. sqlite3_mutex_leave(pSrcDb->mutex);
  69176. return p;
  69177. }
  69178. /*
  69179. ** Argument rc is an SQLite error code. Return true if this error is
  69180. ** considered fatal if encountered during a backup operation. All errors
  69181. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  69182. */
  69183. static int isFatalError(int rc){
  69184. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  69185. }
  69186. /*
  69187. ** Parameter zSrcData points to a buffer containing the data for
  69188. ** page iSrcPg from the source database. Copy this data into the
  69189. ** destination database.
  69190. */
  69191. static int backupOnePage(
  69192. sqlite3_backup *p, /* Backup handle */
  69193. Pgno iSrcPg, /* Source database page to backup */
  69194. const u8 *zSrcData, /* Source database page data */
  69195. int bUpdate /* True for an update, false otherwise */
  69196. ){
  69197. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  69198. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  69199. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  69200. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  69201. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  69202. #ifdef SQLITE_HAS_CODEC
  69203. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  69204. ** guaranteed that the shared-mutex is held by this thread, handle
  69205. ** p->pSrc may not actually be the owner. */
  69206. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  69207. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  69208. #endif
  69209. int rc = SQLITE_OK;
  69210. i64 iOff;
  69211. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  69212. assert( p->bDestLocked );
  69213. assert( !isFatalError(p->rc) );
  69214. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  69215. assert( zSrcData );
  69216. /* Catch the case where the destination is an in-memory database and the
  69217. ** page sizes of the source and destination differ.
  69218. */
  69219. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  69220. rc = SQLITE_READONLY;
  69221. }
  69222. #ifdef SQLITE_HAS_CODEC
  69223. /* Backup is not possible if the page size of the destination is changing
  69224. ** and a codec is in use.
  69225. */
  69226. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  69227. rc = SQLITE_READONLY;
  69228. }
  69229. /* Backup is not possible if the number of bytes of reserve space differ
  69230. ** between source and destination. If there is a difference, try to
  69231. ** fix the destination to agree with the source. If that is not possible,
  69232. ** then the backup cannot proceed.
  69233. */
  69234. if( nSrcReserve!=nDestReserve ){
  69235. u32 newPgsz = nSrcPgsz;
  69236. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  69237. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  69238. }
  69239. #endif
  69240. /* This loop runs once for each destination page spanned by the source
  69241. ** page. For each iteration, variable iOff is set to the byte offset
  69242. ** of the destination page.
  69243. */
  69244. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  69245. DbPage *pDestPg = 0;
  69246. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  69247. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  69248. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
  69249. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  69250. ){
  69251. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  69252. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  69253. u8 *zOut = &zDestData[iOff%nDestPgsz];
  69254. /* Copy the data from the source page into the destination page.
  69255. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  69256. ** and the pager code use this trick (clearing the first byte
  69257. ** of the page 'extra' space to invalidate the Btree layers
  69258. ** cached parse of the page). MemPage.isInit is marked
  69259. ** "MUST BE FIRST" for this purpose.
  69260. */
  69261. memcpy(zOut, zIn, nCopy);
  69262. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  69263. if( iOff==0 && bUpdate==0 ){
  69264. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  69265. }
  69266. }
  69267. sqlite3PagerUnref(pDestPg);
  69268. }
  69269. return rc;
  69270. }
  69271. /*
  69272. ** If pFile is currently larger than iSize bytes, then truncate it to
  69273. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  69274. ** this function is a no-op.
  69275. **
  69276. ** Return SQLITE_OK if everything is successful, or an SQLite error
  69277. ** code if an error occurs.
  69278. */
  69279. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  69280. i64 iCurrent;
  69281. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  69282. if( rc==SQLITE_OK && iCurrent>iSize ){
  69283. rc = sqlite3OsTruncate(pFile, iSize);
  69284. }
  69285. return rc;
  69286. }
  69287. /*
  69288. ** Register this backup object with the associated source pager for
  69289. ** callbacks when pages are changed or the cache invalidated.
  69290. */
  69291. static void attachBackupObject(sqlite3_backup *p){
  69292. sqlite3_backup **pp;
  69293. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  69294. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  69295. p->pNext = *pp;
  69296. *pp = p;
  69297. p->isAttached = 1;
  69298. }
  69299. /*
  69300. ** Copy nPage pages from the source b-tree to the destination.
  69301. */
  69302. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  69303. int rc;
  69304. int destMode; /* Destination journal mode */
  69305. int pgszSrc = 0; /* Source page size */
  69306. int pgszDest = 0; /* Destination page size */
  69307. #ifdef SQLITE_ENABLE_API_ARMOR
  69308. if( p==0 ) return SQLITE_MISUSE_BKPT;
  69309. #endif
  69310. sqlite3_mutex_enter(p->pSrcDb->mutex);
  69311. sqlite3BtreeEnter(p->pSrc);
  69312. if( p->pDestDb ){
  69313. sqlite3_mutex_enter(p->pDestDb->mutex);
  69314. }
  69315. rc = p->rc;
  69316. if( !isFatalError(rc) ){
  69317. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  69318. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  69319. int ii; /* Iterator variable */
  69320. int nSrcPage = -1; /* Size of source db in pages */
  69321. int bCloseTrans = 0; /* True if src db requires unlocking */
  69322. /* If the source pager is currently in a write-transaction, return
  69323. ** SQLITE_BUSY immediately.
  69324. */
  69325. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  69326. rc = SQLITE_BUSY;
  69327. }else{
  69328. rc = SQLITE_OK;
  69329. }
  69330. /* If there is no open read-transaction on the source database, open
  69331. ** one now. If a transaction is opened here, then it will be closed
  69332. ** before this function exits.
  69333. */
  69334. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  69335. rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
  69336. bCloseTrans = 1;
  69337. }
  69338. /* If the destination database has not yet been locked (i.e. if this
  69339. ** is the first call to backup_step() for the current backup operation),
  69340. ** try to set its page size to the same as the source database. This
  69341. ** is especially important on ZipVFS systems, as in that case it is
  69342. ** not possible to create a database file that uses one page size by
  69343. ** writing to it with another. */
  69344. if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
  69345. rc = SQLITE_NOMEM;
  69346. }
  69347. /* Lock the destination database, if it is not locked already. */
  69348. if( SQLITE_OK==rc && p->bDestLocked==0
  69349. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
  69350. (int*)&p->iDestSchema))
  69351. ){
  69352. p->bDestLocked = 1;
  69353. }
  69354. /* Do not allow backup if the destination database is in WAL mode
  69355. ** and the page sizes are different between source and destination */
  69356. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  69357. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  69358. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  69359. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  69360. rc = SQLITE_READONLY;
  69361. }
  69362. /* Now that there is a read-lock on the source database, query the
  69363. ** source pager for the number of pages in the database.
  69364. */
  69365. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  69366. assert( nSrcPage>=0 );
  69367. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  69368. const Pgno iSrcPg = p->iNext; /* Source page number */
  69369. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  69370. DbPage *pSrcPg; /* Source page object */
  69371. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
  69372. if( rc==SQLITE_OK ){
  69373. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  69374. sqlite3PagerUnref(pSrcPg);
  69375. }
  69376. }
  69377. p->iNext++;
  69378. }
  69379. if( rc==SQLITE_OK ){
  69380. p->nPagecount = nSrcPage;
  69381. p->nRemaining = nSrcPage+1-p->iNext;
  69382. if( p->iNext>(Pgno)nSrcPage ){
  69383. rc = SQLITE_DONE;
  69384. }else if( !p->isAttached ){
  69385. attachBackupObject(p);
  69386. }
  69387. }
  69388. /* Update the schema version field in the destination database. This
  69389. ** is to make sure that the schema-version really does change in
  69390. ** the case where the source and destination databases have the
  69391. ** same schema version.
  69392. */
  69393. if( rc==SQLITE_DONE ){
  69394. if( nSrcPage==0 ){
  69395. rc = sqlite3BtreeNewDb(p->pDest);
  69396. nSrcPage = 1;
  69397. }
  69398. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  69399. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  69400. }
  69401. if( rc==SQLITE_OK ){
  69402. if( p->pDestDb ){
  69403. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  69404. }
  69405. if( destMode==PAGER_JOURNALMODE_WAL ){
  69406. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  69407. }
  69408. }
  69409. if( rc==SQLITE_OK ){
  69410. int nDestTruncate;
  69411. /* Set nDestTruncate to the final number of pages in the destination
  69412. ** database. The complication here is that the destination page
  69413. ** size may be different to the source page size.
  69414. **
  69415. ** If the source page size is smaller than the destination page size,
  69416. ** round up. In this case the call to sqlite3OsTruncate() below will
  69417. ** fix the size of the file. However it is important to call
  69418. ** sqlite3PagerTruncateImage() here so that any pages in the
  69419. ** destination file that lie beyond the nDestTruncate page mark are
  69420. ** journalled by PagerCommitPhaseOne() before they are destroyed
  69421. ** by the file truncation.
  69422. */
  69423. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  69424. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  69425. if( pgszSrc<pgszDest ){
  69426. int ratio = pgszDest/pgszSrc;
  69427. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  69428. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  69429. nDestTruncate--;
  69430. }
  69431. }else{
  69432. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  69433. }
  69434. assert( nDestTruncate>0 );
  69435. if( pgszSrc<pgszDest ){
  69436. /* If the source page-size is smaller than the destination page-size,
  69437. ** two extra things may need to happen:
  69438. **
  69439. ** * The destination may need to be truncated, and
  69440. **
  69441. ** * Data stored on the pages immediately following the
  69442. ** pending-byte page in the source database may need to be
  69443. ** copied into the destination database.
  69444. */
  69445. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  69446. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  69447. Pgno iPg;
  69448. int nDstPage;
  69449. i64 iOff;
  69450. i64 iEnd;
  69451. assert( pFile );
  69452. assert( nDestTruncate==0
  69453. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  69454. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  69455. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  69456. ));
  69457. /* This block ensures that all data required to recreate the original
  69458. ** database has been stored in the journal for pDestPager and the
  69459. ** journal synced to disk. So at this point we may safely modify
  69460. ** the database file in any way, knowing that if a power failure
  69461. ** occurs, the original database will be reconstructed from the
  69462. ** journal file. */
  69463. sqlite3PagerPagecount(pDestPager, &nDstPage);
  69464. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  69465. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  69466. DbPage *pPg;
  69467. rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
  69468. if( rc==SQLITE_OK ){
  69469. rc = sqlite3PagerWrite(pPg);
  69470. sqlite3PagerUnref(pPg);
  69471. }
  69472. }
  69473. }
  69474. if( rc==SQLITE_OK ){
  69475. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  69476. }
  69477. /* Write the extra pages and truncate the database file as required */
  69478. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  69479. for(
  69480. iOff=PENDING_BYTE+pgszSrc;
  69481. rc==SQLITE_OK && iOff<iEnd;
  69482. iOff+=pgszSrc
  69483. ){
  69484. PgHdr *pSrcPg = 0;
  69485. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  69486. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
  69487. if( rc==SQLITE_OK ){
  69488. u8 *zData = sqlite3PagerGetData(pSrcPg);
  69489. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  69490. }
  69491. sqlite3PagerUnref(pSrcPg);
  69492. }
  69493. if( rc==SQLITE_OK ){
  69494. rc = backupTruncateFile(pFile, iSize);
  69495. }
  69496. /* Sync the database file to disk. */
  69497. if( rc==SQLITE_OK ){
  69498. rc = sqlite3PagerSync(pDestPager, 0);
  69499. }
  69500. }else{
  69501. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  69502. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  69503. }
  69504. /* Finish committing the transaction to the destination database. */
  69505. if( SQLITE_OK==rc
  69506. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  69507. ){
  69508. rc = SQLITE_DONE;
  69509. }
  69510. }
  69511. }
  69512. /* If bCloseTrans is true, then this function opened a read transaction
  69513. ** on the source database. Close the read transaction here. There is
  69514. ** no need to check the return values of the btree methods here, as
  69515. ** "committing" a read-only transaction cannot fail.
  69516. */
  69517. if( bCloseTrans ){
  69518. TESTONLY( int rc2 );
  69519. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  69520. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  69521. assert( rc2==SQLITE_OK );
  69522. }
  69523. if( rc==SQLITE_IOERR_NOMEM ){
  69524. rc = SQLITE_NOMEM_BKPT;
  69525. }
  69526. p->rc = rc;
  69527. }
  69528. if( p->pDestDb ){
  69529. sqlite3_mutex_leave(p->pDestDb->mutex);
  69530. }
  69531. sqlite3BtreeLeave(p->pSrc);
  69532. sqlite3_mutex_leave(p->pSrcDb->mutex);
  69533. return rc;
  69534. }
  69535. /*
  69536. ** Release all resources associated with an sqlite3_backup* handle.
  69537. */
  69538. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  69539. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  69540. sqlite3 *pSrcDb; /* Source database connection */
  69541. int rc; /* Value to return */
  69542. /* Enter the mutexes */
  69543. if( p==0 ) return SQLITE_OK;
  69544. pSrcDb = p->pSrcDb;
  69545. sqlite3_mutex_enter(pSrcDb->mutex);
  69546. sqlite3BtreeEnter(p->pSrc);
  69547. if( p->pDestDb ){
  69548. sqlite3_mutex_enter(p->pDestDb->mutex);
  69549. }
  69550. /* Detach this backup from the source pager. */
  69551. if( p->pDestDb ){
  69552. p->pSrc->nBackup--;
  69553. }
  69554. if( p->isAttached ){
  69555. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  69556. while( *pp!=p ){
  69557. pp = &(*pp)->pNext;
  69558. }
  69559. *pp = p->pNext;
  69560. }
  69561. /* If a transaction is still open on the Btree, roll it back. */
  69562. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  69563. /* Set the error code of the destination database handle. */
  69564. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  69565. if( p->pDestDb ){
  69566. sqlite3Error(p->pDestDb, rc);
  69567. /* Exit the mutexes and free the backup context structure. */
  69568. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  69569. }
  69570. sqlite3BtreeLeave(p->pSrc);
  69571. if( p->pDestDb ){
  69572. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  69573. ** call to sqlite3_backup_init() and is destroyed by a call to
  69574. ** sqlite3_backup_finish(). */
  69575. sqlite3_free(p);
  69576. }
  69577. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  69578. return rc;
  69579. }
  69580. /*
  69581. ** Return the number of pages still to be backed up as of the most recent
  69582. ** call to sqlite3_backup_step().
  69583. */
  69584. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  69585. #ifdef SQLITE_ENABLE_API_ARMOR
  69586. if( p==0 ){
  69587. (void)SQLITE_MISUSE_BKPT;
  69588. return 0;
  69589. }
  69590. #endif
  69591. return p->nRemaining;
  69592. }
  69593. /*
  69594. ** Return the total number of pages in the source database as of the most
  69595. ** recent call to sqlite3_backup_step().
  69596. */
  69597. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  69598. #ifdef SQLITE_ENABLE_API_ARMOR
  69599. if( p==0 ){
  69600. (void)SQLITE_MISUSE_BKPT;
  69601. return 0;
  69602. }
  69603. #endif
  69604. return p->nPagecount;
  69605. }
  69606. /*
  69607. ** This function is called after the contents of page iPage of the
  69608. ** source database have been modified. If page iPage has already been
  69609. ** copied into the destination database, then the data written to the
  69610. ** destination is now invalidated. The destination copy of iPage needs
  69611. ** to be updated with the new data before the backup operation is
  69612. ** complete.
  69613. **
  69614. ** It is assumed that the mutex associated with the BtShared object
  69615. ** corresponding to the source database is held when this function is
  69616. ** called.
  69617. */
  69618. static SQLITE_NOINLINE void backupUpdate(
  69619. sqlite3_backup *p,
  69620. Pgno iPage,
  69621. const u8 *aData
  69622. ){
  69623. assert( p!=0 );
  69624. do{
  69625. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  69626. if( !isFatalError(p->rc) && iPage<p->iNext ){
  69627. /* The backup process p has already copied page iPage. But now it
  69628. ** has been modified by a transaction on the source pager. Copy
  69629. ** the new data into the backup.
  69630. */
  69631. int rc;
  69632. assert( p->pDestDb );
  69633. sqlite3_mutex_enter(p->pDestDb->mutex);
  69634. rc = backupOnePage(p, iPage, aData, 1);
  69635. sqlite3_mutex_leave(p->pDestDb->mutex);
  69636. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  69637. if( rc!=SQLITE_OK ){
  69638. p->rc = rc;
  69639. }
  69640. }
  69641. }while( (p = p->pNext)!=0 );
  69642. }
  69643. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  69644. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  69645. }
  69646. /*
  69647. ** Restart the backup process. This is called when the pager layer
  69648. ** detects that the database has been modified by an external database
  69649. ** connection. In this case there is no way of knowing which of the
  69650. ** pages that have been copied into the destination database are still
  69651. ** valid and which are not, so the entire process needs to be restarted.
  69652. **
  69653. ** It is assumed that the mutex associated with the BtShared object
  69654. ** corresponding to the source database is held when this function is
  69655. ** called.
  69656. */
  69657. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  69658. sqlite3_backup *p; /* Iterator variable */
  69659. for(p=pBackup; p; p=p->pNext){
  69660. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  69661. p->iNext = 1;
  69662. }
  69663. }
  69664. #ifndef SQLITE_OMIT_VACUUM
  69665. /*
  69666. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  69667. ** must be active for both files.
  69668. **
  69669. ** The size of file pTo may be reduced by this operation. If anything
  69670. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  69671. ** transaction is committed before returning.
  69672. */
  69673. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  69674. int rc;
  69675. sqlite3_file *pFd; /* File descriptor for database pTo */
  69676. sqlite3_backup b;
  69677. sqlite3BtreeEnter(pTo);
  69678. sqlite3BtreeEnter(pFrom);
  69679. assert( sqlite3BtreeIsInTrans(pTo) );
  69680. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  69681. if( pFd->pMethods ){
  69682. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  69683. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  69684. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  69685. if( rc ) goto copy_finished;
  69686. }
  69687. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  69688. ** to 0. This is used by the implementations of sqlite3_backup_step()
  69689. ** and sqlite3_backup_finish() to detect that they are being called
  69690. ** from this function, not directly by the user.
  69691. */
  69692. memset(&b, 0, sizeof(b));
  69693. b.pSrcDb = pFrom->db;
  69694. b.pSrc = pFrom;
  69695. b.pDest = pTo;
  69696. b.iNext = 1;
  69697. #ifdef SQLITE_HAS_CODEC
  69698. sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
  69699. #endif
  69700. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  69701. ** file. By passing this as the number of pages to copy to
  69702. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  69703. ** within a single call (unless an error occurs). The assert() statement
  69704. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  69705. ** or an error code. */
  69706. sqlite3_backup_step(&b, 0x7FFFFFFF);
  69707. assert( b.rc!=SQLITE_OK );
  69708. rc = sqlite3_backup_finish(&b);
  69709. if( rc==SQLITE_OK ){
  69710. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  69711. }else{
  69712. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  69713. }
  69714. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  69715. copy_finished:
  69716. sqlite3BtreeLeave(pFrom);
  69717. sqlite3BtreeLeave(pTo);
  69718. return rc;
  69719. }
  69720. #endif /* SQLITE_OMIT_VACUUM */
  69721. /************** End of backup.c **********************************************/
  69722. /************** Begin file vdbemem.c *****************************************/
  69723. /*
  69724. ** 2004 May 26
  69725. **
  69726. ** The author disclaims copyright to this source code. In place of
  69727. ** a legal notice, here is a blessing:
  69728. **
  69729. ** May you do good and not evil.
  69730. ** May you find forgiveness for yourself and forgive others.
  69731. ** May you share freely, never taking more than you give.
  69732. **
  69733. *************************************************************************
  69734. **
  69735. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  69736. ** stores a single value in the VDBE. Mem is an opaque structure visible
  69737. ** only within the VDBE. Interface routines refer to a Mem using the
  69738. ** name sqlite_value
  69739. */
  69740. /* #include "sqliteInt.h" */
  69741. /* #include "vdbeInt.h" */
  69742. #ifdef SQLITE_DEBUG
  69743. /*
  69744. ** Check invariants on a Mem object.
  69745. **
  69746. ** This routine is intended for use inside of assert() statements, like
  69747. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  69748. */
  69749. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  69750. /* If MEM_Dyn is set then Mem.xDel!=0.
  69751. ** Mem.xDel might not be initialized if MEM_Dyn is clear.
  69752. */
  69753. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  69754. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  69755. ** ensure that if Mem.szMalloc>0 then it is safe to do
  69756. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  69757. ** That saves a few cycles in inner loops. */
  69758. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  69759. /* Cannot be both MEM_Int and MEM_Real at the same time */
  69760. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  69761. if( p->flags & MEM_Null ){
  69762. /* Cannot be both MEM_Null and some other type */
  69763. assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
  69764. /* If MEM_Null is set, then either the value is a pure NULL (the usual
  69765. ** case) or it is a pointer set using sqlite3_bind_pointer() or
  69766. ** sqlite3_result_pointer(). If a pointer, then MEM_Term must also be
  69767. ** set.
  69768. */
  69769. if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
  69770. /* This is a pointer type. There may be a flag to indicate what to
  69771. ** do with the pointer. */
  69772. assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  69773. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  69774. ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
  69775. /* No other bits set */
  69776. assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind
  69777. |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
  69778. }else{
  69779. /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
  69780. ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
  69781. }
  69782. }else{
  69783. /* The MEM_Cleared bit is only allowed on NULLs */
  69784. assert( (p->flags & MEM_Cleared)==0 );
  69785. }
  69786. /* The szMalloc field holds the correct memory allocation size */
  69787. assert( p->szMalloc==0
  69788. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  69789. /* If p holds a string or blob, the Mem.z must point to exactly
  69790. ** one of the following:
  69791. **
  69792. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  69793. ** (2) Memory to be freed using Mem.xDel
  69794. ** (3) An ephemeral string or blob
  69795. ** (4) A static string or blob
  69796. */
  69797. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  69798. assert(
  69799. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  69800. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  69801. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  69802. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  69803. );
  69804. }
  69805. return 1;
  69806. }
  69807. #endif
  69808. #ifdef SQLITE_DEBUG
  69809. /*
  69810. ** Check that string value of pMem agrees with its integer or real value.
  69811. **
  69812. ** A single int or real value always converts to the same strings. But
  69813. ** many different strings can be converted into the same int or real.
  69814. ** If a table contains a numeric value and an index is based on the
  69815. ** corresponding string value, then it is important that the string be
  69816. ** derived from the numeric value, not the other way around, to ensure
  69817. ** that the index and table are consistent. See ticket
  69818. ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
  69819. ** an example.
  69820. **
  69821. ** This routine looks at pMem to verify that if it has both a numeric
  69822. ** representation and a string representation then the string rep has
  69823. ** been derived from the numeric and not the other way around. It returns
  69824. ** true if everything is ok and false if there is a problem.
  69825. **
  69826. ** This routine is for use inside of assert() statements only.
  69827. */
  69828. SQLITE_PRIVATE int sqlite3VdbeMemConsistentDualRep(Mem *p){
  69829. char zBuf[100];
  69830. char *z;
  69831. int i, j, incr;
  69832. if( (p->flags & MEM_Str)==0 ) return 1;
  69833. if( (p->flags & (MEM_Int|MEM_Real))==0 ) return 1;
  69834. if( p->flags & MEM_Int ){
  69835. sqlite3_snprintf(sizeof(zBuf),zBuf,"%lld",p->u.i);
  69836. }else{
  69837. sqlite3_snprintf(sizeof(zBuf),zBuf,"%!.15g",p->u.r);
  69838. }
  69839. z = p->z;
  69840. i = j = 0;
  69841. incr = 1;
  69842. if( p->enc!=SQLITE_UTF8 ){
  69843. incr = 2;
  69844. if( p->enc==SQLITE_UTF16BE ) z++;
  69845. }
  69846. while( zBuf[j] ){
  69847. if( zBuf[j++]!=z[i] ) return 0;
  69848. i += incr;
  69849. }
  69850. return 1;
  69851. }
  69852. #endif /* SQLITE_DEBUG */
  69853. /*
  69854. ** If pMem is an object with a valid string representation, this routine
  69855. ** ensures the internal encoding for the string representation is
  69856. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  69857. **
  69858. ** If pMem is not a string object, or the encoding of the string
  69859. ** representation is already stored using the requested encoding, then this
  69860. ** routine is a no-op.
  69861. **
  69862. ** SQLITE_OK is returned if the conversion is successful (or not required).
  69863. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  69864. ** between formats.
  69865. */
  69866. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  69867. #ifndef SQLITE_OMIT_UTF16
  69868. int rc;
  69869. #endif
  69870. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  69871. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  69872. || desiredEnc==SQLITE_UTF16BE );
  69873. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  69874. return SQLITE_OK;
  69875. }
  69876. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69877. #ifdef SQLITE_OMIT_UTF16
  69878. return SQLITE_ERROR;
  69879. #else
  69880. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  69881. ** then the encoding of the value may not have changed.
  69882. */
  69883. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  69884. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  69885. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  69886. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  69887. return rc;
  69888. #endif
  69889. }
  69890. /*
  69891. ** Make sure pMem->z points to a writable allocation of at least n bytes.
  69892. **
  69893. ** If the bPreserve argument is true, then copy of the content of
  69894. ** pMem->z into the new allocation. pMem must be either a string or
  69895. ** blob if bPreserve is true. If bPreserve is false, any prior content
  69896. ** in pMem->z is discarded.
  69897. */
  69898. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  69899. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  69900. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  69901. testcase( pMem->db==0 );
  69902. /* If the bPreserve flag is set to true, then the memory cell must already
  69903. ** contain a valid string or blob value. */
  69904. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  69905. testcase( bPreserve && pMem->z==0 );
  69906. assert( pMem->szMalloc==0
  69907. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  69908. if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
  69909. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  69910. bPreserve = 0;
  69911. }else{
  69912. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  69913. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  69914. }
  69915. if( pMem->zMalloc==0 ){
  69916. sqlite3VdbeMemSetNull(pMem);
  69917. pMem->z = 0;
  69918. pMem->szMalloc = 0;
  69919. return SQLITE_NOMEM_BKPT;
  69920. }else{
  69921. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  69922. }
  69923. if( bPreserve && pMem->z ){
  69924. assert( pMem->z!=pMem->zMalloc );
  69925. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  69926. }
  69927. if( (pMem->flags&MEM_Dyn)!=0 ){
  69928. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  69929. pMem->xDel((void *)(pMem->z));
  69930. }
  69931. pMem->z = pMem->zMalloc;
  69932. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  69933. return SQLITE_OK;
  69934. }
  69935. /*
  69936. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  69937. ** If pMem->zMalloc already meets or exceeds the requested size, this
  69938. ** routine is a no-op.
  69939. **
  69940. ** Any prior string or blob content in the pMem object may be discarded.
  69941. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  69942. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  69943. ** values are preserved.
  69944. **
  69945. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  69946. ** if unable to complete the resizing.
  69947. */
  69948. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  69949. assert( CORRUPT_DB || szNew>0 );
  69950. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  69951. if( pMem->szMalloc<szNew ){
  69952. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  69953. }
  69954. assert( (pMem->flags & MEM_Dyn)==0 );
  69955. pMem->z = pMem->zMalloc;
  69956. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  69957. return SQLITE_OK;
  69958. }
  69959. /*
  69960. ** It is already known that pMem contains an unterminated string.
  69961. ** Add the zero terminator.
  69962. */
  69963. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  69964. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  69965. return SQLITE_NOMEM_BKPT;
  69966. }
  69967. pMem->z[pMem->n] = 0;
  69968. pMem->z[pMem->n+1] = 0;
  69969. pMem->flags |= MEM_Term;
  69970. return SQLITE_OK;
  69971. }
  69972. /*
  69973. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  69974. ** MEM.zMalloc, where it can be safely written.
  69975. **
  69976. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  69977. */
  69978. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  69979. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  69980. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  69981. if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
  69982. if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
  69983. if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
  69984. int rc = vdbeMemAddTerminator(pMem);
  69985. if( rc ) return rc;
  69986. }
  69987. }
  69988. pMem->flags &= ~MEM_Ephem;
  69989. #ifdef SQLITE_DEBUG
  69990. pMem->pScopyFrom = 0;
  69991. #endif
  69992. return SQLITE_OK;
  69993. }
  69994. /*
  69995. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  69996. ** blob stored in dynamically allocated space.
  69997. */
  69998. #ifndef SQLITE_OMIT_INCRBLOB
  69999. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  70000. int nByte;
  70001. assert( pMem->flags & MEM_Zero );
  70002. assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
  70003. testcase( sqlite3_value_nochange(pMem) );
  70004. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70005. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70006. /* Set nByte to the number of bytes required to store the expanded blob. */
  70007. nByte = pMem->n + pMem->u.nZero;
  70008. if( nByte<=0 ){
  70009. if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;
  70010. nByte = 1;
  70011. }
  70012. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  70013. return SQLITE_NOMEM_BKPT;
  70014. }
  70015. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  70016. pMem->n += pMem->u.nZero;
  70017. pMem->flags &= ~(MEM_Zero|MEM_Term);
  70018. return SQLITE_OK;
  70019. }
  70020. #endif
  70021. /*
  70022. ** Make sure the given Mem is \u0000 terminated.
  70023. */
  70024. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  70025. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70026. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  70027. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  70028. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  70029. return SQLITE_OK; /* Nothing to do */
  70030. }else{
  70031. return vdbeMemAddTerminator(pMem);
  70032. }
  70033. }
  70034. /*
  70035. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  70036. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  70037. ** is a no-op.
  70038. **
  70039. ** Existing representations MEM_Int and MEM_Real are invalidated if
  70040. ** bForce is true but are retained if bForce is false.
  70041. **
  70042. ** A MEM_Null value will never be passed to this function. This function is
  70043. ** used for converting values to text for returning to the user (i.e. via
  70044. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  70045. ** keys are strings. In the former case a NULL pointer is returned the
  70046. ** user and the latter is an internal programming error.
  70047. */
  70048. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  70049. int fg = pMem->flags;
  70050. const int nByte = 32;
  70051. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70052. assert( !(fg&MEM_Zero) );
  70053. assert( !(fg&(MEM_Str|MEM_Blob)) );
  70054. assert( fg&(MEM_Int|MEM_Real) );
  70055. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70056. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70057. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  70058. pMem->enc = 0;
  70059. return SQLITE_NOMEM_BKPT;
  70060. }
  70061. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  70062. ** string representation of the value. Then, if the required encoding
  70063. ** is UTF-16le or UTF-16be do a translation.
  70064. **
  70065. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  70066. */
  70067. if( fg & MEM_Int ){
  70068. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  70069. }else{
  70070. assert( fg & MEM_Real );
  70071. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  70072. }
  70073. assert( pMem->z!=0 );
  70074. pMem->n = sqlite3Strlen30NN(pMem->z);
  70075. pMem->enc = SQLITE_UTF8;
  70076. pMem->flags |= MEM_Str|MEM_Term;
  70077. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  70078. sqlite3VdbeChangeEncoding(pMem, enc);
  70079. return SQLITE_OK;
  70080. }
  70081. /*
  70082. ** Memory cell pMem contains the context of an aggregate function.
  70083. ** This routine calls the finalize method for that function. The
  70084. ** result of the aggregate is stored back into pMem.
  70085. **
  70086. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  70087. ** otherwise.
  70088. */
  70089. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  70090. sqlite3_context ctx;
  70091. Mem t;
  70092. assert( pFunc!=0 );
  70093. assert( pFunc->xFinalize!=0 );
  70094. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  70095. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70096. memset(&ctx, 0, sizeof(ctx));
  70097. memset(&t, 0, sizeof(t));
  70098. t.flags = MEM_Null;
  70099. t.db = pMem->db;
  70100. ctx.pOut = &t;
  70101. ctx.pMem = pMem;
  70102. ctx.pFunc = pFunc;
  70103. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  70104. assert( (pMem->flags & MEM_Dyn)==0 );
  70105. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  70106. memcpy(pMem, &t, sizeof(t));
  70107. return ctx.isError;
  70108. }
  70109. /*
  70110. ** Memory cell pAccum contains the context of an aggregate function.
  70111. ** This routine calls the xValue method for that function and stores
  70112. ** the results in memory cell pMem.
  70113. **
  70114. ** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK
  70115. ** otherwise.
  70116. */
  70117. #ifndef SQLITE_OMIT_WINDOWFUNC
  70118. SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
  70119. sqlite3_context ctx;
  70120. Mem t;
  70121. assert( pFunc!=0 );
  70122. assert( pFunc->xValue!=0 );
  70123. assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
  70124. assert( pAccum->db==0 || sqlite3_mutex_held(pAccum->db->mutex) );
  70125. memset(&ctx, 0, sizeof(ctx));
  70126. memset(&t, 0, sizeof(t));
  70127. t.flags = MEM_Null;
  70128. t.db = pAccum->db;
  70129. sqlite3VdbeMemSetNull(pOut);
  70130. ctx.pOut = pOut;
  70131. ctx.pMem = pAccum;
  70132. ctx.pFunc = pFunc;
  70133. pFunc->xValue(&ctx);
  70134. return ctx.isError;
  70135. }
  70136. #endif /* SQLITE_OMIT_WINDOWFUNC */
  70137. /*
  70138. ** If the memory cell contains a value that must be freed by
  70139. ** invoking the external callback in Mem.xDel, then this routine
  70140. ** will free that value. It also sets Mem.flags to MEM_Null.
  70141. **
  70142. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  70143. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  70144. ** entry point for releasing Mem resources.
  70145. */
  70146. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  70147. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  70148. assert( VdbeMemDynamic(p) );
  70149. if( p->flags&MEM_Agg ){
  70150. sqlite3VdbeMemFinalize(p, p->u.pDef);
  70151. assert( (p->flags & MEM_Agg)==0 );
  70152. testcase( p->flags & MEM_Dyn );
  70153. }
  70154. if( p->flags&MEM_Dyn ){
  70155. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  70156. p->xDel((void *)p->z);
  70157. }
  70158. p->flags = MEM_Null;
  70159. }
  70160. /*
  70161. ** Release memory held by the Mem p, both external memory cleared
  70162. ** by p->xDel and memory in p->zMalloc.
  70163. **
  70164. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  70165. ** the unusual case where there really is memory in p that needs
  70166. ** to be freed.
  70167. */
  70168. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  70169. if( VdbeMemDynamic(p) ){
  70170. vdbeMemClearExternAndSetNull(p);
  70171. }
  70172. if( p->szMalloc ){
  70173. sqlite3DbFreeNN(p->db, p->zMalloc);
  70174. p->szMalloc = 0;
  70175. }
  70176. p->z = 0;
  70177. }
  70178. /*
  70179. ** Release any memory resources held by the Mem. Both the memory that is
  70180. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  70181. **
  70182. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  70183. ** reset a Mem back to its minimum memory utilization.
  70184. **
  70185. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  70186. ** prior to inserting new content into the Mem.
  70187. */
  70188. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  70189. assert( sqlite3VdbeCheckMemInvariants(p) );
  70190. if( VdbeMemDynamic(p) || p->szMalloc ){
  70191. vdbeMemClear(p);
  70192. }
  70193. }
  70194. /*
  70195. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  70196. ** If the double is out of range of a 64-bit signed integer then
  70197. ** return the closest available 64-bit signed integer.
  70198. */
  70199. static SQLITE_NOINLINE i64 doubleToInt64(double r){
  70200. #ifdef SQLITE_OMIT_FLOATING_POINT
  70201. /* When floating-point is omitted, double and int64 are the same thing */
  70202. return r;
  70203. #else
  70204. /*
  70205. ** Many compilers we encounter do not define constants for the
  70206. ** minimum and maximum 64-bit integers, or they define them
  70207. ** inconsistently. And many do not understand the "LL" notation.
  70208. ** So we define our own static constants here using nothing
  70209. ** larger than a 32-bit integer constant.
  70210. */
  70211. static const i64 maxInt = LARGEST_INT64;
  70212. static const i64 minInt = SMALLEST_INT64;
  70213. if( r<=(double)minInt ){
  70214. return minInt;
  70215. }else if( r>=(double)maxInt ){
  70216. return maxInt;
  70217. }else{
  70218. return (i64)r;
  70219. }
  70220. #endif
  70221. }
  70222. /*
  70223. ** Return some kind of integer value which is the best we can do
  70224. ** at representing the value that *pMem describes as an integer.
  70225. ** If pMem is an integer, then the value is exact. If pMem is
  70226. ** a floating-point then the value returned is the integer part.
  70227. ** If pMem is a string or blob, then we make an attempt to convert
  70228. ** it into an integer and return that. If pMem represents an
  70229. ** an SQL-NULL value, return 0.
  70230. **
  70231. ** If pMem represents a string value, its encoding might be changed.
  70232. */
  70233. static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
  70234. i64 value = 0;
  70235. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  70236. return value;
  70237. }
  70238. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  70239. int flags;
  70240. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70241. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70242. flags = pMem->flags;
  70243. if( flags & MEM_Int ){
  70244. return pMem->u.i;
  70245. }else if( flags & MEM_Real ){
  70246. return doubleToInt64(pMem->u.r);
  70247. }else if( flags & (MEM_Str|MEM_Blob) ){
  70248. assert( pMem->z || pMem->n==0 );
  70249. return memIntValue(pMem);
  70250. }else{
  70251. return 0;
  70252. }
  70253. }
  70254. /*
  70255. ** Return the best representation of pMem that we can get into a
  70256. ** double. If pMem is already a double or an integer, return its
  70257. ** value. If it is a string or blob, try to convert it to a double.
  70258. ** If it is a NULL, return 0.0.
  70259. */
  70260. static SQLITE_NOINLINE double memRealValue(Mem *pMem){
  70261. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  70262. double val = (double)0;
  70263. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  70264. return val;
  70265. }
  70266. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  70267. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70268. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70269. if( pMem->flags & MEM_Real ){
  70270. return pMem->u.r;
  70271. }else if( pMem->flags & MEM_Int ){
  70272. return (double)pMem->u.i;
  70273. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  70274. return memRealValue(pMem);
  70275. }else{
  70276. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  70277. return (double)0;
  70278. }
  70279. }
  70280. /*
  70281. ** Return 1 if pMem represents true, and return 0 if pMem represents false.
  70282. ** Return the value ifNull if pMem is NULL.
  70283. */
  70284. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
  70285. if( pMem->flags & MEM_Int ) return pMem->u.i!=0;
  70286. if( pMem->flags & MEM_Null ) return ifNull;
  70287. return sqlite3VdbeRealValue(pMem)!=0.0;
  70288. }
  70289. /*
  70290. ** The MEM structure is already a MEM_Real. Try to also make it a
  70291. ** MEM_Int if we can.
  70292. */
  70293. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  70294. i64 ix;
  70295. assert( pMem->flags & MEM_Real );
  70296. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70297. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70298. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70299. ix = doubleToInt64(pMem->u.r);
  70300. /* Only mark the value as an integer if
  70301. **
  70302. ** (1) the round-trip conversion real->int->real is a no-op, and
  70303. ** (2) The integer is neither the largest nor the smallest
  70304. ** possible integer (ticket #3922)
  70305. **
  70306. ** The second and third terms in the following conditional enforces
  70307. ** the second condition under the assumption that addition overflow causes
  70308. ** values to wrap around.
  70309. */
  70310. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  70311. pMem->u.i = ix;
  70312. MemSetTypeFlag(pMem, MEM_Int);
  70313. }
  70314. }
  70315. /*
  70316. ** Convert pMem to type integer. Invalidate any prior representations.
  70317. */
  70318. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  70319. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70320. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70321. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70322. pMem->u.i = sqlite3VdbeIntValue(pMem);
  70323. MemSetTypeFlag(pMem, MEM_Int);
  70324. return SQLITE_OK;
  70325. }
  70326. /*
  70327. ** Convert pMem so that it is of type MEM_Real.
  70328. ** Invalidate any prior representations.
  70329. */
  70330. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  70331. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70332. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70333. pMem->u.r = sqlite3VdbeRealValue(pMem);
  70334. MemSetTypeFlag(pMem, MEM_Real);
  70335. return SQLITE_OK;
  70336. }
  70337. /* Compare a floating point value to an integer. Return true if the two
  70338. ** values are the same within the precision of the floating point value.
  70339. **
  70340. ** For some versions of GCC on 32-bit machines, if you do the more obvious
  70341. ** comparison of "r1==(double)i" you sometimes get an answer of false even
  70342. ** though the r1 and (double)i values are bit-for-bit the same.
  70343. */
  70344. static int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
  70345. double r2 = (double)i;
  70346. return memcmp(&r1, &r2, sizeof(r1))==0;
  70347. }
  70348. /*
  70349. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  70350. ** Invalidate any prior representations.
  70351. **
  70352. ** Every effort is made to force the conversion, even if the input
  70353. ** is a string that does not look completely like a number. Convert
  70354. ** as much of the string as we can and ignore the rest.
  70355. */
  70356. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  70357. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  70358. int rc;
  70359. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  70360. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70361. rc = sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc);
  70362. if( rc==0 ){
  70363. MemSetTypeFlag(pMem, MEM_Int);
  70364. }else{
  70365. i64 i = pMem->u.i;
  70366. sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
  70367. if( rc==1 && sqlite3RealSameAsInt(pMem->u.r, i) ){
  70368. pMem->u.i = i;
  70369. MemSetTypeFlag(pMem, MEM_Int);
  70370. }else{
  70371. MemSetTypeFlag(pMem, MEM_Real);
  70372. }
  70373. }
  70374. }
  70375. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  70376. pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
  70377. return SQLITE_OK;
  70378. }
  70379. /*
  70380. ** Cast the datatype of the value in pMem according to the affinity
  70381. ** "aff". Casting is different from applying affinity in that a cast
  70382. ** is forced. In other words, the value is converted into the desired
  70383. ** affinity even if that results in loss of data. This routine is
  70384. ** used (for example) to implement the SQL "cast()" operator.
  70385. */
  70386. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  70387. if( pMem->flags & MEM_Null ) return;
  70388. switch( aff ){
  70389. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  70390. if( (pMem->flags & MEM_Blob)==0 ){
  70391. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  70392. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  70393. if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
  70394. }else{
  70395. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  70396. }
  70397. break;
  70398. }
  70399. case SQLITE_AFF_NUMERIC: {
  70400. sqlite3VdbeMemNumerify(pMem);
  70401. break;
  70402. }
  70403. case SQLITE_AFF_INTEGER: {
  70404. sqlite3VdbeMemIntegerify(pMem);
  70405. break;
  70406. }
  70407. case SQLITE_AFF_REAL: {
  70408. sqlite3VdbeMemRealify(pMem);
  70409. break;
  70410. }
  70411. default: {
  70412. assert( aff==SQLITE_AFF_TEXT );
  70413. assert( MEM_Str==(MEM_Blob>>3) );
  70414. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  70415. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  70416. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  70417. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  70418. break;
  70419. }
  70420. }
  70421. }
  70422. /*
  70423. ** Initialize bulk memory to be a consistent Mem object.
  70424. **
  70425. ** The minimum amount of initialization feasible is performed.
  70426. */
  70427. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  70428. assert( (flags & ~MEM_TypeMask)==0 );
  70429. pMem->flags = flags;
  70430. pMem->db = db;
  70431. pMem->szMalloc = 0;
  70432. }
  70433. /*
  70434. ** Delete any previous value and set the value stored in *pMem to NULL.
  70435. **
  70436. ** This routine calls the Mem.xDel destructor to dispose of values that
  70437. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  70438. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  70439. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  70440. **
  70441. ** Use this routine to reset the Mem prior to insert a new value.
  70442. **
  70443. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  70444. */
  70445. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  70446. if( VdbeMemDynamic(pMem) ){
  70447. vdbeMemClearExternAndSetNull(pMem);
  70448. }else{
  70449. pMem->flags = MEM_Null;
  70450. }
  70451. }
  70452. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  70453. sqlite3VdbeMemSetNull((Mem*)p);
  70454. }
  70455. /*
  70456. ** Delete any previous value and set the value to be a BLOB of length
  70457. ** n containing all zeros.
  70458. */
  70459. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  70460. sqlite3VdbeMemRelease(pMem);
  70461. pMem->flags = MEM_Blob|MEM_Zero;
  70462. pMem->n = 0;
  70463. if( n<0 ) n = 0;
  70464. pMem->u.nZero = n;
  70465. pMem->enc = SQLITE_UTF8;
  70466. pMem->z = 0;
  70467. }
  70468. /*
  70469. ** The pMem is known to contain content that needs to be destroyed prior
  70470. ** to a value change. So invoke the destructor, then set the value to
  70471. ** a 64-bit integer.
  70472. */
  70473. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  70474. sqlite3VdbeMemSetNull(pMem);
  70475. pMem->u.i = val;
  70476. pMem->flags = MEM_Int;
  70477. }
  70478. /*
  70479. ** Delete any previous value and set the value stored in *pMem to val,
  70480. ** manifest type INTEGER.
  70481. */
  70482. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  70483. if( VdbeMemDynamic(pMem) ){
  70484. vdbeReleaseAndSetInt64(pMem, val);
  70485. }else{
  70486. pMem->u.i = val;
  70487. pMem->flags = MEM_Int;
  70488. }
  70489. }
  70490. /* A no-op destructor */
  70491. SQLITE_PRIVATE void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
  70492. /*
  70493. ** Set the value stored in *pMem should already be a NULL.
  70494. ** Also store a pointer to go with it.
  70495. */
  70496. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
  70497. Mem *pMem,
  70498. void *pPtr,
  70499. const char *zPType,
  70500. void (*xDestructor)(void*)
  70501. ){
  70502. assert( pMem->flags==MEM_Null );
  70503. pMem->u.zPType = zPType ? zPType : "";
  70504. pMem->z = pPtr;
  70505. pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
  70506. pMem->eSubtype = 'p';
  70507. pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
  70508. }
  70509. #ifndef SQLITE_OMIT_FLOATING_POINT
  70510. /*
  70511. ** Delete any previous value and set the value stored in *pMem to val,
  70512. ** manifest type REAL.
  70513. */
  70514. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  70515. sqlite3VdbeMemSetNull(pMem);
  70516. if( !sqlite3IsNaN(val) ){
  70517. pMem->u.r = val;
  70518. pMem->flags = MEM_Real;
  70519. }
  70520. }
  70521. #endif
  70522. #ifdef SQLITE_DEBUG
  70523. /*
  70524. ** Return true if the Mem holds a RowSet object. This routine is intended
  70525. ** for use inside of assert() statements.
  70526. */
  70527. SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem *pMem){
  70528. return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
  70529. && pMem->xDel==sqlite3RowSetDelete;
  70530. }
  70531. #endif
  70532. /*
  70533. ** Delete any previous value and set the value of pMem to be an
  70534. ** empty boolean index.
  70535. **
  70536. ** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation
  70537. ** error occurs.
  70538. */
  70539. SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem *pMem){
  70540. sqlite3 *db = pMem->db;
  70541. RowSet *p;
  70542. assert( db!=0 );
  70543. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70544. sqlite3VdbeMemRelease(pMem);
  70545. p = sqlite3RowSetInit(db);
  70546. if( p==0 ) return SQLITE_NOMEM;
  70547. pMem->z = (char*)p;
  70548. pMem->flags = MEM_Blob|MEM_Dyn;
  70549. pMem->xDel = sqlite3RowSetDelete;
  70550. return SQLITE_OK;
  70551. }
  70552. /*
  70553. ** Return true if the Mem object contains a TEXT or BLOB that is
  70554. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  70555. */
  70556. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  70557. assert( p->db!=0 );
  70558. if( p->flags & (MEM_Str|MEM_Blob) ){
  70559. int n = p->n;
  70560. if( p->flags & MEM_Zero ){
  70561. n += p->u.nZero;
  70562. }
  70563. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  70564. }
  70565. return 0;
  70566. }
  70567. #ifdef SQLITE_DEBUG
  70568. /*
  70569. ** This routine prepares a memory cell for modification by breaking
  70570. ** its link to a shallow copy and by marking any current shallow
  70571. ** copies of this cell as invalid.
  70572. **
  70573. ** This is used for testing and debugging only - to make sure shallow
  70574. ** copies are not misused.
  70575. */
  70576. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  70577. int i;
  70578. Mem *pX;
  70579. for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
  70580. if( pX->pScopyFrom==pMem ){
  70581. /* If pX is marked as a shallow copy of pMem, then verify that
  70582. ** no significant changes have been made to pX since the OP_SCopy.
  70583. ** A significant change would indicated a missed call to this
  70584. ** function for pX. Minor changes, such as adding or removing a
  70585. ** dual type, are allowed, as long as the underlying value is the
  70586. ** same. */
  70587. u16 mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
  70588. assert( (mFlags&MEM_Int)==0 || pMem->u.i==pX->u.i );
  70589. assert( (mFlags&MEM_Real)==0 || pMem->u.r==pX->u.r );
  70590. assert( (mFlags&MEM_Str)==0 || (pMem->n==pX->n && pMem->z==pX->z) );
  70591. assert( (mFlags&MEM_Blob)==0 || sqlite3BlobCompare(pMem,pX)==0 );
  70592. /* pMem is the register that is changing. But also mark pX as
  70593. ** undefined so that we can quickly detect the shallow-copy error */
  70594. pX->flags = MEM_Undefined;
  70595. pX->pScopyFrom = 0;
  70596. }
  70597. }
  70598. pMem->pScopyFrom = 0;
  70599. }
  70600. #endif /* SQLITE_DEBUG */
  70601. /*
  70602. ** Make an shallow copy of pFrom into pTo. Prior contents of
  70603. ** pTo are freed. The pFrom->z field is not duplicated. If
  70604. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  70605. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  70606. */
  70607. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  70608. vdbeMemClearExternAndSetNull(pTo);
  70609. assert( !VdbeMemDynamic(pTo) );
  70610. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  70611. }
  70612. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  70613. assert( !sqlite3VdbeMemIsRowSet(pFrom) );
  70614. assert( pTo->db==pFrom->db );
  70615. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  70616. memcpy(pTo, pFrom, MEMCELLSIZE);
  70617. if( (pFrom->flags&MEM_Static)==0 ){
  70618. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  70619. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  70620. pTo->flags |= srcType;
  70621. }
  70622. }
  70623. /*
  70624. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  70625. ** freed before the copy is made.
  70626. */
  70627. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  70628. int rc = SQLITE_OK;
  70629. assert( !sqlite3VdbeMemIsRowSet(pFrom) );
  70630. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  70631. memcpy(pTo, pFrom, MEMCELLSIZE);
  70632. pTo->flags &= ~MEM_Dyn;
  70633. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  70634. if( 0==(pFrom->flags&MEM_Static) ){
  70635. pTo->flags |= MEM_Ephem;
  70636. rc = sqlite3VdbeMemMakeWriteable(pTo);
  70637. }
  70638. }
  70639. return rc;
  70640. }
  70641. /*
  70642. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  70643. ** freed. If pFrom contains ephemeral data, a copy is made.
  70644. **
  70645. ** pFrom contains an SQL NULL when this routine returns.
  70646. */
  70647. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  70648. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  70649. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  70650. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  70651. sqlite3VdbeMemRelease(pTo);
  70652. memcpy(pTo, pFrom, sizeof(Mem));
  70653. pFrom->flags = MEM_Null;
  70654. pFrom->szMalloc = 0;
  70655. }
  70656. /*
  70657. ** Change the value of a Mem to be a string or a BLOB.
  70658. **
  70659. ** The memory management strategy depends on the value of the xDel
  70660. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  70661. ** string is copied into a (possibly existing) buffer managed by the
  70662. ** Mem structure. Otherwise, any existing buffer is freed and the
  70663. ** pointer copied.
  70664. **
  70665. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  70666. ** size limit) then no memory allocation occurs. If the string can be
  70667. ** stored without allocating memory, then it is. If a memory allocation
  70668. ** is required to store the string, then value of pMem is unchanged. In
  70669. ** either case, SQLITE_TOOBIG is returned.
  70670. */
  70671. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  70672. Mem *pMem, /* Memory cell to set to string value */
  70673. const char *z, /* String pointer */
  70674. int n, /* Bytes in string, or negative */
  70675. u8 enc, /* Encoding of z. 0 for BLOBs */
  70676. void (*xDel)(void*) /* Destructor function */
  70677. ){
  70678. int nByte = n; /* New value for pMem->n */
  70679. int iLimit; /* Maximum allowed string or blob size */
  70680. u16 flags = 0; /* New value for pMem->flags */
  70681. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  70682. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70683. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  70684. if( !z ){
  70685. sqlite3VdbeMemSetNull(pMem);
  70686. return SQLITE_OK;
  70687. }
  70688. if( pMem->db ){
  70689. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  70690. }else{
  70691. iLimit = SQLITE_MAX_LENGTH;
  70692. }
  70693. flags = (enc==0?MEM_Blob:MEM_Str);
  70694. if( nByte<0 ){
  70695. assert( enc!=0 );
  70696. if( enc==SQLITE_UTF8 ){
  70697. nByte = 0x7fffffff & (int)strlen(z);
  70698. }else{
  70699. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  70700. }
  70701. flags |= MEM_Term;
  70702. }
  70703. /* The following block sets the new values of Mem.z and Mem.xDel. It
  70704. ** also sets a flag in local variable "flags" to indicate the memory
  70705. ** management (one of MEM_Dyn or MEM_Static).
  70706. */
  70707. if( xDel==SQLITE_TRANSIENT ){
  70708. u32 nAlloc = nByte;
  70709. if( flags&MEM_Term ){
  70710. nAlloc += (enc==SQLITE_UTF8?1:2);
  70711. }
  70712. if( nByte>iLimit ){
  70713. return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
  70714. }
  70715. testcase( nAlloc==0 );
  70716. testcase( nAlloc==31 );
  70717. testcase( nAlloc==32 );
  70718. if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){
  70719. return SQLITE_NOMEM_BKPT;
  70720. }
  70721. memcpy(pMem->z, z, nAlloc);
  70722. }else{
  70723. sqlite3VdbeMemRelease(pMem);
  70724. pMem->z = (char *)z;
  70725. if( xDel==SQLITE_DYNAMIC ){
  70726. pMem->zMalloc = pMem->z;
  70727. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  70728. }else{
  70729. pMem->xDel = xDel;
  70730. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  70731. }
  70732. }
  70733. pMem->n = nByte;
  70734. pMem->flags = flags;
  70735. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  70736. #ifndef SQLITE_OMIT_UTF16
  70737. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  70738. return SQLITE_NOMEM_BKPT;
  70739. }
  70740. #endif
  70741. if( nByte>iLimit ){
  70742. return SQLITE_TOOBIG;
  70743. }
  70744. return SQLITE_OK;
  70745. }
  70746. /*
  70747. ** Move data out of a btree key or data field and into a Mem structure.
  70748. ** The data is payload from the entry that pCur is currently pointing
  70749. ** to. offset and amt determine what portion of the data or key to retrieve.
  70750. ** The result is written into the pMem element.
  70751. **
  70752. ** The pMem object must have been initialized. This routine will use
  70753. ** pMem->zMalloc to hold the content from the btree, if possible. New
  70754. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  70755. ** is responsible for making sure that the pMem object is eventually
  70756. ** destroyed.
  70757. **
  70758. ** If this routine fails for any reason (malloc returns NULL or unable
  70759. ** to read from the disk) then the pMem is left in an inconsistent state.
  70760. */
  70761. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  70762. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  70763. u32 offset, /* Offset from the start of data to return bytes from. */
  70764. u32 amt, /* Number of bytes to return. */
  70765. Mem *pMem /* OUT: Return data in this Mem structure. */
  70766. ){
  70767. int rc;
  70768. pMem->flags = MEM_Null;
  70769. if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){
  70770. return SQLITE_CORRUPT_BKPT;
  70771. }
  70772. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
  70773. rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
  70774. if( rc==SQLITE_OK ){
  70775. pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
  70776. pMem->flags = MEM_Blob;
  70777. pMem->n = (int)amt;
  70778. }else{
  70779. sqlite3VdbeMemRelease(pMem);
  70780. }
  70781. }
  70782. return rc;
  70783. }
  70784. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  70785. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  70786. u32 offset, /* Offset from the start of data to return bytes from. */
  70787. u32 amt, /* Number of bytes to return. */
  70788. Mem *pMem /* OUT: Return data in this Mem structure. */
  70789. ){
  70790. char *zData; /* Data from the btree layer */
  70791. u32 available = 0; /* Number of bytes available on the local btree page */
  70792. int rc = SQLITE_OK; /* Return code */
  70793. assert( sqlite3BtreeCursorIsValid(pCur) );
  70794. assert( !VdbeMemDynamic(pMem) );
  70795. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  70796. ** that both the BtShared and database handle mutexes are held. */
  70797. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  70798. zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
  70799. assert( zData!=0 );
  70800. if( offset+amt<=available ){
  70801. pMem->z = &zData[offset];
  70802. pMem->flags = MEM_Blob|MEM_Ephem;
  70803. pMem->n = (int)amt;
  70804. }else{
  70805. rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
  70806. }
  70807. return rc;
  70808. }
  70809. /*
  70810. ** The pVal argument is known to be a value other than NULL.
  70811. ** Convert it into a string with encoding enc and return a pointer
  70812. ** to a zero-terminated version of that string.
  70813. */
  70814. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  70815. assert( pVal!=0 );
  70816. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  70817. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  70818. assert( !sqlite3VdbeMemIsRowSet(pVal) );
  70819. assert( (pVal->flags & (MEM_Null))==0 );
  70820. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  70821. if( ExpandBlob(pVal) ) return 0;
  70822. pVal->flags |= MEM_Str;
  70823. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  70824. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  70825. }
  70826. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  70827. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  70828. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  70829. return 0;
  70830. }
  70831. }
  70832. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  70833. }else{
  70834. sqlite3VdbeMemStringify(pVal, enc, 0);
  70835. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  70836. }
  70837. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  70838. || pVal->db->mallocFailed );
  70839. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  70840. assert( sqlite3VdbeMemConsistentDualRep(pVal) );
  70841. return pVal->z;
  70842. }else{
  70843. return 0;
  70844. }
  70845. }
  70846. /* This function is only available internally, it is not part of the
  70847. ** external API. It works in a similar way to sqlite3_value_text(),
  70848. ** except the data returned is in the encoding specified by the second
  70849. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  70850. ** SQLITE_UTF8.
  70851. **
  70852. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  70853. ** If that is the case, then the result must be aligned on an even byte
  70854. ** boundary.
  70855. */
  70856. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  70857. if( !pVal ) return 0;
  70858. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  70859. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  70860. assert( !sqlite3VdbeMemIsRowSet(pVal) );
  70861. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  70862. assert( sqlite3VdbeMemConsistentDualRep(pVal) );
  70863. return pVal->z;
  70864. }
  70865. if( pVal->flags&MEM_Null ){
  70866. return 0;
  70867. }
  70868. return valueToText(pVal, enc);
  70869. }
  70870. /*
  70871. ** Create a new sqlite3_value object.
  70872. */
  70873. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  70874. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  70875. if( p ){
  70876. p->flags = MEM_Null;
  70877. p->db = db;
  70878. }
  70879. return p;
  70880. }
  70881. /*
  70882. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  70883. ** valueNew(). See comments above valueNew() for details.
  70884. */
  70885. struct ValueNewStat4Ctx {
  70886. Parse *pParse;
  70887. Index *pIdx;
  70888. UnpackedRecord **ppRec;
  70889. int iVal;
  70890. };
  70891. /*
  70892. ** Allocate and return a pointer to a new sqlite3_value object. If
  70893. ** the second argument to this function is NULL, the object is allocated
  70894. ** by calling sqlite3ValueNew().
  70895. **
  70896. ** Otherwise, if the second argument is non-zero, then this function is
  70897. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  70898. ** already been allocated, allocate the UnpackedRecord structure that
  70899. ** that function will return to its caller here. Then return a pointer to
  70900. ** an sqlite3_value within the UnpackedRecord.a[] array.
  70901. */
  70902. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  70903. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  70904. if( p ){
  70905. UnpackedRecord *pRec = p->ppRec[0];
  70906. if( pRec==0 ){
  70907. Index *pIdx = p->pIdx; /* Index being probed */
  70908. int nByte; /* Bytes of space to allocate */
  70909. int i; /* Counter variable */
  70910. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  70911. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  70912. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  70913. if( pRec ){
  70914. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  70915. if( pRec->pKeyInfo ){
  70916. assert( pRec->pKeyInfo->nAllField==nCol );
  70917. assert( pRec->pKeyInfo->enc==ENC(db) );
  70918. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  70919. for(i=0; i<nCol; i++){
  70920. pRec->aMem[i].flags = MEM_Null;
  70921. pRec->aMem[i].db = db;
  70922. }
  70923. }else{
  70924. sqlite3DbFreeNN(db, pRec);
  70925. pRec = 0;
  70926. }
  70927. }
  70928. if( pRec==0 ) return 0;
  70929. p->ppRec[0] = pRec;
  70930. }
  70931. pRec->nField = p->iVal+1;
  70932. return &pRec->aMem[p->iVal];
  70933. }
  70934. #else
  70935. UNUSED_PARAMETER(p);
  70936. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  70937. return sqlite3ValueNew(db);
  70938. }
  70939. /*
  70940. ** The expression object indicated by the second argument is guaranteed
  70941. ** to be a scalar SQL function. If
  70942. **
  70943. ** * all function arguments are SQL literals,
  70944. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  70945. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  70946. **
  70947. ** then this routine attempts to invoke the SQL function. Assuming no
  70948. ** error occurs, output parameter (*ppVal) is set to point to a value
  70949. ** object containing the result before returning SQLITE_OK.
  70950. **
  70951. ** Affinity aff is applied to the result of the function before returning.
  70952. ** If the result is a text value, the sqlite3_value object uses encoding
  70953. ** enc.
  70954. **
  70955. ** If the conditions above are not met, this function returns SQLITE_OK
  70956. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  70957. ** NULL and an SQLite error code returned.
  70958. */
  70959. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  70960. static int valueFromFunction(
  70961. sqlite3 *db, /* The database connection */
  70962. Expr *p, /* The expression to evaluate */
  70963. u8 enc, /* Encoding to use */
  70964. u8 aff, /* Affinity to use */
  70965. sqlite3_value **ppVal, /* Write the new value here */
  70966. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  70967. ){
  70968. sqlite3_context ctx; /* Context object for function invocation */
  70969. sqlite3_value **apVal = 0; /* Function arguments */
  70970. int nVal = 0; /* Size of apVal[] array */
  70971. FuncDef *pFunc = 0; /* Function definition */
  70972. sqlite3_value *pVal = 0; /* New value */
  70973. int rc = SQLITE_OK; /* Return code */
  70974. ExprList *pList = 0; /* Function arguments */
  70975. int i; /* Iterator variable */
  70976. assert( pCtx!=0 );
  70977. assert( (p->flags & EP_TokenOnly)==0 );
  70978. pList = p->x.pList;
  70979. if( pList ) nVal = pList->nExpr;
  70980. pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
  70981. assert( pFunc );
  70982. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  70983. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  70984. ){
  70985. return SQLITE_OK;
  70986. }
  70987. if( pList ){
  70988. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  70989. if( apVal==0 ){
  70990. rc = SQLITE_NOMEM_BKPT;
  70991. goto value_from_function_out;
  70992. }
  70993. for(i=0; i<nVal; i++){
  70994. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  70995. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  70996. }
  70997. }
  70998. pVal = valueNew(db, pCtx);
  70999. if( pVal==0 ){
  71000. rc = SQLITE_NOMEM_BKPT;
  71001. goto value_from_function_out;
  71002. }
  71003. assert( pCtx->pParse->rc==SQLITE_OK );
  71004. memset(&ctx, 0, sizeof(ctx));
  71005. ctx.pOut = pVal;
  71006. ctx.pFunc = pFunc;
  71007. pFunc->xSFunc(&ctx, nVal, apVal);
  71008. if( ctx.isError ){
  71009. rc = ctx.isError;
  71010. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  71011. }else{
  71012. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  71013. assert( rc==SQLITE_OK );
  71014. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  71015. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  71016. rc = SQLITE_TOOBIG;
  71017. pCtx->pParse->nErr++;
  71018. }
  71019. }
  71020. pCtx->pParse->rc = rc;
  71021. value_from_function_out:
  71022. if( rc!=SQLITE_OK ){
  71023. pVal = 0;
  71024. }
  71025. if( apVal ){
  71026. for(i=0; i<nVal; i++){
  71027. sqlite3ValueFree(apVal[i]);
  71028. }
  71029. sqlite3DbFreeNN(db, apVal);
  71030. }
  71031. *ppVal = pVal;
  71032. return rc;
  71033. }
  71034. #else
  71035. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  71036. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  71037. /*
  71038. ** Extract a value from the supplied expression in the manner described
  71039. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  71040. ** using valueNew().
  71041. **
  71042. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  71043. ** has been allocated, it is freed before returning. Or, if pCtx is not
  71044. ** NULL, it is assumed that the caller will free any allocated object
  71045. ** in all cases.
  71046. */
  71047. static int valueFromExpr(
  71048. sqlite3 *db, /* The database connection */
  71049. Expr *pExpr, /* The expression to evaluate */
  71050. u8 enc, /* Encoding to use */
  71051. u8 affinity, /* Affinity to use */
  71052. sqlite3_value **ppVal, /* Write the new value here */
  71053. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  71054. ){
  71055. int op;
  71056. char *zVal = 0;
  71057. sqlite3_value *pVal = 0;
  71058. int negInt = 1;
  71059. const char *zNeg = "";
  71060. int rc = SQLITE_OK;
  71061. assert( pExpr!=0 );
  71062. while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
  71063. #if defined(SQLITE_ENABLE_STAT3_OR_STAT4)
  71064. if( op==TK_REGISTER ) op = pExpr->op2;
  71065. #else
  71066. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  71067. #endif
  71068. /* Compressed expressions only appear when parsing the DEFAULT clause
  71069. ** on a table column definition, and hence only when pCtx==0. This
  71070. ** check ensures that an EP_TokenOnly expression is never passed down
  71071. ** into valueFromFunction(). */
  71072. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  71073. if( op==TK_CAST ){
  71074. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  71075. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  71076. testcase( rc!=SQLITE_OK );
  71077. if( *ppVal ){
  71078. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  71079. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  71080. }
  71081. return rc;
  71082. }
  71083. /* Handle negative integers in a single step. This is needed in the
  71084. ** case when the value is -9223372036854775808.
  71085. */
  71086. if( op==TK_UMINUS
  71087. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  71088. pExpr = pExpr->pLeft;
  71089. op = pExpr->op;
  71090. negInt = -1;
  71091. zNeg = "-";
  71092. }
  71093. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  71094. pVal = valueNew(db, pCtx);
  71095. if( pVal==0 ) goto no_mem;
  71096. if( ExprHasProperty(pExpr, EP_IntValue) ){
  71097. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  71098. }else{
  71099. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  71100. if( zVal==0 ) goto no_mem;
  71101. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  71102. }
  71103. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  71104. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  71105. }else{
  71106. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  71107. }
  71108. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  71109. if( enc!=SQLITE_UTF8 ){
  71110. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  71111. }
  71112. }else if( op==TK_UMINUS ) {
  71113. /* This branch happens for multiple negative signs. Ex: -(-5) */
  71114. if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
  71115. && pVal!=0
  71116. ){
  71117. sqlite3VdbeMemNumerify(pVal);
  71118. if( pVal->flags & MEM_Real ){
  71119. pVal->u.r = -pVal->u.r;
  71120. }else if( pVal->u.i==SMALLEST_INT64 ){
  71121. pVal->u.r = -(double)SMALLEST_INT64;
  71122. MemSetTypeFlag(pVal, MEM_Real);
  71123. }else{
  71124. pVal->u.i = -pVal->u.i;
  71125. }
  71126. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  71127. }
  71128. }else if( op==TK_NULL ){
  71129. pVal = valueNew(db, pCtx);
  71130. if( pVal==0 ) goto no_mem;
  71131. sqlite3VdbeMemNumerify(pVal);
  71132. }
  71133. #ifndef SQLITE_OMIT_BLOB_LITERAL
  71134. else if( op==TK_BLOB ){
  71135. int nVal;
  71136. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  71137. assert( pExpr->u.zToken[1]=='\'' );
  71138. pVal = valueNew(db, pCtx);
  71139. if( !pVal ) goto no_mem;
  71140. zVal = &pExpr->u.zToken[2];
  71141. nVal = sqlite3Strlen30(zVal)-1;
  71142. assert( zVal[nVal]=='\'' );
  71143. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  71144. 0, SQLITE_DYNAMIC);
  71145. }
  71146. #endif
  71147. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71148. else if( op==TK_FUNCTION && pCtx!=0 ){
  71149. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  71150. }
  71151. #endif
  71152. else if( op==TK_TRUEFALSE ){
  71153. pVal = valueNew(db, pCtx);
  71154. if( pVal ){
  71155. pVal->flags = MEM_Int;
  71156. pVal->u.i = pExpr->u.zToken[4]==0;
  71157. }
  71158. }
  71159. *ppVal = pVal;
  71160. return rc;
  71161. no_mem:
  71162. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71163. if( pCtx==0 || pCtx->pParse->nErr==0 )
  71164. #endif
  71165. sqlite3OomFault(db);
  71166. sqlite3DbFree(db, zVal);
  71167. assert( *ppVal==0 );
  71168. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71169. if( pCtx==0 ) sqlite3ValueFree(pVal);
  71170. #else
  71171. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  71172. #endif
  71173. return SQLITE_NOMEM_BKPT;
  71174. }
  71175. /*
  71176. ** Create a new sqlite3_value object, containing the value of pExpr.
  71177. **
  71178. ** This only works for very simple expressions that consist of one constant
  71179. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  71180. ** be converted directly into a value, then the value is allocated and
  71181. ** a pointer written to *ppVal. The caller is responsible for deallocating
  71182. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  71183. ** cannot be converted to a value, then *ppVal is set to NULL.
  71184. */
  71185. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  71186. sqlite3 *db, /* The database connection */
  71187. Expr *pExpr, /* The expression to evaluate */
  71188. u8 enc, /* Encoding to use */
  71189. u8 affinity, /* Affinity to use */
  71190. sqlite3_value **ppVal /* Write the new value here */
  71191. ){
  71192. return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
  71193. }
  71194. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  71195. /*
  71196. ** The implementation of the sqlite_record() function. This function accepts
  71197. ** a single argument of any type. The return value is a formatted database
  71198. ** record (a blob) containing the argument value.
  71199. **
  71200. ** This is used to convert the value stored in the 'sample' column of the
  71201. ** sqlite_stat3 table to the record format SQLite uses internally.
  71202. */
  71203. static void recordFunc(
  71204. sqlite3_context *context,
  71205. int argc,
  71206. sqlite3_value **argv
  71207. ){
  71208. const int file_format = 1;
  71209. u32 iSerial; /* Serial type */
  71210. int nSerial; /* Bytes of space for iSerial as varint */
  71211. u32 nVal; /* Bytes of space required for argv[0] */
  71212. int nRet;
  71213. sqlite3 *db;
  71214. u8 *aRet;
  71215. UNUSED_PARAMETER( argc );
  71216. iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
  71217. nSerial = sqlite3VarintLen(iSerial);
  71218. db = sqlite3_context_db_handle(context);
  71219. nRet = 1 + nSerial + nVal;
  71220. aRet = sqlite3DbMallocRawNN(db, nRet);
  71221. if( aRet==0 ){
  71222. sqlite3_result_error_nomem(context);
  71223. }else{
  71224. aRet[0] = nSerial+1;
  71225. putVarint32(&aRet[1], iSerial);
  71226. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  71227. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  71228. sqlite3DbFreeNN(db, aRet);
  71229. }
  71230. }
  71231. /*
  71232. ** Register built-in functions used to help read ANALYZE data.
  71233. */
  71234. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  71235. static FuncDef aAnalyzeTableFuncs[] = {
  71236. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  71237. };
  71238. sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
  71239. }
  71240. /*
  71241. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  71242. **
  71243. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  71244. ** pAlloc if one does not exist and the new value is added to the
  71245. ** UnpackedRecord object.
  71246. **
  71247. ** A value is extracted in the following cases:
  71248. **
  71249. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  71250. **
  71251. ** * The expression is a bound variable, and this is a reprepare, or
  71252. **
  71253. ** * The expression is a literal value.
  71254. **
  71255. ** On success, *ppVal is made to point to the extracted value. The caller
  71256. ** is responsible for ensuring that the value is eventually freed.
  71257. */
  71258. static int stat4ValueFromExpr(
  71259. Parse *pParse, /* Parse context */
  71260. Expr *pExpr, /* The expression to extract a value from */
  71261. u8 affinity, /* Affinity to use */
  71262. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  71263. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  71264. ){
  71265. int rc = SQLITE_OK;
  71266. sqlite3_value *pVal = 0;
  71267. sqlite3 *db = pParse->db;
  71268. /* Skip over any TK_COLLATE nodes */
  71269. pExpr = sqlite3ExprSkipCollate(pExpr);
  71270. assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
  71271. if( !pExpr ){
  71272. pVal = valueNew(db, pAlloc);
  71273. if( pVal ){
  71274. sqlite3VdbeMemSetNull((Mem*)pVal);
  71275. }
  71276. }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  71277. Vdbe *v;
  71278. int iBindVar = pExpr->iColumn;
  71279. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  71280. if( (v = pParse->pReprepare)!=0 ){
  71281. pVal = valueNew(db, pAlloc);
  71282. if( pVal ){
  71283. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  71284. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  71285. pVal->db = pParse->db;
  71286. }
  71287. }
  71288. }else{
  71289. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  71290. }
  71291. assert( pVal==0 || pVal->db==db );
  71292. *ppVal = pVal;
  71293. return rc;
  71294. }
  71295. /*
  71296. ** This function is used to allocate and populate UnpackedRecord
  71297. ** structures intended to be compared against sample index keys stored
  71298. ** in the sqlite_stat4 table.
  71299. **
  71300. ** A single call to this function populates zero or more fields of the
  71301. ** record starting with field iVal (fields are numbered from left to
  71302. ** right starting with 0). A single field is populated if:
  71303. **
  71304. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  71305. **
  71306. ** * The expression is a bound variable, and this is a reprepare, or
  71307. **
  71308. ** * The sqlite3ValueFromExpr() function is able to extract a value
  71309. ** from the expression (i.e. the expression is a literal value).
  71310. **
  71311. ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
  71312. ** vector components that match either of the two latter criteria listed
  71313. ** above.
  71314. **
  71315. ** Before any value is appended to the record, the affinity of the
  71316. ** corresponding column within index pIdx is applied to it. Before
  71317. ** this function returns, output parameter *pnExtract is set to the
  71318. ** number of values appended to the record.
  71319. **
  71320. ** When this function is called, *ppRec must either point to an object
  71321. ** allocated by an earlier call to this function, or must be NULL. If it
  71322. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  71323. ** is allocated (and *ppRec set to point to it) before returning.
  71324. **
  71325. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  71326. ** error if a value cannot be extracted from pExpr. If an error does
  71327. ** occur, an SQLite error code is returned.
  71328. */
  71329. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  71330. Parse *pParse, /* Parse context */
  71331. Index *pIdx, /* Index being probed */
  71332. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  71333. Expr *pExpr, /* The expression to extract a value from */
  71334. int nElem, /* Maximum number of values to append */
  71335. int iVal, /* Array element to populate */
  71336. int *pnExtract /* OUT: Values appended to the record */
  71337. ){
  71338. int rc = SQLITE_OK;
  71339. int nExtract = 0;
  71340. if( pExpr==0 || pExpr->op!=TK_SELECT ){
  71341. int i;
  71342. struct ValueNewStat4Ctx alloc;
  71343. alloc.pParse = pParse;
  71344. alloc.pIdx = pIdx;
  71345. alloc.ppRec = ppRec;
  71346. for(i=0; i<nElem; i++){
  71347. sqlite3_value *pVal = 0;
  71348. Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
  71349. u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
  71350. alloc.iVal = iVal+i;
  71351. rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
  71352. if( !pVal ) break;
  71353. nExtract++;
  71354. }
  71355. }
  71356. *pnExtract = nExtract;
  71357. return rc;
  71358. }
  71359. /*
  71360. ** Attempt to extract a value from expression pExpr using the methods
  71361. ** as described for sqlite3Stat4ProbeSetValue() above.
  71362. **
  71363. ** If successful, set *ppVal to point to a new value object and return
  71364. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  71365. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  71366. ** does occur, return an SQLite error code. The final value of *ppVal
  71367. ** is undefined in this case.
  71368. */
  71369. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  71370. Parse *pParse, /* Parse context */
  71371. Expr *pExpr, /* The expression to extract a value from */
  71372. u8 affinity, /* Affinity to use */
  71373. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  71374. ){
  71375. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  71376. }
  71377. /*
  71378. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  71379. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  71380. ** sqlite3_value object is allocated.
  71381. **
  71382. ** If *ppVal is initially NULL then the caller is responsible for
  71383. ** ensuring that the value written into *ppVal is eventually freed.
  71384. */
  71385. SQLITE_PRIVATE int sqlite3Stat4Column(
  71386. sqlite3 *db, /* Database handle */
  71387. const void *pRec, /* Pointer to buffer containing record */
  71388. int nRec, /* Size of buffer pRec in bytes */
  71389. int iCol, /* Column to extract */
  71390. sqlite3_value **ppVal /* OUT: Extracted value */
  71391. ){
  71392. u32 t = 0; /* a column type code */
  71393. int nHdr; /* Size of the header in the record */
  71394. int iHdr; /* Next unread header byte */
  71395. int iField; /* Next unread data byte */
  71396. int szField = 0; /* Size of the current data field */
  71397. int i; /* Column index */
  71398. u8 *a = (u8*)pRec; /* Typecast byte array */
  71399. Mem *pMem = *ppVal; /* Write result into this Mem object */
  71400. assert( iCol>0 );
  71401. iHdr = getVarint32(a, nHdr);
  71402. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  71403. iField = nHdr;
  71404. for(i=0; i<=iCol; i++){
  71405. iHdr += getVarint32(&a[iHdr], t);
  71406. testcase( iHdr==nHdr );
  71407. testcase( iHdr==nHdr+1 );
  71408. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  71409. szField = sqlite3VdbeSerialTypeLen(t);
  71410. iField += szField;
  71411. }
  71412. testcase( iField==nRec );
  71413. testcase( iField==nRec+1 );
  71414. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  71415. if( pMem==0 ){
  71416. pMem = *ppVal = sqlite3ValueNew(db);
  71417. if( pMem==0 ) return SQLITE_NOMEM_BKPT;
  71418. }
  71419. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  71420. pMem->enc = ENC(db);
  71421. return SQLITE_OK;
  71422. }
  71423. /*
  71424. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  71425. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  71426. ** the object.
  71427. */
  71428. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  71429. if( pRec ){
  71430. int i;
  71431. int nCol = pRec->pKeyInfo->nAllField;
  71432. Mem *aMem = pRec->aMem;
  71433. sqlite3 *db = aMem[0].db;
  71434. for(i=0; i<nCol; i++){
  71435. sqlite3VdbeMemRelease(&aMem[i]);
  71436. }
  71437. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  71438. sqlite3DbFreeNN(db, pRec);
  71439. }
  71440. }
  71441. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  71442. /*
  71443. ** Change the string value of an sqlite3_value object
  71444. */
  71445. SQLITE_PRIVATE void sqlite3ValueSetStr(
  71446. sqlite3_value *v, /* Value to be set */
  71447. int n, /* Length of string z */
  71448. const void *z, /* Text of the new string */
  71449. u8 enc, /* Encoding to use */
  71450. void (*xDel)(void*) /* Destructor for the string */
  71451. ){
  71452. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  71453. }
  71454. /*
  71455. ** Free an sqlite3_value object
  71456. */
  71457. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  71458. if( !v ) return;
  71459. sqlite3VdbeMemRelease((Mem *)v);
  71460. sqlite3DbFreeNN(((Mem*)v)->db, v);
  71461. }
  71462. /*
  71463. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  71464. ** sqlite3_value object assuming that it uses the encoding "enc".
  71465. ** The valueBytes() routine is a helper function.
  71466. */
  71467. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  71468. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  71469. }
  71470. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  71471. Mem *p = (Mem*)pVal;
  71472. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  71473. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  71474. return p->n;
  71475. }
  71476. if( (p->flags & MEM_Blob)!=0 ){
  71477. if( p->flags & MEM_Zero ){
  71478. return p->n + p->u.nZero;
  71479. }else{
  71480. return p->n;
  71481. }
  71482. }
  71483. if( p->flags & MEM_Null ) return 0;
  71484. return valueBytes(pVal, enc);
  71485. }
  71486. /************** End of vdbemem.c *********************************************/
  71487. /************** Begin file vdbeaux.c *****************************************/
  71488. /*
  71489. ** 2003 September 6
  71490. **
  71491. ** The author disclaims copyright to this source code. In place of
  71492. ** a legal notice, here is a blessing:
  71493. **
  71494. ** May you do good and not evil.
  71495. ** May you find forgiveness for yourself and forgive others.
  71496. ** May you share freely, never taking more than you give.
  71497. **
  71498. *************************************************************************
  71499. ** This file contains code used for creating, destroying, and populating
  71500. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  71501. */
  71502. /* #include "sqliteInt.h" */
  71503. /* #include "vdbeInt.h" */
  71504. /*
  71505. ** Create a new virtual database engine.
  71506. */
  71507. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  71508. sqlite3 *db = pParse->db;
  71509. Vdbe *p;
  71510. p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
  71511. if( p==0 ) return 0;
  71512. memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
  71513. p->db = db;
  71514. if( db->pVdbe ){
  71515. db->pVdbe->pPrev = p;
  71516. }
  71517. p->pNext = db->pVdbe;
  71518. p->pPrev = 0;
  71519. db->pVdbe = p;
  71520. p->magic = VDBE_MAGIC_INIT;
  71521. p->pParse = pParse;
  71522. pParse->pVdbe = p;
  71523. assert( pParse->aLabel==0 );
  71524. assert( pParse->nLabel==0 );
  71525. assert( p->nOpAlloc==0 );
  71526. assert( pParse->szOpAlloc==0 );
  71527. sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
  71528. return p;
  71529. }
  71530. /*
  71531. ** Change the error string stored in Vdbe.zErrMsg
  71532. */
  71533. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  71534. va_list ap;
  71535. sqlite3DbFree(p->db, p->zErrMsg);
  71536. va_start(ap, zFormat);
  71537. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  71538. va_end(ap);
  71539. }
  71540. /*
  71541. ** Remember the SQL string for a prepared statement.
  71542. */
  71543. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
  71544. if( p==0 ) return;
  71545. p->prepFlags = prepFlags;
  71546. if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
  71547. p->expmask = 0;
  71548. }
  71549. assert( p->zSql==0 );
  71550. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  71551. }
  71552. #ifdef SQLITE_ENABLE_NORMALIZE
  71553. /*
  71554. ** Add a new element to the Vdbe->pDblStr list.
  71555. */
  71556. SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){
  71557. if( p ){
  71558. int n = sqlite3Strlen30(z);
  71559. DblquoteStr *pStr = sqlite3DbMallocRawNN(db,
  71560. sizeof(*pStr)+n+1-sizeof(pStr->z));
  71561. if( pStr ){
  71562. pStr->pNextStr = p->pDblStr;
  71563. p->pDblStr = pStr;
  71564. memcpy(pStr->z, z, n+1);
  71565. }
  71566. }
  71567. }
  71568. #endif
  71569. #ifdef SQLITE_ENABLE_NORMALIZE
  71570. /*
  71571. ** zId of length nId is a double-quoted identifier. Check to see if
  71572. ** that identifier is really used as a string literal.
  71573. */
  71574. SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(
  71575. Vdbe *pVdbe, /* The prepared statement */
  71576. const char *zId /* The double-quoted identifier, already dequoted */
  71577. ){
  71578. DblquoteStr *pStr;
  71579. assert( zId!=0 );
  71580. if( pVdbe->pDblStr==0 ) return 0;
  71581. for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
  71582. if( strcmp(zId, pStr->z)==0 ) return 1;
  71583. }
  71584. return 0;
  71585. }
  71586. #endif
  71587. /*
  71588. ** Swap all content between two VDBE structures.
  71589. */
  71590. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  71591. Vdbe tmp, *pTmp;
  71592. char *zTmp;
  71593. assert( pA->db==pB->db );
  71594. tmp = *pA;
  71595. *pA = *pB;
  71596. *pB = tmp;
  71597. pTmp = pA->pNext;
  71598. pA->pNext = pB->pNext;
  71599. pB->pNext = pTmp;
  71600. pTmp = pA->pPrev;
  71601. pA->pPrev = pB->pPrev;
  71602. pB->pPrev = pTmp;
  71603. zTmp = pA->zSql;
  71604. pA->zSql = pB->zSql;
  71605. pB->zSql = zTmp;
  71606. #if 0
  71607. zTmp = pA->zNormSql;
  71608. pA->zNormSql = pB->zNormSql;
  71609. pB->zNormSql = zTmp;
  71610. #endif
  71611. pB->expmask = pA->expmask;
  71612. pB->prepFlags = pA->prepFlags;
  71613. memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
  71614. pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
  71615. }
  71616. /*
  71617. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  71618. ** than its current size. nOp is guaranteed to be less than or equal
  71619. ** to 1024/sizeof(Op).
  71620. **
  71621. ** If an out-of-memory error occurs while resizing the array, return
  71622. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  71623. ** unchanged (this is so that any opcodes already allocated can be
  71624. ** correctly deallocated along with the rest of the Vdbe).
  71625. */
  71626. static int growOpArray(Vdbe *v, int nOp){
  71627. VdbeOp *pNew;
  71628. Parse *p = v->pParse;
  71629. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  71630. ** more frequent reallocs and hence provide more opportunities for
  71631. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  71632. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  71633. ** by the minimum* amount required until the size reaches 512. Normal
  71634. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  71635. ** size of the op array or add 1KB of space, whichever is smaller. */
  71636. #ifdef SQLITE_TEST_REALLOC_STRESS
  71637. sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
  71638. : (sqlite3_int64)v->nOpAlloc+nOp);
  71639. #else
  71640. sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
  71641. : (sqlite3_int64)(1024/sizeof(Op)));
  71642. UNUSED_PARAMETER(nOp);
  71643. #endif
  71644. /* Ensure that the size of a VDBE does not grow too large */
  71645. if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
  71646. sqlite3OomFault(p->db);
  71647. return SQLITE_NOMEM;
  71648. }
  71649. assert( nOp<=(1024/sizeof(Op)) );
  71650. assert( nNew>=(v->nOpAlloc+nOp) );
  71651. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  71652. if( pNew ){
  71653. p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
  71654. v->nOpAlloc = p->szOpAlloc/sizeof(Op);
  71655. v->aOp = pNew;
  71656. }
  71657. return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
  71658. }
  71659. #ifdef SQLITE_DEBUG
  71660. /* This routine is just a convenient place to set a breakpoint that will
  71661. ** fire after each opcode is inserted and displayed using
  71662. ** "PRAGMA vdbe_addoptrace=on".
  71663. */
  71664. static void test_addop_breakpoint(void){
  71665. static int n = 0;
  71666. n++;
  71667. }
  71668. #endif
  71669. /*
  71670. ** Add a new instruction to the list of instructions current in the
  71671. ** VDBE. Return the address of the new instruction.
  71672. **
  71673. ** Parameters:
  71674. **
  71675. ** p Pointer to the VDBE
  71676. **
  71677. ** op The opcode for this instruction
  71678. **
  71679. ** p1, p2, p3 Operands
  71680. **
  71681. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  71682. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  71683. ** operand.
  71684. */
  71685. static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
  71686. assert( p->nOpAlloc<=p->nOp );
  71687. if( growOpArray(p, 1) ) return 1;
  71688. assert( p->nOpAlloc>p->nOp );
  71689. return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  71690. }
  71691. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  71692. int i;
  71693. VdbeOp *pOp;
  71694. i = p->nOp;
  71695. assert( p->magic==VDBE_MAGIC_INIT );
  71696. assert( op>=0 && op<0xff );
  71697. if( p->nOpAlloc<=i ){
  71698. return growOp3(p, op, p1, p2, p3);
  71699. }
  71700. p->nOp++;
  71701. pOp = &p->aOp[i];
  71702. pOp->opcode = (u8)op;
  71703. pOp->p5 = 0;
  71704. pOp->p1 = p1;
  71705. pOp->p2 = p2;
  71706. pOp->p3 = p3;
  71707. pOp->p4.p = 0;
  71708. pOp->p4type = P4_NOTUSED;
  71709. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  71710. pOp->zComment = 0;
  71711. #endif
  71712. #ifdef SQLITE_DEBUG
  71713. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  71714. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  71715. test_addop_breakpoint();
  71716. }
  71717. #endif
  71718. #ifdef VDBE_PROFILE
  71719. pOp->cycles = 0;
  71720. pOp->cnt = 0;
  71721. #endif
  71722. #ifdef SQLITE_VDBE_COVERAGE
  71723. pOp->iSrcLine = 0;
  71724. #endif
  71725. return i;
  71726. }
  71727. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  71728. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  71729. }
  71730. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  71731. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  71732. }
  71733. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  71734. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  71735. }
  71736. /* Generate code for an unconditional jump to instruction iDest
  71737. */
  71738. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  71739. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  71740. }
  71741. /* Generate code to cause the string zStr to be loaded into
  71742. ** register iDest
  71743. */
  71744. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  71745. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  71746. }
  71747. /*
  71748. ** Generate code that initializes multiple registers to string or integer
  71749. ** constants. The registers begin with iDest and increase consecutively.
  71750. ** One register is initialized for each characgter in zTypes[]. For each
  71751. ** "s" character in zTypes[], the register is a string if the argument is
  71752. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  71753. ** in zTypes[], the register is initialized to an integer.
  71754. **
  71755. ** If the input string does not end with "X" then an OP_ResultRow instruction
  71756. ** is generated for the values inserted.
  71757. */
  71758. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  71759. va_list ap;
  71760. int i;
  71761. char c;
  71762. va_start(ap, zTypes);
  71763. for(i=0; (c = zTypes[i])!=0; i++){
  71764. if( c=='s' ){
  71765. const char *z = va_arg(ap, const char*);
  71766. sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
  71767. }else if( c=='i' ){
  71768. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
  71769. }else{
  71770. goto skip_op_resultrow;
  71771. }
  71772. }
  71773. sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
  71774. skip_op_resultrow:
  71775. va_end(ap);
  71776. }
  71777. /*
  71778. ** Add an opcode that includes the p4 value as a pointer.
  71779. */
  71780. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  71781. Vdbe *p, /* Add the opcode to this VM */
  71782. int op, /* The new opcode */
  71783. int p1, /* The P1 operand */
  71784. int p2, /* The P2 operand */
  71785. int p3, /* The P3 operand */
  71786. const char *zP4, /* The P4 operand */
  71787. int p4type /* P4 operand type */
  71788. ){
  71789. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  71790. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  71791. return addr;
  71792. }
  71793. /*
  71794. ** Add an opcode that includes the p4 value with a P4_INT64 or
  71795. ** P4_REAL type.
  71796. */
  71797. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  71798. Vdbe *p, /* Add the opcode to this VM */
  71799. int op, /* The new opcode */
  71800. int p1, /* The P1 operand */
  71801. int p2, /* The P2 operand */
  71802. int p3, /* The P3 operand */
  71803. const u8 *zP4, /* The P4 operand */
  71804. int p4type /* P4 operand type */
  71805. ){
  71806. char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
  71807. if( p4copy ) memcpy(p4copy, zP4, 8);
  71808. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  71809. }
  71810. #ifndef SQLITE_OMIT_EXPLAIN
  71811. /*
  71812. ** Return the address of the current EXPLAIN QUERY PLAN baseline.
  71813. ** 0 means "none".
  71814. */
  71815. SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse *pParse){
  71816. VdbeOp *pOp;
  71817. if( pParse->addrExplain==0 ) return 0;
  71818. pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
  71819. return pOp->p2;
  71820. }
  71821. /*
  71822. ** Set a debugger breakpoint on the following routine in order to
  71823. ** monitor the EXPLAIN QUERY PLAN code generation.
  71824. */
  71825. #if defined(SQLITE_DEBUG)
  71826. SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
  71827. (void)z1;
  71828. (void)z2;
  71829. }
  71830. #endif
  71831. /*
  71832. ** Add a new OP_ opcode.
  71833. **
  71834. ** If the bPush flag is true, then make this opcode the parent for
  71835. ** subsequent Explains until sqlite3VdbeExplainPop() is called.
  71836. */
  71837. SQLITE_PRIVATE void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
  71838. #ifndef SQLITE_DEBUG
  71839. /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
  71840. ** But omit them (for performance) during production builds */
  71841. if( pParse->explain==2 )
  71842. #endif
  71843. {
  71844. char *zMsg;
  71845. Vdbe *v;
  71846. va_list ap;
  71847. int iThis;
  71848. va_start(ap, zFmt);
  71849. zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
  71850. va_end(ap);
  71851. v = pParse->pVdbe;
  71852. iThis = v->nOp;
  71853. sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
  71854. zMsg, P4_DYNAMIC);
  71855. sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetOp(v,-1)->p4.z);
  71856. if( bPush){
  71857. pParse->addrExplain = iThis;
  71858. }
  71859. }
  71860. }
  71861. /*
  71862. ** Pop the EXPLAIN QUERY PLAN stack one level.
  71863. */
  71864. SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){
  71865. sqlite3ExplainBreakpoint("POP", 0);
  71866. pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
  71867. }
  71868. #endif /* SQLITE_OMIT_EXPLAIN */
  71869. /*
  71870. ** Add an OP_ParseSchema opcode. This routine is broken out from
  71871. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  71872. ** as having been used.
  71873. **
  71874. ** The zWhere string must have been obtained from sqlite3_malloc().
  71875. ** This routine will take ownership of the allocated memory.
  71876. */
  71877. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  71878. int j;
  71879. sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  71880. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  71881. }
  71882. /*
  71883. ** Add an opcode that includes the p4 value as an integer.
  71884. */
  71885. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  71886. Vdbe *p, /* Add the opcode to this VM */
  71887. int op, /* The new opcode */
  71888. int p1, /* The P1 operand */
  71889. int p2, /* The P2 operand */
  71890. int p3, /* The P3 operand */
  71891. int p4 /* The P4 operand as an integer */
  71892. ){
  71893. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  71894. if( p->db->mallocFailed==0 ){
  71895. VdbeOp *pOp = &p->aOp[addr];
  71896. pOp->p4type = P4_INT32;
  71897. pOp->p4.i = p4;
  71898. }
  71899. return addr;
  71900. }
  71901. /* Insert the end of a co-routine
  71902. */
  71903. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
  71904. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  71905. /* Clear the temporary register cache, thereby ensuring that each
  71906. ** co-routine has its own independent set of registers, because co-routines
  71907. ** might expect their registers to be preserved across an OP_Yield, and
  71908. ** that could cause problems if two or more co-routines are using the same
  71909. ** temporary register.
  71910. */
  71911. v->pParse->nTempReg = 0;
  71912. v->pParse->nRangeReg = 0;
  71913. }
  71914. /*
  71915. ** Create a new symbolic label for an instruction that has yet to be
  71916. ** coded. The symbolic label is really just a negative number. The
  71917. ** label can be used as the P2 value of an operation. Later, when
  71918. ** the label is resolved to a specific address, the VDBE will scan
  71919. ** through its operation list and change all values of P2 which match
  71920. ** the label into the resolved address.
  71921. **
  71922. ** The VDBE knows that a P2 value is a label because labels are
  71923. ** always negative and P2 values are suppose to be non-negative.
  71924. ** Hence, a negative P2 value is a label that has yet to be resolved.
  71925. ** (Later:) This is only true for opcodes that have the OPFLG_JUMP
  71926. ** property.
  71927. **
  71928. ** Variable usage notes:
  71929. **
  71930. ** Parse.aLabel[x] Stores the address that the x-th label resolves
  71931. ** into. For testing (SQLITE_DEBUG), unresolved
  71932. ** labels stores -1, but that is not required.
  71933. ** Parse.nLabelAlloc Number of slots allocated to Parse.aLabel[]
  71934. ** Parse.nLabel The *negative* of the number of labels that have
  71935. ** been issued. The negative is stored because
  71936. ** that gives a performance improvement over storing
  71937. ** the equivalent positive value.
  71938. */
  71939. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse *pParse){
  71940. return --pParse->nLabel;
  71941. }
  71942. /*
  71943. ** Resolve label "x" to be the address of the next instruction to
  71944. ** be inserted. The parameter "x" must have been obtained from
  71945. ** a prior call to sqlite3VdbeMakeLabel().
  71946. */
  71947. static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
  71948. int nNewSize = 10 - p->nLabel;
  71949. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  71950. nNewSize*sizeof(p->aLabel[0]));
  71951. if( p->aLabel==0 ){
  71952. p->nLabelAlloc = 0;
  71953. }else{
  71954. #ifdef SQLITE_DEBUG
  71955. int i;
  71956. for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
  71957. #endif
  71958. p->nLabelAlloc = nNewSize;
  71959. p->aLabel[j] = v->nOp;
  71960. }
  71961. }
  71962. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  71963. Parse *p = v->pParse;
  71964. int j = ADDR(x);
  71965. assert( v->magic==VDBE_MAGIC_INIT );
  71966. assert( j<-p->nLabel );
  71967. assert( j>=0 );
  71968. #ifdef SQLITE_DEBUG
  71969. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  71970. printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
  71971. }
  71972. #endif
  71973. if( p->nLabelAlloc + p->nLabel < 0 ){
  71974. resizeResolveLabel(p,v,j);
  71975. }else{
  71976. assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
  71977. p->aLabel[j] = v->nOp;
  71978. }
  71979. }
  71980. /*
  71981. ** Mark the VDBE as one that can only be run one time.
  71982. */
  71983. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  71984. p->runOnlyOnce = 1;
  71985. }
  71986. /*
  71987. ** Mark the VDBE as one that can only be run multiple times.
  71988. */
  71989. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
  71990. p->runOnlyOnce = 0;
  71991. }
  71992. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  71993. /*
  71994. ** The following type and function are used to iterate through all opcodes
  71995. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  71996. ** invoke directly or indirectly. It should be used as follows:
  71997. **
  71998. ** Op *pOp;
  71999. ** VdbeOpIter sIter;
  72000. **
  72001. ** memset(&sIter, 0, sizeof(sIter));
  72002. ** sIter.v = v; // v is of type Vdbe*
  72003. ** while( (pOp = opIterNext(&sIter)) ){
  72004. ** // Do something with pOp
  72005. ** }
  72006. ** sqlite3DbFree(v->db, sIter.apSub);
  72007. **
  72008. */
  72009. typedef struct VdbeOpIter VdbeOpIter;
  72010. struct VdbeOpIter {
  72011. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  72012. SubProgram **apSub; /* Array of subprograms */
  72013. int nSub; /* Number of entries in apSub */
  72014. int iAddr; /* Address of next instruction to return */
  72015. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  72016. };
  72017. static Op *opIterNext(VdbeOpIter *p){
  72018. Vdbe *v = p->v;
  72019. Op *pRet = 0;
  72020. Op *aOp;
  72021. int nOp;
  72022. if( p->iSub<=p->nSub ){
  72023. if( p->iSub==0 ){
  72024. aOp = v->aOp;
  72025. nOp = v->nOp;
  72026. }else{
  72027. aOp = p->apSub[p->iSub-1]->aOp;
  72028. nOp = p->apSub[p->iSub-1]->nOp;
  72029. }
  72030. assert( p->iAddr<nOp );
  72031. pRet = &aOp[p->iAddr];
  72032. p->iAddr++;
  72033. if( p->iAddr==nOp ){
  72034. p->iSub++;
  72035. p->iAddr = 0;
  72036. }
  72037. if( pRet->p4type==P4_SUBPROGRAM ){
  72038. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  72039. int j;
  72040. for(j=0; j<p->nSub; j++){
  72041. if( p->apSub[j]==pRet->p4.pProgram ) break;
  72042. }
  72043. if( j==p->nSub ){
  72044. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  72045. if( !p->apSub ){
  72046. pRet = 0;
  72047. }else{
  72048. p->apSub[p->nSub++] = pRet->p4.pProgram;
  72049. }
  72050. }
  72051. }
  72052. }
  72053. return pRet;
  72054. }
  72055. /*
  72056. ** Check if the program stored in the VM associated with pParse may
  72057. ** throw an ABORT exception (causing the statement, but not entire transaction
  72058. ** to be rolled back). This condition is true if the main program or any
  72059. ** sub-programs contains any of the following:
  72060. **
  72061. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  72062. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  72063. ** * OP_Destroy
  72064. ** * OP_VUpdate
  72065. ** * OP_VRename
  72066. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  72067. ** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
  72068. ** (for CREATE TABLE AS SELECT ...)
  72069. **
  72070. ** Then check that the value of Parse.mayAbort is true if an
  72071. ** ABORT may be thrown, or false otherwise. Return true if it does
  72072. ** match, or false otherwise. This function is intended to be used as
  72073. ** part of an assert statement in the compiler. Similar to:
  72074. **
  72075. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  72076. */
  72077. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  72078. int hasAbort = 0;
  72079. int hasFkCounter = 0;
  72080. int hasCreateTable = 0;
  72081. int hasInitCoroutine = 0;
  72082. Op *pOp;
  72083. VdbeOpIter sIter;
  72084. memset(&sIter, 0, sizeof(sIter));
  72085. sIter.v = v;
  72086. while( (pOp = opIterNext(&sIter))!=0 ){
  72087. int opcode = pOp->opcode;
  72088. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  72089. || opcode==OP_VDestroy
  72090. || (opcode==OP_Function0 && pOp->p4.pFunc->funcFlags&SQLITE_FUNC_INTERNAL)
  72091. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  72092. && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
  72093. ){
  72094. hasAbort = 1;
  72095. break;
  72096. }
  72097. if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
  72098. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  72099. #ifndef SQLITE_OMIT_FOREIGN_KEY
  72100. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  72101. hasFkCounter = 1;
  72102. }
  72103. #endif
  72104. }
  72105. sqlite3DbFree(v->db, sIter.apSub);
  72106. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  72107. ** If malloc failed, then the while() loop above may not have iterated
  72108. ** through all opcodes and hasAbort may be set incorrectly. Return
  72109. ** true for this case to prevent the assert() in the callers frame
  72110. ** from failing. */
  72111. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  72112. || (hasCreateTable && hasInitCoroutine) );
  72113. }
  72114. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  72115. #ifdef SQLITE_DEBUG
  72116. /*
  72117. ** Increment the nWrite counter in the VDBE if the cursor is not an
  72118. ** ephemeral cursor, or if the cursor argument is NULL.
  72119. */
  72120. SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
  72121. if( pC==0
  72122. || (pC->eCurType!=CURTYPE_SORTER
  72123. && pC->eCurType!=CURTYPE_PSEUDO
  72124. && !pC->isEphemeral)
  72125. ){
  72126. p->nWrite++;
  72127. }
  72128. }
  72129. #endif
  72130. #ifdef SQLITE_DEBUG
  72131. /*
  72132. ** Assert if an Abort at this point in time might result in a corrupt
  72133. ** database.
  72134. */
  72135. SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){
  72136. assert( p->nWrite==0 || p->usesStmtJournal );
  72137. }
  72138. #endif
  72139. /*
  72140. ** This routine is called after all opcodes have been inserted. It loops
  72141. ** through all the opcodes and fixes up some details.
  72142. **
  72143. ** (1) For each jump instruction with a negative P2 value (a label)
  72144. ** resolve the P2 value to an actual address.
  72145. **
  72146. ** (2) Compute the maximum number of arguments used by any SQL function
  72147. ** and store that value in *pMaxFuncArgs.
  72148. **
  72149. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  72150. ** indicate what the prepared statement actually does.
  72151. **
  72152. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  72153. **
  72154. ** (5) Reclaim the memory allocated for storing labels.
  72155. **
  72156. ** This routine will only function correctly if the mkopcodeh.tcl generator
  72157. ** script numbers the opcodes correctly. Changes to this routine must be
  72158. ** coordinated with changes to mkopcodeh.tcl.
  72159. */
  72160. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  72161. int nMaxArgs = *pMaxFuncArgs;
  72162. Op *pOp;
  72163. Parse *pParse = p->pParse;
  72164. int *aLabel = pParse->aLabel;
  72165. p->readOnly = 1;
  72166. p->bIsReader = 0;
  72167. pOp = &p->aOp[p->nOp-1];
  72168. while(1){
  72169. /* Only JUMP opcodes and the short list of special opcodes in the switch
  72170. ** below need to be considered. The mkopcodeh.tcl generator script groups
  72171. ** all these opcodes together near the front of the opcode list. Skip
  72172. ** any opcode that does not need processing by virtual of the fact that
  72173. ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
  72174. */
  72175. if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
  72176. /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
  72177. ** cases from this switch! */
  72178. switch( pOp->opcode ){
  72179. case OP_Transaction: {
  72180. if( pOp->p2!=0 ) p->readOnly = 0;
  72181. /* fall thru */
  72182. }
  72183. case OP_AutoCommit:
  72184. case OP_Savepoint: {
  72185. p->bIsReader = 1;
  72186. break;
  72187. }
  72188. #ifndef SQLITE_OMIT_WAL
  72189. case OP_Checkpoint:
  72190. #endif
  72191. case OP_Vacuum:
  72192. case OP_JournalMode: {
  72193. p->readOnly = 0;
  72194. p->bIsReader = 1;
  72195. break;
  72196. }
  72197. case OP_Next:
  72198. case OP_SorterNext: {
  72199. pOp->p4.xAdvance = sqlite3BtreeNext;
  72200. pOp->p4type = P4_ADVANCE;
  72201. /* The code generator never codes any of these opcodes as a jump
  72202. ** to a label. They are always coded as a jump backwards to a
  72203. ** known address */
  72204. assert( pOp->p2>=0 );
  72205. break;
  72206. }
  72207. case OP_Prev: {
  72208. pOp->p4.xAdvance = sqlite3BtreePrevious;
  72209. pOp->p4type = P4_ADVANCE;
  72210. /* The code generator never codes any of these opcodes as a jump
  72211. ** to a label. They are always coded as a jump backwards to a
  72212. ** known address */
  72213. assert( pOp->p2>=0 );
  72214. break;
  72215. }
  72216. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72217. case OP_VUpdate: {
  72218. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  72219. break;
  72220. }
  72221. case OP_VFilter: {
  72222. int n;
  72223. assert( (pOp - p->aOp) >= 3 );
  72224. assert( pOp[-1].opcode==OP_Integer );
  72225. n = pOp[-1].p1;
  72226. if( n>nMaxArgs ) nMaxArgs = n;
  72227. /* Fall through into the default case */
  72228. }
  72229. #endif
  72230. default: {
  72231. if( pOp->p2<0 ){
  72232. /* The mkopcodeh.tcl script has so arranged things that the only
  72233. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  72234. ** have non-negative values for P2. */
  72235. assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
  72236. assert( ADDR(pOp->p2)<-pParse->nLabel );
  72237. pOp->p2 = aLabel[ADDR(pOp->p2)];
  72238. }
  72239. break;
  72240. }
  72241. }
  72242. /* The mkopcodeh.tcl script has so arranged things that the only
  72243. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  72244. ** have non-negative values for P2. */
  72245. assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
  72246. }
  72247. if( pOp==p->aOp ) break;
  72248. pOp--;
  72249. }
  72250. sqlite3DbFree(p->db, pParse->aLabel);
  72251. pParse->aLabel = 0;
  72252. pParse->nLabel = 0;
  72253. *pMaxFuncArgs = nMaxArgs;
  72254. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  72255. }
  72256. /*
  72257. ** Return the address of the next instruction to be inserted.
  72258. */
  72259. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  72260. assert( p->magic==VDBE_MAGIC_INIT );
  72261. return p->nOp;
  72262. }
  72263. /*
  72264. ** Verify that at least N opcode slots are available in p without
  72265. ** having to malloc for more space (except when compiled using
  72266. ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
  72267. ** to verify that certain calls to sqlite3VdbeAddOpList() can never
  72268. ** fail due to a OOM fault and hence that the return value from
  72269. ** sqlite3VdbeAddOpList() will always be non-NULL.
  72270. */
  72271. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  72272. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
  72273. assert( p->nOp + N <= p->nOpAlloc );
  72274. }
  72275. #endif
  72276. /*
  72277. ** Verify that the VM passed as the only argument does not contain
  72278. ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
  72279. ** by code in pragma.c to ensure that the implementation of certain
  72280. ** pragmas comports with the flags specified in the mkpragmatab.tcl
  72281. ** script.
  72282. */
  72283. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  72284. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
  72285. int i;
  72286. for(i=0; i<p->nOp; i++){
  72287. assert( p->aOp[i].opcode!=OP_ResultRow );
  72288. }
  72289. }
  72290. #endif
  72291. /*
  72292. ** Generate code (a single OP_Abortable opcode) that will
  72293. ** verify that the VDBE program can safely call Abort in the current
  72294. ** context.
  72295. */
  72296. #if defined(SQLITE_DEBUG)
  72297. SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
  72298. if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
  72299. }
  72300. #endif
  72301. /*
  72302. ** This function returns a pointer to the array of opcodes associated with
  72303. ** the Vdbe passed as the first argument. It is the callers responsibility
  72304. ** to arrange for the returned array to be eventually freed using the
  72305. ** vdbeFreeOpArray() function.
  72306. **
  72307. ** Before returning, *pnOp is set to the number of entries in the returned
  72308. ** array. Also, *pnMaxArg is set to the larger of its current value and
  72309. ** the number of entries in the Vdbe.apArg[] array required to execute the
  72310. ** returned program.
  72311. */
  72312. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  72313. VdbeOp *aOp = p->aOp;
  72314. assert( aOp && !p->db->mallocFailed );
  72315. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  72316. assert( DbMaskAllZero(p->btreeMask) );
  72317. resolveP2Values(p, pnMaxArg);
  72318. *pnOp = p->nOp;
  72319. p->aOp = 0;
  72320. return aOp;
  72321. }
  72322. /*
  72323. ** Add a whole list of operations to the operation stack. Return a
  72324. ** pointer to the first operation inserted.
  72325. **
  72326. ** Non-zero P2 arguments to jump instructions are automatically adjusted
  72327. ** so that the jump target is relative to the first operation inserted.
  72328. */
  72329. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
  72330. Vdbe *p, /* Add opcodes to the prepared statement */
  72331. int nOp, /* Number of opcodes to add */
  72332. VdbeOpList const *aOp, /* The opcodes to be added */
  72333. int iLineno /* Source-file line number of first opcode */
  72334. ){
  72335. int i;
  72336. VdbeOp *pOut, *pFirst;
  72337. assert( nOp>0 );
  72338. assert( p->magic==VDBE_MAGIC_INIT );
  72339. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
  72340. return 0;
  72341. }
  72342. pFirst = pOut = &p->aOp[p->nOp];
  72343. for(i=0; i<nOp; i++, aOp++, pOut++){
  72344. pOut->opcode = aOp->opcode;
  72345. pOut->p1 = aOp->p1;
  72346. pOut->p2 = aOp->p2;
  72347. assert( aOp->p2>=0 );
  72348. if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
  72349. pOut->p2 += p->nOp;
  72350. }
  72351. pOut->p3 = aOp->p3;
  72352. pOut->p4type = P4_NOTUSED;
  72353. pOut->p4.p = 0;
  72354. pOut->p5 = 0;
  72355. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  72356. pOut->zComment = 0;
  72357. #endif
  72358. #ifdef SQLITE_VDBE_COVERAGE
  72359. pOut->iSrcLine = iLineno+i;
  72360. #else
  72361. (void)iLineno;
  72362. #endif
  72363. #ifdef SQLITE_DEBUG
  72364. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  72365. sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
  72366. }
  72367. #endif
  72368. }
  72369. p->nOp += nOp;
  72370. return pFirst;
  72371. }
  72372. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  72373. /*
  72374. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  72375. */
  72376. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  72377. Vdbe *p, /* VM to add scanstatus() to */
  72378. int addrExplain, /* Address of OP_Explain (or 0) */
  72379. int addrLoop, /* Address of loop counter */
  72380. int addrVisit, /* Address of rows visited counter */
  72381. LogEst nEst, /* Estimated number of output rows */
  72382. const char *zName /* Name of table or index being scanned */
  72383. ){
  72384. sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
  72385. ScanStatus *aNew;
  72386. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  72387. if( aNew ){
  72388. ScanStatus *pNew = &aNew[p->nScan++];
  72389. pNew->addrExplain = addrExplain;
  72390. pNew->addrLoop = addrLoop;
  72391. pNew->addrVisit = addrVisit;
  72392. pNew->nEst = nEst;
  72393. pNew->zName = sqlite3DbStrDup(p->db, zName);
  72394. p->aScan = aNew;
  72395. }
  72396. }
  72397. #endif
  72398. /*
  72399. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  72400. ** for a specific instruction.
  72401. */
  72402. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
  72403. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  72404. }
  72405. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  72406. sqlite3VdbeGetOp(p,addr)->p1 = val;
  72407. }
  72408. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  72409. sqlite3VdbeGetOp(p,addr)->p2 = val;
  72410. }
  72411. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  72412. sqlite3VdbeGetOp(p,addr)->p3 = val;
  72413. }
  72414. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
  72415. assert( p->nOp>0 || p->db->mallocFailed );
  72416. if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
  72417. }
  72418. /*
  72419. ** Change the P2 operand of instruction addr so that it points to
  72420. ** the address of the next instruction to be coded.
  72421. */
  72422. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  72423. sqlite3VdbeChangeP2(p, addr, p->nOp);
  72424. }
  72425. /*
  72426. ** If the input FuncDef structure is ephemeral, then free it. If
  72427. ** the FuncDef is not ephermal, then do nothing.
  72428. */
  72429. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  72430. if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  72431. sqlite3DbFreeNN(db, pDef);
  72432. }
  72433. }
  72434. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  72435. /*
  72436. ** Delete a P4 value if necessary.
  72437. */
  72438. static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
  72439. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  72440. sqlite3DbFreeNN(db, p);
  72441. }
  72442. static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
  72443. freeEphemeralFunction(db, p->pFunc);
  72444. sqlite3DbFreeNN(db, p);
  72445. }
  72446. static void freeP4(sqlite3 *db, int p4type, void *p4){
  72447. assert( db );
  72448. switch( p4type ){
  72449. case P4_FUNCCTX: {
  72450. freeP4FuncCtx(db, (sqlite3_context*)p4);
  72451. break;
  72452. }
  72453. case P4_REAL:
  72454. case P4_INT64:
  72455. case P4_DYNAMIC:
  72456. case P4_DYNBLOB:
  72457. case P4_INTARRAY: {
  72458. sqlite3DbFree(db, p4);
  72459. break;
  72460. }
  72461. case P4_KEYINFO: {
  72462. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  72463. break;
  72464. }
  72465. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  72466. case P4_EXPR: {
  72467. sqlite3ExprDelete(db, (Expr*)p4);
  72468. break;
  72469. }
  72470. #endif
  72471. case P4_FUNCDEF: {
  72472. freeEphemeralFunction(db, (FuncDef*)p4);
  72473. break;
  72474. }
  72475. case P4_MEM: {
  72476. if( db->pnBytesFreed==0 ){
  72477. sqlite3ValueFree((sqlite3_value*)p4);
  72478. }else{
  72479. freeP4Mem(db, (Mem*)p4);
  72480. }
  72481. break;
  72482. }
  72483. case P4_VTAB : {
  72484. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  72485. break;
  72486. }
  72487. }
  72488. }
  72489. /*
  72490. ** Free the space allocated for aOp and any p4 values allocated for the
  72491. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  72492. ** nOp entries.
  72493. */
  72494. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  72495. if( aOp ){
  72496. Op *pOp;
  72497. for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
  72498. if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
  72499. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  72500. sqlite3DbFree(db, pOp->zComment);
  72501. #endif
  72502. }
  72503. sqlite3DbFreeNN(db, aOp);
  72504. }
  72505. }
  72506. /*
  72507. ** Link the SubProgram object passed as the second argument into the linked
  72508. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  72509. ** objects when the VM is no longer required.
  72510. */
  72511. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  72512. p->pNext = pVdbe->pProgram;
  72513. pVdbe->pProgram = p;
  72514. }
  72515. /*
  72516. ** Change the opcode at addr into OP_Noop
  72517. */
  72518. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  72519. VdbeOp *pOp;
  72520. if( p->db->mallocFailed ) return 0;
  72521. assert( addr>=0 && addr<p->nOp );
  72522. pOp = &p->aOp[addr];
  72523. freeP4(p->db, pOp->p4type, pOp->p4.p);
  72524. pOp->p4type = P4_NOTUSED;
  72525. pOp->p4.z = 0;
  72526. pOp->opcode = OP_Noop;
  72527. return 1;
  72528. }
  72529. /*
  72530. ** If the last opcode is "op" and it is not a jump destination,
  72531. ** then remove it. Return true if and only if an opcode was removed.
  72532. */
  72533. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  72534. if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
  72535. return sqlite3VdbeChangeToNoop(p, p->nOp-1);
  72536. }else{
  72537. return 0;
  72538. }
  72539. }
  72540. /*
  72541. ** Change the value of the P4 operand for a specific instruction.
  72542. ** This routine is useful when a large program is loaded from a
  72543. ** static array using sqlite3VdbeAddOpList but we want to make a
  72544. ** few minor changes to the program.
  72545. **
  72546. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  72547. ** the string is made into memory obtained from sqlite3_malloc().
  72548. ** A value of n==0 means copy bytes of zP4 up to and including the
  72549. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  72550. **
  72551. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  72552. ** to a string or structure that is guaranteed to exist for the lifetime of
  72553. ** the Vdbe. In these cases we can just copy the pointer.
  72554. **
  72555. ** If addr<0 then change P4 on the most recently inserted instruction.
  72556. */
  72557. static void SQLITE_NOINLINE vdbeChangeP4Full(
  72558. Vdbe *p,
  72559. Op *pOp,
  72560. const char *zP4,
  72561. int n
  72562. ){
  72563. if( pOp->p4type ){
  72564. freeP4(p->db, pOp->p4type, pOp->p4.p);
  72565. pOp->p4type = 0;
  72566. pOp->p4.p = 0;
  72567. }
  72568. if( n<0 ){
  72569. sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
  72570. }else{
  72571. if( n==0 ) n = sqlite3Strlen30(zP4);
  72572. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  72573. pOp->p4type = P4_DYNAMIC;
  72574. }
  72575. }
  72576. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  72577. Op *pOp;
  72578. sqlite3 *db;
  72579. assert( p!=0 );
  72580. db = p->db;
  72581. assert( p->magic==VDBE_MAGIC_INIT );
  72582. assert( p->aOp!=0 || db->mallocFailed );
  72583. if( db->mallocFailed ){
  72584. if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
  72585. return;
  72586. }
  72587. assert( p->nOp>0 );
  72588. assert( addr<p->nOp );
  72589. if( addr<0 ){
  72590. addr = p->nOp - 1;
  72591. }
  72592. pOp = &p->aOp[addr];
  72593. if( n>=0 || pOp->p4type ){
  72594. vdbeChangeP4Full(p, pOp, zP4, n);
  72595. return;
  72596. }
  72597. if( n==P4_INT32 ){
  72598. /* Note: this cast is safe, because the origin data point was an int
  72599. ** that was cast to a (const char *). */
  72600. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  72601. pOp->p4type = P4_INT32;
  72602. }else if( zP4!=0 ){
  72603. assert( n<0 );
  72604. pOp->p4.p = (void*)zP4;
  72605. pOp->p4type = (signed char)n;
  72606. if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
  72607. }
  72608. }
  72609. /*
  72610. ** Change the P4 operand of the most recently coded instruction
  72611. ** to the value defined by the arguments. This is a high-speed
  72612. ** version of sqlite3VdbeChangeP4().
  72613. **
  72614. ** The P4 operand must not have been previously defined. And the new
  72615. ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
  72616. ** those cases.
  72617. */
  72618. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
  72619. VdbeOp *pOp;
  72620. assert( n!=P4_INT32 && n!=P4_VTAB );
  72621. assert( n<=0 );
  72622. if( p->db->mallocFailed ){
  72623. freeP4(p->db, n, pP4);
  72624. }else{
  72625. assert( pP4!=0 );
  72626. assert( p->nOp>0 );
  72627. pOp = &p->aOp[p->nOp-1];
  72628. assert( pOp->p4type==P4_NOTUSED );
  72629. pOp->p4type = n;
  72630. pOp->p4.p = pP4;
  72631. }
  72632. }
  72633. /*
  72634. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  72635. ** index given.
  72636. */
  72637. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  72638. Vdbe *v = pParse->pVdbe;
  72639. KeyInfo *pKeyInfo;
  72640. assert( v!=0 );
  72641. assert( pIdx!=0 );
  72642. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
  72643. if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  72644. }
  72645. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  72646. /*
  72647. ** Change the comment on the most recently coded instruction. Or
  72648. ** insert a No-op and add the comment to that new instruction. This
  72649. ** makes the code easier to read during debugging. None of this happens
  72650. ** in a production build.
  72651. */
  72652. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  72653. assert( p->nOp>0 || p->aOp==0 );
  72654. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  72655. if( p->nOp ){
  72656. assert( p->aOp );
  72657. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  72658. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  72659. }
  72660. }
  72661. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  72662. va_list ap;
  72663. if( p ){
  72664. va_start(ap, zFormat);
  72665. vdbeVComment(p, zFormat, ap);
  72666. va_end(ap);
  72667. }
  72668. }
  72669. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  72670. va_list ap;
  72671. if( p ){
  72672. sqlite3VdbeAddOp0(p, OP_Noop);
  72673. va_start(ap, zFormat);
  72674. vdbeVComment(p, zFormat, ap);
  72675. va_end(ap);
  72676. }
  72677. }
  72678. #endif /* NDEBUG */
  72679. #ifdef SQLITE_VDBE_COVERAGE
  72680. /*
  72681. ** Set the value if the iSrcLine field for the previously coded instruction.
  72682. */
  72683. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  72684. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  72685. }
  72686. #endif /* SQLITE_VDBE_COVERAGE */
  72687. /*
  72688. ** Return the opcode for a given address. If the address is -1, then
  72689. ** return the most recently inserted opcode.
  72690. **
  72691. ** If a memory allocation error has occurred prior to the calling of this
  72692. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  72693. ** is readable but not writable, though it is cast to a writable value.
  72694. ** The return of a dummy opcode allows the call to continue functioning
  72695. ** after an OOM fault without having to check to see if the return from
  72696. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  72697. ** dummy will never be written to. This is verified by code inspection and
  72698. ** by running with Valgrind.
  72699. */
  72700. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  72701. /* C89 specifies that the constant "dummy" will be initialized to all
  72702. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  72703. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  72704. assert( p->magic==VDBE_MAGIC_INIT );
  72705. if( addr<0 ){
  72706. addr = p->nOp - 1;
  72707. }
  72708. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  72709. if( p->db->mallocFailed ){
  72710. return (VdbeOp*)&dummy;
  72711. }else{
  72712. return &p->aOp[addr];
  72713. }
  72714. }
  72715. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  72716. /*
  72717. ** Return an integer value for one of the parameters to the opcode pOp
  72718. ** determined by character c.
  72719. */
  72720. static int translateP(char c, const Op *pOp){
  72721. if( c=='1' ) return pOp->p1;
  72722. if( c=='2' ) return pOp->p2;
  72723. if( c=='3' ) return pOp->p3;
  72724. if( c=='4' ) return pOp->p4.i;
  72725. return pOp->p5;
  72726. }
  72727. /*
  72728. ** Compute a string for the "comment" field of a VDBE opcode listing.
  72729. **
  72730. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  72731. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  72732. ** absence of other comments, this synopsis becomes the comment on the opcode.
  72733. ** Some translation occurs:
  72734. **
  72735. ** "PX" -> "r[X]"
  72736. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  72737. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  72738. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  72739. */
  72740. static int displayComment(
  72741. const Op *pOp, /* The opcode to be commented */
  72742. const char *zP4, /* Previously obtained value for P4 */
  72743. char *zTemp, /* Write result here */
  72744. int nTemp /* Space available in zTemp[] */
  72745. ){
  72746. const char *zOpName;
  72747. const char *zSynopsis;
  72748. int nOpName;
  72749. int ii, jj;
  72750. char zAlt[50];
  72751. zOpName = sqlite3OpcodeName(pOp->opcode);
  72752. nOpName = sqlite3Strlen30(zOpName);
  72753. if( zOpName[nOpName+1] ){
  72754. int seenCom = 0;
  72755. char c;
  72756. zSynopsis = zOpName += nOpName + 1;
  72757. if( strncmp(zSynopsis,"IF ",3)==0 ){
  72758. if( pOp->p5 & SQLITE_STOREP2 ){
  72759. sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
  72760. }else{
  72761. sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
  72762. }
  72763. zSynopsis = zAlt;
  72764. }
  72765. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  72766. if( c=='P' ){
  72767. c = zSynopsis[++ii];
  72768. if( c=='4' ){
  72769. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  72770. }else if( c=='X' ){
  72771. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  72772. seenCom = 1;
  72773. }else{
  72774. int v1 = translateP(c, pOp);
  72775. int v2;
  72776. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  72777. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  72778. ii += 3;
  72779. jj += sqlite3Strlen30(zTemp+jj);
  72780. v2 = translateP(zSynopsis[ii], pOp);
  72781. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  72782. ii += 2;
  72783. v2++;
  72784. }
  72785. if( v2>1 ){
  72786. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  72787. }
  72788. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  72789. ii += 4;
  72790. }
  72791. }
  72792. jj += sqlite3Strlen30(zTemp+jj);
  72793. }else{
  72794. zTemp[jj++] = c;
  72795. }
  72796. }
  72797. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  72798. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  72799. jj += sqlite3Strlen30(zTemp+jj);
  72800. }
  72801. if( jj<nTemp ) zTemp[jj] = 0;
  72802. }else if( pOp->zComment ){
  72803. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  72804. jj = sqlite3Strlen30(zTemp);
  72805. }else{
  72806. zTemp[0] = 0;
  72807. jj = 0;
  72808. }
  72809. return jj;
  72810. }
  72811. #endif /* SQLITE_DEBUG */
  72812. #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
  72813. /*
  72814. ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
  72815. ** that can be displayed in the P4 column of EXPLAIN output.
  72816. */
  72817. static void displayP4Expr(StrAccum *p, Expr *pExpr){
  72818. const char *zOp = 0;
  72819. switch( pExpr->op ){
  72820. case TK_STRING:
  72821. sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
  72822. break;
  72823. case TK_INTEGER:
  72824. sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
  72825. break;
  72826. case TK_NULL:
  72827. sqlite3_str_appendf(p, "NULL");
  72828. break;
  72829. case TK_REGISTER: {
  72830. sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
  72831. break;
  72832. }
  72833. case TK_COLUMN: {
  72834. if( pExpr->iColumn<0 ){
  72835. sqlite3_str_appendf(p, "rowid");
  72836. }else{
  72837. sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
  72838. }
  72839. break;
  72840. }
  72841. case TK_LT: zOp = "LT"; break;
  72842. case TK_LE: zOp = "LE"; break;
  72843. case TK_GT: zOp = "GT"; break;
  72844. case TK_GE: zOp = "GE"; break;
  72845. case TK_NE: zOp = "NE"; break;
  72846. case TK_EQ: zOp = "EQ"; break;
  72847. case TK_IS: zOp = "IS"; break;
  72848. case TK_ISNOT: zOp = "ISNOT"; break;
  72849. case TK_AND: zOp = "AND"; break;
  72850. case TK_OR: zOp = "OR"; break;
  72851. case TK_PLUS: zOp = "ADD"; break;
  72852. case TK_STAR: zOp = "MUL"; break;
  72853. case TK_MINUS: zOp = "SUB"; break;
  72854. case TK_REM: zOp = "REM"; break;
  72855. case TK_BITAND: zOp = "BITAND"; break;
  72856. case TK_BITOR: zOp = "BITOR"; break;
  72857. case TK_SLASH: zOp = "DIV"; break;
  72858. case TK_LSHIFT: zOp = "LSHIFT"; break;
  72859. case TK_RSHIFT: zOp = "RSHIFT"; break;
  72860. case TK_CONCAT: zOp = "CONCAT"; break;
  72861. case TK_UMINUS: zOp = "MINUS"; break;
  72862. case TK_UPLUS: zOp = "PLUS"; break;
  72863. case TK_BITNOT: zOp = "BITNOT"; break;
  72864. case TK_NOT: zOp = "NOT"; break;
  72865. case TK_ISNULL: zOp = "ISNULL"; break;
  72866. case TK_NOTNULL: zOp = "NOTNULL"; break;
  72867. default:
  72868. sqlite3_str_appendf(p, "%s", "expr");
  72869. break;
  72870. }
  72871. if( zOp ){
  72872. sqlite3_str_appendf(p, "%s(", zOp);
  72873. displayP4Expr(p, pExpr->pLeft);
  72874. if( pExpr->pRight ){
  72875. sqlite3_str_append(p, ",", 1);
  72876. displayP4Expr(p, pExpr->pRight);
  72877. }
  72878. sqlite3_str_append(p, ")", 1);
  72879. }
  72880. }
  72881. #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
  72882. #if VDBE_DISPLAY_P4
  72883. /*
  72884. ** Compute a string that describes the P4 parameter for an opcode.
  72885. ** Use zTemp for any required temporary buffer space.
  72886. */
  72887. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  72888. char *zP4 = zTemp;
  72889. StrAccum x;
  72890. assert( nTemp>=20 );
  72891. sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
  72892. switch( pOp->p4type ){
  72893. case P4_KEYINFO: {
  72894. int j;
  72895. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  72896. assert( pKeyInfo->aSortOrder!=0 );
  72897. sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
  72898. for(j=0; j<pKeyInfo->nKeyField; j++){
  72899. CollSeq *pColl = pKeyInfo->aColl[j];
  72900. const char *zColl = pColl ? pColl->zName : "";
  72901. if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
  72902. sqlite3_str_appendf(&x, ",%s%s",
  72903. pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
  72904. }
  72905. sqlite3_str_append(&x, ")", 1);
  72906. break;
  72907. }
  72908. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  72909. case P4_EXPR: {
  72910. displayP4Expr(&x, pOp->p4.pExpr);
  72911. break;
  72912. }
  72913. #endif
  72914. case P4_COLLSEQ: {
  72915. CollSeq *pColl = pOp->p4.pColl;
  72916. sqlite3_str_appendf(&x, "(%.20s)", pColl->zName);
  72917. break;
  72918. }
  72919. case P4_FUNCDEF: {
  72920. FuncDef *pDef = pOp->p4.pFunc;
  72921. sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  72922. break;
  72923. }
  72924. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  72925. case P4_FUNCCTX: {
  72926. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  72927. sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  72928. break;
  72929. }
  72930. #endif
  72931. case P4_INT64: {
  72932. sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
  72933. break;
  72934. }
  72935. case P4_INT32: {
  72936. sqlite3_str_appendf(&x, "%d", pOp->p4.i);
  72937. break;
  72938. }
  72939. case P4_REAL: {
  72940. sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
  72941. break;
  72942. }
  72943. case P4_MEM: {
  72944. Mem *pMem = pOp->p4.pMem;
  72945. if( pMem->flags & MEM_Str ){
  72946. zP4 = pMem->z;
  72947. }else if( pMem->flags & MEM_Int ){
  72948. sqlite3_str_appendf(&x, "%lld", pMem->u.i);
  72949. }else if( pMem->flags & MEM_Real ){
  72950. sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
  72951. }else if( pMem->flags & MEM_Null ){
  72952. zP4 = "NULL";
  72953. }else{
  72954. assert( pMem->flags & MEM_Blob );
  72955. zP4 = "(blob)";
  72956. }
  72957. break;
  72958. }
  72959. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72960. case P4_VTAB: {
  72961. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  72962. sqlite3_str_appendf(&x, "vtab:%p", pVtab);
  72963. break;
  72964. }
  72965. #endif
  72966. case P4_INTARRAY: {
  72967. int i;
  72968. int *ai = pOp->p4.ai;
  72969. int n = ai[0]; /* The first element of an INTARRAY is always the
  72970. ** count of the number of elements to follow */
  72971. for(i=1; i<=n; i++){
  72972. sqlite3_str_appendf(&x, ",%d", ai[i]);
  72973. }
  72974. zTemp[0] = '[';
  72975. sqlite3_str_append(&x, "]", 1);
  72976. break;
  72977. }
  72978. case P4_SUBPROGRAM: {
  72979. sqlite3_str_appendf(&x, "program");
  72980. break;
  72981. }
  72982. case P4_DYNBLOB:
  72983. case P4_ADVANCE: {
  72984. zTemp[0] = 0;
  72985. break;
  72986. }
  72987. case P4_TABLE: {
  72988. sqlite3_str_appendf(&x, "%s", pOp->p4.pTab->zName);
  72989. break;
  72990. }
  72991. default: {
  72992. zP4 = pOp->p4.z;
  72993. if( zP4==0 ){
  72994. zP4 = zTemp;
  72995. zTemp[0] = 0;
  72996. }
  72997. }
  72998. }
  72999. sqlite3StrAccumFinish(&x);
  73000. assert( zP4!=0 );
  73001. return zP4;
  73002. }
  73003. #endif /* VDBE_DISPLAY_P4 */
  73004. /*
  73005. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  73006. **
  73007. ** The prepared statements need to know in advance the complete set of
  73008. ** attached databases that will be use. A mask of these databases
  73009. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  73010. ** p->btreeMask of databases that will require a lock.
  73011. */
  73012. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  73013. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  73014. assert( i<(int)sizeof(p->btreeMask)*8 );
  73015. DbMaskSet(p->btreeMask, i);
  73016. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  73017. DbMaskSet(p->lockMask, i);
  73018. }
  73019. }
  73020. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  73021. /*
  73022. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  73023. ** this routine obtains the mutex associated with each BtShared structure
  73024. ** that may be accessed by the VM passed as an argument. In doing so it also
  73025. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  73026. ** that the correct busy-handler callback is invoked if required.
  73027. **
  73028. ** If SQLite is not threadsafe but does support shared-cache mode, then
  73029. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  73030. ** of all of BtShared structures accessible via the database handle
  73031. ** associated with the VM.
  73032. **
  73033. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  73034. ** function is a no-op.
  73035. **
  73036. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  73037. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  73038. ** corresponding to btrees that use shared cache. Then the runtime of
  73039. ** this routine is N*N. But as N is rarely more than 1, this should not
  73040. ** be a problem.
  73041. */
  73042. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  73043. int i;
  73044. sqlite3 *db;
  73045. Db *aDb;
  73046. int nDb;
  73047. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  73048. db = p->db;
  73049. aDb = db->aDb;
  73050. nDb = db->nDb;
  73051. for(i=0; i<nDb; i++){
  73052. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  73053. sqlite3BtreeEnter(aDb[i].pBt);
  73054. }
  73055. }
  73056. }
  73057. #endif
  73058. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  73059. /*
  73060. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  73061. */
  73062. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  73063. int i;
  73064. sqlite3 *db;
  73065. Db *aDb;
  73066. int nDb;
  73067. db = p->db;
  73068. aDb = db->aDb;
  73069. nDb = db->nDb;
  73070. for(i=0; i<nDb; i++){
  73071. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  73072. sqlite3BtreeLeave(aDb[i].pBt);
  73073. }
  73074. }
  73075. }
  73076. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  73077. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  73078. vdbeLeave(p);
  73079. }
  73080. #endif
  73081. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  73082. /*
  73083. ** Print a single opcode. This routine is used for debugging only.
  73084. */
  73085. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
  73086. char *zP4;
  73087. char zPtr[50];
  73088. char zCom[100];
  73089. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  73090. if( pOut==0 ) pOut = stdout;
  73091. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  73092. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  73093. displayComment(pOp, zP4, zCom, sizeof(zCom));
  73094. #else
  73095. zCom[0] = 0;
  73096. #endif
  73097. /* NB: The sqlite3OpcodeName() function is implemented by code created
  73098. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  73099. ** information from the vdbe.c source text */
  73100. fprintf(pOut, zFormat1, pc,
  73101. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  73102. zCom
  73103. );
  73104. fflush(pOut);
  73105. }
  73106. #endif
  73107. /*
  73108. ** Initialize an array of N Mem element.
  73109. */
  73110. static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
  73111. while( (N--)>0 ){
  73112. p->db = db;
  73113. p->flags = flags;
  73114. p->szMalloc = 0;
  73115. #ifdef SQLITE_DEBUG
  73116. p->pScopyFrom = 0;
  73117. #endif
  73118. p++;
  73119. }
  73120. }
  73121. /*
  73122. ** Release an array of N Mem elements
  73123. */
  73124. static void releaseMemArray(Mem *p, int N){
  73125. if( p && N ){
  73126. Mem *pEnd = &p[N];
  73127. sqlite3 *db = p->db;
  73128. if( db->pnBytesFreed ){
  73129. do{
  73130. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  73131. }while( (++p)<pEnd );
  73132. return;
  73133. }
  73134. do{
  73135. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  73136. assert( sqlite3VdbeCheckMemInvariants(p) );
  73137. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  73138. ** that takes advantage of the fact that the memory cell value is
  73139. ** being set to NULL after releasing any dynamic resources.
  73140. **
  73141. ** The justification for duplicating code is that according to
  73142. ** callgrind, this causes a certain test case to hit the CPU 4.7
  73143. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  73144. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  73145. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  73146. ** with no indexes using a single prepared INSERT statement, bind()
  73147. ** and reset(). Inserts are grouped into a transaction.
  73148. */
  73149. testcase( p->flags & MEM_Agg );
  73150. testcase( p->flags & MEM_Dyn );
  73151. testcase( p->xDel==sqlite3VdbeFrameMemDel );
  73152. if( p->flags&(MEM_Agg|MEM_Dyn) ){
  73153. sqlite3VdbeMemRelease(p);
  73154. }else if( p->szMalloc ){
  73155. sqlite3DbFreeNN(db, p->zMalloc);
  73156. p->szMalloc = 0;
  73157. }
  73158. p->flags = MEM_Undefined;
  73159. }while( (++p)<pEnd );
  73160. }
  73161. }
  73162. #ifdef SQLITE_DEBUG
  73163. /*
  73164. ** Verify that pFrame is a valid VdbeFrame pointer. Return true if it is
  73165. ** and false if something is wrong.
  73166. **
  73167. ** This routine is intended for use inside of assert() statements only.
  73168. */
  73169. SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
  73170. if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
  73171. return 1;
  73172. }
  73173. #endif
  73174. /*
  73175. ** This is a destructor on a Mem object (which is really an sqlite3_value)
  73176. ** that deletes the Frame object that is attached to it as a blob.
  73177. **
  73178. ** This routine does not delete the Frame right away. It merely adds the
  73179. ** frame to a list of frames to be deleted when the Vdbe halts.
  73180. */
  73181. SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void *pArg){
  73182. VdbeFrame *pFrame = (VdbeFrame*)pArg;
  73183. assert( sqlite3VdbeFrameIsValid(pFrame) );
  73184. pFrame->pParent = pFrame->v->pDelFrame;
  73185. pFrame->v->pDelFrame = pFrame;
  73186. }
  73187. /*
  73188. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  73189. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  73190. */
  73191. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  73192. int i;
  73193. Mem *aMem = VdbeFrameMem(p);
  73194. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  73195. assert( sqlite3VdbeFrameIsValid(p) );
  73196. for(i=0; i<p->nChildCsr; i++){
  73197. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  73198. }
  73199. releaseMemArray(aMem, p->nChildMem);
  73200. sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
  73201. sqlite3DbFree(p->v->db, p);
  73202. }
  73203. #ifndef SQLITE_OMIT_EXPLAIN
  73204. /*
  73205. ** Give a listing of the program in the virtual machine.
  73206. **
  73207. ** The interface is the same as sqlite3VdbeExec(). But instead of
  73208. ** running the code, it invokes the callback once for each instruction.
  73209. ** This feature is used to implement "EXPLAIN".
  73210. **
  73211. ** When p->explain==1, each instruction is listed. When
  73212. ** p->explain==2, only OP_Explain instructions are listed and these
  73213. ** are shown in a different format. p->explain==2 is used to implement
  73214. ** EXPLAIN QUERY PLAN.
  73215. ** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
  73216. ** are also shown, so that the boundaries between the main program and
  73217. ** each trigger are clear.
  73218. **
  73219. ** When p->explain==1, first the main program is listed, then each of
  73220. ** the trigger subprograms are listed one by one.
  73221. */
  73222. SQLITE_PRIVATE int sqlite3VdbeList(
  73223. Vdbe *p /* The VDBE */
  73224. ){
  73225. int nRow; /* Stop when row count reaches this */
  73226. int nSub = 0; /* Number of sub-vdbes seen so far */
  73227. SubProgram **apSub = 0; /* Array of sub-vdbes */
  73228. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  73229. sqlite3 *db = p->db; /* The database connection */
  73230. int i; /* Loop counter */
  73231. int rc = SQLITE_OK; /* Return code */
  73232. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  73233. int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
  73234. Op *pOp = 0;
  73235. assert( p->explain );
  73236. assert( p->magic==VDBE_MAGIC_RUN );
  73237. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  73238. /* Even though this opcode does not use dynamic strings for
  73239. ** the result, result columns may become dynamic if the user calls
  73240. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  73241. */
  73242. releaseMemArray(pMem, 8);
  73243. p->pResultSet = 0;
  73244. if( p->rc==SQLITE_NOMEM ){
  73245. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  73246. ** sqlite3_column_text16() failed. */
  73247. sqlite3OomFault(db);
  73248. return SQLITE_ERROR;
  73249. }
  73250. /* When the number of output rows reaches nRow, that means the
  73251. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  73252. ** nRow is the sum of the number of rows in the main program, plus
  73253. ** the sum of the number of rows in all trigger subprograms encountered
  73254. ** so far. The nRow value will increase as new trigger subprograms are
  73255. ** encountered, but p->pc will eventually catch up to nRow.
  73256. */
  73257. nRow = p->nOp;
  73258. if( bListSubprogs ){
  73259. /* The first 8 memory cells are used for the result set. So we will
  73260. ** commandeer the 9th cell to use as storage for an array of pointers
  73261. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  73262. ** cells. */
  73263. assert( p->nMem>9 );
  73264. pSub = &p->aMem[9];
  73265. if( pSub->flags&MEM_Blob ){
  73266. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  73267. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  73268. nSub = pSub->n/sizeof(Vdbe*);
  73269. apSub = (SubProgram **)pSub->z;
  73270. }
  73271. for(i=0; i<nSub; i++){
  73272. nRow += apSub[i]->nOp;
  73273. }
  73274. }
  73275. while(1){ /* Loop exits via break */
  73276. i = p->pc++;
  73277. if( i>=nRow ){
  73278. p->rc = SQLITE_OK;
  73279. rc = SQLITE_DONE;
  73280. break;
  73281. }
  73282. if( i<p->nOp ){
  73283. /* The output line number is small enough that we are still in the
  73284. ** main program. */
  73285. pOp = &p->aOp[i];
  73286. }else{
  73287. /* We are currently listing subprograms. Figure out which one and
  73288. ** pick up the appropriate opcode. */
  73289. int j;
  73290. i -= p->nOp;
  73291. for(j=0; i>=apSub[j]->nOp; j++){
  73292. i -= apSub[j]->nOp;
  73293. }
  73294. pOp = &apSub[j]->aOp[i];
  73295. }
  73296. /* When an OP_Program opcode is encounter (the only opcode that has
  73297. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  73298. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  73299. ** has not already been seen.
  73300. */
  73301. if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
  73302. int nByte = (nSub+1)*sizeof(SubProgram*);
  73303. int j;
  73304. for(j=0; j<nSub; j++){
  73305. if( apSub[j]==pOp->p4.pProgram ) break;
  73306. }
  73307. if( j==nSub ){
  73308. p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
  73309. if( p->rc!=SQLITE_OK ){
  73310. rc = SQLITE_ERROR;
  73311. break;
  73312. }
  73313. apSub = (SubProgram **)pSub->z;
  73314. apSub[nSub++] = pOp->p4.pProgram;
  73315. pSub->flags |= MEM_Blob;
  73316. pSub->n = nSub*sizeof(SubProgram*);
  73317. nRow += pOp->p4.pProgram->nOp;
  73318. }
  73319. }
  73320. if( p->explain<2 ) break;
  73321. if( pOp->opcode==OP_Explain ) break;
  73322. if( pOp->opcode==OP_Init && p->pc>1 ) break;
  73323. }
  73324. if( rc==SQLITE_OK ){
  73325. if( db->u1.isInterrupted ){
  73326. p->rc = SQLITE_INTERRUPT;
  73327. rc = SQLITE_ERROR;
  73328. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  73329. }else{
  73330. char *zP4;
  73331. if( p->explain==1 ){
  73332. pMem->flags = MEM_Int;
  73333. pMem->u.i = i; /* Program counter */
  73334. pMem++;
  73335. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  73336. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  73337. assert( pMem->z!=0 );
  73338. pMem->n = sqlite3Strlen30(pMem->z);
  73339. pMem->enc = SQLITE_UTF8;
  73340. pMem++;
  73341. }
  73342. pMem->flags = MEM_Int;
  73343. pMem->u.i = pOp->p1; /* P1 */
  73344. pMem++;
  73345. pMem->flags = MEM_Int;
  73346. pMem->u.i = pOp->p2; /* P2 */
  73347. pMem++;
  73348. pMem->flags = MEM_Int;
  73349. pMem->u.i = pOp->p3; /* P3 */
  73350. pMem++;
  73351. if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
  73352. assert( p->db->mallocFailed );
  73353. return SQLITE_ERROR;
  73354. }
  73355. pMem->flags = MEM_Str|MEM_Term;
  73356. zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
  73357. if( zP4!=pMem->z ){
  73358. pMem->n = 0;
  73359. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  73360. }else{
  73361. assert( pMem->z!=0 );
  73362. pMem->n = sqlite3Strlen30(pMem->z);
  73363. pMem->enc = SQLITE_UTF8;
  73364. }
  73365. pMem++;
  73366. if( p->explain==1 ){
  73367. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  73368. assert( p->db->mallocFailed );
  73369. return SQLITE_ERROR;
  73370. }
  73371. pMem->flags = MEM_Str|MEM_Term;
  73372. pMem->n = 2;
  73373. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  73374. pMem->enc = SQLITE_UTF8;
  73375. pMem++;
  73376. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  73377. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  73378. assert( p->db->mallocFailed );
  73379. return SQLITE_ERROR;
  73380. }
  73381. pMem->flags = MEM_Str|MEM_Term;
  73382. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  73383. pMem->enc = SQLITE_UTF8;
  73384. #else
  73385. pMem->flags = MEM_Null; /* Comment */
  73386. #endif
  73387. }
  73388. p->nResColumn = 8 - 4*(p->explain-1);
  73389. p->pResultSet = &p->aMem[1];
  73390. p->rc = SQLITE_OK;
  73391. rc = SQLITE_ROW;
  73392. }
  73393. }
  73394. return rc;
  73395. }
  73396. #endif /* SQLITE_OMIT_EXPLAIN */
  73397. #ifdef SQLITE_DEBUG
  73398. /*
  73399. ** Print the SQL that was used to generate a VDBE program.
  73400. */
  73401. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  73402. const char *z = 0;
  73403. if( p->zSql ){
  73404. z = p->zSql;
  73405. }else if( p->nOp>=1 ){
  73406. const VdbeOp *pOp = &p->aOp[0];
  73407. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  73408. z = pOp->p4.z;
  73409. while( sqlite3Isspace(*z) ) z++;
  73410. }
  73411. }
  73412. if( z ) printf("SQL: [%s]\n", z);
  73413. }
  73414. #endif
  73415. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  73416. /*
  73417. ** Print an IOTRACE message showing SQL content.
  73418. */
  73419. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  73420. int nOp = p->nOp;
  73421. VdbeOp *pOp;
  73422. if( sqlite3IoTrace==0 ) return;
  73423. if( nOp<1 ) return;
  73424. pOp = &p->aOp[0];
  73425. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  73426. int i, j;
  73427. char z[1000];
  73428. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  73429. for(i=0; sqlite3Isspace(z[i]); i++){}
  73430. for(j=0; z[i]; i++){
  73431. if( sqlite3Isspace(z[i]) ){
  73432. if( z[i-1]!=' ' ){
  73433. z[j++] = ' ';
  73434. }
  73435. }else{
  73436. z[j++] = z[i];
  73437. }
  73438. }
  73439. z[j] = 0;
  73440. sqlite3IoTrace("SQL %s\n", z);
  73441. }
  73442. }
  73443. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  73444. /* An instance of this object describes bulk memory available for use
  73445. ** by subcomponents of a prepared statement. Space is allocated out
  73446. ** of a ReusableSpace object by the allocSpace() routine below.
  73447. */
  73448. struct ReusableSpace {
  73449. u8 *pSpace; /* Available memory */
  73450. sqlite3_int64 nFree; /* Bytes of available memory */
  73451. sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
  73452. };
  73453. /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
  73454. ** from the ReusableSpace object. Return a pointer to the allocated
  73455. ** memory on success. If insufficient memory is available in the
  73456. ** ReusableSpace object, increase the ReusableSpace.nNeeded
  73457. ** value by the amount needed and return NULL.
  73458. **
  73459. ** If pBuf is not initially NULL, that means that the memory has already
  73460. ** been allocated by a prior call to this routine, so just return a copy
  73461. ** of pBuf and leave ReusableSpace unchanged.
  73462. **
  73463. ** This allocator is employed to repurpose unused slots at the end of the
  73464. ** opcode array of prepared state for other memory needs of the prepared
  73465. ** statement.
  73466. */
  73467. static void *allocSpace(
  73468. struct ReusableSpace *p, /* Bulk memory available for allocation */
  73469. void *pBuf, /* Pointer to a prior allocation */
  73470. sqlite3_int64 nByte /* Bytes of memory needed */
  73471. ){
  73472. assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
  73473. if( pBuf==0 ){
  73474. nByte = ROUND8(nByte);
  73475. if( nByte <= p->nFree ){
  73476. p->nFree -= nByte;
  73477. pBuf = &p->pSpace[p->nFree];
  73478. }else{
  73479. p->nNeeded += nByte;
  73480. }
  73481. }
  73482. assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
  73483. return pBuf;
  73484. }
  73485. /*
  73486. ** Rewind the VDBE back to the beginning in preparation for
  73487. ** running it.
  73488. */
  73489. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  73490. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  73491. int i;
  73492. #endif
  73493. assert( p!=0 );
  73494. assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
  73495. /* There should be at least one opcode.
  73496. */
  73497. assert( p->nOp>0 );
  73498. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  73499. p->magic = VDBE_MAGIC_RUN;
  73500. #ifdef SQLITE_DEBUG
  73501. for(i=0; i<p->nMem; i++){
  73502. assert( p->aMem[i].db==p->db );
  73503. }
  73504. #endif
  73505. p->pc = -1;
  73506. p->rc = SQLITE_OK;
  73507. p->errorAction = OE_Abort;
  73508. p->nChange = 0;
  73509. p->cacheCtr = 1;
  73510. p->minWriteFileFormat = 255;
  73511. p->iStatement = 0;
  73512. p->nFkConstraint = 0;
  73513. #ifdef VDBE_PROFILE
  73514. for(i=0; i<p->nOp; i++){
  73515. p->aOp[i].cnt = 0;
  73516. p->aOp[i].cycles = 0;
  73517. }
  73518. #endif
  73519. }
  73520. /*
  73521. ** Prepare a virtual machine for execution for the first time after
  73522. ** creating the virtual machine. This involves things such
  73523. ** as allocating registers and initializing the program counter.
  73524. ** After the VDBE has be prepped, it can be executed by one or more
  73525. ** calls to sqlite3VdbeExec().
  73526. **
  73527. ** This function may be called exactly once on each virtual machine.
  73528. ** After this routine is called the VM has been "packaged" and is ready
  73529. ** to run. After this routine is called, further calls to
  73530. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  73531. ** the Vdbe from the Parse object that helped generate it so that the
  73532. ** the Vdbe becomes an independent entity and the Parse object can be
  73533. ** destroyed.
  73534. **
  73535. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  73536. ** to its initial state after it has been run.
  73537. */
  73538. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  73539. Vdbe *p, /* The VDBE */
  73540. Parse *pParse /* Parsing context */
  73541. ){
  73542. sqlite3 *db; /* The database connection */
  73543. int nVar; /* Number of parameters */
  73544. int nMem; /* Number of VM memory registers */
  73545. int nCursor; /* Number of cursors required */
  73546. int nArg; /* Number of arguments in subprograms */
  73547. int n; /* Loop counter */
  73548. struct ReusableSpace x; /* Reusable bulk memory */
  73549. assert( p!=0 );
  73550. assert( p->nOp>0 );
  73551. assert( pParse!=0 );
  73552. assert( p->magic==VDBE_MAGIC_INIT );
  73553. assert( pParse==p->pParse );
  73554. db = p->db;
  73555. assert( db->mallocFailed==0 );
  73556. nVar = pParse->nVar;
  73557. nMem = pParse->nMem;
  73558. nCursor = pParse->nTab;
  73559. nArg = pParse->nMaxArg;
  73560. /* Each cursor uses a memory cell. The first cursor (cursor 0) can
  73561. ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
  73562. ** space at the end of aMem[] for cursors 1 and greater.
  73563. ** See also: allocateCursor().
  73564. */
  73565. nMem += nCursor;
  73566. if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
  73567. /* Figure out how much reusable memory is available at the end of the
  73568. ** opcode array. This extra memory will be reallocated for other elements
  73569. ** of the prepared statement.
  73570. */
  73571. n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
  73572. x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
  73573. assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
  73574. x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
  73575. assert( x.nFree>=0 );
  73576. assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
  73577. resolveP2Values(p, &nArg);
  73578. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  73579. if( pParse->explain && nMem<10 ){
  73580. nMem = 10;
  73581. }
  73582. p->expired = 0;
  73583. /* Memory for registers, parameters, cursor, etc, is allocated in one or two
  73584. ** passes. On the first pass, we try to reuse unused memory at the
  73585. ** end of the opcode array. If we are unable to satisfy all memory
  73586. ** requirements by reusing the opcode array tail, then the second
  73587. ** pass will fill in the remainder using a fresh memory allocation.
  73588. **
  73589. ** This two-pass approach that reuses as much memory as possible from
  73590. ** the leftover memory at the end of the opcode array. This can significantly
  73591. ** reduce the amount of memory held by a prepared statement.
  73592. */
  73593. x.nNeeded = 0;
  73594. p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
  73595. p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
  73596. p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
  73597. p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
  73598. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73599. p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64));
  73600. #endif
  73601. if( x.nNeeded ){
  73602. x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
  73603. x.nFree = x.nNeeded;
  73604. if( !db->mallocFailed ){
  73605. p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
  73606. p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
  73607. p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
  73608. p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
  73609. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73610. p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
  73611. #endif
  73612. }
  73613. }
  73614. p->pVList = pParse->pVList;
  73615. pParse->pVList = 0;
  73616. p->explain = pParse->explain;
  73617. if( db->mallocFailed ){
  73618. p->nVar = 0;
  73619. p->nCursor = 0;
  73620. p->nMem = 0;
  73621. }else{
  73622. p->nCursor = nCursor;
  73623. p->nVar = (ynVar)nVar;
  73624. initMemArray(p->aVar, nVar, db, MEM_Null);
  73625. p->nMem = nMem;
  73626. initMemArray(p->aMem, nMem, db, MEM_Undefined);
  73627. memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
  73628. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73629. memset(p->anExec, 0, p->nOp*sizeof(i64));
  73630. #endif
  73631. }
  73632. sqlite3VdbeRewind(p);
  73633. }
  73634. /*
  73635. ** Close a VDBE cursor and release all the resources that cursor
  73636. ** happens to hold.
  73637. */
  73638. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  73639. if( pCx==0 ){
  73640. return;
  73641. }
  73642. assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
  73643. switch( pCx->eCurType ){
  73644. case CURTYPE_SORTER: {
  73645. sqlite3VdbeSorterClose(p->db, pCx);
  73646. break;
  73647. }
  73648. case CURTYPE_BTREE: {
  73649. if( pCx->isEphemeral ){
  73650. if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
  73651. /* The pCx->pCursor will be close automatically, if it exists, by
  73652. ** the call above. */
  73653. }else{
  73654. assert( pCx->uc.pCursor!=0 );
  73655. sqlite3BtreeCloseCursor(pCx->uc.pCursor);
  73656. }
  73657. break;
  73658. }
  73659. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73660. case CURTYPE_VTAB: {
  73661. sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
  73662. const sqlite3_module *pModule = pVCur->pVtab->pModule;
  73663. assert( pVCur->pVtab->nRef>0 );
  73664. pVCur->pVtab->nRef--;
  73665. pModule->xClose(pVCur);
  73666. break;
  73667. }
  73668. #endif
  73669. }
  73670. }
  73671. /*
  73672. ** Close all cursors in the current frame.
  73673. */
  73674. static void closeCursorsInFrame(Vdbe *p){
  73675. if( p->apCsr ){
  73676. int i;
  73677. for(i=0; i<p->nCursor; i++){
  73678. VdbeCursor *pC = p->apCsr[i];
  73679. if( pC ){
  73680. sqlite3VdbeFreeCursor(p, pC);
  73681. p->apCsr[i] = 0;
  73682. }
  73683. }
  73684. }
  73685. }
  73686. /*
  73687. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  73688. ** is used, for example, when a trigger sub-program is halted to restore
  73689. ** control to the main program.
  73690. */
  73691. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  73692. Vdbe *v = pFrame->v;
  73693. closeCursorsInFrame(v);
  73694. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73695. v->anExec = pFrame->anExec;
  73696. #endif
  73697. v->aOp = pFrame->aOp;
  73698. v->nOp = pFrame->nOp;
  73699. v->aMem = pFrame->aMem;
  73700. v->nMem = pFrame->nMem;
  73701. v->apCsr = pFrame->apCsr;
  73702. v->nCursor = pFrame->nCursor;
  73703. v->db->lastRowid = pFrame->lastRowid;
  73704. v->nChange = pFrame->nChange;
  73705. v->db->nChange = pFrame->nDbChange;
  73706. sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
  73707. v->pAuxData = pFrame->pAuxData;
  73708. pFrame->pAuxData = 0;
  73709. return pFrame->pc;
  73710. }
  73711. /*
  73712. ** Close all cursors.
  73713. **
  73714. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  73715. ** cell array. This is necessary as the memory cell array may contain
  73716. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  73717. ** open cursors.
  73718. */
  73719. static void closeAllCursors(Vdbe *p){
  73720. if( p->pFrame ){
  73721. VdbeFrame *pFrame;
  73722. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  73723. sqlite3VdbeFrameRestore(pFrame);
  73724. p->pFrame = 0;
  73725. p->nFrame = 0;
  73726. }
  73727. assert( p->nFrame==0 );
  73728. closeCursorsInFrame(p);
  73729. if( p->aMem ){
  73730. releaseMemArray(p->aMem, p->nMem);
  73731. }
  73732. while( p->pDelFrame ){
  73733. VdbeFrame *pDel = p->pDelFrame;
  73734. p->pDelFrame = pDel->pParent;
  73735. sqlite3VdbeFrameDelete(pDel);
  73736. }
  73737. /* Delete any auxdata allocations made by the VM */
  73738. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
  73739. assert( p->pAuxData==0 );
  73740. }
  73741. /*
  73742. ** Set the number of result columns that will be returned by this SQL
  73743. ** statement. This is now set at compile time, rather than during
  73744. ** execution of the vdbe program so that sqlite3_column_count() can
  73745. ** be called on an SQL statement before sqlite3_step().
  73746. */
  73747. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  73748. int n;
  73749. sqlite3 *db = p->db;
  73750. if( p->nResColumn ){
  73751. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  73752. sqlite3DbFree(db, p->aColName);
  73753. }
  73754. n = nResColumn*COLNAME_N;
  73755. p->nResColumn = (u16)nResColumn;
  73756. p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
  73757. if( p->aColName==0 ) return;
  73758. initMemArray(p->aColName, n, db, MEM_Null);
  73759. }
  73760. /*
  73761. ** Set the name of the idx'th column to be returned by the SQL statement.
  73762. ** zName must be a pointer to a nul terminated string.
  73763. **
  73764. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  73765. **
  73766. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  73767. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  73768. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  73769. */
  73770. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  73771. Vdbe *p, /* Vdbe being configured */
  73772. int idx, /* Index of column zName applies to */
  73773. int var, /* One of the COLNAME_* constants */
  73774. const char *zName, /* Pointer to buffer containing name */
  73775. void (*xDel)(void*) /* Memory management strategy for zName */
  73776. ){
  73777. int rc;
  73778. Mem *pColName;
  73779. assert( idx<p->nResColumn );
  73780. assert( var<COLNAME_N );
  73781. if( p->db->mallocFailed ){
  73782. assert( !zName || xDel!=SQLITE_DYNAMIC );
  73783. return SQLITE_NOMEM_BKPT;
  73784. }
  73785. assert( p->aColName!=0 );
  73786. pColName = &(p->aColName[idx+var*p->nResColumn]);
  73787. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  73788. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  73789. return rc;
  73790. }
  73791. /*
  73792. ** A read or write transaction may or may not be active on database handle
  73793. ** db. If a transaction is active, commit it. If there is a
  73794. ** write-transaction spanning more than one database file, this routine
  73795. ** takes care of the master journal trickery.
  73796. */
  73797. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  73798. int i;
  73799. int nTrans = 0; /* Number of databases with an active write-transaction
  73800. ** that are candidates for a two-phase commit using a
  73801. ** master-journal */
  73802. int rc = SQLITE_OK;
  73803. int needXcommit = 0;
  73804. #ifdef SQLITE_OMIT_VIRTUALTABLE
  73805. /* With this option, sqlite3VtabSync() is defined to be simply
  73806. ** SQLITE_OK so p is not used.
  73807. */
  73808. UNUSED_PARAMETER(p);
  73809. #endif
  73810. /* Before doing anything else, call the xSync() callback for any
  73811. ** virtual module tables written in this transaction. This has to
  73812. ** be done before determining whether a master journal file is
  73813. ** required, as an xSync() callback may add an attached database
  73814. ** to the transaction.
  73815. */
  73816. rc = sqlite3VtabSync(db, p);
  73817. /* This loop determines (a) if the commit hook should be invoked and
  73818. ** (b) how many database files have open write transactions, not
  73819. ** including the temp database. (b) is important because if more than
  73820. ** one database file has an open write transaction, a master journal
  73821. ** file is required for an atomic commit.
  73822. */
  73823. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  73824. Btree *pBt = db->aDb[i].pBt;
  73825. if( sqlite3BtreeIsInTrans(pBt) ){
  73826. /* Whether or not a database might need a master journal depends upon
  73827. ** its journal mode (among other things). This matrix determines which
  73828. ** journal modes use a master journal and which do not */
  73829. static const u8 aMJNeeded[] = {
  73830. /* DELETE */ 1,
  73831. /* PERSIST */ 1,
  73832. /* OFF */ 0,
  73833. /* TRUNCATE */ 1,
  73834. /* MEMORY */ 0,
  73835. /* WAL */ 0
  73836. };
  73837. Pager *pPager; /* Pager associated with pBt */
  73838. needXcommit = 1;
  73839. sqlite3BtreeEnter(pBt);
  73840. pPager = sqlite3BtreePager(pBt);
  73841. if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
  73842. && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
  73843. && sqlite3PagerIsMemdb(pPager)==0
  73844. ){
  73845. assert( i!=1 );
  73846. nTrans++;
  73847. }
  73848. rc = sqlite3PagerExclusiveLock(pPager);
  73849. sqlite3BtreeLeave(pBt);
  73850. }
  73851. }
  73852. if( rc!=SQLITE_OK ){
  73853. return rc;
  73854. }
  73855. /* If there are any write-transactions at all, invoke the commit hook */
  73856. if( needXcommit && db->xCommitCallback ){
  73857. rc = db->xCommitCallback(db->pCommitArg);
  73858. if( rc ){
  73859. return SQLITE_CONSTRAINT_COMMITHOOK;
  73860. }
  73861. }
  73862. /* The simple case - no more than one database file (not counting the
  73863. ** TEMP database) has a transaction active. There is no need for the
  73864. ** master-journal.
  73865. **
  73866. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  73867. ** string, it means the main database is :memory: or a temp file. In
  73868. ** that case we do not support atomic multi-file commits, so use the
  73869. ** simple case then too.
  73870. */
  73871. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  73872. || nTrans<=1
  73873. ){
  73874. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  73875. Btree *pBt = db->aDb[i].pBt;
  73876. if( pBt ){
  73877. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  73878. }
  73879. }
  73880. /* Do the commit only if all databases successfully complete phase 1.
  73881. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  73882. ** IO error while deleting or truncating a journal file. It is unlikely,
  73883. ** but could happen. In this case abandon processing and return the error.
  73884. */
  73885. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  73886. Btree *pBt = db->aDb[i].pBt;
  73887. if( pBt ){
  73888. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  73889. }
  73890. }
  73891. if( rc==SQLITE_OK ){
  73892. sqlite3VtabCommit(db);
  73893. }
  73894. }
  73895. /* The complex case - There is a multi-file write-transaction active.
  73896. ** This requires a master journal file to ensure the transaction is
  73897. ** committed atomically.
  73898. */
  73899. #ifndef SQLITE_OMIT_DISKIO
  73900. else{
  73901. sqlite3_vfs *pVfs = db->pVfs;
  73902. char *zMaster = 0; /* File-name for the master journal */
  73903. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  73904. sqlite3_file *pMaster = 0;
  73905. i64 offset = 0;
  73906. int res;
  73907. int retryCount = 0;
  73908. int nMainFile;
  73909. /* Select a master journal file name */
  73910. nMainFile = sqlite3Strlen30(zMainFile);
  73911. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  73912. if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
  73913. do {
  73914. u32 iRandom;
  73915. if( retryCount ){
  73916. if( retryCount>100 ){
  73917. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  73918. sqlite3OsDelete(pVfs, zMaster, 0);
  73919. break;
  73920. }else if( retryCount==1 ){
  73921. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  73922. }
  73923. }
  73924. retryCount++;
  73925. sqlite3_randomness(sizeof(iRandom), &iRandom);
  73926. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  73927. (iRandom>>8)&0xffffff, iRandom&0xff);
  73928. /* The antipenultimate character of the master journal name must
  73929. ** be "9" to avoid name collisions when using 8+3 filenames. */
  73930. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  73931. sqlite3FileSuffix3(zMainFile, zMaster);
  73932. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  73933. }while( rc==SQLITE_OK && res );
  73934. if( rc==SQLITE_OK ){
  73935. /* Open the master journal. */
  73936. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  73937. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  73938. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  73939. );
  73940. }
  73941. if( rc!=SQLITE_OK ){
  73942. sqlite3DbFree(db, zMaster);
  73943. return rc;
  73944. }
  73945. /* Write the name of each database file in the transaction into the new
  73946. ** master journal file. If an error occurs at this point close
  73947. ** and delete the master journal file. All the individual journal files
  73948. ** still have 'null' as the master journal pointer, so they will roll
  73949. ** back independently if a failure occurs.
  73950. */
  73951. for(i=0; i<db->nDb; i++){
  73952. Btree *pBt = db->aDb[i].pBt;
  73953. if( sqlite3BtreeIsInTrans(pBt) ){
  73954. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  73955. if( zFile==0 ){
  73956. continue; /* Ignore TEMP and :memory: databases */
  73957. }
  73958. assert( zFile[0]!=0 );
  73959. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  73960. offset += sqlite3Strlen30(zFile)+1;
  73961. if( rc!=SQLITE_OK ){
  73962. sqlite3OsCloseFree(pMaster);
  73963. sqlite3OsDelete(pVfs, zMaster, 0);
  73964. sqlite3DbFree(db, zMaster);
  73965. return rc;
  73966. }
  73967. }
  73968. }
  73969. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  73970. ** flag is set this is not required.
  73971. */
  73972. if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  73973. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  73974. ){
  73975. sqlite3OsCloseFree(pMaster);
  73976. sqlite3OsDelete(pVfs, zMaster, 0);
  73977. sqlite3DbFree(db, zMaster);
  73978. return rc;
  73979. }
  73980. /* Sync all the db files involved in the transaction. The same call
  73981. ** sets the master journal pointer in each individual journal. If
  73982. ** an error occurs here, do not delete the master journal file.
  73983. **
  73984. ** If the error occurs during the first call to
  73985. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  73986. ** master journal file will be orphaned. But we cannot delete it,
  73987. ** in case the master journal file name was written into the journal
  73988. ** file before the failure occurred.
  73989. */
  73990. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  73991. Btree *pBt = db->aDb[i].pBt;
  73992. if( pBt ){
  73993. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  73994. }
  73995. }
  73996. sqlite3OsCloseFree(pMaster);
  73997. assert( rc!=SQLITE_BUSY );
  73998. if( rc!=SQLITE_OK ){
  73999. sqlite3DbFree(db, zMaster);
  74000. return rc;
  74001. }
  74002. /* Delete the master journal file. This commits the transaction. After
  74003. ** doing this the directory is synced again before any individual
  74004. ** transaction files are deleted.
  74005. */
  74006. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  74007. sqlite3DbFree(db, zMaster);
  74008. zMaster = 0;
  74009. if( rc ){
  74010. return rc;
  74011. }
  74012. /* All files and directories have already been synced, so the following
  74013. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  74014. ** deleting or truncating journals. If something goes wrong while
  74015. ** this is happening we don't really care. The integrity of the
  74016. ** transaction is already guaranteed, but some stray 'cold' journals
  74017. ** may be lying around. Returning an error code won't help matters.
  74018. */
  74019. disable_simulated_io_errors();
  74020. sqlite3BeginBenignMalloc();
  74021. for(i=0; i<db->nDb; i++){
  74022. Btree *pBt = db->aDb[i].pBt;
  74023. if( pBt ){
  74024. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  74025. }
  74026. }
  74027. sqlite3EndBenignMalloc();
  74028. enable_simulated_io_errors();
  74029. sqlite3VtabCommit(db);
  74030. }
  74031. #endif
  74032. return rc;
  74033. }
  74034. /*
  74035. ** This routine checks that the sqlite3.nVdbeActive count variable
  74036. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  74037. ** currently active. An assertion fails if the two counts do not match.
  74038. ** This is an internal self-check only - it is not an essential processing
  74039. ** step.
  74040. **
  74041. ** This is a no-op if NDEBUG is defined.
  74042. */
  74043. #ifndef NDEBUG
  74044. static void checkActiveVdbeCnt(sqlite3 *db){
  74045. Vdbe *p;
  74046. int cnt = 0;
  74047. int nWrite = 0;
  74048. int nRead = 0;
  74049. p = db->pVdbe;
  74050. while( p ){
  74051. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  74052. cnt++;
  74053. if( p->readOnly==0 ) nWrite++;
  74054. if( p->bIsReader ) nRead++;
  74055. }
  74056. p = p->pNext;
  74057. }
  74058. assert( cnt==db->nVdbeActive );
  74059. assert( nWrite==db->nVdbeWrite );
  74060. assert( nRead==db->nVdbeRead );
  74061. }
  74062. #else
  74063. #define checkActiveVdbeCnt(x)
  74064. #endif
  74065. /*
  74066. ** If the Vdbe passed as the first argument opened a statement-transaction,
  74067. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  74068. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  74069. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  74070. ** statement transaction is committed.
  74071. **
  74072. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  74073. ** Otherwise SQLITE_OK.
  74074. */
  74075. static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
  74076. sqlite3 *const db = p->db;
  74077. int rc = SQLITE_OK;
  74078. int i;
  74079. const int iSavepoint = p->iStatement-1;
  74080. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  74081. assert( db->nStatement>0 );
  74082. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  74083. for(i=0; i<db->nDb; i++){
  74084. int rc2 = SQLITE_OK;
  74085. Btree *pBt = db->aDb[i].pBt;
  74086. if( pBt ){
  74087. if( eOp==SAVEPOINT_ROLLBACK ){
  74088. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  74089. }
  74090. if( rc2==SQLITE_OK ){
  74091. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  74092. }
  74093. if( rc==SQLITE_OK ){
  74094. rc = rc2;
  74095. }
  74096. }
  74097. }
  74098. db->nStatement--;
  74099. p->iStatement = 0;
  74100. if( rc==SQLITE_OK ){
  74101. if( eOp==SAVEPOINT_ROLLBACK ){
  74102. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  74103. }
  74104. if( rc==SQLITE_OK ){
  74105. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  74106. }
  74107. }
  74108. /* If the statement transaction is being rolled back, also restore the
  74109. ** database handles deferred constraint counter to the value it had when
  74110. ** the statement transaction was opened. */
  74111. if( eOp==SAVEPOINT_ROLLBACK ){
  74112. db->nDeferredCons = p->nStmtDefCons;
  74113. db->nDeferredImmCons = p->nStmtDefImmCons;
  74114. }
  74115. return rc;
  74116. }
  74117. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  74118. if( p->db->nStatement && p->iStatement ){
  74119. return vdbeCloseStatement(p, eOp);
  74120. }
  74121. return SQLITE_OK;
  74122. }
  74123. /*
  74124. ** This function is called when a transaction opened by the database
  74125. ** handle associated with the VM passed as an argument is about to be
  74126. ** committed. If there are outstanding deferred foreign key constraint
  74127. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  74128. **
  74129. ** If there are outstanding FK violations and this function returns
  74130. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  74131. ** and write an error message to it. Then return SQLITE_ERROR.
  74132. */
  74133. #ifndef SQLITE_OMIT_FOREIGN_KEY
  74134. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  74135. sqlite3 *db = p->db;
  74136. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  74137. || (!deferred && p->nFkConstraint>0)
  74138. ){
  74139. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  74140. p->errorAction = OE_Abort;
  74141. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  74142. return SQLITE_ERROR;
  74143. }
  74144. return SQLITE_OK;
  74145. }
  74146. #endif
  74147. /*
  74148. ** This routine is called the when a VDBE tries to halt. If the VDBE
  74149. ** has made changes and is in autocommit mode, then commit those
  74150. ** changes. If a rollback is needed, then do the rollback.
  74151. **
  74152. ** This routine is the only way to move the state of a VM from
  74153. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  74154. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  74155. **
  74156. ** Return an error code. If the commit could not complete because of
  74157. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  74158. ** means the close did not happen and needs to be repeated.
  74159. */
  74160. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  74161. int rc; /* Used to store transient return codes */
  74162. sqlite3 *db = p->db;
  74163. /* This function contains the logic that determines if a statement or
  74164. ** transaction will be committed or rolled back as a result of the
  74165. ** execution of this virtual machine.
  74166. **
  74167. ** If any of the following errors occur:
  74168. **
  74169. ** SQLITE_NOMEM
  74170. ** SQLITE_IOERR
  74171. ** SQLITE_FULL
  74172. ** SQLITE_INTERRUPT
  74173. **
  74174. ** Then the internal cache might have been left in an inconsistent
  74175. ** state. We need to rollback the statement transaction, if there is
  74176. ** one, or the complete transaction if there is no statement transaction.
  74177. */
  74178. if( p->magic!=VDBE_MAGIC_RUN ){
  74179. return SQLITE_OK;
  74180. }
  74181. if( db->mallocFailed ){
  74182. p->rc = SQLITE_NOMEM_BKPT;
  74183. }
  74184. closeAllCursors(p);
  74185. checkActiveVdbeCnt(db);
  74186. /* No commit or rollback needed if the program never started or if the
  74187. ** SQL statement does not read or write a database file. */
  74188. if( p->pc>=0 && p->bIsReader ){
  74189. int mrc; /* Primary error code from p->rc */
  74190. int eStatementOp = 0;
  74191. int isSpecialError; /* Set to true if a 'special' error */
  74192. /* Lock all btrees used by the statement */
  74193. sqlite3VdbeEnter(p);
  74194. /* Check for one of the special errors */
  74195. mrc = p->rc & 0xff;
  74196. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  74197. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  74198. if( isSpecialError ){
  74199. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  74200. ** no rollback is necessary. Otherwise, at least a savepoint
  74201. ** transaction must be rolled back to restore the database to a
  74202. ** consistent state.
  74203. **
  74204. ** Even if the statement is read-only, it is important to perform
  74205. ** a statement or transaction rollback operation. If the error
  74206. ** occurred while writing to the journal, sub-journal or database
  74207. ** file as part of an effort to free up cache space (see function
  74208. ** pagerStress() in pager.c), the rollback is required to restore
  74209. ** the pager to a consistent state.
  74210. */
  74211. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  74212. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  74213. eStatementOp = SAVEPOINT_ROLLBACK;
  74214. }else{
  74215. /* We are forced to roll back the active transaction. Before doing
  74216. ** so, abort any other statements this handle currently has active.
  74217. */
  74218. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  74219. sqlite3CloseSavepoints(db);
  74220. db->autoCommit = 1;
  74221. p->nChange = 0;
  74222. }
  74223. }
  74224. }
  74225. /* Check for immediate foreign key violations. */
  74226. if( p->rc==SQLITE_OK ){
  74227. sqlite3VdbeCheckFk(p, 0);
  74228. }
  74229. /* If the auto-commit flag is set and this is the only active writer
  74230. ** VM, then we do either a commit or rollback of the current transaction.
  74231. **
  74232. ** Note: This block also runs if one of the special errors handled
  74233. ** above has occurred.
  74234. */
  74235. if( !sqlite3VtabInSync(db)
  74236. && db->autoCommit
  74237. && db->nVdbeWrite==(p->readOnly==0)
  74238. ){
  74239. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  74240. rc = sqlite3VdbeCheckFk(p, 1);
  74241. if( rc!=SQLITE_OK ){
  74242. if( NEVER(p->readOnly) ){
  74243. sqlite3VdbeLeave(p);
  74244. return SQLITE_ERROR;
  74245. }
  74246. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  74247. }else{
  74248. /* The auto-commit flag is true, the vdbe program was successful
  74249. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  74250. ** key constraints to hold up the transaction. This means a commit
  74251. ** is required. */
  74252. rc = vdbeCommit(db, p);
  74253. }
  74254. if( rc==SQLITE_BUSY && p->readOnly ){
  74255. sqlite3VdbeLeave(p);
  74256. return SQLITE_BUSY;
  74257. }else if( rc!=SQLITE_OK ){
  74258. p->rc = rc;
  74259. sqlite3RollbackAll(db, SQLITE_OK);
  74260. p->nChange = 0;
  74261. }else{
  74262. db->nDeferredCons = 0;
  74263. db->nDeferredImmCons = 0;
  74264. db->flags &= ~(u64)SQLITE_DeferFKs;
  74265. sqlite3CommitInternalChanges(db);
  74266. }
  74267. }else{
  74268. sqlite3RollbackAll(db, SQLITE_OK);
  74269. p->nChange = 0;
  74270. }
  74271. db->nStatement = 0;
  74272. }else if( eStatementOp==0 ){
  74273. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  74274. eStatementOp = SAVEPOINT_RELEASE;
  74275. }else if( p->errorAction==OE_Abort ){
  74276. eStatementOp = SAVEPOINT_ROLLBACK;
  74277. }else{
  74278. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  74279. sqlite3CloseSavepoints(db);
  74280. db->autoCommit = 1;
  74281. p->nChange = 0;
  74282. }
  74283. }
  74284. /* If eStatementOp is non-zero, then a statement transaction needs to
  74285. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  74286. ** do so. If this operation returns an error, and the current statement
  74287. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  74288. ** current statement error code.
  74289. */
  74290. if( eStatementOp ){
  74291. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  74292. if( rc ){
  74293. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  74294. p->rc = rc;
  74295. sqlite3DbFree(db, p->zErrMsg);
  74296. p->zErrMsg = 0;
  74297. }
  74298. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  74299. sqlite3CloseSavepoints(db);
  74300. db->autoCommit = 1;
  74301. p->nChange = 0;
  74302. }
  74303. }
  74304. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  74305. ** has been rolled back, update the database connection change-counter.
  74306. */
  74307. if( p->changeCntOn ){
  74308. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  74309. sqlite3VdbeSetChanges(db, p->nChange);
  74310. }else{
  74311. sqlite3VdbeSetChanges(db, 0);
  74312. }
  74313. p->nChange = 0;
  74314. }
  74315. /* Release the locks */
  74316. sqlite3VdbeLeave(p);
  74317. }
  74318. /* We have successfully halted and closed the VM. Record this fact. */
  74319. if( p->pc>=0 ){
  74320. db->nVdbeActive--;
  74321. if( !p->readOnly ) db->nVdbeWrite--;
  74322. if( p->bIsReader ) db->nVdbeRead--;
  74323. assert( db->nVdbeActive>=db->nVdbeRead );
  74324. assert( db->nVdbeRead>=db->nVdbeWrite );
  74325. assert( db->nVdbeWrite>=0 );
  74326. }
  74327. p->magic = VDBE_MAGIC_HALT;
  74328. checkActiveVdbeCnt(db);
  74329. if( db->mallocFailed ){
  74330. p->rc = SQLITE_NOMEM_BKPT;
  74331. }
  74332. /* If the auto-commit flag is set to true, then any locks that were held
  74333. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  74334. ** to invoke any required unlock-notify callbacks.
  74335. */
  74336. if( db->autoCommit ){
  74337. sqlite3ConnectionUnlocked(db);
  74338. }
  74339. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  74340. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  74341. }
  74342. /*
  74343. ** Each VDBE holds the result of the most recent sqlite3_step() call
  74344. ** in p->rc. This routine sets that result back to SQLITE_OK.
  74345. */
  74346. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  74347. p->rc = SQLITE_OK;
  74348. }
  74349. /*
  74350. ** Copy the error code and error message belonging to the VDBE passed
  74351. ** as the first argument to its database handle (so that they will be
  74352. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  74353. **
  74354. ** This function does not clear the VDBE error code or message, just
  74355. ** copies them to the database handle.
  74356. */
  74357. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  74358. sqlite3 *db = p->db;
  74359. int rc = p->rc;
  74360. if( p->zErrMsg ){
  74361. db->bBenignMalloc++;
  74362. sqlite3BeginBenignMalloc();
  74363. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  74364. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  74365. sqlite3EndBenignMalloc();
  74366. db->bBenignMalloc--;
  74367. }else if( db->pErr ){
  74368. sqlite3ValueSetNull(db->pErr);
  74369. }
  74370. db->errCode = rc;
  74371. return rc;
  74372. }
  74373. #ifdef SQLITE_ENABLE_SQLLOG
  74374. /*
  74375. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  74376. ** invoke it.
  74377. */
  74378. static void vdbeInvokeSqllog(Vdbe *v){
  74379. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  74380. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  74381. assert( v->db->init.busy==0 );
  74382. if( zExpanded ){
  74383. sqlite3GlobalConfig.xSqllog(
  74384. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  74385. );
  74386. sqlite3DbFree(v->db, zExpanded);
  74387. }
  74388. }
  74389. }
  74390. #else
  74391. # define vdbeInvokeSqllog(x)
  74392. #endif
  74393. /*
  74394. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  74395. ** Write any error messages into *pzErrMsg. Return the result code.
  74396. **
  74397. ** After this routine is run, the VDBE should be ready to be executed
  74398. ** again.
  74399. **
  74400. ** To look at it another way, this routine resets the state of the
  74401. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  74402. ** VDBE_MAGIC_INIT.
  74403. */
  74404. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  74405. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  74406. int i;
  74407. #endif
  74408. sqlite3 *db;
  74409. db = p->db;
  74410. /* If the VM did not run to completion or if it encountered an
  74411. ** error, then it might not have been halted properly. So halt
  74412. ** it now.
  74413. */
  74414. sqlite3VdbeHalt(p);
  74415. /* If the VDBE has been run even partially, then transfer the error code
  74416. ** and error message from the VDBE into the main database structure. But
  74417. ** if the VDBE has just been set to run but has not actually executed any
  74418. ** instructions yet, leave the main database error information unchanged.
  74419. */
  74420. if( p->pc>=0 ){
  74421. vdbeInvokeSqllog(p);
  74422. sqlite3VdbeTransferError(p);
  74423. if( p->runOnlyOnce ) p->expired = 1;
  74424. }else if( p->rc && p->expired ){
  74425. /* The expired flag was set on the VDBE before the first call
  74426. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  74427. ** called), set the database error in this case as well.
  74428. */
  74429. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  74430. }
  74431. /* Reset register contents and reclaim error message memory.
  74432. */
  74433. #ifdef SQLITE_DEBUG
  74434. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  74435. ** Vdbe.aMem[] arrays have already been cleaned up. */
  74436. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  74437. if( p->aMem ){
  74438. for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  74439. }
  74440. #endif
  74441. sqlite3DbFree(db, p->zErrMsg);
  74442. p->zErrMsg = 0;
  74443. p->pResultSet = 0;
  74444. #ifdef SQLITE_DEBUG
  74445. p->nWrite = 0;
  74446. #endif
  74447. /* Save profiling information from this VDBE run.
  74448. */
  74449. #ifdef VDBE_PROFILE
  74450. {
  74451. FILE *out = fopen("vdbe_profile.out", "a");
  74452. if( out ){
  74453. fprintf(out, "---- ");
  74454. for(i=0; i<p->nOp; i++){
  74455. fprintf(out, "%02x", p->aOp[i].opcode);
  74456. }
  74457. fprintf(out, "\n");
  74458. if( p->zSql ){
  74459. char c, pc = 0;
  74460. fprintf(out, "-- ");
  74461. for(i=0; (c = p->zSql[i])!=0; i++){
  74462. if( pc=='\n' ) fprintf(out, "-- ");
  74463. putc(c, out);
  74464. pc = c;
  74465. }
  74466. if( pc!='\n' ) fprintf(out, "\n");
  74467. }
  74468. for(i=0; i<p->nOp; i++){
  74469. char zHdr[100];
  74470. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  74471. p->aOp[i].cnt,
  74472. p->aOp[i].cycles,
  74473. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  74474. );
  74475. fprintf(out, "%s", zHdr);
  74476. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  74477. }
  74478. fclose(out);
  74479. }
  74480. }
  74481. #endif
  74482. p->magic = VDBE_MAGIC_RESET;
  74483. return p->rc & db->errMask;
  74484. }
  74485. /*
  74486. ** Clean up and delete a VDBE after execution. Return an integer which is
  74487. ** the result code. Write any error message text into *pzErrMsg.
  74488. */
  74489. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  74490. int rc = SQLITE_OK;
  74491. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  74492. rc = sqlite3VdbeReset(p);
  74493. assert( (rc & p->db->errMask)==rc );
  74494. }
  74495. sqlite3VdbeDelete(p);
  74496. return rc;
  74497. }
  74498. /*
  74499. ** If parameter iOp is less than zero, then invoke the destructor for
  74500. ** all auxiliary data pointers currently cached by the VM passed as
  74501. ** the first argument.
  74502. **
  74503. ** Or, if iOp is greater than or equal to zero, then the destructor is
  74504. ** only invoked for those auxiliary data pointers created by the user
  74505. ** function invoked by the OP_Function opcode at instruction iOp of
  74506. ** VM pVdbe, and only then if:
  74507. **
  74508. ** * the associated function parameter is the 32nd or later (counting
  74509. ** from left to right), or
  74510. **
  74511. ** * the corresponding bit in argument mask is clear (where the first
  74512. ** function parameter corresponds to bit 0 etc.).
  74513. */
  74514. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
  74515. while( *pp ){
  74516. AuxData *pAux = *pp;
  74517. if( (iOp<0)
  74518. || (pAux->iAuxOp==iOp
  74519. && pAux->iAuxArg>=0
  74520. && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
  74521. ){
  74522. testcase( pAux->iAuxArg==31 );
  74523. if( pAux->xDeleteAux ){
  74524. pAux->xDeleteAux(pAux->pAux);
  74525. }
  74526. *pp = pAux->pNextAux;
  74527. sqlite3DbFree(db, pAux);
  74528. }else{
  74529. pp= &pAux->pNextAux;
  74530. }
  74531. }
  74532. }
  74533. /*
  74534. ** Free all memory associated with the Vdbe passed as the second argument,
  74535. ** except for object itself, which is preserved.
  74536. **
  74537. ** The difference between this function and sqlite3VdbeDelete() is that
  74538. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  74539. ** the database connection and frees the object itself.
  74540. */
  74541. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  74542. SubProgram *pSub, *pNext;
  74543. assert( p->db==0 || p->db==db );
  74544. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  74545. for(pSub=p->pProgram; pSub; pSub=pNext){
  74546. pNext = pSub->pNext;
  74547. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  74548. sqlite3DbFree(db, pSub);
  74549. }
  74550. if( p->magic!=VDBE_MAGIC_INIT ){
  74551. releaseMemArray(p->aVar, p->nVar);
  74552. sqlite3DbFree(db, p->pVList);
  74553. sqlite3DbFree(db, p->pFree);
  74554. }
  74555. vdbeFreeOpArray(db, p->aOp, p->nOp);
  74556. sqlite3DbFree(db, p->aColName);
  74557. sqlite3DbFree(db, p->zSql);
  74558. #ifdef SQLITE_ENABLE_NORMALIZE
  74559. sqlite3DbFree(db, p->zNormSql);
  74560. {
  74561. DblquoteStr *pThis, *pNext;
  74562. for(pThis=p->pDblStr; pThis; pThis=pNext){
  74563. pNext = pThis->pNextStr;
  74564. sqlite3DbFree(db, pThis);
  74565. }
  74566. }
  74567. #endif
  74568. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  74569. {
  74570. int i;
  74571. for(i=0; i<p->nScan; i++){
  74572. sqlite3DbFree(db, p->aScan[i].zName);
  74573. }
  74574. sqlite3DbFree(db, p->aScan);
  74575. }
  74576. #endif
  74577. }
  74578. /*
  74579. ** Delete an entire VDBE.
  74580. */
  74581. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  74582. sqlite3 *db;
  74583. assert( p!=0 );
  74584. db = p->db;
  74585. assert( sqlite3_mutex_held(db->mutex) );
  74586. sqlite3VdbeClearObject(db, p);
  74587. if( p->pPrev ){
  74588. p->pPrev->pNext = p->pNext;
  74589. }else{
  74590. assert( db->pVdbe==p );
  74591. db->pVdbe = p->pNext;
  74592. }
  74593. if( p->pNext ){
  74594. p->pNext->pPrev = p->pPrev;
  74595. }
  74596. p->magic = VDBE_MAGIC_DEAD;
  74597. p->db = 0;
  74598. sqlite3DbFreeNN(db, p);
  74599. }
  74600. /*
  74601. ** The cursor "p" has a pending seek operation that has not yet been
  74602. ** carried out. Seek the cursor now. If an error occurs, return
  74603. ** the appropriate error code.
  74604. */
  74605. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  74606. int res, rc;
  74607. #ifdef SQLITE_TEST
  74608. extern int sqlite3_search_count;
  74609. #endif
  74610. assert( p->deferredMoveto );
  74611. assert( p->isTable );
  74612. assert( p->eCurType==CURTYPE_BTREE );
  74613. rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
  74614. if( rc ) return rc;
  74615. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  74616. #ifdef SQLITE_TEST
  74617. sqlite3_search_count++;
  74618. #endif
  74619. p->deferredMoveto = 0;
  74620. p->cacheStatus = CACHE_STALE;
  74621. return SQLITE_OK;
  74622. }
  74623. /*
  74624. ** Something has moved cursor "p" out of place. Maybe the row it was
  74625. ** pointed to was deleted out from under it. Or maybe the btree was
  74626. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  74627. ** is supposed to be pointing. If the row was deleted out from under the
  74628. ** cursor, set the cursor to point to a NULL row.
  74629. */
  74630. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  74631. int isDifferentRow, rc;
  74632. assert( p->eCurType==CURTYPE_BTREE );
  74633. assert( p->uc.pCursor!=0 );
  74634. assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
  74635. rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
  74636. p->cacheStatus = CACHE_STALE;
  74637. if( isDifferentRow ) p->nullRow = 1;
  74638. return rc;
  74639. }
  74640. /*
  74641. ** Check to ensure that the cursor is valid. Restore the cursor
  74642. ** if need be. Return any I/O error from the restore operation.
  74643. */
  74644. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  74645. assert( p->eCurType==CURTYPE_BTREE );
  74646. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  74647. return handleMovedCursor(p);
  74648. }
  74649. return SQLITE_OK;
  74650. }
  74651. /*
  74652. ** Make sure the cursor p is ready to read or write the row to which it
  74653. ** was last positioned. Return an error code if an OOM fault or I/O error
  74654. ** prevents us from positioning the cursor to its correct position.
  74655. **
  74656. ** If a MoveTo operation is pending on the given cursor, then do that
  74657. ** MoveTo now. If no move is pending, check to see if the row has been
  74658. ** deleted out from under the cursor and if it has, mark the row as
  74659. ** a NULL row.
  74660. **
  74661. ** If the cursor is already pointing to the correct row and that row has
  74662. ** not been deleted out from under the cursor, then this routine is a no-op.
  74663. */
  74664. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
  74665. VdbeCursor *p = *pp;
  74666. assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
  74667. if( p->deferredMoveto ){
  74668. int iMap;
  74669. if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
  74670. *pp = p->pAltCursor;
  74671. *piCol = iMap - 1;
  74672. return SQLITE_OK;
  74673. }
  74674. return handleDeferredMoveto(p);
  74675. }
  74676. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  74677. return handleMovedCursor(p);
  74678. }
  74679. return SQLITE_OK;
  74680. }
  74681. /*
  74682. ** The following functions:
  74683. **
  74684. ** sqlite3VdbeSerialType()
  74685. ** sqlite3VdbeSerialTypeLen()
  74686. ** sqlite3VdbeSerialLen()
  74687. ** sqlite3VdbeSerialPut()
  74688. ** sqlite3VdbeSerialGet()
  74689. **
  74690. ** encapsulate the code that serializes values for storage in SQLite
  74691. ** data and index records. Each serialized value consists of a
  74692. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  74693. ** integer, stored as a varint.
  74694. **
  74695. ** In an SQLite index record, the serial type is stored directly before
  74696. ** the blob of data that it corresponds to. In a table record, all serial
  74697. ** types are stored at the start of the record, and the blobs of data at
  74698. ** the end. Hence these functions allow the caller to handle the
  74699. ** serial-type and data blob separately.
  74700. **
  74701. ** The following table describes the various storage classes for data:
  74702. **
  74703. ** serial type bytes of data type
  74704. ** -------------- --------------- ---------------
  74705. ** 0 0 NULL
  74706. ** 1 1 signed integer
  74707. ** 2 2 signed integer
  74708. ** 3 3 signed integer
  74709. ** 4 4 signed integer
  74710. ** 5 6 signed integer
  74711. ** 6 8 signed integer
  74712. ** 7 8 IEEE float
  74713. ** 8 0 Integer constant 0
  74714. ** 9 0 Integer constant 1
  74715. ** 10,11 reserved for expansion
  74716. ** N>=12 and even (N-12)/2 BLOB
  74717. ** N>=13 and odd (N-13)/2 text
  74718. **
  74719. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  74720. ** of SQLite will not understand those serial types.
  74721. */
  74722. /*
  74723. ** Return the serial-type for the value stored in pMem.
  74724. */
  74725. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
  74726. int flags = pMem->flags;
  74727. u32 n;
  74728. assert( pLen!=0 );
  74729. if( flags&MEM_Null ){
  74730. *pLen = 0;
  74731. return 0;
  74732. }
  74733. if( flags&MEM_Int ){
  74734. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  74735. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  74736. i64 i = pMem->u.i;
  74737. u64 u;
  74738. if( i<0 ){
  74739. u = ~i;
  74740. }else{
  74741. u = i;
  74742. }
  74743. if( u<=127 ){
  74744. if( (i&1)==i && file_format>=4 ){
  74745. *pLen = 0;
  74746. return 8+(u32)u;
  74747. }else{
  74748. *pLen = 1;
  74749. return 1;
  74750. }
  74751. }
  74752. if( u<=32767 ){ *pLen = 2; return 2; }
  74753. if( u<=8388607 ){ *pLen = 3; return 3; }
  74754. if( u<=2147483647 ){ *pLen = 4; return 4; }
  74755. if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
  74756. *pLen = 8;
  74757. return 6;
  74758. }
  74759. if( flags&MEM_Real ){
  74760. *pLen = 8;
  74761. return 7;
  74762. }
  74763. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  74764. assert( pMem->n>=0 );
  74765. n = (u32)pMem->n;
  74766. if( flags & MEM_Zero ){
  74767. n += pMem->u.nZero;
  74768. }
  74769. *pLen = n;
  74770. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  74771. }
  74772. /*
  74773. ** The sizes for serial types less than 128
  74774. */
  74775. static const u8 sqlite3SmallTypeSizes[] = {
  74776. /* 0 1 2 3 4 5 6 7 8 9 */
  74777. /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
  74778. /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  74779. /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  74780. /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  74781. /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
  74782. /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
  74783. /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
  74784. /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
  74785. /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
  74786. /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
  74787. /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
  74788. /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
  74789. /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
  74790. };
  74791. /*
  74792. ** Return the length of the data corresponding to the supplied serial-type.
  74793. */
  74794. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  74795. if( serial_type>=128 ){
  74796. return (serial_type-12)/2;
  74797. }else{
  74798. assert( serial_type<12
  74799. || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
  74800. return sqlite3SmallTypeSizes[serial_type];
  74801. }
  74802. }
  74803. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
  74804. assert( serial_type<128 );
  74805. return sqlite3SmallTypeSizes[serial_type];
  74806. }
  74807. /*
  74808. ** If we are on an architecture with mixed-endian floating
  74809. ** points (ex: ARM7) then swap the lower 4 bytes with the
  74810. ** upper 4 bytes. Return the result.
  74811. **
  74812. ** For most architectures, this is a no-op.
  74813. **
  74814. ** (later): It is reported to me that the mixed-endian problem
  74815. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  74816. ** that early versions of GCC stored the two words of a 64-bit
  74817. ** float in the wrong order. And that error has been propagated
  74818. ** ever since. The blame is not necessarily with GCC, though.
  74819. ** GCC might have just copying the problem from a prior compiler.
  74820. ** I am also told that newer versions of GCC that follow a different
  74821. ** ABI get the byte order right.
  74822. **
  74823. ** Developers using SQLite on an ARM7 should compile and run their
  74824. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  74825. ** enabled, some asserts below will ensure that the byte order of
  74826. ** floating point values is correct.
  74827. **
  74828. ** (2007-08-30) Frank van Vugt has studied this problem closely
  74829. ** and has send his findings to the SQLite developers. Frank
  74830. ** writes that some Linux kernels offer floating point hardware
  74831. ** emulation that uses only 32-bit mantissas instead of a full
  74832. ** 48-bits as required by the IEEE standard. (This is the
  74833. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  74834. ** byte swapping becomes very complicated. To avoid problems,
  74835. ** the necessary byte swapping is carried out using a 64-bit integer
  74836. ** rather than a 64-bit float. Frank assures us that the code here
  74837. ** works for him. We, the developers, have no way to independently
  74838. ** verify this, but Frank seems to know what he is talking about
  74839. ** so we trust him.
  74840. */
  74841. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  74842. static u64 floatSwap(u64 in){
  74843. union {
  74844. u64 r;
  74845. u32 i[2];
  74846. } u;
  74847. u32 t;
  74848. u.r = in;
  74849. t = u.i[0];
  74850. u.i[0] = u.i[1];
  74851. u.i[1] = t;
  74852. return u.r;
  74853. }
  74854. # define swapMixedEndianFloat(X) X = floatSwap(X)
  74855. #else
  74856. # define swapMixedEndianFloat(X)
  74857. #endif
  74858. /*
  74859. ** Write the serialized data blob for the value stored in pMem into
  74860. ** buf. It is assumed that the caller has allocated sufficient space.
  74861. ** Return the number of bytes written.
  74862. **
  74863. ** nBuf is the amount of space left in buf[]. The caller is responsible
  74864. ** for allocating enough space to buf[] to hold the entire field, exclusive
  74865. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  74866. **
  74867. ** Return the number of bytes actually written into buf[]. The number
  74868. ** of bytes in the zero-filled tail is included in the return value only
  74869. ** if those bytes were zeroed in buf[].
  74870. */
  74871. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  74872. u32 len;
  74873. /* Integer and Real */
  74874. if( serial_type<=7 && serial_type>0 ){
  74875. u64 v;
  74876. u32 i;
  74877. if( serial_type==7 ){
  74878. assert( sizeof(v)==sizeof(pMem->u.r) );
  74879. memcpy(&v, &pMem->u.r, sizeof(v));
  74880. swapMixedEndianFloat(v);
  74881. }else{
  74882. v = pMem->u.i;
  74883. }
  74884. len = i = sqlite3SmallTypeSizes[serial_type];
  74885. assert( i>0 );
  74886. do{
  74887. buf[--i] = (u8)(v&0xFF);
  74888. v >>= 8;
  74889. }while( i );
  74890. return len;
  74891. }
  74892. /* String or blob */
  74893. if( serial_type>=12 ){
  74894. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  74895. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  74896. len = pMem->n;
  74897. if( len>0 ) memcpy(buf, pMem->z, len);
  74898. return len;
  74899. }
  74900. /* NULL or constants 0 or 1 */
  74901. return 0;
  74902. }
  74903. /* Input "x" is a sequence of unsigned characters that represent a
  74904. ** big-endian integer. Return the equivalent native integer
  74905. */
  74906. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  74907. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  74908. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  74909. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  74910. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  74911. /*
  74912. ** Deserialize the data blob pointed to by buf as serial type serial_type
  74913. ** and store the result in pMem. Return the number of bytes read.
  74914. **
  74915. ** This function is implemented as two separate routines for performance.
  74916. ** The few cases that require local variables are broken out into a separate
  74917. ** routine so that in most cases the overhead of moving the stack pointer
  74918. ** is avoided.
  74919. */
  74920. static u32 SQLITE_NOINLINE serialGet(
  74921. const unsigned char *buf, /* Buffer to deserialize from */
  74922. u32 serial_type, /* Serial type to deserialize */
  74923. Mem *pMem /* Memory cell to write value into */
  74924. ){
  74925. u64 x = FOUR_BYTE_UINT(buf);
  74926. u32 y = FOUR_BYTE_UINT(buf+4);
  74927. x = (x<<32) + y;
  74928. if( serial_type==6 ){
  74929. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  74930. ** twos-complement integer. */
  74931. pMem->u.i = *(i64*)&x;
  74932. pMem->flags = MEM_Int;
  74933. testcase( pMem->u.i<0 );
  74934. }else{
  74935. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  74936. ** floating point number. */
  74937. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  74938. /* Verify that integers and floating point values use the same
  74939. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  74940. ** defined that 64-bit floating point values really are mixed
  74941. ** endian.
  74942. */
  74943. static const u64 t1 = ((u64)0x3ff00000)<<32;
  74944. static const double r1 = 1.0;
  74945. u64 t2 = t1;
  74946. swapMixedEndianFloat(t2);
  74947. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  74948. #endif
  74949. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  74950. swapMixedEndianFloat(x);
  74951. memcpy(&pMem->u.r, &x, sizeof(x));
  74952. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  74953. }
  74954. return 8;
  74955. }
  74956. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  74957. const unsigned char *buf, /* Buffer to deserialize from */
  74958. u32 serial_type, /* Serial type to deserialize */
  74959. Mem *pMem /* Memory cell to write value into */
  74960. ){
  74961. switch( serial_type ){
  74962. case 10: { /* Internal use only: NULL with virtual table
  74963. ** UPDATE no-change flag set */
  74964. pMem->flags = MEM_Null|MEM_Zero;
  74965. pMem->n = 0;
  74966. pMem->u.nZero = 0;
  74967. break;
  74968. }
  74969. case 11: /* Reserved for future use */
  74970. case 0: { /* Null */
  74971. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  74972. pMem->flags = MEM_Null;
  74973. break;
  74974. }
  74975. case 1: {
  74976. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  74977. ** integer. */
  74978. pMem->u.i = ONE_BYTE_INT(buf);
  74979. pMem->flags = MEM_Int;
  74980. testcase( pMem->u.i<0 );
  74981. return 1;
  74982. }
  74983. case 2: { /* 2-byte signed integer */
  74984. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  74985. ** twos-complement integer. */
  74986. pMem->u.i = TWO_BYTE_INT(buf);
  74987. pMem->flags = MEM_Int;
  74988. testcase( pMem->u.i<0 );
  74989. return 2;
  74990. }
  74991. case 3: { /* 3-byte signed integer */
  74992. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  74993. ** twos-complement integer. */
  74994. pMem->u.i = THREE_BYTE_INT(buf);
  74995. pMem->flags = MEM_Int;
  74996. testcase( pMem->u.i<0 );
  74997. return 3;
  74998. }
  74999. case 4: { /* 4-byte signed integer */
  75000. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  75001. ** twos-complement integer. */
  75002. pMem->u.i = FOUR_BYTE_INT(buf);
  75003. #ifdef __HP_cc
  75004. /* Work around a sign-extension bug in the HP compiler for HP/UX */
  75005. if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
  75006. #endif
  75007. pMem->flags = MEM_Int;
  75008. testcase( pMem->u.i<0 );
  75009. return 4;
  75010. }
  75011. case 5: { /* 6-byte signed integer */
  75012. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  75013. ** twos-complement integer. */
  75014. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  75015. pMem->flags = MEM_Int;
  75016. testcase( pMem->u.i<0 );
  75017. return 6;
  75018. }
  75019. case 6: /* 8-byte signed integer */
  75020. case 7: { /* IEEE floating point */
  75021. /* These use local variables, so do them in a separate routine
  75022. ** to avoid having to move the frame pointer in the common case */
  75023. return serialGet(buf,serial_type,pMem);
  75024. }
  75025. case 8: /* Integer 0 */
  75026. case 9: { /* Integer 1 */
  75027. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  75028. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  75029. pMem->u.i = serial_type-8;
  75030. pMem->flags = MEM_Int;
  75031. return 0;
  75032. }
  75033. default: {
  75034. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  75035. ** length.
  75036. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  75037. ** (N-13)/2 bytes in length. */
  75038. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  75039. pMem->z = (char *)buf;
  75040. pMem->n = (serial_type-12)/2;
  75041. pMem->flags = aFlag[serial_type&1];
  75042. return pMem->n;
  75043. }
  75044. }
  75045. return 0;
  75046. }
  75047. /*
  75048. ** This routine is used to allocate sufficient space for an UnpackedRecord
  75049. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  75050. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  75051. **
  75052. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  75053. ** the unaligned buffer passed via the second and third arguments (presumably
  75054. ** stack space). If the former, then *ppFree is set to a pointer that should
  75055. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  75056. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  75057. ** before returning.
  75058. **
  75059. ** If an OOM error occurs, NULL is returned.
  75060. */
  75061. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  75062. KeyInfo *pKeyInfo /* Description of the record */
  75063. ){
  75064. UnpackedRecord *p; /* Unpacked record to return */
  75065. int nByte; /* Number of bytes required for *p */
  75066. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
  75067. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  75068. if( !p ) return 0;
  75069. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  75070. assert( pKeyInfo->aSortOrder!=0 );
  75071. p->pKeyInfo = pKeyInfo;
  75072. p->nField = pKeyInfo->nKeyField + 1;
  75073. return p;
  75074. }
  75075. /*
  75076. ** Given the nKey-byte encoding of a record in pKey[], populate the
  75077. ** UnpackedRecord structure indicated by the fourth argument with the
  75078. ** contents of the decoded record.
  75079. */
  75080. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  75081. KeyInfo *pKeyInfo, /* Information about the record format */
  75082. int nKey, /* Size of the binary record */
  75083. const void *pKey, /* The binary record */
  75084. UnpackedRecord *p /* Populate this structure before returning. */
  75085. ){
  75086. const unsigned char *aKey = (const unsigned char *)pKey;
  75087. u32 d;
  75088. u32 idx; /* Offset in aKey[] to read from */
  75089. u16 u; /* Unsigned loop counter */
  75090. u32 szHdr;
  75091. Mem *pMem = p->aMem;
  75092. p->default_rc = 0;
  75093. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  75094. idx = getVarint32(aKey, szHdr);
  75095. d = szHdr;
  75096. u = 0;
  75097. while( idx<szHdr && d<=(u32)nKey ){
  75098. u32 serial_type;
  75099. idx += getVarint32(&aKey[idx], serial_type);
  75100. pMem->enc = pKeyInfo->enc;
  75101. pMem->db = pKeyInfo->db;
  75102. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  75103. pMem->szMalloc = 0;
  75104. pMem->z = 0;
  75105. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  75106. pMem++;
  75107. if( (++u)>=p->nField ) break;
  75108. }
  75109. if( d>(u32)nKey && u ){
  75110. assert( CORRUPT_DB );
  75111. /* In a corrupt record entry, the last pMem might have been set up using
  75112. ** uninitialized memory. Overwrite its value with NULL, to prevent
  75113. ** warnings from MSAN. */
  75114. sqlite3VdbeMemSetNull(pMem-1);
  75115. }
  75116. assert( u<=pKeyInfo->nKeyField + 1 );
  75117. p->nField = u;
  75118. }
  75119. #ifdef SQLITE_DEBUG
  75120. /*
  75121. ** This function compares two index or table record keys in the same way
  75122. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  75123. ** this function deserializes and compares values using the
  75124. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  75125. ** in assert() statements to ensure that the optimized code in
  75126. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  75127. **
  75128. ** Return true if the result of comparison is equivalent to desiredResult.
  75129. ** Return false if there is a disagreement.
  75130. */
  75131. static int vdbeRecordCompareDebug(
  75132. int nKey1, const void *pKey1, /* Left key */
  75133. const UnpackedRecord *pPKey2, /* Right key */
  75134. int desiredResult /* Correct answer */
  75135. ){
  75136. u32 d1; /* Offset into aKey[] of next data element */
  75137. u32 idx1; /* Offset into aKey[] of next header element */
  75138. u32 szHdr1; /* Number of bytes in header */
  75139. int i = 0;
  75140. int rc = 0;
  75141. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  75142. KeyInfo *pKeyInfo;
  75143. Mem mem1;
  75144. pKeyInfo = pPKey2->pKeyInfo;
  75145. if( pKeyInfo->db==0 ) return 1;
  75146. mem1.enc = pKeyInfo->enc;
  75147. mem1.db = pKeyInfo->db;
  75148. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  75149. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  75150. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  75151. ** We could initialize it, as shown here, to silence those complaints.
  75152. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  75153. ** the unnecessary initialization has a measurable negative performance
  75154. ** impact, since this routine is a very high runner. And so, we choose
  75155. ** to ignore the compiler warnings and leave this variable uninitialized.
  75156. */
  75157. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  75158. idx1 = getVarint32(aKey1, szHdr1);
  75159. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  75160. d1 = szHdr1;
  75161. assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
  75162. assert( pKeyInfo->aSortOrder!=0 );
  75163. assert( pKeyInfo->nKeyField>0 );
  75164. assert( idx1<=szHdr1 || CORRUPT_DB );
  75165. do{
  75166. u32 serial_type1;
  75167. /* Read the serial types for the next element in each key. */
  75168. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  75169. /* Verify that there is enough key space remaining to avoid
  75170. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  75171. ** always be greater than or equal to the amount of required key space.
  75172. ** Use that approximation to avoid the more expensive call to
  75173. ** sqlite3VdbeSerialTypeLen() in the common case.
  75174. */
  75175. if( d1+(u64)serial_type1+2>(u64)nKey1
  75176. && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
  75177. ){
  75178. break;
  75179. }
  75180. /* Extract the values to be compared.
  75181. */
  75182. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  75183. /* Do the comparison
  75184. */
  75185. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
  75186. pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
  75187. if( rc!=0 ){
  75188. assert( mem1.szMalloc==0 ); /* See comment below */
  75189. if( pKeyInfo->aSortOrder[i] ){
  75190. rc = -rc; /* Invert the result for DESC sort order. */
  75191. }
  75192. goto debugCompareEnd;
  75193. }
  75194. i++;
  75195. }while( idx1<szHdr1 && i<pPKey2->nField );
  75196. /* No memory allocation is ever used on mem1. Prove this using
  75197. ** the following assert(). If the assert() fails, it indicates a
  75198. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  75199. */
  75200. assert( mem1.szMalloc==0 );
  75201. /* rc==0 here means that one of the keys ran out of fields and
  75202. ** all the fields up to that point were equal. Return the default_rc
  75203. ** value. */
  75204. rc = pPKey2->default_rc;
  75205. debugCompareEnd:
  75206. if( desiredResult==0 && rc==0 ) return 1;
  75207. if( desiredResult<0 && rc<0 ) return 1;
  75208. if( desiredResult>0 && rc>0 ) return 1;
  75209. if( CORRUPT_DB ) return 1;
  75210. if( pKeyInfo->db->mallocFailed ) return 1;
  75211. return 0;
  75212. }
  75213. #endif
  75214. #ifdef SQLITE_DEBUG
  75215. /*
  75216. ** Count the number of fields (a.k.a. columns) in the record given by
  75217. ** pKey,nKey. The verify that this count is less than or equal to the
  75218. ** limit given by pKeyInfo->nAllField.
  75219. **
  75220. ** If this constraint is not satisfied, it means that the high-speed
  75221. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  75222. ** not work correctly. If this assert() ever fires, it probably means
  75223. ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
  75224. ** incorrectly.
  75225. */
  75226. static void vdbeAssertFieldCountWithinLimits(
  75227. int nKey, const void *pKey, /* The record to verify */
  75228. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  75229. ){
  75230. int nField = 0;
  75231. u32 szHdr;
  75232. u32 idx;
  75233. u32 notUsed;
  75234. const unsigned char *aKey = (const unsigned char*)pKey;
  75235. if( CORRUPT_DB ) return;
  75236. idx = getVarint32(aKey, szHdr);
  75237. assert( nKey>=0 );
  75238. assert( szHdr<=(u32)nKey );
  75239. while( idx<szHdr ){
  75240. idx += getVarint32(aKey+idx, notUsed);
  75241. nField++;
  75242. }
  75243. assert( nField <= pKeyInfo->nAllField );
  75244. }
  75245. #else
  75246. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  75247. #endif
  75248. /*
  75249. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  75250. ** using the collation sequence pColl. As usual, return a negative , zero
  75251. ** or positive value if *pMem1 is less than, equal to or greater than
  75252. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  75253. */
  75254. static int vdbeCompareMemString(
  75255. const Mem *pMem1,
  75256. const Mem *pMem2,
  75257. const CollSeq *pColl,
  75258. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  75259. ){
  75260. if( pMem1->enc==pColl->enc ){
  75261. /* The strings are already in the correct encoding. Call the
  75262. ** comparison function directly */
  75263. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  75264. }else{
  75265. int rc;
  75266. const void *v1, *v2;
  75267. Mem c1;
  75268. Mem c2;
  75269. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  75270. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  75271. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  75272. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  75273. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  75274. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  75275. if( (v1==0 || v2==0) ){
  75276. if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
  75277. rc = 0;
  75278. }else{
  75279. rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
  75280. }
  75281. sqlite3VdbeMemRelease(&c1);
  75282. sqlite3VdbeMemRelease(&c2);
  75283. return rc;
  75284. }
  75285. }
  75286. /*
  75287. ** The input pBlob is guaranteed to be a Blob that is not marked
  75288. ** with MEM_Zero. Return true if it could be a zero-blob.
  75289. */
  75290. static int isAllZero(const char *z, int n){
  75291. int i;
  75292. for(i=0; i<n; i++){
  75293. if( z[i] ) return 0;
  75294. }
  75295. return 1;
  75296. }
  75297. /*
  75298. ** Compare two blobs. Return negative, zero, or positive if the first
  75299. ** is less than, equal to, or greater than the second, respectively.
  75300. ** If one blob is a prefix of the other, then the shorter is the lessor.
  75301. */
  75302. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  75303. int c;
  75304. int n1 = pB1->n;
  75305. int n2 = pB2->n;
  75306. /* It is possible to have a Blob value that has some non-zero content
  75307. ** followed by zero content. But that only comes up for Blobs formed
  75308. ** by the OP_MakeRecord opcode, and such Blobs never get passed into
  75309. ** sqlite3MemCompare(). */
  75310. assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
  75311. assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
  75312. if( (pB1->flags|pB2->flags) & MEM_Zero ){
  75313. if( pB1->flags & pB2->flags & MEM_Zero ){
  75314. return pB1->u.nZero - pB2->u.nZero;
  75315. }else if( pB1->flags & MEM_Zero ){
  75316. if( !isAllZero(pB2->z, pB2->n) ) return -1;
  75317. return pB1->u.nZero - n2;
  75318. }else{
  75319. if( !isAllZero(pB1->z, pB1->n) ) return +1;
  75320. return n1 - pB2->u.nZero;
  75321. }
  75322. }
  75323. c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
  75324. if( c ) return c;
  75325. return n1 - n2;
  75326. }
  75327. /*
  75328. ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
  75329. ** number. Return negative, zero, or positive if the first (i64) is less than,
  75330. ** equal to, or greater than the second (double).
  75331. */
  75332. static int sqlite3IntFloatCompare(i64 i, double r){
  75333. if( sizeof(LONGDOUBLE_TYPE)>8 ){
  75334. LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
  75335. if( x<r ) return -1;
  75336. if( x>r ) return +1;
  75337. return 0;
  75338. }else{
  75339. i64 y;
  75340. double s;
  75341. if( r<-9223372036854775808.0 ) return +1;
  75342. if( r>=9223372036854775808.0 ) return -1;
  75343. y = (i64)r;
  75344. if( i<y ) return -1;
  75345. if( i>y ) return +1;
  75346. s = (double)i;
  75347. if( s<r ) return -1;
  75348. if( s>r ) return +1;
  75349. return 0;
  75350. }
  75351. }
  75352. /*
  75353. ** Compare the values contained by the two memory cells, returning
  75354. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  75355. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  75356. ** and reals) sorted numerically, followed by text ordered by the collating
  75357. ** sequence pColl and finally blob's ordered by memcmp().
  75358. **
  75359. ** Two NULL values are considered equal by this function.
  75360. */
  75361. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  75362. int f1, f2;
  75363. int combined_flags;
  75364. f1 = pMem1->flags;
  75365. f2 = pMem2->flags;
  75366. combined_flags = f1|f2;
  75367. assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
  75368. /* If one value is NULL, it is less than the other. If both values
  75369. ** are NULL, return 0.
  75370. */
  75371. if( combined_flags&MEM_Null ){
  75372. return (f2&MEM_Null) - (f1&MEM_Null);
  75373. }
  75374. /* At least one of the two values is a number
  75375. */
  75376. if( combined_flags&(MEM_Int|MEM_Real) ){
  75377. if( (f1 & f2 & MEM_Int)!=0 ){
  75378. if( pMem1->u.i < pMem2->u.i ) return -1;
  75379. if( pMem1->u.i > pMem2->u.i ) return +1;
  75380. return 0;
  75381. }
  75382. if( (f1 & f2 & MEM_Real)!=0 ){
  75383. if( pMem1->u.r < pMem2->u.r ) return -1;
  75384. if( pMem1->u.r > pMem2->u.r ) return +1;
  75385. return 0;
  75386. }
  75387. if( (f1&MEM_Int)!=0 ){
  75388. if( (f2&MEM_Real)!=0 ){
  75389. return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
  75390. }else{
  75391. return -1;
  75392. }
  75393. }
  75394. if( (f1&MEM_Real)!=0 ){
  75395. if( (f2&MEM_Int)!=0 ){
  75396. return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
  75397. }else{
  75398. return -1;
  75399. }
  75400. }
  75401. return +1;
  75402. }
  75403. /* If one value is a string and the other is a blob, the string is less.
  75404. ** If both are strings, compare using the collating functions.
  75405. */
  75406. if( combined_flags&MEM_Str ){
  75407. if( (f1 & MEM_Str)==0 ){
  75408. return 1;
  75409. }
  75410. if( (f2 & MEM_Str)==0 ){
  75411. return -1;
  75412. }
  75413. assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
  75414. assert( pMem1->enc==SQLITE_UTF8 ||
  75415. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  75416. /* The collation sequence must be defined at this point, even if
  75417. ** the user deletes the collation sequence after the vdbe program is
  75418. ** compiled (this was not always the case).
  75419. */
  75420. assert( !pColl || pColl->xCmp );
  75421. if( pColl ){
  75422. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  75423. }
  75424. /* If a NULL pointer was passed as the collate function, fall through
  75425. ** to the blob case and use memcmp(). */
  75426. }
  75427. /* Both values must be blobs. Compare using memcmp(). */
  75428. return sqlite3BlobCompare(pMem1, pMem2);
  75429. }
  75430. /*
  75431. ** The first argument passed to this function is a serial-type that
  75432. ** corresponds to an integer - all values between 1 and 9 inclusive
  75433. ** except 7. The second points to a buffer containing an integer value
  75434. ** serialized according to serial_type. This function deserializes
  75435. ** and returns the value.
  75436. */
  75437. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  75438. u32 y;
  75439. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  75440. switch( serial_type ){
  75441. case 0:
  75442. case 1:
  75443. testcase( aKey[0]&0x80 );
  75444. return ONE_BYTE_INT(aKey);
  75445. case 2:
  75446. testcase( aKey[0]&0x80 );
  75447. return TWO_BYTE_INT(aKey);
  75448. case 3:
  75449. testcase( aKey[0]&0x80 );
  75450. return THREE_BYTE_INT(aKey);
  75451. case 4: {
  75452. testcase( aKey[0]&0x80 );
  75453. y = FOUR_BYTE_UINT(aKey);
  75454. return (i64)*(int*)&y;
  75455. }
  75456. case 5: {
  75457. testcase( aKey[0]&0x80 );
  75458. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  75459. }
  75460. case 6: {
  75461. u64 x = FOUR_BYTE_UINT(aKey);
  75462. testcase( aKey[0]&0x80 );
  75463. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  75464. return (i64)*(i64*)&x;
  75465. }
  75466. }
  75467. return (serial_type - 8);
  75468. }
  75469. /*
  75470. ** This function compares the two table rows or index records
  75471. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  75472. ** or positive integer if key1 is less than, equal to or
  75473. ** greater than key2. The {nKey1, pKey1} key must be a blob
  75474. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  75475. ** key must be a parsed key such as obtained from
  75476. ** sqlite3VdbeParseRecord.
  75477. **
  75478. ** If argument bSkip is non-zero, it is assumed that the caller has already
  75479. ** determined that the first fields of the keys are equal.
  75480. **
  75481. ** Key1 and Key2 do not have to contain the same number of fields. If all
  75482. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  75483. ** returned.
  75484. **
  75485. ** If database corruption is discovered, set pPKey2->errCode to
  75486. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  75487. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  75488. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  75489. */
  75490. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  75491. int nKey1, const void *pKey1, /* Left key */
  75492. UnpackedRecord *pPKey2, /* Right key */
  75493. int bSkip /* If true, skip the first field */
  75494. ){
  75495. u32 d1; /* Offset into aKey[] of next data element */
  75496. int i; /* Index of next field to compare */
  75497. u32 szHdr1; /* Size of record header in bytes */
  75498. u32 idx1; /* Offset of first type in header */
  75499. int rc = 0; /* Return value */
  75500. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  75501. KeyInfo *pKeyInfo;
  75502. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  75503. Mem mem1;
  75504. /* If bSkip is true, then the caller has already determined that the first
  75505. ** two elements in the keys are equal. Fix the various stack variables so
  75506. ** that this routine begins comparing at the second field. */
  75507. if( bSkip ){
  75508. u32 s1;
  75509. idx1 = 1 + getVarint32(&aKey1[1], s1);
  75510. szHdr1 = aKey1[0];
  75511. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  75512. i = 1;
  75513. pRhs++;
  75514. }else{
  75515. idx1 = getVarint32(aKey1, szHdr1);
  75516. d1 = szHdr1;
  75517. i = 0;
  75518. }
  75519. if( d1>(unsigned)nKey1 ){
  75520. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  75521. return 0; /* Corruption */
  75522. }
  75523. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  75524. assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
  75525. || CORRUPT_DB );
  75526. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  75527. assert( pPKey2->pKeyInfo->nKeyField>0 );
  75528. assert( idx1<=szHdr1 || CORRUPT_DB );
  75529. do{
  75530. u32 serial_type;
  75531. /* RHS is an integer */
  75532. if( pRhs->flags & MEM_Int ){
  75533. serial_type = aKey1[idx1];
  75534. testcase( serial_type==12 );
  75535. if( serial_type>=10 ){
  75536. rc = +1;
  75537. }else if( serial_type==0 ){
  75538. rc = -1;
  75539. }else if( serial_type==7 ){
  75540. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  75541. rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
  75542. }else{
  75543. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  75544. i64 rhs = pRhs->u.i;
  75545. if( lhs<rhs ){
  75546. rc = -1;
  75547. }else if( lhs>rhs ){
  75548. rc = +1;
  75549. }
  75550. }
  75551. }
  75552. /* RHS is real */
  75553. else if( pRhs->flags & MEM_Real ){
  75554. serial_type = aKey1[idx1];
  75555. if( serial_type>=10 ){
  75556. /* Serial types 12 or greater are strings and blobs (greater than
  75557. ** numbers). Types 10 and 11 are currently "reserved for future
  75558. ** use", so it doesn't really matter what the results of comparing
  75559. ** them to numberic values are. */
  75560. rc = +1;
  75561. }else if( serial_type==0 ){
  75562. rc = -1;
  75563. }else{
  75564. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  75565. if( serial_type==7 ){
  75566. if( mem1.u.r<pRhs->u.r ){
  75567. rc = -1;
  75568. }else if( mem1.u.r>pRhs->u.r ){
  75569. rc = +1;
  75570. }
  75571. }else{
  75572. rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
  75573. }
  75574. }
  75575. }
  75576. /* RHS is a string */
  75577. else if( pRhs->flags & MEM_Str ){
  75578. getVarint32(&aKey1[idx1], serial_type);
  75579. testcase( serial_type==12 );
  75580. if( serial_type<12 ){
  75581. rc = -1;
  75582. }else if( !(serial_type & 0x01) ){
  75583. rc = +1;
  75584. }else{
  75585. mem1.n = (serial_type - 12) / 2;
  75586. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  75587. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  75588. if( (d1+mem1.n) > (unsigned)nKey1
  75589. || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
  75590. ){
  75591. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  75592. return 0; /* Corruption */
  75593. }else if( pKeyInfo->aColl[i] ){
  75594. mem1.enc = pKeyInfo->enc;
  75595. mem1.db = pKeyInfo->db;
  75596. mem1.flags = MEM_Str;
  75597. mem1.z = (char*)&aKey1[d1];
  75598. rc = vdbeCompareMemString(
  75599. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  75600. );
  75601. }else{
  75602. int nCmp = MIN(mem1.n, pRhs->n);
  75603. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  75604. if( rc==0 ) rc = mem1.n - pRhs->n;
  75605. }
  75606. }
  75607. }
  75608. /* RHS is a blob */
  75609. else if( pRhs->flags & MEM_Blob ){
  75610. assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
  75611. getVarint32(&aKey1[idx1], serial_type);
  75612. testcase( serial_type==12 );
  75613. if( serial_type<12 || (serial_type & 0x01) ){
  75614. rc = -1;
  75615. }else{
  75616. int nStr = (serial_type - 12) / 2;
  75617. testcase( (d1+nStr)==(unsigned)nKey1 );
  75618. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  75619. if( (d1+nStr) > (unsigned)nKey1 ){
  75620. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  75621. return 0; /* Corruption */
  75622. }else if( pRhs->flags & MEM_Zero ){
  75623. if( !isAllZero((const char*)&aKey1[d1],nStr) ){
  75624. rc = 1;
  75625. }else{
  75626. rc = nStr - pRhs->u.nZero;
  75627. }
  75628. }else{
  75629. int nCmp = MIN(nStr, pRhs->n);
  75630. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  75631. if( rc==0 ) rc = nStr - pRhs->n;
  75632. }
  75633. }
  75634. }
  75635. /* RHS is null */
  75636. else{
  75637. serial_type = aKey1[idx1];
  75638. rc = (serial_type!=0);
  75639. }
  75640. if( rc!=0 ){
  75641. if( pPKey2->pKeyInfo->aSortOrder[i] ){
  75642. rc = -rc;
  75643. }
  75644. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  75645. assert( mem1.szMalloc==0 ); /* See comment below */
  75646. return rc;
  75647. }
  75648. i++;
  75649. if( i==pPKey2->nField ) break;
  75650. pRhs++;
  75651. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  75652. idx1 += sqlite3VarintLen(serial_type);
  75653. }while( idx1<(unsigned)szHdr1 && d1<=(unsigned)nKey1 );
  75654. /* No memory allocation is ever used on mem1. Prove this using
  75655. ** the following assert(). If the assert() fails, it indicates a
  75656. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  75657. assert( mem1.szMalloc==0 );
  75658. /* rc==0 here means that one or both of the keys ran out of fields and
  75659. ** all the fields up to that point were equal. Return the default_rc
  75660. ** value. */
  75661. assert( CORRUPT_DB
  75662. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  75663. || pPKey2->pKeyInfo->db->mallocFailed
  75664. );
  75665. pPKey2->eqSeen = 1;
  75666. return pPKey2->default_rc;
  75667. }
  75668. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  75669. int nKey1, const void *pKey1, /* Left key */
  75670. UnpackedRecord *pPKey2 /* Right key */
  75671. ){
  75672. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  75673. }
  75674. /*
  75675. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  75676. ** that (a) the first field of pPKey2 is an integer, and (b) the
  75677. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  75678. ** byte (i.e. is less than 128).
  75679. **
  75680. ** To avoid concerns about buffer overreads, this routine is only used
  75681. ** on schemas where the maximum valid header size is 63 bytes or less.
  75682. */
  75683. static int vdbeRecordCompareInt(
  75684. int nKey1, const void *pKey1, /* Left key */
  75685. UnpackedRecord *pPKey2 /* Right key */
  75686. ){
  75687. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  75688. int serial_type = ((const u8*)pKey1)[1];
  75689. int res;
  75690. u32 y;
  75691. u64 x;
  75692. i64 v;
  75693. i64 lhs;
  75694. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  75695. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  75696. switch( serial_type ){
  75697. case 1: { /* 1-byte signed integer */
  75698. lhs = ONE_BYTE_INT(aKey);
  75699. testcase( lhs<0 );
  75700. break;
  75701. }
  75702. case 2: { /* 2-byte signed integer */
  75703. lhs = TWO_BYTE_INT(aKey);
  75704. testcase( lhs<0 );
  75705. break;
  75706. }
  75707. case 3: { /* 3-byte signed integer */
  75708. lhs = THREE_BYTE_INT(aKey);
  75709. testcase( lhs<0 );
  75710. break;
  75711. }
  75712. case 4: { /* 4-byte signed integer */
  75713. y = FOUR_BYTE_UINT(aKey);
  75714. lhs = (i64)*(int*)&y;
  75715. testcase( lhs<0 );
  75716. break;
  75717. }
  75718. case 5: { /* 6-byte signed integer */
  75719. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  75720. testcase( lhs<0 );
  75721. break;
  75722. }
  75723. case 6: { /* 8-byte signed integer */
  75724. x = FOUR_BYTE_UINT(aKey);
  75725. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  75726. lhs = *(i64*)&x;
  75727. testcase( lhs<0 );
  75728. break;
  75729. }
  75730. case 8:
  75731. lhs = 0;
  75732. break;
  75733. case 9:
  75734. lhs = 1;
  75735. break;
  75736. /* This case could be removed without changing the results of running
  75737. ** this code. Including it causes gcc to generate a faster switch
  75738. ** statement (since the range of switch targets now starts at zero and
  75739. ** is contiguous) but does not cause any duplicate code to be generated
  75740. ** (as gcc is clever enough to combine the two like cases). Other
  75741. ** compilers might be similar. */
  75742. case 0: case 7:
  75743. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  75744. default:
  75745. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  75746. }
  75747. v = pPKey2->aMem[0].u.i;
  75748. if( v>lhs ){
  75749. res = pPKey2->r1;
  75750. }else if( v<lhs ){
  75751. res = pPKey2->r2;
  75752. }else if( pPKey2->nField>1 ){
  75753. /* The first fields of the two keys are equal. Compare the trailing
  75754. ** fields. */
  75755. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  75756. }else{
  75757. /* The first fields of the two keys are equal and there are no trailing
  75758. ** fields. Return pPKey2->default_rc in this case. */
  75759. res = pPKey2->default_rc;
  75760. pPKey2->eqSeen = 1;
  75761. }
  75762. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  75763. return res;
  75764. }
  75765. /*
  75766. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  75767. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  75768. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  75769. ** at the start of (pKey1/nKey1) fits in a single byte.
  75770. */
  75771. static int vdbeRecordCompareString(
  75772. int nKey1, const void *pKey1, /* Left key */
  75773. UnpackedRecord *pPKey2 /* Right key */
  75774. ){
  75775. const u8 *aKey1 = (const u8*)pKey1;
  75776. int serial_type;
  75777. int res;
  75778. assert( pPKey2->aMem[0].flags & MEM_Str );
  75779. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  75780. getVarint32(&aKey1[1], serial_type);
  75781. if( serial_type<12 ){
  75782. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  75783. }else if( !(serial_type & 0x01) ){
  75784. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  75785. }else{
  75786. int nCmp;
  75787. int nStr;
  75788. int szHdr = aKey1[0];
  75789. nStr = (serial_type-12) / 2;
  75790. if( (szHdr + nStr) > nKey1 ){
  75791. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  75792. return 0; /* Corruption */
  75793. }
  75794. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  75795. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  75796. if( res==0 ){
  75797. res = nStr - pPKey2->aMem[0].n;
  75798. if( res==0 ){
  75799. if( pPKey2->nField>1 ){
  75800. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  75801. }else{
  75802. res = pPKey2->default_rc;
  75803. pPKey2->eqSeen = 1;
  75804. }
  75805. }else if( res>0 ){
  75806. res = pPKey2->r2;
  75807. }else{
  75808. res = pPKey2->r1;
  75809. }
  75810. }else if( res>0 ){
  75811. res = pPKey2->r2;
  75812. }else{
  75813. res = pPKey2->r1;
  75814. }
  75815. }
  75816. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  75817. || CORRUPT_DB
  75818. || pPKey2->pKeyInfo->db->mallocFailed
  75819. );
  75820. return res;
  75821. }
  75822. /*
  75823. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  75824. ** suitable for comparing serialized records to the unpacked record passed
  75825. ** as the only argument.
  75826. */
  75827. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  75828. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  75829. ** that the size-of-header varint that occurs at the start of each record
  75830. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  75831. ** also assumes that it is safe to overread a buffer by at least the
  75832. ** maximum possible legal header size plus 8 bytes. Because there is
  75833. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  75834. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  75835. ** limit the size of the header to 64 bytes in cases where the first field
  75836. ** is an integer.
  75837. **
  75838. ** The easiest way to enforce this limit is to consider only records with
  75839. ** 13 fields or less. If the first field is an integer, the maximum legal
  75840. ** header size is (12*5 + 1 + 1) bytes. */
  75841. if( p->pKeyInfo->nAllField<=13 ){
  75842. int flags = p->aMem[0].flags;
  75843. if( p->pKeyInfo->aSortOrder[0] ){
  75844. p->r1 = 1;
  75845. p->r2 = -1;
  75846. }else{
  75847. p->r1 = -1;
  75848. p->r2 = 1;
  75849. }
  75850. if( (flags & MEM_Int) ){
  75851. return vdbeRecordCompareInt;
  75852. }
  75853. testcase( flags & MEM_Real );
  75854. testcase( flags & MEM_Null );
  75855. testcase( flags & MEM_Blob );
  75856. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  75857. assert( flags & MEM_Str );
  75858. return vdbeRecordCompareString;
  75859. }
  75860. }
  75861. return sqlite3VdbeRecordCompare;
  75862. }
  75863. /*
  75864. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  75865. ** Read the rowid (the last field in the record) and store it in *rowid.
  75866. ** Return SQLITE_OK if everything works, or an error code otherwise.
  75867. **
  75868. ** pCur might be pointing to text obtained from a corrupt database file.
  75869. ** So the content cannot be trusted. Do appropriate checks on the content.
  75870. */
  75871. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  75872. i64 nCellKey = 0;
  75873. int rc;
  75874. u32 szHdr; /* Size of the header */
  75875. u32 typeRowid; /* Serial type of the rowid */
  75876. u32 lenRowid; /* Size of the rowid */
  75877. Mem m, v;
  75878. /* Get the size of the index entry. Only indices entries of less
  75879. ** than 2GiB are support - anything large must be database corruption.
  75880. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  75881. ** this code can safely assume that nCellKey is 32-bits
  75882. */
  75883. assert( sqlite3BtreeCursorIsValid(pCur) );
  75884. nCellKey = sqlite3BtreePayloadSize(pCur);
  75885. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  75886. /* Read in the complete content of the index entry */
  75887. sqlite3VdbeMemInit(&m, db, 0);
  75888. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  75889. if( rc ){
  75890. return rc;
  75891. }
  75892. /* The index entry must begin with a header size */
  75893. (void)getVarint32((u8*)m.z, szHdr);
  75894. testcase( szHdr==3 );
  75895. testcase( szHdr==m.n );
  75896. testcase( szHdr>0x7fffffff );
  75897. assert( m.n>=0 );
  75898. if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
  75899. goto idx_rowid_corruption;
  75900. }
  75901. /* The last field of the index should be an integer - the ROWID.
  75902. ** Verify that the last entry really is an integer. */
  75903. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  75904. testcase( typeRowid==1 );
  75905. testcase( typeRowid==2 );
  75906. testcase( typeRowid==3 );
  75907. testcase( typeRowid==4 );
  75908. testcase( typeRowid==5 );
  75909. testcase( typeRowid==6 );
  75910. testcase( typeRowid==8 );
  75911. testcase( typeRowid==9 );
  75912. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  75913. goto idx_rowid_corruption;
  75914. }
  75915. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  75916. testcase( (u32)m.n==szHdr+lenRowid );
  75917. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  75918. goto idx_rowid_corruption;
  75919. }
  75920. /* Fetch the integer off the end of the index record */
  75921. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  75922. *rowid = v.u.i;
  75923. sqlite3VdbeMemRelease(&m);
  75924. return SQLITE_OK;
  75925. /* Jump here if database corruption is detected after m has been
  75926. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  75927. idx_rowid_corruption:
  75928. testcase( m.szMalloc!=0 );
  75929. sqlite3VdbeMemRelease(&m);
  75930. return SQLITE_CORRUPT_BKPT;
  75931. }
  75932. /*
  75933. ** Compare the key of the index entry that cursor pC is pointing to against
  75934. ** the key string in pUnpacked. Write into *pRes a number
  75935. ** that is negative, zero, or positive if pC is less than, equal to,
  75936. ** or greater than pUnpacked. Return SQLITE_OK on success.
  75937. **
  75938. ** pUnpacked is either created without a rowid or is truncated so that it
  75939. ** omits the rowid at the end. The rowid at the end of the index entry
  75940. ** is ignored as well. Hence, this routine only compares the prefixes
  75941. ** of the keys prior to the final rowid, not the entire key.
  75942. */
  75943. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  75944. sqlite3 *db, /* Database connection */
  75945. VdbeCursor *pC, /* The cursor to compare against */
  75946. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  75947. int *res /* Write the comparison result here */
  75948. ){
  75949. i64 nCellKey = 0;
  75950. int rc;
  75951. BtCursor *pCur;
  75952. Mem m;
  75953. assert( pC->eCurType==CURTYPE_BTREE );
  75954. pCur = pC->uc.pCursor;
  75955. assert( sqlite3BtreeCursorIsValid(pCur) );
  75956. nCellKey = sqlite3BtreePayloadSize(pCur);
  75957. /* nCellKey will always be between 0 and 0xffffffff because of the way
  75958. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  75959. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  75960. *res = 0;
  75961. return SQLITE_CORRUPT_BKPT;
  75962. }
  75963. sqlite3VdbeMemInit(&m, db, 0);
  75964. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  75965. if( rc ){
  75966. return rc;
  75967. }
  75968. *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
  75969. sqlite3VdbeMemRelease(&m);
  75970. return SQLITE_OK;
  75971. }
  75972. /*
  75973. ** This routine sets the value to be returned by subsequent calls to
  75974. ** sqlite3_changes() on the database handle 'db'.
  75975. */
  75976. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  75977. assert( sqlite3_mutex_held(db->mutex) );
  75978. db->nChange = nChange;
  75979. db->nTotalChange += nChange;
  75980. }
  75981. /*
  75982. ** Set a flag in the vdbe to update the change counter when it is finalised
  75983. ** or reset.
  75984. */
  75985. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  75986. v->changeCntOn = 1;
  75987. }
  75988. /*
  75989. ** Mark every prepared statement associated with a database connection
  75990. ** as expired.
  75991. **
  75992. ** An expired statement means that recompilation of the statement is
  75993. ** recommend. Statements expire when things happen that make their
  75994. ** programs obsolete. Removing user-defined functions or collating
  75995. ** sequences, or changing an authorization function are the types of
  75996. ** things that make prepared statements obsolete.
  75997. **
  75998. ** If iCode is 1, then expiration is advisory. The statement should
  75999. ** be reprepared before being restarted, but if it is already running
  76000. ** it is allowed to run to completion.
  76001. **
  76002. ** Internally, this function just sets the Vdbe.expired flag on all
  76003. ** prepared statements. The flag is set to 1 for an immediate expiration
  76004. ** and set to 2 for an advisory expiration.
  76005. */
  76006. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
  76007. Vdbe *p;
  76008. for(p = db->pVdbe; p; p=p->pNext){
  76009. p->expired = iCode+1;
  76010. }
  76011. }
  76012. /*
  76013. ** Return the database associated with the Vdbe.
  76014. */
  76015. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  76016. return v->db;
  76017. }
  76018. /*
  76019. ** Return the SQLITE_PREPARE flags for a Vdbe.
  76020. */
  76021. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
  76022. return v->prepFlags;
  76023. }
  76024. /*
  76025. ** Return a pointer to an sqlite3_value structure containing the value bound
  76026. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  76027. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  76028. ** constants) to the value before returning it.
  76029. **
  76030. ** The returned value must be freed by the caller using sqlite3ValueFree().
  76031. */
  76032. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  76033. assert( iVar>0 );
  76034. if( v ){
  76035. Mem *pMem = &v->aVar[iVar-1];
  76036. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  76037. if( 0==(pMem->flags & MEM_Null) ){
  76038. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  76039. if( pRet ){
  76040. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  76041. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  76042. }
  76043. return pRet;
  76044. }
  76045. }
  76046. return 0;
  76047. }
  76048. /*
  76049. ** Configure SQL variable iVar so that binding a new value to it signals
  76050. ** to sqlite3_reoptimize() that re-preparing the statement may result
  76051. ** in a better query plan.
  76052. */
  76053. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  76054. assert( iVar>0 );
  76055. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  76056. if( iVar>=32 ){
  76057. v->expmask |= 0x80000000;
  76058. }else{
  76059. v->expmask |= ((u32)1 << (iVar-1));
  76060. }
  76061. }
  76062. /*
  76063. ** Cause a function to throw an error if it was call from OP_PureFunc
  76064. ** rather than OP_Function.
  76065. **
  76066. ** OP_PureFunc means that the function must be deterministic, and should
  76067. ** throw an error if it is given inputs that would make it non-deterministic.
  76068. ** This routine is invoked by date/time functions that use non-deterministic
  76069. ** features such as 'now'.
  76070. */
  76071. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
  76072. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  76073. if( pCtx->pVdbe==0 ) return 1;
  76074. #endif
  76075. if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
  76076. sqlite3_result_error(pCtx,
  76077. "non-deterministic function in index expression or CHECK constraint",
  76078. -1);
  76079. return 0;
  76080. }
  76081. return 1;
  76082. }
  76083. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76084. /*
  76085. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  76086. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  76087. ** in memory obtained from sqlite3DbMalloc).
  76088. */
  76089. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  76090. if( pVtab->zErrMsg ){
  76091. sqlite3 *db = p->db;
  76092. sqlite3DbFree(db, p->zErrMsg);
  76093. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  76094. sqlite3_free(pVtab->zErrMsg);
  76095. pVtab->zErrMsg = 0;
  76096. }
  76097. }
  76098. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  76099. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  76100. /*
  76101. ** If the second argument is not NULL, release any allocations associated
  76102. ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
  76103. ** structure itself, using sqlite3DbFree().
  76104. **
  76105. ** This function is used to free UnpackedRecord structures allocated by
  76106. ** the vdbeUnpackRecord() function found in vdbeapi.c.
  76107. */
  76108. static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
  76109. if( p ){
  76110. int i;
  76111. for(i=0; i<nField; i++){
  76112. Mem *pMem = &p->aMem[i];
  76113. if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
  76114. }
  76115. sqlite3DbFreeNN(db, p);
  76116. }
  76117. }
  76118. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  76119. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  76120. /*
  76121. ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
  76122. ** then cursor passed as the second argument should point to the row about
  76123. ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
  76124. ** the required value will be read from the row the cursor points to.
  76125. */
  76126. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
  76127. Vdbe *v, /* Vdbe pre-update hook is invoked by */
  76128. VdbeCursor *pCsr, /* Cursor to grab old.* values from */
  76129. int op, /* SQLITE_INSERT, UPDATE or DELETE */
  76130. const char *zDb, /* Database name */
  76131. Table *pTab, /* Modified table */
  76132. i64 iKey1, /* Initial key value */
  76133. int iReg /* Register for new.* record */
  76134. ){
  76135. sqlite3 *db = v->db;
  76136. i64 iKey2;
  76137. PreUpdate preupdate;
  76138. const char *zTbl = pTab->zName;
  76139. static const u8 fakeSortOrder = 0;
  76140. assert( db->pPreUpdate==0 );
  76141. memset(&preupdate, 0, sizeof(PreUpdate));
  76142. if( HasRowid(pTab)==0 ){
  76143. iKey1 = iKey2 = 0;
  76144. preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
  76145. }else{
  76146. if( op==SQLITE_UPDATE ){
  76147. iKey2 = v->aMem[iReg].u.i;
  76148. }else{
  76149. iKey2 = iKey1;
  76150. }
  76151. }
  76152. assert( pCsr->nField==pTab->nCol
  76153. || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
  76154. );
  76155. preupdate.v = v;
  76156. preupdate.pCsr = pCsr;
  76157. preupdate.op = op;
  76158. preupdate.iNewReg = iReg;
  76159. preupdate.keyinfo.db = db;
  76160. preupdate.keyinfo.enc = ENC(db);
  76161. preupdate.keyinfo.nKeyField = pTab->nCol;
  76162. preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
  76163. preupdate.iKey1 = iKey1;
  76164. preupdate.iKey2 = iKey2;
  76165. preupdate.pTab = pTab;
  76166. db->pPreUpdate = &preupdate;
  76167. db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
  76168. db->pPreUpdate = 0;
  76169. sqlite3DbFree(db, preupdate.aRecord);
  76170. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
  76171. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
  76172. if( preupdate.aNew ){
  76173. int i;
  76174. for(i=0; i<pCsr->nField; i++){
  76175. sqlite3VdbeMemRelease(&preupdate.aNew[i]);
  76176. }
  76177. sqlite3DbFreeNN(db, preupdate.aNew);
  76178. }
  76179. }
  76180. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  76181. /************** End of vdbeaux.c *********************************************/
  76182. /************** Begin file vdbeapi.c *****************************************/
  76183. /*
  76184. ** 2004 May 26
  76185. **
  76186. ** The author disclaims copyright to this source code. In place of
  76187. ** a legal notice, here is a blessing:
  76188. **
  76189. ** May you do good and not evil.
  76190. ** May you find forgiveness for yourself and forgive others.
  76191. ** May you share freely, never taking more than you give.
  76192. **
  76193. *************************************************************************
  76194. **
  76195. ** This file contains code use to implement APIs that are part of the
  76196. ** VDBE.
  76197. */
  76198. /* #include "sqliteInt.h" */
  76199. /* #include "vdbeInt.h" */
  76200. #ifndef SQLITE_OMIT_DEPRECATED
  76201. /*
  76202. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  76203. ** to be recompiled. A statement needs to be recompiled whenever the
  76204. ** execution environment changes in a way that would alter the program
  76205. ** that sqlite3_prepare() generates. For example, if new functions or
  76206. ** collating sequences are registered or if an authorizer function is
  76207. ** added or changed.
  76208. */
  76209. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  76210. Vdbe *p = (Vdbe*)pStmt;
  76211. return p==0 || p->expired;
  76212. }
  76213. #endif
  76214. /*
  76215. ** Check on a Vdbe to make sure it has not been finalized. Log
  76216. ** an error and return true if it has been finalized (or is otherwise
  76217. ** invalid). Return false if it is ok.
  76218. */
  76219. static int vdbeSafety(Vdbe *p){
  76220. if( p->db==0 ){
  76221. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  76222. return 1;
  76223. }else{
  76224. return 0;
  76225. }
  76226. }
  76227. static int vdbeSafetyNotNull(Vdbe *p){
  76228. if( p==0 ){
  76229. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  76230. return 1;
  76231. }else{
  76232. return vdbeSafety(p);
  76233. }
  76234. }
  76235. #ifndef SQLITE_OMIT_TRACE
  76236. /*
  76237. ** Invoke the profile callback. This routine is only called if we already
  76238. ** know that the profile callback is defined and needs to be invoked.
  76239. */
  76240. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  76241. sqlite3_int64 iNow;
  76242. sqlite3_int64 iElapse;
  76243. assert( p->startTime>0 );
  76244. assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 );
  76245. assert( db->init.busy==0 );
  76246. assert( p->zSql!=0 );
  76247. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  76248. iElapse = (iNow - p->startTime)*1000000;
  76249. #ifndef SQLITE_OMIT_DEPRECATED
  76250. if( db->xProfile ){
  76251. db->xProfile(db->pProfileArg, p->zSql, iElapse);
  76252. }
  76253. #endif
  76254. if( db->mTrace & SQLITE_TRACE_PROFILE ){
  76255. db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
  76256. }
  76257. p->startTime = 0;
  76258. }
  76259. /*
  76260. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  76261. ** is needed, and it invokes the callback if it is needed.
  76262. */
  76263. # define checkProfileCallback(DB,P) \
  76264. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  76265. #else
  76266. # define checkProfileCallback(DB,P) /*no-op*/
  76267. #endif
  76268. /*
  76269. ** The following routine destroys a virtual machine that is created by
  76270. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  76271. ** success/failure code that describes the result of executing the virtual
  76272. ** machine.
  76273. **
  76274. ** This routine sets the error code and string returned by
  76275. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  76276. */
  76277. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  76278. int rc;
  76279. if( pStmt==0 ){
  76280. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  76281. ** pointer is a harmless no-op. */
  76282. rc = SQLITE_OK;
  76283. }else{
  76284. Vdbe *v = (Vdbe*)pStmt;
  76285. sqlite3 *db = v->db;
  76286. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  76287. sqlite3_mutex_enter(db->mutex);
  76288. checkProfileCallback(db, v);
  76289. rc = sqlite3VdbeFinalize(v);
  76290. rc = sqlite3ApiExit(db, rc);
  76291. sqlite3LeaveMutexAndCloseZombie(db);
  76292. }
  76293. return rc;
  76294. }
  76295. /*
  76296. ** Terminate the current execution of an SQL statement and reset it
  76297. ** back to its starting state so that it can be reused. A success code from
  76298. ** the prior execution is returned.
  76299. **
  76300. ** This routine sets the error code and string returned by
  76301. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  76302. */
  76303. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  76304. int rc;
  76305. if( pStmt==0 ){
  76306. rc = SQLITE_OK;
  76307. }else{
  76308. Vdbe *v = (Vdbe*)pStmt;
  76309. sqlite3 *db = v->db;
  76310. sqlite3_mutex_enter(db->mutex);
  76311. checkProfileCallback(db, v);
  76312. rc = sqlite3VdbeReset(v);
  76313. sqlite3VdbeRewind(v);
  76314. assert( (rc & (db->errMask))==rc );
  76315. rc = sqlite3ApiExit(db, rc);
  76316. sqlite3_mutex_leave(db->mutex);
  76317. }
  76318. return rc;
  76319. }
  76320. /*
  76321. ** Set all the parameters in the compiled SQL statement to NULL.
  76322. */
  76323. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  76324. int i;
  76325. int rc = SQLITE_OK;
  76326. Vdbe *p = (Vdbe*)pStmt;
  76327. #if SQLITE_THREADSAFE
  76328. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  76329. #endif
  76330. sqlite3_mutex_enter(mutex);
  76331. for(i=0; i<p->nVar; i++){
  76332. sqlite3VdbeMemRelease(&p->aVar[i]);
  76333. p->aVar[i].flags = MEM_Null;
  76334. }
  76335. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  76336. if( p->expmask ){
  76337. p->expired = 1;
  76338. }
  76339. sqlite3_mutex_leave(mutex);
  76340. return rc;
  76341. }
  76342. /**************************** sqlite3_value_ *******************************
  76343. ** The following routines extract information from a Mem or sqlite3_value
  76344. ** structure.
  76345. */
  76346. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  76347. Mem *p = (Mem*)pVal;
  76348. if( p->flags & (MEM_Blob|MEM_Str) ){
  76349. if( ExpandBlob(p)!=SQLITE_OK ){
  76350. assert( p->flags==MEM_Null && p->z==0 );
  76351. return 0;
  76352. }
  76353. p->flags |= MEM_Blob;
  76354. return p->n ? p->z : 0;
  76355. }else{
  76356. return sqlite3_value_text(pVal);
  76357. }
  76358. }
  76359. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  76360. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  76361. }
  76362. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  76363. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  76364. }
  76365. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  76366. return sqlite3VdbeRealValue((Mem*)pVal);
  76367. }
  76368. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  76369. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  76370. }
  76371. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  76372. return sqlite3VdbeIntValue((Mem*)pVal);
  76373. }
  76374. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
  76375. Mem *pMem = (Mem*)pVal;
  76376. return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
  76377. }
  76378. SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
  76379. Mem *p = (Mem*)pVal;
  76380. if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
  76381. (MEM_Null|MEM_Term|MEM_Subtype)
  76382. && zPType!=0
  76383. && p->eSubtype=='p'
  76384. && strcmp(p->u.zPType, zPType)==0
  76385. ){
  76386. return (void*)p->z;
  76387. }else{
  76388. return 0;
  76389. }
  76390. }
  76391. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  76392. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  76393. }
  76394. #ifndef SQLITE_OMIT_UTF16
  76395. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  76396. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  76397. }
  76398. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  76399. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  76400. }
  76401. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  76402. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  76403. }
  76404. #endif /* SQLITE_OMIT_UTF16 */
  76405. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  76406. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  76407. ** point number string BLOB NULL
  76408. */
  76409. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  76410. static const u8 aType[] = {
  76411. SQLITE_BLOB, /* 0x00 */
  76412. SQLITE_NULL, /* 0x01 */
  76413. SQLITE_TEXT, /* 0x02 */
  76414. SQLITE_NULL, /* 0x03 */
  76415. SQLITE_INTEGER, /* 0x04 */
  76416. SQLITE_NULL, /* 0x05 */
  76417. SQLITE_INTEGER, /* 0x06 */
  76418. SQLITE_NULL, /* 0x07 */
  76419. SQLITE_FLOAT, /* 0x08 */
  76420. SQLITE_NULL, /* 0x09 */
  76421. SQLITE_FLOAT, /* 0x0a */
  76422. SQLITE_NULL, /* 0x0b */
  76423. SQLITE_INTEGER, /* 0x0c */
  76424. SQLITE_NULL, /* 0x0d */
  76425. SQLITE_INTEGER, /* 0x0e */
  76426. SQLITE_NULL, /* 0x0f */
  76427. SQLITE_BLOB, /* 0x10 */
  76428. SQLITE_NULL, /* 0x11 */
  76429. SQLITE_TEXT, /* 0x12 */
  76430. SQLITE_NULL, /* 0x13 */
  76431. SQLITE_INTEGER, /* 0x14 */
  76432. SQLITE_NULL, /* 0x15 */
  76433. SQLITE_INTEGER, /* 0x16 */
  76434. SQLITE_NULL, /* 0x17 */
  76435. SQLITE_FLOAT, /* 0x18 */
  76436. SQLITE_NULL, /* 0x19 */
  76437. SQLITE_FLOAT, /* 0x1a */
  76438. SQLITE_NULL, /* 0x1b */
  76439. SQLITE_INTEGER, /* 0x1c */
  76440. SQLITE_NULL, /* 0x1d */
  76441. SQLITE_INTEGER, /* 0x1e */
  76442. SQLITE_NULL, /* 0x1f */
  76443. };
  76444. return aType[pVal->flags&MEM_AffMask];
  76445. }
  76446. /* Return true if a parameter to xUpdate represents an unchanged column */
  76447. SQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){
  76448. return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
  76449. }
  76450. /* Return true if a parameter value originated from an sqlite3_bind() */
  76451. SQLITE_API int sqlite3_value_frombind(sqlite3_value *pVal){
  76452. return (pVal->flags&MEM_FromBind)!=0;
  76453. }
  76454. /* Make a copy of an sqlite3_value object
  76455. */
  76456. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
  76457. sqlite3_value *pNew;
  76458. if( pOrig==0 ) return 0;
  76459. pNew = sqlite3_malloc( sizeof(*pNew) );
  76460. if( pNew==0 ) return 0;
  76461. memset(pNew, 0, sizeof(*pNew));
  76462. memcpy(pNew, pOrig, MEMCELLSIZE);
  76463. pNew->flags &= ~MEM_Dyn;
  76464. pNew->db = 0;
  76465. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  76466. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  76467. pNew->flags |= MEM_Ephem;
  76468. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  76469. sqlite3ValueFree(pNew);
  76470. pNew = 0;
  76471. }
  76472. }
  76473. return pNew;
  76474. }
  76475. /* Destroy an sqlite3_value object previously obtained from
  76476. ** sqlite3_value_dup().
  76477. */
  76478. SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
  76479. sqlite3ValueFree(pOld);
  76480. }
  76481. /**************************** sqlite3_result_ *******************************
  76482. ** The following routines are used by user-defined functions to specify
  76483. ** the function result.
  76484. **
  76485. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  76486. ** result as a string or blob but if the string or blob is too large, it
  76487. ** then sets the error code to SQLITE_TOOBIG
  76488. **
  76489. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  76490. ** on value P is not going to be used and need to be destroyed.
  76491. */
  76492. static void setResultStrOrError(
  76493. sqlite3_context *pCtx, /* Function context */
  76494. const char *z, /* String pointer */
  76495. int n, /* Bytes in string, or negative */
  76496. u8 enc, /* Encoding of z. 0 for BLOBs */
  76497. void (*xDel)(void*) /* Destructor function */
  76498. ){
  76499. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  76500. sqlite3_result_error_toobig(pCtx);
  76501. }
  76502. }
  76503. static int invokeValueDestructor(
  76504. const void *p, /* Value to destroy */
  76505. void (*xDel)(void*), /* The destructor */
  76506. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  76507. ){
  76508. assert( xDel!=SQLITE_DYNAMIC );
  76509. if( xDel==0 ){
  76510. /* noop */
  76511. }else if( xDel==SQLITE_TRANSIENT ){
  76512. /* noop */
  76513. }else{
  76514. xDel((void*)p);
  76515. }
  76516. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  76517. return SQLITE_TOOBIG;
  76518. }
  76519. SQLITE_API void sqlite3_result_blob(
  76520. sqlite3_context *pCtx,
  76521. const void *z,
  76522. int n,
  76523. void (*xDel)(void *)
  76524. ){
  76525. assert( n>=0 );
  76526. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76527. setResultStrOrError(pCtx, z, n, 0, xDel);
  76528. }
  76529. SQLITE_API void sqlite3_result_blob64(
  76530. sqlite3_context *pCtx,
  76531. const void *z,
  76532. sqlite3_uint64 n,
  76533. void (*xDel)(void *)
  76534. ){
  76535. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76536. assert( xDel!=SQLITE_DYNAMIC );
  76537. if( n>0x7fffffff ){
  76538. (void)invokeValueDestructor(z, xDel, pCtx);
  76539. }else{
  76540. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  76541. }
  76542. }
  76543. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  76544. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76545. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  76546. }
  76547. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  76548. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76549. pCtx->isError = SQLITE_ERROR;
  76550. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  76551. }
  76552. #ifndef SQLITE_OMIT_UTF16
  76553. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  76554. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76555. pCtx->isError = SQLITE_ERROR;
  76556. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  76557. }
  76558. #endif
  76559. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  76560. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76561. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  76562. }
  76563. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  76564. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76565. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  76566. }
  76567. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  76568. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76569. sqlite3VdbeMemSetNull(pCtx->pOut);
  76570. }
  76571. SQLITE_API void sqlite3_result_pointer(
  76572. sqlite3_context *pCtx,
  76573. void *pPtr,
  76574. const char *zPType,
  76575. void (*xDestructor)(void*)
  76576. ){
  76577. Mem *pOut = pCtx->pOut;
  76578. assert( sqlite3_mutex_held(pOut->db->mutex) );
  76579. sqlite3VdbeMemRelease(pOut);
  76580. pOut->flags = MEM_Null;
  76581. sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
  76582. }
  76583. SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  76584. Mem *pOut = pCtx->pOut;
  76585. assert( sqlite3_mutex_held(pOut->db->mutex) );
  76586. pOut->eSubtype = eSubtype & 0xff;
  76587. pOut->flags |= MEM_Subtype;
  76588. }
  76589. SQLITE_API void sqlite3_result_text(
  76590. sqlite3_context *pCtx,
  76591. const char *z,
  76592. int n,
  76593. void (*xDel)(void *)
  76594. ){
  76595. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76596. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  76597. }
  76598. SQLITE_API void sqlite3_result_text64(
  76599. sqlite3_context *pCtx,
  76600. const char *z,
  76601. sqlite3_uint64 n,
  76602. void (*xDel)(void *),
  76603. unsigned char enc
  76604. ){
  76605. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76606. assert( xDel!=SQLITE_DYNAMIC );
  76607. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  76608. if( n>0x7fffffff ){
  76609. (void)invokeValueDestructor(z, xDel, pCtx);
  76610. }else{
  76611. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  76612. }
  76613. }
  76614. #ifndef SQLITE_OMIT_UTF16
  76615. SQLITE_API void sqlite3_result_text16(
  76616. sqlite3_context *pCtx,
  76617. const void *z,
  76618. int n,
  76619. void (*xDel)(void *)
  76620. ){
  76621. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76622. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  76623. }
  76624. SQLITE_API void sqlite3_result_text16be(
  76625. sqlite3_context *pCtx,
  76626. const void *z,
  76627. int n,
  76628. void (*xDel)(void *)
  76629. ){
  76630. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76631. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  76632. }
  76633. SQLITE_API void sqlite3_result_text16le(
  76634. sqlite3_context *pCtx,
  76635. const void *z,
  76636. int n,
  76637. void (*xDel)(void *)
  76638. ){
  76639. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76640. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  76641. }
  76642. #endif /* SQLITE_OMIT_UTF16 */
  76643. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  76644. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76645. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  76646. }
  76647. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  76648. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76649. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  76650. }
  76651. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  76652. Mem *pOut = pCtx->pOut;
  76653. assert( sqlite3_mutex_held(pOut->db->mutex) );
  76654. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  76655. return SQLITE_TOOBIG;
  76656. }
  76657. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  76658. return SQLITE_OK;
  76659. }
  76660. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  76661. pCtx->isError = errCode ? errCode : -1;
  76662. #ifdef SQLITE_DEBUG
  76663. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  76664. #endif
  76665. if( pCtx->pOut->flags & MEM_Null ){
  76666. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  76667. SQLITE_UTF8, SQLITE_STATIC);
  76668. }
  76669. }
  76670. /* Force an SQLITE_TOOBIG error. */
  76671. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  76672. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76673. pCtx->isError = SQLITE_TOOBIG;
  76674. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  76675. SQLITE_UTF8, SQLITE_STATIC);
  76676. }
  76677. /* An SQLITE_NOMEM error. */
  76678. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  76679. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76680. sqlite3VdbeMemSetNull(pCtx->pOut);
  76681. pCtx->isError = SQLITE_NOMEM_BKPT;
  76682. sqlite3OomFault(pCtx->pOut->db);
  76683. }
  76684. /*
  76685. ** This function is called after a transaction has been committed. It
  76686. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  76687. */
  76688. static int doWalCallbacks(sqlite3 *db){
  76689. int rc = SQLITE_OK;
  76690. #ifndef SQLITE_OMIT_WAL
  76691. int i;
  76692. for(i=0; i<db->nDb; i++){
  76693. Btree *pBt = db->aDb[i].pBt;
  76694. if( pBt ){
  76695. int nEntry;
  76696. sqlite3BtreeEnter(pBt);
  76697. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  76698. sqlite3BtreeLeave(pBt);
  76699. if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
  76700. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
  76701. }
  76702. }
  76703. }
  76704. #endif
  76705. return rc;
  76706. }
  76707. /*
  76708. ** Execute the statement pStmt, either until a row of data is ready, the
  76709. ** statement is completely executed or an error occurs.
  76710. **
  76711. ** This routine implements the bulk of the logic behind the sqlite_step()
  76712. ** API. The only thing omitted is the automatic recompile if a
  76713. ** schema change has occurred. That detail is handled by the
  76714. ** outer sqlite3_step() wrapper procedure.
  76715. */
  76716. static int sqlite3Step(Vdbe *p){
  76717. sqlite3 *db;
  76718. int rc;
  76719. assert(p);
  76720. if( p->magic!=VDBE_MAGIC_RUN ){
  76721. /* We used to require that sqlite3_reset() be called before retrying
  76722. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  76723. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  76724. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  76725. ** This "automatic-reset" change is not technically an incompatibility,
  76726. ** since any application that receives an SQLITE_MISUSE is broken by
  76727. ** definition.
  76728. **
  76729. ** Nevertheless, some published applications that were originally written
  76730. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  76731. ** returns, and those were broken by the automatic-reset change. As a
  76732. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  76733. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  76734. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  76735. ** or SQLITE_BUSY error.
  76736. */
  76737. #ifdef SQLITE_OMIT_AUTORESET
  76738. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  76739. sqlite3_reset((sqlite3_stmt*)p);
  76740. }else{
  76741. return SQLITE_MISUSE_BKPT;
  76742. }
  76743. #else
  76744. sqlite3_reset((sqlite3_stmt*)p);
  76745. #endif
  76746. }
  76747. /* Check that malloc() has not failed. If it has, return early. */
  76748. db = p->db;
  76749. if( db->mallocFailed ){
  76750. p->rc = SQLITE_NOMEM;
  76751. return SQLITE_NOMEM_BKPT;
  76752. }
  76753. if( p->pc<0 && p->expired ){
  76754. p->rc = SQLITE_SCHEMA;
  76755. rc = SQLITE_ERROR;
  76756. goto end_of_step;
  76757. }
  76758. if( p->pc<0 ){
  76759. /* If there are no other statements currently running, then
  76760. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  76761. ** from interrupting a statement that has not yet started.
  76762. */
  76763. if( db->nVdbeActive==0 ){
  76764. db->u1.isInterrupted = 0;
  76765. }
  76766. assert( db->nVdbeWrite>0 || db->autoCommit==0
  76767. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  76768. );
  76769. #ifndef SQLITE_OMIT_TRACE
  76770. if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
  76771. && !db->init.busy && p->zSql ){
  76772. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  76773. }else{
  76774. assert( p->startTime==0 );
  76775. }
  76776. #endif
  76777. db->nVdbeActive++;
  76778. if( p->readOnly==0 ) db->nVdbeWrite++;
  76779. if( p->bIsReader ) db->nVdbeRead++;
  76780. p->pc = 0;
  76781. }
  76782. #ifdef SQLITE_DEBUG
  76783. p->rcApp = SQLITE_OK;
  76784. #endif
  76785. #ifndef SQLITE_OMIT_EXPLAIN
  76786. if( p->explain ){
  76787. rc = sqlite3VdbeList(p);
  76788. }else
  76789. #endif /* SQLITE_OMIT_EXPLAIN */
  76790. {
  76791. db->nVdbeExec++;
  76792. rc = sqlite3VdbeExec(p);
  76793. db->nVdbeExec--;
  76794. }
  76795. if( rc!=SQLITE_ROW ){
  76796. #ifndef SQLITE_OMIT_TRACE
  76797. /* If the statement completed successfully, invoke the profile callback */
  76798. checkProfileCallback(db, p);
  76799. #endif
  76800. if( rc==SQLITE_DONE && db->autoCommit ){
  76801. assert( p->rc==SQLITE_OK );
  76802. p->rc = doWalCallbacks(db);
  76803. if( p->rc!=SQLITE_OK ){
  76804. rc = SQLITE_ERROR;
  76805. }
  76806. }
  76807. }
  76808. db->errCode = rc;
  76809. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  76810. p->rc = SQLITE_NOMEM_BKPT;
  76811. }
  76812. end_of_step:
  76813. /* At this point local variable rc holds the value that should be
  76814. ** returned if this statement was compiled using the legacy
  76815. ** sqlite3_prepare() interface. According to the docs, this can only
  76816. ** be one of the values in the first assert() below. Variable p->rc
  76817. ** contains the value that would be returned if sqlite3_finalize()
  76818. ** were called on statement p.
  76819. */
  76820. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  76821. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  76822. );
  76823. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  76824. if( rc!=SQLITE_ROW
  76825. && rc!=SQLITE_DONE
  76826. && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
  76827. ){
  76828. /* If this statement was prepared using saved SQL and an
  76829. ** error has occurred, then return the error code in p->rc to the
  76830. ** caller. Set the error code in the database handle to the same value.
  76831. */
  76832. rc = sqlite3VdbeTransferError(p);
  76833. }
  76834. return (rc&db->errMask);
  76835. }
  76836. /*
  76837. ** This is the top-level implementation of sqlite3_step(). Call
  76838. ** sqlite3Step() to do most of the work. If a schema error occurs,
  76839. ** call sqlite3Reprepare() and try again.
  76840. */
  76841. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  76842. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  76843. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  76844. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  76845. sqlite3 *db; /* The database connection */
  76846. if( vdbeSafetyNotNull(v) ){
  76847. return SQLITE_MISUSE_BKPT;
  76848. }
  76849. db = v->db;
  76850. sqlite3_mutex_enter(db->mutex);
  76851. v->doingRerun = 0;
  76852. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  76853. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  76854. int savedPc = v->pc;
  76855. rc = sqlite3Reprepare(v);
  76856. if( rc!=SQLITE_OK ){
  76857. /* This case occurs after failing to recompile an sql statement.
  76858. ** The error message from the SQL compiler has already been loaded
  76859. ** into the database handle. This block copies the error message
  76860. ** from the database handle into the statement and sets the statement
  76861. ** program counter to 0 to ensure that when the statement is
  76862. ** finalized or reset the parser error message is available via
  76863. ** sqlite3_errmsg() and sqlite3_errcode().
  76864. */
  76865. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  76866. sqlite3DbFree(db, v->zErrMsg);
  76867. if( !db->mallocFailed ){
  76868. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  76869. v->rc = rc = sqlite3ApiExit(db, rc);
  76870. } else {
  76871. v->zErrMsg = 0;
  76872. v->rc = rc = SQLITE_NOMEM_BKPT;
  76873. }
  76874. break;
  76875. }
  76876. sqlite3_reset(pStmt);
  76877. if( savedPc>=0 ) v->doingRerun = 1;
  76878. assert( v->expired==0 );
  76879. }
  76880. sqlite3_mutex_leave(db->mutex);
  76881. return rc;
  76882. }
  76883. /*
  76884. ** Extract the user data from a sqlite3_context structure and return a
  76885. ** pointer to it.
  76886. */
  76887. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  76888. assert( p && p->pFunc );
  76889. return p->pFunc->pUserData;
  76890. }
  76891. /*
  76892. ** Extract the user data from a sqlite3_context structure and return a
  76893. ** pointer to it.
  76894. **
  76895. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  76896. ** returns a copy of the pointer to the database connection (the 1st
  76897. ** parameter) of the sqlite3_create_function() and
  76898. ** sqlite3_create_function16() routines that originally registered the
  76899. ** application defined function.
  76900. */
  76901. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  76902. assert( p && p->pOut );
  76903. return p->pOut->db;
  76904. }
  76905. /*
  76906. ** If this routine is invoked from within an xColumn method of a virtual
  76907. ** table, then it returns true if and only if the the call is during an
  76908. ** UPDATE operation and the value of the column will not be modified
  76909. ** by the UPDATE.
  76910. **
  76911. ** If this routine is called from any context other than within the
  76912. ** xColumn method of a virtual table, then the return value is meaningless
  76913. ** and arbitrary.
  76914. **
  76915. ** Virtual table implements might use this routine to optimize their
  76916. ** performance by substituting a NULL result, or some other light-weight
  76917. ** value, as a signal to the xUpdate routine that the column is unchanged.
  76918. */
  76919. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
  76920. assert( p );
  76921. return sqlite3_value_nochange(p->pOut);
  76922. }
  76923. /*
  76924. ** Return the current time for a statement. If the current time
  76925. ** is requested more than once within the same run of a single prepared
  76926. ** statement, the exact same time is returned for each invocation regardless
  76927. ** of the amount of time that elapses between invocations. In other words,
  76928. ** the time returned is always the time of the first call.
  76929. */
  76930. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  76931. int rc;
  76932. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  76933. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  76934. assert( p->pVdbe!=0 );
  76935. #else
  76936. sqlite3_int64 iTime = 0;
  76937. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  76938. #endif
  76939. if( *piTime==0 ){
  76940. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  76941. if( rc ) *piTime = 0;
  76942. }
  76943. return *piTime;
  76944. }
  76945. /*
  76946. ** Create a new aggregate context for p and return a pointer to
  76947. ** its pMem->z element.
  76948. */
  76949. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  76950. Mem *pMem = p->pMem;
  76951. assert( (pMem->flags & MEM_Agg)==0 );
  76952. if( nByte<=0 ){
  76953. sqlite3VdbeMemSetNull(pMem);
  76954. pMem->z = 0;
  76955. }else{
  76956. sqlite3VdbeMemClearAndResize(pMem, nByte);
  76957. pMem->flags = MEM_Agg;
  76958. pMem->u.pDef = p->pFunc;
  76959. if( pMem->z ){
  76960. memset(pMem->z, 0, nByte);
  76961. }
  76962. }
  76963. return (void*)pMem->z;
  76964. }
  76965. /*
  76966. ** Allocate or return the aggregate context for a user function. A new
  76967. ** context is allocated on the first call. Subsequent calls return the
  76968. ** same context that was returned on prior calls.
  76969. */
  76970. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  76971. assert( p && p->pFunc && p->pFunc->xFinalize );
  76972. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  76973. testcase( nByte<0 );
  76974. if( (p->pMem->flags & MEM_Agg)==0 ){
  76975. return createAggContext(p, nByte);
  76976. }else{
  76977. return (void*)p->pMem->z;
  76978. }
  76979. }
  76980. /*
  76981. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  76982. ** the user-function defined by pCtx.
  76983. **
  76984. ** The left-most argument is 0.
  76985. **
  76986. ** Undocumented behavior: If iArg is negative then access a cache of
  76987. ** auxiliary data pointers that is available to all functions within a
  76988. ** single prepared statement. The iArg values must match.
  76989. */
  76990. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  76991. AuxData *pAuxData;
  76992. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  76993. #if SQLITE_ENABLE_STAT3_OR_STAT4
  76994. if( pCtx->pVdbe==0 ) return 0;
  76995. #else
  76996. assert( pCtx->pVdbe!=0 );
  76997. #endif
  76998. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  76999. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  77000. return pAuxData->pAux;
  77001. }
  77002. }
  77003. return 0;
  77004. }
  77005. /*
  77006. ** Set the auxiliary data pointer and delete function, for the iArg'th
  77007. ** argument to the user-function defined by pCtx. Any previous value is
  77008. ** deleted by calling the delete function specified when it was set.
  77009. **
  77010. ** The left-most argument is 0.
  77011. **
  77012. ** Undocumented behavior: If iArg is negative then make the data available
  77013. ** to all functions within the current prepared statement using iArg as an
  77014. ** access code.
  77015. */
  77016. SQLITE_API void sqlite3_set_auxdata(
  77017. sqlite3_context *pCtx,
  77018. int iArg,
  77019. void *pAux,
  77020. void (*xDelete)(void*)
  77021. ){
  77022. AuxData *pAuxData;
  77023. Vdbe *pVdbe = pCtx->pVdbe;
  77024. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  77025. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  77026. if( pVdbe==0 ) goto failed;
  77027. #else
  77028. assert( pVdbe!=0 );
  77029. #endif
  77030. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  77031. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  77032. break;
  77033. }
  77034. }
  77035. if( pAuxData==0 ){
  77036. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  77037. if( !pAuxData ) goto failed;
  77038. pAuxData->iAuxOp = pCtx->iOp;
  77039. pAuxData->iAuxArg = iArg;
  77040. pAuxData->pNextAux = pVdbe->pAuxData;
  77041. pVdbe->pAuxData = pAuxData;
  77042. if( pCtx->isError==0 ) pCtx->isError = -1;
  77043. }else if( pAuxData->xDeleteAux ){
  77044. pAuxData->xDeleteAux(pAuxData->pAux);
  77045. }
  77046. pAuxData->pAux = pAux;
  77047. pAuxData->xDeleteAux = xDelete;
  77048. return;
  77049. failed:
  77050. if( xDelete ){
  77051. xDelete(pAux);
  77052. }
  77053. }
  77054. #ifndef SQLITE_OMIT_DEPRECATED
  77055. /*
  77056. ** Return the number of times the Step function of an aggregate has been
  77057. ** called.
  77058. **
  77059. ** This function is deprecated. Do not use it for new code. It is
  77060. ** provide only to avoid breaking legacy code. New aggregate function
  77061. ** implementations should keep their own counts within their aggregate
  77062. ** context.
  77063. */
  77064. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  77065. assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
  77066. return p->pMem->n;
  77067. }
  77068. #endif
  77069. /*
  77070. ** Return the number of columns in the result set for the statement pStmt.
  77071. */
  77072. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  77073. Vdbe *pVm = (Vdbe *)pStmt;
  77074. return pVm ? pVm->nResColumn : 0;
  77075. }
  77076. /*
  77077. ** Return the number of values available from the current row of the
  77078. ** currently executing statement pStmt.
  77079. */
  77080. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  77081. Vdbe *pVm = (Vdbe *)pStmt;
  77082. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  77083. return pVm->nResColumn;
  77084. }
  77085. /*
  77086. ** Return a pointer to static memory containing an SQL NULL value.
  77087. */
  77088. static const Mem *columnNullValue(void){
  77089. /* Even though the Mem structure contains an element
  77090. ** of type i64, on certain architectures (x86) with certain compiler
  77091. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  77092. ** instead of an 8-byte one. This all works fine, except that when
  77093. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  77094. ** that a Mem structure is located on an 8-byte boundary. To prevent
  77095. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  77096. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  77097. ** __attribute__((aligned(8))) macro. */
  77098. static const Mem nullMem
  77099. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  77100. __attribute__((aligned(8)))
  77101. #endif
  77102. = {
  77103. /* .u = */ {0},
  77104. /* .flags = */ (u16)MEM_Null,
  77105. /* .enc = */ (u8)0,
  77106. /* .eSubtype = */ (u8)0,
  77107. /* .n = */ (int)0,
  77108. /* .z = */ (char*)0,
  77109. /* .zMalloc = */ (char*)0,
  77110. /* .szMalloc = */ (int)0,
  77111. /* .uTemp = */ (u32)0,
  77112. /* .db = */ (sqlite3*)0,
  77113. /* .xDel = */ (void(*)(void*))0,
  77114. #ifdef SQLITE_DEBUG
  77115. /* .pScopyFrom = */ (Mem*)0,
  77116. /* .mScopyFlags= */ 0,
  77117. #endif
  77118. };
  77119. return &nullMem;
  77120. }
  77121. /*
  77122. ** Check to see if column iCol of the given statement is valid. If
  77123. ** it is, return a pointer to the Mem for the value of that column.
  77124. ** If iCol is not valid, return a pointer to a Mem which has a value
  77125. ** of NULL.
  77126. */
  77127. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  77128. Vdbe *pVm;
  77129. Mem *pOut;
  77130. pVm = (Vdbe *)pStmt;
  77131. if( pVm==0 ) return (Mem*)columnNullValue();
  77132. assert( pVm->db );
  77133. sqlite3_mutex_enter(pVm->db->mutex);
  77134. if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  77135. pOut = &pVm->pResultSet[i];
  77136. }else{
  77137. sqlite3Error(pVm->db, SQLITE_RANGE);
  77138. pOut = (Mem*)columnNullValue();
  77139. }
  77140. return pOut;
  77141. }
  77142. /*
  77143. ** This function is called after invoking an sqlite3_value_XXX function on a
  77144. ** column value (i.e. a value returned by evaluating an SQL expression in the
  77145. ** select list of a SELECT statement) that may cause a malloc() failure. If
  77146. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  77147. ** code of statement pStmt set to SQLITE_NOMEM.
  77148. **
  77149. ** Specifically, this is called from within:
  77150. **
  77151. ** sqlite3_column_int()
  77152. ** sqlite3_column_int64()
  77153. ** sqlite3_column_text()
  77154. ** sqlite3_column_text16()
  77155. ** sqlite3_column_real()
  77156. ** sqlite3_column_bytes()
  77157. ** sqlite3_column_bytes16()
  77158. ** sqiite3_column_blob()
  77159. */
  77160. static void columnMallocFailure(sqlite3_stmt *pStmt)
  77161. {
  77162. /* If malloc() failed during an encoding conversion within an
  77163. ** sqlite3_column_XXX API, then set the return code of the statement to
  77164. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  77165. ** and _finalize() will return NOMEM.
  77166. */
  77167. Vdbe *p = (Vdbe *)pStmt;
  77168. if( p ){
  77169. assert( p->db!=0 );
  77170. assert( sqlite3_mutex_held(p->db->mutex) );
  77171. p->rc = sqlite3ApiExit(p->db, p->rc);
  77172. sqlite3_mutex_leave(p->db->mutex);
  77173. }
  77174. }
  77175. /**************************** sqlite3_column_ *******************************
  77176. ** The following routines are used to access elements of the current row
  77177. ** in the result set.
  77178. */
  77179. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  77180. const void *val;
  77181. val = sqlite3_value_blob( columnMem(pStmt,i) );
  77182. /* Even though there is no encoding conversion, value_blob() might
  77183. ** need to call malloc() to expand the result of a zeroblob()
  77184. ** expression.
  77185. */
  77186. columnMallocFailure(pStmt);
  77187. return val;
  77188. }
  77189. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  77190. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  77191. columnMallocFailure(pStmt);
  77192. return val;
  77193. }
  77194. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  77195. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  77196. columnMallocFailure(pStmt);
  77197. return val;
  77198. }
  77199. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  77200. double val = sqlite3_value_double( columnMem(pStmt,i) );
  77201. columnMallocFailure(pStmt);
  77202. return val;
  77203. }
  77204. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  77205. int val = sqlite3_value_int( columnMem(pStmt,i) );
  77206. columnMallocFailure(pStmt);
  77207. return val;
  77208. }
  77209. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  77210. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  77211. columnMallocFailure(pStmt);
  77212. return val;
  77213. }
  77214. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  77215. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  77216. columnMallocFailure(pStmt);
  77217. return val;
  77218. }
  77219. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  77220. Mem *pOut = columnMem(pStmt, i);
  77221. if( pOut->flags&MEM_Static ){
  77222. pOut->flags &= ~MEM_Static;
  77223. pOut->flags |= MEM_Ephem;
  77224. }
  77225. columnMallocFailure(pStmt);
  77226. return (sqlite3_value *)pOut;
  77227. }
  77228. #ifndef SQLITE_OMIT_UTF16
  77229. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  77230. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  77231. columnMallocFailure(pStmt);
  77232. return val;
  77233. }
  77234. #endif /* SQLITE_OMIT_UTF16 */
  77235. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  77236. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  77237. columnMallocFailure(pStmt);
  77238. return iType;
  77239. }
  77240. /*
  77241. ** Convert the N-th element of pStmt->pColName[] into a string using
  77242. ** xFunc() then return that string. If N is out of range, return 0.
  77243. **
  77244. ** There are up to 5 names for each column. useType determines which
  77245. ** name is returned. Here are the names:
  77246. **
  77247. ** 0 The column name as it should be displayed for output
  77248. ** 1 The datatype name for the column
  77249. ** 2 The name of the database that the column derives from
  77250. ** 3 The name of the table that the column derives from
  77251. ** 4 The name of the table column that the result column derives from
  77252. **
  77253. ** If the result is not a simple column reference (if it is an expression
  77254. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  77255. */
  77256. static const void *columnName(
  77257. sqlite3_stmt *pStmt, /* The statement */
  77258. int N, /* Which column to get the name for */
  77259. int useUtf16, /* True to return the name as UTF16 */
  77260. int useType /* What type of name */
  77261. ){
  77262. const void *ret;
  77263. Vdbe *p;
  77264. int n;
  77265. sqlite3 *db;
  77266. #ifdef SQLITE_ENABLE_API_ARMOR
  77267. if( pStmt==0 ){
  77268. (void)SQLITE_MISUSE_BKPT;
  77269. return 0;
  77270. }
  77271. #endif
  77272. ret = 0;
  77273. p = (Vdbe *)pStmt;
  77274. db = p->db;
  77275. assert( db!=0 );
  77276. n = sqlite3_column_count(pStmt);
  77277. if( N<n && N>=0 ){
  77278. N += useType*n;
  77279. sqlite3_mutex_enter(db->mutex);
  77280. assert( db->mallocFailed==0 );
  77281. #ifndef SQLITE_OMIT_UTF16
  77282. if( useUtf16 ){
  77283. ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
  77284. }else
  77285. #endif
  77286. {
  77287. ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
  77288. }
  77289. /* A malloc may have failed inside of the _text() call. If this
  77290. ** is the case, clear the mallocFailed flag and return NULL.
  77291. */
  77292. if( db->mallocFailed ){
  77293. sqlite3OomClear(db);
  77294. ret = 0;
  77295. }
  77296. sqlite3_mutex_leave(db->mutex);
  77297. }
  77298. return ret;
  77299. }
  77300. /*
  77301. ** Return the name of the Nth column of the result set returned by SQL
  77302. ** statement pStmt.
  77303. */
  77304. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  77305. return columnName(pStmt, N, 0, COLNAME_NAME);
  77306. }
  77307. #ifndef SQLITE_OMIT_UTF16
  77308. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  77309. return columnName(pStmt, N, 1, COLNAME_NAME);
  77310. }
  77311. #endif
  77312. /*
  77313. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  77314. ** not define OMIT_DECLTYPE.
  77315. */
  77316. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  77317. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  77318. and SQLITE_ENABLE_COLUMN_METADATA"
  77319. #endif
  77320. #ifndef SQLITE_OMIT_DECLTYPE
  77321. /*
  77322. ** Return the column declaration type (if applicable) of the 'i'th column
  77323. ** of the result set of SQL statement pStmt.
  77324. */
  77325. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  77326. return columnName(pStmt, N, 0, COLNAME_DECLTYPE);
  77327. }
  77328. #ifndef SQLITE_OMIT_UTF16
  77329. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  77330. return columnName(pStmt, N, 1, COLNAME_DECLTYPE);
  77331. }
  77332. #endif /* SQLITE_OMIT_UTF16 */
  77333. #endif /* SQLITE_OMIT_DECLTYPE */
  77334. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  77335. /*
  77336. ** Return the name of the database from which a result column derives.
  77337. ** NULL is returned if the result column is an expression or constant or
  77338. ** anything else which is not an unambiguous reference to a database column.
  77339. */
  77340. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  77341. return columnName(pStmt, N, 0, COLNAME_DATABASE);
  77342. }
  77343. #ifndef SQLITE_OMIT_UTF16
  77344. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  77345. return columnName(pStmt, N, 1, COLNAME_DATABASE);
  77346. }
  77347. #endif /* SQLITE_OMIT_UTF16 */
  77348. /*
  77349. ** Return the name of the table from which a result column derives.
  77350. ** NULL is returned if the result column is an expression or constant or
  77351. ** anything else which is not an unambiguous reference to a database column.
  77352. */
  77353. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  77354. return columnName(pStmt, N, 0, COLNAME_TABLE);
  77355. }
  77356. #ifndef SQLITE_OMIT_UTF16
  77357. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  77358. return columnName(pStmt, N, 1, COLNAME_TABLE);
  77359. }
  77360. #endif /* SQLITE_OMIT_UTF16 */
  77361. /*
  77362. ** Return the name of the table column from which a result column derives.
  77363. ** NULL is returned if the result column is an expression or constant or
  77364. ** anything else which is not an unambiguous reference to a database column.
  77365. */
  77366. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  77367. return columnName(pStmt, N, 0, COLNAME_COLUMN);
  77368. }
  77369. #ifndef SQLITE_OMIT_UTF16
  77370. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  77371. return columnName(pStmt, N, 1, COLNAME_COLUMN);
  77372. }
  77373. #endif /* SQLITE_OMIT_UTF16 */
  77374. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  77375. /******************************* sqlite3_bind_ ***************************
  77376. **
  77377. ** Routines used to attach values to wildcards in a compiled SQL statement.
  77378. */
  77379. /*
  77380. ** Unbind the value bound to variable i in virtual machine p. This is the
  77381. ** the same as binding a NULL value to the column. If the "i" parameter is
  77382. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  77383. **
  77384. ** A successful evaluation of this routine acquires the mutex on p.
  77385. ** the mutex is released if any kind of error occurs.
  77386. **
  77387. ** The error code stored in database p->db is overwritten with the return
  77388. ** value in any case.
  77389. */
  77390. static int vdbeUnbind(Vdbe *p, int i){
  77391. Mem *pVar;
  77392. if( vdbeSafetyNotNull(p) ){
  77393. return SQLITE_MISUSE_BKPT;
  77394. }
  77395. sqlite3_mutex_enter(p->db->mutex);
  77396. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  77397. sqlite3Error(p->db, SQLITE_MISUSE);
  77398. sqlite3_mutex_leave(p->db->mutex);
  77399. sqlite3_log(SQLITE_MISUSE,
  77400. "bind on a busy prepared statement: [%s]", p->zSql);
  77401. return SQLITE_MISUSE_BKPT;
  77402. }
  77403. if( i<1 || i>p->nVar ){
  77404. sqlite3Error(p->db, SQLITE_RANGE);
  77405. sqlite3_mutex_leave(p->db->mutex);
  77406. return SQLITE_RANGE;
  77407. }
  77408. i--;
  77409. pVar = &p->aVar[i];
  77410. sqlite3VdbeMemRelease(pVar);
  77411. pVar->flags = MEM_Null;
  77412. p->db->errCode = SQLITE_OK;
  77413. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  77414. ** binding a new value to this variable invalidates the current query plan.
  77415. **
  77416. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  77417. ** parameter in the WHERE clause might influence the choice of query plan
  77418. ** for a statement, then the statement will be automatically recompiled,
  77419. ** as if there had been a schema change, on the first sqlite3_step() call
  77420. ** following any change to the bindings of that parameter.
  77421. */
  77422. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  77423. if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
  77424. p->expired = 1;
  77425. }
  77426. return SQLITE_OK;
  77427. }
  77428. /*
  77429. ** Bind a text or BLOB value.
  77430. */
  77431. static int bindText(
  77432. sqlite3_stmt *pStmt, /* The statement to bind against */
  77433. int i, /* Index of the parameter to bind */
  77434. const void *zData, /* Pointer to the data to be bound */
  77435. int nData, /* Number of bytes of data to be bound */
  77436. void (*xDel)(void*), /* Destructor for the data */
  77437. u8 encoding /* Encoding for the data */
  77438. ){
  77439. Vdbe *p = (Vdbe *)pStmt;
  77440. Mem *pVar;
  77441. int rc;
  77442. rc = vdbeUnbind(p, i);
  77443. if( rc==SQLITE_OK ){
  77444. if( zData!=0 ){
  77445. pVar = &p->aVar[i-1];
  77446. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  77447. if( rc==SQLITE_OK && encoding!=0 ){
  77448. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  77449. }
  77450. if( rc ){
  77451. sqlite3Error(p->db, rc);
  77452. rc = sqlite3ApiExit(p->db, rc);
  77453. }
  77454. }
  77455. sqlite3_mutex_leave(p->db->mutex);
  77456. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  77457. xDel((void*)zData);
  77458. }
  77459. return rc;
  77460. }
  77461. /*
  77462. ** Bind a blob value to an SQL statement variable.
  77463. */
  77464. SQLITE_API int sqlite3_bind_blob(
  77465. sqlite3_stmt *pStmt,
  77466. int i,
  77467. const void *zData,
  77468. int nData,
  77469. void (*xDel)(void*)
  77470. ){
  77471. #ifdef SQLITE_ENABLE_API_ARMOR
  77472. if( nData<0 ) return SQLITE_MISUSE_BKPT;
  77473. #endif
  77474. return bindText(pStmt, i, zData, nData, xDel, 0);
  77475. }
  77476. SQLITE_API int sqlite3_bind_blob64(
  77477. sqlite3_stmt *pStmt,
  77478. int i,
  77479. const void *zData,
  77480. sqlite3_uint64 nData,
  77481. void (*xDel)(void*)
  77482. ){
  77483. assert( xDel!=SQLITE_DYNAMIC );
  77484. if( nData>0x7fffffff ){
  77485. return invokeValueDestructor(zData, xDel, 0);
  77486. }else{
  77487. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  77488. }
  77489. }
  77490. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  77491. int rc;
  77492. Vdbe *p = (Vdbe *)pStmt;
  77493. rc = vdbeUnbind(p, i);
  77494. if( rc==SQLITE_OK ){
  77495. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  77496. sqlite3_mutex_leave(p->db->mutex);
  77497. }
  77498. return rc;
  77499. }
  77500. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  77501. return sqlite3_bind_int64(p, i, (i64)iValue);
  77502. }
  77503. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  77504. int rc;
  77505. Vdbe *p = (Vdbe *)pStmt;
  77506. rc = vdbeUnbind(p, i);
  77507. if( rc==SQLITE_OK ){
  77508. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  77509. sqlite3_mutex_leave(p->db->mutex);
  77510. }
  77511. return rc;
  77512. }
  77513. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  77514. int rc;
  77515. Vdbe *p = (Vdbe*)pStmt;
  77516. rc = vdbeUnbind(p, i);
  77517. if( rc==SQLITE_OK ){
  77518. sqlite3_mutex_leave(p->db->mutex);
  77519. }
  77520. return rc;
  77521. }
  77522. SQLITE_API int sqlite3_bind_pointer(
  77523. sqlite3_stmt *pStmt,
  77524. int i,
  77525. void *pPtr,
  77526. const char *zPTtype,
  77527. void (*xDestructor)(void*)
  77528. ){
  77529. int rc;
  77530. Vdbe *p = (Vdbe*)pStmt;
  77531. rc = vdbeUnbind(p, i);
  77532. if( rc==SQLITE_OK ){
  77533. sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
  77534. sqlite3_mutex_leave(p->db->mutex);
  77535. }else if( xDestructor ){
  77536. xDestructor(pPtr);
  77537. }
  77538. return rc;
  77539. }
  77540. SQLITE_API int sqlite3_bind_text(
  77541. sqlite3_stmt *pStmt,
  77542. int i,
  77543. const char *zData,
  77544. int nData,
  77545. void (*xDel)(void*)
  77546. ){
  77547. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  77548. }
  77549. SQLITE_API int sqlite3_bind_text64(
  77550. sqlite3_stmt *pStmt,
  77551. int i,
  77552. const char *zData,
  77553. sqlite3_uint64 nData,
  77554. void (*xDel)(void*),
  77555. unsigned char enc
  77556. ){
  77557. assert( xDel!=SQLITE_DYNAMIC );
  77558. if( nData>0x7fffffff ){
  77559. return invokeValueDestructor(zData, xDel, 0);
  77560. }else{
  77561. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  77562. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  77563. }
  77564. }
  77565. #ifndef SQLITE_OMIT_UTF16
  77566. SQLITE_API int sqlite3_bind_text16(
  77567. sqlite3_stmt *pStmt,
  77568. int i,
  77569. const void *zData,
  77570. int nData,
  77571. void (*xDel)(void*)
  77572. ){
  77573. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  77574. }
  77575. #endif /* SQLITE_OMIT_UTF16 */
  77576. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  77577. int rc;
  77578. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  77579. case SQLITE_INTEGER: {
  77580. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  77581. break;
  77582. }
  77583. case SQLITE_FLOAT: {
  77584. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  77585. break;
  77586. }
  77587. case SQLITE_BLOB: {
  77588. if( pValue->flags & MEM_Zero ){
  77589. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  77590. }else{
  77591. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  77592. }
  77593. break;
  77594. }
  77595. case SQLITE_TEXT: {
  77596. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  77597. pValue->enc);
  77598. break;
  77599. }
  77600. default: {
  77601. rc = sqlite3_bind_null(pStmt, i);
  77602. break;
  77603. }
  77604. }
  77605. return rc;
  77606. }
  77607. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  77608. int rc;
  77609. Vdbe *p = (Vdbe *)pStmt;
  77610. rc = vdbeUnbind(p, i);
  77611. if( rc==SQLITE_OK ){
  77612. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  77613. sqlite3_mutex_leave(p->db->mutex);
  77614. }
  77615. return rc;
  77616. }
  77617. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  77618. int rc;
  77619. Vdbe *p = (Vdbe *)pStmt;
  77620. sqlite3_mutex_enter(p->db->mutex);
  77621. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  77622. rc = SQLITE_TOOBIG;
  77623. }else{
  77624. assert( (n & 0x7FFFFFFF)==n );
  77625. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  77626. }
  77627. rc = sqlite3ApiExit(p->db, rc);
  77628. sqlite3_mutex_leave(p->db->mutex);
  77629. return rc;
  77630. }
  77631. /*
  77632. ** Return the number of wildcards that can be potentially bound to.
  77633. ** This routine is added to support DBD::SQLite.
  77634. */
  77635. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  77636. Vdbe *p = (Vdbe*)pStmt;
  77637. return p ? p->nVar : 0;
  77638. }
  77639. /*
  77640. ** Return the name of a wildcard parameter. Return NULL if the index
  77641. ** is out of range or if the wildcard is unnamed.
  77642. **
  77643. ** The result is always UTF-8.
  77644. */
  77645. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  77646. Vdbe *p = (Vdbe*)pStmt;
  77647. if( p==0 ) return 0;
  77648. return sqlite3VListNumToName(p->pVList, i);
  77649. }
  77650. /*
  77651. ** Given a wildcard parameter name, return the index of the variable
  77652. ** with that name. If there is no variable with the given name,
  77653. ** return 0.
  77654. */
  77655. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  77656. if( p==0 || zName==0 ) return 0;
  77657. return sqlite3VListNameToNum(p->pVList, zName, nName);
  77658. }
  77659. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  77660. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  77661. }
  77662. /*
  77663. ** Transfer all bindings from the first statement over to the second.
  77664. */
  77665. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  77666. Vdbe *pFrom = (Vdbe*)pFromStmt;
  77667. Vdbe *pTo = (Vdbe*)pToStmt;
  77668. int i;
  77669. assert( pTo->db==pFrom->db );
  77670. assert( pTo->nVar==pFrom->nVar );
  77671. sqlite3_mutex_enter(pTo->db->mutex);
  77672. for(i=0; i<pFrom->nVar; i++){
  77673. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  77674. }
  77675. sqlite3_mutex_leave(pTo->db->mutex);
  77676. return SQLITE_OK;
  77677. }
  77678. #ifndef SQLITE_OMIT_DEPRECATED
  77679. /*
  77680. ** Deprecated external interface. Internal/core SQLite code
  77681. ** should call sqlite3TransferBindings.
  77682. **
  77683. ** It is misuse to call this routine with statements from different
  77684. ** database connections. But as this is a deprecated interface, we
  77685. ** will not bother to check for that condition.
  77686. **
  77687. ** If the two statements contain a different number of bindings, then
  77688. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  77689. ** SQLITE_OK is returned.
  77690. */
  77691. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  77692. Vdbe *pFrom = (Vdbe*)pFromStmt;
  77693. Vdbe *pTo = (Vdbe*)pToStmt;
  77694. if( pFrom->nVar!=pTo->nVar ){
  77695. return SQLITE_ERROR;
  77696. }
  77697. assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
  77698. if( pTo->expmask ){
  77699. pTo->expired = 1;
  77700. }
  77701. assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
  77702. if( pFrom->expmask ){
  77703. pFrom->expired = 1;
  77704. }
  77705. return sqlite3TransferBindings(pFromStmt, pToStmt);
  77706. }
  77707. #endif
  77708. /*
  77709. ** Return the sqlite3* database handle to which the prepared statement given
  77710. ** in the argument belongs. This is the same database handle that was
  77711. ** the first argument to the sqlite3_prepare() that was used to create
  77712. ** the statement in the first place.
  77713. */
  77714. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  77715. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  77716. }
  77717. /*
  77718. ** Return true if the prepared statement is guaranteed to not modify the
  77719. ** database.
  77720. */
  77721. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  77722. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  77723. }
  77724. /*
  77725. ** Return 1 if the statement is an EXPLAIN and return 2 if the
  77726. ** statement is an EXPLAIN QUERY PLAN
  77727. */
  77728. SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){
  77729. return pStmt ? ((Vdbe*)pStmt)->explain : 0;
  77730. }
  77731. /*
  77732. ** Return true if the prepared statement is in need of being reset.
  77733. */
  77734. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  77735. Vdbe *v = (Vdbe*)pStmt;
  77736. return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
  77737. }
  77738. /*
  77739. ** Return a pointer to the next prepared statement after pStmt associated
  77740. ** with database connection pDb. If pStmt is NULL, return the first
  77741. ** prepared statement for the database connection. Return NULL if there
  77742. ** are no more.
  77743. */
  77744. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  77745. sqlite3_stmt *pNext;
  77746. #ifdef SQLITE_ENABLE_API_ARMOR
  77747. if( !sqlite3SafetyCheckOk(pDb) ){
  77748. (void)SQLITE_MISUSE_BKPT;
  77749. return 0;
  77750. }
  77751. #endif
  77752. sqlite3_mutex_enter(pDb->mutex);
  77753. if( pStmt==0 ){
  77754. pNext = (sqlite3_stmt*)pDb->pVdbe;
  77755. }else{
  77756. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  77757. }
  77758. sqlite3_mutex_leave(pDb->mutex);
  77759. return pNext;
  77760. }
  77761. /*
  77762. ** Return the value of a status counter for a prepared statement
  77763. */
  77764. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  77765. Vdbe *pVdbe = (Vdbe*)pStmt;
  77766. u32 v;
  77767. #ifdef SQLITE_ENABLE_API_ARMOR
  77768. if( !pStmt
  77769. || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
  77770. ){
  77771. (void)SQLITE_MISUSE_BKPT;
  77772. return 0;
  77773. }
  77774. #endif
  77775. if( op==SQLITE_STMTSTATUS_MEMUSED ){
  77776. sqlite3 *db = pVdbe->db;
  77777. sqlite3_mutex_enter(db->mutex);
  77778. v = 0;
  77779. db->pnBytesFreed = (int*)&v;
  77780. sqlite3VdbeClearObject(db, pVdbe);
  77781. sqlite3DbFree(db, pVdbe);
  77782. db->pnBytesFreed = 0;
  77783. sqlite3_mutex_leave(db->mutex);
  77784. }else{
  77785. v = pVdbe->aCounter[op];
  77786. if( resetFlag ) pVdbe->aCounter[op] = 0;
  77787. }
  77788. return (int)v;
  77789. }
  77790. /*
  77791. ** Return the SQL associated with a prepared statement
  77792. */
  77793. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  77794. Vdbe *p = (Vdbe *)pStmt;
  77795. return p ? p->zSql : 0;
  77796. }
  77797. /*
  77798. ** Return the SQL associated with a prepared statement with
  77799. ** bound parameters expanded. Space to hold the returned string is
  77800. ** obtained from sqlite3_malloc(). The caller is responsible for
  77801. ** freeing the returned string by passing it to sqlite3_free().
  77802. **
  77803. ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
  77804. ** expanded bound parameters.
  77805. */
  77806. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
  77807. #ifdef SQLITE_OMIT_TRACE
  77808. return 0;
  77809. #else
  77810. char *z = 0;
  77811. const char *zSql = sqlite3_sql(pStmt);
  77812. if( zSql ){
  77813. Vdbe *p = (Vdbe *)pStmt;
  77814. sqlite3_mutex_enter(p->db->mutex);
  77815. z = sqlite3VdbeExpandSql(p, zSql);
  77816. sqlite3_mutex_leave(p->db->mutex);
  77817. }
  77818. return z;
  77819. #endif
  77820. }
  77821. #ifdef SQLITE_ENABLE_NORMALIZE
  77822. /*
  77823. ** Return the normalized SQL associated with a prepared statement.
  77824. */
  77825. SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
  77826. Vdbe *p = (Vdbe *)pStmt;
  77827. if( p==0 ) return 0;
  77828. if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
  77829. sqlite3_mutex_enter(p->db->mutex);
  77830. p->zNormSql = sqlite3Normalize(p, p->zSql);
  77831. sqlite3_mutex_leave(p->db->mutex);
  77832. }
  77833. return p->zNormSql;
  77834. }
  77835. #endif /* SQLITE_ENABLE_NORMALIZE */
  77836. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77837. /*
  77838. ** Allocate and populate an UnpackedRecord structure based on the serialized
  77839. ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
  77840. ** if successful, or a NULL pointer if an OOM error is encountered.
  77841. */
  77842. static UnpackedRecord *vdbeUnpackRecord(
  77843. KeyInfo *pKeyInfo,
  77844. int nKey,
  77845. const void *pKey
  77846. ){
  77847. UnpackedRecord *pRet; /* Return value */
  77848. pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  77849. if( pRet ){
  77850. memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
  77851. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
  77852. }
  77853. return pRet;
  77854. }
  77855. /*
  77856. ** This function is called from within a pre-update callback to retrieve
  77857. ** a field of the row currently being updated or deleted.
  77858. */
  77859. SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  77860. PreUpdate *p = db->pPreUpdate;
  77861. Mem *pMem;
  77862. int rc = SQLITE_OK;
  77863. /* Test that this call is being made from within an SQLITE_DELETE or
  77864. ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
  77865. if( !p || p->op==SQLITE_INSERT ){
  77866. rc = SQLITE_MISUSE_BKPT;
  77867. goto preupdate_old_out;
  77868. }
  77869. if( p->pPk ){
  77870. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  77871. }
  77872. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  77873. rc = SQLITE_RANGE;
  77874. goto preupdate_old_out;
  77875. }
  77876. /* If the old.* record has not yet been loaded into memory, do so now. */
  77877. if( p->pUnpacked==0 ){
  77878. u32 nRec;
  77879. u8 *aRec;
  77880. nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
  77881. aRec = sqlite3DbMallocRaw(db, nRec);
  77882. if( !aRec ) goto preupdate_old_out;
  77883. rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
  77884. if( rc==SQLITE_OK ){
  77885. p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
  77886. if( !p->pUnpacked ) rc = SQLITE_NOMEM;
  77887. }
  77888. if( rc!=SQLITE_OK ){
  77889. sqlite3DbFree(db, aRec);
  77890. goto preupdate_old_out;
  77891. }
  77892. p->aRecord = aRec;
  77893. }
  77894. pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
  77895. if( iIdx==p->pTab->iPKey ){
  77896. sqlite3VdbeMemSetInt64(pMem, p->iKey1);
  77897. }else if( iIdx>=p->pUnpacked->nField ){
  77898. *ppValue = (sqlite3_value *)columnNullValue();
  77899. }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
  77900. if( pMem->flags & MEM_Int ){
  77901. sqlite3VdbeMemRealify(pMem);
  77902. }
  77903. }
  77904. preupdate_old_out:
  77905. sqlite3Error(db, rc);
  77906. return sqlite3ApiExit(db, rc);
  77907. }
  77908. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  77909. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77910. /*
  77911. ** This function is called from within a pre-update callback to retrieve
  77912. ** the number of columns in the row being updated, deleted or inserted.
  77913. */
  77914. SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
  77915. PreUpdate *p = db->pPreUpdate;
  77916. return (p ? p->keyinfo.nKeyField : 0);
  77917. }
  77918. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  77919. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77920. /*
  77921. ** This function is designed to be called from within a pre-update callback
  77922. ** only. It returns zero if the change that caused the callback was made
  77923. ** immediately by a user SQL statement. Or, if the change was made by a
  77924. ** trigger program, it returns the number of trigger programs currently
  77925. ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
  77926. ** top-level trigger etc.).
  77927. **
  77928. ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
  77929. ** or SET DEFAULT action is considered a trigger.
  77930. */
  77931. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
  77932. PreUpdate *p = db->pPreUpdate;
  77933. return (p ? p->v->nFrame : 0);
  77934. }
  77935. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  77936. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77937. /*
  77938. ** This function is called from within a pre-update callback to retrieve
  77939. ** a field of the row currently being updated or inserted.
  77940. */
  77941. SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  77942. PreUpdate *p = db->pPreUpdate;
  77943. int rc = SQLITE_OK;
  77944. Mem *pMem;
  77945. if( !p || p->op==SQLITE_DELETE ){
  77946. rc = SQLITE_MISUSE_BKPT;
  77947. goto preupdate_new_out;
  77948. }
  77949. if( p->pPk && p->op!=SQLITE_UPDATE ){
  77950. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  77951. }
  77952. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  77953. rc = SQLITE_RANGE;
  77954. goto preupdate_new_out;
  77955. }
  77956. if( p->op==SQLITE_INSERT ){
  77957. /* For an INSERT, memory cell p->iNewReg contains the serialized record
  77958. ** that is being inserted. Deserialize it. */
  77959. UnpackedRecord *pUnpack = p->pNewUnpacked;
  77960. if( !pUnpack ){
  77961. Mem *pData = &p->v->aMem[p->iNewReg];
  77962. rc = ExpandBlob(pData);
  77963. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  77964. pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
  77965. if( !pUnpack ){
  77966. rc = SQLITE_NOMEM;
  77967. goto preupdate_new_out;
  77968. }
  77969. p->pNewUnpacked = pUnpack;
  77970. }
  77971. pMem = &pUnpack->aMem[iIdx];
  77972. if( iIdx==p->pTab->iPKey ){
  77973. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  77974. }else if( iIdx>=pUnpack->nField ){
  77975. pMem = (sqlite3_value *)columnNullValue();
  77976. }
  77977. }else{
  77978. /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
  77979. ** value. Make a copy of the cell contents and return a pointer to it.
  77980. ** It is not safe to return a pointer to the memory cell itself as the
  77981. ** caller may modify the value text encoding.
  77982. */
  77983. assert( p->op==SQLITE_UPDATE );
  77984. if( !p->aNew ){
  77985. p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
  77986. if( !p->aNew ){
  77987. rc = SQLITE_NOMEM;
  77988. goto preupdate_new_out;
  77989. }
  77990. }
  77991. assert( iIdx>=0 && iIdx<p->pCsr->nField );
  77992. pMem = &p->aNew[iIdx];
  77993. if( pMem->flags==0 ){
  77994. if( iIdx==p->pTab->iPKey ){
  77995. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  77996. }else{
  77997. rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
  77998. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  77999. }
  78000. }
  78001. }
  78002. *ppValue = pMem;
  78003. preupdate_new_out:
  78004. sqlite3Error(db, rc);
  78005. return sqlite3ApiExit(db, rc);
  78006. }
  78007. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  78008. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  78009. /*
  78010. ** Return status data for a single loop within query pStmt.
  78011. */
  78012. SQLITE_API int sqlite3_stmt_scanstatus(
  78013. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  78014. int idx, /* Index of loop to report on */
  78015. int iScanStatusOp, /* Which metric to return */
  78016. void *pOut /* OUT: Write the answer here */
  78017. ){
  78018. Vdbe *p = (Vdbe*)pStmt;
  78019. ScanStatus *pScan;
  78020. if( idx<0 || idx>=p->nScan ) return 1;
  78021. pScan = &p->aScan[idx];
  78022. switch( iScanStatusOp ){
  78023. case SQLITE_SCANSTAT_NLOOP: {
  78024. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  78025. break;
  78026. }
  78027. case SQLITE_SCANSTAT_NVISIT: {
  78028. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  78029. break;
  78030. }
  78031. case SQLITE_SCANSTAT_EST: {
  78032. double r = 1.0;
  78033. LogEst x = pScan->nEst;
  78034. while( x<100 ){
  78035. x += 10;
  78036. r *= 0.5;
  78037. }
  78038. *(double*)pOut = r*sqlite3LogEstToInt(x);
  78039. break;
  78040. }
  78041. case SQLITE_SCANSTAT_NAME: {
  78042. *(const char**)pOut = pScan->zName;
  78043. break;
  78044. }
  78045. case SQLITE_SCANSTAT_EXPLAIN: {
  78046. if( pScan->addrExplain ){
  78047. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  78048. }else{
  78049. *(const char**)pOut = 0;
  78050. }
  78051. break;
  78052. }
  78053. case SQLITE_SCANSTAT_SELECTID: {
  78054. if( pScan->addrExplain ){
  78055. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  78056. }else{
  78057. *(int*)pOut = -1;
  78058. }
  78059. break;
  78060. }
  78061. default: {
  78062. return 1;
  78063. }
  78064. }
  78065. return 0;
  78066. }
  78067. /*
  78068. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  78069. */
  78070. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  78071. Vdbe *p = (Vdbe*)pStmt;
  78072. memset(p->anExec, 0, p->nOp * sizeof(i64));
  78073. }
  78074. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  78075. /************** End of vdbeapi.c *********************************************/
  78076. /************** Begin file vdbetrace.c ***************************************/
  78077. /*
  78078. ** 2009 November 25
  78079. **
  78080. ** The author disclaims copyright to this source code. In place of
  78081. ** a legal notice, here is a blessing:
  78082. **
  78083. ** May you do good and not evil.
  78084. ** May you find forgiveness for yourself and forgive others.
  78085. ** May you share freely, never taking more than you give.
  78086. **
  78087. *************************************************************************
  78088. **
  78089. ** This file contains code used to insert the values of host parameters
  78090. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  78091. **
  78092. ** The Vdbe parse-tree explainer is also found here.
  78093. */
  78094. /* #include "sqliteInt.h" */
  78095. /* #include "vdbeInt.h" */
  78096. #ifndef SQLITE_OMIT_TRACE
  78097. /*
  78098. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  78099. ** bytes in this text up to but excluding the first character in
  78100. ** a host parameter. If the text contains no host parameters, return
  78101. ** the total number of bytes in the text.
  78102. */
  78103. static int findNextHostParameter(const char *zSql, int *pnToken){
  78104. int tokenType;
  78105. int nTotal = 0;
  78106. int n;
  78107. *pnToken = 0;
  78108. while( zSql[0] ){
  78109. n = sqlite3GetToken((u8*)zSql, &tokenType);
  78110. assert( n>0 && tokenType!=TK_ILLEGAL );
  78111. if( tokenType==TK_VARIABLE ){
  78112. *pnToken = n;
  78113. break;
  78114. }
  78115. nTotal += n;
  78116. zSql += n;
  78117. }
  78118. return nTotal;
  78119. }
  78120. /*
  78121. ** This function returns a pointer to a nul-terminated string in memory
  78122. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  78123. ** string contains a copy of zRawSql but with host parameters expanded to
  78124. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  78125. ** then the returned string holds a copy of zRawSql with "-- " prepended
  78126. ** to each line of text.
  78127. **
  78128. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  78129. ** then long strings and blobs are truncated to that many bytes. This
  78130. ** can be used to prevent unreasonably large trace strings when dealing
  78131. ** with large (multi-megabyte) strings and blobs.
  78132. **
  78133. ** The calling function is responsible for making sure the memory returned
  78134. ** is eventually freed.
  78135. **
  78136. ** ALGORITHM: Scan the input string looking for host parameters in any of
  78137. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  78138. ** string literals, quoted identifier names, and comments. For text forms,
  78139. ** the host parameter index is found by scanning the prepared
  78140. ** statement for the corresponding OP_Variable opcode. Once the host
  78141. ** parameter index is known, locate the value in p->aVar[]. Then render
  78142. ** the value as a literal in place of the host parameter name.
  78143. */
  78144. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  78145. Vdbe *p, /* The prepared statement being evaluated */
  78146. const char *zRawSql /* Raw text of the SQL statement */
  78147. ){
  78148. sqlite3 *db; /* The database connection */
  78149. int idx = 0; /* Index of a host parameter */
  78150. int nextIndex = 1; /* Index of next ? host parameter */
  78151. int n; /* Length of a token prefix */
  78152. int nToken; /* Length of the parameter token */
  78153. int i; /* Loop counter */
  78154. Mem *pVar; /* Value of a host parameter */
  78155. StrAccum out; /* Accumulate the output here */
  78156. #ifndef SQLITE_OMIT_UTF16
  78157. Mem utf8; /* Used to convert UTF16 into UTF8 for display */
  78158. #endif
  78159. char zBase[100]; /* Initial working space */
  78160. db = p->db;
  78161. sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
  78162. db->aLimit[SQLITE_LIMIT_LENGTH]);
  78163. if( db->nVdbeExec>1 ){
  78164. while( *zRawSql ){
  78165. const char *zStart = zRawSql;
  78166. while( *(zRawSql++)!='\n' && *zRawSql );
  78167. sqlite3_str_append(&out, "-- ", 3);
  78168. assert( (zRawSql - zStart) > 0 );
  78169. sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));
  78170. }
  78171. }else if( p->nVar==0 ){
  78172. sqlite3_str_append(&out, zRawSql, sqlite3Strlen30(zRawSql));
  78173. }else{
  78174. while( zRawSql[0] ){
  78175. n = findNextHostParameter(zRawSql, &nToken);
  78176. assert( n>0 );
  78177. sqlite3_str_append(&out, zRawSql, n);
  78178. zRawSql += n;
  78179. assert( zRawSql[0] || nToken==0 );
  78180. if( nToken==0 ) break;
  78181. if( zRawSql[0]=='?' ){
  78182. if( nToken>1 ){
  78183. assert( sqlite3Isdigit(zRawSql[1]) );
  78184. sqlite3GetInt32(&zRawSql[1], &idx);
  78185. }else{
  78186. idx = nextIndex;
  78187. }
  78188. }else{
  78189. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  78190. zRawSql[0]=='@' || zRawSql[0]=='#' );
  78191. testcase( zRawSql[0]==':' );
  78192. testcase( zRawSql[0]=='$' );
  78193. testcase( zRawSql[0]=='@' );
  78194. testcase( zRawSql[0]=='#' );
  78195. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  78196. assert( idx>0 );
  78197. }
  78198. zRawSql += nToken;
  78199. nextIndex = idx + 1;
  78200. assert( idx>0 && idx<=p->nVar );
  78201. pVar = &p->aVar[idx-1];
  78202. if( pVar->flags & MEM_Null ){
  78203. sqlite3_str_append(&out, "NULL", 4);
  78204. }else if( pVar->flags & MEM_Int ){
  78205. sqlite3_str_appendf(&out, "%lld", pVar->u.i);
  78206. }else if( pVar->flags & MEM_Real ){
  78207. sqlite3_str_appendf(&out, "%!.15g", pVar->u.r);
  78208. }else if( pVar->flags & MEM_Str ){
  78209. int nOut; /* Number of bytes of the string text to include in output */
  78210. #ifndef SQLITE_OMIT_UTF16
  78211. u8 enc = ENC(db);
  78212. if( enc!=SQLITE_UTF8 ){
  78213. memset(&utf8, 0, sizeof(utf8));
  78214. utf8.db = db;
  78215. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  78216. if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
  78217. out.accError = SQLITE_NOMEM;
  78218. out.nAlloc = 0;
  78219. }
  78220. pVar = &utf8;
  78221. }
  78222. #endif
  78223. nOut = pVar->n;
  78224. #ifdef SQLITE_TRACE_SIZE_LIMIT
  78225. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  78226. nOut = SQLITE_TRACE_SIZE_LIMIT;
  78227. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  78228. }
  78229. #endif
  78230. sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
  78231. #ifdef SQLITE_TRACE_SIZE_LIMIT
  78232. if( nOut<pVar->n ){
  78233. sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
  78234. }
  78235. #endif
  78236. #ifndef SQLITE_OMIT_UTF16
  78237. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  78238. #endif
  78239. }else if( pVar->flags & MEM_Zero ){
  78240. sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero);
  78241. }else{
  78242. int nOut; /* Number of bytes of the blob to include in output */
  78243. assert( pVar->flags & MEM_Blob );
  78244. sqlite3_str_append(&out, "x'", 2);
  78245. nOut = pVar->n;
  78246. #ifdef SQLITE_TRACE_SIZE_LIMIT
  78247. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  78248. #endif
  78249. for(i=0; i<nOut; i++){
  78250. sqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff);
  78251. }
  78252. sqlite3_str_append(&out, "'", 1);
  78253. #ifdef SQLITE_TRACE_SIZE_LIMIT
  78254. if( nOut<pVar->n ){
  78255. sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
  78256. }
  78257. #endif
  78258. }
  78259. }
  78260. }
  78261. if( out.accError ) sqlite3_str_reset(&out);
  78262. return sqlite3StrAccumFinish(&out);
  78263. }
  78264. #endif /* #ifndef SQLITE_OMIT_TRACE */
  78265. /************** End of vdbetrace.c *******************************************/
  78266. /************** Begin file vdbe.c ********************************************/
  78267. /*
  78268. ** 2001 September 15
  78269. **
  78270. ** The author disclaims copyright to this source code. In place of
  78271. ** a legal notice, here is a blessing:
  78272. **
  78273. ** May you do good and not evil.
  78274. ** May you find forgiveness for yourself and forgive others.
  78275. ** May you share freely, never taking more than you give.
  78276. **
  78277. *************************************************************************
  78278. ** The code in this file implements the function that runs the
  78279. ** bytecode of a prepared statement.
  78280. **
  78281. ** Various scripts scan this source file in order to generate HTML
  78282. ** documentation, headers files, or other derived files. The formatting
  78283. ** of the code in this file is, therefore, important. See other comments
  78284. ** in this file for details. If in doubt, do not deviate from existing
  78285. ** commenting and indentation practices when changing or adding code.
  78286. */
  78287. /* #include "sqliteInt.h" */
  78288. /* #include "vdbeInt.h" */
  78289. /*
  78290. ** Invoke this macro on memory cells just prior to changing the
  78291. ** value of the cell. This macro verifies that shallow copies are
  78292. ** not misused. A shallow copy of a string or blob just copies a
  78293. ** pointer to the string or blob, not the content. If the original
  78294. ** is changed while the copy is still in use, the string or blob might
  78295. ** be changed out from under the copy. This macro verifies that nothing
  78296. ** like that ever happens.
  78297. */
  78298. #ifdef SQLITE_DEBUG
  78299. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  78300. #else
  78301. # define memAboutToChange(P,M)
  78302. #endif
  78303. /*
  78304. ** The following global variable is incremented every time a cursor
  78305. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  78306. ** procedures use this information to make sure that indices are
  78307. ** working correctly. This variable has no function other than to
  78308. ** help verify the correct operation of the library.
  78309. */
  78310. #ifdef SQLITE_TEST
  78311. SQLITE_API int sqlite3_search_count = 0;
  78312. #endif
  78313. /*
  78314. ** When this global variable is positive, it gets decremented once before
  78315. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  78316. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  78317. **
  78318. ** This facility is used for testing purposes only. It does not function
  78319. ** in an ordinary build.
  78320. */
  78321. #ifdef SQLITE_TEST
  78322. SQLITE_API int sqlite3_interrupt_count = 0;
  78323. #endif
  78324. /*
  78325. ** The next global variable is incremented each type the OP_Sort opcode
  78326. ** is executed. The test procedures use this information to make sure that
  78327. ** sorting is occurring or not occurring at appropriate times. This variable
  78328. ** has no function other than to help verify the correct operation of the
  78329. ** library.
  78330. */
  78331. #ifdef SQLITE_TEST
  78332. SQLITE_API int sqlite3_sort_count = 0;
  78333. #endif
  78334. /*
  78335. ** The next global variable records the size of the largest MEM_Blob
  78336. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  78337. ** use this information to make sure that the zero-blob functionality
  78338. ** is working correctly. This variable has no function other than to
  78339. ** help verify the correct operation of the library.
  78340. */
  78341. #ifdef SQLITE_TEST
  78342. SQLITE_API int sqlite3_max_blobsize = 0;
  78343. static void updateMaxBlobsize(Mem *p){
  78344. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  78345. sqlite3_max_blobsize = p->n;
  78346. }
  78347. }
  78348. #endif
  78349. /*
  78350. ** This macro evaluates to true if either the update hook or the preupdate
  78351. ** hook are enabled for database connect DB.
  78352. */
  78353. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  78354. # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
  78355. #else
  78356. # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
  78357. #endif
  78358. /*
  78359. ** The next global variable is incremented each time the OP_Found opcode
  78360. ** is executed. This is used to test whether or not the foreign key
  78361. ** operation implemented using OP_FkIsZero is working. This variable
  78362. ** has no function other than to help verify the correct operation of the
  78363. ** library.
  78364. */
  78365. #ifdef SQLITE_TEST
  78366. SQLITE_API int sqlite3_found_count = 0;
  78367. #endif
  78368. /*
  78369. ** Test a register to see if it exceeds the current maximum blob size.
  78370. ** If it does, record the new maximum blob size.
  78371. */
  78372. #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
  78373. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  78374. #else
  78375. # define UPDATE_MAX_BLOBSIZE(P)
  78376. #endif
  78377. /*
  78378. ** Invoke the VDBE coverage callback, if that callback is defined. This
  78379. ** feature is used for test suite validation only and does not appear an
  78380. ** production builds.
  78381. **
  78382. ** M is the type of branch. I is the direction taken for this instance of
  78383. ** the branch.
  78384. **
  78385. ** M: 2 - two-way branch (I=0: fall-thru 1: jump )
  78386. ** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL )
  78387. ** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3)
  78388. **
  78389. ** In other words, if M is 2, then I is either 0 (for fall-through) or
  78390. ** 1 (for when the branch is taken). If M is 3, the I is 0 for an
  78391. ** ordinary fall-through, I is 1 if the branch was taken, and I is 2
  78392. ** if the result of comparison is NULL. For M=3, I=2 the jump may or
  78393. ** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5.
  78394. ** When M is 4, that means that an OP_Jump is being run. I is 0, 1, or 2
  78395. ** depending on if the operands are less than, equal, or greater than.
  78396. **
  78397. ** iSrcLine is the source code line (from the __LINE__ macro) that
  78398. ** generated the VDBE instruction combined with flag bits. The source
  78399. ** code line number is in the lower 24 bits of iSrcLine and the upper
  78400. ** 8 bytes are flags. The lower three bits of the flags indicate
  78401. ** values for I that should never occur. For example, if the branch is
  78402. ** always taken, the flags should be 0x05 since the fall-through and
  78403. ** alternate branch are never taken. If a branch is never taken then
  78404. ** flags should be 0x06 since only the fall-through approach is allowed.
  78405. **
  78406. ** Bit 0x08 of the flags indicates an OP_Jump opcode that is only
  78407. ** interested in equal or not-equal. In other words, I==0 and I==2
  78408. ** should be treated as equivalent
  78409. **
  78410. ** Since only a line number is retained, not the filename, this macro
  78411. ** only works for amalgamation builds. But that is ok, since these macros
  78412. ** should be no-ops except for special builds used to measure test coverage.
  78413. */
  78414. #if !defined(SQLITE_VDBE_COVERAGE)
  78415. # define VdbeBranchTaken(I,M)
  78416. #else
  78417. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  78418. static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){
  78419. u8 mNever;
  78420. assert( I<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */
  78421. assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
  78422. assert( I<M ); /* I can only be 2 if M is 3 or 4 */
  78423. /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */
  78424. I = 1<<I;
  78425. /* The upper 8 bits of iSrcLine are flags. The lower three bits of
  78426. ** the flags indicate directions that the branch can never go. If
  78427. ** a branch really does go in one of those directions, assert right
  78428. ** away. */
  78429. mNever = iSrcLine >> 24;
  78430. assert( (I & mNever)==0 );
  78431. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  78432. /* Invoke the branch coverage callback with three arguments:
  78433. ** iSrcLine - the line number of the VdbeCoverage() macro, with
  78434. ** flags removed.
  78435. ** I - Mask of bits 0x07 indicating which cases are are
  78436. ** fulfilled by this instance of the jump. 0x01 means
  78437. ** fall-thru, 0x02 means taken, 0x04 means NULL. Any
  78438. ** impossible cases (ex: if the comparison is never NULL)
  78439. ** are filled in automatically so that the coverage
  78440. ** measurement logic does not flag those impossible cases
  78441. ** as missed coverage.
  78442. ** M - Type of jump. Same as M argument above
  78443. */
  78444. I |= mNever;
  78445. if( M==2 ) I |= 0x04;
  78446. if( M==4 ){
  78447. I |= 0x08;
  78448. if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/
  78449. }
  78450. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  78451. iSrcLine&0xffffff, I, M);
  78452. }
  78453. #endif
  78454. /*
  78455. ** Convert the given register into a string if it isn't one
  78456. ** already. Return non-zero if a malloc() fails.
  78457. */
  78458. #define Stringify(P, enc) \
  78459. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  78460. { goto no_mem; }
  78461. /*
  78462. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  78463. ** a pointer to a dynamically allocated string where some other entity
  78464. ** is responsible for deallocating that string. Because the register
  78465. ** does not control the string, it might be deleted without the register
  78466. ** knowing it.
  78467. **
  78468. ** This routine converts an ephemeral string into a dynamically allocated
  78469. ** string that the register itself controls. In other words, it
  78470. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  78471. */
  78472. #define Deephemeralize(P) \
  78473. if( ((P)->flags&MEM_Ephem)!=0 \
  78474. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  78475. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  78476. #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
  78477. /*
  78478. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  78479. ** if we run out of memory.
  78480. */
  78481. static VdbeCursor *allocateCursor(
  78482. Vdbe *p, /* The virtual machine */
  78483. int iCur, /* Index of the new VdbeCursor */
  78484. int nField, /* Number of fields in the table or index */
  78485. int iDb, /* Database the cursor belongs to, or -1 */
  78486. u8 eCurType /* Type of the new cursor */
  78487. ){
  78488. /* Find the memory cell that will be used to store the blob of memory
  78489. ** required for this VdbeCursor structure. It is convenient to use a
  78490. ** vdbe memory cell to manage the memory allocation required for a
  78491. ** VdbeCursor structure for the following reasons:
  78492. **
  78493. ** * Sometimes cursor numbers are used for a couple of different
  78494. ** purposes in a vdbe program. The different uses might require
  78495. ** different sized allocations. Memory cells provide growable
  78496. ** allocations.
  78497. **
  78498. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  78499. ** be freed lazily via the sqlite3_release_memory() API. This
  78500. ** minimizes the number of malloc calls made by the system.
  78501. **
  78502. ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
  78503. ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
  78504. ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
  78505. */
  78506. Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
  78507. int nByte;
  78508. VdbeCursor *pCx = 0;
  78509. nByte =
  78510. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  78511. (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
  78512. assert( iCur>=0 && iCur<p->nCursor );
  78513. if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
  78514. /* Before calling sqlite3VdbeFreeCursor(), ensure the isEphemeral flag
  78515. ** is clear. Otherwise, if this is an ephemeral cursor created by
  78516. ** OP_OpenDup, the cursor will not be closed and will still be part
  78517. ** of a BtShared.pCursor list. */
  78518. p->apCsr[iCur]->isEphemeral = 0;
  78519. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  78520. p->apCsr[iCur] = 0;
  78521. }
  78522. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  78523. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  78524. memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
  78525. pCx->eCurType = eCurType;
  78526. pCx->iDb = iDb;
  78527. pCx->nField = nField;
  78528. pCx->aOffset = &pCx->aType[nField];
  78529. if( eCurType==CURTYPE_BTREE ){
  78530. pCx->uc.pCursor = (BtCursor*)
  78531. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  78532. sqlite3BtreeCursorZero(pCx->uc.pCursor);
  78533. }
  78534. }
  78535. return pCx;
  78536. }
  78537. /*
  78538. ** Try to convert a value into a numeric representation if we can
  78539. ** do so without loss of information. In other words, if the string
  78540. ** looks like a number, convert it into a number. If it does not
  78541. ** look like a number, leave it alone.
  78542. **
  78543. ** If the bTryForInt flag is true, then extra effort is made to give
  78544. ** an integer representation. Strings that look like floating point
  78545. ** values but which have no fractional component (example: '48.00')
  78546. ** will have a MEM_Int representation when bTryForInt is true.
  78547. **
  78548. ** If bTryForInt is false, then if the input string contains a decimal
  78549. ** point or exponential notation, the result is only MEM_Real, even
  78550. ** if there is an exact integer representation of the quantity.
  78551. */
  78552. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  78553. double rValue;
  78554. i64 iValue;
  78555. u8 enc = pRec->enc;
  78556. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  78557. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  78558. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  78559. pRec->u.i = iValue;
  78560. pRec->flags |= MEM_Int;
  78561. }else{
  78562. pRec->u.r = rValue;
  78563. pRec->flags |= MEM_Real;
  78564. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  78565. }
  78566. /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
  78567. ** string representation after computing a numeric equivalent, because the
  78568. ** string representation might not be the canonical representation for the
  78569. ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
  78570. pRec->flags &= ~MEM_Str;
  78571. }
  78572. /*
  78573. ** Processing is determine by the affinity parameter:
  78574. **
  78575. ** SQLITE_AFF_INTEGER:
  78576. ** SQLITE_AFF_REAL:
  78577. ** SQLITE_AFF_NUMERIC:
  78578. ** Try to convert pRec to an integer representation or a
  78579. ** floating-point representation if an integer representation
  78580. ** is not possible. Note that the integer representation is
  78581. ** always preferred, even if the affinity is REAL, because
  78582. ** an integer representation is more space efficient on disk.
  78583. **
  78584. ** SQLITE_AFF_TEXT:
  78585. ** Convert pRec to a text representation.
  78586. **
  78587. ** SQLITE_AFF_BLOB:
  78588. ** No-op. pRec is unchanged.
  78589. */
  78590. static void applyAffinity(
  78591. Mem *pRec, /* The value to apply affinity to */
  78592. char affinity, /* The affinity to be applied */
  78593. u8 enc /* Use this text encoding */
  78594. ){
  78595. if( affinity>=SQLITE_AFF_NUMERIC ){
  78596. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  78597. || affinity==SQLITE_AFF_NUMERIC );
  78598. if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  78599. if( (pRec->flags & MEM_Real)==0 ){
  78600. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  78601. }else{
  78602. sqlite3VdbeIntegerAffinity(pRec);
  78603. }
  78604. }
  78605. }else if( affinity==SQLITE_AFF_TEXT ){
  78606. /* Only attempt the conversion to TEXT if there is an integer or real
  78607. ** representation (blob and NULL do not get converted) but no string
  78608. ** representation. It would be harmless to repeat the conversion if
  78609. ** there is already a string rep, but it is pointless to waste those
  78610. ** CPU cycles. */
  78611. if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
  78612. if( (pRec->flags&(MEM_Real|MEM_Int)) ){
  78613. sqlite3VdbeMemStringify(pRec, enc, 1);
  78614. }
  78615. }
  78616. pRec->flags &= ~(MEM_Real|MEM_Int);
  78617. }
  78618. }
  78619. /*
  78620. ** Try to convert the type of a function argument or a result column
  78621. ** into a numeric representation. Use either INTEGER or REAL whichever
  78622. ** is appropriate. But only do the conversion if it is possible without
  78623. ** loss of information and return the revised type of the argument.
  78624. */
  78625. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  78626. int eType = sqlite3_value_type(pVal);
  78627. if( eType==SQLITE_TEXT ){
  78628. Mem *pMem = (Mem*)pVal;
  78629. applyNumericAffinity(pMem, 0);
  78630. eType = sqlite3_value_type(pVal);
  78631. }
  78632. return eType;
  78633. }
  78634. /*
  78635. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  78636. ** not the internal Mem* type.
  78637. */
  78638. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  78639. sqlite3_value *pVal,
  78640. u8 affinity,
  78641. u8 enc
  78642. ){
  78643. applyAffinity((Mem *)pVal, affinity, enc);
  78644. }
  78645. /*
  78646. ** pMem currently only holds a string type (or maybe a BLOB that we can
  78647. ** interpret as a string if we want to). Compute its corresponding
  78648. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  78649. ** accordingly.
  78650. */
  78651. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  78652. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  78653. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  78654. ExpandBlob(pMem);
  78655. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  78656. return 0;
  78657. }
  78658. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
  78659. return MEM_Int;
  78660. }
  78661. return MEM_Real;
  78662. }
  78663. /*
  78664. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  78665. ** none.
  78666. **
  78667. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  78668. ** But it does set pMem->u.r and pMem->u.i appropriately.
  78669. */
  78670. static u16 numericType(Mem *pMem){
  78671. if( pMem->flags & (MEM_Int|MEM_Real) ){
  78672. return pMem->flags & (MEM_Int|MEM_Real);
  78673. }
  78674. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  78675. return computeNumericType(pMem);
  78676. }
  78677. return 0;
  78678. }
  78679. #ifdef SQLITE_DEBUG
  78680. /*
  78681. ** Write a nice string representation of the contents of cell pMem
  78682. ** into buffer zBuf, length nBuf.
  78683. */
  78684. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  78685. char *zCsr = zBuf;
  78686. int f = pMem->flags;
  78687. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  78688. if( f&MEM_Blob ){
  78689. int i;
  78690. char c;
  78691. if( f & MEM_Dyn ){
  78692. c = 'z';
  78693. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  78694. }else if( f & MEM_Static ){
  78695. c = 't';
  78696. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  78697. }else if( f & MEM_Ephem ){
  78698. c = 'e';
  78699. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  78700. }else{
  78701. c = 's';
  78702. }
  78703. *(zCsr++) = c;
  78704. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  78705. zCsr += sqlite3Strlen30(zCsr);
  78706. for(i=0; i<16 && i<pMem->n; i++){
  78707. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  78708. zCsr += sqlite3Strlen30(zCsr);
  78709. }
  78710. for(i=0; i<16 && i<pMem->n; i++){
  78711. char z = pMem->z[i];
  78712. if( z<32 || z>126 ) *zCsr++ = '.';
  78713. else *zCsr++ = z;
  78714. }
  78715. *(zCsr++) = ']';
  78716. if( f & MEM_Zero ){
  78717. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  78718. zCsr += sqlite3Strlen30(zCsr);
  78719. }
  78720. *zCsr = '\0';
  78721. }else if( f & MEM_Str ){
  78722. int j, k;
  78723. zBuf[0] = ' ';
  78724. if( f & MEM_Dyn ){
  78725. zBuf[1] = 'z';
  78726. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  78727. }else if( f & MEM_Static ){
  78728. zBuf[1] = 't';
  78729. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  78730. }else if( f & MEM_Ephem ){
  78731. zBuf[1] = 'e';
  78732. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  78733. }else{
  78734. zBuf[1] = 's';
  78735. }
  78736. k = 2;
  78737. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  78738. k += sqlite3Strlen30(&zBuf[k]);
  78739. zBuf[k++] = '[';
  78740. for(j=0; j<15 && j<pMem->n; j++){
  78741. u8 c = pMem->z[j];
  78742. if( c>=0x20 && c<0x7f ){
  78743. zBuf[k++] = c;
  78744. }else{
  78745. zBuf[k++] = '.';
  78746. }
  78747. }
  78748. zBuf[k++] = ']';
  78749. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  78750. k += sqlite3Strlen30(&zBuf[k]);
  78751. zBuf[k++] = 0;
  78752. }
  78753. }
  78754. #endif
  78755. #ifdef SQLITE_DEBUG
  78756. /*
  78757. ** Print the value of a register for tracing purposes:
  78758. */
  78759. static void memTracePrint(Mem *p){
  78760. if( p->flags & MEM_Undefined ){
  78761. printf(" undefined");
  78762. }else if( p->flags & MEM_Null ){
  78763. printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
  78764. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  78765. printf(" si:%lld", p->u.i);
  78766. }else if( p->flags & MEM_Int ){
  78767. printf(" i:%lld", p->u.i);
  78768. #ifndef SQLITE_OMIT_FLOATING_POINT
  78769. }else if( p->flags & MEM_Real ){
  78770. printf(" r:%g", p->u.r);
  78771. #endif
  78772. }else if( sqlite3VdbeMemIsRowSet(p) ){
  78773. printf(" (rowset)");
  78774. }else{
  78775. char zBuf[200];
  78776. sqlite3VdbeMemPrettyPrint(p, zBuf);
  78777. printf(" %s", zBuf);
  78778. }
  78779. if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
  78780. }
  78781. static void registerTrace(int iReg, Mem *p){
  78782. printf("REG[%d] = ", iReg);
  78783. memTracePrint(p);
  78784. printf("\n");
  78785. sqlite3VdbeCheckMemInvariants(p);
  78786. }
  78787. #endif
  78788. #ifdef SQLITE_DEBUG
  78789. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  78790. #else
  78791. # define REGISTER_TRACE(R,M)
  78792. #endif
  78793. #ifdef VDBE_PROFILE
  78794. /*
  78795. ** hwtime.h contains inline assembler code for implementing
  78796. ** high-performance timing routines.
  78797. */
  78798. /************** Include hwtime.h in the middle of vdbe.c *********************/
  78799. /************** Begin file hwtime.h ******************************************/
  78800. /*
  78801. ** 2008 May 27
  78802. **
  78803. ** The author disclaims copyright to this source code. In place of
  78804. ** a legal notice, here is a blessing:
  78805. **
  78806. ** May you do good and not evil.
  78807. ** May you find forgiveness for yourself and forgive others.
  78808. ** May you share freely, never taking more than you give.
  78809. **
  78810. ******************************************************************************
  78811. **
  78812. ** This file contains inline asm code for retrieving "high-performance"
  78813. ** counters for x86 class CPUs.
  78814. */
  78815. #ifndef SQLITE_HWTIME_H
  78816. #define SQLITE_HWTIME_H
  78817. /*
  78818. ** The following routine only works on pentium-class (or newer) processors.
  78819. ** It uses the RDTSC opcode to read the cycle count value out of the
  78820. ** processor and returns that value. This can be used for high-res
  78821. ** profiling.
  78822. */
  78823. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  78824. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  78825. #if defined(__GNUC__)
  78826. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  78827. unsigned int lo, hi;
  78828. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  78829. return (sqlite_uint64)hi << 32 | lo;
  78830. }
  78831. #elif defined(_MSC_VER)
  78832. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  78833. __asm {
  78834. rdtsc
  78835. ret ; return value at EDX:EAX
  78836. }
  78837. }
  78838. #endif
  78839. #elif (defined(__GNUC__) && defined(__x86_64__))
  78840. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  78841. unsigned long val;
  78842. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  78843. return val;
  78844. }
  78845. #elif (defined(__GNUC__) && defined(__ppc__))
  78846. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  78847. unsigned long long retval;
  78848. unsigned long junk;
  78849. __asm__ __volatile__ ("\n\
  78850. 1: mftbu %1\n\
  78851. mftb %L0\n\
  78852. mftbu %0\n\
  78853. cmpw %0,%1\n\
  78854. bne 1b"
  78855. : "=r" (retval), "=r" (junk));
  78856. return retval;
  78857. }
  78858. #else
  78859. #error Need implementation of sqlite3Hwtime() for your platform.
  78860. /*
  78861. ** To compile without implementing sqlite3Hwtime() for your platform,
  78862. ** you can remove the above #error and use the following
  78863. ** stub function. You will lose timing support for many
  78864. ** of the debugging and testing utilities, but it should at
  78865. ** least compile and run.
  78866. */
  78867. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  78868. #endif
  78869. #endif /* !defined(SQLITE_HWTIME_H) */
  78870. /************** End of hwtime.h **********************************************/
  78871. /************** Continuing where we left off in vdbe.c ***********************/
  78872. #endif
  78873. #ifndef NDEBUG
  78874. /*
  78875. ** This function is only called from within an assert() expression. It
  78876. ** checks that the sqlite3.nTransaction variable is correctly set to
  78877. ** the number of non-transaction savepoints currently in the
  78878. ** linked list starting at sqlite3.pSavepoint.
  78879. **
  78880. ** Usage:
  78881. **
  78882. ** assert( checkSavepointCount(db) );
  78883. */
  78884. static int checkSavepointCount(sqlite3 *db){
  78885. int n = 0;
  78886. Savepoint *p;
  78887. for(p=db->pSavepoint; p; p=p->pNext) n++;
  78888. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  78889. return 1;
  78890. }
  78891. #endif
  78892. /*
  78893. ** Return the register of pOp->p2 after first preparing it to be
  78894. ** overwritten with an integer value.
  78895. */
  78896. static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
  78897. sqlite3VdbeMemSetNull(pOut);
  78898. pOut->flags = MEM_Int;
  78899. return pOut;
  78900. }
  78901. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  78902. Mem *pOut;
  78903. assert( pOp->p2>0 );
  78904. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  78905. pOut = &p->aMem[pOp->p2];
  78906. memAboutToChange(p, pOut);
  78907. if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
  78908. return out2PrereleaseWithClear(pOut);
  78909. }else{
  78910. pOut->flags = MEM_Int;
  78911. return pOut;
  78912. }
  78913. }
  78914. /*
  78915. ** Execute as much of a VDBE program as we can.
  78916. ** This is the core of sqlite3_step().
  78917. */
  78918. SQLITE_PRIVATE int sqlite3VdbeExec(
  78919. Vdbe *p /* The VDBE */
  78920. ){
  78921. Op *aOp = p->aOp; /* Copy of p->aOp */
  78922. Op *pOp = aOp; /* Current operation */
  78923. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  78924. Op *pOrigOp; /* Value of pOp at the top of the loop */
  78925. #endif
  78926. #ifdef SQLITE_DEBUG
  78927. int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
  78928. #endif
  78929. int rc = SQLITE_OK; /* Value to return */
  78930. sqlite3 *db = p->db; /* The database */
  78931. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  78932. u8 encoding = ENC(db); /* The database encoding */
  78933. int iCompare = 0; /* Result of last comparison */
  78934. unsigned nVmStep = 0; /* Number of virtual machine steps */
  78935. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  78936. unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
  78937. #endif
  78938. Mem *aMem = p->aMem; /* Copy of p->aMem */
  78939. Mem *pIn1 = 0; /* 1st input operand */
  78940. Mem *pIn2 = 0; /* 2nd input operand */
  78941. Mem *pIn3 = 0; /* 3rd input operand */
  78942. Mem *pOut = 0; /* Output operand */
  78943. #ifdef VDBE_PROFILE
  78944. u64 start; /* CPU clock count at start of opcode */
  78945. #endif
  78946. /*** INSERT STACK UNION HERE ***/
  78947. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  78948. sqlite3VdbeEnter(p);
  78949. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  78950. if( db->xProgress ){
  78951. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  78952. assert( 0 < db->nProgressOps );
  78953. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  78954. }else{
  78955. nProgressLimit = 0xffffffff;
  78956. }
  78957. #endif
  78958. if( p->rc==SQLITE_NOMEM ){
  78959. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  78960. ** sqlite3_column_text16() failed. */
  78961. goto no_mem;
  78962. }
  78963. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  78964. assert( p->bIsReader || p->readOnly!=0 );
  78965. p->iCurrentTime = 0;
  78966. assert( p->explain==0 );
  78967. p->pResultSet = 0;
  78968. db->busyHandler.nBusy = 0;
  78969. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  78970. sqlite3VdbeIOTraceSql(p);
  78971. #ifdef SQLITE_DEBUG
  78972. sqlite3BeginBenignMalloc();
  78973. if( p->pc==0
  78974. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  78975. ){
  78976. int i;
  78977. int once = 1;
  78978. sqlite3VdbePrintSql(p);
  78979. if( p->db->flags & SQLITE_VdbeListing ){
  78980. printf("VDBE Program Listing:\n");
  78981. for(i=0; i<p->nOp; i++){
  78982. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  78983. }
  78984. }
  78985. if( p->db->flags & SQLITE_VdbeEQP ){
  78986. for(i=0; i<p->nOp; i++){
  78987. if( aOp[i].opcode==OP_Explain ){
  78988. if( once ) printf("VDBE Query Plan:\n");
  78989. printf("%s\n", aOp[i].p4.z);
  78990. once = 0;
  78991. }
  78992. }
  78993. }
  78994. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  78995. }
  78996. sqlite3EndBenignMalloc();
  78997. #endif
  78998. for(pOp=&aOp[p->pc]; 1; pOp++){
  78999. /* Errors are detected by individual opcodes, with an immediate
  79000. ** jumps to abort_due_to_error. */
  79001. assert( rc==SQLITE_OK );
  79002. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  79003. #ifdef VDBE_PROFILE
  79004. start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  79005. #endif
  79006. nVmStep++;
  79007. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  79008. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  79009. #endif
  79010. /* Only allow tracing if SQLITE_DEBUG is defined.
  79011. */
  79012. #ifdef SQLITE_DEBUG
  79013. if( db->flags & SQLITE_VdbeTrace ){
  79014. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  79015. }
  79016. #endif
  79017. /* Check to see if we need to simulate an interrupt. This only happens
  79018. ** if we have a special test build.
  79019. */
  79020. #ifdef SQLITE_TEST
  79021. if( sqlite3_interrupt_count>0 ){
  79022. sqlite3_interrupt_count--;
  79023. if( sqlite3_interrupt_count==0 ){
  79024. sqlite3_interrupt(db);
  79025. }
  79026. }
  79027. #endif
  79028. /* Sanity checking on other operands */
  79029. #ifdef SQLITE_DEBUG
  79030. {
  79031. u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
  79032. if( (opProperty & OPFLG_IN1)!=0 ){
  79033. assert( pOp->p1>0 );
  79034. assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
  79035. assert( memIsValid(&aMem[pOp->p1]) );
  79036. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  79037. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  79038. }
  79039. if( (opProperty & OPFLG_IN2)!=0 ){
  79040. assert( pOp->p2>0 );
  79041. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  79042. assert( memIsValid(&aMem[pOp->p2]) );
  79043. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  79044. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  79045. }
  79046. if( (opProperty & OPFLG_IN3)!=0 ){
  79047. assert( pOp->p3>0 );
  79048. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  79049. assert( memIsValid(&aMem[pOp->p3]) );
  79050. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  79051. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  79052. }
  79053. if( (opProperty & OPFLG_OUT2)!=0 ){
  79054. assert( pOp->p2>0 );
  79055. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  79056. memAboutToChange(p, &aMem[pOp->p2]);
  79057. }
  79058. if( (opProperty & OPFLG_OUT3)!=0 ){
  79059. assert( pOp->p3>0 );
  79060. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  79061. memAboutToChange(p, &aMem[pOp->p3]);
  79062. }
  79063. }
  79064. #endif
  79065. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  79066. pOrigOp = pOp;
  79067. #endif
  79068. switch( pOp->opcode ){
  79069. /*****************************************************************************
  79070. ** What follows is a massive switch statement where each case implements a
  79071. ** separate instruction in the virtual machine. If we follow the usual
  79072. ** indentation conventions, each case should be indented by 6 spaces. But
  79073. ** that is a lot of wasted space on the left margin. So the code within
  79074. ** the switch statement will break with convention and be flush-left. Another
  79075. ** big comment (similar to this one) will mark the point in the code where
  79076. ** we transition back to normal indentation.
  79077. **
  79078. ** The formatting of each case is important. The makefile for SQLite
  79079. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  79080. ** file looking for lines that begin with "case OP_". The opcodes.h files
  79081. ** will be filled with #defines that give unique integer values to each
  79082. ** opcode and the opcodes.c file is filled with an array of strings where
  79083. ** each string is the symbolic name for the corresponding opcode. If the
  79084. ** case statement is followed by a comment of the form "/# same as ... #/"
  79085. ** that comment is used to determine the particular value of the opcode.
  79086. **
  79087. ** Other keywords in the comment that follows each case are used to
  79088. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  79089. ** Keywords include: in1, in2, in3, out2, out3. See
  79090. ** the mkopcodeh.awk script for additional information.
  79091. **
  79092. ** Documentation about VDBE opcodes is generated by scanning this file
  79093. ** for lines of that contain "Opcode:". That line and all subsequent
  79094. ** comment lines are used in the generation of the opcode.html documentation
  79095. ** file.
  79096. **
  79097. ** SUMMARY:
  79098. **
  79099. ** Formatting is important to scripts that scan this file.
  79100. ** Do not deviate from the formatting style currently in use.
  79101. **
  79102. *****************************************************************************/
  79103. /* Opcode: Goto * P2 * * *
  79104. **
  79105. ** An unconditional jump to address P2.
  79106. ** The next instruction executed will be
  79107. ** the one at index P2 from the beginning of
  79108. ** the program.
  79109. **
  79110. ** The P1 parameter is not actually used by this opcode. However, it
  79111. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  79112. ** that this Goto is the bottom of a loop and that the lines from P2 down
  79113. ** to the current line should be indented for EXPLAIN output.
  79114. */
  79115. case OP_Goto: { /* jump */
  79116. jump_to_p2_and_check_for_interrupt:
  79117. pOp = &aOp[pOp->p2 - 1];
  79118. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  79119. ** OP_VNext, or OP_SorterNext) all jump here upon
  79120. ** completion. Check to see if sqlite3_interrupt() has been called
  79121. ** or if the progress callback needs to be invoked.
  79122. **
  79123. ** This code uses unstructured "goto" statements and does not look clean.
  79124. ** But that is not due to sloppy coding habits. The code is written this
  79125. ** way for performance, to avoid having to run the interrupt and progress
  79126. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  79127. ** faster according to "valgrind --tool=cachegrind" */
  79128. check_for_interrupt:
  79129. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  79130. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  79131. /* Call the progress callback if it is configured and the required number
  79132. ** of VDBE ops have been executed (either since this invocation of
  79133. ** sqlite3VdbeExec() or since last time the progress callback was called).
  79134. ** If the progress callback returns non-zero, exit the virtual machine with
  79135. ** a return code SQLITE_ABORT.
  79136. */
  79137. while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
  79138. assert( db->nProgressOps!=0 );
  79139. nProgressLimit += db->nProgressOps;
  79140. if( db->xProgress(db->pProgressArg) ){
  79141. nProgressLimit = 0xffffffff;
  79142. rc = SQLITE_INTERRUPT;
  79143. goto abort_due_to_error;
  79144. }
  79145. }
  79146. #endif
  79147. break;
  79148. }
  79149. /* Opcode: Gosub P1 P2 * * *
  79150. **
  79151. ** Write the current address onto register P1
  79152. ** and then jump to address P2.
  79153. */
  79154. case OP_Gosub: { /* jump */
  79155. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  79156. pIn1 = &aMem[pOp->p1];
  79157. assert( VdbeMemDynamic(pIn1)==0 );
  79158. memAboutToChange(p, pIn1);
  79159. pIn1->flags = MEM_Int;
  79160. pIn1->u.i = (int)(pOp-aOp);
  79161. REGISTER_TRACE(pOp->p1, pIn1);
  79162. /* Most jump operations do a goto to this spot in order to update
  79163. ** the pOp pointer. */
  79164. jump_to_p2:
  79165. pOp = &aOp[pOp->p2 - 1];
  79166. break;
  79167. }
  79168. /* Opcode: Return P1 * * * *
  79169. **
  79170. ** Jump to the next instruction after the address in register P1. After
  79171. ** the jump, register P1 becomes undefined.
  79172. */
  79173. case OP_Return: { /* in1 */
  79174. pIn1 = &aMem[pOp->p1];
  79175. assert( pIn1->flags==MEM_Int );
  79176. pOp = &aOp[pIn1->u.i];
  79177. pIn1->flags = MEM_Undefined;
  79178. break;
  79179. }
  79180. /* Opcode: InitCoroutine P1 P2 P3 * *
  79181. **
  79182. ** Set up register P1 so that it will Yield to the coroutine
  79183. ** located at address P3.
  79184. **
  79185. ** If P2!=0 then the coroutine implementation immediately follows
  79186. ** this opcode. So jump over the coroutine implementation to
  79187. ** address P2.
  79188. **
  79189. ** See also: EndCoroutine
  79190. */
  79191. case OP_InitCoroutine: { /* jump */
  79192. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  79193. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  79194. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  79195. pOut = &aMem[pOp->p1];
  79196. assert( !VdbeMemDynamic(pOut) );
  79197. pOut->u.i = pOp->p3 - 1;
  79198. pOut->flags = MEM_Int;
  79199. if( pOp->p2 ) goto jump_to_p2;
  79200. break;
  79201. }
  79202. /* Opcode: EndCoroutine P1 * * * *
  79203. **
  79204. ** The instruction at the address in register P1 is a Yield.
  79205. ** Jump to the P2 parameter of that Yield.
  79206. ** After the jump, register P1 becomes undefined.
  79207. **
  79208. ** See also: InitCoroutine
  79209. */
  79210. case OP_EndCoroutine: { /* in1 */
  79211. VdbeOp *pCaller;
  79212. pIn1 = &aMem[pOp->p1];
  79213. assert( pIn1->flags==MEM_Int );
  79214. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  79215. pCaller = &aOp[pIn1->u.i];
  79216. assert( pCaller->opcode==OP_Yield );
  79217. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  79218. pOp = &aOp[pCaller->p2 - 1];
  79219. pIn1->flags = MEM_Undefined;
  79220. break;
  79221. }
  79222. /* Opcode: Yield P1 P2 * * *
  79223. **
  79224. ** Swap the program counter with the value in register P1. This
  79225. ** has the effect of yielding to a coroutine.
  79226. **
  79227. ** If the coroutine that is launched by this instruction ends with
  79228. ** Yield or Return then continue to the next instruction. But if
  79229. ** the coroutine launched by this instruction ends with
  79230. ** EndCoroutine, then jump to P2 rather than continuing with the
  79231. ** next instruction.
  79232. **
  79233. ** See also: InitCoroutine
  79234. */
  79235. case OP_Yield: { /* in1, jump */
  79236. int pcDest;
  79237. pIn1 = &aMem[pOp->p1];
  79238. assert( VdbeMemDynamic(pIn1)==0 );
  79239. pIn1->flags = MEM_Int;
  79240. pcDest = (int)pIn1->u.i;
  79241. pIn1->u.i = (int)(pOp - aOp);
  79242. REGISTER_TRACE(pOp->p1, pIn1);
  79243. pOp = &aOp[pcDest];
  79244. break;
  79245. }
  79246. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  79247. ** Synopsis: if r[P3]=null halt
  79248. **
  79249. ** Check the value in register P3. If it is NULL then Halt using
  79250. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  79251. ** value in register P3 is not NULL, then this routine is a no-op.
  79252. ** The P5 parameter should be 1.
  79253. */
  79254. case OP_HaltIfNull: { /* in3 */
  79255. pIn3 = &aMem[pOp->p3];
  79256. #ifdef SQLITE_DEBUG
  79257. if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
  79258. #endif
  79259. if( (pIn3->flags & MEM_Null)==0 ) break;
  79260. /* Fall through into OP_Halt */
  79261. }
  79262. /* Opcode: Halt P1 P2 * P4 P5
  79263. **
  79264. ** Exit immediately. All open cursors, etc are closed
  79265. ** automatically.
  79266. **
  79267. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  79268. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  79269. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  79270. ** whether or not to rollback the current transaction. Do not rollback
  79271. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  79272. ** then back out all changes that have occurred during this execution of the
  79273. ** VDBE, but do not rollback the transaction.
  79274. **
  79275. ** If P4 is not null then it is an error message string.
  79276. **
  79277. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  79278. **
  79279. ** 0: (no change)
  79280. ** 1: NOT NULL contraint failed: P4
  79281. ** 2: UNIQUE constraint failed: P4
  79282. ** 3: CHECK constraint failed: P4
  79283. ** 4: FOREIGN KEY constraint failed: P4
  79284. **
  79285. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  79286. ** omitted.
  79287. **
  79288. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  79289. ** every program. So a jump past the last instruction of the program
  79290. ** is the same as executing Halt.
  79291. */
  79292. case OP_Halt: {
  79293. VdbeFrame *pFrame;
  79294. int pcx;
  79295. pcx = (int)(pOp - aOp);
  79296. #ifdef SQLITE_DEBUG
  79297. if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
  79298. #endif
  79299. if( pOp->p1==SQLITE_OK && p->pFrame ){
  79300. /* Halt the sub-program. Return control to the parent frame. */
  79301. pFrame = p->pFrame;
  79302. p->pFrame = pFrame->pParent;
  79303. p->nFrame--;
  79304. sqlite3VdbeSetChanges(db, p->nChange);
  79305. pcx = sqlite3VdbeFrameRestore(pFrame);
  79306. if( pOp->p2==OE_Ignore ){
  79307. /* Instruction pcx is the OP_Program that invoked the sub-program
  79308. ** currently being halted. If the p2 instruction of this OP_Halt
  79309. ** instruction is set to OE_Ignore, then the sub-program is throwing
  79310. ** an IGNORE exception. In this case jump to the address specified
  79311. ** as the p2 of the calling OP_Program. */
  79312. pcx = p->aOp[pcx].p2-1;
  79313. }
  79314. aOp = p->aOp;
  79315. aMem = p->aMem;
  79316. pOp = &aOp[pcx];
  79317. break;
  79318. }
  79319. p->rc = pOp->p1;
  79320. p->errorAction = (u8)pOp->p2;
  79321. p->pc = pcx;
  79322. assert( pOp->p5<=4 );
  79323. if( p->rc ){
  79324. if( pOp->p5 ){
  79325. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  79326. "FOREIGN KEY" };
  79327. testcase( pOp->p5==1 );
  79328. testcase( pOp->p5==2 );
  79329. testcase( pOp->p5==3 );
  79330. testcase( pOp->p5==4 );
  79331. sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
  79332. if( pOp->p4.z ){
  79333. p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
  79334. }
  79335. }else{
  79336. sqlite3VdbeError(p, "%s", pOp->p4.z);
  79337. }
  79338. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
  79339. }
  79340. rc = sqlite3VdbeHalt(p);
  79341. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  79342. if( rc==SQLITE_BUSY ){
  79343. p->rc = SQLITE_BUSY;
  79344. }else{
  79345. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  79346. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  79347. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  79348. }
  79349. goto vdbe_return;
  79350. }
  79351. /* Opcode: Integer P1 P2 * * *
  79352. ** Synopsis: r[P2]=P1
  79353. **
  79354. ** The 32-bit integer value P1 is written into register P2.
  79355. */
  79356. case OP_Integer: { /* out2 */
  79357. pOut = out2Prerelease(p, pOp);
  79358. pOut->u.i = pOp->p1;
  79359. break;
  79360. }
  79361. /* Opcode: Int64 * P2 * P4 *
  79362. ** Synopsis: r[P2]=P4
  79363. **
  79364. ** P4 is a pointer to a 64-bit integer value.
  79365. ** Write that value into register P2.
  79366. */
  79367. case OP_Int64: { /* out2 */
  79368. pOut = out2Prerelease(p, pOp);
  79369. assert( pOp->p4.pI64!=0 );
  79370. pOut->u.i = *pOp->p4.pI64;
  79371. break;
  79372. }
  79373. #ifndef SQLITE_OMIT_FLOATING_POINT
  79374. /* Opcode: Real * P2 * P4 *
  79375. ** Synopsis: r[P2]=P4
  79376. **
  79377. ** P4 is a pointer to a 64-bit floating point value.
  79378. ** Write that value into register P2.
  79379. */
  79380. case OP_Real: { /* same as TK_FLOAT, out2 */
  79381. pOut = out2Prerelease(p, pOp);
  79382. pOut->flags = MEM_Real;
  79383. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  79384. pOut->u.r = *pOp->p4.pReal;
  79385. break;
  79386. }
  79387. #endif
  79388. /* Opcode: String8 * P2 * P4 *
  79389. ** Synopsis: r[P2]='P4'
  79390. **
  79391. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  79392. ** into a String opcode before it is executed for the first time. During
  79393. ** this transformation, the length of string P4 is computed and stored
  79394. ** as the P1 parameter.
  79395. */
  79396. case OP_String8: { /* same as TK_STRING, out2 */
  79397. assert( pOp->p4.z!=0 );
  79398. pOut = out2Prerelease(p, pOp);
  79399. pOp->opcode = OP_String;
  79400. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  79401. #ifndef SQLITE_OMIT_UTF16
  79402. if( encoding!=SQLITE_UTF8 ){
  79403. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  79404. assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
  79405. if( rc ) goto too_big;
  79406. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  79407. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  79408. assert( VdbeMemDynamic(pOut)==0 );
  79409. pOut->szMalloc = 0;
  79410. pOut->flags |= MEM_Static;
  79411. if( pOp->p4type==P4_DYNAMIC ){
  79412. sqlite3DbFree(db, pOp->p4.z);
  79413. }
  79414. pOp->p4type = P4_DYNAMIC;
  79415. pOp->p4.z = pOut->z;
  79416. pOp->p1 = pOut->n;
  79417. }
  79418. #endif
  79419. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  79420. goto too_big;
  79421. }
  79422. assert( rc==SQLITE_OK );
  79423. /* Fall through to the next case, OP_String */
  79424. }
  79425. /* Opcode: String P1 P2 P3 P4 P5
  79426. ** Synopsis: r[P2]='P4' (len=P1)
  79427. **
  79428. ** The string value P4 of length P1 (bytes) is stored in register P2.
  79429. **
  79430. ** If P3 is not zero and the content of register P3 is equal to P5, then
  79431. ** the datatype of the register P2 is converted to BLOB. The content is
  79432. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  79433. ** of a string, as if it had been CAST. In other words:
  79434. **
  79435. ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
  79436. */
  79437. case OP_String: { /* out2 */
  79438. assert( pOp->p4.z!=0 );
  79439. pOut = out2Prerelease(p, pOp);
  79440. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  79441. pOut->z = pOp->p4.z;
  79442. pOut->n = pOp->p1;
  79443. pOut->enc = encoding;
  79444. UPDATE_MAX_BLOBSIZE(pOut);
  79445. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  79446. if( pOp->p3>0 ){
  79447. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  79448. pIn3 = &aMem[pOp->p3];
  79449. assert( pIn3->flags & MEM_Int );
  79450. if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  79451. }
  79452. #endif
  79453. break;
  79454. }
  79455. /* Opcode: Null P1 P2 P3 * *
  79456. ** Synopsis: r[P2..P3]=NULL
  79457. **
  79458. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  79459. ** NULL into register P3 and every register in between P2 and P3. If P3
  79460. ** is less than P2 (typically P3 is zero) then only register P2 is
  79461. ** set to NULL.
  79462. **
  79463. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  79464. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  79465. ** OP_Ne or OP_Eq.
  79466. */
  79467. case OP_Null: { /* out2 */
  79468. int cnt;
  79469. u16 nullFlag;
  79470. pOut = out2Prerelease(p, pOp);
  79471. cnt = pOp->p3-pOp->p2;
  79472. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  79473. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  79474. pOut->n = 0;
  79475. #ifdef SQLITE_DEBUG
  79476. pOut->uTemp = 0;
  79477. #endif
  79478. while( cnt>0 ){
  79479. pOut++;
  79480. memAboutToChange(p, pOut);
  79481. sqlite3VdbeMemSetNull(pOut);
  79482. pOut->flags = nullFlag;
  79483. pOut->n = 0;
  79484. cnt--;
  79485. }
  79486. break;
  79487. }
  79488. /* Opcode: SoftNull P1 * * * *
  79489. ** Synopsis: r[P1]=NULL
  79490. **
  79491. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  79492. ** instruction, but do not free any string or blob memory associated with
  79493. ** the register, so that if the value was a string or blob that was
  79494. ** previously copied using OP_SCopy, the copies will continue to be valid.
  79495. */
  79496. case OP_SoftNull: {
  79497. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  79498. pOut = &aMem[pOp->p1];
  79499. pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
  79500. break;
  79501. }
  79502. /* Opcode: Blob P1 P2 * P4 *
  79503. ** Synopsis: r[P2]=P4 (len=P1)
  79504. **
  79505. ** P4 points to a blob of data P1 bytes long. Store this
  79506. ** blob in register P2.
  79507. */
  79508. case OP_Blob: { /* out2 */
  79509. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  79510. pOut = out2Prerelease(p, pOp);
  79511. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  79512. pOut->enc = encoding;
  79513. UPDATE_MAX_BLOBSIZE(pOut);
  79514. break;
  79515. }
  79516. /* Opcode: Variable P1 P2 * P4 *
  79517. ** Synopsis: r[P2]=parameter(P1,P4)
  79518. **
  79519. ** Transfer the values of bound parameter P1 into register P2
  79520. **
  79521. ** If the parameter is named, then its name appears in P4.
  79522. ** The P4 value is used by sqlite3_bind_parameter_name().
  79523. */
  79524. case OP_Variable: { /* out2 */
  79525. Mem *pVar; /* Value being transferred */
  79526. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  79527. assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
  79528. pVar = &p->aVar[pOp->p1 - 1];
  79529. if( sqlite3VdbeMemTooBig(pVar) ){
  79530. goto too_big;
  79531. }
  79532. pOut = &aMem[pOp->p2];
  79533. if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
  79534. memcpy(pOut, pVar, MEMCELLSIZE);
  79535. pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
  79536. pOut->flags |= MEM_Static|MEM_FromBind;
  79537. UPDATE_MAX_BLOBSIZE(pOut);
  79538. break;
  79539. }
  79540. /* Opcode: Move P1 P2 P3 * *
  79541. ** Synopsis: r[P2@P3]=r[P1@P3]
  79542. **
  79543. ** Move the P3 values in register P1..P1+P3-1 over into
  79544. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  79545. ** left holding a NULL. It is an error for register ranges
  79546. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  79547. ** for P3 to be less than 1.
  79548. */
  79549. case OP_Move: {
  79550. int n; /* Number of registers left to copy */
  79551. int p1; /* Register to copy from */
  79552. int p2; /* Register to copy to */
  79553. n = pOp->p3;
  79554. p1 = pOp->p1;
  79555. p2 = pOp->p2;
  79556. assert( n>0 && p1>0 && p2>0 );
  79557. assert( p1+n<=p2 || p2+n<=p1 );
  79558. pIn1 = &aMem[p1];
  79559. pOut = &aMem[p2];
  79560. do{
  79561. assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
  79562. assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
  79563. assert( memIsValid(pIn1) );
  79564. memAboutToChange(p, pOut);
  79565. sqlite3VdbeMemMove(pOut, pIn1);
  79566. #ifdef SQLITE_DEBUG
  79567. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  79568. pOut->pScopyFrom += pOp->p2 - p1;
  79569. }
  79570. #endif
  79571. Deephemeralize(pOut);
  79572. REGISTER_TRACE(p2++, pOut);
  79573. pIn1++;
  79574. pOut++;
  79575. }while( --n );
  79576. break;
  79577. }
  79578. /* Opcode: Copy P1 P2 P3 * *
  79579. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  79580. **
  79581. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  79582. **
  79583. ** This instruction makes a deep copy of the value. A duplicate
  79584. ** is made of any string or blob constant. See also OP_SCopy.
  79585. */
  79586. case OP_Copy: {
  79587. int n;
  79588. n = pOp->p3;
  79589. pIn1 = &aMem[pOp->p1];
  79590. pOut = &aMem[pOp->p2];
  79591. assert( pOut!=pIn1 );
  79592. while( 1 ){
  79593. memAboutToChange(p, pOut);
  79594. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  79595. Deephemeralize(pOut);
  79596. #ifdef SQLITE_DEBUG
  79597. pOut->pScopyFrom = 0;
  79598. #endif
  79599. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  79600. if( (n--)==0 ) break;
  79601. pOut++;
  79602. pIn1++;
  79603. }
  79604. break;
  79605. }
  79606. /* Opcode: SCopy P1 P2 * * *
  79607. ** Synopsis: r[P2]=r[P1]
  79608. **
  79609. ** Make a shallow copy of register P1 into register P2.
  79610. **
  79611. ** This instruction makes a shallow copy of the value. If the value
  79612. ** is a string or blob, then the copy is only a pointer to the
  79613. ** original and hence if the original changes so will the copy.
  79614. ** Worse, if the original is deallocated, the copy becomes invalid.
  79615. ** Thus the program must guarantee that the original will not change
  79616. ** during the lifetime of the copy. Use OP_Copy to make a complete
  79617. ** copy.
  79618. */
  79619. case OP_SCopy: { /* out2 */
  79620. pIn1 = &aMem[pOp->p1];
  79621. pOut = &aMem[pOp->p2];
  79622. assert( pOut!=pIn1 );
  79623. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  79624. #ifdef SQLITE_DEBUG
  79625. pOut->pScopyFrom = pIn1;
  79626. pOut->mScopyFlags = pIn1->flags;
  79627. #endif
  79628. break;
  79629. }
  79630. /* Opcode: IntCopy P1 P2 * * *
  79631. ** Synopsis: r[P2]=r[P1]
  79632. **
  79633. ** Transfer the integer value held in register P1 into register P2.
  79634. **
  79635. ** This is an optimized version of SCopy that works only for integer
  79636. ** values.
  79637. */
  79638. case OP_IntCopy: { /* out2 */
  79639. pIn1 = &aMem[pOp->p1];
  79640. assert( (pIn1->flags & MEM_Int)!=0 );
  79641. pOut = &aMem[pOp->p2];
  79642. sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
  79643. break;
  79644. }
  79645. /* Opcode: ResultRow P1 P2 * * *
  79646. ** Synopsis: output=r[P1@P2]
  79647. **
  79648. ** The registers P1 through P1+P2-1 contain a single row of
  79649. ** results. This opcode causes the sqlite3_step() call to terminate
  79650. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  79651. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  79652. ** the result row.
  79653. */
  79654. case OP_ResultRow: {
  79655. Mem *pMem;
  79656. int i;
  79657. assert( p->nResColumn==pOp->p2 );
  79658. assert( pOp->p1>0 );
  79659. assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
  79660. /* If this statement has violated immediate foreign key constraints, do
  79661. ** not return the number of rows modified. And do not RELEASE the statement
  79662. ** transaction. It needs to be rolled back. */
  79663. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  79664. assert( db->flags&SQLITE_CountRows );
  79665. assert( p->usesStmtJournal );
  79666. goto abort_due_to_error;
  79667. }
  79668. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  79669. ** DML statements invoke this opcode to return the number of rows
  79670. ** modified to the user. This is the only way that a VM that
  79671. ** opens a statement transaction may invoke this opcode.
  79672. **
  79673. ** In case this is such a statement, close any statement transaction
  79674. ** opened by this VM before returning control to the user. This is to
  79675. ** ensure that statement-transactions are always nested, not overlapping.
  79676. ** If the open statement-transaction is not closed here, then the user
  79677. ** may step another VM that opens its own statement transaction. This
  79678. ** may lead to overlapping statement transactions.
  79679. **
  79680. ** The statement transaction is never a top-level transaction. Hence
  79681. ** the RELEASE call below can never fail.
  79682. */
  79683. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  79684. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  79685. assert( rc==SQLITE_OK );
  79686. /* Invalidate all ephemeral cursor row caches */
  79687. p->cacheCtr = (p->cacheCtr + 2)|1;
  79688. /* Make sure the results of the current row are \000 terminated
  79689. ** and have an assigned type. The results are de-ephemeralized as
  79690. ** a side effect.
  79691. */
  79692. pMem = p->pResultSet = &aMem[pOp->p1];
  79693. for(i=0; i<pOp->p2; i++){
  79694. assert( memIsValid(&pMem[i]) );
  79695. Deephemeralize(&pMem[i]);
  79696. assert( (pMem[i].flags & MEM_Ephem)==0
  79697. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  79698. sqlite3VdbeMemNulTerminate(&pMem[i]);
  79699. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  79700. }
  79701. if( db->mallocFailed ) goto no_mem;
  79702. if( db->mTrace & SQLITE_TRACE_ROW ){
  79703. db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
  79704. }
  79705. /* Return SQLITE_ROW
  79706. */
  79707. p->pc = (int)(pOp - aOp) + 1;
  79708. rc = SQLITE_ROW;
  79709. goto vdbe_return;
  79710. }
  79711. /* Opcode: Concat P1 P2 P3 * *
  79712. ** Synopsis: r[P3]=r[P2]+r[P1]
  79713. **
  79714. ** Add the text in register P1 onto the end of the text in
  79715. ** register P2 and store the result in register P3.
  79716. ** If either the P1 or P2 text are NULL then store NULL in P3.
  79717. **
  79718. ** P3 = P2 || P1
  79719. **
  79720. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  79721. ** if P3 is the same register as P2, the implementation is able
  79722. ** to avoid a memcpy().
  79723. */
  79724. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  79725. i64 nByte;
  79726. pIn1 = &aMem[pOp->p1];
  79727. pIn2 = &aMem[pOp->p2];
  79728. pOut = &aMem[pOp->p3];
  79729. assert( pIn1!=pOut );
  79730. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  79731. sqlite3VdbeMemSetNull(pOut);
  79732. break;
  79733. }
  79734. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  79735. Stringify(pIn1, encoding);
  79736. Stringify(pIn2, encoding);
  79737. nByte = pIn1->n + pIn2->n;
  79738. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  79739. goto too_big;
  79740. }
  79741. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  79742. goto no_mem;
  79743. }
  79744. MemSetTypeFlag(pOut, MEM_Str);
  79745. if( pOut!=pIn2 ){
  79746. memcpy(pOut->z, pIn2->z, pIn2->n);
  79747. }
  79748. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  79749. pOut->z[nByte]=0;
  79750. pOut->z[nByte+1] = 0;
  79751. pOut->flags |= MEM_Term;
  79752. pOut->n = (int)nByte;
  79753. pOut->enc = encoding;
  79754. UPDATE_MAX_BLOBSIZE(pOut);
  79755. break;
  79756. }
  79757. /* Opcode: Add P1 P2 P3 * *
  79758. ** Synopsis: r[P3]=r[P1]+r[P2]
  79759. **
  79760. ** Add the value in register P1 to the value in register P2
  79761. ** and store the result in register P3.
  79762. ** If either input is NULL, the result is NULL.
  79763. */
  79764. /* Opcode: Multiply P1 P2 P3 * *
  79765. ** Synopsis: r[P3]=r[P1]*r[P2]
  79766. **
  79767. **
  79768. ** Multiply the value in register P1 by the value in register P2
  79769. ** and store the result in register P3.
  79770. ** If either input is NULL, the result is NULL.
  79771. */
  79772. /* Opcode: Subtract P1 P2 P3 * *
  79773. ** Synopsis: r[P3]=r[P2]-r[P1]
  79774. **
  79775. ** Subtract the value in register P1 from the value in register P2
  79776. ** and store the result in register P3.
  79777. ** If either input is NULL, the result is NULL.
  79778. */
  79779. /* Opcode: Divide P1 P2 P3 * *
  79780. ** Synopsis: r[P3]=r[P2]/r[P1]
  79781. **
  79782. ** Divide the value in register P1 by the value in register P2
  79783. ** and store the result in register P3 (P3=P2/P1). If the value in
  79784. ** register P1 is zero, then the result is NULL. If either input is
  79785. ** NULL, the result is NULL.
  79786. */
  79787. /* Opcode: Remainder P1 P2 P3 * *
  79788. ** Synopsis: r[P3]=r[P2]%r[P1]
  79789. **
  79790. ** Compute the remainder after integer register P2 is divided by
  79791. ** register P1 and store the result in register P3.
  79792. ** If the value in register P1 is zero the result is NULL.
  79793. ** If either operand is NULL, the result is NULL.
  79794. */
  79795. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  79796. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  79797. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  79798. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  79799. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  79800. char bIntint; /* Started out as two integer operands */
  79801. u16 flags; /* Combined MEM_* flags from both inputs */
  79802. u16 type1; /* Numeric type of left operand */
  79803. u16 type2; /* Numeric type of right operand */
  79804. i64 iA; /* Integer value of left operand */
  79805. i64 iB; /* Integer value of right operand */
  79806. double rA; /* Real value of left operand */
  79807. double rB; /* Real value of right operand */
  79808. pIn1 = &aMem[pOp->p1];
  79809. type1 = numericType(pIn1);
  79810. pIn2 = &aMem[pOp->p2];
  79811. type2 = numericType(pIn2);
  79812. pOut = &aMem[pOp->p3];
  79813. flags = pIn1->flags | pIn2->flags;
  79814. if( (type1 & type2 & MEM_Int)!=0 ){
  79815. iA = pIn1->u.i;
  79816. iB = pIn2->u.i;
  79817. bIntint = 1;
  79818. switch( pOp->opcode ){
  79819. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  79820. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  79821. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  79822. case OP_Divide: {
  79823. if( iA==0 ) goto arithmetic_result_is_null;
  79824. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  79825. iB /= iA;
  79826. break;
  79827. }
  79828. default: {
  79829. if( iA==0 ) goto arithmetic_result_is_null;
  79830. if( iA==-1 ) iA = 1;
  79831. iB %= iA;
  79832. break;
  79833. }
  79834. }
  79835. pOut->u.i = iB;
  79836. MemSetTypeFlag(pOut, MEM_Int);
  79837. }else if( (flags & MEM_Null)!=0 ){
  79838. goto arithmetic_result_is_null;
  79839. }else{
  79840. bIntint = 0;
  79841. fp_math:
  79842. rA = sqlite3VdbeRealValue(pIn1);
  79843. rB = sqlite3VdbeRealValue(pIn2);
  79844. switch( pOp->opcode ){
  79845. case OP_Add: rB += rA; break;
  79846. case OP_Subtract: rB -= rA; break;
  79847. case OP_Multiply: rB *= rA; break;
  79848. case OP_Divide: {
  79849. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  79850. if( rA==(double)0 ) goto arithmetic_result_is_null;
  79851. rB /= rA;
  79852. break;
  79853. }
  79854. default: {
  79855. iA = sqlite3VdbeIntValue(pIn1);
  79856. iB = sqlite3VdbeIntValue(pIn2);
  79857. if( iA==0 ) goto arithmetic_result_is_null;
  79858. if( iA==-1 ) iA = 1;
  79859. rB = (double)(iB % iA);
  79860. break;
  79861. }
  79862. }
  79863. #ifdef SQLITE_OMIT_FLOATING_POINT
  79864. pOut->u.i = rB;
  79865. MemSetTypeFlag(pOut, MEM_Int);
  79866. #else
  79867. if( sqlite3IsNaN(rB) ){
  79868. goto arithmetic_result_is_null;
  79869. }
  79870. pOut->u.r = rB;
  79871. MemSetTypeFlag(pOut, MEM_Real);
  79872. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  79873. sqlite3VdbeIntegerAffinity(pOut);
  79874. }
  79875. #endif
  79876. }
  79877. break;
  79878. arithmetic_result_is_null:
  79879. sqlite3VdbeMemSetNull(pOut);
  79880. break;
  79881. }
  79882. /* Opcode: CollSeq P1 * * P4
  79883. **
  79884. ** P4 is a pointer to a CollSeq object. If the next call to a user function
  79885. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  79886. ** be returned. This is used by the built-in min(), max() and nullif()
  79887. ** functions.
  79888. **
  79889. ** If P1 is not zero, then it is a register that a subsequent min() or
  79890. ** max() aggregate will set to 1 if the current row is not the minimum or
  79891. ** maximum. The P1 register is initialized to 0 by this instruction.
  79892. **
  79893. ** The interface used by the implementation of the aforementioned functions
  79894. ** to retrieve the collation sequence set by this opcode is not available
  79895. ** publicly. Only built-in functions have access to this feature.
  79896. */
  79897. case OP_CollSeq: {
  79898. assert( pOp->p4type==P4_COLLSEQ );
  79899. if( pOp->p1 ){
  79900. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  79901. }
  79902. break;
  79903. }
  79904. /* Opcode: BitAnd P1 P2 P3 * *
  79905. ** Synopsis: r[P3]=r[P1]&r[P2]
  79906. **
  79907. ** Take the bit-wise AND of the values in register P1 and P2 and
  79908. ** store the result in register P3.
  79909. ** If either input is NULL, the result is NULL.
  79910. */
  79911. /* Opcode: BitOr P1 P2 P3 * *
  79912. ** Synopsis: r[P3]=r[P1]|r[P2]
  79913. **
  79914. ** Take the bit-wise OR of the values in register P1 and P2 and
  79915. ** store the result in register P3.
  79916. ** If either input is NULL, the result is NULL.
  79917. */
  79918. /* Opcode: ShiftLeft P1 P2 P3 * *
  79919. ** Synopsis: r[P3]=r[P2]<<r[P1]
  79920. **
  79921. ** Shift the integer value in register P2 to the left by the
  79922. ** number of bits specified by the integer in register P1.
  79923. ** Store the result in register P3.
  79924. ** If either input is NULL, the result is NULL.
  79925. */
  79926. /* Opcode: ShiftRight P1 P2 P3 * *
  79927. ** Synopsis: r[P3]=r[P2]>>r[P1]
  79928. **
  79929. ** Shift the integer value in register P2 to the right by the
  79930. ** number of bits specified by the integer in register P1.
  79931. ** Store the result in register P3.
  79932. ** If either input is NULL, the result is NULL.
  79933. */
  79934. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  79935. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  79936. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  79937. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  79938. i64 iA;
  79939. u64 uA;
  79940. i64 iB;
  79941. u8 op;
  79942. pIn1 = &aMem[pOp->p1];
  79943. pIn2 = &aMem[pOp->p2];
  79944. pOut = &aMem[pOp->p3];
  79945. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  79946. sqlite3VdbeMemSetNull(pOut);
  79947. break;
  79948. }
  79949. iA = sqlite3VdbeIntValue(pIn2);
  79950. iB = sqlite3VdbeIntValue(pIn1);
  79951. op = pOp->opcode;
  79952. if( op==OP_BitAnd ){
  79953. iA &= iB;
  79954. }else if( op==OP_BitOr ){
  79955. iA |= iB;
  79956. }else if( iB!=0 ){
  79957. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  79958. /* If shifting by a negative amount, shift in the other direction */
  79959. if( iB<0 ){
  79960. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  79961. op = 2*OP_ShiftLeft + 1 - op;
  79962. iB = iB>(-64) ? -iB : 64;
  79963. }
  79964. if( iB>=64 ){
  79965. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  79966. }else{
  79967. memcpy(&uA, &iA, sizeof(uA));
  79968. if( op==OP_ShiftLeft ){
  79969. uA <<= iB;
  79970. }else{
  79971. uA >>= iB;
  79972. /* Sign-extend on a right shift of a negative number */
  79973. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  79974. }
  79975. memcpy(&iA, &uA, sizeof(iA));
  79976. }
  79977. }
  79978. pOut->u.i = iA;
  79979. MemSetTypeFlag(pOut, MEM_Int);
  79980. break;
  79981. }
  79982. /* Opcode: AddImm P1 P2 * * *
  79983. ** Synopsis: r[P1]=r[P1]+P2
  79984. **
  79985. ** Add the constant P2 to the value in register P1.
  79986. ** The result is always an integer.
  79987. **
  79988. ** To force any register to be an integer, just add 0.
  79989. */
  79990. case OP_AddImm: { /* in1 */
  79991. pIn1 = &aMem[pOp->p1];
  79992. memAboutToChange(p, pIn1);
  79993. sqlite3VdbeMemIntegerify(pIn1);
  79994. pIn1->u.i += pOp->p2;
  79995. break;
  79996. }
  79997. /* Opcode: MustBeInt P1 P2 * * *
  79998. **
  79999. ** Force the value in register P1 to be an integer. If the value
  80000. ** in P1 is not an integer and cannot be converted into an integer
  80001. ** without data loss, then jump immediately to P2, or if P2==0
  80002. ** raise an SQLITE_MISMATCH exception.
  80003. */
  80004. case OP_MustBeInt: { /* jump, in1 */
  80005. pIn1 = &aMem[pOp->p1];
  80006. if( (pIn1->flags & MEM_Int)==0 ){
  80007. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  80008. if( (pIn1->flags & MEM_Int)==0 ){
  80009. VdbeBranchTaken(1, 2);
  80010. if( pOp->p2==0 ){
  80011. rc = SQLITE_MISMATCH;
  80012. goto abort_due_to_error;
  80013. }else{
  80014. goto jump_to_p2;
  80015. }
  80016. }
  80017. }
  80018. VdbeBranchTaken(0, 2);
  80019. MemSetTypeFlag(pIn1, MEM_Int);
  80020. break;
  80021. }
  80022. #ifndef SQLITE_OMIT_FLOATING_POINT
  80023. /* Opcode: RealAffinity P1 * * * *
  80024. **
  80025. ** If register P1 holds an integer convert it to a real value.
  80026. **
  80027. ** This opcode is used when extracting information from a column that
  80028. ** has REAL affinity. Such column values may still be stored as
  80029. ** integers, for space efficiency, but after extraction we want them
  80030. ** to have only a real value.
  80031. */
  80032. case OP_RealAffinity: { /* in1 */
  80033. pIn1 = &aMem[pOp->p1];
  80034. if( pIn1->flags & MEM_Int ){
  80035. sqlite3VdbeMemRealify(pIn1);
  80036. }
  80037. break;
  80038. }
  80039. #endif
  80040. #ifndef SQLITE_OMIT_CAST
  80041. /* Opcode: Cast P1 P2 * * *
  80042. ** Synopsis: affinity(r[P1])
  80043. **
  80044. ** Force the value in register P1 to be the type defined by P2.
  80045. **
  80046. ** <ul>
  80047. ** <li> P2=='A' &rarr; BLOB
  80048. ** <li> P2=='B' &rarr; TEXT
  80049. ** <li> P2=='C' &rarr; NUMERIC
  80050. ** <li> P2=='D' &rarr; INTEGER
  80051. ** <li> P2=='E' &rarr; REAL
  80052. ** </ul>
  80053. **
  80054. ** A NULL value is not changed by this routine. It remains NULL.
  80055. */
  80056. case OP_Cast: { /* in1 */
  80057. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  80058. testcase( pOp->p2==SQLITE_AFF_TEXT );
  80059. testcase( pOp->p2==SQLITE_AFF_BLOB );
  80060. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  80061. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  80062. testcase( pOp->p2==SQLITE_AFF_REAL );
  80063. pIn1 = &aMem[pOp->p1];
  80064. memAboutToChange(p, pIn1);
  80065. rc = ExpandBlob(pIn1);
  80066. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  80067. UPDATE_MAX_BLOBSIZE(pIn1);
  80068. if( rc ) goto abort_due_to_error;
  80069. break;
  80070. }
  80071. #endif /* SQLITE_OMIT_CAST */
  80072. /* Opcode: Eq P1 P2 P3 P4 P5
  80073. ** Synopsis: IF r[P3]==r[P1]
  80074. **
  80075. ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
  80076. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
  80077. ** store the result of comparison in register P2.
  80078. **
  80079. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  80080. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  80081. ** to coerce both inputs according to this affinity before the
  80082. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  80083. ** affinity is used. Note that the affinity conversions are stored
  80084. ** back into the input registers P1 and P3. So this opcode can cause
  80085. ** persistent changes to registers P1 and P3.
  80086. **
  80087. ** Once any conversions have taken place, and neither value is NULL,
  80088. ** the values are compared. If both values are blobs then memcmp() is
  80089. ** used to determine the results of the comparison. If both values
  80090. ** are text, then the appropriate collating function specified in
  80091. ** P4 is used to do the comparison. If P4 is not specified then
  80092. ** memcmp() is used to compare text string. If both values are
  80093. ** numeric, then a numeric comparison is used. If the two values
  80094. ** are of different types, then numbers are considered less than
  80095. ** strings and strings are considered less than blobs.
  80096. **
  80097. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  80098. ** true or false and is never NULL. If both operands are NULL then the result
  80099. ** of comparison is true. If either operand is NULL then the result is false.
  80100. ** If neither operand is NULL the result is the same as it would be if
  80101. ** the SQLITE_NULLEQ flag were omitted from P5.
  80102. **
  80103. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  80104. ** content of r[P2] is only changed if the new value is NULL or 0 (false).
  80105. ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
  80106. */
  80107. /* Opcode: Ne P1 P2 P3 P4 P5
  80108. ** Synopsis: IF r[P3]!=r[P1]
  80109. **
  80110. ** This works just like the Eq opcode except that the jump is taken if
  80111. ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
  80112. ** additional information.
  80113. **
  80114. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  80115. ** content of r[P2] is only changed if the new value is NULL or 1 (true).
  80116. ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
  80117. */
  80118. /* Opcode: Lt P1 P2 P3 P4 P5
  80119. ** Synopsis: IF r[P3]<r[P1]
  80120. **
  80121. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  80122. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
  80123. ** the result of comparison (0 or 1 or NULL) into register P2.
  80124. **
  80125. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  80126. ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
  80127. ** bit is clear then fall through if either operand is NULL.
  80128. **
  80129. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  80130. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  80131. ** to coerce both inputs according to this affinity before the
  80132. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  80133. ** affinity is used. Note that the affinity conversions are stored
  80134. ** back into the input registers P1 and P3. So this opcode can cause
  80135. ** persistent changes to registers P1 and P3.
  80136. **
  80137. ** Once any conversions have taken place, and neither value is NULL,
  80138. ** the values are compared. If both values are blobs then memcmp() is
  80139. ** used to determine the results of the comparison. If both values
  80140. ** are text, then the appropriate collating function specified in
  80141. ** P4 is used to do the comparison. If P4 is not specified then
  80142. ** memcmp() is used to compare text string. If both values are
  80143. ** numeric, then a numeric comparison is used. If the two values
  80144. ** are of different types, then numbers are considered less than
  80145. ** strings and strings are considered less than blobs.
  80146. */
  80147. /* Opcode: Le P1 P2 P3 P4 P5
  80148. ** Synopsis: IF r[P3]<=r[P1]
  80149. **
  80150. ** This works just like the Lt opcode except that the jump is taken if
  80151. ** the content of register P3 is less than or equal to the content of
  80152. ** register P1. See the Lt opcode for additional information.
  80153. */
  80154. /* Opcode: Gt P1 P2 P3 P4 P5
  80155. ** Synopsis: IF r[P3]>r[P1]
  80156. **
  80157. ** This works just like the Lt opcode except that the jump is taken if
  80158. ** the content of register P3 is greater than the content of
  80159. ** register P1. See the Lt opcode for additional information.
  80160. */
  80161. /* Opcode: Ge P1 P2 P3 P4 P5
  80162. ** Synopsis: IF r[P3]>=r[P1]
  80163. **
  80164. ** This works just like the Lt opcode except that the jump is taken if
  80165. ** the content of register P3 is greater than or equal to the content of
  80166. ** register P1. See the Lt opcode for additional information.
  80167. */
  80168. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  80169. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  80170. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  80171. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  80172. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  80173. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  80174. int res, res2; /* Result of the comparison of pIn1 against pIn3 */
  80175. char affinity; /* Affinity to use for comparison */
  80176. u16 flags1; /* Copy of initial value of pIn1->flags */
  80177. u16 flags3; /* Copy of initial value of pIn3->flags */
  80178. pIn1 = &aMem[pOp->p1];
  80179. pIn3 = &aMem[pOp->p3];
  80180. flags1 = pIn1->flags;
  80181. flags3 = pIn3->flags;
  80182. if( (flags1 | flags3)&MEM_Null ){
  80183. /* One or both operands are NULL */
  80184. if( pOp->p5 & SQLITE_NULLEQ ){
  80185. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  80186. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  80187. ** or not both operands are null.
  80188. */
  80189. assert( (flags1 & MEM_Cleared)==0 );
  80190. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
  80191. testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
  80192. if( (flags1&flags3&MEM_Null)!=0
  80193. && (flags3&MEM_Cleared)==0
  80194. ){
  80195. res = 0; /* Operands are equal */
  80196. }else{
  80197. res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */
  80198. }
  80199. }else{
  80200. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  80201. ** then the result is always NULL.
  80202. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  80203. */
  80204. if( pOp->p5 & SQLITE_STOREP2 ){
  80205. pOut = &aMem[pOp->p2];
  80206. iCompare = 1; /* Operands are not equal */
  80207. memAboutToChange(p, pOut);
  80208. MemSetTypeFlag(pOut, MEM_Null);
  80209. REGISTER_TRACE(pOp->p2, pOut);
  80210. }else{
  80211. VdbeBranchTaken(2,3);
  80212. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  80213. goto jump_to_p2;
  80214. }
  80215. }
  80216. break;
  80217. }
  80218. }else{
  80219. /* Neither operand is NULL. Do a comparison. */
  80220. affinity = pOp->p5 & SQLITE_AFF_MASK;
  80221. if( affinity>=SQLITE_AFF_NUMERIC ){
  80222. if( (flags1 | flags3)&MEM_Str ){
  80223. if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  80224. applyNumericAffinity(pIn1,0);
  80225. assert( flags3==pIn3->flags );
  80226. /* testcase( flags3!=pIn3->flags );
  80227. ** this used to be possible with pIn1==pIn3, but not since
  80228. ** the column cache was removed. The following assignment
  80229. ** is essentially a no-op. But, it provides defense-in-depth
  80230. ** in case our analysis is incorrect, so it is left in. */
  80231. flags3 = pIn3->flags;
  80232. }
  80233. if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  80234. applyNumericAffinity(pIn3,0);
  80235. }
  80236. }
  80237. /* Handle the common case of integer comparison here, as an
  80238. ** optimization, to avoid a call to sqlite3MemCompare() */
  80239. if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
  80240. if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
  80241. if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
  80242. res = 0;
  80243. goto compare_op;
  80244. }
  80245. }else if( affinity==SQLITE_AFF_TEXT ){
  80246. if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
  80247. testcase( pIn1->flags & MEM_Int );
  80248. testcase( pIn1->flags & MEM_Real );
  80249. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  80250. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  80251. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  80252. assert( pIn1!=pIn3 );
  80253. }
  80254. if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
  80255. testcase( pIn3->flags & MEM_Int );
  80256. testcase( pIn3->flags & MEM_Real );
  80257. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  80258. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  80259. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  80260. }
  80261. }
  80262. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  80263. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  80264. }
  80265. compare_op:
  80266. /* At this point, res is negative, zero, or positive if reg[P1] is
  80267. ** less than, equal to, or greater than reg[P3], respectively. Compute
  80268. ** the answer to this operator in res2, depending on what the comparison
  80269. ** operator actually is. The next block of code depends on the fact
  80270. ** that the 6 comparison operators are consecutive integers in this
  80271. ** order: NE, EQ, GT, LE, LT, GE */
  80272. assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
  80273. assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
  80274. if( res<0 ){ /* ne, eq, gt, le, lt, ge */
  80275. static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
  80276. res2 = aLTb[pOp->opcode - OP_Ne];
  80277. }else if( res==0 ){
  80278. static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
  80279. res2 = aEQb[pOp->opcode - OP_Ne];
  80280. }else{
  80281. static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
  80282. res2 = aGTb[pOp->opcode - OP_Ne];
  80283. }
  80284. /* Undo any changes made by applyAffinity() to the input registers. */
  80285. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  80286. pIn1->flags = flags1;
  80287. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  80288. pIn3->flags = flags3;
  80289. if( pOp->p5 & SQLITE_STOREP2 ){
  80290. pOut = &aMem[pOp->p2];
  80291. iCompare = res;
  80292. if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
  80293. /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
  80294. ** and prevents OP_Ne from overwriting NULL with 0. This flag
  80295. ** is only used in contexts where either:
  80296. ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
  80297. ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
  80298. ** Therefore it is not necessary to check the content of r[P2] for
  80299. ** NULL. */
  80300. assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
  80301. assert( res2==0 || res2==1 );
  80302. testcase( res2==0 && pOp->opcode==OP_Eq );
  80303. testcase( res2==1 && pOp->opcode==OP_Eq );
  80304. testcase( res2==0 && pOp->opcode==OP_Ne );
  80305. testcase( res2==1 && pOp->opcode==OP_Ne );
  80306. if( (pOp->opcode==OP_Eq)==res2 ) break;
  80307. }
  80308. memAboutToChange(p, pOut);
  80309. MemSetTypeFlag(pOut, MEM_Int);
  80310. pOut->u.i = res2;
  80311. REGISTER_TRACE(pOp->p2, pOut);
  80312. }else{
  80313. VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  80314. if( res2 ){
  80315. goto jump_to_p2;
  80316. }
  80317. }
  80318. break;
  80319. }
  80320. /* Opcode: ElseNotEq * P2 * * *
  80321. **
  80322. ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
  80323. ** If result of an OP_Eq comparison on the same two operands
  80324. ** would have be NULL or false (0), then then jump to P2.
  80325. ** If the result of an OP_Eq comparison on the two previous operands
  80326. ** would have been true (1), then fall through.
  80327. */
  80328. case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
  80329. assert( pOp>aOp );
  80330. assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
  80331. assert( pOp[-1].p5 & SQLITE_STOREP2 );
  80332. VdbeBranchTaken(iCompare!=0, 2);
  80333. if( iCompare!=0 ) goto jump_to_p2;
  80334. break;
  80335. }
  80336. /* Opcode: Permutation * * * P4 *
  80337. **
  80338. ** Set the permutation used by the OP_Compare operator in the next
  80339. ** instruction. The permutation is stored in the P4 operand.
  80340. **
  80341. ** The permutation is only valid until the next OP_Compare that has
  80342. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  80343. ** occur immediately prior to the OP_Compare.
  80344. **
  80345. ** The first integer in the P4 integer array is the length of the array
  80346. ** and does not become part of the permutation.
  80347. */
  80348. case OP_Permutation: {
  80349. assert( pOp->p4type==P4_INTARRAY );
  80350. assert( pOp->p4.ai );
  80351. assert( pOp[1].opcode==OP_Compare );
  80352. assert( pOp[1].p5 & OPFLAG_PERMUTE );
  80353. break;
  80354. }
  80355. /* Opcode: Compare P1 P2 P3 P4 P5
  80356. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  80357. **
  80358. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  80359. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  80360. ** the comparison for use by the next OP_Jump instruct.
  80361. **
  80362. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  80363. ** determined by the most recent OP_Permutation operator. If the
  80364. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  80365. ** order.
  80366. **
  80367. ** P4 is a KeyInfo structure that defines collating sequences and sort
  80368. ** orders for the comparison. The permutation applies to registers
  80369. ** only. The KeyInfo elements are used sequentially.
  80370. **
  80371. ** The comparison is a sort comparison, so NULLs compare equal,
  80372. ** NULLs are less than numbers, numbers are less than strings,
  80373. ** and strings are less than blobs.
  80374. */
  80375. case OP_Compare: {
  80376. int n;
  80377. int i;
  80378. int p1;
  80379. int p2;
  80380. const KeyInfo *pKeyInfo;
  80381. int idx;
  80382. CollSeq *pColl; /* Collating sequence to use on this term */
  80383. int bRev; /* True for DESCENDING sort order */
  80384. int *aPermute; /* The permutation */
  80385. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
  80386. aPermute = 0;
  80387. }else{
  80388. assert( pOp>aOp );
  80389. assert( pOp[-1].opcode==OP_Permutation );
  80390. assert( pOp[-1].p4type==P4_INTARRAY );
  80391. aPermute = pOp[-1].p4.ai + 1;
  80392. assert( aPermute!=0 );
  80393. }
  80394. n = pOp->p3;
  80395. pKeyInfo = pOp->p4.pKeyInfo;
  80396. assert( n>0 );
  80397. assert( pKeyInfo!=0 );
  80398. p1 = pOp->p1;
  80399. p2 = pOp->p2;
  80400. #ifdef SQLITE_DEBUG
  80401. if( aPermute ){
  80402. int k, mx = 0;
  80403. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  80404. assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
  80405. assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
  80406. }else{
  80407. assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
  80408. assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
  80409. }
  80410. #endif /* SQLITE_DEBUG */
  80411. for(i=0; i<n; i++){
  80412. idx = aPermute ? aPermute[i] : i;
  80413. assert( memIsValid(&aMem[p1+idx]) );
  80414. assert( memIsValid(&aMem[p2+idx]) );
  80415. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  80416. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  80417. assert( i<pKeyInfo->nKeyField );
  80418. pColl = pKeyInfo->aColl[i];
  80419. bRev = pKeyInfo->aSortOrder[i];
  80420. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  80421. if( iCompare ){
  80422. if( bRev ) iCompare = -iCompare;
  80423. break;
  80424. }
  80425. }
  80426. break;
  80427. }
  80428. /* Opcode: Jump P1 P2 P3 * *
  80429. **
  80430. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  80431. ** in the most recent OP_Compare instruction the P1 vector was less than
  80432. ** equal to, or greater than the P2 vector, respectively.
  80433. */
  80434. case OP_Jump: { /* jump */
  80435. if( iCompare<0 ){
  80436. VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
  80437. }else if( iCompare==0 ){
  80438. VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
  80439. }else{
  80440. VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
  80441. }
  80442. break;
  80443. }
  80444. /* Opcode: And P1 P2 P3 * *
  80445. ** Synopsis: r[P3]=(r[P1] && r[P2])
  80446. **
  80447. ** Take the logical AND of the values in registers P1 and P2 and
  80448. ** write the result into register P3.
  80449. **
  80450. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  80451. ** the other input is NULL. A NULL and true or two NULLs give
  80452. ** a NULL output.
  80453. */
  80454. /* Opcode: Or P1 P2 P3 * *
  80455. ** Synopsis: r[P3]=(r[P1] || r[P2])
  80456. **
  80457. ** Take the logical OR of the values in register P1 and P2 and
  80458. ** store the answer in register P3.
  80459. **
  80460. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  80461. ** even if the other input is NULL. A NULL and false or two NULLs
  80462. ** give a NULL output.
  80463. */
  80464. case OP_And: /* same as TK_AND, in1, in2, out3 */
  80465. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  80466. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  80467. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  80468. v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
  80469. v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
  80470. if( pOp->opcode==OP_And ){
  80471. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  80472. v1 = and_logic[v1*3+v2];
  80473. }else{
  80474. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  80475. v1 = or_logic[v1*3+v2];
  80476. }
  80477. pOut = &aMem[pOp->p3];
  80478. if( v1==2 ){
  80479. MemSetTypeFlag(pOut, MEM_Null);
  80480. }else{
  80481. pOut->u.i = v1;
  80482. MemSetTypeFlag(pOut, MEM_Int);
  80483. }
  80484. break;
  80485. }
  80486. /* Opcode: IsTrue P1 P2 P3 P4 *
  80487. ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
  80488. **
  80489. ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
  80490. ** IS NOT FALSE operators.
  80491. **
  80492. ** Interpret the value in register P1 as a boolean value. Store that
  80493. ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
  80494. ** NULL, then the P3 is stored in register P2. Invert the answer if P4
  80495. ** is 1.
  80496. **
  80497. ** The logic is summarized like this:
  80498. **
  80499. ** <ul>
  80500. ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
  80501. ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
  80502. ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
  80503. ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
  80504. ** </ul>
  80505. */
  80506. case OP_IsTrue: { /* in1, out2 */
  80507. assert( pOp->p4type==P4_INT32 );
  80508. assert( pOp->p4.i==0 || pOp->p4.i==1 );
  80509. assert( pOp->p3==0 || pOp->p3==1 );
  80510. sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
  80511. sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
  80512. break;
  80513. }
  80514. /* Opcode: Not P1 P2 * * *
  80515. ** Synopsis: r[P2]= !r[P1]
  80516. **
  80517. ** Interpret the value in register P1 as a boolean value. Store the
  80518. ** boolean complement in register P2. If the value in register P1 is
  80519. ** NULL, then a NULL is stored in P2.
  80520. */
  80521. case OP_Not: { /* same as TK_NOT, in1, out2 */
  80522. pIn1 = &aMem[pOp->p1];
  80523. pOut = &aMem[pOp->p2];
  80524. if( (pIn1->flags & MEM_Null)==0 ){
  80525. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
  80526. }else{
  80527. sqlite3VdbeMemSetNull(pOut);
  80528. }
  80529. break;
  80530. }
  80531. /* Opcode: BitNot P1 P2 * * *
  80532. ** Synopsis: r[P2]= ~r[P1]
  80533. **
  80534. ** Interpret the content of register P1 as an integer. Store the
  80535. ** ones-complement of the P1 value into register P2. If P1 holds
  80536. ** a NULL then store a NULL in P2.
  80537. */
  80538. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  80539. pIn1 = &aMem[pOp->p1];
  80540. pOut = &aMem[pOp->p2];
  80541. sqlite3VdbeMemSetNull(pOut);
  80542. if( (pIn1->flags & MEM_Null)==0 ){
  80543. pOut->flags = MEM_Int;
  80544. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  80545. }
  80546. break;
  80547. }
  80548. /* Opcode: Once P1 P2 * * *
  80549. **
  80550. ** Fall through to the next instruction the first time this opcode is
  80551. ** encountered on each invocation of the byte-code program. Jump to P2
  80552. ** on the second and all subsequent encounters during the same invocation.
  80553. **
  80554. ** Top-level programs determine first invocation by comparing the P1
  80555. ** operand against the P1 operand on the OP_Init opcode at the beginning
  80556. ** of the program. If the P1 values differ, then fall through and make
  80557. ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
  80558. ** the same then take the jump.
  80559. **
  80560. ** For subprograms, there is a bitmask in the VdbeFrame that determines
  80561. ** whether or not the jump should be taken. The bitmask is necessary
  80562. ** because the self-altering code trick does not work for recursive
  80563. ** triggers.
  80564. */
  80565. case OP_Once: { /* jump */
  80566. u32 iAddr; /* Address of this instruction */
  80567. assert( p->aOp[0].opcode==OP_Init );
  80568. if( p->pFrame ){
  80569. iAddr = (int)(pOp - p->aOp);
  80570. if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
  80571. VdbeBranchTaken(1, 2);
  80572. goto jump_to_p2;
  80573. }
  80574. p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
  80575. }else{
  80576. if( p->aOp[0].p1==pOp->p1 ){
  80577. VdbeBranchTaken(1, 2);
  80578. goto jump_to_p2;
  80579. }
  80580. }
  80581. VdbeBranchTaken(0, 2);
  80582. pOp->p1 = p->aOp[0].p1;
  80583. break;
  80584. }
  80585. /* Opcode: If P1 P2 P3 * *
  80586. **
  80587. ** Jump to P2 if the value in register P1 is true. The value
  80588. ** is considered true if it is numeric and non-zero. If the value
  80589. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  80590. */
  80591. case OP_If: { /* jump, in1 */
  80592. int c;
  80593. c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
  80594. VdbeBranchTaken(c!=0, 2);
  80595. if( c ) goto jump_to_p2;
  80596. break;
  80597. }
  80598. /* Opcode: IfNot P1 P2 P3 * *
  80599. **
  80600. ** Jump to P2 if the value in register P1 is False. The value
  80601. ** is considered false if it has a numeric value of zero. If the value
  80602. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  80603. */
  80604. case OP_IfNot: { /* jump, in1 */
  80605. int c;
  80606. c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
  80607. VdbeBranchTaken(c!=0, 2);
  80608. if( c ) goto jump_to_p2;
  80609. break;
  80610. }
  80611. /* Opcode: IsNull P1 P2 * * *
  80612. ** Synopsis: if r[P1]==NULL goto P2
  80613. **
  80614. ** Jump to P2 if the value in register P1 is NULL.
  80615. */
  80616. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  80617. pIn1 = &aMem[pOp->p1];
  80618. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  80619. if( (pIn1->flags & MEM_Null)!=0 ){
  80620. goto jump_to_p2;
  80621. }
  80622. break;
  80623. }
  80624. /* Opcode: NotNull P1 P2 * * *
  80625. ** Synopsis: if r[P1]!=NULL goto P2
  80626. **
  80627. ** Jump to P2 if the value in register P1 is not NULL.
  80628. */
  80629. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  80630. pIn1 = &aMem[pOp->p1];
  80631. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  80632. if( (pIn1->flags & MEM_Null)==0 ){
  80633. goto jump_to_p2;
  80634. }
  80635. break;
  80636. }
  80637. /* Opcode: IfNullRow P1 P2 P3 * *
  80638. ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
  80639. **
  80640. ** Check the cursor P1 to see if it is currently pointing at a NULL row.
  80641. ** If it is, then set register P3 to NULL and jump immediately to P2.
  80642. ** If P1 is not on a NULL row, then fall through without making any
  80643. ** changes.
  80644. */
  80645. case OP_IfNullRow: { /* jump */
  80646. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80647. assert( p->apCsr[pOp->p1]!=0 );
  80648. if( p->apCsr[pOp->p1]->nullRow ){
  80649. sqlite3VdbeMemSetNull(aMem + pOp->p3);
  80650. goto jump_to_p2;
  80651. }
  80652. break;
  80653. }
  80654. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  80655. /* Opcode: Offset P1 P2 P3 * *
  80656. ** Synopsis: r[P3] = sqlite_offset(P1)
  80657. **
  80658. ** Store in register r[P3] the byte offset into the database file that is the
  80659. ** start of the payload for the record at which that cursor P1 is currently
  80660. ** pointing.
  80661. **
  80662. ** P2 is the column number for the argument to the sqlite_offset() function.
  80663. ** This opcode does not use P2 itself, but the P2 value is used by the
  80664. ** code generator. The P1, P2, and P3 operands to this opcode are the
  80665. ** same as for OP_Column.
  80666. **
  80667. ** This opcode is only available if SQLite is compiled with the
  80668. ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
  80669. */
  80670. case OP_Offset: { /* out3 */
  80671. VdbeCursor *pC; /* The VDBE cursor */
  80672. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80673. pC = p->apCsr[pOp->p1];
  80674. pOut = &p->aMem[pOp->p3];
  80675. if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
  80676. sqlite3VdbeMemSetNull(pOut);
  80677. }else{
  80678. sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
  80679. }
  80680. break;
  80681. }
  80682. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  80683. /* Opcode: Column P1 P2 P3 P4 P5
  80684. ** Synopsis: r[P3]=PX
  80685. **
  80686. ** Interpret the data that cursor P1 points to as a structure built using
  80687. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  80688. ** information about the format of the data.) Extract the P2-th column
  80689. ** from this record. If there are less that (P2+1)
  80690. ** values in the record, extract a NULL.
  80691. **
  80692. ** The value extracted is stored in register P3.
  80693. **
  80694. ** If the record contains fewer than P2 fields, then extract a NULL. Or,
  80695. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  80696. ** the result.
  80697. **
  80698. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  80699. ** then the cache of the cursor is reset prior to extracting the column.
  80700. ** The first OP_Column against a pseudo-table after the value of the content
  80701. ** register has changed should have this bit set.
  80702. **
  80703. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
  80704. ** the result is guaranteed to only be used as the argument of a length()
  80705. ** or typeof() function, respectively. The loading of large blobs can be
  80706. ** skipped for length() and all content loading can be skipped for typeof().
  80707. */
  80708. case OP_Column: {
  80709. int p2; /* column number to retrieve */
  80710. VdbeCursor *pC; /* The VDBE cursor */
  80711. BtCursor *pCrsr; /* The BTree cursor */
  80712. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  80713. int len; /* The length of the serialized data for the column */
  80714. int i; /* Loop counter */
  80715. Mem *pDest; /* Where to write the extracted value */
  80716. Mem sMem; /* For storing the record being decoded */
  80717. const u8 *zData; /* Part of the record being decoded */
  80718. const u8 *zHdr; /* Next unparsed byte of the header */
  80719. const u8 *zEndHdr; /* Pointer to first byte after the header */
  80720. u64 offset64; /* 64-bit offset */
  80721. u32 t; /* A type code from the record header */
  80722. Mem *pReg; /* PseudoTable input register */
  80723. pC = p->apCsr[pOp->p1];
  80724. p2 = pOp->p2;
  80725. /* If the cursor cache is stale (meaning it is not currently point at
  80726. ** the correct row) then bring it up-to-date by doing the necessary
  80727. ** B-Tree seek. */
  80728. rc = sqlite3VdbeCursorMoveto(&pC, &p2);
  80729. if( rc ) goto abort_due_to_error;
  80730. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  80731. pDest = &aMem[pOp->p3];
  80732. memAboutToChange(p, pDest);
  80733. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80734. assert( pC!=0 );
  80735. assert( p2<pC->nField );
  80736. aOffset = pC->aOffset;
  80737. assert( pC->eCurType!=CURTYPE_VTAB );
  80738. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  80739. assert( pC->eCurType!=CURTYPE_SORTER );
  80740. if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
  80741. if( pC->nullRow ){
  80742. if( pC->eCurType==CURTYPE_PSEUDO ){
  80743. /* For the special case of as pseudo-cursor, the seekResult field
  80744. ** identifies the register that holds the record */
  80745. assert( pC->seekResult>0 );
  80746. pReg = &aMem[pC->seekResult];
  80747. assert( pReg->flags & MEM_Blob );
  80748. assert( memIsValid(pReg) );
  80749. pC->payloadSize = pC->szRow = pReg->n;
  80750. pC->aRow = (u8*)pReg->z;
  80751. }else{
  80752. sqlite3VdbeMemSetNull(pDest);
  80753. goto op_column_out;
  80754. }
  80755. }else{
  80756. pCrsr = pC->uc.pCursor;
  80757. assert( pC->eCurType==CURTYPE_BTREE );
  80758. assert( pCrsr );
  80759. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  80760. pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
  80761. pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
  80762. assert( pC->szRow<=pC->payloadSize );
  80763. assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
  80764. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  80765. goto too_big;
  80766. }
  80767. }
  80768. pC->cacheStatus = p->cacheCtr;
  80769. pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
  80770. pC->nHdrParsed = 0;
  80771. if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
  80772. /* pC->aRow does not have to hold the entire row, but it does at least
  80773. ** need to cover the header of the record. If pC->aRow does not contain
  80774. ** the complete header, then set it to zero, forcing the header to be
  80775. ** dynamically allocated. */
  80776. pC->aRow = 0;
  80777. pC->szRow = 0;
  80778. /* Make sure a corrupt database has not given us an oversize header.
  80779. ** Do this now to avoid an oversize memory allocation.
  80780. **
  80781. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  80782. ** types use so much data space that there can only be 4096 and 32 of
  80783. ** them, respectively. So the maximum header length results from a
  80784. ** 3-byte type for each of the maximum of 32768 columns plus three
  80785. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  80786. */
  80787. if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
  80788. goto op_column_corrupt;
  80789. }
  80790. }else{
  80791. /* This is an optimization. By skipping over the first few tests
  80792. ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
  80793. ** measurable performance gain.
  80794. **
  80795. ** This branch is taken even if aOffset[0]==0. Such a record is never
  80796. ** generated by SQLite, and could be considered corruption, but we
  80797. ** accept it for historical reasons. When aOffset[0]==0, the code this
  80798. ** branch jumps to reads past the end of the record, but never more
  80799. ** than a few bytes. Even if the record occurs at the end of the page
  80800. ** content area, the "page header" comes after the page content and so
  80801. ** this overread is harmless. Similar overreads can occur for a corrupt
  80802. ** database file.
  80803. */
  80804. zData = pC->aRow;
  80805. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  80806. testcase( aOffset[0]==0 );
  80807. goto op_column_read_header;
  80808. }
  80809. }
  80810. /* Make sure at least the first p2+1 entries of the header have been
  80811. ** parsed and valid information is in aOffset[] and pC->aType[].
  80812. */
  80813. if( pC->nHdrParsed<=p2 ){
  80814. /* If there is more header available for parsing in the record, try
  80815. ** to extract additional fields up through the p2+1-th field
  80816. */
  80817. if( pC->iHdrOffset<aOffset[0] ){
  80818. /* Make sure zData points to enough of the record to cover the header. */
  80819. if( pC->aRow==0 ){
  80820. memset(&sMem, 0, sizeof(sMem));
  80821. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
  80822. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  80823. zData = (u8*)sMem.z;
  80824. }else{
  80825. zData = pC->aRow;
  80826. }
  80827. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  80828. op_column_read_header:
  80829. i = pC->nHdrParsed;
  80830. offset64 = aOffset[i];
  80831. zHdr = zData + pC->iHdrOffset;
  80832. zEndHdr = zData + aOffset[0];
  80833. testcase( zHdr>=zEndHdr );
  80834. do{
  80835. if( (pC->aType[i] = t = zHdr[0])<0x80 ){
  80836. zHdr++;
  80837. offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
  80838. }else{
  80839. zHdr += sqlite3GetVarint32(zHdr, &t);
  80840. pC->aType[i] = t;
  80841. offset64 += sqlite3VdbeSerialTypeLen(t);
  80842. }
  80843. aOffset[++i] = (u32)(offset64 & 0xffffffff);
  80844. }while( i<=p2 && zHdr<zEndHdr );
  80845. /* The record is corrupt if any of the following are true:
  80846. ** (1) the bytes of the header extend past the declared header size
  80847. ** (2) the entire header was used but not all data was used
  80848. ** (3) the end of the data extends beyond the end of the record.
  80849. */
  80850. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
  80851. || (offset64 > pC->payloadSize)
  80852. ){
  80853. if( aOffset[0]==0 ){
  80854. i = 0;
  80855. zHdr = zEndHdr;
  80856. }else{
  80857. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  80858. goto op_column_corrupt;
  80859. }
  80860. }
  80861. pC->nHdrParsed = i;
  80862. pC->iHdrOffset = (u32)(zHdr - zData);
  80863. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  80864. }else{
  80865. t = 0;
  80866. }
  80867. /* If after trying to extract new entries from the header, nHdrParsed is
  80868. ** still not up to p2, that means that the record has fewer than p2
  80869. ** columns. So the result will be either the default value or a NULL.
  80870. */
  80871. if( pC->nHdrParsed<=p2 ){
  80872. if( pOp->p4type==P4_MEM ){
  80873. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  80874. }else{
  80875. sqlite3VdbeMemSetNull(pDest);
  80876. }
  80877. goto op_column_out;
  80878. }
  80879. }else{
  80880. t = pC->aType[p2];
  80881. }
  80882. /* Extract the content for the p2+1-th column. Control can only
  80883. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  80884. ** all valid.
  80885. */
  80886. assert( p2<pC->nHdrParsed );
  80887. assert( rc==SQLITE_OK );
  80888. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  80889. if( VdbeMemDynamic(pDest) ){
  80890. sqlite3VdbeMemSetNull(pDest);
  80891. }
  80892. assert( t==pC->aType[p2] );
  80893. if( pC->szRow>=aOffset[p2+1] ){
  80894. /* This is the common case where the desired content fits on the original
  80895. ** page - where the content is not on an overflow page */
  80896. zData = pC->aRow + aOffset[p2];
  80897. if( t<12 ){
  80898. sqlite3VdbeSerialGet(zData, t, pDest);
  80899. }else{
  80900. /* If the column value is a string, we need a persistent value, not
  80901. ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
  80902. ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
  80903. */
  80904. static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
  80905. pDest->n = len = (t-12)/2;
  80906. pDest->enc = encoding;
  80907. if( pDest->szMalloc < len+2 ){
  80908. pDest->flags = MEM_Null;
  80909. if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
  80910. }else{
  80911. pDest->z = pDest->zMalloc;
  80912. }
  80913. memcpy(pDest->z, zData, len);
  80914. pDest->z[len] = 0;
  80915. pDest->z[len+1] = 0;
  80916. pDest->flags = aFlag[t&1];
  80917. }
  80918. }else{
  80919. pDest->enc = encoding;
  80920. /* This branch happens only when content is on overflow pages */
  80921. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  80922. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  80923. || (len = sqlite3VdbeSerialTypeLen(t))==0
  80924. ){
  80925. /* Content is irrelevant for
  80926. ** 1. the typeof() function,
  80927. ** 2. the length(X) function if X is a blob, and
  80928. ** 3. if the content length is zero.
  80929. ** So we might as well use bogus content rather than reading
  80930. ** content from disk.
  80931. **
  80932. ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
  80933. ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
  80934. ** read up to 16. So 16 bytes of bogus content is supplied.
  80935. */
  80936. static u8 aZero[16]; /* This is the bogus content */
  80937. sqlite3VdbeSerialGet(aZero, t, pDest);
  80938. }else{
  80939. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
  80940. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  80941. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  80942. pDest->flags &= ~MEM_Ephem;
  80943. }
  80944. }
  80945. op_column_out:
  80946. UPDATE_MAX_BLOBSIZE(pDest);
  80947. REGISTER_TRACE(pOp->p3, pDest);
  80948. break;
  80949. op_column_corrupt:
  80950. if( aOp[0].p3>0 ){
  80951. pOp = &aOp[aOp[0].p3-1];
  80952. break;
  80953. }else{
  80954. rc = SQLITE_CORRUPT_BKPT;
  80955. goto abort_due_to_error;
  80956. }
  80957. }
  80958. /* Opcode: Affinity P1 P2 * P4 *
  80959. ** Synopsis: affinity(r[P1@P2])
  80960. **
  80961. ** Apply affinities to a range of P2 registers starting with P1.
  80962. **
  80963. ** P4 is a string that is P2 characters long. The N-th character of the
  80964. ** string indicates the column affinity that should be used for the N-th
  80965. ** memory cell in the range.
  80966. */
  80967. case OP_Affinity: {
  80968. const char *zAffinity; /* The affinity to be applied */
  80969. zAffinity = pOp->p4.z;
  80970. assert( zAffinity!=0 );
  80971. assert( pOp->p2>0 );
  80972. assert( zAffinity[pOp->p2]==0 );
  80973. pIn1 = &aMem[pOp->p1];
  80974. do{
  80975. assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
  80976. assert( memIsValid(pIn1) );
  80977. applyAffinity(pIn1, *(zAffinity++), encoding);
  80978. pIn1++;
  80979. }while( zAffinity[0] );
  80980. break;
  80981. }
  80982. /* Opcode: MakeRecord P1 P2 P3 P4 *
  80983. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  80984. **
  80985. ** Convert P2 registers beginning with P1 into the [record format]
  80986. ** use as a data record in a database table or as a key
  80987. ** in an index. The OP_Column opcode can decode the record later.
  80988. **
  80989. ** P4 may be a string that is P2 characters long. The N-th character of the
  80990. ** string indicates the column affinity that should be used for the N-th
  80991. ** field of the index key.
  80992. **
  80993. ** The mapping from character to affinity is given by the SQLITE_AFF_
  80994. ** macros defined in sqliteInt.h.
  80995. **
  80996. ** If P4 is NULL then all index fields have the affinity BLOB.
  80997. */
  80998. case OP_MakeRecord: {
  80999. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  81000. Mem *pRec; /* The new record */
  81001. u64 nData; /* Number of bytes of data space */
  81002. int nHdr; /* Number of bytes of header space */
  81003. i64 nByte; /* Data space required for this record */
  81004. i64 nZero; /* Number of zero bytes at the end of the record */
  81005. int nVarint; /* Number of bytes in a varint */
  81006. u32 serial_type; /* Type field */
  81007. Mem *pData0; /* First field to be combined into the record */
  81008. Mem *pLast; /* Last field of the record */
  81009. int nField; /* Number of fields in the record */
  81010. char *zAffinity; /* The affinity string for the record */
  81011. int file_format; /* File format to use for encoding */
  81012. int i; /* Space used in zNewRecord[] header */
  81013. int j; /* Space used in zNewRecord[] content */
  81014. u32 len; /* Length of a field */
  81015. /* Assuming the record contains N fields, the record format looks
  81016. ** like this:
  81017. **
  81018. ** ------------------------------------------------------------------------
  81019. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  81020. ** ------------------------------------------------------------------------
  81021. **
  81022. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  81023. ** and so forth.
  81024. **
  81025. ** Each type field is a varint representing the serial type of the
  81026. ** corresponding data element (see sqlite3VdbeSerialType()). The
  81027. ** hdr-size field is also a varint which is the offset from the beginning
  81028. ** of the record to data0.
  81029. */
  81030. nData = 0; /* Number of bytes of data space */
  81031. nHdr = 0; /* Number of bytes of header space */
  81032. nZero = 0; /* Number of zero bytes at the end of the record */
  81033. nField = pOp->p1;
  81034. zAffinity = pOp->p4.z;
  81035. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
  81036. pData0 = &aMem[nField];
  81037. nField = pOp->p2;
  81038. pLast = &pData0[nField-1];
  81039. file_format = p->minWriteFileFormat;
  81040. /* Identify the output register */
  81041. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  81042. pOut = &aMem[pOp->p3];
  81043. memAboutToChange(p, pOut);
  81044. /* Apply the requested affinity to all inputs
  81045. */
  81046. assert( pData0<=pLast );
  81047. if( zAffinity ){
  81048. pRec = pData0;
  81049. do{
  81050. applyAffinity(pRec++, *(zAffinity++), encoding);
  81051. assert( zAffinity[0]==0 || pRec<=pLast );
  81052. }while( zAffinity[0] );
  81053. }
  81054. #ifdef SQLITE_ENABLE_NULL_TRIM
  81055. /* NULLs can be safely trimmed from the end of the record, as long as
  81056. ** as the schema format is 2 or more and none of the omitted columns
  81057. ** have a non-NULL default value. Also, the record must be left with
  81058. ** at least one field. If P5>0 then it will be one more than the
  81059. ** index of the right-most column with a non-NULL default value */
  81060. if( pOp->p5 ){
  81061. while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
  81062. pLast--;
  81063. nField--;
  81064. }
  81065. }
  81066. #endif
  81067. /* Loop through the elements that will make up the record to figure
  81068. ** out how much space is required for the new record.
  81069. */
  81070. pRec = pLast;
  81071. do{
  81072. assert( memIsValid(pRec) );
  81073. serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
  81074. if( pRec->flags & MEM_Zero ){
  81075. if( serial_type==0 ){
  81076. /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
  81077. ** table methods that never invoke sqlite3_result_xxxxx() while
  81078. ** computing an unchanging column value in an UPDATE statement.
  81079. ** Give such values a special internal-use-only serial-type of 10
  81080. ** so that they can be passed through to xUpdate and have
  81081. ** a true sqlite3_value_nochange(). */
  81082. assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
  81083. serial_type = 10;
  81084. }else if( nData ){
  81085. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  81086. }else{
  81087. nZero += pRec->u.nZero;
  81088. len -= pRec->u.nZero;
  81089. }
  81090. }
  81091. nData += len;
  81092. testcase( serial_type==127 );
  81093. testcase( serial_type==128 );
  81094. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  81095. pRec->uTemp = serial_type;
  81096. if( pRec==pData0 ) break;
  81097. pRec--;
  81098. }while(1);
  81099. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  81100. ** which determines the total number of bytes in the header. The varint
  81101. ** value is the size of the header in bytes including the size varint
  81102. ** itself. */
  81103. testcase( nHdr==126 );
  81104. testcase( nHdr==127 );
  81105. if( nHdr<=126 ){
  81106. /* The common case */
  81107. nHdr += 1;
  81108. }else{
  81109. /* Rare case of a really large header */
  81110. nVarint = sqlite3VarintLen(nHdr);
  81111. nHdr += nVarint;
  81112. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  81113. }
  81114. nByte = nHdr+nData;
  81115. /* Make sure the output register has a buffer large enough to store
  81116. ** the new record. The output register (pOp->p3) is not allowed to
  81117. ** be one of the input registers (because the following call to
  81118. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  81119. */
  81120. if( nByte+nZero<=pOut->szMalloc ){
  81121. /* The output register is already large enough to hold the record.
  81122. ** No error checks or buffer enlargement is required */
  81123. pOut->z = pOut->zMalloc;
  81124. }else{
  81125. /* Need to make sure that the output is not too big and then enlarge
  81126. ** the output register to hold the full result */
  81127. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  81128. goto too_big;
  81129. }
  81130. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  81131. goto no_mem;
  81132. }
  81133. }
  81134. zNewRecord = (u8 *)pOut->z;
  81135. /* Write the record */
  81136. i = putVarint32(zNewRecord, nHdr);
  81137. j = nHdr;
  81138. assert( pData0<=pLast );
  81139. pRec = pData0;
  81140. do{
  81141. serial_type = pRec->uTemp;
  81142. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  81143. ** additional varints, one per column. */
  81144. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  81145. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  81146. ** immediately follow the header. */
  81147. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  81148. }while( (++pRec)<=pLast );
  81149. assert( i==nHdr );
  81150. assert( j==nByte );
  81151. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  81152. pOut->n = (int)nByte;
  81153. pOut->flags = MEM_Blob;
  81154. if( nZero ){
  81155. pOut->u.nZero = nZero;
  81156. pOut->flags |= MEM_Zero;
  81157. }
  81158. REGISTER_TRACE(pOp->p3, pOut);
  81159. UPDATE_MAX_BLOBSIZE(pOut);
  81160. break;
  81161. }
  81162. /* Opcode: Count P1 P2 * * *
  81163. ** Synopsis: r[P2]=count()
  81164. **
  81165. ** Store the number of entries (an integer value) in the table or index
  81166. ** opened by cursor P1 in register P2
  81167. */
  81168. #ifndef SQLITE_OMIT_BTREECOUNT
  81169. case OP_Count: { /* out2 */
  81170. i64 nEntry;
  81171. BtCursor *pCrsr;
  81172. assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
  81173. pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
  81174. assert( pCrsr );
  81175. nEntry = 0; /* Not needed. Only used to silence a warning. */
  81176. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  81177. if( rc ) goto abort_due_to_error;
  81178. pOut = out2Prerelease(p, pOp);
  81179. pOut->u.i = nEntry;
  81180. break;
  81181. }
  81182. #endif
  81183. /* Opcode: Savepoint P1 * * P4 *
  81184. **
  81185. ** Open, release or rollback the savepoint named by parameter P4, depending
  81186. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  81187. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  81188. */
  81189. case OP_Savepoint: {
  81190. int p1; /* Value of P1 operand */
  81191. char *zName; /* Name of savepoint */
  81192. int nName;
  81193. Savepoint *pNew;
  81194. Savepoint *pSavepoint;
  81195. Savepoint *pTmp;
  81196. int iSavepoint;
  81197. int ii;
  81198. p1 = pOp->p1;
  81199. zName = pOp->p4.z;
  81200. /* Assert that the p1 parameter is valid. Also that if there is no open
  81201. ** transaction, then there cannot be any savepoints.
  81202. */
  81203. assert( db->pSavepoint==0 || db->autoCommit==0 );
  81204. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  81205. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  81206. assert( checkSavepointCount(db) );
  81207. assert( p->bIsReader );
  81208. if( p1==SAVEPOINT_BEGIN ){
  81209. if( db->nVdbeWrite>0 ){
  81210. /* A new savepoint cannot be created if there are active write
  81211. ** statements (i.e. open read/write incremental blob handles).
  81212. */
  81213. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  81214. rc = SQLITE_BUSY;
  81215. }else{
  81216. nName = sqlite3Strlen30(zName);
  81217. #ifndef SQLITE_OMIT_VIRTUALTABLE
  81218. /* This call is Ok even if this savepoint is actually a transaction
  81219. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  81220. ** If this is a transaction savepoint being opened, it is guaranteed
  81221. ** that the db->aVTrans[] array is empty. */
  81222. assert( db->autoCommit==0 || db->nVTrans==0 );
  81223. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  81224. db->nStatement+db->nSavepoint);
  81225. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  81226. #endif
  81227. /* Create a new savepoint structure. */
  81228. pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
  81229. if( pNew ){
  81230. pNew->zName = (char *)&pNew[1];
  81231. memcpy(pNew->zName, zName, nName+1);
  81232. /* If there is no open transaction, then mark this as a special
  81233. ** "transaction savepoint". */
  81234. if( db->autoCommit ){
  81235. db->autoCommit = 0;
  81236. db->isTransactionSavepoint = 1;
  81237. }else{
  81238. db->nSavepoint++;
  81239. }
  81240. /* Link the new savepoint into the database handle's list. */
  81241. pNew->pNext = db->pSavepoint;
  81242. db->pSavepoint = pNew;
  81243. pNew->nDeferredCons = db->nDeferredCons;
  81244. pNew->nDeferredImmCons = db->nDeferredImmCons;
  81245. }
  81246. }
  81247. }else{
  81248. iSavepoint = 0;
  81249. /* Find the named savepoint. If there is no such savepoint, then an
  81250. ** an error is returned to the user. */
  81251. for(
  81252. pSavepoint = db->pSavepoint;
  81253. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  81254. pSavepoint = pSavepoint->pNext
  81255. ){
  81256. iSavepoint++;
  81257. }
  81258. if( !pSavepoint ){
  81259. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  81260. rc = SQLITE_ERROR;
  81261. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  81262. /* It is not possible to release (commit) a savepoint if there are
  81263. ** active write statements.
  81264. */
  81265. sqlite3VdbeError(p, "cannot release savepoint - "
  81266. "SQL statements in progress");
  81267. rc = SQLITE_BUSY;
  81268. }else{
  81269. /* Determine whether or not this is a transaction savepoint. If so,
  81270. ** and this is a RELEASE command, then the current transaction
  81271. ** is committed.
  81272. */
  81273. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  81274. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  81275. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  81276. goto vdbe_return;
  81277. }
  81278. db->autoCommit = 1;
  81279. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  81280. p->pc = (int)(pOp - aOp);
  81281. db->autoCommit = 0;
  81282. p->rc = rc = SQLITE_BUSY;
  81283. goto vdbe_return;
  81284. }
  81285. db->isTransactionSavepoint = 0;
  81286. rc = p->rc;
  81287. }else{
  81288. int isSchemaChange;
  81289. iSavepoint = db->nSavepoint - iSavepoint - 1;
  81290. if( p1==SAVEPOINT_ROLLBACK ){
  81291. isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
  81292. for(ii=0; ii<db->nDb; ii++){
  81293. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  81294. SQLITE_ABORT_ROLLBACK,
  81295. isSchemaChange==0);
  81296. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  81297. }
  81298. }else{
  81299. isSchemaChange = 0;
  81300. }
  81301. for(ii=0; ii<db->nDb; ii++){
  81302. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  81303. if( rc!=SQLITE_OK ){
  81304. goto abort_due_to_error;
  81305. }
  81306. }
  81307. if( isSchemaChange ){
  81308. sqlite3ExpirePreparedStatements(db, 0);
  81309. sqlite3ResetAllSchemasOfConnection(db);
  81310. db->mDbFlags |= DBFLAG_SchemaChange;
  81311. }
  81312. }
  81313. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  81314. ** savepoints nested inside of the savepoint being operated on. */
  81315. while( db->pSavepoint!=pSavepoint ){
  81316. pTmp = db->pSavepoint;
  81317. db->pSavepoint = pTmp->pNext;
  81318. sqlite3DbFree(db, pTmp);
  81319. db->nSavepoint--;
  81320. }
  81321. /* If it is a RELEASE, then destroy the savepoint being operated on
  81322. ** too. If it is a ROLLBACK TO, then set the number of deferred
  81323. ** constraint violations present in the database to the value stored
  81324. ** when the savepoint was created. */
  81325. if( p1==SAVEPOINT_RELEASE ){
  81326. assert( pSavepoint==db->pSavepoint );
  81327. db->pSavepoint = pSavepoint->pNext;
  81328. sqlite3DbFree(db, pSavepoint);
  81329. if( !isTransaction ){
  81330. db->nSavepoint--;
  81331. }
  81332. }else{
  81333. db->nDeferredCons = pSavepoint->nDeferredCons;
  81334. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  81335. }
  81336. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  81337. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  81338. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  81339. }
  81340. }
  81341. }
  81342. if( rc ) goto abort_due_to_error;
  81343. break;
  81344. }
  81345. /* Opcode: AutoCommit P1 P2 * * *
  81346. **
  81347. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  81348. ** back any currently active btree transactions. If there are any active
  81349. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  81350. ** there are active writing VMs or active VMs that use shared cache.
  81351. **
  81352. ** This instruction causes the VM to halt.
  81353. */
  81354. case OP_AutoCommit: {
  81355. int desiredAutoCommit;
  81356. int iRollback;
  81357. desiredAutoCommit = pOp->p1;
  81358. iRollback = pOp->p2;
  81359. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  81360. assert( desiredAutoCommit==1 || iRollback==0 );
  81361. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  81362. assert( p->bIsReader );
  81363. if( desiredAutoCommit!=db->autoCommit ){
  81364. if( iRollback ){
  81365. assert( desiredAutoCommit==1 );
  81366. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  81367. db->autoCommit = 1;
  81368. }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
  81369. /* If this instruction implements a COMMIT and other VMs are writing
  81370. ** return an error indicating that the other VMs must complete first.
  81371. */
  81372. sqlite3VdbeError(p, "cannot commit transaction - "
  81373. "SQL statements in progress");
  81374. rc = SQLITE_BUSY;
  81375. goto abort_due_to_error;
  81376. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  81377. goto vdbe_return;
  81378. }else{
  81379. db->autoCommit = (u8)desiredAutoCommit;
  81380. }
  81381. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  81382. p->pc = (int)(pOp - aOp);
  81383. db->autoCommit = (u8)(1-desiredAutoCommit);
  81384. p->rc = rc = SQLITE_BUSY;
  81385. goto vdbe_return;
  81386. }
  81387. assert( db->nStatement==0 );
  81388. sqlite3CloseSavepoints(db);
  81389. if( p->rc==SQLITE_OK ){
  81390. rc = SQLITE_DONE;
  81391. }else{
  81392. rc = SQLITE_ERROR;
  81393. }
  81394. goto vdbe_return;
  81395. }else{
  81396. sqlite3VdbeError(p,
  81397. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  81398. (iRollback)?"cannot rollback - no transaction is active":
  81399. "cannot commit - no transaction is active"));
  81400. rc = SQLITE_ERROR;
  81401. goto abort_due_to_error;
  81402. }
  81403. break;
  81404. }
  81405. /* Opcode: Transaction P1 P2 P3 P4 P5
  81406. **
  81407. ** Begin a transaction on database P1 if a transaction is not already
  81408. ** active.
  81409. ** If P2 is non-zero, then a write-transaction is started, or if a
  81410. ** read-transaction is already active, it is upgraded to a write-transaction.
  81411. ** If P2 is zero, then a read-transaction is started.
  81412. **
  81413. ** P1 is the index of the database file on which the transaction is
  81414. ** started. Index 0 is the main database file and index 1 is the
  81415. ** file used for temporary tables. Indices of 2 or more are used for
  81416. ** attached databases.
  81417. **
  81418. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  81419. ** true (this flag is set if the Vdbe may modify more than one row and may
  81420. ** throw an ABORT exception), a statement transaction may also be opened.
  81421. ** More specifically, a statement transaction is opened iff the database
  81422. ** connection is currently not in autocommit mode, or if there are other
  81423. ** active statements. A statement transaction allows the changes made by this
  81424. ** VDBE to be rolled back after an error without having to roll back the
  81425. ** entire transaction. If no error is encountered, the statement transaction
  81426. ** will automatically commit when the VDBE halts.
  81427. **
  81428. ** If P5!=0 then this opcode also checks the schema cookie against P3
  81429. ** and the schema generation counter against P4.
  81430. ** The cookie changes its value whenever the database schema changes.
  81431. ** This operation is used to detect when that the cookie has changed
  81432. ** and that the current process needs to reread the schema. If the schema
  81433. ** cookie in P3 differs from the schema cookie in the database header or
  81434. ** if the schema generation counter in P4 differs from the current
  81435. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  81436. ** halts. The sqlite3_step() wrapper function might then reprepare the
  81437. ** statement and rerun it from the beginning.
  81438. */
  81439. case OP_Transaction: {
  81440. Btree *pBt;
  81441. int iMeta = 0;
  81442. assert( p->bIsReader );
  81443. assert( p->readOnly==0 || pOp->p2==0 );
  81444. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  81445. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  81446. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  81447. rc = SQLITE_READONLY;
  81448. goto abort_due_to_error;
  81449. }
  81450. pBt = db->aDb[pOp->p1].pBt;
  81451. if( pBt ){
  81452. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
  81453. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  81454. testcase( rc==SQLITE_BUSY_RECOVERY );
  81455. if( rc!=SQLITE_OK ){
  81456. if( (rc&0xff)==SQLITE_BUSY ){
  81457. p->pc = (int)(pOp - aOp);
  81458. p->rc = rc;
  81459. goto vdbe_return;
  81460. }
  81461. goto abort_due_to_error;
  81462. }
  81463. if( pOp->p2 && p->usesStmtJournal
  81464. && (db->autoCommit==0 || db->nVdbeRead>1)
  81465. ){
  81466. assert( sqlite3BtreeIsInTrans(pBt) );
  81467. if( p->iStatement==0 ){
  81468. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  81469. db->nStatement++;
  81470. p->iStatement = db->nSavepoint + db->nStatement;
  81471. }
  81472. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  81473. if( rc==SQLITE_OK ){
  81474. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  81475. }
  81476. /* Store the current value of the database handles deferred constraint
  81477. ** counter. If the statement transaction needs to be rolled back,
  81478. ** the value of this counter needs to be restored too. */
  81479. p->nStmtDefCons = db->nDeferredCons;
  81480. p->nStmtDefImmCons = db->nDeferredImmCons;
  81481. }
  81482. }
  81483. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  81484. if( pOp->p5
  81485. && (iMeta!=pOp->p3
  81486. || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
  81487. ){
  81488. /*
  81489. ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
  81490. ** version is checked to ensure that the schema has not changed since the
  81491. ** SQL statement was prepared.
  81492. */
  81493. sqlite3DbFree(db, p->zErrMsg);
  81494. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  81495. /* If the schema-cookie from the database file matches the cookie
  81496. ** stored with the in-memory representation of the schema, do
  81497. ** not reload the schema from the database file.
  81498. **
  81499. ** If virtual-tables are in use, this is not just an optimization.
  81500. ** Often, v-tables store their data in other SQLite tables, which
  81501. ** are queried from within xNext() and other v-table methods using
  81502. ** prepared queries. If such a query is out-of-date, we do not want to
  81503. ** discard the database schema, as the user code implementing the
  81504. ** v-table would have to be ready for the sqlite3_vtab structure itself
  81505. ** to be invalidated whenever sqlite3_step() is called from within
  81506. ** a v-table method.
  81507. */
  81508. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  81509. sqlite3ResetOneSchema(db, pOp->p1);
  81510. }
  81511. p->expired = 1;
  81512. rc = SQLITE_SCHEMA;
  81513. }
  81514. if( rc ) goto abort_due_to_error;
  81515. break;
  81516. }
  81517. /* Opcode: ReadCookie P1 P2 P3 * *
  81518. **
  81519. ** Read cookie number P3 from database P1 and write it into register P2.
  81520. ** P3==1 is the schema version. P3==2 is the database format.
  81521. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  81522. ** the main database file and P1==1 is the database file used to store
  81523. ** temporary tables.
  81524. **
  81525. ** There must be a read-lock on the database (either a transaction
  81526. ** must be started or there must be an open cursor) before
  81527. ** executing this instruction.
  81528. */
  81529. case OP_ReadCookie: { /* out2 */
  81530. int iMeta;
  81531. int iDb;
  81532. int iCookie;
  81533. assert( p->bIsReader );
  81534. iDb = pOp->p1;
  81535. iCookie = pOp->p3;
  81536. assert( pOp->p3<SQLITE_N_BTREE_META );
  81537. assert( iDb>=0 && iDb<db->nDb );
  81538. assert( db->aDb[iDb].pBt!=0 );
  81539. assert( DbMaskTest(p->btreeMask, iDb) );
  81540. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  81541. pOut = out2Prerelease(p, pOp);
  81542. pOut->u.i = iMeta;
  81543. break;
  81544. }
  81545. /* Opcode: SetCookie P1 P2 P3 * *
  81546. **
  81547. ** Write the integer value P3 into cookie number P2 of database P1.
  81548. ** P2==1 is the schema version. P2==2 is the database format.
  81549. ** P2==3 is the recommended pager cache
  81550. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  81551. ** database file used to store temporary tables.
  81552. **
  81553. ** A transaction must be started before executing this opcode.
  81554. */
  81555. case OP_SetCookie: {
  81556. Db *pDb;
  81557. sqlite3VdbeIncrWriteCounter(p, 0);
  81558. assert( pOp->p2<SQLITE_N_BTREE_META );
  81559. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  81560. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  81561. assert( p->readOnly==0 );
  81562. pDb = &db->aDb[pOp->p1];
  81563. assert( pDb->pBt!=0 );
  81564. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  81565. /* See note about index shifting on OP_ReadCookie */
  81566. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
  81567. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  81568. /* When the schema cookie changes, record the new cookie internally */
  81569. pDb->pSchema->schema_cookie = pOp->p3;
  81570. db->mDbFlags |= DBFLAG_SchemaChange;
  81571. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  81572. /* Record changes in the file format */
  81573. pDb->pSchema->file_format = pOp->p3;
  81574. }
  81575. if( pOp->p1==1 ){
  81576. /* Invalidate all prepared statements whenever the TEMP database
  81577. ** schema is changed. Ticket #1644 */
  81578. sqlite3ExpirePreparedStatements(db, 0);
  81579. p->expired = 0;
  81580. }
  81581. if( rc ) goto abort_due_to_error;
  81582. break;
  81583. }
  81584. /* Opcode: OpenRead P1 P2 P3 P4 P5
  81585. ** Synopsis: root=P2 iDb=P3
  81586. **
  81587. ** Open a read-only cursor for the database table whose root page is
  81588. ** P2 in a database file. The database file is determined by P3.
  81589. ** P3==0 means the main database, P3==1 means the database used for
  81590. ** temporary tables, and P3>1 means used the corresponding attached
  81591. ** database. Give the new cursor an identifier of P1. The P1
  81592. ** values need not be contiguous but all P1 values should be small integers.
  81593. ** It is an error for P1 to be negative.
  81594. **
  81595. ** Allowed P5 bits:
  81596. ** <ul>
  81597. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  81598. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  81599. ** of OP_SeekLE/OP_IdxGT)
  81600. ** </ul>
  81601. **
  81602. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  81603. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  81604. ** object, then table being opened must be an [index b-tree] where the
  81605. ** KeyInfo object defines the content and collating
  81606. ** sequence of that index b-tree. Otherwise, if P4 is an integer
  81607. ** value, then the table being opened must be a [table b-tree] with a
  81608. ** number of columns no less than the value of P4.
  81609. **
  81610. ** See also: OpenWrite, ReopenIdx
  81611. */
  81612. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  81613. ** Synopsis: root=P2 iDb=P3
  81614. **
  81615. ** The ReopenIdx opcode works like OP_OpenRead except that it first
  81616. ** checks to see if the cursor on P1 is already open on the same
  81617. ** b-tree and if it is this opcode becomes a no-op. In other words,
  81618. ** if the cursor is already open, do not reopen it.
  81619. **
  81620. ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
  81621. ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
  81622. ** be the same as every other ReopenIdx or OpenRead for the same cursor
  81623. ** number.
  81624. **
  81625. ** Allowed P5 bits:
  81626. ** <ul>
  81627. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  81628. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  81629. ** of OP_SeekLE/OP_IdxGT)
  81630. ** </ul>
  81631. **
  81632. ** See also: OP_OpenRead, OP_OpenWrite
  81633. */
  81634. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  81635. ** Synopsis: root=P2 iDb=P3
  81636. **
  81637. ** Open a read/write cursor named P1 on the table or index whose root
  81638. ** page is P2 (or whose root page is held in register P2 if the
  81639. ** OPFLAG_P2ISREG bit is set in P5 - see below).
  81640. **
  81641. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  81642. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  81643. ** object, then table being opened must be an [index b-tree] where the
  81644. ** KeyInfo object defines the content and collating
  81645. ** sequence of that index b-tree. Otherwise, if P4 is an integer
  81646. ** value, then the table being opened must be a [table b-tree] with a
  81647. ** number of columns no less than the value of P4.
  81648. **
  81649. ** Allowed P5 bits:
  81650. ** <ul>
  81651. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  81652. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  81653. ** of OP_SeekLE/OP_IdxGT)
  81654. ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
  81655. ** and subsequently delete entries in an index btree. This is a
  81656. ** hint to the storage engine that the storage engine is allowed to
  81657. ** ignore. The hint is not used by the official SQLite b*tree storage
  81658. ** engine, but is used by COMDB2.
  81659. ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
  81660. ** as the root page, not the value of P2 itself.
  81661. ** </ul>
  81662. **
  81663. ** This instruction works like OpenRead except that it opens the cursor
  81664. ** in read/write mode.
  81665. **
  81666. ** See also: OP_OpenRead, OP_ReopenIdx
  81667. */
  81668. case OP_ReopenIdx: {
  81669. int nField;
  81670. KeyInfo *pKeyInfo;
  81671. int p2;
  81672. int iDb;
  81673. int wrFlag;
  81674. Btree *pX;
  81675. VdbeCursor *pCur;
  81676. Db *pDb;
  81677. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  81678. assert( pOp->p4type==P4_KEYINFO );
  81679. pCur = p->apCsr[pOp->p1];
  81680. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  81681. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  81682. goto open_cursor_set_hints;
  81683. }
  81684. /* If the cursor is not currently open or is open on a different
  81685. ** index, then fall through into OP_OpenRead to force a reopen */
  81686. case OP_OpenRead:
  81687. case OP_OpenWrite:
  81688. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  81689. assert( p->bIsReader );
  81690. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  81691. || p->readOnly==0 );
  81692. if( p->expired==1 ){
  81693. rc = SQLITE_ABORT_ROLLBACK;
  81694. goto abort_due_to_error;
  81695. }
  81696. nField = 0;
  81697. pKeyInfo = 0;
  81698. p2 = pOp->p2;
  81699. iDb = pOp->p3;
  81700. assert( iDb>=0 && iDb<db->nDb );
  81701. assert( DbMaskTest(p->btreeMask, iDb) );
  81702. pDb = &db->aDb[iDb];
  81703. pX = pDb->pBt;
  81704. assert( pX!=0 );
  81705. if( pOp->opcode==OP_OpenWrite ){
  81706. assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
  81707. wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
  81708. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81709. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  81710. p->minWriteFileFormat = pDb->pSchema->file_format;
  81711. }
  81712. }else{
  81713. wrFlag = 0;
  81714. }
  81715. if( pOp->p5 & OPFLAG_P2ISREG ){
  81716. assert( p2>0 );
  81717. assert( p2<=(p->nMem+1 - p->nCursor) );
  81718. assert( pOp->opcode==OP_OpenWrite );
  81719. pIn2 = &aMem[p2];
  81720. assert( memIsValid(pIn2) );
  81721. assert( (pIn2->flags & MEM_Int)!=0 );
  81722. sqlite3VdbeMemIntegerify(pIn2);
  81723. p2 = (int)pIn2->u.i;
  81724. /* The p2 value always comes from a prior OP_CreateBtree opcode and
  81725. ** that opcode will always set the p2 value to 2 or more or else fail.
  81726. ** If there were a failure, the prepared statement would have halted
  81727. ** before reaching this instruction. */
  81728. assert( p2>=2 );
  81729. }
  81730. if( pOp->p4type==P4_KEYINFO ){
  81731. pKeyInfo = pOp->p4.pKeyInfo;
  81732. assert( pKeyInfo->enc==ENC(db) );
  81733. assert( pKeyInfo->db==db );
  81734. nField = pKeyInfo->nAllField;
  81735. }else if( pOp->p4type==P4_INT32 ){
  81736. nField = pOp->p4.i;
  81737. }
  81738. assert( pOp->p1>=0 );
  81739. assert( nField>=0 );
  81740. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  81741. pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
  81742. if( pCur==0 ) goto no_mem;
  81743. pCur->nullRow = 1;
  81744. pCur->isOrdered = 1;
  81745. pCur->pgnoRoot = p2;
  81746. #ifdef SQLITE_DEBUG
  81747. pCur->wrFlag = wrFlag;
  81748. #endif
  81749. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
  81750. pCur->pKeyInfo = pKeyInfo;
  81751. /* Set the VdbeCursor.isTable variable. Previous versions of
  81752. ** SQLite used to check if the root-page flags were sane at this point
  81753. ** and report database corruption if they were not, but this check has
  81754. ** since moved into the btree layer. */
  81755. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  81756. open_cursor_set_hints:
  81757. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  81758. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  81759. testcase( pOp->p5 & OPFLAG_BULKCSR );
  81760. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  81761. testcase( pOp->p2 & OPFLAG_SEEKEQ );
  81762. #endif
  81763. sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
  81764. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  81765. if( rc ) goto abort_due_to_error;
  81766. break;
  81767. }
  81768. /* Opcode: OpenDup P1 P2 * * *
  81769. **
  81770. ** Open a new cursor P1 that points to the same ephemeral table as
  81771. ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
  81772. ** opcode. Only ephemeral cursors may be duplicated.
  81773. **
  81774. ** Duplicate ephemeral cursors are used for self-joins of materialized views.
  81775. */
  81776. case OP_OpenDup: {
  81777. VdbeCursor *pOrig; /* The original cursor to be duplicated */
  81778. VdbeCursor *pCx; /* The new cursor */
  81779. pOrig = p->apCsr[pOp->p2];
  81780. assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
  81781. pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
  81782. if( pCx==0 ) goto no_mem;
  81783. pCx->nullRow = 1;
  81784. pCx->isEphemeral = 1;
  81785. pCx->pKeyInfo = pOrig->pKeyInfo;
  81786. pCx->isTable = pOrig->isTable;
  81787. pCx->pgnoRoot = pOrig->pgnoRoot;
  81788. pCx->isOrdered = pOrig->isOrdered;
  81789. rc = sqlite3BtreeCursor(pOrig->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
  81790. pCx->pKeyInfo, pCx->uc.pCursor);
  81791. /* The sqlite3BtreeCursor() routine can only fail for the first cursor
  81792. ** opened for a database. Since there is already an open cursor when this
  81793. ** opcode is run, the sqlite3BtreeCursor() cannot fail */
  81794. assert( rc==SQLITE_OK );
  81795. break;
  81796. }
  81797. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  81798. ** Synopsis: nColumn=P2
  81799. **
  81800. ** Open a new cursor P1 to a transient table.
  81801. ** The cursor is always opened read/write even if
  81802. ** the main database is read-only. The ephemeral
  81803. ** table is deleted automatically when the cursor is closed.
  81804. **
  81805. ** If the cursor P1 is already opened on an ephemeral table, the table
  81806. ** is cleared (all content is erased).
  81807. **
  81808. ** P2 is the number of columns in the ephemeral table.
  81809. ** The cursor points to a BTree table if P4==0 and to a BTree index
  81810. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  81811. ** that defines the format of keys in the index.
  81812. **
  81813. ** The P5 parameter can be a mask of the BTREE_* flags defined
  81814. ** in btree.h. These flags control aspects of the operation of
  81815. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  81816. ** added automatically.
  81817. */
  81818. /* Opcode: OpenAutoindex P1 P2 * P4 *
  81819. ** Synopsis: nColumn=P2
  81820. **
  81821. ** This opcode works the same as OP_OpenEphemeral. It has a
  81822. ** different name to distinguish its use. Tables created using
  81823. ** by this opcode will be used for automatically created transient
  81824. ** indices in joins.
  81825. */
  81826. case OP_OpenAutoindex:
  81827. case OP_OpenEphemeral: {
  81828. VdbeCursor *pCx;
  81829. KeyInfo *pKeyInfo;
  81830. static const int vfsFlags =
  81831. SQLITE_OPEN_READWRITE |
  81832. SQLITE_OPEN_CREATE |
  81833. SQLITE_OPEN_EXCLUSIVE |
  81834. SQLITE_OPEN_DELETEONCLOSE |
  81835. SQLITE_OPEN_TRANSIENT_DB;
  81836. assert( pOp->p1>=0 );
  81837. assert( pOp->p2>=0 );
  81838. pCx = p->apCsr[pOp->p1];
  81839. if( pCx ){
  81840. /* If the ephermeral table is already open, erase all existing content
  81841. ** so that the table is empty again, rather than creating a new table. */
  81842. rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);
  81843. }else{
  81844. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
  81845. if( pCx==0 ) goto no_mem;
  81846. pCx->nullRow = 1;
  81847. pCx->isEphemeral = 1;
  81848. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
  81849. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
  81850. vfsFlags);
  81851. if( rc==SQLITE_OK ){
  81852. rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
  81853. }
  81854. if( rc==SQLITE_OK ){
  81855. /* If a transient index is required, create it by calling
  81856. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  81857. ** opening it. If a transient table is required, just use the
  81858. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  81859. */
  81860. if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  81861. assert( pOp->p4type==P4_KEYINFO );
  81862. rc = sqlite3BtreeCreateTable(pCx->pBtx, (int*)&pCx->pgnoRoot,
  81863. BTREE_BLOBKEY | pOp->p5);
  81864. if( rc==SQLITE_OK ){
  81865. assert( pCx->pgnoRoot==MASTER_ROOT+1 );
  81866. assert( pKeyInfo->db==db );
  81867. assert( pKeyInfo->enc==ENC(db) );
  81868. rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
  81869. pKeyInfo, pCx->uc.pCursor);
  81870. }
  81871. pCx->isTable = 0;
  81872. }else{
  81873. pCx->pgnoRoot = MASTER_ROOT;
  81874. rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
  81875. 0, pCx->uc.pCursor);
  81876. pCx->isTable = 1;
  81877. }
  81878. }
  81879. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  81880. }
  81881. if( rc ) goto abort_due_to_error;
  81882. break;
  81883. }
  81884. /* Opcode: SorterOpen P1 P2 P3 P4 *
  81885. **
  81886. ** This opcode works like OP_OpenEphemeral except that it opens
  81887. ** a transient index that is specifically designed to sort large
  81888. ** tables using an external merge-sort algorithm.
  81889. **
  81890. ** If argument P3 is non-zero, then it indicates that the sorter may
  81891. ** assume that a stable sort considering the first P3 fields of each
  81892. ** key is sufficient to produce the required results.
  81893. */
  81894. case OP_SorterOpen: {
  81895. VdbeCursor *pCx;
  81896. assert( pOp->p1>=0 );
  81897. assert( pOp->p2>=0 );
  81898. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
  81899. if( pCx==0 ) goto no_mem;
  81900. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  81901. assert( pCx->pKeyInfo->db==db );
  81902. assert( pCx->pKeyInfo->enc==ENC(db) );
  81903. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  81904. if( rc ) goto abort_due_to_error;
  81905. break;
  81906. }
  81907. /* Opcode: SequenceTest P1 P2 * * *
  81908. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  81909. **
  81910. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  81911. ** to P2. Regardless of whether or not the jump is taken, increment the
  81912. ** the sequence value.
  81913. */
  81914. case OP_SequenceTest: {
  81915. VdbeCursor *pC;
  81916. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81917. pC = p->apCsr[pOp->p1];
  81918. assert( isSorter(pC) );
  81919. if( (pC->seqCount++)==0 ){
  81920. goto jump_to_p2;
  81921. }
  81922. break;
  81923. }
  81924. /* Opcode: OpenPseudo P1 P2 P3 * *
  81925. ** Synopsis: P3 columns in r[P2]
  81926. **
  81927. ** Open a new cursor that points to a fake table that contains a single
  81928. ** row of data. The content of that one row is the content of memory
  81929. ** register P2. In other words, cursor P1 becomes an alias for the
  81930. ** MEM_Blob content contained in register P2.
  81931. **
  81932. ** A pseudo-table created by this opcode is used to hold a single
  81933. ** row output from the sorter so that the row can be decomposed into
  81934. ** individual columns using the OP_Column opcode. The OP_Column opcode
  81935. ** is the only cursor opcode that works with a pseudo-table.
  81936. **
  81937. ** P3 is the number of fields in the records that will be stored by
  81938. ** the pseudo-table.
  81939. */
  81940. case OP_OpenPseudo: {
  81941. VdbeCursor *pCx;
  81942. assert( pOp->p1>=0 );
  81943. assert( pOp->p3>=0 );
  81944. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
  81945. if( pCx==0 ) goto no_mem;
  81946. pCx->nullRow = 1;
  81947. pCx->seekResult = pOp->p2;
  81948. pCx->isTable = 1;
  81949. /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
  81950. ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
  81951. ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
  81952. ** which is a performance optimization */
  81953. pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
  81954. assert( pOp->p5==0 );
  81955. break;
  81956. }
  81957. /* Opcode: Close P1 * * * *
  81958. **
  81959. ** Close a cursor previously opened as P1. If P1 is not
  81960. ** currently open, this instruction is a no-op.
  81961. */
  81962. case OP_Close: {
  81963. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81964. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  81965. p->apCsr[pOp->p1] = 0;
  81966. break;
  81967. }
  81968. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  81969. /* Opcode: ColumnsUsed P1 * * P4 *
  81970. **
  81971. ** This opcode (which only exists if SQLite was compiled with
  81972. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  81973. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  81974. ** (P4_INT64) in which the first 63 bits are one for each of the
  81975. ** first 63 columns of the table or index that are actually used
  81976. ** by the cursor. The high-order bit is set if any column after
  81977. ** the 64th is used.
  81978. */
  81979. case OP_ColumnsUsed: {
  81980. VdbeCursor *pC;
  81981. pC = p->apCsr[pOp->p1];
  81982. assert( pC->eCurType==CURTYPE_BTREE );
  81983. pC->maskUsed = *(u64*)pOp->p4.pI64;
  81984. break;
  81985. }
  81986. #endif
  81987. /* Opcode: SeekGE P1 P2 P3 P4 *
  81988. ** Synopsis: key=r[P3@P4]
  81989. **
  81990. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  81991. ** use the value in register P3 as the key. If cursor P1 refers
  81992. ** to an SQL index, then P3 is the first in an array of P4 registers
  81993. ** that are used as an unpacked index key.
  81994. **
  81995. ** Reposition cursor P1 so that it points to the smallest entry that
  81996. ** is greater than or equal to the key value. If there are no records
  81997. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  81998. **
  81999. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  82000. ** opcode will always land on a record that equally equals the key, or
  82001. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  82002. ** opcode must be followed by an IdxLE opcode with the same arguments.
  82003. ** The IdxLE opcode will be skipped if this opcode succeeds, but the
  82004. ** IdxLE opcode will be used on subsequent loop iterations.
  82005. **
  82006. ** This opcode leaves the cursor configured to move in forward order,
  82007. ** from the beginning toward the end. In other words, the cursor is
  82008. ** configured to use Next, not Prev.
  82009. **
  82010. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  82011. */
  82012. /* Opcode: SeekGT P1 P2 P3 P4 *
  82013. ** Synopsis: key=r[P3@P4]
  82014. **
  82015. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  82016. ** use the value in register P3 as a key. If cursor P1 refers
  82017. ** to an SQL index, then P3 is the first in an array of P4 registers
  82018. ** that are used as an unpacked index key.
  82019. **
  82020. ** Reposition cursor P1 so that it points to the smallest entry that
  82021. ** is greater than the key value. If there are no records greater than
  82022. ** the key and P2 is not zero, then jump to P2.
  82023. **
  82024. ** This opcode leaves the cursor configured to move in forward order,
  82025. ** from the beginning toward the end. In other words, the cursor is
  82026. ** configured to use Next, not Prev.
  82027. **
  82028. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  82029. */
  82030. /* Opcode: SeekLT P1 P2 P3 P4 *
  82031. ** Synopsis: key=r[P3@P4]
  82032. **
  82033. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  82034. ** use the value in register P3 as a key. If cursor P1 refers
  82035. ** to an SQL index, then P3 is the first in an array of P4 registers
  82036. ** that are used as an unpacked index key.
  82037. **
  82038. ** Reposition cursor P1 so that it points to the largest entry that
  82039. ** is less than the key value. If there are no records less than
  82040. ** the key and P2 is not zero, then jump to P2.
  82041. **
  82042. ** This opcode leaves the cursor configured to move in reverse order,
  82043. ** from the end toward the beginning. In other words, the cursor is
  82044. ** configured to use Prev, not Next.
  82045. **
  82046. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  82047. */
  82048. /* Opcode: SeekLE P1 P2 P3 P4 *
  82049. ** Synopsis: key=r[P3@P4]
  82050. **
  82051. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  82052. ** use the value in register P3 as a key. If cursor P1 refers
  82053. ** to an SQL index, then P3 is the first in an array of P4 registers
  82054. ** that are used as an unpacked index key.
  82055. **
  82056. ** Reposition cursor P1 so that it points to the largest entry that
  82057. ** is less than or equal to the key value. If there are no records
  82058. ** less than or equal to the key and P2 is not zero, then jump to P2.
  82059. **
  82060. ** This opcode leaves the cursor configured to move in reverse order,
  82061. ** from the end toward the beginning. In other words, the cursor is
  82062. ** configured to use Prev, not Next.
  82063. **
  82064. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  82065. ** opcode will always land on a record that equally equals the key, or
  82066. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  82067. ** opcode must be followed by an IdxGE opcode with the same arguments.
  82068. ** The IdxGE opcode will be skipped if this opcode succeeds, but the
  82069. ** IdxGE opcode will be used on subsequent loop iterations.
  82070. **
  82071. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  82072. */
  82073. case OP_SeekLT: /* jump, in3, group */
  82074. case OP_SeekLE: /* jump, in3, group */
  82075. case OP_SeekGE: /* jump, in3, group */
  82076. case OP_SeekGT: { /* jump, in3, group */
  82077. int res; /* Comparison result */
  82078. int oc; /* Opcode */
  82079. VdbeCursor *pC; /* The cursor to seek */
  82080. UnpackedRecord r; /* The key to seek for */
  82081. int nField; /* Number of columns or fields in the key */
  82082. i64 iKey; /* The rowid we are to seek to */
  82083. int eqOnly; /* Only interested in == results */
  82084. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82085. assert( pOp->p2!=0 );
  82086. pC = p->apCsr[pOp->p1];
  82087. assert( pC!=0 );
  82088. assert( pC->eCurType==CURTYPE_BTREE );
  82089. assert( OP_SeekLE == OP_SeekLT+1 );
  82090. assert( OP_SeekGE == OP_SeekLT+2 );
  82091. assert( OP_SeekGT == OP_SeekLT+3 );
  82092. assert( pC->isOrdered );
  82093. assert( pC->uc.pCursor!=0 );
  82094. oc = pOp->opcode;
  82095. eqOnly = 0;
  82096. pC->nullRow = 0;
  82097. #ifdef SQLITE_DEBUG
  82098. pC->seekOp = pOp->opcode;
  82099. #endif
  82100. if( pC->isTable ){
  82101. /* The BTREE_SEEK_EQ flag is only set on index cursors */
  82102. assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
  82103. || CORRUPT_DB );
  82104. /* The input value in P3 might be of any type: integer, real, string,
  82105. ** blob, or NULL. But it needs to be an integer before we can do
  82106. ** the seek, so convert it. */
  82107. pIn3 = &aMem[pOp->p3];
  82108. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  82109. applyNumericAffinity(pIn3, 0);
  82110. }
  82111. iKey = sqlite3VdbeIntValue(pIn3);
  82112. /* If the P3 value could not be converted into an integer without
  82113. ** loss of information, then special processing is required... */
  82114. if( (pIn3->flags & MEM_Int)==0 ){
  82115. if( (pIn3->flags & MEM_Real)==0 ){
  82116. /* If the P3 value cannot be converted into any kind of a number,
  82117. ** then the seek is not possible, so jump to P2 */
  82118. VdbeBranchTaken(1,2); goto jump_to_p2;
  82119. break;
  82120. }
  82121. /* If the approximation iKey is larger than the actual real search
  82122. ** term, substitute >= for > and < for <=. e.g. if the search term
  82123. ** is 4.9 and the integer approximation 5:
  82124. **
  82125. ** (x > 4.9) -> (x >= 5)
  82126. ** (x <= 4.9) -> (x < 5)
  82127. */
  82128. if( pIn3->u.r<(double)iKey ){
  82129. assert( OP_SeekGE==(OP_SeekGT-1) );
  82130. assert( OP_SeekLT==(OP_SeekLE-1) );
  82131. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  82132. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  82133. }
  82134. /* If the approximation iKey is smaller than the actual real search
  82135. ** term, substitute <= for < and > for >=. */
  82136. else if( pIn3->u.r>(double)iKey ){
  82137. assert( OP_SeekLE==(OP_SeekLT+1) );
  82138. assert( OP_SeekGT==(OP_SeekGE+1) );
  82139. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  82140. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  82141. }
  82142. }
  82143. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
  82144. pC->movetoTarget = iKey; /* Used by OP_Delete */
  82145. if( rc!=SQLITE_OK ){
  82146. goto abort_due_to_error;
  82147. }
  82148. }else{
  82149. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  82150. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  82151. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  82152. */
  82153. if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
  82154. eqOnly = 1;
  82155. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  82156. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  82157. assert( pOp[1].p1==pOp[0].p1 );
  82158. assert( pOp[1].p2==pOp[0].p2 );
  82159. assert( pOp[1].p3==pOp[0].p3 );
  82160. assert( pOp[1].p4.i==pOp[0].p4.i );
  82161. }
  82162. nField = pOp->p4.i;
  82163. assert( pOp->p4type==P4_INT32 );
  82164. assert( nField>0 );
  82165. r.pKeyInfo = pC->pKeyInfo;
  82166. r.nField = (u16)nField;
  82167. /* The next line of code computes as follows, only faster:
  82168. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  82169. ** r.default_rc = -1;
  82170. ** }else{
  82171. ** r.default_rc = +1;
  82172. ** }
  82173. */
  82174. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  82175. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  82176. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  82177. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  82178. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  82179. r.aMem = &aMem[pOp->p3];
  82180. #ifdef SQLITE_DEBUG
  82181. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  82182. #endif
  82183. r.eqSeen = 0;
  82184. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
  82185. if( rc!=SQLITE_OK ){
  82186. goto abort_due_to_error;
  82187. }
  82188. if( eqOnly && r.eqSeen==0 ){
  82189. assert( res!=0 );
  82190. goto seek_not_found;
  82191. }
  82192. }
  82193. pC->deferredMoveto = 0;
  82194. pC->cacheStatus = CACHE_STALE;
  82195. #ifdef SQLITE_TEST
  82196. sqlite3_search_count++;
  82197. #endif
  82198. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  82199. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  82200. res = 0;
  82201. rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
  82202. if( rc!=SQLITE_OK ){
  82203. if( rc==SQLITE_DONE ){
  82204. rc = SQLITE_OK;
  82205. res = 1;
  82206. }else{
  82207. goto abort_due_to_error;
  82208. }
  82209. }
  82210. }else{
  82211. res = 0;
  82212. }
  82213. }else{
  82214. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  82215. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  82216. res = 0;
  82217. rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
  82218. if( rc!=SQLITE_OK ){
  82219. if( rc==SQLITE_DONE ){
  82220. rc = SQLITE_OK;
  82221. res = 1;
  82222. }else{
  82223. goto abort_due_to_error;
  82224. }
  82225. }
  82226. }else{
  82227. /* res might be negative because the table is empty. Check to
  82228. ** see if this is the case.
  82229. */
  82230. res = sqlite3BtreeEof(pC->uc.pCursor);
  82231. }
  82232. }
  82233. seek_not_found:
  82234. assert( pOp->p2>0 );
  82235. VdbeBranchTaken(res!=0,2);
  82236. if( res ){
  82237. goto jump_to_p2;
  82238. }else if( eqOnly ){
  82239. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  82240. pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
  82241. }
  82242. break;
  82243. }
  82244. /* Opcode: SeekHit P1 P2 * * *
  82245. ** Synopsis: seekHit=P2
  82246. **
  82247. ** Set the seekHit flag on cursor P1 to the value in P2.
  82248. ** The seekHit flag is used by the IfNoHope opcode.
  82249. **
  82250. ** P1 must be a valid b-tree cursor. P2 must be a boolean value,
  82251. ** either 0 or 1.
  82252. */
  82253. case OP_SeekHit: {
  82254. VdbeCursor *pC;
  82255. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82256. pC = p->apCsr[pOp->p1];
  82257. assert( pC!=0 );
  82258. assert( pOp->p2==0 || pOp->p2==1 );
  82259. pC->seekHit = pOp->p2 & 1;
  82260. break;
  82261. }
  82262. /* Opcode: Found P1 P2 P3 P4 *
  82263. ** Synopsis: key=r[P3@P4]
  82264. **
  82265. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  82266. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  82267. ** record.
  82268. **
  82269. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  82270. ** is a prefix of any entry in P1 then a jump is made to P2 and
  82271. ** P1 is left pointing at the matching entry.
  82272. **
  82273. ** This operation leaves the cursor in a state where it can be
  82274. ** advanced in the forward direction. The Next instruction will work,
  82275. ** but not the Prev instruction.
  82276. **
  82277. ** See also: NotFound, NoConflict, NotExists. SeekGe
  82278. */
  82279. /* Opcode: NotFound P1 P2 P3 P4 *
  82280. ** Synopsis: key=r[P3@P4]
  82281. **
  82282. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  82283. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  82284. ** record.
  82285. **
  82286. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  82287. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  82288. ** does contain an entry whose prefix matches the P3/P4 record then control
  82289. ** falls through to the next instruction and P1 is left pointing at the
  82290. ** matching entry.
  82291. **
  82292. ** This operation leaves the cursor in a state where it cannot be
  82293. ** advanced in either direction. In other words, the Next and Prev
  82294. ** opcodes do not work after this operation.
  82295. **
  82296. ** See also: Found, NotExists, NoConflict, IfNoHope
  82297. */
  82298. /* Opcode: IfNoHope P1 P2 P3 P4 *
  82299. ** Synopsis: key=r[P3@P4]
  82300. **
  82301. ** Register P3 is the first of P4 registers that form an unpacked
  82302. ** record.
  82303. **
  82304. ** Cursor P1 is on an index btree. If the seekHit flag is set on P1, then
  82305. ** this opcode is a no-op. But if the seekHit flag of P1 is clear, then
  82306. ** check to see if there is any entry in P1 that matches the
  82307. ** prefix identified by P3 and P4. If no entry matches the prefix,
  82308. ** jump to P2. Otherwise fall through.
  82309. **
  82310. ** This opcode behaves like OP_NotFound if the seekHit
  82311. ** flag is clear and it behaves like OP_Noop if the seekHit flag is set.
  82312. **
  82313. ** This opcode is used in IN clause processing for a multi-column key.
  82314. ** If an IN clause is attached to an element of the key other than the
  82315. ** left-most element, and if there are no matches on the most recent
  82316. ** seek over the whole key, then it might be that one of the key element
  82317. ** to the left is prohibiting a match, and hence there is "no hope" of
  82318. ** any match regardless of how many IN clause elements are checked.
  82319. ** In such a case, we abandon the IN clause search early, using this
  82320. ** opcode. The opcode name comes from the fact that the
  82321. ** jump is taken if there is "no hope" of achieving a match.
  82322. **
  82323. ** See also: NotFound, SeekHit
  82324. */
  82325. /* Opcode: NoConflict P1 P2 P3 P4 *
  82326. ** Synopsis: key=r[P3@P4]
  82327. **
  82328. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  82329. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  82330. ** record.
  82331. **
  82332. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  82333. ** contains any NULL value, jump immediately to P2. If all terms of the
  82334. ** record are not-NULL then a check is done to determine if any row in the
  82335. ** P1 index btree has a matching key prefix. If there are no matches, jump
  82336. ** immediately to P2. If there is a match, fall through and leave the P1
  82337. ** cursor pointing to the matching row.
  82338. **
  82339. ** This opcode is similar to OP_NotFound with the exceptions that the
  82340. ** branch is always taken if any part of the search key input is NULL.
  82341. **
  82342. ** This operation leaves the cursor in a state where it cannot be
  82343. ** advanced in either direction. In other words, the Next and Prev
  82344. ** opcodes do not work after this operation.
  82345. **
  82346. ** See also: NotFound, Found, NotExists
  82347. */
  82348. case OP_IfNoHope: { /* jump, in3 */
  82349. VdbeCursor *pC;
  82350. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82351. pC = p->apCsr[pOp->p1];
  82352. assert( pC!=0 );
  82353. if( pC->seekHit ) break;
  82354. /* Fall through into OP_NotFound */
  82355. }
  82356. case OP_NoConflict: /* jump, in3 */
  82357. case OP_NotFound: /* jump, in3 */
  82358. case OP_Found: { /* jump, in3 */
  82359. int alreadyExists;
  82360. int takeJump;
  82361. int ii;
  82362. VdbeCursor *pC;
  82363. int res;
  82364. UnpackedRecord *pFree;
  82365. UnpackedRecord *pIdxKey;
  82366. UnpackedRecord r;
  82367. #ifdef SQLITE_TEST
  82368. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  82369. #endif
  82370. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82371. assert( pOp->p4type==P4_INT32 );
  82372. pC = p->apCsr[pOp->p1];
  82373. assert( pC!=0 );
  82374. #ifdef SQLITE_DEBUG
  82375. pC->seekOp = pOp->opcode;
  82376. #endif
  82377. pIn3 = &aMem[pOp->p3];
  82378. assert( pC->eCurType==CURTYPE_BTREE );
  82379. assert( pC->uc.pCursor!=0 );
  82380. assert( pC->isTable==0 );
  82381. if( pOp->p4.i>0 ){
  82382. r.pKeyInfo = pC->pKeyInfo;
  82383. r.nField = (u16)pOp->p4.i;
  82384. r.aMem = pIn3;
  82385. #ifdef SQLITE_DEBUG
  82386. for(ii=0; ii<r.nField; ii++){
  82387. assert( memIsValid(&r.aMem[ii]) );
  82388. assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
  82389. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  82390. }
  82391. #endif
  82392. pIdxKey = &r;
  82393. pFree = 0;
  82394. }else{
  82395. assert( pIn3->flags & MEM_Blob );
  82396. rc = ExpandBlob(pIn3);
  82397. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  82398. if( rc ) goto no_mem;
  82399. pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
  82400. if( pIdxKey==0 ) goto no_mem;
  82401. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  82402. }
  82403. pIdxKey->default_rc = 0;
  82404. takeJump = 0;
  82405. if( pOp->opcode==OP_NoConflict ){
  82406. /* For the OP_NoConflict opcode, take the jump if any of the
  82407. ** input fields are NULL, since any key with a NULL will not
  82408. ** conflict */
  82409. for(ii=0; ii<pIdxKey->nField; ii++){
  82410. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  82411. takeJump = 1;
  82412. break;
  82413. }
  82414. }
  82415. }
  82416. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
  82417. if( pFree ) sqlite3DbFreeNN(db, pFree);
  82418. if( rc!=SQLITE_OK ){
  82419. goto abort_due_to_error;
  82420. }
  82421. pC->seekResult = res;
  82422. alreadyExists = (res==0);
  82423. pC->nullRow = 1-alreadyExists;
  82424. pC->deferredMoveto = 0;
  82425. pC->cacheStatus = CACHE_STALE;
  82426. if( pOp->opcode==OP_Found ){
  82427. VdbeBranchTaken(alreadyExists!=0,2);
  82428. if( alreadyExists ) goto jump_to_p2;
  82429. }else{
  82430. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  82431. if( takeJump || !alreadyExists ) goto jump_to_p2;
  82432. }
  82433. break;
  82434. }
  82435. /* Opcode: SeekRowid P1 P2 P3 * *
  82436. ** Synopsis: intkey=r[P3]
  82437. **
  82438. ** P1 is the index of a cursor open on an SQL table btree (with integer
  82439. ** keys). If register P3 does not contain an integer or if P1 does not
  82440. ** contain a record with rowid P3 then jump immediately to P2.
  82441. ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
  82442. ** a record with rowid P3 then
  82443. ** leave the cursor pointing at that record and fall through to the next
  82444. ** instruction.
  82445. **
  82446. ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
  82447. ** the P3 register must be guaranteed to contain an integer value. With this
  82448. ** opcode, register P3 might not contain an integer.
  82449. **
  82450. ** The OP_NotFound opcode performs the same operation on index btrees
  82451. ** (with arbitrary multi-value keys).
  82452. **
  82453. ** This opcode leaves the cursor in a state where it cannot be advanced
  82454. ** in either direction. In other words, the Next and Prev opcodes will
  82455. ** not work following this opcode.
  82456. **
  82457. ** See also: Found, NotFound, NoConflict, SeekRowid
  82458. */
  82459. /* Opcode: NotExists P1 P2 P3 * *
  82460. ** Synopsis: intkey=r[P3]
  82461. **
  82462. ** P1 is the index of a cursor open on an SQL table btree (with integer
  82463. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  82464. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  82465. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  82466. ** leave the cursor pointing at that record and fall through to the next
  82467. ** instruction.
  82468. **
  82469. ** The OP_SeekRowid opcode performs the same operation but also allows the
  82470. ** P3 register to contain a non-integer value, in which case the jump is
  82471. ** always taken. This opcode requires that P3 always contain an integer.
  82472. **
  82473. ** The OP_NotFound opcode performs the same operation on index btrees
  82474. ** (with arbitrary multi-value keys).
  82475. **
  82476. ** This opcode leaves the cursor in a state where it cannot be advanced
  82477. ** in either direction. In other words, the Next and Prev opcodes will
  82478. ** not work following this opcode.
  82479. **
  82480. ** See also: Found, NotFound, NoConflict, SeekRowid
  82481. */
  82482. case OP_SeekRowid: { /* jump, in3 */
  82483. VdbeCursor *pC;
  82484. BtCursor *pCrsr;
  82485. int res;
  82486. u64 iKey;
  82487. pIn3 = &aMem[pOp->p3];
  82488. if( (pIn3->flags & MEM_Int)==0 ){
  82489. /* Make sure pIn3->u.i contains a valid integer representation of
  82490. ** the key value, but do not change the datatype of the register, as
  82491. ** other parts of the perpared statement might be depending on the
  82492. ** current datatype. */
  82493. u16 origFlags = pIn3->flags;
  82494. int isNotInt;
  82495. applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
  82496. isNotInt = (pIn3->flags & MEM_Int)==0;
  82497. pIn3->flags = origFlags;
  82498. if( isNotInt ) goto jump_to_p2;
  82499. }
  82500. /* Fall through into OP_NotExists */
  82501. case OP_NotExists: /* jump, in3 */
  82502. pIn3 = &aMem[pOp->p3];
  82503. assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
  82504. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82505. pC = p->apCsr[pOp->p1];
  82506. assert( pC!=0 );
  82507. #ifdef SQLITE_DEBUG
  82508. if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
  82509. #endif
  82510. assert( pC->isTable );
  82511. assert( pC->eCurType==CURTYPE_BTREE );
  82512. pCrsr = pC->uc.pCursor;
  82513. assert( pCrsr!=0 );
  82514. res = 0;
  82515. iKey = pIn3->u.i;
  82516. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  82517. assert( rc==SQLITE_OK || res==0 );
  82518. pC->movetoTarget = iKey; /* Used by OP_Delete */
  82519. pC->nullRow = 0;
  82520. pC->cacheStatus = CACHE_STALE;
  82521. pC->deferredMoveto = 0;
  82522. VdbeBranchTaken(res!=0,2);
  82523. pC->seekResult = res;
  82524. if( res!=0 ){
  82525. assert( rc==SQLITE_OK );
  82526. if( pOp->p2==0 ){
  82527. rc = SQLITE_CORRUPT_BKPT;
  82528. }else{
  82529. goto jump_to_p2;
  82530. }
  82531. }
  82532. if( rc ) goto abort_due_to_error;
  82533. break;
  82534. }
  82535. /* Opcode: Sequence P1 P2 * * *
  82536. ** Synopsis: r[P2]=cursor[P1].ctr++
  82537. **
  82538. ** Find the next available sequence number for cursor P1.
  82539. ** Write the sequence number into register P2.
  82540. ** The sequence number on the cursor is incremented after this
  82541. ** instruction.
  82542. */
  82543. case OP_Sequence: { /* out2 */
  82544. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82545. assert( p->apCsr[pOp->p1]!=0 );
  82546. assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
  82547. pOut = out2Prerelease(p, pOp);
  82548. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  82549. break;
  82550. }
  82551. /* Opcode: NewRowid P1 P2 P3 * *
  82552. ** Synopsis: r[P2]=rowid
  82553. **
  82554. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  82555. ** The record number is not previously used as a key in the database
  82556. ** table that cursor P1 points to. The new record number is written
  82557. ** written to register P2.
  82558. **
  82559. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  82560. ** the largest previously generated record number. No new record numbers are
  82561. ** allowed to be less than this value. When this value reaches its maximum,
  82562. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  82563. ** generated record number. This P3 mechanism is used to help implement the
  82564. ** AUTOINCREMENT feature.
  82565. */
  82566. case OP_NewRowid: { /* out2 */
  82567. i64 v; /* The new rowid */
  82568. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  82569. int res; /* Result of an sqlite3BtreeLast() */
  82570. int cnt; /* Counter to limit the number of searches */
  82571. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  82572. VdbeFrame *pFrame; /* Root frame of VDBE */
  82573. v = 0;
  82574. res = 0;
  82575. pOut = out2Prerelease(p, pOp);
  82576. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82577. pC = p->apCsr[pOp->p1];
  82578. assert( pC!=0 );
  82579. assert( pC->isTable );
  82580. assert( pC->eCurType==CURTYPE_BTREE );
  82581. assert( pC->uc.pCursor!=0 );
  82582. {
  82583. /* The next rowid or record number (different terms for the same
  82584. ** thing) is obtained in a two-step algorithm.
  82585. **
  82586. ** First we attempt to find the largest existing rowid and add one
  82587. ** to that. But if the largest existing rowid is already the maximum
  82588. ** positive integer, we have to fall through to the second
  82589. ** probabilistic algorithm
  82590. **
  82591. ** The second algorithm is to select a rowid at random and see if
  82592. ** it already exists in the table. If it does not exist, we have
  82593. ** succeeded. If the random rowid does exist, we select a new one
  82594. ** and try again, up to 100 times.
  82595. */
  82596. assert( pC->isTable );
  82597. #ifdef SQLITE_32BIT_ROWID
  82598. # define MAX_ROWID 0x7fffffff
  82599. #else
  82600. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  82601. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  82602. ** to provide the constant while making all compilers happy.
  82603. */
  82604. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  82605. #endif
  82606. if( !pC->useRandomRowid ){
  82607. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  82608. if( rc!=SQLITE_OK ){
  82609. goto abort_due_to_error;
  82610. }
  82611. if( res ){
  82612. v = 1; /* IMP: R-61914-48074 */
  82613. }else{
  82614. assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
  82615. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  82616. if( v>=MAX_ROWID ){
  82617. pC->useRandomRowid = 1;
  82618. }else{
  82619. v++; /* IMP: R-29538-34987 */
  82620. }
  82621. }
  82622. }
  82623. #ifndef SQLITE_OMIT_AUTOINCREMENT
  82624. if( pOp->p3 ){
  82625. /* Assert that P3 is a valid memory cell. */
  82626. assert( pOp->p3>0 );
  82627. if( p->pFrame ){
  82628. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  82629. /* Assert that P3 is a valid memory cell. */
  82630. assert( pOp->p3<=pFrame->nMem );
  82631. pMem = &pFrame->aMem[pOp->p3];
  82632. }else{
  82633. /* Assert that P3 is a valid memory cell. */
  82634. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  82635. pMem = &aMem[pOp->p3];
  82636. memAboutToChange(p, pMem);
  82637. }
  82638. assert( memIsValid(pMem) );
  82639. REGISTER_TRACE(pOp->p3, pMem);
  82640. sqlite3VdbeMemIntegerify(pMem);
  82641. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  82642. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  82643. rc = SQLITE_FULL; /* IMP: R-17817-00630 */
  82644. goto abort_due_to_error;
  82645. }
  82646. if( v<pMem->u.i+1 ){
  82647. v = pMem->u.i + 1;
  82648. }
  82649. pMem->u.i = v;
  82650. }
  82651. #endif
  82652. if( pC->useRandomRowid ){
  82653. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  82654. ** largest possible integer (9223372036854775807) then the database
  82655. ** engine starts picking positive candidate ROWIDs at random until
  82656. ** it finds one that is not previously used. */
  82657. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  82658. ** an AUTOINCREMENT table. */
  82659. cnt = 0;
  82660. do{
  82661. sqlite3_randomness(sizeof(v), &v);
  82662. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  82663. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
  82664. 0, &res))==SQLITE_OK)
  82665. && (res==0)
  82666. && (++cnt<100));
  82667. if( rc ) goto abort_due_to_error;
  82668. if( res==0 ){
  82669. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  82670. goto abort_due_to_error;
  82671. }
  82672. assert( v>0 ); /* EV: R-40812-03570 */
  82673. }
  82674. pC->deferredMoveto = 0;
  82675. pC->cacheStatus = CACHE_STALE;
  82676. }
  82677. pOut->u.i = v;
  82678. break;
  82679. }
  82680. /* Opcode: Insert P1 P2 P3 P4 P5
  82681. ** Synopsis: intkey=r[P3] data=r[P2]
  82682. **
  82683. ** Write an entry into the table of cursor P1. A new entry is
  82684. ** created if it doesn't already exist or the data for an existing
  82685. ** entry is overwritten. The data is the value MEM_Blob stored in register
  82686. ** number P2. The key is stored in register P3. The key must
  82687. ** be a MEM_Int.
  82688. **
  82689. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  82690. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  82691. ** then rowid is stored for subsequent return by the
  82692. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  82693. **
  82694. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  82695. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  82696. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  82697. ** seeks on the cursor or if the most recent seek used a key equal to P3.
  82698. **
  82699. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  82700. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  82701. ** is part of an INSERT operation. The difference is only important to
  82702. ** the update hook.
  82703. **
  82704. ** Parameter P4 may point to a Table structure, or may be NULL. If it is
  82705. ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
  82706. ** following a successful insert.
  82707. **
  82708. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  82709. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  82710. ** and register P2 becomes ephemeral. If the cursor is changed, the
  82711. ** value of register P2 will then change. Make sure this does not
  82712. ** cause any problems.)
  82713. **
  82714. ** This instruction only works on tables. The equivalent instruction
  82715. ** for indices is OP_IdxInsert.
  82716. */
  82717. case OP_Insert: {
  82718. Mem *pData; /* MEM cell holding data for the record to be inserted */
  82719. Mem *pKey; /* MEM cell holding key for the record */
  82720. VdbeCursor *pC; /* Cursor to table into which insert is written */
  82721. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  82722. const char *zDb; /* database name - used by the update hook */
  82723. Table *pTab; /* Table structure - used by update and pre-update hooks */
  82724. BtreePayload x; /* Payload to be inserted */
  82725. pData = &aMem[pOp->p2];
  82726. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82727. assert( memIsValid(pData) );
  82728. pC = p->apCsr[pOp->p1];
  82729. assert( pC!=0 );
  82730. assert( pC->eCurType==CURTYPE_BTREE );
  82731. assert( pC->uc.pCursor!=0 );
  82732. assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
  82733. assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
  82734. REGISTER_TRACE(pOp->p2, pData);
  82735. sqlite3VdbeIncrWriteCounter(p, pC);
  82736. pKey = &aMem[pOp->p3];
  82737. assert( pKey->flags & MEM_Int );
  82738. assert( memIsValid(pKey) );
  82739. REGISTER_TRACE(pOp->p3, pKey);
  82740. x.nKey = pKey->u.i;
  82741. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  82742. assert( pC->iDb>=0 );
  82743. zDb = db->aDb[pC->iDb].zDbSName;
  82744. pTab = pOp->p4.pTab;
  82745. assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
  82746. }else{
  82747. pTab = 0;
  82748. zDb = 0; /* Not needed. Silence a compiler warning. */
  82749. }
  82750. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  82751. /* Invoke the pre-update hook, if any */
  82752. if( pTab ){
  82753. if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
  82754. sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
  82755. }
  82756. if( db->xUpdateCallback==0 || pTab->aCol==0 ){
  82757. /* Prevent post-update hook from running in cases when it should not */
  82758. pTab = 0;
  82759. }
  82760. }
  82761. if( pOp->p5 & OPFLAG_ISNOOP ) break;
  82762. #endif
  82763. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  82764. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
  82765. assert( pData->flags & (MEM_Blob|MEM_Str) );
  82766. x.pData = pData->z;
  82767. x.nData = pData->n;
  82768. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  82769. if( pData->flags & MEM_Zero ){
  82770. x.nZero = pData->u.nZero;
  82771. }else{
  82772. x.nZero = 0;
  82773. }
  82774. x.pKey = 0;
  82775. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  82776. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
  82777. );
  82778. pC->deferredMoveto = 0;
  82779. pC->cacheStatus = CACHE_STALE;
  82780. /* Invoke the update-hook if required. */
  82781. if( rc ) goto abort_due_to_error;
  82782. if( pTab ){
  82783. assert( db->xUpdateCallback!=0 );
  82784. assert( pTab->aCol!=0 );
  82785. db->xUpdateCallback(db->pUpdateArg,
  82786. (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
  82787. zDb, pTab->zName, x.nKey);
  82788. }
  82789. break;
  82790. }
  82791. /* Opcode: Delete P1 P2 P3 P4 P5
  82792. **
  82793. ** Delete the record at which the P1 cursor is currently pointing.
  82794. **
  82795. ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
  82796. ** the cursor will be left pointing at either the next or the previous
  82797. ** record in the table. If it is left pointing at the next record, then
  82798. ** the next Next instruction will be a no-op. As a result, in this case
  82799. ** it is ok to delete a record from within a Next loop. If
  82800. ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
  82801. ** left in an undefined state.
  82802. **
  82803. ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
  82804. ** delete one of several associated with deleting a table row and all its
  82805. ** associated index entries. Exactly one of those deletes is the "primary"
  82806. ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
  82807. ** marked with the AUXDELETE flag.
  82808. **
  82809. ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
  82810. ** change count is incremented (otherwise not).
  82811. **
  82812. ** P1 must not be pseudo-table. It has to be a real table with
  82813. ** multiple rows.
  82814. **
  82815. ** If P4 is not NULL then it points to a Table object. In this case either
  82816. ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
  82817. ** have been positioned using OP_NotFound prior to invoking this opcode in
  82818. ** this case. Specifically, if one is configured, the pre-update hook is
  82819. ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
  82820. ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
  82821. **
  82822. ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
  82823. ** of the memory cell that contains the value that the rowid of the row will
  82824. ** be set to by the update.
  82825. */
  82826. case OP_Delete: {
  82827. VdbeCursor *pC;
  82828. const char *zDb;
  82829. Table *pTab;
  82830. int opflags;
  82831. opflags = pOp->p2;
  82832. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82833. pC = p->apCsr[pOp->p1];
  82834. assert( pC!=0 );
  82835. assert( pC->eCurType==CURTYPE_BTREE );
  82836. assert( pC->uc.pCursor!=0 );
  82837. assert( pC->deferredMoveto==0 );
  82838. sqlite3VdbeIncrWriteCounter(p, pC);
  82839. #ifdef SQLITE_DEBUG
  82840. if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
  82841. /* If p5 is zero, the seek operation that positioned the cursor prior to
  82842. ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
  82843. ** the row that is being deleted */
  82844. i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  82845. assert( pC->movetoTarget==iKey );
  82846. }
  82847. #endif
  82848. /* If the update-hook or pre-update-hook will be invoked, set zDb to
  82849. ** the name of the db to pass as to it. Also set local pTab to a copy
  82850. ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
  82851. ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
  82852. ** VdbeCursor.movetoTarget to the current rowid. */
  82853. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  82854. assert( pC->iDb>=0 );
  82855. assert( pOp->p4.pTab!=0 );
  82856. zDb = db->aDb[pC->iDb].zDbSName;
  82857. pTab = pOp->p4.pTab;
  82858. if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
  82859. pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  82860. }
  82861. }else{
  82862. zDb = 0; /* Not needed. Silence a compiler warning. */
  82863. pTab = 0; /* Not needed. Silence a compiler warning. */
  82864. }
  82865. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  82866. /* Invoke the pre-update-hook if required. */
  82867. if( db->xPreUpdateCallback && pOp->p4.pTab ){
  82868. assert( !(opflags & OPFLAG_ISUPDATE)
  82869. || HasRowid(pTab)==0
  82870. || (aMem[pOp->p3].flags & MEM_Int)
  82871. );
  82872. sqlite3VdbePreUpdateHook(p, pC,
  82873. (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
  82874. zDb, pTab, pC->movetoTarget,
  82875. pOp->p3
  82876. );
  82877. }
  82878. if( opflags & OPFLAG_ISNOOP ) break;
  82879. #endif
  82880. /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
  82881. assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
  82882. assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
  82883. assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
  82884. #ifdef SQLITE_DEBUG
  82885. if( p->pFrame==0 ){
  82886. if( pC->isEphemeral==0
  82887. && (pOp->p5 & OPFLAG_AUXDELETE)==0
  82888. && (pC->wrFlag & OPFLAG_FORDELETE)==0
  82889. ){
  82890. nExtraDelete++;
  82891. }
  82892. if( pOp->p2 & OPFLAG_NCHANGE ){
  82893. nExtraDelete--;
  82894. }
  82895. }
  82896. #endif
  82897. rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
  82898. pC->cacheStatus = CACHE_STALE;
  82899. pC->seekResult = 0;
  82900. if( rc ) goto abort_due_to_error;
  82901. /* Invoke the update-hook if required. */
  82902. if( opflags & OPFLAG_NCHANGE ){
  82903. p->nChange++;
  82904. if( db->xUpdateCallback && HasRowid(pTab) ){
  82905. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
  82906. pC->movetoTarget);
  82907. assert( pC->iDb>=0 );
  82908. }
  82909. }
  82910. break;
  82911. }
  82912. /* Opcode: ResetCount * * * * *
  82913. **
  82914. ** The value of the change counter is copied to the database handle
  82915. ** change counter (returned by subsequent calls to sqlite3_changes()).
  82916. ** Then the VMs internal change counter resets to 0.
  82917. ** This is used by trigger programs.
  82918. */
  82919. case OP_ResetCount: {
  82920. sqlite3VdbeSetChanges(db, p->nChange);
  82921. p->nChange = 0;
  82922. break;
  82923. }
  82924. /* Opcode: SorterCompare P1 P2 P3 P4
  82925. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  82926. **
  82927. ** P1 is a sorter cursor. This instruction compares a prefix of the
  82928. ** record blob in register P3 against a prefix of the entry that
  82929. ** the sorter cursor currently points to. Only the first P4 fields
  82930. ** of r[P3] and the sorter record are compared.
  82931. **
  82932. ** If either P3 or the sorter contains a NULL in one of their significant
  82933. ** fields (not counting the P4 fields at the end which are ignored) then
  82934. ** the comparison is assumed to be equal.
  82935. **
  82936. ** Fall through to next instruction if the two records compare equal to
  82937. ** each other. Jump to P2 if they are different.
  82938. */
  82939. case OP_SorterCompare: {
  82940. VdbeCursor *pC;
  82941. int res;
  82942. int nKeyCol;
  82943. pC = p->apCsr[pOp->p1];
  82944. assert( isSorter(pC) );
  82945. assert( pOp->p4type==P4_INT32 );
  82946. pIn3 = &aMem[pOp->p3];
  82947. nKeyCol = pOp->p4.i;
  82948. res = 0;
  82949. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  82950. VdbeBranchTaken(res!=0,2);
  82951. if( rc ) goto abort_due_to_error;
  82952. if( res ) goto jump_to_p2;
  82953. break;
  82954. };
  82955. /* Opcode: SorterData P1 P2 P3 * *
  82956. ** Synopsis: r[P2]=data
  82957. **
  82958. ** Write into register P2 the current sorter data for sorter cursor P1.
  82959. ** Then clear the column header cache on cursor P3.
  82960. **
  82961. ** This opcode is normally use to move a record out of the sorter and into
  82962. ** a register that is the source for a pseudo-table cursor created using
  82963. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  82964. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  82965. ** us from having to issue a separate NullRow instruction to clear that cache.
  82966. */
  82967. case OP_SorterData: {
  82968. VdbeCursor *pC;
  82969. pOut = &aMem[pOp->p2];
  82970. pC = p->apCsr[pOp->p1];
  82971. assert( isSorter(pC) );
  82972. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  82973. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  82974. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82975. if( rc ) goto abort_due_to_error;
  82976. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  82977. break;
  82978. }
  82979. /* Opcode: RowData P1 P2 P3 * *
  82980. ** Synopsis: r[P2]=data
  82981. **
  82982. ** Write into register P2 the complete row content for the row at
  82983. ** which cursor P1 is currently pointing.
  82984. ** There is no interpretation of the data.
  82985. ** It is just copied onto the P2 register exactly as
  82986. ** it is found in the database file.
  82987. **
  82988. ** If cursor P1 is an index, then the content is the key of the row.
  82989. ** If cursor P2 is a table, then the content extracted is the data.
  82990. **
  82991. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  82992. ** of a real table, not a pseudo-table.
  82993. **
  82994. ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
  82995. ** into the database page. That means that the content of the output
  82996. ** register will be invalidated as soon as the cursor moves - including
  82997. ** moves caused by other cursors that "save" the current cursors
  82998. ** position in order that they can write to the same table. If P3==0
  82999. ** then a copy of the data is made into memory. P3!=0 is faster, but
  83000. ** P3==0 is safer.
  83001. **
  83002. ** If P3!=0 then the content of the P2 register is unsuitable for use
  83003. ** in OP_Result and any OP_Result will invalidate the P2 register content.
  83004. ** The P2 register content is invalidated by opcodes like OP_Function or
  83005. ** by any use of another cursor pointing to the same table.
  83006. */
  83007. case OP_RowData: {
  83008. VdbeCursor *pC;
  83009. BtCursor *pCrsr;
  83010. u32 n;
  83011. pOut = out2Prerelease(p, pOp);
  83012. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83013. pC = p->apCsr[pOp->p1];
  83014. assert( pC!=0 );
  83015. assert( pC->eCurType==CURTYPE_BTREE );
  83016. assert( isSorter(pC)==0 );
  83017. assert( pC->nullRow==0 );
  83018. assert( pC->uc.pCursor!=0 );
  83019. pCrsr = pC->uc.pCursor;
  83020. /* The OP_RowData opcodes always follow OP_NotExists or
  83021. ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
  83022. ** that might invalidate the cursor.
  83023. ** If this where not the case, on of the following assert()s
  83024. ** would fail. Should this ever change (because of changes in the code
  83025. ** generator) then the fix would be to insert a call to
  83026. ** sqlite3VdbeCursorMoveto().
  83027. */
  83028. assert( pC->deferredMoveto==0 );
  83029. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  83030. #if 0 /* Not required due to the previous to assert() statements */
  83031. rc = sqlite3VdbeCursorMoveto(pC);
  83032. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  83033. #endif
  83034. n = sqlite3BtreePayloadSize(pCrsr);
  83035. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  83036. goto too_big;
  83037. }
  83038. testcase( n==0 );
  83039. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
  83040. if( rc ) goto abort_due_to_error;
  83041. if( !pOp->p3 ) Deephemeralize(pOut);
  83042. UPDATE_MAX_BLOBSIZE(pOut);
  83043. REGISTER_TRACE(pOp->p2, pOut);
  83044. break;
  83045. }
  83046. /* Opcode: Rowid P1 P2 * * *
  83047. ** Synopsis: r[P2]=rowid
  83048. **
  83049. ** Store in register P2 an integer which is the key of the table entry that
  83050. ** P1 is currently point to.
  83051. **
  83052. ** P1 can be either an ordinary table or a virtual table. There used to
  83053. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  83054. ** one opcode now works for both table types.
  83055. */
  83056. case OP_Rowid: { /* out2 */
  83057. VdbeCursor *pC;
  83058. i64 v;
  83059. sqlite3_vtab *pVtab;
  83060. const sqlite3_module *pModule;
  83061. pOut = out2Prerelease(p, pOp);
  83062. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83063. pC = p->apCsr[pOp->p1];
  83064. assert( pC!=0 );
  83065. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  83066. if( pC->nullRow ){
  83067. pOut->flags = MEM_Null;
  83068. break;
  83069. }else if( pC->deferredMoveto ){
  83070. v = pC->movetoTarget;
  83071. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83072. }else if( pC->eCurType==CURTYPE_VTAB ){
  83073. assert( pC->uc.pVCur!=0 );
  83074. pVtab = pC->uc.pVCur->pVtab;
  83075. pModule = pVtab->pModule;
  83076. assert( pModule->xRowid );
  83077. rc = pModule->xRowid(pC->uc.pVCur, &v);
  83078. sqlite3VtabImportErrmsg(p, pVtab);
  83079. if( rc ) goto abort_due_to_error;
  83080. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  83081. }else{
  83082. assert( pC->eCurType==CURTYPE_BTREE );
  83083. assert( pC->uc.pCursor!=0 );
  83084. rc = sqlite3VdbeCursorRestore(pC);
  83085. if( rc ) goto abort_due_to_error;
  83086. if( pC->nullRow ){
  83087. pOut->flags = MEM_Null;
  83088. break;
  83089. }
  83090. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  83091. }
  83092. pOut->u.i = v;
  83093. break;
  83094. }
  83095. /* Opcode: NullRow P1 * * * *
  83096. **
  83097. ** Move the cursor P1 to a null row. Any OP_Column operations
  83098. ** that occur while the cursor is on the null row will always
  83099. ** write a NULL.
  83100. */
  83101. case OP_NullRow: {
  83102. VdbeCursor *pC;
  83103. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83104. pC = p->apCsr[pOp->p1];
  83105. assert( pC!=0 );
  83106. pC->nullRow = 1;
  83107. pC->cacheStatus = CACHE_STALE;
  83108. if( pC->eCurType==CURTYPE_BTREE ){
  83109. assert( pC->uc.pCursor!=0 );
  83110. sqlite3BtreeClearCursor(pC->uc.pCursor);
  83111. }
  83112. #ifdef SQLITE_DEBUG
  83113. if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
  83114. #endif
  83115. break;
  83116. }
  83117. /* Opcode: SeekEnd P1 * * * *
  83118. **
  83119. ** Position cursor P1 at the end of the btree for the purpose of
  83120. ** appending a new entry onto the btree.
  83121. **
  83122. ** It is assumed that the cursor is used only for appending and so
  83123. ** if the cursor is valid, then the cursor must already be pointing
  83124. ** at the end of the btree and so no changes are made to
  83125. ** the cursor.
  83126. */
  83127. /* Opcode: Last P1 P2 * * *
  83128. **
  83129. ** The next use of the Rowid or Column or Prev instruction for P1
  83130. ** will refer to the last entry in the database table or index.
  83131. ** If the table or index is empty and P2>0, then jump immediately to P2.
  83132. ** If P2 is 0 or if the table or index is not empty, fall through
  83133. ** to the following instruction.
  83134. **
  83135. ** This opcode leaves the cursor configured to move in reverse order,
  83136. ** from the end toward the beginning. In other words, the cursor is
  83137. ** configured to use Prev, not Next.
  83138. */
  83139. case OP_SeekEnd:
  83140. case OP_Last: { /* jump */
  83141. VdbeCursor *pC;
  83142. BtCursor *pCrsr;
  83143. int res;
  83144. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83145. pC = p->apCsr[pOp->p1];
  83146. assert( pC!=0 );
  83147. assert( pC->eCurType==CURTYPE_BTREE );
  83148. pCrsr = pC->uc.pCursor;
  83149. res = 0;
  83150. assert( pCrsr!=0 );
  83151. #ifdef SQLITE_DEBUG
  83152. pC->seekOp = pOp->opcode;
  83153. #endif
  83154. if( pOp->opcode==OP_SeekEnd ){
  83155. assert( pOp->p2==0 );
  83156. pC->seekResult = -1;
  83157. if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
  83158. break;
  83159. }
  83160. }
  83161. rc = sqlite3BtreeLast(pCrsr, &res);
  83162. pC->nullRow = (u8)res;
  83163. pC->deferredMoveto = 0;
  83164. pC->cacheStatus = CACHE_STALE;
  83165. if( rc ) goto abort_due_to_error;
  83166. if( pOp->p2>0 ){
  83167. VdbeBranchTaken(res!=0,2);
  83168. if( res ) goto jump_to_p2;
  83169. }
  83170. break;
  83171. }
  83172. /* Opcode: IfSmaller P1 P2 P3 * *
  83173. **
  83174. ** Estimate the number of rows in the table P1. Jump to P2 if that
  83175. ** estimate is less than approximately 2**(0.1*P3).
  83176. */
  83177. case OP_IfSmaller: { /* jump */
  83178. VdbeCursor *pC;
  83179. BtCursor *pCrsr;
  83180. int res;
  83181. i64 sz;
  83182. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83183. pC = p->apCsr[pOp->p1];
  83184. assert( pC!=0 );
  83185. pCrsr = pC->uc.pCursor;
  83186. assert( pCrsr );
  83187. rc = sqlite3BtreeFirst(pCrsr, &res);
  83188. if( rc ) goto abort_due_to_error;
  83189. if( res==0 ){
  83190. sz = sqlite3BtreeRowCountEst(pCrsr);
  83191. if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
  83192. }
  83193. VdbeBranchTaken(res!=0,2);
  83194. if( res ) goto jump_to_p2;
  83195. break;
  83196. }
  83197. /* Opcode: SorterSort P1 P2 * * *
  83198. **
  83199. ** After all records have been inserted into the Sorter object
  83200. ** identified by P1, invoke this opcode to actually do the sorting.
  83201. ** Jump to P2 if there are no records to be sorted.
  83202. **
  83203. ** This opcode is an alias for OP_Sort and OP_Rewind that is used
  83204. ** for Sorter objects.
  83205. */
  83206. /* Opcode: Sort P1 P2 * * *
  83207. **
  83208. ** This opcode does exactly the same thing as OP_Rewind except that
  83209. ** it increments an undocumented global variable used for testing.
  83210. **
  83211. ** Sorting is accomplished by writing records into a sorting index,
  83212. ** then rewinding that index and playing it back from beginning to
  83213. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  83214. ** rewinding so that the global variable will be incremented and
  83215. ** regression tests can determine whether or not the optimizer is
  83216. ** correctly optimizing out sorts.
  83217. */
  83218. case OP_SorterSort: /* jump */
  83219. case OP_Sort: { /* jump */
  83220. #ifdef SQLITE_TEST
  83221. sqlite3_sort_count++;
  83222. sqlite3_search_count--;
  83223. #endif
  83224. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  83225. /* Fall through into OP_Rewind */
  83226. }
  83227. /* Opcode: Rewind P1 P2 * * *
  83228. **
  83229. ** The next use of the Rowid or Column or Next instruction for P1
  83230. ** will refer to the first entry in the database table or index.
  83231. ** If the table or index is empty, jump immediately to P2.
  83232. ** If the table or index is not empty, fall through to the following
  83233. ** instruction.
  83234. **
  83235. ** This opcode leaves the cursor configured to move in forward order,
  83236. ** from the beginning toward the end. In other words, the cursor is
  83237. ** configured to use Next, not Prev.
  83238. */
  83239. case OP_Rewind: { /* jump */
  83240. VdbeCursor *pC;
  83241. BtCursor *pCrsr;
  83242. int res;
  83243. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83244. assert( pOp->p5==0 );
  83245. pC = p->apCsr[pOp->p1];
  83246. assert( pC!=0 );
  83247. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  83248. res = 1;
  83249. #ifdef SQLITE_DEBUG
  83250. pC->seekOp = OP_Rewind;
  83251. #endif
  83252. if( isSorter(pC) ){
  83253. rc = sqlite3VdbeSorterRewind(pC, &res);
  83254. }else{
  83255. assert( pC->eCurType==CURTYPE_BTREE );
  83256. pCrsr = pC->uc.pCursor;
  83257. assert( pCrsr );
  83258. rc = sqlite3BtreeFirst(pCrsr, &res);
  83259. pC->deferredMoveto = 0;
  83260. pC->cacheStatus = CACHE_STALE;
  83261. }
  83262. if( rc ) goto abort_due_to_error;
  83263. pC->nullRow = (u8)res;
  83264. assert( pOp->p2>0 && pOp->p2<p->nOp );
  83265. VdbeBranchTaken(res!=0,2);
  83266. if( res ) goto jump_to_p2;
  83267. break;
  83268. }
  83269. /* Opcode: Next P1 P2 P3 P4 P5
  83270. **
  83271. ** Advance cursor P1 so that it points to the next key/data pair in its
  83272. ** table or index. If there are no more key/value pairs then fall through
  83273. ** to the following instruction. But if the cursor advance was successful,
  83274. ** jump immediately to P2.
  83275. **
  83276. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  83277. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  83278. ** to follow SeekLT, SeekLE, or OP_Last.
  83279. **
  83280. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  83281. ** been opened prior to this opcode or the program will segfault.
  83282. **
  83283. ** The P3 value is a hint to the btree implementation. If P3==1, that
  83284. ** means P1 is an SQL index and that this instruction could have been
  83285. ** omitted if that index had been unique. P3 is usually 0. P3 is
  83286. ** always either 0 or 1.
  83287. **
  83288. ** P4 is always of type P4_ADVANCE. The function pointer points to
  83289. ** sqlite3BtreeNext().
  83290. **
  83291. ** If P5 is positive and the jump is taken, then event counter
  83292. ** number P5-1 in the prepared statement is incremented.
  83293. **
  83294. ** See also: Prev
  83295. */
  83296. /* Opcode: Prev P1 P2 P3 P4 P5
  83297. **
  83298. ** Back up cursor P1 so that it points to the previous key/data pair in its
  83299. ** table or index. If there is no previous key/value pairs then fall through
  83300. ** to the following instruction. But if the cursor backup was successful,
  83301. ** jump immediately to P2.
  83302. **
  83303. **
  83304. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  83305. ** OP_Last opcode used to position the cursor. Prev is not allowed
  83306. ** to follow SeekGT, SeekGE, or OP_Rewind.
  83307. **
  83308. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  83309. ** not open then the behavior is undefined.
  83310. **
  83311. ** The P3 value is a hint to the btree implementation. If P3==1, that
  83312. ** means P1 is an SQL index and that this instruction could have been
  83313. ** omitted if that index had been unique. P3 is usually 0. P3 is
  83314. ** always either 0 or 1.
  83315. **
  83316. ** P4 is always of type P4_ADVANCE. The function pointer points to
  83317. ** sqlite3BtreePrevious().
  83318. **
  83319. ** If P5 is positive and the jump is taken, then event counter
  83320. ** number P5-1 in the prepared statement is incremented.
  83321. */
  83322. /* Opcode: SorterNext P1 P2 * * P5
  83323. **
  83324. ** This opcode works just like OP_Next except that P1 must be a
  83325. ** sorter object for which the OP_SorterSort opcode has been
  83326. ** invoked. This opcode advances the cursor to the next sorted
  83327. ** record, or jumps to P2 if there are no more sorted records.
  83328. */
  83329. case OP_SorterNext: { /* jump */
  83330. VdbeCursor *pC;
  83331. pC = p->apCsr[pOp->p1];
  83332. assert( isSorter(pC) );
  83333. rc = sqlite3VdbeSorterNext(db, pC);
  83334. goto next_tail;
  83335. case OP_Prev: /* jump */
  83336. case OP_Next: /* jump */
  83337. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83338. assert( pOp->p5<ArraySize(p->aCounter) );
  83339. pC = p->apCsr[pOp->p1];
  83340. assert( pC!=0 );
  83341. assert( pC->deferredMoveto==0 );
  83342. assert( pC->eCurType==CURTYPE_BTREE );
  83343. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  83344. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  83345. /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
  83346. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  83347. assert( pOp->opcode!=OP_Next
  83348. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  83349. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
  83350. || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid);
  83351. assert( pOp->opcode!=OP_Prev
  83352. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  83353. || pC->seekOp==OP_Last
  83354. || pC->seekOp==OP_NullRow);
  83355. rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
  83356. next_tail:
  83357. pC->cacheStatus = CACHE_STALE;
  83358. VdbeBranchTaken(rc==SQLITE_OK,2);
  83359. if( rc==SQLITE_OK ){
  83360. pC->nullRow = 0;
  83361. p->aCounter[pOp->p5]++;
  83362. #ifdef SQLITE_TEST
  83363. sqlite3_search_count++;
  83364. #endif
  83365. goto jump_to_p2_and_check_for_interrupt;
  83366. }
  83367. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  83368. rc = SQLITE_OK;
  83369. pC->nullRow = 1;
  83370. goto check_for_interrupt;
  83371. }
  83372. /* Opcode: IdxInsert P1 P2 P3 P4 P5
  83373. ** Synopsis: key=r[P2]
  83374. **
  83375. ** Register P2 holds an SQL index key made using the
  83376. ** MakeRecord instructions. This opcode writes that key
  83377. ** into the index P1. Data for the entry is nil.
  83378. **
  83379. ** If P4 is not zero, then it is the number of values in the unpacked
  83380. ** key of reg(P2). In that case, P3 is the index of the first register
  83381. ** for the unpacked key. The availability of the unpacked key can sometimes
  83382. ** be an optimization.
  83383. **
  83384. ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
  83385. ** that this insert is likely to be an append.
  83386. **
  83387. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  83388. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  83389. ** then the change counter is unchanged.
  83390. **
  83391. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  83392. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  83393. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  83394. ** seeks on the cursor or if the most recent seek used a key equivalent
  83395. ** to P2.
  83396. **
  83397. ** This instruction only works for indices. The equivalent instruction
  83398. ** for tables is OP_Insert.
  83399. */
  83400. /* Opcode: SorterInsert P1 P2 * * *
  83401. ** Synopsis: key=r[P2]
  83402. **
  83403. ** Register P2 holds an SQL index key made using the
  83404. ** MakeRecord instructions. This opcode writes that key
  83405. ** into the sorter P1. Data for the entry is nil.
  83406. */
  83407. case OP_SorterInsert: /* in2 */
  83408. case OP_IdxInsert: { /* in2 */
  83409. VdbeCursor *pC;
  83410. BtreePayload x;
  83411. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83412. pC = p->apCsr[pOp->p1];
  83413. sqlite3VdbeIncrWriteCounter(p, pC);
  83414. assert( pC!=0 );
  83415. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  83416. pIn2 = &aMem[pOp->p2];
  83417. assert( pIn2->flags & MEM_Blob );
  83418. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  83419. assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
  83420. assert( pC->isTable==0 );
  83421. rc = ExpandBlob(pIn2);
  83422. if( rc ) goto abort_due_to_error;
  83423. if( pOp->opcode==OP_SorterInsert ){
  83424. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  83425. }else{
  83426. x.nKey = pIn2->n;
  83427. x.pKey = pIn2->z;
  83428. x.aMem = aMem + pOp->p3;
  83429. x.nMem = (u16)pOp->p4.i;
  83430. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  83431. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
  83432. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  83433. );
  83434. assert( pC->deferredMoveto==0 );
  83435. pC->cacheStatus = CACHE_STALE;
  83436. }
  83437. if( rc) goto abort_due_to_error;
  83438. break;
  83439. }
  83440. /* Opcode: IdxDelete P1 P2 P3 * *
  83441. ** Synopsis: key=r[P2@P3]
  83442. **
  83443. ** The content of P3 registers starting at register P2 form
  83444. ** an unpacked index key. This opcode removes that entry from the
  83445. ** index opened by cursor P1.
  83446. */
  83447. case OP_IdxDelete: {
  83448. VdbeCursor *pC;
  83449. BtCursor *pCrsr;
  83450. int res;
  83451. UnpackedRecord r;
  83452. assert( pOp->p3>0 );
  83453. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
  83454. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83455. pC = p->apCsr[pOp->p1];
  83456. assert( pC!=0 );
  83457. assert( pC->eCurType==CURTYPE_BTREE );
  83458. sqlite3VdbeIncrWriteCounter(p, pC);
  83459. pCrsr = pC->uc.pCursor;
  83460. assert( pCrsr!=0 );
  83461. assert( pOp->p5==0 );
  83462. r.pKeyInfo = pC->pKeyInfo;
  83463. r.nField = (u16)pOp->p3;
  83464. r.default_rc = 0;
  83465. r.aMem = &aMem[pOp->p2];
  83466. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  83467. if( rc ) goto abort_due_to_error;
  83468. if( res==0 ){
  83469. rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
  83470. if( rc ) goto abort_due_to_error;
  83471. }
  83472. assert( pC->deferredMoveto==0 );
  83473. pC->cacheStatus = CACHE_STALE;
  83474. pC->seekResult = 0;
  83475. break;
  83476. }
  83477. /* Opcode: DeferredSeek P1 * P3 P4 *
  83478. ** Synopsis: Move P3 to P1.rowid if needed
  83479. **
  83480. ** P1 is an open index cursor and P3 is a cursor on the corresponding
  83481. ** table. This opcode does a deferred seek of the P3 table cursor
  83482. ** to the row that corresponds to the current row of P1.
  83483. **
  83484. ** This is a deferred seek. Nothing actually happens until
  83485. ** the cursor is used to read a record. That way, if no reads
  83486. ** occur, no unnecessary I/O happens.
  83487. **
  83488. ** P4 may be an array of integers (type P4_INTARRAY) containing
  83489. ** one entry for each column in the P3 table. If array entry a(i)
  83490. ** is non-zero, then reading column a(i)-1 from cursor P3 is
  83491. ** equivalent to performing the deferred seek and then reading column i
  83492. ** from P1. This information is stored in P3 and used to redirect
  83493. ** reads against P3 over to P1, thus possibly avoiding the need to
  83494. ** seek and read cursor P3.
  83495. */
  83496. /* Opcode: IdxRowid P1 P2 * * *
  83497. ** Synopsis: r[P2]=rowid
  83498. **
  83499. ** Write into register P2 an integer which is the last entry in the record at
  83500. ** the end of the index key pointed to by cursor P1. This integer should be
  83501. ** the rowid of the table entry to which this index entry points.
  83502. **
  83503. ** See also: Rowid, MakeRecord.
  83504. */
  83505. case OP_DeferredSeek:
  83506. case OP_IdxRowid: { /* out2 */
  83507. VdbeCursor *pC; /* The P1 index cursor */
  83508. VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
  83509. i64 rowid; /* Rowid that P1 current points to */
  83510. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83511. pC = p->apCsr[pOp->p1];
  83512. assert( pC!=0 );
  83513. assert( pC->eCurType==CURTYPE_BTREE );
  83514. assert( pC->uc.pCursor!=0 );
  83515. assert( pC->isTable==0 );
  83516. assert( pC->deferredMoveto==0 );
  83517. assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
  83518. /* The IdxRowid and Seek opcodes are combined because of the commonality
  83519. ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
  83520. rc = sqlite3VdbeCursorRestore(pC);
  83521. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  83522. ** out from under the cursor. That will never happens for an IdxRowid
  83523. ** or Seek opcode */
  83524. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  83525. if( !pC->nullRow ){
  83526. rowid = 0; /* Not needed. Only used to silence a warning. */
  83527. rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
  83528. if( rc!=SQLITE_OK ){
  83529. goto abort_due_to_error;
  83530. }
  83531. if( pOp->opcode==OP_DeferredSeek ){
  83532. assert( pOp->p3>=0 && pOp->p3<p->nCursor );
  83533. pTabCur = p->apCsr[pOp->p3];
  83534. assert( pTabCur!=0 );
  83535. assert( pTabCur->eCurType==CURTYPE_BTREE );
  83536. assert( pTabCur->uc.pCursor!=0 );
  83537. assert( pTabCur->isTable );
  83538. pTabCur->nullRow = 0;
  83539. pTabCur->movetoTarget = rowid;
  83540. pTabCur->deferredMoveto = 1;
  83541. assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
  83542. pTabCur->aAltMap = pOp->p4.ai;
  83543. pTabCur->pAltCursor = pC;
  83544. }else{
  83545. pOut = out2Prerelease(p, pOp);
  83546. pOut->u.i = rowid;
  83547. }
  83548. }else{
  83549. assert( pOp->opcode==OP_IdxRowid );
  83550. sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
  83551. }
  83552. break;
  83553. }
  83554. /* Opcode: IdxGE P1 P2 P3 P4 P5
  83555. ** Synopsis: key=r[P3@P4]
  83556. **
  83557. ** The P4 register values beginning with P3 form an unpacked index
  83558. ** key that omits the PRIMARY KEY. Compare this key value against the index
  83559. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  83560. ** fields at the end.
  83561. **
  83562. ** If the P1 index entry is greater than or equal to the key value
  83563. ** then jump to P2. Otherwise fall through to the next instruction.
  83564. */
  83565. /* Opcode: IdxGT P1 P2 P3 P4 P5
  83566. ** Synopsis: key=r[P3@P4]
  83567. **
  83568. ** The P4 register values beginning with P3 form an unpacked index
  83569. ** key that omits the PRIMARY KEY. Compare this key value against the index
  83570. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  83571. ** fields at the end.
  83572. **
  83573. ** If the P1 index entry is greater than the key value
  83574. ** then jump to P2. Otherwise fall through to the next instruction.
  83575. */
  83576. /* Opcode: IdxLT P1 P2 P3 P4 P5
  83577. ** Synopsis: key=r[P3@P4]
  83578. **
  83579. ** The P4 register values beginning with P3 form an unpacked index
  83580. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  83581. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  83582. ** ROWID on the P1 index.
  83583. **
  83584. ** If the P1 index entry is less than the key value then jump to P2.
  83585. ** Otherwise fall through to the next instruction.
  83586. */
  83587. /* Opcode: IdxLE P1 P2 P3 P4 P5
  83588. ** Synopsis: key=r[P3@P4]
  83589. **
  83590. ** The P4 register values beginning with P3 form an unpacked index
  83591. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  83592. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  83593. ** ROWID on the P1 index.
  83594. **
  83595. ** If the P1 index entry is less than or equal to the key value then jump
  83596. ** to P2. Otherwise fall through to the next instruction.
  83597. */
  83598. case OP_IdxLE: /* jump */
  83599. case OP_IdxGT: /* jump */
  83600. case OP_IdxLT: /* jump */
  83601. case OP_IdxGE: { /* jump */
  83602. VdbeCursor *pC;
  83603. int res;
  83604. UnpackedRecord r;
  83605. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83606. pC = p->apCsr[pOp->p1];
  83607. assert( pC!=0 );
  83608. assert( pC->isOrdered );
  83609. assert( pC->eCurType==CURTYPE_BTREE );
  83610. assert( pC->uc.pCursor!=0);
  83611. assert( pC->deferredMoveto==0 );
  83612. assert( pOp->p5==0 || pOp->p5==1 );
  83613. assert( pOp->p4type==P4_INT32 );
  83614. r.pKeyInfo = pC->pKeyInfo;
  83615. r.nField = (u16)pOp->p4.i;
  83616. if( pOp->opcode<OP_IdxLT ){
  83617. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  83618. r.default_rc = -1;
  83619. }else{
  83620. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  83621. r.default_rc = 0;
  83622. }
  83623. r.aMem = &aMem[pOp->p3];
  83624. #ifdef SQLITE_DEBUG
  83625. {
  83626. int i;
  83627. for(i=0; i<r.nField; i++){
  83628. assert( memIsValid(&r.aMem[i]) );
  83629. REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
  83630. }
  83631. }
  83632. #endif
  83633. res = 0; /* Not needed. Only used to silence a warning. */
  83634. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  83635. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  83636. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  83637. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  83638. res = -res;
  83639. }else{
  83640. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  83641. res++;
  83642. }
  83643. VdbeBranchTaken(res>0,2);
  83644. if( rc ) goto abort_due_to_error;
  83645. if( res>0 ) goto jump_to_p2;
  83646. break;
  83647. }
  83648. /* Opcode: Destroy P1 P2 P3 * *
  83649. **
  83650. ** Delete an entire database table or index whose root page in the database
  83651. ** file is given by P1.
  83652. **
  83653. ** The table being destroyed is in the main database file if P3==0. If
  83654. ** P3==1 then the table to be clear is in the auxiliary database file
  83655. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  83656. **
  83657. ** If AUTOVACUUM is enabled then it is possible that another root page
  83658. ** might be moved into the newly deleted root page in order to keep all
  83659. ** root pages contiguous at the beginning of the database. The former
  83660. ** value of the root page that moved - its value before the move occurred -
  83661. ** is stored in register P2. If no page movement was required (because the
  83662. ** table being dropped was already the last one in the database) then a
  83663. ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
  83664. ** is stored in register P2.
  83665. **
  83666. ** This opcode throws an error if there are any active reader VMs when
  83667. ** it is invoked. This is done to avoid the difficulty associated with
  83668. ** updating existing cursors when a root page is moved in an AUTOVACUUM
  83669. ** database. This error is thrown even if the database is not an AUTOVACUUM
  83670. ** db in order to avoid introducing an incompatibility between autovacuum
  83671. ** and non-autovacuum modes.
  83672. **
  83673. ** See also: Clear
  83674. */
  83675. case OP_Destroy: { /* out2 */
  83676. int iMoved;
  83677. int iDb;
  83678. sqlite3VdbeIncrWriteCounter(p, 0);
  83679. assert( p->readOnly==0 );
  83680. assert( pOp->p1>1 );
  83681. pOut = out2Prerelease(p, pOp);
  83682. pOut->flags = MEM_Null;
  83683. if( db->nVdbeRead > db->nVDestroy+1 ){
  83684. rc = SQLITE_LOCKED;
  83685. p->errorAction = OE_Abort;
  83686. goto abort_due_to_error;
  83687. }else{
  83688. iDb = pOp->p3;
  83689. assert( DbMaskTest(p->btreeMask, iDb) );
  83690. iMoved = 0; /* Not needed. Only to silence a warning. */
  83691. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  83692. pOut->flags = MEM_Int;
  83693. pOut->u.i = iMoved;
  83694. if( rc ) goto abort_due_to_error;
  83695. #ifndef SQLITE_OMIT_AUTOVACUUM
  83696. if( iMoved!=0 ){
  83697. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  83698. /* All OP_Destroy operations occur on the same btree */
  83699. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  83700. resetSchemaOnFault = iDb+1;
  83701. }
  83702. #endif
  83703. }
  83704. break;
  83705. }
  83706. /* Opcode: Clear P1 P2 P3
  83707. **
  83708. ** Delete all contents of the database table or index whose root page
  83709. ** in the database file is given by P1. But, unlike Destroy, do not
  83710. ** remove the table or index from the database file.
  83711. **
  83712. ** The table being clear is in the main database file if P2==0. If
  83713. ** P2==1 then the table to be clear is in the auxiliary database file
  83714. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  83715. **
  83716. ** If the P3 value is non-zero, then the table referred to must be an
  83717. ** intkey table (an SQL table, not an index). In this case the row change
  83718. ** count is incremented by the number of rows in the table being cleared.
  83719. ** If P3 is greater than zero, then the value stored in register P3 is
  83720. ** also incremented by the number of rows in the table being cleared.
  83721. **
  83722. ** See also: Destroy
  83723. */
  83724. case OP_Clear: {
  83725. int nChange;
  83726. sqlite3VdbeIncrWriteCounter(p, 0);
  83727. nChange = 0;
  83728. assert( p->readOnly==0 );
  83729. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  83730. rc = sqlite3BtreeClearTable(
  83731. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  83732. );
  83733. if( pOp->p3 ){
  83734. p->nChange += nChange;
  83735. if( pOp->p3>0 ){
  83736. assert( memIsValid(&aMem[pOp->p3]) );
  83737. memAboutToChange(p, &aMem[pOp->p3]);
  83738. aMem[pOp->p3].u.i += nChange;
  83739. }
  83740. }
  83741. if( rc ) goto abort_due_to_error;
  83742. break;
  83743. }
  83744. /* Opcode: ResetSorter P1 * * * *
  83745. **
  83746. ** Delete all contents from the ephemeral table or sorter
  83747. ** that is open on cursor P1.
  83748. **
  83749. ** This opcode only works for cursors used for sorting and
  83750. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  83751. */
  83752. case OP_ResetSorter: {
  83753. VdbeCursor *pC;
  83754. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83755. pC = p->apCsr[pOp->p1];
  83756. assert( pC!=0 );
  83757. if( isSorter(pC) ){
  83758. sqlite3VdbeSorterReset(db, pC->uc.pSorter);
  83759. }else{
  83760. assert( pC->eCurType==CURTYPE_BTREE );
  83761. assert( pC->isEphemeral );
  83762. rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
  83763. if( rc ) goto abort_due_to_error;
  83764. }
  83765. break;
  83766. }
  83767. /* Opcode: CreateBtree P1 P2 P3 * *
  83768. ** Synopsis: r[P2]=root iDb=P1 flags=P3
  83769. **
  83770. ** Allocate a new b-tree in the main database file if P1==0 or in the
  83771. ** TEMP database file if P1==1 or in an attached database if
  83772. ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
  83773. ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
  83774. ** The root page number of the new b-tree is stored in register P2.
  83775. */
  83776. case OP_CreateBtree: { /* out2 */
  83777. int pgno;
  83778. Db *pDb;
  83779. sqlite3VdbeIncrWriteCounter(p, 0);
  83780. pOut = out2Prerelease(p, pOp);
  83781. pgno = 0;
  83782. assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
  83783. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  83784. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  83785. assert( p->readOnly==0 );
  83786. pDb = &db->aDb[pOp->p1];
  83787. assert( pDb->pBt!=0 );
  83788. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
  83789. if( rc ) goto abort_due_to_error;
  83790. pOut->u.i = pgno;
  83791. break;
  83792. }
  83793. /* Opcode: SqlExec * * * P4 *
  83794. **
  83795. ** Run the SQL statement or statements specified in the P4 string.
  83796. */
  83797. case OP_SqlExec: {
  83798. sqlite3VdbeIncrWriteCounter(p, 0);
  83799. db->nSqlExec++;
  83800. rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
  83801. db->nSqlExec--;
  83802. if( rc ) goto abort_due_to_error;
  83803. break;
  83804. }
  83805. /* Opcode: ParseSchema P1 * * P4 *
  83806. **
  83807. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  83808. ** that match the WHERE clause P4. If P4 is a NULL pointer, then the
  83809. ** entire schema for P1 is reparsed.
  83810. **
  83811. ** This opcode invokes the parser to create a new virtual machine,
  83812. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  83813. */
  83814. case OP_ParseSchema: {
  83815. int iDb;
  83816. const char *zMaster;
  83817. char *zSql;
  83818. InitData initData;
  83819. /* Any prepared statement that invokes this opcode will hold mutexes
  83820. ** on every btree. This is a prerequisite for invoking
  83821. ** sqlite3InitCallback().
  83822. */
  83823. #ifdef SQLITE_DEBUG
  83824. for(iDb=0; iDb<db->nDb; iDb++){
  83825. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  83826. }
  83827. #endif
  83828. iDb = pOp->p1;
  83829. assert( iDb>=0 && iDb<db->nDb );
  83830. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  83831. #ifndef SQLITE_OMIT_ALTERTABLE
  83832. if( pOp->p4.z==0 ){
  83833. sqlite3SchemaClear(db->aDb[iDb].pSchema);
  83834. db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
  83835. rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable);
  83836. db->mDbFlags |= DBFLAG_SchemaChange;
  83837. p->expired = 0;
  83838. }else
  83839. #endif
  83840. {
  83841. zMaster = MASTER_NAME;
  83842. initData.db = db;
  83843. initData.iDb = iDb;
  83844. initData.pzErrMsg = &p->zErrMsg;
  83845. initData.mInitFlags = 0;
  83846. zSql = sqlite3MPrintf(db,
  83847. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  83848. db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
  83849. if( zSql==0 ){
  83850. rc = SQLITE_NOMEM_BKPT;
  83851. }else{
  83852. assert( db->init.busy==0 );
  83853. db->init.busy = 1;
  83854. initData.rc = SQLITE_OK;
  83855. initData.nInitRow = 0;
  83856. assert( !db->mallocFailed );
  83857. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  83858. if( rc==SQLITE_OK ) rc = initData.rc;
  83859. if( rc==SQLITE_OK && initData.nInitRow==0 ){
  83860. /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
  83861. ** at least one SQL statement. Any less than that indicates that
  83862. ** the sqlite_master table is corrupt. */
  83863. rc = SQLITE_CORRUPT_BKPT;
  83864. }
  83865. sqlite3DbFreeNN(db, zSql);
  83866. db->init.busy = 0;
  83867. }
  83868. }
  83869. if( rc ){
  83870. sqlite3ResetAllSchemasOfConnection(db);
  83871. if( rc==SQLITE_NOMEM ){
  83872. goto no_mem;
  83873. }
  83874. goto abort_due_to_error;
  83875. }
  83876. break;
  83877. }
  83878. #if !defined(SQLITE_OMIT_ANALYZE)
  83879. /* Opcode: LoadAnalysis P1 * * * *
  83880. **
  83881. ** Read the sqlite_stat1 table for database P1 and load the content
  83882. ** of that table into the internal index hash table. This will cause
  83883. ** the analysis to be used when preparing all subsequent queries.
  83884. */
  83885. case OP_LoadAnalysis: {
  83886. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  83887. rc = sqlite3AnalysisLoad(db, pOp->p1);
  83888. if( rc ) goto abort_due_to_error;
  83889. break;
  83890. }
  83891. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  83892. /* Opcode: DropTable P1 * * P4 *
  83893. **
  83894. ** Remove the internal (in-memory) data structures that describe
  83895. ** the table named P4 in database P1. This is called after a table
  83896. ** is dropped from disk (using the Destroy opcode) in order to keep
  83897. ** the internal representation of the
  83898. ** schema consistent with what is on disk.
  83899. */
  83900. case OP_DropTable: {
  83901. sqlite3VdbeIncrWriteCounter(p, 0);
  83902. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  83903. break;
  83904. }
  83905. /* Opcode: DropIndex P1 * * P4 *
  83906. **
  83907. ** Remove the internal (in-memory) data structures that describe
  83908. ** the index named P4 in database P1. This is called after an index
  83909. ** is dropped from disk (using the Destroy opcode)
  83910. ** in order to keep the internal representation of the
  83911. ** schema consistent with what is on disk.
  83912. */
  83913. case OP_DropIndex: {
  83914. sqlite3VdbeIncrWriteCounter(p, 0);
  83915. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  83916. break;
  83917. }
  83918. /* Opcode: DropTrigger P1 * * P4 *
  83919. **
  83920. ** Remove the internal (in-memory) data structures that describe
  83921. ** the trigger named P4 in database P1. This is called after a trigger
  83922. ** is dropped from disk (using the Destroy opcode) in order to keep
  83923. ** the internal representation of the
  83924. ** schema consistent with what is on disk.
  83925. */
  83926. case OP_DropTrigger: {
  83927. sqlite3VdbeIncrWriteCounter(p, 0);
  83928. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  83929. break;
  83930. }
  83931. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  83932. /* Opcode: IntegrityCk P1 P2 P3 P4 P5
  83933. **
  83934. ** Do an analysis of the currently open database. Store in
  83935. ** register P1 the text of an error message describing any problems.
  83936. ** If no problems are found, store a NULL in register P1.
  83937. **
  83938. ** The register P3 contains one less than the maximum number of allowed errors.
  83939. ** At most reg(P3) errors will be reported.
  83940. ** In other words, the analysis stops as soon as reg(P1) errors are
  83941. ** seen. Reg(P1) is updated with the number of errors remaining.
  83942. **
  83943. ** The root page numbers of all tables in the database are integers
  83944. ** stored in P4_INTARRAY argument.
  83945. **
  83946. ** If P5 is not zero, the check is done on the auxiliary database
  83947. ** file, not the main database file.
  83948. **
  83949. ** This opcode is used to implement the integrity_check pragma.
  83950. */
  83951. case OP_IntegrityCk: {
  83952. int nRoot; /* Number of tables to check. (Number of root pages.) */
  83953. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  83954. int nErr; /* Number of errors reported */
  83955. char *z; /* Text of the error report */
  83956. Mem *pnErr; /* Register keeping track of errors remaining */
  83957. assert( p->bIsReader );
  83958. nRoot = pOp->p2;
  83959. aRoot = pOp->p4.ai;
  83960. assert( nRoot>0 );
  83961. assert( aRoot[0]==nRoot );
  83962. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  83963. pnErr = &aMem[pOp->p3];
  83964. assert( (pnErr->flags & MEM_Int)!=0 );
  83965. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  83966. pIn1 = &aMem[pOp->p1];
  83967. assert( pOp->p5<db->nDb );
  83968. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  83969. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
  83970. (int)pnErr->u.i+1, &nErr);
  83971. sqlite3VdbeMemSetNull(pIn1);
  83972. if( nErr==0 ){
  83973. assert( z==0 );
  83974. }else if( z==0 ){
  83975. goto no_mem;
  83976. }else{
  83977. pnErr->u.i -= nErr-1;
  83978. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  83979. }
  83980. UPDATE_MAX_BLOBSIZE(pIn1);
  83981. sqlite3VdbeChangeEncoding(pIn1, encoding);
  83982. break;
  83983. }
  83984. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  83985. /* Opcode: RowSetAdd P1 P2 * * *
  83986. ** Synopsis: rowset(P1)=r[P2]
  83987. **
  83988. ** Insert the integer value held by register P2 into a RowSet object
  83989. ** held in register P1.
  83990. **
  83991. ** An assertion fails if P2 is not an integer.
  83992. */
  83993. case OP_RowSetAdd: { /* in1, in2 */
  83994. pIn1 = &aMem[pOp->p1];
  83995. pIn2 = &aMem[pOp->p2];
  83996. assert( (pIn2->flags & MEM_Int)!=0 );
  83997. if( (pIn1->flags & MEM_Blob)==0 ){
  83998. if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
  83999. }
  84000. assert( sqlite3VdbeMemIsRowSet(pIn1) );
  84001. sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
  84002. break;
  84003. }
  84004. /* Opcode: RowSetRead P1 P2 P3 * *
  84005. ** Synopsis: r[P3]=rowset(P1)
  84006. **
  84007. ** Extract the smallest value from the RowSet object in P1
  84008. ** and put that value into register P3.
  84009. ** Or, if RowSet object P1 is initially empty, leave P3
  84010. ** unchanged and jump to instruction P2.
  84011. */
  84012. case OP_RowSetRead: { /* jump, in1, out3 */
  84013. i64 val;
  84014. pIn1 = &aMem[pOp->p1];
  84015. assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
  84016. if( (pIn1->flags & MEM_Blob)==0
  84017. || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
  84018. ){
  84019. /* The boolean index is empty */
  84020. sqlite3VdbeMemSetNull(pIn1);
  84021. VdbeBranchTaken(1,2);
  84022. goto jump_to_p2_and_check_for_interrupt;
  84023. }else{
  84024. /* A value was pulled from the index */
  84025. VdbeBranchTaken(0,2);
  84026. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  84027. }
  84028. goto check_for_interrupt;
  84029. }
  84030. /* Opcode: RowSetTest P1 P2 P3 P4
  84031. ** Synopsis: if r[P3] in rowset(P1) goto P2
  84032. **
  84033. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  84034. ** contains a RowSet object and that RowSet object contains
  84035. ** the value held in P3, jump to register P2. Otherwise, insert the
  84036. ** integer in P3 into the RowSet and continue on to the
  84037. ** next opcode.
  84038. **
  84039. ** The RowSet object is optimized for the case where sets of integers
  84040. ** are inserted in distinct phases, which each set contains no duplicates.
  84041. ** Each set is identified by a unique P4 value. The first set
  84042. ** must have P4==0, the final set must have P4==-1, and for all other sets
  84043. ** must have P4>0.
  84044. **
  84045. ** This allows optimizations: (a) when P4==0 there is no need to test
  84046. ** the RowSet object for P3, as it is guaranteed not to contain it,
  84047. ** (b) when P4==-1 there is no need to insert the value, as it will
  84048. ** never be tested for, and (c) when a value that is part of set X is
  84049. ** inserted, there is no need to search to see if the same value was
  84050. ** previously inserted as part of set X (only if it was previously
  84051. ** inserted as part of some other set).
  84052. */
  84053. case OP_RowSetTest: { /* jump, in1, in3 */
  84054. int iSet;
  84055. int exists;
  84056. pIn1 = &aMem[pOp->p1];
  84057. pIn3 = &aMem[pOp->p3];
  84058. iSet = pOp->p4.i;
  84059. assert( pIn3->flags&MEM_Int );
  84060. /* If there is anything other than a rowset object in memory cell P1,
  84061. ** delete it now and initialize P1 with an empty rowset
  84062. */
  84063. if( (pIn1->flags & MEM_Blob)==0 ){
  84064. if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
  84065. }
  84066. assert( sqlite3VdbeMemIsRowSet(pIn1) );
  84067. assert( pOp->p4type==P4_INT32 );
  84068. assert( iSet==-1 || iSet>=0 );
  84069. if( iSet ){
  84070. exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
  84071. VdbeBranchTaken(exists!=0,2);
  84072. if( exists ) goto jump_to_p2;
  84073. }
  84074. if( iSet>=0 ){
  84075. sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
  84076. }
  84077. break;
  84078. }
  84079. #ifndef SQLITE_OMIT_TRIGGER
  84080. /* Opcode: Program P1 P2 P3 P4 P5
  84081. **
  84082. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  84083. **
  84084. ** P1 contains the address of the memory cell that contains the first memory
  84085. ** cell in an array of values used as arguments to the sub-program. P2
  84086. ** contains the address to jump to if the sub-program throws an IGNORE
  84087. ** exception using the RAISE() function. Register P3 contains the address
  84088. ** of a memory cell in this (the parent) VM that is used to allocate the
  84089. ** memory required by the sub-vdbe at runtime.
  84090. **
  84091. ** P4 is a pointer to the VM containing the trigger program.
  84092. **
  84093. ** If P5 is non-zero, then recursive program invocation is enabled.
  84094. */
  84095. case OP_Program: { /* jump */
  84096. int nMem; /* Number of memory registers for sub-program */
  84097. int nByte; /* Bytes of runtime space required for sub-program */
  84098. Mem *pRt; /* Register to allocate runtime space */
  84099. Mem *pMem; /* Used to iterate through memory cells */
  84100. Mem *pEnd; /* Last memory cell in new array */
  84101. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  84102. SubProgram *pProgram; /* Sub-program to execute */
  84103. void *t; /* Token identifying trigger */
  84104. pProgram = pOp->p4.pProgram;
  84105. pRt = &aMem[pOp->p3];
  84106. assert( pProgram->nOp>0 );
  84107. /* If the p5 flag is clear, then recursive invocation of triggers is
  84108. ** disabled for backwards compatibility (p5 is set if this sub-program
  84109. ** is really a trigger, not a foreign key action, and the flag set
  84110. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  84111. **
  84112. ** It is recursive invocation of triggers, at the SQL level, that is
  84113. ** disabled. In some cases a single trigger may generate more than one
  84114. ** SubProgram (if the trigger may be executed with more than one different
  84115. ** ON CONFLICT algorithm). SubProgram structures associated with a
  84116. ** single trigger all have the same value for the SubProgram.token
  84117. ** variable. */
  84118. if( pOp->p5 ){
  84119. t = pProgram->token;
  84120. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  84121. if( pFrame ) break;
  84122. }
  84123. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  84124. rc = SQLITE_ERROR;
  84125. sqlite3VdbeError(p, "too many levels of trigger recursion");
  84126. goto abort_due_to_error;
  84127. }
  84128. /* Register pRt is used to store the memory required to save the state
  84129. ** of the current program, and the memory required at runtime to execute
  84130. ** the trigger program. If this trigger has been fired before, then pRt
  84131. ** is already allocated. Otherwise, it must be initialized. */
  84132. if( (pRt->flags&MEM_Blob)==0 ){
  84133. /* SubProgram.nMem is set to the number of memory cells used by the
  84134. ** program stored in SubProgram.aOp. As well as these, one memory
  84135. ** cell is required for each cursor used by the program. Set local
  84136. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  84137. */
  84138. nMem = pProgram->nMem + pProgram->nCsr;
  84139. assert( nMem>0 );
  84140. if( pProgram->nCsr==0 ) nMem++;
  84141. nByte = ROUND8(sizeof(VdbeFrame))
  84142. + nMem * sizeof(Mem)
  84143. + pProgram->nCsr * sizeof(VdbeCursor*)
  84144. + (pProgram->nOp + 7)/8;
  84145. pFrame = sqlite3DbMallocZero(db, nByte);
  84146. if( !pFrame ){
  84147. goto no_mem;
  84148. }
  84149. sqlite3VdbeMemRelease(pRt);
  84150. pRt->flags = MEM_Blob|MEM_Dyn;
  84151. pRt->z = (char*)pFrame;
  84152. pRt->n = nByte;
  84153. pRt->xDel = sqlite3VdbeFrameMemDel;
  84154. pFrame->v = p;
  84155. pFrame->nChildMem = nMem;
  84156. pFrame->nChildCsr = pProgram->nCsr;
  84157. pFrame->pc = (int)(pOp - aOp);
  84158. pFrame->aMem = p->aMem;
  84159. pFrame->nMem = p->nMem;
  84160. pFrame->apCsr = p->apCsr;
  84161. pFrame->nCursor = p->nCursor;
  84162. pFrame->aOp = p->aOp;
  84163. pFrame->nOp = p->nOp;
  84164. pFrame->token = pProgram->token;
  84165. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  84166. pFrame->anExec = p->anExec;
  84167. #endif
  84168. #ifdef SQLITE_DEBUG
  84169. pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
  84170. #endif
  84171. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  84172. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  84173. pMem->flags = MEM_Undefined;
  84174. pMem->db = db;
  84175. }
  84176. }else{
  84177. pFrame = (VdbeFrame*)pRt->z;
  84178. assert( pRt->xDel==sqlite3VdbeFrameMemDel );
  84179. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
  84180. || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
  84181. assert( pProgram->nCsr==pFrame->nChildCsr );
  84182. assert( (int)(pOp - aOp)==pFrame->pc );
  84183. }
  84184. p->nFrame++;
  84185. pFrame->pParent = p->pFrame;
  84186. pFrame->lastRowid = db->lastRowid;
  84187. pFrame->nChange = p->nChange;
  84188. pFrame->nDbChange = p->db->nChange;
  84189. assert( pFrame->pAuxData==0 );
  84190. pFrame->pAuxData = p->pAuxData;
  84191. p->pAuxData = 0;
  84192. p->nChange = 0;
  84193. p->pFrame = pFrame;
  84194. p->aMem = aMem = VdbeFrameMem(pFrame);
  84195. p->nMem = pFrame->nChildMem;
  84196. p->nCursor = (u16)pFrame->nChildCsr;
  84197. p->apCsr = (VdbeCursor **)&aMem[p->nMem];
  84198. pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
  84199. memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
  84200. p->aOp = aOp = pProgram->aOp;
  84201. p->nOp = pProgram->nOp;
  84202. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  84203. p->anExec = 0;
  84204. #endif
  84205. #ifdef SQLITE_DEBUG
  84206. /* Verify that second and subsequent executions of the same trigger do not
  84207. ** try to reuse register values from the first use. */
  84208. {
  84209. int i;
  84210. for(i=0; i<p->nMem; i++){
  84211. aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */
  84212. aMem[i].flags |= MEM_Undefined; /* Cause a fault if this reg is reused */
  84213. }
  84214. }
  84215. #endif
  84216. pOp = &aOp[-1];
  84217. goto check_for_interrupt;
  84218. }
  84219. /* Opcode: Param P1 P2 * * *
  84220. **
  84221. ** This opcode is only ever present in sub-programs called via the
  84222. ** OP_Program instruction. Copy a value currently stored in a memory
  84223. ** cell of the calling (parent) frame to cell P2 in the current frames
  84224. ** address space. This is used by trigger programs to access the new.*
  84225. ** and old.* values.
  84226. **
  84227. ** The address of the cell in the parent frame is determined by adding
  84228. ** the value of the P1 argument to the value of the P1 argument to the
  84229. ** calling OP_Program instruction.
  84230. */
  84231. case OP_Param: { /* out2 */
  84232. VdbeFrame *pFrame;
  84233. Mem *pIn;
  84234. pOut = out2Prerelease(p, pOp);
  84235. pFrame = p->pFrame;
  84236. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  84237. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  84238. break;
  84239. }
  84240. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  84241. #ifndef SQLITE_OMIT_FOREIGN_KEY
  84242. /* Opcode: FkCounter P1 P2 * * *
  84243. ** Synopsis: fkctr[P1]+=P2
  84244. **
  84245. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  84246. ** If P1 is non-zero, the database constraint counter is incremented
  84247. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  84248. ** statement counter is incremented (immediate foreign key constraints).
  84249. */
  84250. case OP_FkCounter: {
  84251. if( db->flags & SQLITE_DeferFKs ){
  84252. db->nDeferredImmCons += pOp->p2;
  84253. }else if( pOp->p1 ){
  84254. db->nDeferredCons += pOp->p2;
  84255. }else{
  84256. p->nFkConstraint += pOp->p2;
  84257. }
  84258. break;
  84259. }
  84260. /* Opcode: FkIfZero P1 P2 * * *
  84261. ** Synopsis: if fkctr[P1]==0 goto P2
  84262. **
  84263. ** This opcode tests if a foreign key constraint-counter is currently zero.
  84264. ** If so, jump to instruction P2. Otherwise, fall through to the next
  84265. ** instruction.
  84266. **
  84267. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  84268. ** is zero (the one that counts deferred constraint violations). If P1 is
  84269. ** zero, the jump is taken if the statement constraint-counter is zero
  84270. ** (immediate foreign key constraint violations).
  84271. */
  84272. case OP_FkIfZero: { /* jump */
  84273. if( pOp->p1 ){
  84274. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  84275. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  84276. }else{
  84277. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  84278. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  84279. }
  84280. break;
  84281. }
  84282. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  84283. #ifndef SQLITE_OMIT_AUTOINCREMENT
  84284. /* Opcode: MemMax P1 P2 * * *
  84285. ** Synopsis: r[P1]=max(r[P1],r[P2])
  84286. **
  84287. ** P1 is a register in the root frame of this VM (the root frame is
  84288. ** different from the current frame if this instruction is being executed
  84289. ** within a sub-program). Set the value of register P1 to the maximum of
  84290. ** its current value and the value in register P2.
  84291. **
  84292. ** This instruction throws an error if the memory cell is not initially
  84293. ** an integer.
  84294. */
  84295. case OP_MemMax: { /* in2 */
  84296. VdbeFrame *pFrame;
  84297. if( p->pFrame ){
  84298. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  84299. pIn1 = &pFrame->aMem[pOp->p1];
  84300. }else{
  84301. pIn1 = &aMem[pOp->p1];
  84302. }
  84303. assert( memIsValid(pIn1) );
  84304. sqlite3VdbeMemIntegerify(pIn1);
  84305. pIn2 = &aMem[pOp->p2];
  84306. sqlite3VdbeMemIntegerify(pIn2);
  84307. if( pIn1->u.i<pIn2->u.i){
  84308. pIn1->u.i = pIn2->u.i;
  84309. }
  84310. break;
  84311. }
  84312. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  84313. /* Opcode: IfPos P1 P2 P3 * *
  84314. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  84315. **
  84316. ** Register P1 must contain an integer.
  84317. ** If the value of register P1 is 1 or greater, subtract P3 from the
  84318. ** value in P1 and jump to P2.
  84319. **
  84320. ** If the initial value of register P1 is less than 1, then the
  84321. ** value is unchanged and control passes through to the next instruction.
  84322. */
  84323. case OP_IfPos: { /* jump, in1 */
  84324. pIn1 = &aMem[pOp->p1];
  84325. assert( pIn1->flags&MEM_Int );
  84326. VdbeBranchTaken( pIn1->u.i>0, 2);
  84327. if( pIn1->u.i>0 ){
  84328. pIn1->u.i -= pOp->p3;
  84329. goto jump_to_p2;
  84330. }
  84331. break;
  84332. }
  84333. /* Opcode: OffsetLimit P1 P2 P3 * *
  84334. ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
  84335. **
  84336. ** This opcode performs a commonly used computation associated with
  84337. ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
  84338. ** holds the offset counter. The opcode computes the combined value
  84339. ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
  84340. ** value computed is the total number of rows that will need to be
  84341. ** visited in order to complete the query.
  84342. **
  84343. ** If r[P3] is zero or negative, that means there is no OFFSET
  84344. ** and r[P2] is set to be the value of the LIMIT, r[P1].
  84345. **
  84346. ** if r[P1] is zero or negative, that means there is no LIMIT
  84347. ** and r[P2] is set to -1.
  84348. **
  84349. ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
  84350. */
  84351. case OP_OffsetLimit: { /* in1, out2, in3 */
  84352. i64 x;
  84353. pIn1 = &aMem[pOp->p1];
  84354. pIn3 = &aMem[pOp->p3];
  84355. pOut = out2Prerelease(p, pOp);
  84356. assert( pIn1->flags & MEM_Int );
  84357. assert( pIn3->flags & MEM_Int );
  84358. x = pIn1->u.i;
  84359. if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
  84360. /* If the LIMIT is less than or equal to zero, loop forever. This
  84361. ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
  84362. ** also loop forever. This is undocumented. In fact, one could argue
  84363. ** that the loop should terminate. But assuming 1 billion iterations
  84364. ** per second (far exceeding the capabilities of any current hardware)
  84365. ** it would take nearly 300 years to actually reach the limit. So
  84366. ** looping forever is a reasonable approximation. */
  84367. pOut->u.i = -1;
  84368. }else{
  84369. pOut->u.i = x;
  84370. }
  84371. break;
  84372. }
  84373. /* Opcode: IfNotZero P1 P2 * * *
  84374. ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
  84375. **
  84376. ** Register P1 must contain an integer. If the content of register P1 is
  84377. ** initially greater than zero, then decrement the value in register P1.
  84378. ** If it is non-zero (negative or positive) and then also jump to P2.
  84379. ** If register P1 is initially zero, leave it unchanged and fall through.
  84380. */
  84381. case OP_IfNotZero: { /* jump, in1 */
  84382. pIn1 = &aMem[pOp->p1];
  84383. assert( pIn1->flags&MEM_Int );
  84384. VdbeBranchTaken(pIn1->u.i<0, 2);
  84385. if( pIn1->u.i ){
  84386. if( pIn1->u.i>0 ) pIn1->u.i--;
  84387. goto jump_to_p2;
  84388. }
  84389. break;
  84390. }
  84391. /* Opcode: DecrJumpZero P1 P2 * * *
  84392. ** Synopsis: if (--r[P1])==0 goto P2
  84393. **
  84394. ** Register P1 must hold an integer. Decrement the value in P1
  84395. ** and jump to P2 if the new value is exactly zero.
  84396. */
  84397. case OP_DecrJumpZero: { /* jump, in1 */
  84398. pIn1 = &aMem[pOp->p1];
  84399. assert( pIn1->flags&MEM_Int );
  84400. if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
  84401. VdbeBranchTaken(pIn1->u.i==0, 2);
  84402. if( pIn1->u.i==0 ) goto jump_to_p2;
  84403. break;
  84404. }
  84405. /* Opcode: AggStep * P2 P3 P4 P5
  84406. ** Synopsis: accum=r[P3] step(r[P2@P5])
  84407. **
  84408. ** Execute the xStep function for an aggregate.
  84409. ** The function has P5 arguments. P4 is a pointer to the
  84410. ** FuncDef structure that specifies the function. Register P3 is the
  84411. ** accumulator.
  84412. **
  84413. ** The P5 arguments are taken from register P2 and its
  84414. ** successors.
  84415. */
  84416. /* Opcode: AggInverse * P2 P3 P4 P5
  84417. ** Synopsis: accum=r[P3] inverse(r[P2@P5])
  84418. **
  84419. ** Execute the xInverse function for an aggregate.
  84420. ** The function has P5 arguments. P4 is a pointer to the
  84421. ** FuncDef structure that specifies the function. Register P3 is the
  84422. ** accumulator.
  84423. **
  84424. ** The P5 arguments are taken from register P2 and its
  84425. ** successors.
  84426. */
  84427. /* Opcode: AggStep1 P1 P2 P3 P4 P5
  84428. ** Synopsis: accum=r[P3] step(r[P2@P5])
  84429. **
  84430. ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
  84431. ** aggregate. The function has P5 arguments. P4 is a pointer to the
  84432. ** FuncDef structure that specifies the function. Register P3 is the
  84433. ** accumulator.
  84434. **
  84435. ** The P5 arguments are taken from register P2 and its
  84436. ** successors.
  84437. **
  84438. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  84439. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  84440. ** the opcode is changed. In this way, the initialization of the
  84441. ** sqlite3_context only happens once, instead of on each call to the
  84442. ** step function.
  84443. */
  84444. case OP_AggInverse:
  84445. case OP_AggStep: {
  84446. int n;
  84447. sqlite3_context *pCtx;
  84448. assert( pOp->p4type==P4_FUNCDEF );
  84449. n = pOp->p5;
  84450. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  84451. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  84452. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  84453. pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
  84454. (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
  84455. if( pCtx==0 ) goto no_mem;
  84456. pCtx->pMem = 0;
  84457. pCtx->pOut = (Mem*)&(pCtx->argv[n]);
  84458. sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
  84459. pCtx->pFunc = pOp->p4.pFunc;
  84460. pCtx->iOp = (int)(pOp - aOp);
  84461. pCtx->pVdbe = p;
  84462. pCtx->skipFlag = 0;
  84463. pCtx->isError = 0;
  84464. pCtx->argc = n;
  84465. pOp->p4type = P4_FUNCCTX;
  84466. pOp->p4.pCtx = pCtx;
  84467. /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
  84468. assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
  84469. pOp->opcode = OP_AggStep1;
  84470. /* Fall through into OP_AggStep */
  84471. }
  84472. case OP_AggStep1: {
  84473. int i;
  84474. sqlite3_context *pCtx;
  84475. Mem *pMem;
  84476. assert( pOp->p4type==P4_FUNCCTX );
  84477. pCtx = pOp->p4.pCtx;
  84478. pMem = &aMem[pOp->p3];
  84479. #ifdef SQLITE_DEBUG
  84480. if( pOp->p1 ){
  84481. /* This is an OP_AggInverse call. Verify that xStep has always
  84482. ** been called at least once prior to any xInverse call. */
  84483. assert( pMem->uTemp==0x1122e0e3 );
  84484. }else{
  84485. /* This is an OP_AggStep call. Mark it as such. */
  84486. pMem->uTemp = 0x1122e0e3;
  84487. }
  84488. #endif
  84489. /* If this function is inside of a trigger, the register array in aMem[]
  84490. ** might change from one evaluation to the next. The next block of code
  84491. ** checks to see if the register array has changed, and if so it
  84492. ** reinitializes the relavant parts of the sqlite3_context object */
  84493. if( pCtx->pMem != pMem ){
  84494. pCtx->pMem = pMem;
  84495. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  84496. }
  84497. #ifdef SQLITE_DEBUG
  84498. for(i=0; i<pCtx->argc; i++){
  84499. assert( memIsValid(pCtx->argv[i]) );
  84500. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  84501. }
  84502. #endif
  84503. pMem->n++;
  84504. assert( pCtx->pOut->flags==MEM_Null );
  84505. assert( pCtx->isError==0 );
  84506. assert( pCtx->skipFlag==0 );
  84507. #ifndef SQLITE_OMIT_WINDOWFUNC
  84508. if( pOp->p1 ){
  84509. (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
  84510. }else
  84511. #endif
  84512. (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  84513. if( pCtx->isError ){
  84514. if( pCtx->isError>0 ){
  84515. sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
  84516. rc = pCtx->isError;
  84517. }
  84518. if( pCtx->skipFlag ){
  84519. assert( pOp[-1].opcode==OP_CollSeq );
  84520. i = pOp[-1].p1;
  84521. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  84522. pCtx->skipFlag = 0;
  84523. }
  84524. sqlite3VdbeMemRelease(pCtx->pOut);
  84525. pCtx->pOut->flags = MEM_Null;
  84526. pCtx->isError = 0;
  84527. if( rc ) goto abort_due_to_error;
  84528. }
  84529. assert( pCtx->pOut->flags==MEM_Null );
  84530. assert( pCtx->skipFlag==0 );
  84531. break;
  84532. }
  84533. /* Opcode: AggFinal P1 P2 * P4 *
  84534. ** Synopsis: accum=r[P1] N=P2
  84535. **
  84536. ** P1 is the memory location that is the accumulator for an aggregate
  84537. ** or window function. Execute the finalizer function
  84538. ** for an aggregate and store the result in P1.
  84539. **
  84540. ** P2 is the number of arguments that the step function takes and
  84541. ** P4 is a pointer to the FuncDef for this function. The P2
  84542. ** argument is not used by this opcode. It is only there to disambiguate
  84543. ** functions that can take varying numbers of arguments. The
  84544. ** P4 argument is only needed for the case where
  84545. ** the step function was not previously called.
  84546. */
  84547. /* Opcode: AggValue * P2 P3 P4 *
  84548. ** Synopsis: r[P3]=value N=P2
  84549. **
  84550. ** Invoke the xValue() function and store the result in register P3.
  84551. **
  84552. ** P2 is the number of arguments that the step function takes and
  84553. ** P4 is a pointer to the FuncDef for this function. The P2
  84554. ** argument is not used by this opcode. It is only there to disambiguate
  84555. ** functions that can take varying numbers of arguments. The
  84556. ** P4 argument is only needed for the case where
  84557. ** the step function was not previously called.
  84558. */
  84559. case OP_AggValue:
  84560. case OP_AggFinal: {
  84561. Mem *pMem;
  84562. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  84563. assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
  84564. pMem = &aMem[pOp->p1];
  84565. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  84566. #ifndef SQLITE_OMIT_WINDOWFUNC
  84567. if( pOp->p3 ){
  84568. memAboutToChange(p, &aMem[pOp->p3]);
  84569. rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
  84570. pMem = &aMem[pOp->p3];
  84571. }else
  84572. #endif
  84573. {
  84574. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  84575. }
  84576. if( rc ){
  84577. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  84578. goto abort_due_to_error;
  84579. }
  84580. sqlite3VdbeChangeEncoding(pMem, encoding);
  84581. UPDATE_MAX_BLOBSIZE(pMem);
  84582. if( sqlite3VdbeMemTooBig(pMem) ){
  84583. goto too_big;
  84584. }
  84585. break;
  84586. }
  84587. #ifndef SQLITE_OMIT_WAL
  84588. /* Opcode: Checkpoint P1 P2 P3 * *
  84589. **
  84590. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  84591. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  84592. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  84593. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  84594. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  84595. ** in the WAL that have been checkpointed after the checkpoint
  84596. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  84597. ** mem[P3+2] are initialized to -1.
  84598. */
  84599. case OP_Checkpoint: {
  84600. int i; /* Loop counter */
  84601. int aRes[3]; /* Results */
  84602. Mem *pMem; /* Write results here */
  84603. assert( p->readOnly==0 );
  84604. aRes[0] = 0;
  84605. aRes[1] = aRes[2] = -1;
  84606. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  84607. || pOp->p2==SQLITE_CHECKPOINT_FULL
  84608. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  84609. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  84610. );
  84611. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  84612. if( rc ){
  84613. if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
  84614. rc = SQLITE_OK;
  84615. aRes[0] = 1;
  84616. }
  84617. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  84618. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  84619. }
  84620. break;
  84621. };
  84622. #endif
  84623. #ifndef SQLITE_OMIT_PRAGMA
  84624. /* Opcode: JournalMode P1 P2 P3 * *
  84625. **
  84626. ** Change the journal mode of database P1 to P3. P3 must be one of the
  84627. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  84628. ** modes (delete, truncate, persist, off and memory), this is a simple
  84629. ** operation. No IO is required.
  84630. **
  84631. ** If changing into or out of WAL mode the procedure is more complicated.
  84632. **
  84633. ** Write a string containing the final journal-mode to register P2.
  84634. */
  84635. case OP_JournalMode: { /* out2 */
  84636. Btree *pBt; /* Btree to change journal mode of */
  84637. Pager *pPager; /* Pager associated with pBt */
  84638. int eNew; /* New journal mode */
  84639. int eOld; /* The old journal mode */
  84640. #ifndef SQLITE_OMIT_WAL
  84641. const char *zFilename; /* Name of database file for pPager */
  84642. #endif
  84643. pOut = out2Prerelease(p, pOp);
  84644. eNew = pOp->p3;
  84645. assert( eNew==PAGER_JOURNALMODE_DELETE
  84646. || eNew==PAGER_JOURNALMODE_TRUNCATE
  84647. || eNew==PAGER_JOURNALMODE_PERSIST
  84648. || eNew==PAGER_JOURNALMODE_OFF
  84649. || eNew==PAGER_JOURNALMODE_MEMORY
  84650. || eNew==PAGER_JOURNALMODE_WAL
  84651. || eNew==PAGER_JOURNALMODE_QUERY
  84652. );
  84653. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  84654. assert( p->readOnly==0 );
  84655. pBt = db->aDb[pOp->p1].pBt;
  84656. pPager = sqlite3BtreePager(pBt);
  84657. eOld = sqlite3PagerGetJournalMode(pPager);
  84658. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  84659. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  84660. #ifndef SQLITE_OMIT_WAL
  84661. zFilename = sqlite3PagerFilename(pPager, 1);
  84662. /* Do not allow a transition to journal_mode=WAL for a database
  84663. ** in temporary storage or if the VFS does not support shared memory
  84664. */
  84665. if( eNew==PAGER_JOURNALMODE_WAL
  84666. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  84667. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  84668. ){
  84669. eNew = eOld;
  84670. }
  84671. if( (eNew!=eOld)
  84672. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  84673. ){
  84674. if( !db->autoCommit || db->nVdbeRead>1 ){
  84675. rc = SQLITE_ERROR;
  84676. sqlite3VdbeError(p,
  84677. "cannot change %s wal mode from within a transaction",
  84678. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  84679. );
  84680. goto abort_due_to_error;
  84681. }else{
  84682. if( eOld==PAGER_JOURNALMODE_WAL ){
  84683. /* If leaving WAL mode, close the log file. If successful, the call
  84684. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  84685. ** file. An EXCLUSIVE lock may still be held on the database file
  84686. ** after a successful return.
  84687. */
  84688. rc = sqlite3PagerCloseWal(pPager, db);
  84689. if( rc==SQLITE_OK ){
  84690. sqlite3PagerSetJournalMode(pPager, eNew);
  84691. }
  84692. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  84693. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  84694. ** as an intermediate */
  84695. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  84696. }
  84697. /* Open a transaction on the database file. Regardless of the journal
  84698. ** mode, this transaction always uses a rollback journal.
  84699. */
  84700. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  84701. if( rc==SQLITE_OK ){
  84702. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  84703. }
  84704. }
  84705. }
  84706. #endif /* ifndef SQLITE_OMIT_WAL */
  84707. if( rc ) eNew = eOld;
  84708. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  84709. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  84710. pOut->z = (char *)sqlite3JournalModename(eNew);
  84711. pOut->n = sqlite3Strlen30(pOut->z);
  84712. pOut->enc = SQLITE_UTF8;
  84713. sqlite3VdbeChangeEncoding(pOut, encoding);
  84714. if( rc ) goto abort_due_to_error;
  84715. break;
  84716. };
  84717. #endif /* SQLITE_OMIT_PRAGMA */
  84718. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  84719. /* Opcode: Vacuum P1 P2 * * *
  84720. **
  84721. ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
  84722. ** for an attached database. The "temp" database may not be vacuumed.
  84723. **
  84724. ** If P2 is not zero, then it is a register holding a string which is
  84725. ** the file into which the result of vacuum should be written. When
  84726. ** P2 is zero, the vacuum overwrites the original database.
  84727. */
  84728. case OP_Vacuum: {
  84729. assert( p->readOnly==0 );
  84730. rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
  84731. pOp->p2 ? &aMem[pOp->p2] : 0);
  84732. if( rc ) goto abort_due_to_error;
  84733. break;
  84734. }
  84735. #endif
  84736. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  84737. /* Opcode: IncrVacuum P1 P2 * * *
  84738. **
  84739. ** Perform a single step of the incremental vacuum procedure on
  84740. ** the P1 database. If the vacuum has finished, jump to instruction
  84741. ** P2. Otherwise, fall through to the next instruction.
  84742. */
  84743. case OP_IncrVacuum: { /* jump */
  84744. Btree *pBt;
  84745. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  84746. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  84747. assert( p->readOnly==0 );
  84748. pBt = db->aDb[pOp->p1].pBt;
  84749. rc = sqlite3BtreeIncrVacuum(pBt);
  84750. VdbeBranchTaken(rc==SQLITE_DONE,2);
  84751. if( rc ){
  84752. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  84753. rc = SQLITE_OK;
  84754. goto jump_to_p2;
  84755. }
  84756. break;
  84757. }
  84758. #endif
  84759. /* Opcode: Expire P1 P2 * * *
  84760. **
  84761. ** Cause precompiled statements to expire. When an expired statement
  84762. ** is executed using sqlite3_step() it will either automatically
  84763. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  84764. ** or it will fail with SQLITE_SCHEMA.
  84765. **
  84766. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  84767. ** then only the currently executing statement is expired.
  84768. **
  84769. ** If P2 is 0, then SQL statements are expired immediately. If P2 is 1,
  84770. ** then running SQL statements are allowed to continue to run to completion.
  84771. ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
  84772. ** that might help the statement run faster but which does not affect the
  84773. ** correctness of operation.
  84774. */
  84775. case OP_Expire: {
  84776. assert( pOp->p2==0 || pOp->p2==1 );
  84777. if( !pOp->p1 ){
  84778. sqlite3ExpirePreparedStatements(db, pOp->p2);
  84779. }else{
  84780. p->expired = pOp->p2+1;
  84781. }
  84782. break;
  84783. }
  84784. #ifndef SQLITE_OMIT_SHARED_CACHE
  84785. /* Opcode: TableLock P1 P2 P3 P4 *
  84786. ** Synopsis: iDb=P1 root=P2 write=P3
  84787. **
  84788. ** Obtain a lock on a particular table. This instruction is only used when
  84789. ** the shared-cache feature is enabled.
  84790. **
  84791. ** P1 is the index of the database in sqlite3.aDb[] of the database
  84792. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  84793. ** a write lock if P3==1.
  84794. **
  84795. ** P2 contains the root-page of the table to lock.
  84796. **
  84797. ** P4 contains a pointer to the name of the table being locked. This is only
  84798. ** used to generate an error message if the lock cannot be obtained.
  84799. */
  84800. case OP_TableLock: {
  84801. u8 isWriteLock = (u8)pOp->p3;
  84802. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
  84803. int p1 = pOp->p1;
  84804. assert( p1>=0 && p1<db->nDb );
  84805. assert( DbMaskTest(p->btreeMask, p1) );
  84806. assert( isWriteLock==0 || isWriteLock==1 );
  84807. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  84808. if( rc ){
  84809. if( (rc&0xFF)==SQLITE_LOCKED ){
  84810. const char *z = pOp->p4.z;
  84811. sqlite3VdbeError(p, "database table is locked: %s", z);
  84812. }
  84813. goto abort_due_to_error;
  84814. }
  84815. }
  84816. break;
  84817. }
  84818. #endif /* SQLITE_OMIT_SHARED_CACHE */
  84819. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84820. /* Opcode: VBegin * * * P4 *
  84821. **
  84822. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  84823. ** xBegin method for that table.
  84824. **
  84825. ** Also, whether or not P4 is set, check that this is not being called from
  84826. ** within a callback to a virtual table xSync() method. If it is, the error
  84827. ** code will be set to SQLITE_LOCKED.
  84828. */
  84829. case OP_VBegin: {
  84830. VTable *pVTab;
  84831. pVTab = pOp->p4.pVtab;
  84832. rc = sqlite3VtabBegin(db, pVTab);
  84833. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  84834. if( rc ) goto abort_due_to_error;
  84835. break;
  84836. }
  84837. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84838. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84839. /* Opcode: VCreate P1 P2 * * *
  84840. **
  84841. ** P2 is a register that holds the name of a virtual table in database
  84842. ** P1. Call the xCreate method for that table.
  84843. */
  84844. case OP_VCreate: {
  84845. Mem sMem; /* For storing the record being decoded */
  84846. const char *zTab; /* Name of the virtual table */
  84847. memset(&sMem, 0, sizeof(sMem));
  84848. sMem.db = db;
  84849. /* Because P2 is always a static string, it is impossible for the
  84850. ** sqlite3VdbeMemCopy() to fail */
  84851. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  84852. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  84853. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  84854. assert( rc==SQLITE_OK );
  84855. zTab = (const char*)sqlite3_value_text(&sMem);
  84856. assert( zTab || db->mallocFailed );
  84857. if( zTab ){
  84858. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  84859. }
  84860. sqlite3VdbeMemRelease(&sMem);
  84861. if( rc ) goto abort_due_to_error;
  84862. break;
  84863. }
  84864. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84865. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84866. /* Opcode: VDestroy P1 * * P4 *
  84867. **
  84868. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  84869. ** of that table.
  84870. */
  84871. case OP_VDestroy: {
  84872. db->nVDestroy++;
  84873. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  84874. db->nVDestroy--;
  84875. assert( p->errorAction==OE_Abort && p->usesStmtJournal );
  84876. if( rc ) goto abort_due_to_error;
  84877. break;
  84878. }
  84879. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84880. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84881. /* Opcode: VOpen P1 * * P4 *
  84882. **
  84883. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  84884. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  84885. ** table and stores that cursor in P1.
  84886. */
  84887. case OP_VOpen: {
  84888. VdbeCursor *pCur;
  84889. sqlite3_vtab_cursor *pVCur;
  84890. sqlite3_vtab *pVtab;
  84891. const sqlite3_module *pModule;
  84892. assert( p->bIsReader );
  84893. pCur = 0;
  84894. pVCur = 0;
  84895. pVtab = pOp->p4.pVtab->pVtab;
  84896. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  84897. rc = SQLITE_LOCKED;
  84898. goto abort_due_to_error;
  84899. }
  84900. pModule = pVtab->pModule;
  84901. rc = pModule->xOpen(pVtab, &pVCur);
  84902. sqlite3VtabImportErrmsg(p, pVtab);
  84903. if( rc ) goto abort_due_to_error;
  84904. /* Initialize sqlite3_vtab_cursor base class */
  84905. pVCur->pVtab = pVtab;
  84906. /* Initialize vdbe cursor object */
  84907. pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
  84908. if( pCur ){
  84909. pCur->uc.pVCur = pVCur;
  84910. pVtab->nRef++;
  84911. }else{
  84912. assert( db->mallocFailed );
  84913. pModule->xClose(pVCur);
  84914. goto no_mem;
  84915. }
  84916. break;
  84917. }
  84918. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84919. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84920. /* Opcode: VFilter P1 P2 P3 P4 *
  84921. ** Synopsis: iplan=r[P3] zplan='P4'
  84922. **
  84923. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  84924. ** the filtered result set is empty.
  84925. **
  84926. ** P4 is either NULL or a string that was generated by the xBestIndex
  84927. ** method of the module. The interpretation of the P4 string is left
  84928. ** to the module implementation.
  84929. **
  84930. ** This opcode invokes the xFilter method on the virtual table specified
  84931. ** by P1. The integer query plan parameter to xFilter is stored in register
  84932. ** P3. Register P3+1 stores the argc parameter to be passed to the
  84933. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  84934. ** additional parameters which are passed to
  84935. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  84936. **
  84937. ** A jump is made to P2 if the result set after filtering would be empty.
  84938. */
  84939. case OP_VFilter: { /* jump */
  84940. int nArg;
  84941. int iQuery;
  84942. const sqlite3_module *pModule;
  84943. Mem *pQuery;
  84944. Mem *pArgc;
  84945. sqlite3_vtab_cursor *pVCur;
  84946. sqlite3_vtab *pVtab;
  84947. VdbeCursor *pCur;
  84948. int res;
  84949. int i;
  84950. Mem **apArg;
  84951. pQuery = &aMem[pOp->p3];
  84952. pArgc = &pQuery[1];
  84953. pCur = p->apCsr[pOp->p1];
  84954. assert( memIsValid(pQuery) );
  84955. REGISTER_TRACE(pOp->p3, pQuery);
  84956. assert( pCur->eCurType==CURTYPE_VTAB );
  84957. pVCur = pCur->uc.pVCur;
  84958. pVtab = pVCur->pVtab;
  84959. pModule = pVtab->pModule;
  84960. /* Grab the index number and argc parameters */
  84961. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  84962. nArg = (int)pArgc->u.i;
  84963. iQuery = (int)pQuery->u.i;
  84964. /* Invoke the xFilter method */
  84965. res = 0;
  84966. apArg = p->apArg;
  84967. for(i = 0; i<nArg; i++){
  84968. apArg[i] = &pArgc[i+1];
  84969. }
  84970. rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
  84971. sqlite3VtabImportErrmsg(p, pVtab);
  84972. if( rc ) goto abort_due_to_error;
  84973. res = pModule->xEof(pVCur);
  84974. pCur->nullRow = 0;
  84975. VdbeBranchTaken(res!=0,2);
  84976. if( res ) goto jump_to_p2;
  84977. break;
  84978. }
  84979. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84980. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84981. /* Opcode: VColumn P1 P2 P3 * P5
  84982. ** Synopsis: r[P3]=vcolumn(P2)
  84983. **
  84984. ** Store in register P3 the value of the P2-th column of
  84985. ** the current row of the virtual-table of cursor P1.
  84986. **
  84987. ** If the VColumn opcode is being used to fetch the value of
  84988. ** an unchanging column during an UPDATE operation, then the P5
  84989. ** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange()
  84990. ** function to return true inside the xColumn method of the virtual
  84991. ** table implementation. The P5 column might also contain other
  84992. ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
  84993. ** unused by OP_VColumn.
  84994. */
  84995. case OP_VColumn: {
  84996. sqlite3_vtab *pVtab;
  84997. const sqlite3_module *pModule;
  84998. Mem *pDest;
  84999. sqlite3_context sContext;
  85000. VdbeCursor *pCur = p->apCsr[pOp->p1];
  85001. assert( pCur->eCurType==CURTYPE_VTAB );
  85002. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  85003. pDest = &aMem[pOp->p3];
  85004. memAboutToChange(p, pDest);
  85005. if( pCur->nullRow ){
  85006. sqlite3VdbeMemSetNull(pDest);
  85007. break;
  85008. }
  85009. pVtab = pCur->uc.pVCur->pVtab;
  85010. pModule = pVtab->pModule;
  85011. assert( pModule->xColumn );
  85012. memset(&sContext, 0, sizeof(sContext));
  85013. sContext.pOut = pDest;
  85014. testcase( (pOp->p5 & OPFLAG_NOCHNG)==0 && pOp->p5!=0 );
  85015. if( pOp->p5 & OPFLAG_NOCHNG ){
  85016. sqlite3VdbeMemSetNull(pDest);
  85017. pDest->flags = MEM_Null|MEM_Zero;
  85018. pDest->u.nZero = 0;
  85019. }else{
  85020. MemSetTypeFlag(pDest, MEM_Null);
  85021. }
  85022. rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
  85023. sqlite3VtabImportErrmsg(p, pVtab);
  85024. if( sContext.isError>0 ){
  85025. sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
  85026. rc = sContext.isError;
  85027. }
  85028. sqlite3VdbeChangeEncoding(pDest, encoding);
  85029. REGISTER_TRACE(pOp->p3, pDest);
  85030. UPDATE_MAX_BLOBSIZE(pDest);
  85031. if( sqlite3VdbeMemTooBig(pDest) ){
  85032. goto too_big;
  85033. }
  85034. if( rc ) goto abort_due_to_error;
  85035. break;
  85036. }
  85037. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  85038. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85039. /* Opcode: VNext P1 P2 * * *
  85040. **
  85041. ** Advance virtual table P1 to the next row in its result set and
  85042. ** jump to instruction P2. Or, if the virtual table has reached
  85043. ** the end of its result set, then fall through to the next instruction.
  85044. */
  85045. case OP_VNext: { /* jump */
  85046. sqlite3_vtab *pVtab;
  85047. const sqlite3_module *pModule;
  85048. int res;
  85049. VdbeCursor *pCur;
  85050. res = 0;
  85051. pCur = p->apCsr[pOp->p1];
  85052. assert( pCur->eCurType==CURTYPE_VTAB );
  85053. if( pCur->nullRow ){
  85054. break;
  85055. }
  85056. pVtab = pCur->uc.pVCur->pVtab;
  85057. pModule = pVtab->pModule;
  85058. assert( pModule->xNext );
  85059. /* Invoke the xNext() method of the module. There is no way for the
  85060. ** underlying implementation to return an error if one occurs during
  85061. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  85062. ** data is available) and the error code returned when xColumn or
  85063. ** some other method is next invoked on the save virtual table cursor.
  85064. */
  85065. rc = pModule->xNext(pCur->uc.pVCur);
  85066. sqlite3VtabImportErrmsg(p, pVtab);
  85067. if( rc ) goto abort_due_to_error;
  85068. res = pModule->xEof(pCur->uc.pVCur);
  85069. VdbeBranchTaken(!res,2);
  85070. if( !res ){
  85071. /* If there is data, jump to P2 */
  85072. goto jump_to_p2_and_check_for_interrupt;
  85073. }
  85074. goto check_for_interrupt;
  85075. }
  85076. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  85077. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85078. /* Opcode: VRename P1 * * P4 *
  85079. **
  85080. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  85081. ** This opcode invokes the corresponding xRename method. The value
  85082. ** in register P1 is passed as the zName argument to the xRename method.
  85083. */
  85084. case OP_VRename: {
  85085. sqlite3_vtab *pVtab;
  85086. Mem *pName;
  85087. int isLegacy;
  85088. isLegacy = (db->flags & SQLITE_LegacyAlter);
  85089. db->flags |= SQLITE_LegacyAlter;
  85090. pVtab = pOp->p4.pVtab->pVtab;
  85091. pName = &aMem[pOp->p1];
  85092. assert( pVtab->pModule->xRename );
  85093. assert( memIsValid(pName) );
  85094. assert( p->readOnly==0 );
  85095. REGISTER_TRACE(pOp->p1, pName);
  85096. assert( pName->flags & MEM_Str );
  85097. testcase( pName->enc==SQLITE_UTF8 );
  85098. testcase( pName->enc==SQLITE_UTF16BE );
  85099. testcase( pName->enc==SQLITE_UTF16LE );
  85100. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  85101. if( rc ) goto abort_due_to_error;
  85102. rc = pVtab->pModule->xRename(pVtab, pName->z);
  85103. if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
  85104. sqlite3VtabImportErrmsg(p, pVtab);
  85105. p->expired = 0;
  85106. if( rc ) goto abort_due_to_error;
  85107. break;
  85108. }
  85109. #endif
  85110. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85111. /* Opcode: VUpdate P1 P2 P3 P4 P5
  85112. ** Synopsis: data=r[P3@P2]
  85113. **
  85114. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  85115. ** This opcode invokes the corresponding xUpdate method. P2 values
  85116. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  85117. ** invocation. The value in register (P3+P2-1) corresponds to the
  85118. ** p2th element of the argv array passed to xUpdate.
  85119. **
  85120. ** The xUpdate method will do a DELETE or an INSERT or both.
  85121. ** The argv[0] element (which corresponds to memory cell P3)
  85122. ** is the rowid of a row to delete. If argv[0] is NULL then no
  85123. ** deletion occurs. The argv[1] element is the rowid of the new
  85124. ** row. This can be NULL to have the virtual table select the new
  85125. ** rowid for itself. The subsequent elements in the array are
  85126. ** the values of columns in the new row.
  85127. **
  85128. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  85129. ** a row to delete.
  85130. **
  85131. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  85132. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  85133. ** is set to the value of the rowid for the row just inserted.
  85134. **
  85135. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  85136. ** apply in the case of a constraint failure on an insert or update.
  85137. */
  85138. case OP_VUpdate: {
  85139. sqlite3_vtab *pVtab;
  85140. const sqlite3_module *pModule;
  85141. int nArg;
  85142. int i;
  85143. sqlite_int64 rowid;
  85144. Mem **apArg;
  85145. Mem *pX;
  85146. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  85147. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  85148. );
  85149. assert( p->readOnly==0 );
  85150. if( db->mallocFailed ) goto no_mem;
  85151. sqlite3VdbeIncrWriteCounter(p, 0);
  85152. pVtab = pOp->p4.pVtab->pVtab;
  85153. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  85154. rc = SQLITE_LOCKED;
  85155. goto abort_due_to_error;
  85156. }
  85157. pModule = pVtab->pModule;
  85158. nArg = pOp->p2;
  85159. assert( pOp->p4type==P4_VTAB );
  85160. if( ALWAYS(pModule->xUpdate) ){
  85161. u8 vtabOnConflict = db->vtabOnConflict;
  85162. apArg = p->apArg;
  85163. pX = &aMem[pOp->p3];
  85164. for(i=0; i<nArg; i++){
  85165. assert( memIsValid(pX) );
  85166. memAboutToChange(p, pX);
  85167. apArg[i] = pX;
  85168. pX++;
  85169. }
  85170. db->vtabOnConflict = pOp->p5;
  85171. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  85172. db->vtabOnConflict = vtabOnConflict;
  85173. sqlite3VtabImportErrmsg(p, pVtab);
  85174. if( rc==SQLITE_OK && pOp->p1 ){
  85175. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  85176. db->lastRowid = rowid;
  85177. }
  85178. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  85179. if( pOp->p5==OE_Ignore ){
  85180. rc = SQLITE_OK;
  85181. }else{
  85182. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  85183. }
  85184. }else{
  85185. p->nChange++;
  85186. }
  85187. if( rc ) goto abort_due_to_error;
  85188. }
  85189. break;
  85190. }
  85191. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  85192. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  85193. /* Opcode: Pagecount P1 P2 * * *
  85194. **
  85195. ** Write the current number of pages in database P1 to memory cell P2.
  85196. */
  85197. case OP_Pagecount: { /* out2 */
  85198. pOut = out2Prerelease(p, pOp);
  85199. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  85200. break;
  85201. }
  85202. #endif
  85203. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  85204. /* Opcode: MaxPgcnt P1 P2 P3 * *
  85205. **
  85206. ** Try to set the maximum page count for database P1 to the value in P3.
  85207. ** Do not let the maximum page count fall below the current page count and
  85208. ** do not change the maximum page count value if P3==0.
  85209. **
  85210. ** Store the maximum page count after the change in register P2.
  85211. */
  85212. case OP_MaxPgcnt: { /* out2 */
  85213. unsigned int newMax;
  85214. Btree *pBt;
  85215. pOut = out2Prerelease(p, pOp);
  85216. pBt = db->aDb[pOp->p1].pBt;
  85217. newMax = 0;
  85218. if( pOp->p3 ){
  85219. newMax = sqlite3BtreeLastPage(pBt);
  85220. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  85221. }
  85222. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  85223. break;
  85224. }
  85225. #endif
  85226. /* Opcode: Function0 P1 P2 P3 P4 P5
  85227. ** Synopsis: r[P3]=func(r[P2@P5])
  85228. **
  85229. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  85230. ** defines the function) with P5 arguments taken from register P2 and
  85231. ** successors. The result of the function is stored in register P3.
  85232. ** Register P3 must not be one of the function inputs.
  85233. **
  85234. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  85235. ** function was determined to be constant at compile time. If the first
  85236. ** argument was constant then bit 0 of P1 is set. This is used to determine
  85237. ** whether meta data associated with a user function argument using the
  85238. ** sqlite3_set_auxdata() API may be safely retained until the next
  85239. ** invocation of this opcode.
  85240. **
  85241. ** See also: Function, AggStep, AggFinal
  85242. */
  85243. /* Opcode: Function P1 P2 P3 P4 P5
  85244. ** Synopsis: r[P3]=func(r[P2@P5])
  85245. **
  85246. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  85247. ** contains a pointer to the function to be run) with P5 arguments taken
  85248. ** from register P2 and successors. The result of the function is stored
  85249. ** in register P3. Register P3 must not be one of the function inputs.
  85250. **
  85251. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  85252. ** function was determined to be constant at compile time. If the first
  85253. ** argument was constant then bit 0 of P1 is set. This is used to determine
  85254. ** whether meta data associated with a user function argument using the
  85255. ** sqlite3_set_auxdata() API may be safely retained until the next
  85256. ** invocation of this opcode.
  85257. **
  85258. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  85259. ** to a FuncDef object. But on first evaluation, the P4 operand is
  85260. ** automatically converted into an sqlite3_context object and the operation
  85261. ** changed to this OP_Function opcode. In this way, the initialization of
  85262. ** the sqlite3_context object occurs only once, rather than once for each
  85263. ** evaluation of the function.
  85264. **
  85265. ** See also: Function0, AggStep, AggFinal
  85266. */
  85267. case OP_PureFunc0: /* group */
  85268. case OP_Function0: { /* group */
  85269. int n;
  85270. sqlite3_context *pCtx;
  85271. assert( pOp->p4type==P4_FUNCDEF );
  85272. n = pOp->p5;
  85273. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  85274. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  85275. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  85276. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  85277. if( pCtx==0 ) goto no_mem;
  85278. pCtx->pOut = 0;
  85279. pCtx->pFunc = pOp->p4.pFunc;
  85280. pCtx->iOp = (int)(pOp - aOp);
  85281. pCtx->pVdbe = p;
  85282. pCtx->isError = 0;
  85283. pCtx->argc = n;
  85284. pOp->p4type = P4_FUNCCTX;
  85285. pOp->p4.pCtx = pCtx;
  85286. assert( OP_PureFunc == OP_PureFunc0+2 );
  85287. assert( OP_Function == OP_Function0+2 );
  85288. pOp->opcode += 2;
  85289. /* Fall through into OP_Function */
  85290. }
  85291. case OP_PureFunc: /* group */
  85292. case OP_Function: { /* group */
  85293. int i;
  85294. sqlite3_context *pCtx;
  85295. assert( pOp->p4type==P4_FUNCCTX );
  85296. pCtx = pOp->p4.pCtx;
  85297. /* If this function is inside of a trigger, the register array in aMem[]
  85298. ** might change from one evaluation to the next. The next block of code
  85299. ** checks to see if the register array has changed, and if so it
  85300. ** reinitializes the relavant parts of the sqlite3_context object */
  85301. pOut = &aMem[pOp->p3];
  85302. if( pCtx->pOut != pOut ){
  85303. pCtx->pOut = pOut;
  85304. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  85305. }
  85306. memAboutToChange(p, pOut);
  85307. #ifdef SQLITE_DEBUG
  85308. for(i=0; i<pCtx->argc; i++){
  85309. assert( memIsValid(pCtx->argv[i]) );
  85310. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  85311. }
  85312. #endif
  85313. MemSetTypeFlag(pOut, MEM_Null);
  85314. assert( pCtx->isError==0 );
  85315. (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
  85316. /* If the function returned an error, throw an exception */
  85317. if( pCtx->isError ){
  85318. if( pCtx->isError>0 ){
  85319. sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
  85320. rc = pCtx->isError;
  85321. }
  85322. sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
  85323. pCtx->isError = 0;
  85324. if( rc ) goto abort_due_to_error;
  85325. }
  85326. /* Copy the result of the function into register P3 */
  85327. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  85328. sqlite3VdbeChangeEncoding(pOut, encoding);
  85329. if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
  85330. }
  85331. REGISTER_TRACE(pOp->p3, pOut);
  85332. UPDATE_MAX_BLOBSIZE(pOut);
  85333. break;
  85334. }
  85335. /* Opcode: Trace P1 P2 * P4 *
  85336. **
  85337. ** Write P4 on the statement trace output if statement tracing is
  85338. ** enabled.
  85339. **
  85340. ** Operand P1 must be 0x7fffffff and P2 must positive.
  85341. */
  85342. /* Opcode: Init P1 P2 P3 P4 *
  85343. ** Synopsis: Start at P2
  85344. **
  85345. ** Programs contain a single instance of this opcode as the very first
  85346. ** opcode.
  85347. **
  85348. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  85349. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  85350. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  85351. **
  85352. ** If P2 is not zero, jump to instruction P2.
  85353. **
  85354. ** Increment the value of P1 so that OP_Once opcodes will jump the
  85355. ** first time they are evaluated for this run.
  85356. **
  85357. ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
  85358. ** error is encountered.
  85359. */
  85360. case OP_Trace:
  85361. case OP_Init: { /* jump */
  85362. int i;
  85363. #ifndef SQLITE_OMIT_TRACE
  85364. char *zTrace;
  85365. #endif
  85366. /* If the P4 argument is not NULL, then it must be an SQL comment string.
  85367. ** The "--" string is broken up to prevent false-positives with srcck1.c.
  85368. **
  85369. ** This assert() provides evidence for:
  85370. ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
  85371. ** would have been returned by the legacy sqlite3_trace() interface by
  85372. ** using the X argument when X begins with "--" and invoking
  85373. ** sqlite3_expanded_sql(P) otherwise.
  85374. */
  85375. assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
  85376. /* OP_Init is always instruction 0 */
  85377. assert( pOp==p->aOp || pOp->opcode==OP_Trace );
  85378. #ifndef SQLITE_OMIT_TRACE
  85379. if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
  85380. && !p->doingRerun
  85381. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  85382. ){
  85383. #ifndef SQLITE_OMIT_DEPRECATED
  85384. if( db->mTrace & SQLITE_TRACE_LEGACY ){
  85385. void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
  85386. char *z = sqlite3VdbeExpandSql(p, zTrace);
  85387. x(db->pTraceArg, z);
  85388. sqlite3_free(z);
  85389. }else
  85390. #endif
  85391. if( db->nVdbeExec>1 ){
  85392. char *z = sqlite3MPrintf(db, "-- %s", zTrace);
  85393. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
  85394. sqlite3DbFree(db, z);
  85395. }else{
  85396. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
  85397. }
  85398. }
  85399. #ifdef SQLITE_USE_FCNTL_TRACE
  85400. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  85401. if( zTrace ){
  85402. int j;
  85403. for(j=0; j<db->nDb; j++){
  85404. if( DbMaskTest(p->btreeMask, j)==0 ) continue;
  85405. sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
  85406. }
  85407. }
  85408. #endif /* SQLITE_USE_FCNTL_TRACE */
  85409. #ifdef SQLITE_DEBUG
  85410. if( (db->flags & SQLITE_SqlTrace)!=0
  85411. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  85412. ){
  85413. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  85414. }
  85415. #endif /* SQLITE_DEBUG */
  85416. #endif /* SQLITE_OMIT_TRACE */
  85417. assert( pOp->p2>0 );
  85418. if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
  85419. if( pOp->opcode==OP_Trace ) break;
  85420. for(i=1; i<p->nOp; i++){
  85421. if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
  85422. }
  85423. pOp->p1 = 0;
  85424. }
  85425. pOp->p1++;
  85426. p->aCounter[SQLITE_STMTSTATUS_RUN]++;
  85427. goto jump_to_p2;
  85428. }
  85429. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  85430. /* Opcode: CursorHint P1 * * P4 *
  85431. **
  85432. ** Provide a hint to cursor P1 that it only needs to return rows that
  85433. ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
  85434. ** to values currently held in registers. TK_COLUMN terms in the P4
  85435. ** expression refer to columns in the b-tree to which cursor P1 is pointing.
  85436. */
  85437. case OP_CursorHint: {
  85438. VdbeCursor *pC;
  85439. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  85440. assert( pOp->p4type==P4_EXPR );
  85441. pC = p->apCsr[pOp->p1];
  85442. if( pC ){
  85443. assert( pC->eCurType==CURTYPE_BTREE );
  85444. sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
  85445. pOp->p4.pExpr, aMem);
  85446. }
  85447. break;
  85448. }
  85449. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  85450. #ifdef SQLITE_DEBUG
  85451. /* Opcode: Abortable * * * * *
  85452. **
  85453. ** Verify that an Abort can happen. Assert if an Abort at this point
  85454. ** might cause database corruption. This opcode only appears in debugging
  85455. ** builds.
  85456. **
  85457. ** An Abort is safe if either there have been no writes, or if there is
  85458. ** an active statement journal.
  85459. */
  85460. case OP_Abortable: {
  85461. sqlite3VdbeAssertAbortable(p);
  85462. break;
  85463. }
  85464. #endif
  85465. /* Opcode: Noop * * * * *
  85466. **
  85467. ** Do nothing. This instruction is often useful as a jump
  85468. ** destination.
  85469. */
  85470. /*
  85471. ** The magic Explain opcode are only inserted when explain==2 (which
  85472. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  85473. ** This opcode records information from the optimizer. It is the
  85474. ** the same as a no-op. This opcodesnever appears in a real VM program.
  85475. */
  85476. default: { /* This is really OP_Noop, OP_Explain */
  85477. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  85478. break;
  85479. }
  85480. /*****************************************************************************
  85481. ** The cases of the switch statement above this line should all be indented
  85482. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  85483. ** readability. From this point on down, the normal indentation rules are
  85484. ** restored.
  85485. *****************************************************************************/
  85486. }
  85487. #ifdef VDBE_PROFILE
  85488. {
  85489. u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  85490. if( endTime>start ) pOrigOp->cycles += endTime - start;
  85491. pOrigOp->cnt++;
  85492. }
  85493. #endif
  85494. /* The following code adds nothing to the actual functionality
  85495. ** of the program. It is only here for testing and debugging.
  85496. ** On the other hand, it does burn CPU cycles every time through
  85497. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  85498. */
  85499. #ifndef NDEBUG
  85500. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  85501. #ifdef SQLITE_DEBUG
  85502. if( db->flags & SQLITE_VdbeTrace ){
  85503. u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
  85504. if( rc!=0 ) printf("rc=%d\n",rc);
  85505. if( opProperty & (OPFLG_OUT2) ){
  85506. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  85507. }
  85508. if( opProperty & OPFLG_OUT3 ){
  85509. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  85510. }
  85511. }
  85512. #endif /* SQLITE_DEBUG */
  85513. #endif /* NDEBUG */
  85514. } /* The end of the for(;;) loop the loops through opcodes */
  85515. /* If we reach this point, it means that execution is finished with
  85516. ** an error of some kind.
  85517. */
  85518. abort_due_to_error:
  85519. if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
  85520. assert( rc );
  85521. if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
  85522. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  85523. }
  85524. p->rc = rc;
  85525. sqlite3SystemError(db, rc);
  85526. testcase( sqlite3GlobalConfig.xLog!=0 );
  85527. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  85528. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  85529. sqlite3VdbeHalt(p);
  85530. if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
  85531. rc = SQLITE_ERROR;
  85532. if( resetSchemaOnFault>0 ){
  85533. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  85534. }
  85535. /* This is the only way out of this procedure. We have to
  85536. ** release the mutexes on btrees that were acquired at the
  85537. ** top. */
  85538. vdbe_return:
  85539. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  85540. while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
  85541. nProgressLimit += db->nProgressOps;
  85542. if( db->xProgress(db->pProgressArg) ){
  85543. nProgressLimit = 0xffffffff;
  85544. rc = SQLITE_INTERRUPT;
  85545. goto abort_due_to_error;
  85546. }
  85547. }
  85548. #endif
  85549. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  85550. sqlite3VdbeLeave(p);
  85551. assert( rc!=SQLITE_OK || nExtraDelete==0
  85552. || sqlite3_strlike("DELETE%",p->zSql,0)!=0
  85553. );
  85554. return rc;
  85555. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  85556. ** is encountered.
  85557. */
  85558. too_big:
  85559. sqlite3VdbeError(p, "string or blob too big");
  85560. rc = SQLITE_TOOBIG;
  85561. goto abort_due_to_error;
  85562. /* Jump to here if a malloc() fails.
  85563. */
  85564. no_mem:
  85565. sqlite3OomFault(db);
  85566. sqlite3VdbeError(p, "out of memory");
  85567. rc = SQLITE_NOMEM_BKPT;
  85568. goto abort_due_to_error;
  85569. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  85570. ** flag.
  85571. */
  85572. abort_due_to_interrupt:
  85573. assert( db->u1.isInterrupted );
  85574. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  85575. p->rc = rc;
  85576. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  85577. goto abort_due_to_error;
  85578. }
  85579. /************** End of vdbe.c ************************************************/
  85580. /************** Begin file vdbeblob.c ****************************************/
  85581. /*
  85582. ** 2007 May 1
  85583. **
  85584. ** The author disclaims copyright to this source code. In place of
  85585. ** a legal notice, here is a blessing:
  85586. **
  85587. ** May you do good and not evil.
  85588. ** May you find forgiveness for yourself and forgive others.
  85589. ** May you share freely, never taking more than you give.
  85590. **
  85591. *************************************************************************
  85592. **
  85593. ** This file contains code used to implement incremental BLOB I/O.
  85594. */
  85595. /* #include "sqliteInt.h" */
  85596. /* #include "vdbeInt.h" */
  85597. #ifndef SQLITE_OMIT_INCRBLOB
  85598. /*
  85599. ** Valid sqlite3_blob* handles point to Incrblob structures.
  85600. */
  85601. typedef struct Incrblob Incrblob;
  85602. struct Incrblob {
  85603. int nByte; /* Size of open blob, in bytes */
  85604. int iOffset; /* Byte offset of blob in cursor data */
  85605. u16 iCol; /* Table column this handle is open on */
  85606. BtCursor *pCsr; /* Cursor pointing at blob row */
  85607. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  85608. sqlite3 *db; /* The associated database */
  85609. char *zDb; /* Database name */
  85610. Table *pTab; /* Table object */
  85611. };
  85612. /*
  85613. ** This function is used by both blob_open() and blob_reopen(). It seeks
  85614. ** the b-tree cursor associated with blob handle p to point to row iRow.
  85615. ** If successful, SQLITE_OK is returned and subsequent calls to
  85616. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  85617. **
  85618. ** If an error occurs, or if the specified row does not exist or does not
  85619. ** contain a value of type TEXT or BLOB in the column nominated when the
  85620. ** blob handle was opened, then an error code is returned and *pzErr may
  85621. ** be set to point to a buffer containing an error message. It is the
  85622. ** responsibility of the caller to free the error message buffer using
  85623. ** sqlite3DbFree().
  85624. **
  85625. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  85626. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  85627. ** immediately return SQLITE_ABORT.
  85628. */
  85629. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  85630. int rc; /* Error code */
  85631. char *zErr = 0; /* Error message */
  85632. Vdbe *v = (Vdbe *)p->pStmt;
  85633. /* Set the value of register r[1] in the SQL statement to integer iRow.
  85634. ** This is done directly as a performance optimization
  85635. */
  85636. v->aMem[1].flags = MEM_Int;
  85637. v->aMem[1].u.i = iRow;
  85638. /* If the statement has been run before (and is paused at the OP_ResultRow)
  85639. ** then back it up to the point where it does the OP_NotExists. This could
  85640. ** have been down with an extra OP_Goto, but simply setting the program
  85641. ** counter is faster. */
  85642. if( v->pc>4 ){
  85643. v->pc = 4;
  85644. assert( v->aOp[v->pc].opcode==OP_NotExists );
  85645. rc = sqlite3VdbeExec(v);
  85646. }else{
  85647. rc = sqlite3_step(p->pStmt);
  85648. }
  85649. if( rc==SQLITE_ROW ){
  85650. VdbeCursor *pC = v->apCsr[0];
  85651. u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
  85652. testcase( pC->nHdrParsed==p->iCol );
  85653. testcase( pC->nHdrParsed==p->iCol+1 );
  85654. if( type<12 ){
  85655. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  85656. type==0?"null": type==7?"real": "integer"
  85657. );
  85658. rc = SQLITE_ERROR;
  85659. sqlite3_finalize(p->pStmt);
  85660. p->pStmt = 0;
  85661. }else{
  85662. p->iOffset = pC->aType[p->iCol + pC->nField];
  85663. p->nByte = sqlite3VdbeSerialTypeLen(type);
  85664. p->pCsr = pC->uc.pCursor;
  85665. sqlite3BtreeIncrblobCursor(p->pCsr);
  85666. }
  85667. }
  85668. if( rc==SQLITE_ROW ){
  85669. rc = SQLITE_OK;
  85670. }else if( p->pStmt ){
  85671. rc = sqlite3_finalize(p->pStmt);
  85672. p->pStmt = 0;
  85673. if( rc==SQLITE_OK ){
  85674. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  85675. rc = SQLITE_ERROR;
  85676. }else{
  85677. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  85678. }
  85679. }
  85680. assert( rc!=SQLITE_OK || zErr==0 );
  85681. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  85682. *pzErr = zErr;
  85683. return rc;
  85684. }
  85685. /*
  85686. ** Open a blob handle.
  85687. */
  85688. SQLITE_API int sqlite3_blob_open(
  85689. sqlite3* db, /* The database connection */
  85690. const char *zDb, /* The attached database containing the blob */
  85691. const char *zTable, /* The table containing the blob */
  85692. const char *zColumn, /* The column containing the blob */
  85693. sqlite_int64 iRow, /* The row containing the glob */
  85694. int wrFlag, /* True -> read/write access, false -> read-only */
  85695. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  85696. ){
  85697. int nAttempt = 0;
  85698. int iCol; /* Index of zColumn in row-record */
  85699. int rc = SQLITE_OK;
  85700. char *zErr = 0;
  85701. Table *pTab;
  85702. Incrblob *pBlob = 0;
  85703. Parse sParse;
  85704. #ifdef SQLITE_ENABLE_API_ARMOR
  85705. if( ppBlob==0 ){
  85706. return SQLITE_MISUSE_BKPT;
  85707. }
  85708. #endif
  85709. *ppBlob = 0;
  85710. #ifdef SQLITE_ENABLE_API_ARMOR
  85711. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  85712. return SQLITE_MISUSE_BKPT;
  85713. }
  85714. #endif
  85715. wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
  85716. sqlite3_mutex_enter(db->mutex);
  85717. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  85718. do {
  85719. memset(&sParse, 0, sizeof(Parse));
  85720. if( !pBlob ) goto blob_open_out;
  85721. sParse.db = db;
  85722. sqlite3DbFree(db, zErr);
  85723. zErr = 0;
  85724. sqlite3BtreeEnterAll(db);
  85725. pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
  85726. if( pTab && IsVirtual(pTab) ){
  85727. pTab = 0;
  85728. sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
  85729. }
  85730. if( pTab && !HasRowid(pTab) ){
  85731. pTab = 0;
  85732. sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
  85733. }
  85734. #ifndef SQLITE_OMIT_VIEW
  85735. if( pTab && pTab->pSelect ){
  85736. pTab = 0;
  85737. sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
  85738. }
  85739. #endif
  85740. if( !pTab ){
  85741. if( sParse.zErrMsg ){
  85742. sqlite3DbFree(db, zErr);
  85743. zErr = sParse.zErrMsg;
  85744. sParse.zErrMsg = 0;
  85745. }
  85746. rc = SQLITE_ERROR;
  85747. sqlite3BtreeLeaveAll(db);
  85748. goto blob_open_out;
  85749. }
  85750. pBlob->pTab = pTab;
  85751. pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
  85752. /* Now search pTab for the exact column. */
  85753. for(iCol=0; iCol<pTab->nCol; iCol++) {
  85754. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  85755. break;
  85756. }
  85757. }
  85758. if( iCol==pTab->nCol ){
  85759. sqlite3DbFree(db, zErr);
  85760. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  85761. rc = SQLITE_ERROR;
  85762. sqlite3BtreeLeaveAll(db);
  85763. goto blob_open_out;
  85764. }
  85765. /* If the value is being opened for writing, check that the
  85766. ** column is not indexed, and that it is not part of a foreign key.
  85767. */
  85768. if( wrFlag ){
  85769. const char *zFault = 0;
  85770. Index *pIdx;
  85771. #ifndef SQLITE_OMIT_FOREIGN_KEY
  85772. if( db->flags&SQLITE_ForeignKeys ){
  85773. /* Check that the column is not part of an FK child key definition. It
  85774. ** is not necessary to check if it is part of a parent key, as parent
  85775. ** key columns must be indexed. The check below will pick up this
  85776. ** case. */
  85777. FKey *pFKey;
  85778. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  85779. int j;
  85780. for(j=0; j<pFKey->nCol; j++){
  85781. if( pFKey->aCol[j].iFrom==iCol ){
  85782. zFault = "foreign key";
  85783. }
  85784. }
  85785. }
  85786. }
  85787. #endif
  85788. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  85789. int j;
  85790. for(j=0; j<pIdx->nKeyCol; j++){
  85791. /* FIXME: Be smarter about indexes that use expressions */
  85792. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  85793. zFault = "indexed";
  85794. }
  85795. }
  85796. }
  85797. if( zFault ){
  85798. sqlite3DbFree(db, zErr);
  85799. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  85800. rc = SQLITE_ERROR;
  85801. sqlite3BtreeLeaveAll(db);
  85802. goto blob_open_out;
  85803. }
  85804. }
  85805. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
  85806. assert( pBlob->pStmt || db->mallocFailed );
  85807. if( pBlob->pStmt ){
  85808. /* This VDBE program seeks a btree cursor to the identified
  85809. ** db/table/row entry. The reason for using a vdbe program instead
  85810. ** of writing code to use the b-tree layer directly is that the
  85811. ** vdbe program will take advantage of the various transaction,
  85812. ** locking and error handling infrastructure built into the vdbe.
  85813. **
  85814. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  85815. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  85816. ** uses it to implement the blob_read(), blob_write() and
  85817. ** blob_bytes() functions.
  85818. **
  85819. ** The sqlite3_blob_close() function finalizes the vdbe program,
  85820. ** which closes the b-tree cursor and (possibly) commits the
  85821. ** transaction.
  85822. */
  85823. static const int iLn = VDBE_OFFSET_LINENO(2);
  85824. static const VdbeOpList openBlob[] = {
  85825. {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
  85826. {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
  85827. /* blobSeekToRow() will initialize r[1] to the desired rowid */
  85828. {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
  85829. {OP_Column, 0, 0, 1}, /* 3 */
  85830. {OP_ResultRow, 1, 0, 0}, /* 4 */
  85831. {OP_Halt, 0, 0, 0}, /* 5 */
  85832. };
  85833. Vdbe *v = (Vdbe *)pBlob->pStmt;
  85834. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85835. VdbeOp *aOp;
  85836. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
  85837. pTab->pSchema->schema_cookie,
  85838. pTab->pSchema->iGeneration);
  85839. sqlite3VdbeChangeP5(v, 1);
  85840. assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
  85841. aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  85842. /* Make sure a mutex is held on the table to be accessed */
  85843. sqlite3VdbeUsesBtree(v, iDb);
  85844. if( db->mallocFailed==0 ){
  85845. assert( aOp!=0 );
  85846. /* Configure the OP_TableLock instruction */
  85847. #ifdef SQLITE_OMIT_SHARED_CACHE
  85848. aOp[0].opcode = OP_Noop;
  85849. #else
  85850. aOp[0].p1 = iDb;
  85851. aOp[0].p2 = pTab->tnum;
  85852. aOp[0].p3 = wrFlag;
  85853. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  85854. }
  85855. if( db->mallocFailed==0 ){
  85856. #endif
  85857. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  85858. ** parameter of the other to pTab->tnum. */
  85859. if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
  85860. aOp[1].p2 = pTab->tnum;
  85861. aOp[1].p3 = iDb;
  85862. /* Configure the number of columns. Configure the cursor to
  85863. ** think that the table has one more column than it really
  85864. ** does. An OP_Column to retrieve this imaginary column will
  85865. ** always return an SQL NULL. This is useful because it means
  85866. ** we can invoke OP_Column to fill in the vdbe cursors type
  85867. ** and offset cache without causing any IO.
  85868. */
  85869. aOp[1].p4type = P4_INT32;
  85870. aOp[1].p4.i = pTab->nCol+1;
  85871. aOp[3].p2 = pTab->nCol;
  85872. sParse.nVar = 0;
  85873. sParse.nMem = 1;
  85874. sParse.nTab = 1;
  85875. sqlite3VdbeMakeReady(v, &sParse);
  85876. }
  85877. }
  85878. pBlob->iCol = iCol;
  85879. pBlob->db = db;
  85880. sqlite3BtreeLeaveAll(db);
  85881. if( db->mallocFailed ){
  85882. goto blob_open_out;
  85883. }
  85884. rc = blobSeekToRow(pBlob, iRow, &zErr);
  85885. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  85886. blob_open_out:
  85887. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  85888. *ppBlob = (sqlite3_blob *)pBlob;
  85889. }else{
  85890. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  85891. sqlite3DbFree(db, pBlob);
  85892. }
  85893. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  85894. sqlite3DbFree(db, zErr);
  85895. sqlite3ParserReset(&sParse);
  85896. rc = sqlite3ApiExit(db, rc);
  85897. sqlite3_mutex_leave(db->mutex);
  85898. return rc;
  85899. }
  85900. /*
  85901. ** Close a blob handle that was previously created using
  85902. ** sqlite3_blob_open().
  85903. */
  85904. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  85905. Incrblob *p = (Incrblob *)pBlob;
  85906. int rc;
  85907. sqlite3 *db;
  85908. if( p ){
  85909. db = p->db;
  85910. sqlite3_mutex_enter(db->mutex);
  85911. rc = sqlite3_finalize(p->pStmt);
  85912. sqlite3DbFree(db, p);
  85913. sqlite3_mutex_leave(db->mutex);
  85914. }else{
  85915. rc = SQLITE_OK;
  85916. }
  85917. return rc;
  85918. }
  85919. /*
  85920. ** Perform a read or write operation on a blob
  85921. */
  85922. static int blobReadWrite(
  85923. sqlite3_blob *pBlob,
  85924. void *z,
  85925. int n,
  85926. int iOffset,
  85927. int (*xCall)(BtCursor*, u32, u32, void*)
  85928. ){
  85929. int rc;
  85930. Incrblob *p = (Incrblob *)pBlob;
  85931. Vdbe *v;
  85932. sqlite3 *db;
  85933. if( p==0 ) return SQLITE_MISUSE_BKPT;
  85934. db = p->db;
  85935. sqlite3_mutex_enter(db->mutex);
  85936. v = (Vdbe*)p->pStmt;
  85937. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  85938. /* Request is out of range. Return a transient error. */
  85939. rc = SQLITE_ERROR;
  85940. }else if( v==0 ){
  85941. /* If there is no statement handle, then the blob-handle has
  85942. ** already been invalidated. Return SQLITE_ABORT in this case.
  85943. */
  85944. rc = SQLITE_ABORT;
  85945. }else{
  85946. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  85947. ** returned, clean-up the statement handle.
  85948. */
  85949. assert( db == v->db );
  85950. sqlite3BtreeEnterCursor(p->pCsr);
  85951. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  85952. if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
  85953. /* If a pre-update hook is registered and this is a write cursor,
  85954. ** invoke it here.
  85955. **
  85956. ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
  85957. ** operation should really be an SQLITE_UPDATE. This is probably
  85958. ** incorrect, but is convenient because at this point the new.* values
  85959. ** are not easily obtainable. And for the sessions module, an
  85960. ** SQLITE_UPDATE where the PK columns do not change is handled in the
  85961. ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
  85962. ** slightly more efficient). Since you cannot write to a PK column
  85963. ** using the incremental-blob API, this works. For the sessions module
  85964. ** anyhow.
  85965. */
  85966. sqlite3_int64 iKey;
  85967. iKey = sqlite3BtreeIntegerKey(p->pCsr);
  85968. sqlite3VdbePreUpdateHook(
  85969. v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
  85970. );
  85971. }
  85972. #endif
  85973. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  85974. sqlite3BtreeLeaveCursor(p->pCsr);
  85975. if( rc==SQLITE_ABORT ){
  85976. sqlite3VdbeFinalize(v);
  85977. p->pStmt = 0;
  85978. }else{
  85979. v->rc = rc;
  85980. }
  85981. }
  85982. sqlite3Error(db, rc);
  85983. rc = sqlite3ApiExit(db, rc);
  85984. sqlite3_mutex_leave(db->mutex);
  85985. return rc;
  85986. }
  85987. /*
  85988. ** Read data from a blob handle.
  85989. */
  85990. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  85991. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
  85992. }
  85993. /*
  85994. ** Write data to a blob handle.
  85995. */
  85996. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  85997. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  85998. }
  85999. /*
  86000. ** Query a blob handle for the size of the data.
  86001. **
  86002. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  86003. ** so no mutex is required for access.
  86004. */
  86005. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  86006. Incrblob *p = (Incrblob *)pBlob;
  86007. return (p && p->pStmt) ? p->nByte : 0;
  86008. }
  86009. /*
  86010. ** Move an existing blob handle to point to a different row of the same
  86011. ** database table.
  86012. **
  86013. ** If an error occurs, or if the specified row does not exist or does not
  86014. ** contain a blob or text value, then an error code is returned and the
  86015. ** database handle error code and message set. If this happens, then all
  86016. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  86017. ** immediately return SQLITE_ABORT.
  86018. */
  86019. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  86020. int rc;
  86021. Incrblob *p = (Incrblob *)pBlob;
  86022. sqlite3 *db;
  86023. if( p==0 ) return SQLITE_MISUSE_BKPT;
  86024. db = p->db;
  86025. sqlite3_mutex_enter(db->mutex);
  86026. if( p->pStmt==0 ){
  86027. /* If there is no statement handle, then the blob-handle has
  86028. ** already been invalidated. Return SQLITE_ABORT in this case.
  86029. */
  86030. rc = SQLITE_ABORT;
  86031. }else{
  86032. char *zErr;
  86033. rc = blobSeekToRow(p, iRow, &zErr);
  86034. if( rc!=SQLITE_OK ){
  86035. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  86036. sqlite3DbFree(db, zErr);
  86037. }
  86038. assert( rc!=SQLITE_SCHEMA );
  86039. }
  86040. rc = sqlite3ApiExit(db, rc);
  86041. assert( rc==SQLITE_OK || p->pStmt==0 );
  86042. sqlite3_mutex_leave(db->mutex);
  86043. return rc;
  86044. }
  86045. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  86046. /************** End of vdbeblob.c ********************************************/
  86047. /************** Begin file vdbesort.c ****************************************/
  86048. /*
  86049. ** 2011-07-09
  86050. **
  86051. ** The author disclaims copyright to this source code. In place of
  86052. ** a legal notice, here is a blessing:
  86053. **
  86054. ** May you do good and not evil.
  86055. ** May you find forgiveness for yourself and forgive others.
  86056. ** May you share freely, never taking more than you give.
  86057. **
  86058. *************************************************************************
  86059. ** This file contains code for the VdbeSorter object, used in concert with
  86060. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  86061. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  86062. ** using indexes and without LIMIT clauses.
  86063. **
  86064. ** The VdbeSorter object implements a multi-threaded external merge sort
  86065. ** algorithm that is efficient even if the number of elements being sorted
  86066. ** exceeds the available memory.
  86067. **
  86068. ** Here is the (internal, non-API) interface between this module and the
  86069. ** rest of the SQLite system:
  86070. **
  86071. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  86072. **
  86073. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  86074. ** object. The row is a binary blob in the
  86075. ** OP_MakeRecord format that contains both
  86076. ** the ORDER BY key columns and result columns
  86077. ** in the case of a SELECT w/ ORDER BY, or
  86078. ** the complete record for an index entry
  86079. ** in the case of a CREATE INDEX.
  86080. **
  86081. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  86082. ** Position the read cursor on the
  86083. ** first sorted element.
  86084. **
  86085. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  86086. ** element.
  86087. **
  86088. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  86089. ** row currently under the read cursor.
  86090. **
  86091. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  86092. ** currently under the read cursor against
  86093. ** another binary blob X and report if
  86094. ** X is strictly less than the read cursor.
  86095. ** Used to enforce uniqueness in a
  86096. ** CREATE UNIQUE INDEX statement.
  86097. **
  86098. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  86099. ** all resources.
  86100. **
  86101. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  86102. ** is like Close() followed by Init() only
  86103. ** much faster.
  86104. **
  86105. ** The interfaces above must be called in a particular order. Write() can
  86106. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  86107. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  86108. **
  86109. ** Init()
  86110. ** for each record: Write()
  86111. ** Rewind()
  86112. ** Rowkey()/Compare()
  86113. ** Next()
  86114. ** Close()
  86115. **
  86116. ** Algorithm:
  86117. **
  86118. ** Records passed to the sorter via calls to Write() are initially held
  86119. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  86120. ** a threshold, when Rewind() is called the set of records is sorted using
  86121. ** an in-memory merge sort. In this case, no temporary files are required
  86122. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  86123. ** directly from main memory.
  86124. **
  86125. ** If the amount of space used to store records in main memory exceeds the
  86126. ** threshold, then the set of records currently in memory are sorted and
  86127. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  86128. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  86129. ** of PMAs may be created by merging existing PMAs together - for example
  86130. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  86131. **
  86132. ** The threshold for the amount of main memory to use before flushing
  86133. ** records to a PMA is roughly the same as the limit configured for the
  86134. ** page-cache of the main database. Specifically, the threshold is set to
  86135. ** the value returned by "PRAGMA main.page_size" multipled by
  86136. ** that returned by "PRAGMA main.cache_size", in bytes.
  86137. **
  86138. ** If the sorter is running in single-threaded mode, then all PMAs generated
  86139. ** are appended to a single temporary file. Or, if the sorter is running in
  86140. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  86141. ** N is the configured number of worker threads. In this case, instead of
  86142. ** sorting the records and writing the PMA to a temporary file itself, the
  86143. ** calling thread usually launches a worker thread to do so. Except, if
  86144. ** there are already N worker threads running, the main thread does the work
  86145. ** itself.
  86146. **
  86147. ** The sorter is running in multi-threaded mode if (a) the library was built
  86148. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  86149. ** than zero, and (b) worker threads have been enabled at runtime by calling
  86150. ** "PRAGMA threads=N" with some value of N greater than 0.
  86151. **
  86152. ** When Rewind() is called, any data remaining in memory is flushed to a
  86153. ** final PMA. So at this point the data is stored in some number of sorted
  86154. ** PMAs within temporary files on disk.
  86155. **
  86156. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  86157. ** sorter is running in single-threaded mode, then these PMAs are merged
  86158. ** incrementally as keys are retreived from the sorter by the VDBE. The
  86159. ** MergeEngine object, described in further detail below, performs this
  86160. ** merge.
  86161. **
  86162. ** Or, if running in multi-threaded mode, then a background thread is
  86163. ** launched to merge the existing PMAs. Once the background thread has
  86164. ** merged T bytes of data into a single sorted PMA, the main thread
  86165. ** begins reading keys from that PMA while the background thread proceeds
  86166. ** with merging the next T bytes of data. And so on.
  86167. **
  86168. ** Parameter T is set to half the value of the memory threshold used
  86169. ** by Write() above to determine when to create a new PMA.
  86170. **
  86171. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  86172. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  86173. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  86174. ** disk are merged together. Then T bytes of data from the second set, and
  86175. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  86176. ** PMAs at a time. This done is to improve locality.
  86177. **
  86178. ** If running in multi-threaded mode and there are more than
  86179. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  86180. ** than one background thread may be created. Specifically, there may be
  86181. ** one background thread for each temporary file on disk, and one background
  86182. ** thread to merge the output of each of the others to a single PMA for
  86183. ** the main thread to read from.
  86184. */
  86185. /* #include "sqliteInt.h" */
  86186. /* #include "vdbeInt.h" */
  86187. /*
  86188. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  86189. ** messages to stderr that may be helpful in understanding the performance
  86190. ** characteristics of the sorter in multi-threaded mode.
  86191. */
  86192. #if 0
  86193. # define SQLITE_DEBUG_SORTER_THREADS 1
  86194. #endif
  86195. /*
  86196. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  86197. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  86198. ** overflows. 512MiB.
  86199. */
  86200. #define SQLITE_MAX_PMASZ (1<<29)
  86201. /*
  86202. ** Private objects used by the sorter
  86203. */
  86204. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  86205. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  86206. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  86207. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  86208. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  86209. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  86210. typedef struct SorterList SorterList; /* In-memory list of records */
  86211. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  86212. /*
  86213. ** A container for a temp file handle and the current amount of data
  86214. ** stored in the file.
  86215. */
  86216. struct SorterFile {
  86217. sqlite3_file *pFd; /* File handle */
  86218. i64 iEof; /* Bytes of data stored in pFd */
  86219. };
  86220. /*
  86221. ** An in-memory list of objects to be sorted.
  86222. **
  86223. ** If aMemory==0 then each object is allocated separately and the objects
  86224. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  86225. ** are stored in the aMemory[] bulk memory, one right after the other, and
  86226. ** are connected using SorterRecord.u.iNext.
  86227. */
  86228. struct SorterList {
  86229. SorterRecord *pList; /* Linked list of records */
  86230. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  86231. int szPMA; /* Size of pList as PMA in bytes */
  86232. };
  86233. /*
  86234. ** The MergeEngine object is used to combine two or more smaller PMAs into
  86235. ** one big PMA using a merge operation. Separate PMAs all need to be
  86236. ** combined into one big PMA in order to be able to step through the sorted
  86237. ** records in order.
  86238. **
  86239. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  86240. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  86241. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  86242. ** For the purposes of the paragraphs below, we assume that the array is
  86243. ** actually N elements in size, where N is the smallest power of 2 greater
  86244. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  86245. ** are treated as if they are empty (always at EOF).
  86246. **
  86247. ** The aTree[] array is also N elements in size. The value of N is stored in
  86248. ** the MergeEngine.nTree variable.
  86249. **
  86250. ** The final (N/2) elements of aTree[] contain the results of comparing
  86251. ** pairs of PMA keys together. Element i contains the result of
  86252. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  86253. ** aTree element is set to the index of it.
  86254. **
  86255. ** For the purposes of this comparison, EOF is considered greater than any
  86256. ** other key value. If the keys are equal (only possible with two EOF
  86257. ** values), it doesn't matter which index is stored.
  86258. **
  86259. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  86260. ** above contains the index of the smallest of each block of 4 PmaReaders
  86261. ** And so on. So that aTree[1] contains the index of the PmaReader that
  86262. ** currently points to the smallest key value. aTree[0] is unused.
  86263. **
  86264. ** Example:
  86265. **
  86266. ** aReadr[0] -> Banana
  86267. ** aReadr[1] -> Feijoa
  86268. ** aReadr[2] -> Elderberry
  86269. ** aReadr[3] -> Currant
  86270. ** aReadr[4] -> Grapefruit
  86271. ** aReadr[5] -> Apple
  86272. ** aReadr[6] -> Durian
  86273. ** aReadr[7] -> EOF
  86274. **
  86275. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  86276. **
  86277. ** The current element is "Apple" (the value of the key indicated by
  86278. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  86279. ** be advanced to the next key in its segment. Say the next key is
  86280. ** "Eggplant":
  86281. **
  86282. ** aReadr[5] -> Eggplant
  86283. **
  86284. ** The contents of aTree[] are updated first by comparing the new PmaReader
  86285. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  86286. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  86287. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  86288. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  86289. ** so the value written into element 1 of the array is 0. As follows:
  86290. **
  86291. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  86292. **
  86293. ** In other words, each time we advance to the next sorter element, log2(N)
  86294. ** key comparison operations are required, where N is the number of segments
  86295. ** being merged (rounded up to the next power of 2).
  86296. */
  86297. struct MergeEngine {
  86298. int nTree; /* Used size of aTree/aReadr (power of 2) */
  86299. SortSubtask *pTask; /* Used by this thread only */
  86300. int *aTree; /* Current state of incremental merge */
  86301. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  86302. };
  86303. /*
  86304. ** This object represents a single thread of control in a sort operation.
  86305. ** Exactly VdbeSorter.nTask instances of this object are allocated
  86306. ** as part of each VdbeSorter object. Instances are never allocated any
  86307. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  86308. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  86309. ** single-threaded operation, there is exactly one instance of this object
  86310. ** and for multi-threaded operation there are two or more instances.
  86311. **
  86312. ** Essentially, this structure contains all those fields of the VdbeSorter
  86313. ** structure for which each thread requires a separate instance. For example,
  86314. ** each thread requries its own UnpackedRecord object to unpack records in
  86315. ** as part of comparison operations.
  86316. **
  86317. ** Before a background thread is launched, variable bDone is set to 0. Then,
  86318. ** right before it exits, the thread itself sets bDone to 1. This is used for
  86319. ** two purposes:
  86320. **
  86321. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  86322. ** attempt to select a SortSubtask for which there is not already an
  86323. ** active background thread (since doing so causes the main thread
  86324. ** to block until it finishes).
  86325. **
  86326. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  86327. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  86328. ** block provoke debugging output.
  86329. **
  86330. ** In both cases, the effects of the main thread seeing (bDone==0) even
  86331. ** after the thread has finished are not dire. So we don't worry about
  86332. ** memory barriers and such here.
  86333. */
  86334. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  86335. struct SortSubtask {
  86336. SQLiteThread *pThread; /* Background thread, if any */
  86337. int bDone; /* Set if thread is finished but not joined */
  86338. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  86339. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  86340. SorterList list; /* List for thread to write to a PMA */
  86341. int nPMA; /* Number of PMAs currently in file */
  86342. SorterCompare xCompare; /* Compare function to use */
  86343. SorterFile file; /* Temp file for level-0 PMAs */
  86344. SorterFile file2; /* Space for other PMAs */
  86345. };
  86346. /*
  86347. ** Main sorter structure. A single instance of this is allocated for each
  86348. ** sorter cursor created by the VDBE.
  86349. **
  86350. ** mxKeysize:
  86351. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  86352. ** this variable is updated so as to be set to the size on disk of the
  86353. ** largest record in the sorter.
  86354. */
  86355. struct VdbeSorter {
  86356. int mnPmaSize; /* Minimum PMA size, in bytes */
  86357. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  86358. int mxKeysize; /* Largest serialized key seen so far */
  86359. int pgsz; /* Main database page size */
  86360. PmaReader *pReader; /* Readr data from here after Rewind() */
  86361. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  86362. sqlite3 *db; /* Database connection */
  86363. KeyInfo *pKeyInfo; /* How to compare records */
  86364. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  86365. SorterList list; /* List of in-memory records */
  86366. int iMemory; /* Offset of free space in list.aMemory */
  86367. int nMemory; /* Size of list.aMemory allocation in bytes */
  86368. u8 bUsePMA; /* True if one or more PMAs created */
  86369. u8 bUseThreads; /* True to use background threads */
  86370. u8 iPrev; /* Previous thread used to flush PMA */
  86371. u8 nTask; /* Size of aTask[] array */
  86372. u8 typeMask;
  86373. SortSubtask aTask[1]; /* One or more subtasks */
  86374. };
  86375. #define SORTER_TYPE_INTEGER 0x01
  86376. #define SORTER_TYPE_TEXT 0x02
  86377. /*
  86378. ** An instance of the following object is used to read records out of a
  86379. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  86380. ** aKey might point into aMap or into aBuffer. If neither of those locations
  86381. ** contain a contiguous representation of the key, then aAlloc is allocated
  86382. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  86383. **
  86384. ** pFd==0 at EOF.
  86385. */
  86386. struct PmaReader {
  86387. i64 iReadOff; /* Current read offset */
  86388. i64 iEof; /* 1 byte past EOF for this PmaReader */
  86389. int nAlloc; /* Bytes of space at aAlloc */
  86390. int nKey; /* Number of bytes in key */
  86391. sqlite3_file *pFd; /* File handle we are reading from */
  86392. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  86393. u8 *aKey; /* Pointer to current key */
  86394. u8 *aBuffer; /* Current read buffer */
  86395. int nBuffer; /* Size of read buffer in bytes */
  86396. u8 *aMap; /* Pointer to mapping of entire file */
  86397. IncrMerger *pIncr; /* Incremental merger */
  86398. };
  86399. /*
  86400. ** Normally, a PmaReader object iterates through an existing PMA stored
  86401. ** within a temp file. However, if the PmaReader.pIncr variable points to
  86402. ** an object of the following type, it may be used to iterate/merge through
  86403. ** multiple PMAs simultaneously.
  86404. **
  86405. ** There are two types of IncrMerger object - single (bUseThread==0) and
  86406. ** multi-threaded (bUseThread==1).
  86407. **
  86408. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  86409. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  86410. ** size. When the IncrMerger is initialized, it reads enough data from
  86411. ** pMerger to populate aFile[0]. It then sets variables within the
  86412. ** corresponding PmaReader object to read from that file and kicks off
  86413. ** a background thread to populate aFile[1] with the next mxSz bytes of
  86414. ** sorted record data from pMerger.
  86415. **
  86416. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  86417. ** background thread has finished populating aFile[1]. It then exchanges
  86418. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  86419. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  86420. ** another background thread to populate the new aFile[1]. And so on, until
  86421. ** the contents of pMerger are exhausted.
  86422. **
  86423. ** A single-threaded IncrMerger does not open any temporary files of its
  86424. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  86425. ** at offset iStartOff of file pTask->file2. And instead of using a
  86426. ** background thread to prepare data for the PmaReader, with a single
  86427. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  86428. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  86429. ** of data.
  86430. */
  86431. struct IncrMerger {
  86432. SortSubtask *pTask; /* Task that owns this merger */
  86433. MergeEngine *pMerger; /* Merge engine thread reads data from */
  86434. i64 iStartOff; /* Offset to start writing file at */
  86435. int mxSz; /* Maximum bytes of data to store */
  86436. int bEof; /* Set to true when merge is finished */
  86437. int bUseThread; /* True to use a bg thread for this object */
  86438. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  86439. };
  86440. /*
  86441. ** An instance of this object is used for writing a PMA.
  86442. **
  86443. ** The PMA is written one record at a time. Each record is of an arbitrary
  86444. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  86445. ** each block is aligned on a page boundary. This object caches writes to
  86446. ** the PMA so that aligned, page-size blocks are written.
  86447. */
  86448. struct PmaWriter {
  86449. int eFWErr; /* Non-zero if in an error state */
  86450. u8 *aBuffer; /* Pointer to write buffer */
  86451. int nBuffer; /* Size of write buffer in bytes */
  86452. int iBufStart; /* First byte of buffer to write */
  86453. int iBufEnd; /* Last byte of buffer to write */
  86454. i64 iWriteOff; /* Offset of start of buffer in file */
  86455. sqlite3_file *pFd; /* File handle to write to */
  86456. };
  86457. /*
  86458. ** This object is the header on a single record while that record is being
  86459. ** held in memory and prior to being written out as part of a PMA.
  86460. **
  86461. ** How the linked list is connected depends on how memory is being managed
  86462. ** by this module. If using a separate allocation for each in-memory record
  86463. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  86464. ** SorterRecord.u.pNext pointers.
  86465. **
  86466. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  86467. ** then while records are being accumulated the list is linked using the
  86468. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  86469. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  86470. ** has finished passing records to the sorter, or when the in-memory buffer
  86471. ** is full, the list is sorted. As part of the sorting process, it is
  86472. ** converted to use the SorterRecord.u.pNext pointers. See function
  86473. ** vdbeSorterSort() for details.
  86474. */
  86475. struct SorterRecord {
  86476. int nVal; /* Size of the record in bytes */
  86477. union {
  86478. SorterRecord *pNext; /* Pointer to next record in list */
  86479. int iNext; /* Offset within aMemory of next record */
  86480. } u;
  86481. /* The data for the record immediately follows this header */
  86482. };
  86483. /* Return a pointer to the buffer containing the record data for SorterRecord
  86484. ** object p. Should be used as if:
  86485. **
  86486. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  86487. */
  86488. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  86489. /* Maximum number of PMAs that a single MergeEngine can merge */
  86490. #define SORTER_MAX_MERGE_COUNT 16
  86491. static int vdbeIncrSwap(IncrMerger*);
  86492. static void vdbeIncrFree(IncrMerger *);
  86493. /*
  86494. ** Free all memory belonging to the PmaReader object passed as the
  86495. ** argument. All structure fields are set to zero before returning.
  86496. */
  86497. static void vdbePmaReaderClear(PmaReader *pReadr){
  86498. sqlite3_free(pReadr->aAlloc);
  86499. sqlite3_free(pReadr->aBuffer);
  86500. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  86501. vdbeIncrFree(pReadr->pIncr);
  86502. memset(pReadr, 0, sizeof(PmaReader));
  86503. }
  86504. /*
  86505. ** Read the next nByte bytes of data from the PMA p.
  86506. ** If successful, set *ppOut to point to a buffer containing the data
  86507. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  86508. ** error code.
  86509. **
  86510. ** The buffer returned in *ppOut is only valid until the
  86511. ** next call to this function.
  86512. */
  86513. static int vdbePmaReadBlob(
  86514. PmaReader *p, /* PmaReader from which to take the blob */
  86515. int nByte, /* Bytes of data to read */
  86516. u8 **ppOut /* OUT: Pointer to buffer containing data */
  86517. ){
  86518. int iBuf; /* Offset within buffer to read from */
  86519. int nAvail; /* Bytes of data available in buffer */
  86520. if( p->aMap ){
  86521. *ppOut = &p->aMap[p->iReadOff];
  86522. p->iReadOff += nByte;
  86523. return SQLITE_OK;
  86524. }
  86525. assert( p->aBuffer );
  86526. /* If there is no more data to be read from the buffer, read the next
  86527. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  86528. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  86529. iBuf = p->iReadOff % p->nBuffer;
  86530. if( iBuf==0 ){
  86531. int nRead; /* Bytes to read from disk */
  86532. int rc; /* sqlite3OsRead() return code */
  86533. /* Determine how many bytes of data to read. */
  86534. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  86535. nRead = p->nBuffer;
  86536. }else{
  86537. nRead = (int)(p->iEof - p->iReadOff);
  86538. }
  86539. assert( nRead>0 );
  86540. /* Readr data from the file. Return early if an error occurs. */
  86541. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  86542. assert( rc!=SQLITE_IOERR_SHORT_READ );
  86543. if( rc!=SQLITE_OK ) return rc;
  86544. }
  86545. nAvail = p->nBuffer - iBuf;
  86546. if( nByte<=nAvail ){
  86547. /* The requested data is available in the in-memory buffer. In this
  86548. ** case there is no need to make a copy of the data, just return a
  86549. ** pointer into the buffer to the caller. */
  86550. *ppOut = &p->aBuffer[iBuf];
  86551. p->iReadOff += nByte;
  86552. }else{
  86553. /* The requested data is not all available in the in-memory buffer.
  86554. ** In this case, allocate space at p->aAlloc[] to copy the requested
  86555. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  86556. int nRem; /* Bytes remaining to copy */
  86557. /* Extend the p->aAlloc[] allocation if required. */
  86558. if( p->nAlloc<nByte ){
  86559. u8 *aNew;
  86560. sqlite3_int64 nNew = MAX(128, 2*(sqlite3_int64)p->nAlloc);
  86561. while( nByte>nNew ) nNew = nNew*2;
  86562. aNew = sqlite3Realloc(p->aAlloc, nNew);
  86563. if( !aNew ) return SQLITE_NOMEM_BKPT;
  86564. p->nAlloc = nNew;
  86565. p->aAlloc = aNew;
  86566. }
  86567. /* Copy as much data as is available in the buffer into the start of
  86568. ** p->aAlloc[]. */
  86569. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  86570. p->iReadOff += nAvail;
  86571. nRem = nByte - nAvail;
  86572. /* The following loop copies up to p->nBuffer bytes per iteration into
  86573. ** the p->aAlloc[] buffer. */
  86574. while( nRem>0 ){
  86575. int rc; /* vdbePmaReadBlob() return code */
  86576. int nCopy; /* Number of bytes to copy */
  86577. u8 *aNext; /* Pointer to buffer to copy data from */
  86578. nCopy = nRem;
  86579. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  86580. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  86581. if( rc!=SQLITE_OK ) return rc;
  86582. assert( aNext!=p->aAlloc );
  86583. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  86584. nRem -= nCopy;
  86585. }
  86586. *ppOut = p->aAlloc;
  86587. }
  86588. return SQLITE_OK;
  86589. }
  86590. /*
  86591. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  86592. ** the value read.
  86593. */
  86594. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  86595. int iBuf;
  86596. if( p->aMap ){
  86597. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  86598. }else{
  86599. iBuf = p->iReadOff % p->nBuffer;
  86600. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  86601. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  86602. }else{
  86603. u8 aVarint[16], *a;
  86604. int i = 0, rc;
  86605. do{
  86606. rc = vdbePmaReadBlob(p, 1, &a);
  86607. if( rc ) return rc;
  86608. aVarint[(i++)&0xf] = a[0];
  86609. }while( (a[0]&0x80)!=0 );
  86610. sqlite3GetVarint(aVarint, pnOut);
  86611. }
  86612. }
  86613. return SQLITE_OK;
  86614. }
  86615. /*
  86616. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  86617. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  86618. ** (because the file is too large or the VFS layer is configured not to use
  86619. ** mmap), return SQLITE_OK and set *pp to NULL.
  86620. **
  86621. ** Or, if an error occurs, return an SQLite error code. The final value of
  86622. ** *pp is undefined in this case.
  86623. */
  86624. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  86625. int rc = SQLITE_OK;
  86626. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  86627. sqlite3_file *pFd = pFile->pFd;
  86628. if( pFd->pMethods->iVersion>=3 ){
  86629. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  86630. testcase( rc!=SQLITE_OK );
  86631. }
  86632. }
  86633. return rc;
  86634. }
  86635. /*
  86636. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  86637. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  86638. ** if successful, or an SQLite error code if an error occurs.
  86639. */
  86640. static int vdbePmaReaderSeek(
  86641. SortSubtask *pTask, /* Task context */
  86642. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  86643. SorterFile *pFile, /* Sorter file to read from */
  86644. i64 iOff /* Offset in pFile */
  86645. ){
  86646. int rc = SQLITE_OK;
  86647. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  86648. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  86649. if( pReadr->aMap ){
  86650. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  86651. pReadr->aMap = 0;
  86652. }
  86653. pReadr->iReadOff = iOff;
  86654. pReadr->iEof = pFile->iEof;
  86655. pReadr->pFd = pFile->pFd;
  86656. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  86657. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  86658. int pgsz = pTask->pSorter->pgsz;
  86659. int iBuf = pReadr->iReadOff % pgsz;
  86660. if( pReadr->aBuffer==0 ){
  86661. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  86662. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
  86663. pReadr->nBuffer = pgsz;
  86664. }
  86665. if( rc==SQLITE_OK && iBuf ){
  86666. int nRead = pgsz - iBuf;
  86667. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  86668. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  86669. }
  86670. rc = sqlite3OsRead(
  86671. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  86672. );
  86673. testcase( rc!=SQLITE_OK );
  86674. }
  86675. }
  86676. return rc;
  86677. }
  86678. /*
  86679. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  86680. ** no error occurs, or an SQLite error code if one does.
  86681. */
  86682. static int vdbePmaReaderNext(PmaReader *pReadr){
  86683. int rc = SQLITE_OK; /* Return Code */
  86684. u64 nRec = 0; /* Size of record in bytes */
  86685. if( pReadr->iReadOff>=pReadr->iEof ){
  86686. IncrMerger *pIncr = pReadr->pIncr;
  86687. int bEof = 1;
  86688. if( pIncr ){
  86689. rc = vdbeIncrSwap(pIncr);
  86690. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  86691. rc = vdbePmaReaderSeek(
  86692. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  86693. );
  86694. bEof = 0;
  86695. }
  86696. }
  86697. if( bEof ){
  86698. /* This is an EOF condition */
  86699. vdbePmaReaderClear(pReadr);
  86700. testcase( rc!=SQLITE_OK );
  86701. return rc;
  86702. }
  86703. }
  86704. if( rc==SQLITE_OK ){
  86705. rc = vdbePmaReadVarint(pReadr, &nRec);
  86706. }
  86707. if( rc==SQLITE_OK ){
  86708. pReadr->nKey = (int)nRec;
  86709. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  86710. testcase( rc!=SQLITE_OK );
  86711. }
  86712. return rc;
  86713. }
  86714. /*
  86715. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  86716. ** starting at offset iStart and ending at offset iEof-1. This function
  86717. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  86718. ** PMA is empty).
  86719. **
  86720. ** If the pnByte parameter is NULL, then it is assumed that the file
  86721. ** contains a single PMA, and that that PMA omits the initial length varint.
  86722. */
  86723. static int vdbePmaReaderInit(
  86724. SortSubtask *pTask, /* Task context */
  86725. SorterFile *pFile, /* Sorter file to read from */
  86726. i64 iStart, /* Start offset in pFile */
  86727. PmaReader *pReadr, /* PmaReader to populate */
  86728. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  86729. ){
  86730. int rc;
  86731. assert( pFile->iEof>iStart );
  86732. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  86733. assert( pReadr->aBuffer==0 );
  86734. assert( pReadr->aMap==0 );
  86735. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  86736. if( rc==SQLITE_OK ){
  86737. u64 nByte = 0; /* Size of PMA in bytes */
  86738. rc = vdbePmaReadVarint(pReadr, &nByte);
  86739. pReadr->iEof = pReadr->iReadOff + nByte;
  86740. *pnByte += nByte;
  86741. }
  86742. if( rc==SQLITE_OK ){
  86743. rc = vdbePmaReaderNext(pReadr);
  86744. }
  86745. return rc;
  86746. }
  86747. /*
  86748. ** A version of vdbeSorterCompare() that assumes that it has already been
  86749. ** determined that the first field of key1 is equal to the first field of
  86750. ** key2.
  86751. */
  86752. static int vdbeSorterCompareTail(
  86753. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  86754. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  86755. const void *pKey1, int nKey1, /* Left side of comparison */
  86756. const void *pKey2, int nKey2 /* Right side of comparison */
  86757. ){
  86758. UnpackedRecord *r2 = pTask->pUnpacked;
  86759. if( *pbKey2Cached==0 ){
  86760. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  86761. *pbKey2Cached = 1;
  86762. }
  86763. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  86764. }
  86765. /*
  86766. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  86767. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  86768. ** used by the comparison. Return the result of the comparison.
  86769. **
  86770. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  86771. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  86772. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  86773. ** version of key2 and *pbKey2Cached set to true before returning.
  86774. **
  86775. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  86776. ** to SQLITE_NOMEM.
  86777. */
  86778. static int vdbeSorterCompare(
  86779. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  86780. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  86781. const void *pKey1, int nKey1, /* Left side of comparison */
  86782. const void *pKey2, int nKey2 /* Right side of comparison */
  86783. ){
  86784. UnpackedRecord *r2 = pTask->pUnpacked;
  86785. if( !*pbKey2Cached ){
  86786. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  86787. *pbKey2Cached = 1;
  86788. }
  86789. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  86790. }
  86791. /*
  86792. ** A specially optimized version of vdbeSorterCompare() that assumes that
  86793. ** the first field of each key is a TEXT value and that the collation
  86794. ** sequence to compare them with is BINARY.
  86795. */
  86796. static int vdbeSorterCompareText(
  86797. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  86798. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  86799. const void *pKey1, int nKey1, /* Left side of comparison */
  86800. const void *pKey2, int nKey2 /* Right side of comparison */
  86801. ){
  86802. const u8 * const p1 = (const u8 * const)pKey1;
  86803. const u8 * const p2 = (const u8 * const)pKey2;
  86804. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  86805. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  86806. int n1;
  86807. int n2;
  86808. int res;
  86809. getVarint32(&p1[1], n1);
  86810. getVarint32(&p2[1], n2);
  86811. res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
  86812. if( res==0 ){
  86813. res = n1 - n2;
  86814. }
  86815. if( res==0 ){
  86816. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  86817. res = vdbeSorterCompareTail(
  86818. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  86819. );
  86820. }
  86821. }else{
  86822. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  86823. res = res * -1;
  86824. }
  86825. }
  86826. return res;
  86827. }
  86828. /*
  86829. ** A specially optimized version of vdbeSorterCompare() that assumes that
  86830. ** the first field of each key is an INTEGER value.
  86831. */
  86832. static int vdbeSorterCompareInt(
  86833. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  86834. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  86835. const void *pKey1, int nKey1, /* Left side of comparison */
  86836. const void *pKey2, int nKey2 /* Right side of comparison */
  86837. ){
  86838. const u8 * const p1 = (const u8 * const)pKey1;
  86839. const u8 * const p2 = (const u8 * const)pKey2;
  86840. const int s1 = p1[1]; /* Left hand serial type */
  86841. const int s2 = p2[1]; /* Right hand serial type */
  86842. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  86843. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  86844. int res; /* Return value */
  86845. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  86846. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  86847. if( s1==s2 ){
  86848. /* The two values have the same sign. Compare using memcmp(). */
  86849. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
  86850. const u8 n = aLen[s1];
  86851. int i;
  86852. res = 0;
  86853. for(i=0; i<n; i++){
  86854. if( (res = v1[i] - v2[i])!=0 ){
  86855. if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
  86856. res = v1[0] & 0x80 ? -1 : +1;
  86857. }
  86858. break;
  86859. }
  86860. }
  86861. }else if( s1>7 && s2>7 ){
  86862. res = s1 - s2;
  86863. }else{
  86864. if( s2>7 ){
  86865. res = +1;
  86866. }else if( s1>7 ){
  86867. res = -1;
  86868. }else{
  86869. res = s1 - s2;
  86870. }
  86871. assert( res!=0 );
  86872. if( res>0 ){
  86873. if( *v1 & 0x80 ) res = -1;
  86874. }else{
  86875. if( *v2 & 0x80 ) res = +1;
  86876. }
  86877. }
  86878. if( res==0 ){
  86879. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  86880. res = vdbeSorterCompareTail(
  86881. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  86882. );
  86883. }
  86884. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  86885. res = res * -1;
  86886. }
  86887. return res;
  86888. }
  86889. /*
  86890. ** Initialize the temporary index cursor just opened as a sorter cursor.
  86891. **
  86892. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
  86893. ** to determine the number of fields that should be compared from the
  86894. ** records being sorted. However, if the value passed as argument nField
  86895. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  86896. ** is used instead. This is used when sorting records for a CREATE INDEX
  86897. ** statement. In this case, keys are always delivered to the sorter in
  86898. ** order of the primary key, which happens to be make up the final part
  86899. ** of the records being sorted. So if the sort is stable, there is never
  86900. ** any reason to compare PK fields and they can be ignored for a small
  86901. ** performance boost.
  86902. **
  86903. ** The sorter can guarantee a stable sort when running in single-threaded
  86904. ** mode, but not in multi-threaded mode.
  86905. **
  86906. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  86907. */
  86908. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  86909. sqlite3 *db, /* Database connection (for malloc()) */
  86910. int nField, /* Number of key fields in each record */
  86911. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  86912. ){
  86913. int pgsz; /* Page size of main database */
  86914. int i; /* Used to iterate through aTask[] */
  86915. VdbeSorter *pSorter; /* The new sorter */
  86916. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  86917. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  86918. int sz; /* Size of pSorter in bytes */
  86919. int rc = SQLITE_OK;
  86920. #if SQLITE_MAX_WORKER_THREADS==0
  86921. # define nWorker 0
  86922. #else
  86923. int nWorker;
  86924. #endif
  86925. /* Initialize the upper limit on the number of worker threads */
  86926. #if SQLITE_MAX_WORKER_THREADS>0
  86927. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  86928. nWorker = 0;
  86929. }else{
  86930. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  86931. }
  86932. #endif
  86933. /* Do not allow the total number of threads (main thread + all workers)
  86934. ** to exceed the maximum merge count */
  86935. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  86936. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  86937. nWorker = SORTER_MAX_MERGE_COUNT-1;
  86938. }
  86939. #endif
  86940. assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
  86941. assert( pCsr->eCurType==CURTYPE_SORTER );
  86942. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
  86943. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  86944. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  86945. pCsr->uc.pSorter = pSorter;
  86946. if( pSorter==0 ){
  86947. rc = SQLITE_NOMEM_BKPT;
  86948. }else{
  86949. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  86950. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  86951. pKeyInfo->db = 0;
  86952. if( nField && nWorker==0 ){
  86953. pKeyInfo->nKeyField = nField;
  86954. }
  86955. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  86956. pSorter->nTask = nWorker + 1;
  86957. pSorter->iPrev = (u8)(nWorker - 1);
  86958. pSorter->bUseThreads = (pSorter->nTask>1);
  86959. pSorter->db = db;
  86960. for(i=0; i<pSorter->nTask; i++){
  86961. SortSubtask *pTask = &pSorter->aTask[i];
  86962. pTask->pSorter = pSorter;
  86963. }
  86964. if( !sqlite3TempInMemory(db) ){
  86965. i64 mxCache; /* Cache size in bytes*/
  86966. u32 szPma = sqlite3GlobalConfig.szPma;
  86967. pSorter->mnPmaSize = szPma * pgsz;
  86968. mxCache = db->aDb[0].pSchema->cache_size;
  86969. if( mxCache<0 ){
  86970. /* A negative cache-size value C indicates that the cache is abs(C)
  86971. ** KiB in size. */
  86972. mxCache = mxCache * -1024;
  86973. }else{
  86974. mxCache = mxCache * pgsz;
  86975. }
  86976. mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
  86977. pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
  86978. /* Avoid large memory allocations if the application has requested
  86979. ** SQLITE_CONFIG_SMALL_MALLOC. */
  86980. if( sqlite3GlobalConfig.bSmallMalloc==0 ){
  86981. assert( pSorter->iMemory==0 );
  86982. pSorter->nMemory = pgsz;
  86983. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  86984. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
  86985. }
  86986. }
  86987. if( pKeyInfo->nAllField<13
  86988. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  86989. ){
  86990. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  86991. }
  86992. }
  86993. return rc;
  86994. }
  86995. #undef nWorker /* Defined at the top of this function */
  86996. /*
  86997. ** Free the list of sorted records starting at pRecord.
  86998. */
  86999. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  87000. SorterRecord *p;
  87001. SorterRecord *pNext;
  87002. for(p=pRecord; p; p=pNext){
  87003. pNext = p->u.pNext;
  87004. sqlite3DbFree(db, p);
  87005. }
  87006. }
  87007. /*
  87008. ** Free all resources owned by the object indicated by argument pTask. All
  87009. ** fields of *pTask are zeroed before returning.
  87010. */
  87011. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  87012. sqlite3DbFree(db, pTask->pUnpacked);
  87013. #if SQLITE_MAX_WORKER_THREADS>0
  87014. /* pTask->list.aMemory can only be non-zero if it was handed memory
  87015. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  87016. if( pTask->list.aMemory ){
  87017. sqlite3_free(pTask->list.aMemory);
  87018. }else
  87019. #endif
  87020. {
  87021. assert( pTask->list.aMemory==0 );
  87022. vdbeSorterRecordFree(0, pTask->list.pList);
  87023. }
  87024. if( pTask->file.pFd ){
  87025. sqlite3OsCloseFree(pTask->file.pFd);
  87026. }
  87027. if( pTask->file2.pFd ){
  87028. sqlite3OsCloseFree(pTask->file2.pFd);
  87029. }
  87030. memset(pTask, 0, sizeof(SortSubtask));
  87031. }
  87032. #ifdef SQLITE_DEBUG_SORTER_THREADS
  87033. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  87034. i64 t;
  87035. int iTask = (pTask - pTask->pSorter->aTask);
  87036. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  87037. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  87038. }
  87039. static void vdbeSorterRewindDebug(const char *zEvent){
  87040. i64 t;
  87041. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  87042. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  87043. }
  87044. static void vdbeSorterPopulateDebug(
  87045. SortSubtask *pTask,
  87046. const char *zEvent
  87047. ){
  87048. i64 t;
  87049. int iTask = (pTask - pTask->pSorter->aTask);
  87050. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  87051. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  87052. }
  87053. static void vdbeSorterBlockDebug(
  87054. SortSubtask *pTask,
  87055. int bBlocked,
  87056. const char *zEvent
  87057. ){
  87058. if( bBlocked ){
  87059. i64 t;
  87060. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  87061. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  87062. }
  87063. }
  87064. #else
  87065. # define vdbeSorterWorkDebug(x,y)
  87066. # define vdbeSorterRewindDebug(y)
  87067. # define vdbeSorterPopulateDebug(x,y)
  87068. # define vdbeSorterBlockDebug(x,y,z)
  87069. #endif
  87070. #if SQLITE_MAX_WORKER_THREADS>0
  87071. /*
  87072. ** Join thread pTask->thread.
  87073. */
  87074. static int vdbeSorterJoinThread(SortSubtask *pTask){
  87075. int rc = SQLITE_OK;
  87076. if( pTask->pThread ){
  87077. #ifdef SQLITE_DEBUG_SORTER_THREADS
  87078. int bDone = pTask->bDone;
  87079. #endif
  87080. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  87081. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  87082. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  87083. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  87084. rc = SQLITE_PTR_TO_INT(pRet);
  87085. assert( pTask->bDone==1 );
  87086. pTask->bDone = 0;
  87087. pTask->pThread = 0;
  87088. }
  87089. return rc;
  87090. }
  87091. /*
  87092. ** Launch a background thread to run xTask(pIn).
  87093. */
  87094. static int vdbeSorterCreateThread(
  87095. SortSubtask *pTask, /* Thread will use this task object */
  87096. void *(*xTask)(void*), /* Routine to run in a separate thread */
  87097. void *pIn /* Argument passed into xTask() */
  87098. ){
  87099. assert( pTask->pThread==0 && pTask->bDone==0 );
  87100. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  87101. }
  87102. /*
  87103. ** Join all outstanding threads launched by SorterWrite() to create
  87104. ** level-0 PMAs.
  87105. */
  87106. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  87107. int rc = rcin;
  87108. int i;
  87109. /* This function is always called by the main user thread.
  87110. **
  87111. ** If this function is being called after SorterRewind() has been called,
  87112. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  87113. ** is currently attempt to join one of the other threads. To avoid a race
  87114. ** condition where this thread also attempts to join the same object, join
  87115. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  87116. for(i=pSorter->nTask-1; i>=0; i--){
  87117. SortSubtask *pTask = &pSorter->aTask[i];
  87118. int rc2 = vdbeSorterJoinThread(pTask);
  87119. if( rc==SQLITE_OK ) rc = rc2;
  87120. }
  87121. return rc;
  87122. }
  87123. #else
  87124. # define vdbeSorterJoinAll(x,rcin) (rcin)
  87125. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  87126. #endif
  87127. /*
  87128. ** Allocate a new MergeEngine object capable of handling up to
  87129. ** nReader PmaReader inputs.
  87130. **
  87131. ** nReader is automatically rounded up to the next power of two.
  87132. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  87133. */
  87134. static MergeEngine *vdbeMergeEngineNew(int nReader){
  87135. int N = 2; /* Smallest power of two >= nReader */
  87136. int nByte; /* Total bytes of space to allocate */
  87137. MergeEngine *pNew; /* Pointer to allocated object to return */
  87138. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  87139. while( N<nReader ) N += N;
  87140. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  87141. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  87142. if( pNew ){
  87143. pNew->nTree = N;
  87144. pNew->pTask = 0;
  87145. pNew->aReadr = (PmaReader*)&pNew[1];
  87146. pNew->aTree = (int*)&pNew->aReadr[N];
  87147. }
  87148. return pNew;
  87149. }
  87150. /*
  87151. ** Free the MergeEngine object passed as the only argument.
  87152. */
  87153. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  87154. int i;
  87155. if( pMerger ){
  87156. for(i=0; i<pMerger->nTree; i++){
  87157. vdbePmaReaderClear(&pMerger->aReadr[i]);
  87158. }
  87159. }
  87160. sqlite3_free(pMerger);
  87161. }
  87162. /*
  87163. ** Free all resources associated with the IncrMerger object indicated by
  87164. ** the first argument.
  87165. */
  87166. static void vdbeIncrFree(IncrMerger *pIncr){
  87167. if( pIncr ){
  87168. #if SQLITE_MAX_WORKER_THREADS>0
  87169. if( pIncr->bUseThread ){
  87170. vdbeSorterJoinThread(pIncr->pTask);
  87171. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  87172. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  87173. }
  87174. #endif
  87175. vdbeMergeEngineFree(pIncr->pMerger);
  87176. sqlite3_free(pIncr);
  87177. }
  87178. }
  87179. /*
  87180. ** Reset a sorting cursor back to its original empty state.
  87181. */
  87182. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  87183. int i;
  87184. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  87185. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  87186. #if SQLITE_MAX_WORKER_THREADS>0
  87187. if( pSorter->pReader ){
  87188. vdbePmaReaderClear(pSorter->pReader);
  87189. sqlite3DbFree(db, pSorter->pReader);
  87190. pSorter->pReader = 0;
  87191. }
  87192. #endif
  87193. vdbeMergeEngineFree(pSorter->pMerger);
  87194. pSorter->pMerger = 0;
  87195. for(i=0; i<pSorter->nTask; i++){
  87196. SortSubtask *pTask = &pSorter->aTask[i];
  87197. vdbeSortSubtaskCleanup(db, pTask);
  87198. pTask->pSorter = pSorter;
  87199. }
  87200. if( pSorter->list.aMemory==0 ){
  87201. vdbeSorterRecordFree(0, pSorter->list.pList);
  87202. }
  87203. pSorter->list.pList = 0;
  87204. pSorter->list.szPMA = 0;
  87205. pSorter->bUsePMA = 0;
  87206. pSorter->iMemory = 0;
  87207. pSorter->mxKeysize = 0;
  87208. sqlite3DbFree(db, pSorter->pUnpacked);
  87209. pSorter->pUnpacked = 0;
  87210. }
  87211. /*
  87212. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  87213. */
  87214. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  87215. VdbeSorter *pSorter;
  87216. assert( pCsr->eCurType==CURTYPE_SORTER );
  87217. pSorter = pCsr->uc.pSorter;
  87218. if( pSorter ){
  87219. sqlite3VdbeSorterReset(db, pSorter);
  87220. sqlite3_free(pSorter->list.aMemory);
  87221. sqlite3DbFree(db, pSorter);
  87222. pCsr->uc.pSorter = 0;
  87223. }
  87224. }
  87225. #if SQLITE_MAX_MMAP_SIZE>0
  87226. /*
  87227. ** The first argument is a file-handle open on a temporary file. The file
  87228. ** is guaranteed to be nByte bytes or smaller in size. This function
  87229. ** attempts to extend the file to nByte bytes in size and to ensure that
  87230. ** the VFS has memory mapped it.
  87231. **
  87232. ** Whether or not the file does end up memory mapped of course depends on
  87233. ** the specific VFS implementation.
  87234. */
  87235. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  87236. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  87237. void *p = 0;
  87238. int chunksize = 4*1024;
  87239. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  87240. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  87241. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  87242. sqlite3OsUnfetch(pFd, 0, p);
  87243. }
  87244. }
  87245. #else
  87246. # define vdbeSorterExtendFile(x,y,z)
  87247. #endif
  87248. /*
  87249. ** Allocate space for a file-handle and open a temporary file. If successful,
  87250. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  87251. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  87252. */
  87253. static int vdbeSorterOpenTempFile(
  87254. sqlite3 *db, /* Database handle doing sort */
  87255. i64 nExtend, /* Attempt to extend file to this size */
  87256. sqlite3_file **ppFd
  87257. ){
  87258. int rc;
  87259. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  87260. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  87261. SQLITE_OPEN_TEMP_JOURNAL |
  87262. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  87263. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  87264. );
  87265. if( rc==SQLITE_OK ){
  87266. i64 max = SQLITE_MAX_MMAP_SIZE;
  87267. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  87268. if( nExtend>0 ){
  87269. vdbeSorterExtendFile(db, *ppFd, nExtend);
  87270. }
  87271. }
  87272. return rc;
  87273. }
  87274. /*
  87275. ** If it has not already been allocated, allocate the UnpackedRecord
  87276. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  87277. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  87278. */
  87279. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  87280. if( pTask->pUnpacked==0 ){
  87281. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
  87282. if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
  87283. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
  87284. pTask->pUnpacked->errCode = 0;
  87285. }
  87286. return SQLITE_OK;
  87287. }
  87288. /*
  87289. ** Merge the two sorted lists p1 and p2 into a single list.
  87290. */
  87291. static SorterRecord *vdbeSorterMerge(
  87292. SortSubtask *pTask, /* Calling thread context */
  87293. SorterRecord *p1, /* First list to merge */
  87294. SorterRecord *p2 /* Second list to merge */
  87295. ){
  87296. SorterRecord *pFinal = 0;
  87297. SorterRecord **pp = &pFinal;
  87298. int bCached = 0;
  87299. assert( p1!=0 && p2!=0 );
  87300. for(;;){
  87301. int res;
  87302. res = pTask->xCompare(
  87303. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  87304. );
  87305. if( res<=0 ){
  87306. *pp = p1;
  87307. pp = &p1->u.pNext;
  87308. p1 = p1->u.pNext;
  87309. if( p1==0 ){
  87310. *pp = p2;
  87311. break;
  87312. }
  87313. }else{
  87314. *pp = p2;
  87315. pp = &p2->u.pNext;
  87316. p2 = p2->u.pNext;
  87317. bCached = 0;
  87318. if( p2==0 ){
  87319. *pp = p1;
  87320. break;
  87321. }
  87322. }
  87323. }
  87324. return pFinal;
  87325. }
  87326. /*
  87327. ** Return the SorterCompare function to compare values collected by the
  87328. ** sorter object passed as the only argument.
  87329. */
  87330. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  87331. if( p->typeMask==SORTER_TYPE_INTEGER ){
  87332. return vdbeSorterCompareInt;
  87333. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  87334. return vdbeSorterCompareText;
  87335. }
  87336. return vdbeSorterCompare;
  87337. }
  87338. /*
  87339. ** Sort the linked list of records headed at pTask->pList. Return
  87340. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  87341. ** an error occurs.
  87342. */
  87343. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  87344. int i;
  87345. SorterRecord **aSlot;
  87346. SorterRecord *p;
  87347. int rc;
  87348. rc = vdbeSortAllocUnpacked(pTask);
  87349. if( rc!=SQLITE_OK ) return rc;
  87350. p = pList->pList;
  87351. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  87352. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  87353. if( !aSlot ){
  87354. return SQLITE_NOMEM_BKPT;
  87355. }
  87356. while( p ){
  87357. SorterRecord *pNext;
  87358. if( pList->aMemory ){
  87359. if( (u8*)p==pList->aMemory ){
  87360. pNext = 0;
  87361. }else{
  87362. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  87363. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  87364. }
  87365. }else{
  87366. pNext = p->u.pNext;
  87367. }
  87368. p->u.pNext = 0;
  87369. for(i=0; aSlot[i]; i++){
  87370. p = vdbeSorterMerge(pTask, p, aSlot[i]);
  87371. aSlot[i] = 0;
  87372. }
  87373. aSlot[i] = p;
  87374. p = pNext;
  87375. }
  87376. p = 0;
  87377. for(i=0; i<64; i++){
  87378. if( aSlot[i]==0 ) continue;
  87379. p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
  87380. }
  87381. pList->pList = p;
  87382. sqlite3_free(aSlot);
  87383. assert( pTask->pUnpacked->errCode==SQLITE_OK
  87384. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  87385. );
  87386. return pTask->pUnpacked->errCode;
  87387. }
  87388. /*
  87389. ** Initialize a PMA-writer object.
  87390. */
  87391. static void vdbePmaWriterInit(
  87392. sqlite3_file *pFd, /* File handle to write to */
  87393. PmaWriter *p, /* Object to populate */
  87394. int nBuf, /* Buffer size */
  87395. i64 iStart /* Offset of pFd to begin writing at */
  87396. ){
  87397. memset(p, 0, sizeof(PmaWriter));
  87398. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  87399. if( !p->aBuffer ){
  87400. p->eFWErr = SQLITE_NOMEM_BKPT;
  87401. }else{
  87402. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  87403. p->iWriteOff = iStart - p->iBufStart;
  87404. p->nBuffer = nBuf;
  87405. p->pFd = pFd;
  87406. }
  87407. }
  87408. /*
  87409. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  87410. ** if successful, or an SQLite error code if an error occurs.
  87411. */
  87412. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  87413. int nRem = nData;
  87414. while( nRem>0 && p->eFWErr==0 ){
  87415. int nCopy = nRem;
  87416. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  87417. nCopy = p->nBuffer - p->iBufEnd;
  87418. }
  87419. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  87420. p->iBufEnd += nCopy;
  87421. if( p->iBufEnd==p->nBuffer ){
  87422. p->eFWErr = sqlite3OsWrite(p->pFd,
  87423. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  87424. p->iWriteOff + p->iBufStart
  87425. );
  87426. p->iBufStart = p->iBufEnd = 0;
  87427. p->iWriteOff += p->nBuffer;
  87428. }
  87429. assert( p->iBufEnd<p->nBuffer );
  87430. nRem -= nCopy;
  87431. }
  87432. }
  87433. /*
  87434. ** Flush any buffered data to disk and clean up the PMA-writer object.
  87435. ** The results of using the PMA-writer after this call are undefined.
  87436. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  87437. ** required. Otherwise, return an SQLite error code.
  87438. **
  87439. ** Before returning, set *piEof to the offset immediately following the
  87440. ** last byte written to the file.
  87441. */
  87442. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  87443. int rc;
  87444. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  87445. p->eFWErr = sqlite3OsWrite(p->pFd,
  87446. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  87447. p->iWriteOff + p->iBufStart
  87448. );
  87449. }
  87450. *piEof = (p->iWriteOff + p->iBufEnd);
  87451. sqlite3_free(p->aBuffer);
  87452. rc = p->eFWErr;
  87453. memset(p, 0, sizeof(PmaWriter));
  87454. return rc;
  87455. }
  87456. /*
  87457. ** Write value iVal encoded as a varint to the PMA. Return
  87458. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  87459. */
  87460. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  87461. int nByte;
  87462. u8 aByte[10];
  87463. nByte = sqlite3PutVarint(aByte, iVal);
  87464. vdbePmaWriteBlob(p, aByte, nByte);
  87465. }
  87466. /*
  87467. ** Write the current contents of in-memory linked-list pList to a level-0
  87468. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  87469. ** successful, or an SQLite error code otherwise.
  87470. **
  87471. ** The format of a PMA is:
  87472. **
  87473. ** * A varint. This varint contains the total number of bytes of content
  87474. ** in the PMA (not including the varint itself).
  87475. **
  87476. ** * One or more records packed end-to-end in order of ascending keys.
  87477. ** Each record consists of a varint followed by a blob of data (the
  87478. ** key). The varint is the number of bytes in the blob of data.
  87479. */
  87480. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  87481. sqlite3 *db = pTask->pSorter->db;
  87482. int rc = SQLITE_OK; /* Return code */
  87483. PmaWriter writer; /* Object used to write to the file */
  87484. #ifdef SQLITE_DEBUG
  87485. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  87486. ** This is used by an assert() statement at the end of this function. */
  87487. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  87488. #endif
  87489. vdbeSorterWorkDebug(pTask, "enter");
  87490. memset(&writer, 0, sizeof(PmaWriter));
  87491. assert( pList->szPMA>0 );
  87492. /* If the first temporary PMA file has not been opened, open it now. */
  87493. if( pTask->file.pFd==0 ){
  87494. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  87495. assert( rc!=SQLITE_OK || pTask->file.pFd );
  87496. assert( pTask->file.iEof==0 );
  87497. assert( pTask->nPMA==0 );
  87498. }
  87499. /* Try to get the file to memory map */
  87500. if( rc==SQLITE_OK ){
  87501. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  87502. }
  87503. /* Sort the list */
  87504. if( rc==SQLITE_OK ){
  87505. rc = vdbeSorterSort(pTask, pList);
  87506. }
  87507. if( rc==SQLITE_OK ){
  87508. SorterRecord *p;
  87509. SorterRecord *pNext = 0;
  87510. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  87511. pTask->file.iEof);
  87512. pTask->nPMA++;
  87513. vdbePmaWriteVarint(&writer, pList->szPMA);
  87514. for(p=pList->pList; p; p=pNext){
  87515. pNext = p->u.pNext;
  87516. vdbePmaWriteVarint(&writer, p->nVal);
  87517. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  87518. if( pList->aMemory==0 ) sqlite3_free(p);
  87519. }
  87520. pList->pList = p;
  87521. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  87522. }
  87523. vdbeSorterWorkDebug(pTask, "exit");
  87524. assert( rc!=SQLITE_OK || pList->pList==0 );
  87525. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  87526. return rc;
  87527. }
  87528. /*
  87529. ** Advance the MergeEngine to its next entry.
  87530. ** Set *pbEof to true there is no next entry because
  87531. ** the MergeEngine has reached the end of all its inputs.
  87532. **
  87533. ** Return SQLITE_OK if successful or an error code if an error occurs.
  87534. */
  87535. static int vdbeMergeEngineStep(
  87536. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  87537. int *pbEof /* Set TRUE at EOF. Set false for more content */
  87538. ){
  87539. int rc;
  87540. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  87541. SortSubtask *pTask = pMerger->pTask;
  87542. /* Advance the current PmaReader */
  87543. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  87544. /* Update contents of aTree[] */
  87545. if( rc==SQLITE_OK ){
  87546. int i; /* Index of aTree[] to recalculate */
  87547. PmaReader *pReadr1; /* First PmaReader to compare */
  87548. PmaReader *pReadr2; /* Second PmaReader to compare */
  87549. int bCached = 0;
  87550. /* Find the first two PmaReaders to compare. The one that was just
  87551. ** advanced (iPrev) and the one next to it in the array. */
  87552. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  87553. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  87554. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  87555. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  87556. int iRes;
  87557. if( pReadr1->pFd==0 ){
  87558. iRes = +1;
  87559. }else if( pReadr2->pFd==0 ){
  87560. iRes = -1;
  87561. }else{
  87562. iRes = pTask->xCompare(pTask, &bCached,
  87563. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  87564. );
  87565. }
  87566. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  87567. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  87568. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  87569. ** pKey2 to point to the record belonging to pReadr2.
  87570. **
  87571. ** Alternatively, if pReadr2 contains the smaller of the two values,
  87572. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  87573. ** was actually called above, then pTask->pUnpacked now contains
  87574. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  87575. ** vdbeSorterCompare() from decoding pReadr2 again.
  87576. **
  87577. ** If the two values were equal, then the value from the oldest
  87578. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  87579. ** is sorted from oldest to newest, so pReadr1 contains older values
  87580. ** than pReadr2 iff (pReadr1<pReadr2). */
  87581. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  87582. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  87583. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  87584. bCached = 0;
  87585. }else{
  87586. if( pReadr1->pFd ) bCached = 0;
  87587. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  87588. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  87589. }
  87590. }
  87591. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  87592. }
  87593. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  87594. }
  87595. #if SQLITE_MAX_WORKER_THREADS>0
  87596. /*
  87597. ** The main routine for background threads that write level-0 PMAs.
  87598. */
  87599. static void *vdbeSorterFlushThread(void *pCtx){
  87600. SortSubtask *pTask = (SortSubtask*)pCtx;
  87601. int rc; /* Return code */
  87602. assert( pTask->bDone==0 );
  87603. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  87604. pTask->bDone = 1;
  87605. return SQLITE_INT_TO_PTR(rc);
  87606. }
  87607. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  87608. /*
  87609. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  87610. ** using a background thread.
  87611. */
  87612. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  87613. #if SQLITE_MAX_WORKER_THREADS==0
  87614. pSorter->bUsePMA = 1;
  87615. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  87616. #else
  87617. int rc = SQLITE_OK;
  87618. int i;
  87619. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  87620. int nWorker = (pSorter->nTask-1);
  87621. /* Set the flag to indicate that at least one PMA has been written.
  87622. ** Or will be, anyhow. */
  87623. pSorter->bUsePMA = 1;
  87624. /* Select a sub-task to sort and flush the current list of in-memory
  87625. ** records to disk. If the sorter is running in multi-threaded mode,
  87626. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  87627. ** the background thread from a sub-tasks previous turn is still running,
  87628. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  87629. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  87630. ** sub-tasks are prefered as they use background threads - the final
  87631. ** sub-task uses the main thread. */
  87632. for(i=0; i<nWorker; i++){
  87633. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  87634. pTask = &pSorter->aTask[iTest];
  87635. if( pTask->bDone ){
  87636. rc = vdbeSorterJoinThread(pTask);
  87637. }
  87638. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  87639. }
  87640. if( rc==SQLITE_OK ){
  87641. if( i==nWorker ){
  87642. /* Use the foreground thread for this operation */
  87643. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  87644. }else{
  87645. /* Launch a background thread for this operation */
  87646. u8 *aMem = pTask->list.aMemory;
  87647. void *pCtx = (void*)pTask;
  87648. assert( pTask->pThread==0 && pTask->bDone==0 );
  87649. assert( pTask->list.pList==0 );
  87650. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  87651. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  87652. pTask->list = pSorter->list;
  87653. pSorter->list.pList = 0;
  87654. pSorter->list.szPMA = 0;
  87655. if( aMem ){
  87656. pSorter->list.aMemory = aMem;
  87657. pSorter->nMemory = sqlite3MallocSize(aMem);
  87658. }else if( pSorter->list.aMemory ){
  87659. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  87660. if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
  87661. }
  87662. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  87663. }
  87664. }
  87665. return rc;
  87666. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  87667. }
  87668. /*
  87669. ** Add a record to the sorter.
  87670. */
  87671. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  87672. const VdbeCursor *pCsr, /* Sorter cursor */
  87673. Mem *pVal /* Memory cell containing record */
  87674. ){
  87675. VdbeSorter *pSorter;
  87676. int rc = SQLITE_OK; /* Return Code */
  87677. SorterRecord *pNew; /* New list element */
  87678. int bFlush; /* True to flush contents of memory to PMA */
  87679. int nReq; /* Bytes of memory required */
  87680. int nPMA; /* Bytes of PMA space required */
  87681. int t; /* serial type of first record field */
  87682. assert( pCsr->eCurType==CURTYPE_SORTER );
  87683. pSorter = pCsr->uc.pSorter;
  87684. getVarint32((const u8*)&pVal->z[1], t);
  87685. if( t>0 && t<10 && t!=7 ){
  87686. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  87687. }else if( t>10 && (t & 0x01) ){
  87688. pSorter->typeMask &= SORTER_TYPE_TEXT;
  87689. }else{
  87690. pSorter->typeMask = 0;
  87691. }
  87692. assert( pSorter );
  87693. /* Figure out whether or not the current contents of memory should be
  87694. ** flushed to a PMA before continuing. If so, do so.
  87695. **
  87696. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  87697. ** flush the contents of memory to a new PMA if (a) at least one value is
  87698. ** already in memory and (b) the new value will not fit in memory.
  87699. **
  87700. ** Or, if using separate allocations for each record, flush the contents
  87701. ** of memory to a PMA if either of the following are true:
  87702. **
  87703. ** * The total memory allocated for the in-memory list is greater
  87704. ** than (page-size * cache-size), or
  87705. **
  87706. ** * The total memory allocated for the in-memory list is greater
  87707. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  87708. */
  87709. nReq = pVal->n + sizeof(SorterRecord);
  87710. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  87711. if( pSorter->mxPmaSize ){
  87712. if( pSorter->list.aMemory ){
  87713. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  87714. }else{
  87715. bFlush = (
  87716. (pSorter->list.szPMA > pSorter->mxPmaSize)
  87717. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  87718. );
  87719. }
  87720. if( bFlush ){
  87721. rc = vdbeSorterFlushPMA(pSorter);
  87722. pSorter->list.szPMA = 0;
  87723. pSorter->iMemory = 0;
  87724. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  87725. }
  87726. }
  87727. pSorter->list.szPMA += nPMA;
  87728. if( nPMA>pSorter->mxKeysize ){
  87729. pSorter->mxKeysize = nPMA;
  87730. }
  87731. if( pSorter->list.aMemory ){
  87732. int nMin = pSorter->iMemory + nReq;
  87733. if( nMin>pSorter->nMemory ){
  87734. u8 *aNew;
  87735. sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory;
  87736. int iListOff = -1;
  87737. if( pSorter->list.pList ){
  87738. iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
  87739. }
  87740. while( nNew < nMin ) nNew = nNew*2;
  87741. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  87742. if( nNew < nMin ) nNew = nMin;
  87743. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  87744. if( !aNew ) return SQLITE_NOMEM_BKPT;
  87745. if( iListOff>=0 ){
  87746. pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
  87747. }
  87748. pSorter->list.aMemory = aNew;
  87749. pSorter->nMemory = nNew;
  87750. }
  87751. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  87752. pSorter->iMemory += ROUND8(nReq);
  87753. if( pSorter->list.pList ){
  87754. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  87755. }
  87756. }else{
  87757. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  87758. if( pNew==0 ){
  87759. return SQLITE_NOMEM_BKPT;
  87760. }
  87761. pNew->u.pNext = pSorter->list.pList;
  87762. }
  87763. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  87764. pNew->nVal = pVal->n;
  87765. pSorter->list.pList = pNew;
  87766. return rc;
  87767. }
  87768. /*
  87769. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  87770. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  87771. ** except that the number-of-bytes varint is omitted from the start.
  87772. */
  87773. static int vdbeIncrPopulate(IncrMerger *pIncr){
  87774. int rc = SQLITE_OK;
  87775. int rc2;
  87776. i64 iStart = pIncr->iStartOff;
  87777. SorterFile *pOut = &pIncr->aFile[1];
  87778. SortSubtask *pTask = pIncr->pTask;
  87779. MergeEngine *pMerger = pIncr->pMerger;
  87780. PmaWriter writer;
  87781. assert( pIncr->bEof==0 );
  87782. vdbeSorterPopulateDebug(pTask, "enter");
  87783. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  87784. while( rc==SQLITE_OK ){
  87785. int dummy;
  87786. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  87787. int nKey = pReader->nKey;
  87788. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  87789. /* Check if the output file is full or if the input has been exhausted.
  87790. ** In either case exit the loop. */
  87791. if( pReader->pFd==0 ) break;
  87792. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  87793. /* Write the next key to the output. */
  87794. vdbePmaWriteVarint(&writer, nKey);
  87795. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  87796. assert( pIncr->pMerger->pTask==pTask );
  87797. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  87798. }
  87799. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  87800. if( rc==SQLITE_OK ) rc = rc2;
  87801. vdbeSorterPopulateDebug(pTask, "exit");
  87802. return rc;
  87803. }
  87804. #if SQLITE_MAX_WORKER_THREADS>0
  87805. /*
  87806. ** The main routine for background threads that populate aFile[1] of
  87807. ** multi-threaded IncrMerger objects.
  87808. */
  87809. static void *vdbeIncrPopulateThread(void *pCtx){
  87810. IncrMerger *pIncr = (IncrMerger*)pCtx;
  87811. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  87812. pIncr->pTask->bDone = 1;
  87813. return pRet;
  87814. }
  87815. /*
  87816. ** Launch a background thread to populate aFile[1] of pIncr.
  87817. */
  87818. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  87819. void *p = (void*)pIncr;
  87820. assert( pIncr->bUseThread );
  87821. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  87822. }
  87823. #endif
  87824. /*
  87825. ** This function is called when the PmaReader corresponding to pIncr has
  87826. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  87827. ** aFile[0] such that the PmaReader should start rereading it from the
  87828. ** beginning.
  87829. **
  87830. ** For single-threaded objects, this is accomplished by literally reading
  87831. ** keys from pIncr->pMerger and repopulating aFile[0].
  87832. **
  87833. ** For multi-threaded objects, all that is required is to wait until the
  87834. ** background thread is finished (if it is not already) and then swap
  87835. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  87836. ** been exhausted, this function also launches a new background thread
  87837. ** to populate the new aFile[1].
  87838. **
  87839. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  87840. */
  87841. static int vdbeIncrSwap(IncrMerger *pIncr){
  87842. int rc = SQLITE_OK;
  87843. #if SQLITE_MAX_WORKER_THREADS>0
  87844. if( pIncr->bUseThread ){
  87845. rc = vdbeSorterJoinThread(pIncr->pTask);
  87846. if( rc==SQLITE_OK ){
  87847. SorterFile f0 = pIncr->aFile[0];
  87848. pIncr->aFile[0] = pIncr->aFile[1];
  87849. pIncr->aFile[1] = f0;
  87850. }
  87851. if( rc==SQLITE_OK ){
  87852. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  87853. pIncr->bEof = 1;
  87854. }else{
  87855. rc = vdbeIncrBgPopulate(pIncr);
  87856. }
  87857. }
  87858. }else
  87859. #endif
  87860. {
  87861. rc = vdbeIncrPopulate(pIncr);
  87862. pIncr->aFile[0] = pIncr->aFile[1];
  87863. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  87864. pIncr->bEof = 1;
  87865. }
  87866. }
  87867. return rc;
  87868. }
  87869. /*
  87870. ** Allocate and return a new IncrMerger object to read data from pMerger.
  87871. **
  87872. ** If an OOM condition is encountered, return NULL. In this case free the
  87873. ** pMerger argument before returning.
  87874. */
  87875. static int vdbeIncrMergerNew(
  87876. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  87877. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  87878. IncrMerger **ppOut /* Write the new IncrMerger here */
  87879. ){
  87880. int rc = SQLITE_OK;
  87881. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  87882. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  87883. if( pIncr ){
  87884. pIncr->pMerger = pMerger;
  87885. pIncr->pTask = pTask;
  87886. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  87887. pTask->file2.iEof += pIncr->mxSz;
  87888. }else{
  87889. vdbeMergeEngineFree(pMerger);
  87890. rc = SQLITE_NOMEM_BKPT;
  87891. }
  87892. return rc;
  87893. }
  87894. #if SQLITE_MAX_WORKER_THREADS>0
  87895. /*
  87896. ** Set the "use-threads" flag on object pIncr.
  87897. */
  87898. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  87899. pIncr->bUseThread = 1;
  87900. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  87901. }
  87902. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  87903. /*
  87904. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  87905. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  87906. ** are advanced. This routine merely does the comparison.
  87907. */
  87908. static void vdbeMergeEngineCompare(
  87909. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  87910. int iOut /* Store the result in pMerger->aTree[iOut] */
  87911. ){
  87912. int i1;
  87913. int i2;
  87914. int iRes;
  87915. PmaReader *p1;
  87916. PmaReader *p2;
  87917. assert( iOut<pMerger->nTree && iOut>0 );
  87918. if( iOut>=(pMerger->nTree/2) ){
  87919. i1 = (iOut - pMerger->nTree/2) * 2;
  87920. i2 = i1 + 1;
  87921. }else{
  87922. i1 = pMerger->aTree[iOut*2];
  87923. i2 = pMerger->aTree[iOut*2+1];
  87924. }
  87925. p1 = &pMerger->aReadr[i1];
  87926. p2 = &pMerger->aReadr[i2];
  87927. if( p1->pFd==0 ){
  87928. iRes = i2;
  87929. }else if( p2->pFd==0 ){
  87930. iRes = i1;
  87931. }else{
  87932. SortSubtask *pTask = pMerger->pTask;
  87933. int bCached = 0;
  87934. int res;
  87935. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  87936. res = pTask->xCompare(
  87937. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  87938. );
  87939. if( res<=0 ){
  87940. iRes = i1;
  87941. }else{
  87942. iRes = i2;
  87943. }
  87944. }
  87945. pMerger->aTree[iOut] = iRes;
  87946. }
  87947. /*
  87948. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  87949. ** and vdbePmaReaderIncrMergeInit().
  87950. **
  87951. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  87952. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  87953. ** when there exists one or more separate worker threads.
  87954. */
  87955. #define INCRINIT_NORMAL 0
  87956. #define INCRINIT_TASK 1
  87957. #define INCRINIT_ROOT 2
  87958. /*
  87959. ** Forward reference required as the vdbeIncrMergeInit() and
  87960. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  87961. ** building a merge tree.
  87962. */
  87963. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  87964. /*
  87965. ** Initialize the MergeEngine object passed as the second argument. Once this
  87966. ** function returns, the first key of merged data may be read from the
  87967. ** MergeEngine object in the usual fashion.
  87968. **
  87969. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  87970. ** objects attached to the PmaReader objects that the merger reads from have
  87971. ** already been populated, but that they have not yet populated aFile[0] and
  87972. ** set the PmaReader objects up to read from it. In this case all that is
  87973. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  87974. ** its first key.
  87975. **
  87976. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  87977. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  87978. ** to pMerger.
  87979. **
  87980. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  87981. */
  87982. static int vdbeMergeEngineInit(
  87983. SortSubtask *pTask, /* Thread that will run pMerger */
  87984. MergeEngine *pMerger, /* MergeEngine to initialize */
  87985. int eMode /* One of the INCRINIT_XXX constants */
  87986. ){
  87987. int rc = SQLITE_OK; /* Return code */
  87988. int i; /* For looping over PmaReader objects */
  87989. int nTree; /* Number of subtrees to merge */
  87990. /* Failure to allocate the merge would have been detected prior to
  87991. ** invoking this routine */
  87992. assert( pMerger!=0 );
  87993. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  87994. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  87995. /* Verify that the MergeEngine is assigned to a single thread */
  87996. assert( pMerger->pTask==0 );
  87997. pMerger->pTask = pTask;
  87998. nTree = pMerger->nTree;
  87999. for(i=0; i<nTree; i++){
  88000. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  88001. /* PmaReaders should be normally initialized in order, as if they are
  88002. ** reading from the same temp file this makes for more linear file IO.
  88003. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  88004. ** in use it will block the vdbePmaReaderNext() call while it uses
  88005. ** the main thread to fill its buffer. So calling PmaReaderNext()
  88006. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  88007. ** better advantage of multi-processor hardware. */
  88008. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  88009. }else{
  88010. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  88011. }
  88012. if( rc!=SQLITE_OK ) return rc;
  88013. }
  88014. for(i=pMerger->nTree-1; i>0; i--){
  88015. vdbeMergeEngineCompare(pMerger, i);
  88016. }
  88017. return pTask->pUnpacked->errCode;
  88018. }
  88019. /*
  88020. ** The PmaReader passed as the first argument is guaranteed to be an
  88021. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  88022. ** and/or initialize the temp file related fields of the IncrMerge
  88023. ** object at (pReadr->pIncr).
  88024. **
  88025. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  88026. ** in the sub-tree headed by pReadr are also initialized. Data is then
  88027. ** loaded into the buffers belonging to pReadr and it is set to point to
  88028. ** the first key in its range.
  88029. **
  88030. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  88031. ** to be a multi-threaded PmaReader and this function is being called in a
  88032. ** background thread. In this case all PmaReaders in the sub-tree are
  88033. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  88034. ** pReadr is populated. However, pReadr itself is not set up to point
  88035. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  88036. ** that.
  88037. **
  88038. ** The reason this function does not call vdbePmaReaderNext() immediately
  88039. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  88040. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  88041. ** this entire function is being run by thread (pTask->thread), that will
  88042. ** lead to the current background thread attempting to join itself.
  88043. **
  88044. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  88045. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  88046. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  88047. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  88048. ** the current PmaReader set to point to the first key in its range.
  88049. **
  88050. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  88051. */
  88052. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  88053. int rc = SQLITE_OK;
  88054. IncrMerger *pIncr = pReadr->pIncr;
  88055. SortSubtask *pTask = pIncr->pTask;
  88056. sqlite3 *db = pTask->pSorter->db;
  88057. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  88058. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  88059. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  88060. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  88061. ** requires two temp files to itself, whereas a single-threaded object
  88062. ** only requires a region of pTask->file2. */
  88063. if( rc==SQLITE_OK ){
  88064. int mxSz = pIncr->mxSz;
  88065. #if SQLITE_MAX_WORKER_THREADS>0
  88066. if( pIncr->bUseThread ){
  88067. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  88068. if( rc==SQLITE_OK ){
  88069. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  88070. }
  88071. }else
  88072. #endif
  88073. /*if( !pIncr->bUseThread )*/{
  88074. if( pTask->file2.pFd==0 ){
  88075. assert( pTask->file2.iEof>0 );
  88076. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  88077. pTask->file2.iEof = 0;
  88078. }
  88079. if( rc==SQLITE_OK ){
  88080. pIncr->aFile[1].pFd = pTask->file2.pFd;
  88081. pIncr->iStartOff = pTask->file2.iEof;
  88082. pTask->file2.iEof += mxSz;
  88083. }
  88084. }
  88085. }
  88086. #if SQLITE_MAX_WORKER_THREADS>0
  88087. if( rc==SQLITE_OK && pIncr->bUseThread ){
  88088. /* Use the current thread to populate aFile[1], even though this
  88089. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  88090. ** then this function is already running in background thread
  88091. ** pIncr->pTask->thread.
  88092. **
  88093. ** If this is the INCRINIT_ROOT object, then it is running in the
  88094. ** main VDBE thread. But that is Ok, as that thread cannot return
  88095. ** control to the VDBE or proceed with anything useful until the
  88096. ** first results are ready from this merger object anyway.
  88097. */
  88098. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  88099. rc = vdbeIncrPopulate(pIncr);
  88100. }
  88101. #endif
  88102. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  88103. rc = vdbePmaReaderNext(pReadr);
  88104. }
  88105. return rc;
  88106. }
  88107. #if SQLITE_MAX_WORKER_THREADS>0
  88108. /*
  88109. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  88110. ** background threads.
  88111. */
  88112. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  88113. PmaReader *pReader = (PmaReader*)pCtx;
  88114. void *pRet = SQLITE_INT_TO_PTR(
  88115. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  88116. );
  88117. pReader->pIncr->pTask->bDone = 1;
  88118. return pRet;
  88119. }
  88120. #endif
  88121. /*
  88122. ** If the PmaReader passed as the first argument is not an incremental-reader
  88123. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  88124. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  88125. ** this routine to initialize the incremental merge.
  88126. **
  88127. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  88128. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  88129. ** Or, if the IncrMerger is single threaded, the same function is called
  88130. ** using the current thread.
  88131. */
  88132. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  88133. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  88134. int rc = SQLITE_OK; /* Return code */
  88135. if( pIncr ){
  88136. #if SQLITE_MAX_WORKER_THREADS>0
  88137. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  88138. if( pIncr->bUseThread ){
  88139. void *pCtx = (void*)pReadr;
  88140. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  88141. }else
  88142. #endif
  88143. {
  88144. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  88145. }
  88146. }
  88147. return rc;
  88148. }
  88149. /*
  88150. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  88151. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  88152. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  88153. ** to NULL and return an SQLite error code.
  88154. **
  88155. ** When this function is called, *piOffset is set to the offset of the
  88156. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  88157. ** set to the offset immediately following the last byte of the last
  88158. ** PMA before returning. If an error does occur, then the final value of
  88159. ** *piOffset is undefined.
  88160. */
  88161. static int vdbeMergeEngineLevel0(
  88162. SortSubtask *pTask, /* Sorter task to read from */
  88163. int nPMA, /* Number of PMAs to read */
  88164. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  88165. MergeEngine **ppOut /* OUT: New merge-engine */
  88166. ){
  88167. MergeEngine *pNew; /* Merge engine to return */
  88168. i64 iOff = *piOffset;
  88169. int i;
  88170. int rc = SQLITE_OK;
  88171. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  88172. if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
  88173. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  88174. i64 nDummy = 0;
  88175. PmaReader *pReadr = &pNew->aReadr[i];
  88176. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  88177. iOff = pReadr->iEof;
  88178. }
  88179. if( rc!=SQLITE_OK ){
  88180. vdbeMergeEngineFree(pNew);
  88181. *ppOut = 0;
  88182. }
  88183. *piOffset = iOff;
  88184. return rc;
  88185. }
  88186. /*
  88187. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  88188. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  88189. **
  88190. ** i.e.
  88191. **
  88192. ** nPMA<=16 -> TreeDepth() == 0
  88193. ** nPMA<=256 -> TreeDepth() == 1
  88194. ** nPMA<=65536 -> TreeDepth() == 2
  88195. */
  88196. static int vdbeSorterTreeDepth(int nPMA){
  88197. int nDepth = 0;
  88198. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  88199. while( nDiv < (i64)nPMA ){
  88200. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  88201. nDepth++;
  88202. }
  88203. return nDepth;
  88204. }
  88205. /*
  88206. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  88207. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  88208. ** tree, counting from zero. This function adds pLeaf to the tree.
  88209. **
  88210. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  88211. ** code is returned and pLeaf is freed.
  88212. */
  88213. static int vdbeSorterAddToTree(
  88214. SortSubtask *pTask, /* Task context */
  88215. int nDepth, /* Depth of tree according to TreeDepth() */
  88216. int iSeq, /* Sequence number of leaf within tree */
  88217. MergeEngine *pRoot, /* Root of tree */
  88218. MergeEngine *pLeaf /* Leaf to add to tree */
  88219. ){
  88220. int rc = SQLITE_OK;
  88221. int nDiv = 1;
  88222. int i;
  88223. MergeEngine *p = pRoot;
  88224. IncrMerger *pIncr;
  88225. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  88226. for(i=1; i<nDepth; i++){
  88227. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  88228. }
  88229. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  88230. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  88231. PmaReader *pReadr = &p->aReadr[iIter];
  88232. if( pReadr->pIncr==0 ){
  88233. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  88234. if( pNew==0 ){
  88235. rc = SQLITE_NOMEM_BKPT;
  88236. }else{
  88237. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  88238. }
  88239. }
  88240. if( rc==SQLITE_OK ){
  88241. p = pReadr->pIncr->pMerger;
  88242. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  88243. }
  88244. }
  88245. if( rc==SQLITE_OK ){
  88246. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  88247. }else{
  88248. vdbeIncrFree(pIncr);
  88249. }
  88250. return rc;
  88251. }
  88252. /*
  88253. ** This function is called as part of a SorterRewind() operation on a sorter
  88254. ** that has already written two or more level-0 PMAs to one or more temp
  88255. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  88256. ** can be used to incrementally merge all PMAs on disk.
  88257. **
  88258. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  88259. ** MergeEngine object at the root of the tree before returning. Or, if an
  88260. ** error occurs, an SQLite error code is returned and the final value
  88261. ** of *ppOut is undefined.
  88262. */
  88263. static int vdbeSorterMergeTreeBuild(
  88264. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  88265. MergeEngine **ppOut /* Write the MergeEngine here */
  88266. ){
  88267. MergeEngine *pMain = 0;
  88268. int rc = SQLITE_OK;
  88269. int iTask;
  88270. #if SQLITE_MAX_WORKER_THREADS>0
  88271. /* If the sorter uses more than one task, then create the top-level
  88272. ** MergeEngine here. This MergeEngine will read data from exactly
  88273. ** one PmaReader per sub-task. */
  88274. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  88275. if( pSorter->nTask>1 ){
  88276. pMain = vdbeMergeEngineNew(pSorter->nTask);
  88277. if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
  88278. }
  88279. #endif
  88280. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  88281. SortSubtask *pTask = &pSorter->aTask[iTask];
  88282. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  88283. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  88284. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  88285. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  88286. i64 iReadOff = 0;
  88287. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  88288. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  88289. }else{
  88290. int i;
  88291. int iSeq = 0;
  88292. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  88293. if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
  88294. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  88295. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  88296. int nReader; /* Number of level-0 PMAs to merge */
  88297. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  88298. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  88299. if( rc==SQLITE_OK ){
  88300. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  88301. }
  88302. }
  88303. }
  88304. if( rc==SQLITE_OK ){
  88305. #if SQLITE_MAX_WORKER_THREADS>0
  88306. if( pMain!=0 ){
  88307. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  88308. }else
  88309. #endif
  88310. {
  88311. assert( pMain==0 );
  88312. pMain = pRoot;
  88313. }
  88314. }else{
  88315. vdbeMergeEngineFree(pRoot);
  88316. }
  88317. }
  88318. }
  88319. if( rc!=SQLITE_OK ){
  88320. vdbeMergeEngineFree(pMain);
  88321. pMain = 0;
  88322. }
  88323. *ppOut = pMain;
  88324. return rc;
  88325. }
  88326. /*
  88327. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  88328. ** on a sorter that has written two or more PMAs to temporary files. It sets
  88329. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  88330. ** (for multi-threaded sorters) so that it can be used to iterate through
  88331. ** all records stored in the sorter.
  88332. **
  88333. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  88334. */
  88335. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  88336. int rc; /* Return code */
  88337. SortSubtask *pTask0 = &pSorter->aTask[0];
  88338. MergeEngine *pMain = 0;
  88339. #if SQLITE_MAX_WORKER_THREADS
  88340. sqlite3 *db = pTask0->pSorter->db;
  88341. int i;
  88342. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  88343. for(i=0; i<pSorter->nTask; i++){
  88344. pSorter->aTask[i].xCompare = xCompare;
  88345. }
  88346. #endif
  88347. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  88348. if( rc==SQLITE_OK ){
  88349. #if SQLITE_MAX_WORKER_THREADS
  88350. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  88351. if( pSorter->bUseThreads ){
  88352. int iTask;
  88353. PmaReader *pReadr = 0;
  88354. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  88355. rc = vdbeSortAllocUnpacked(pLast);
  88356. if( rc==SQLITE_OK ){
  88357. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  88358. pSorter->pReader = pReadr;
  88359. if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
  88360. }
  88361. if( rc==SQLITE_OK ){
  88362. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  88363. if( rc==SQLITE_OK ){
  88364. vdbeIncrMergerSetThreads(pReadr->pIncr);
  88365. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  88366. IncrMerger *pIncr;
  88367. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  88368. vdbeIncrMergerSetThreads(pIncr);
  88369. assert( pIncr->pTask!=pLast );
  88370. }
  88371. }
  88372. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  88373. /* Check that:
  88374. **
  88375. ** a) The incremental merge object is configured to use the
  88376. ** right task, and
  88377. ** b) If it is using task (nTask-1), it is configured to run
  88378. ** in single-threaded mode. This is important, as the
  88379. ** root merge (INCRINIT_ROOT) will be using the same task
  88380. ** object.
  88381. */
  88382. PmaReader *p = &pMain->aReadr[iTask];
  88383. assert( p->pIncr==0 || (
  88384. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  88385. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  88386. ));
  88387. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  88388. }
  88389. }
  88390. pMain = 0;
  88391. }
  88392. if( rc==SQLITE_OK ){
  88393. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  88394. }
  88395. }else
  88396. #endif
  88397. {
  88398. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  88399. pSorter->pMerger = pMain;
  88400. pMain = 0;
  88401. }
  88402. }
  88403. if( rc!=SQLITE_OK ){
  88404. vdbeMergeEngineFree(pMain);
  88405. }
  88406. return rc;
  88407. }
  88408. /*
  88409. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  88410. ** this function is called to prepare for iterating through the records
  88411. ** in sorted order.
  88412. */
  88413. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  88414. VdbeSorter *pSorter;
  88415. int rc = SQLITE_OK; /* Return code */
  88416. assert( pCsr->eCurType==CURTYPE_SORTER );
  88417. pSorter = pCsr->uc.pSorter;
  88418. assert( pSorter );
  88419. /* If no data has been written to disk, then do not do so now. Instead,
  88420. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  88421. ** from the in-memory list. */
  88422. if( pSorter->bUsePMA==0 ){
  88423. if( pSorter->list.pList ){
  88424. *pbEof = 0;
  88425. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  88426. }else{
  88427. *pbEof = 1;
  88428. }
  88429. return rc;
  88430. }
  88431. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  88432. ** function flushes the contents of memory to disk, it immediately always
  88433. ** creates a new list consisting of a single key immediately afterwards.
  88434. ** So the list is never empty at this point. */
  88435. assert( pSorter->list.pList );
  88436. rc = vdbeSorterFlushPMA(pSorter);
  88437. /* Join all threads */
  88438. rc = vdbeSorterJoinAll(pSorter, rc);
  88439. vdbeSorterRewindDebug("rewind");
  88440. /* Assuming no errors have occurred, set up a merger structure to
  88441. ** incrementally read and merge all remaining PMAs. */
  88442. assert( pSorter->pReader==0 );
  88443. if( rc==SQLITE_OK ){
  88444. rc = vdbeSorterSetupMerge(pSorter);
  88445. *pbEof = 0;
  88446. }
  88447. vdbeSorterRewindDebug("rewinddone");
  88448. return rc;
  88449. }
  88450. /*
  88451. ** Advance to the next element in the sorter. Return value:
  88452. **
  88453. ** SQLITE_OK success
  88454. ** SQLITE_DONE end of data
  88455. ** otherwise some kind of error.
  88456. */
  88457. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
  88458. VdbeSorter *pSorter;
  88459. int rc; /* Return code */
  88460. assert( pCsr->eCurType==CURTYPE_SORTER );
  88461. pSorter = pCsr->uc.pSorter;
  88462. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  88463. if( pSorter->bUsePMA ){
  88464. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  88465. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  88466. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  88467. #if SQLITE_MAX_WORKER_THREADS>0
  88468. if( pSorter->bUseThreads ){
  88469. rc = vdbePmaReaderNext(pSorter->pReader);
  88470. if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
  88471. }else
  88472. #endif
  88473. /*if( !pSorter->bUseThreads )*/ {
  88474. int res = 0;
  88475. assert( pSorter->pMerger!=0 );
  88476. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  88477. rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
  88478. if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
  88479. }
  88480. }else{
  88481. SorterRecord *pFree = pSorter->list.pList;
  88482. pSorter->list.pList = pFree->u.pNext;
  88483. pFree->u.pNext = 0;
  88484. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  88485. rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
  88486. }
  88487. return rc;
  88488. }
  88489. /*
  88490. ** Return a pointer to a buffer owned by the sorter that contains the
  88491. ** current key.
  88492. */
  88493. static void *vdbeSorterRowkey(
  88494. const VdbeSorter *pSorter, /* Sorter object */
  88495. int *pnKey /* OUT: Size of current key in bytes */
  88496. ){
  88497. void *pKey;
  88498. if( pSorter->bUsePMA ){
  88499. PmaReader *pReader;
  88500. #if SQLITE_MAX_WORKER_THREADS>0
  88501. if( pSorter->bUseThreads ){
  88502. pReader = pSorter->pReader;
  88503. }else
  88504. #endif
  88505. /*if( !pSorter->bUseThreads )*/{
  88506. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  88507. }
  88508. *pnKey = pReader->nKey;
  88509. pKey = pReader->aKey;
  88510. }else{
  88511. *pnKey = pSorter->list.pList->nVal;
  88512. pKey = SRVAL(pSorter->list.pList);
  88513. }
  88514. return pKey;
  88515. }
  88516. /*
  88517. ** Copy the current sorter key into the memory cell pOut.
  88518. */
  88519. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  88520. VdbeSorter *pSorter;
  88521. void *pKey; int nKey; /* Sorter key to copy into pOut */
  88522. assert( pCsr->eCurType==CURTYPE_SORTER );
  88523. pSorter = pCsr->uc.pSorter;
  88524. pKey = vdbeSorterRowkey(pSorter, &nKey);
  88525. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  88526. return SQLITE_NOMEM_BKPT;
  88527. }
  88528. pOut->n = nKey;
  88529. MemSetTypeFlag(pOut, MEM_Blob);
  88530. memcpy(pOut->z, pKey, nKey);
  88531. return SQLITE_OK;
  88532. }
  88533. /*
  88534. ** Compare the key in memory cell pVal with the key that the sorter cursor
  88535. ** passed as the first argument currently points to. For the purposes of
  88536. ** the comparison, ignore the rowid field at the end of each record.
  88537. **
  88538. ** If the sorter cursor key contains any NULL values, consider it to be
  88539. ** less than pVal. Even if pVal also contains NULL values.
  88540. **
  88541. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  88542. ** Otherwise, set *pRes to a negative, zero or positive value if the
  88543. ** key in pVal is smaller than, equal to or larger than the current sorter
  88544. ** key.
  88545. **
  88546. ** This routine forms the core of the OP_SorterCompare opcode, which in
  88547. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  88548. */
  88549. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  88550. const VdbeCursor *pCsr, /* Sorter cursor */
  88551. Mem *pVal, /* Value to compare to current sorter key */
  88552. int nKeyCol, /* Compare this many columns */
  88553. int *pRes /* OUT: Result of comparison */
  88554. ){
  88555. VdbeSorter *pSorter;
  88556. UnpackedRecord *r2;
  88557. KeyInfo *pKeyInfo;
  88558. int i;
  88559. void *pKey; int nKey; /* Sorter key to compare pVal with */
  88560. assert( pCsr->eCurType==CURTYPE_SORTER );
  88561. pSorter = pCsr->uc.pSorter;
  88562. r2 = pSorter->pUnpacked;
  88563. pKeyInfo = pCsr->pKeyInfo;
  88564. if( r2==0 ){
  88565. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  88566. if( r2==0 ) return SQLITE_NOMEM_BKPT;
  88567. r2->nField = nKeyCol;
  88568. }
  88569. assert( r2->nField==nKeyCol );
  88570. pKey = vdbeSorterRowkey(pSorter, &nKey);
  88571. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  88572. for(i=0; i<nKeyCol; i++){
  88573. if( r2->aMem[i].flags & MEM_Null ){
  88574. *pRes = -1;
  88575. return SQLITE_OK;
  88576. }
  88577. }
  88578. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  88579. return SQLITE_OK;
  88580. }
  88581. /************** End of vdbesort.c ********************************************/
  88582. /************** Begin file memjournal.c **************************************/
  88583. /*
  88584. ** 2008 October 7
  88585. **
  88586. ** The author disclaims copyright to this source code. In place of
  88587. ** a legal notice, here is a blessing:
  88588. **
  88589. ** May you do good and not evil.
  88590. ** May you find forgiveness for yourself and forgive others.
  88591. ** May you share freely, never taking more than you give.
  88592. **
  88593. *************************************************************************
  88594. **
  88595. ** This file contains code use to implement an in-memory rollback journal.
  88596. ** The in-memory rollback journal is used to journal transactions for
  88597. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  88598. **
  88599. ** Update: The in-memory journal is also used to temporarily cache
  88600. ** smaller journals that are not critical for power-loss recovery.
  88601. ** For example, statement journals that are not too big will be held
  88602. ** entirely in memory, thus reducing the number of file I/O calls, and
  88603. ** more importantly, reducing temporary file creation events. If these
  88604. ** journals become too large for memory, they are spilled to disk. But
  88605. ** in the common case, they are usually small and no file I/O needs to
  88606. ** occur.
  88607. */
  88608. /* #include "sqliteInt.h" */
  88609. /* Forward references to internal structures */
  88610. typedef struct MemJournal MemJournal;
  88611. typedef struct FilePoint FilePoint;
  88612. typedef struct FileChunk FileChunk;
  88613. /*
  88614. ** The rollback journal is composed of a linked list of these structures.
  88615. **
  88616. ** The zChunk array is always at least 8 bytes in size - usually much more.
  88617. ** Its actual size is stored in the MemJournal.nChunkSize variable.
  88618. */
  88619. struct FileChunk {
  88620. FileChunk *pNext; /* Next chunk in the journal */
  88621. u8 zChunk[8]; /* Content of this chunk */
  88622. };
  88623. /*
  88624. ** By default, allocate this many bytes of memory for each FileChunk object.
  88625. */
  88626. #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
  88627. /*
  88628. ** For chunk size nChunkSize, return the number of bytes that should
  88629. ** be allocated for each FileChunk structure.
  88630. */
  88631. #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
  88632. /*
  88633. ** An instance of this object serves as a cursor into the rollback journal.
  88634. ** The cursor can be either for reading or writing.
  88635. */
  88636. struct FilePoint {
  88637. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  88638. FileChunk *pChunk; /* Specific chunk into which cursor points */
  88639. };
  88640. /*
  88641. ** This structure is a subclass of sqlite3_file. Each open memory-journal
  88642. ** is an instance of this class.
  88643. */
  88644. struct MemJournal {
  88645. const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  88646. int nChunkSize; /* In-memory chunk-size */
  88647. int nSpill; /* Bytes of data before flushing */
  88648. int nSize; /* Bytes of data currently in memory */
  88649. FileChunk *pFirst; /* Head of in-memory chunk-list */
  88650. FilePoint endpoint; /* Pointer to the end of the file */
  88651. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  88652. int flags; /* xOpen flags */
  88653. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  88654. const char *zJournal; /* Name of the journal file */
  88655. };
  88656. /*
  88657. ** Read data from the in-memory journal file. This is the implementation
  88658. ** of the sqlite3_vfs.xRead method.
  88659. */
  88660. static int memjrnlRead(
  88661. sqlite3_file *pJfd, /* The journal file from which to read */
  88662. void *zBuf, /* Put the results here */
  88663. int iAmt, /* Number of bytes to read */
  88664. sqlite_int64 iOfst /* Begin reading at this offset */
  88665. ){
  88666. MemJournal *p = (MemJournal *)pJfd;
  88667. u8 *zOut = zBuf;
  88668. int nRead = iAmt;
  88669. int iChunkOffset;
  88670. FileChunk *pChunk;
  88671. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  88672. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  88673. if( (iAmt+iOfst)>p->endpoint.iOffset ){
  88674. return SQLITE_IOERR_SHORT_READ;
  88675. }
  88676. #endif
  88677. assert( (iAmt+iOfst)<=p->endpoint.iOffset );
  88678. assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
  88679. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  88680. sqlite3_int64 iOff = 0;
  88681. for(pChunk=p->pFirst;
  88682. ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
  88683. pChunk=pChunk->pNext
  88684. ){
  88685. iOff += p->nChunkSize;
  88686. }
  88687. }else{
  88688. pChunk = p->readpoint.pChunk;
  88689. assert( pChunk!=0 );
  88690. }
  88691. iChunkOffset = (int)(iOfst%p->nChunkSize);
  88692. do {
  88693. int iSpace = p->nChunkSize - iChunkOffset;
  88694. int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
  88695. memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
  88696. zOut += nCopy;
  88697. nRead -= iSpace;
  88698. iChunkOffset = 0;
  88699. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  88700. p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
  88701. p->readpoint.pChunk = pChunk;
  88702. return SQLITE_OK;
  88703. }
  88704. /*
  88705. ** Free the list of FileChunk structures headed at MemJournal.pFirst.
  88706. */
  88707. static void memjrnlFreeChunks(MemJournal *p){
  88708. FileChunk *pIter;
  88709. FileChunk *pNext;
  88710. for(pIter=p->pFirst; pIter; pIter=pNext){
  88711. pNext = pIter->pNext;
  88712. sqlite3_free(pIter);
  88713. }
  88714. p->pFirst = 0;
  88715. }
  88716. /*
  88717. ** Flush the contents of memory to a real file on disk.
  88718. */
  88719. static int memjrnlCreateFile(MemJournal *p){
  88720. int rc;
  88721. sqlite3_file *pReal = (sqlite3_file*)p;
  88722. MemJournal copy = *p;
  88723. memset(p, 0, sizeof(MemJournal));
  88724. rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
  88725. if( rc==SQLITE_OK ){
  88726. int nChunk = copy.nChunkSize;
  88727. i64 iOff = 0;
  88728. FileChunk *pIter;
  88729. for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
  88730. if( iOff + nChunk > copy.endpoint.iOffset ){
  88731. nChunk = copy.endpoint.iOffset - iOff;
  88732. }
  88733. rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
  88734. if( rc ) break;
  88735. iOff += nChunk;
  88736. }
  88737. if( rc==SQLITE_OK ){
  88738. /* No error has occurred. Free the in-memory buffers. */
  88739. memjrnlFreeChunks(&copy);
  88740. }
  88741. }
  88742. if( rc!=SQLITE_OK ){
  88743. /* If an error occurred while creating or writing to the file, restore
  88744. ** the original before returning. This way, SQLite uses the in-memory
  88745. ** journal data to roll back changes made to the internal page-cache
  88746. ** before this function was called. */
  88747. sqlite3OsClose(pReal);
  88748. *p = copy;
  88749. }
  88750. return rc;
  88751. }
  88752. /*
  88753. ** Write data to the file.
  88754. */
  88755. static int memjrnlWrite(
  88756. sqlite3_file *pJfd, /* The journal file into which to write */
  88757. const void *zBuf, /* Take data to be written from here */
  88758. int iAmt, /* Number of bytes to write */
  88759. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  88760. ){
  88761. MemJournal *p = (MemJournal *)pJfd;
  88762. int nWrite = iAmt;
  88763. u8 *zWrite = (u8 *)zBuf;
  88764. /* If the file should be created now, create it and write the new data
  88765. ** into the file on disk. */
  88766. if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
  88767. int rc = memjrnlCreateFile(p);
  88768. if( rc==SQLITE_OK ){
  88769. rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
  88770. }
  88771. return rc;
  88772. }
  88773. /* If the contents of this write should be stored in memory */
  88774. else{
  88775. /* An in-memory journal file should only ever be appended to. Random
  88776. ** access writes are not required. The only exception to this is when
  88777. ** the in-memory journal is being used by a connection using the
  88778. ** atomic-write optimization. In this case the first 28 bytes of the
  88779. ** journal file may be written as part of committing the transaction. */
  88780. assert( iOfst==p->endpoint.iOffset || iOfst==0 );
  88781. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  88782. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  88783. if( iOfst==0 && p->pFirst ){
  88784. assert( p->nChunkSize>iAmt );
  88785. memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
  88786. }else
  88787. #else
  88788. assert( iOfst>0 || p->pFirst==0 );
  88789. #endif
  88790. {
  88791. while( nWrite>0 ){
  88792. FileChunk *pChunk = p->endpoint.pChunk;
  88793. int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
  88794. int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
  88795. if( iChunkOffset==0 ){
  88796. /* New chunk is required to extend the file. */
  88797. FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
  88798. if( !pNew ){
  88799. return SQLITE_IOERR_NOMEM_BKPT;
  88800. }
  88801. pNew->pNext = 0;
  88802. if( pChunk ){
  88803. assert( p->pFirst );
  88804. pChunk->pNext = pNew;
  88805. }else{
  88806. assert( !p->pFirst );
  88807. p->pFirst = pNew;
  88808. }
  88809. p->endpoint.pChunk = pNew;
  88810. }
  88811. memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
  88812. zWrite += iSpace;
  88813. nWrite -= iSpace;
  88814. p->endpoint.iOffset += iSpace;
  88815. }
  88816. p->nSize = iAmt + iOfst;
  88817. }
  88818. }
  88819. return SQLITE_OK;
  88820. }
  88821. /*
  88822. ** Truncate the file.
  88823. **
  88824. ** If the journal file is already on disk, truncate it there. Or, if it
  88825. ** is still in main memory but is being truncated to zero bytes in size,
  88826. ** ignore
  88827. */
  88828. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  88829. MemJournal *p = (MemJournal *)pJfd;
  88830. if( ALWAYS(size==0) ){
  88831. memjrnlFreeChunks(p);
  88832. p->nSize = 0;
  88833. p->endpoint.pChunk = 0;
  88834. p->endpoint.iOffset = 0;
  88835. p->readpoint.pChunk = 0;
  88836. p->readpoint.iOffset = 0;
  88837. }
  88838. return SQLITE_OK;
  88839. }
  88840. /*
  88841. ** Close the file.
  88842. */
  88843. static int memjrnlClose(sqlite3_file *pJfd){
  88844. MemJournal *p = (MemJournal *)pJfd;
  88845. memjrnlFreeChunks(p);
  88846. return SQLITE_OK;
  88847. }
  88848. /*
  88849. ** Sync the file.
  88850. **
  88851. ** If the real file has been created, call its xSync method. Otherwise,
  88852. ** syncing an in-memory journal is a no-op.
  88853. */
  88854. static int memjrnlSync(sqlite3_file *pJfd, int flags){
  88855. UNUSED_PARAMETER2(pJfd, flags);
  88856. return SQLITE_OK;
  88857. }
  88858. /*
  88859. ** Query the size of the file in bytes.
  88860. */
  88861. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  88862. MemJournal *p = (MemJournal *)pJfd;
  88863. *pSize = (sqlite_int64) p->endpoint.iOffset;
  88864. return SQLITE_OK;
  88865. }
  88866. /*
  88867. ** Table of methods for MemJournal sqlite3_file object.
  88868. */
  88869. static const struct sqlite3_io_methods MemJournalMethods = {
  88870. 1, /* iVersion */
  88871. memjrnlClose, /* xClose */
  88872. memjrnlRead, /* xRead */
  88873. memjrnlWrite, /* xWrite */
  88874. memjrnlTruncate, /* xTruncate */
  88875. memjrnlSync, /* xSync */
  88876. memjrnlFileSize, /* xFileSize */
  88877. 0, /* xLock */
  88878. 0, /* xUnlock */
  88879. 0, /* xCheckReservedLock */
  88880. 0, /* xFileControl */
  88881. 0, /* xSectorSize */
  88882. 0, /* xDeviceCharacteristics */
  88883. 0, /* xShmMap */
  88884. 0, /* xShmLock */
  88885. 0, /* xShmBarrier */
  88886. 0, /* xShmUnmap */
  88887. 0, /* xFetch */
  88888. 0 /* xUnfetch */
  88889. };
  88890. /*
  88891. ** Open a journal file.
  88892. **
  88893. ** The behaviour of the journal file depends on the value of parameter
  88894. ** nSpill. If nSpill is 0, then the journal file is always create and
  88895. ** accessed using the underlying VFS. If nSpill is less than zero, then
  88896. ** all content is always stored in main-memory. Finally, if nSpill is a
  88897. ** positive value, then the journal file is initially created in-memory
  88898. ** but may be flushed to disk later on. In this case the journal file is
  88899. ** flushed to disk either when it grows larger than nSpill bytes in size,
  88900. ** or when sqlite3JournalCreate() is called.
  88901. */
  88902. SQLITE_PRIVATE int sqlite3JournalOpen(
  88903. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  88904. const char *zName, /* Name of the journal file */
  88905. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  88906. int flags, /* Opening flags */
  88907. int nSpill /* Bytes buffered before opening the file */
  88908. ){
  88909. MemJournal *p = (MemJournal*)pJfd;
  88910. /* Zero the file-handle object. If nSpill was passed zero, initialize
  88911. ** it using the sqlite3OsOpen() function of the underlying VFS. In this
  88912. ** case none of the code in this module is executed as a result of calls
  88913. ** made on the journal file-handle. */
  88914. memset(p, 0, sizeof(MemJournal));
  88915. if( nSpill==0 ){
  88916. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  88917. }
  88918. if( nSpill>0 ){
  88919. p->nChunkSize = nSpill;
  88920. }else{
  88921. p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
  88922. assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
  88923. }
  88924. p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
  88925. p->nSpill = nSpill;
  88926. p->flags = flags;
  88927. p->zJournal = zName;
  88928. p->pVfs = pVfs;
  88929. return SQLITE_OK;
  88930. }
  88931. /*
  88932. ** Open an in-memory journal file.
  88933. */
  88934. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  88935. sqlite3JournalOpen(0, 0, pJfd, 0, -1);
  88936. }
  88937. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  88938. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  88939. /*
  88940. ** If the argument p points to a MemJournal structure that is not an
  88941. ** in-memory-only journal file (i.e. is one that was opened with a +ve
  88942. ** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
  88943. ** file has not yet been created, create it now.
  88944. */
  88945. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
  88946. int rc = SQLITE_OK;
  88947. MemJournal *p = (MemJournal*)pJfd;
  88948. if( p->pMethod==&MemJournalMethods && (
  88949. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  88950. p->nSpill>0
  88951. #else
  88952. /* While this appears to not be possible without ATOMIC_WRITE, the
  88953. ** paths are complex, so it seems prudent to leave the test in as
  88954. ** a NEVER(), in case our analysis is subtly flawed. */
  88955. NEVER(p->nSpill>0)
  88956. #endif
  88957. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  88958. || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
  88959. #endif
  88960. )){
  88961. rc = memjrnlCreateFile(p);
  88962. }
  88963. return rc;
  88964. }
  88965. #endif
  88966. /*
  88967. ** The file-handle passed as the only argument is open on a journal file.
  88968. ** Return true if this "journal file" is currently stored in heap memory,
  88969. ** or false otherwise.
  88970. */
  88971. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
  88972. return p->pMethods==&MemJournalMethods;
  88973. }
  88974. /*
  88975. ** Return the number of bytes required to store a JournalFile that uses vfs
  88976. ** pVfs to create the underlying on-disk files.
  88977. */
  88978. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  88979. return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
  88980. }
  88981. /************** End of memjournal.c ******************************************/
  88982. /************** Begin file walker.c ******************************************/
  88983. /*
  88984. ** 2008 August 16
  88985. **
  88986. ** The author disclaims copyright to this source code. In place of
  88987. ** a legal notice, here is a blessing:
  88988. **
  88989. ** May you do good and not evil.
  88990. ** May you find forgiveness for yourself and forgive others.
  88991. ** May you share freely, never taking more than you give.
  88992. **
  88993. *************************************************************************
  88994. ** This file contains routines used for walking the parser tree for
  88995. ** an SQL statement.
  88996. */
  88997. /* #include "sqliteInt.h" */
  88998. /* #include <stdlib.h> */
  88999. /* #include <string.h> */
  89000. #if !defined(SQLITE_OMIT_WINDOWFUNC)
  89001. /*
  89002. ** Walk all expressions linked into the list of Window objects passed
  89003. ** as the second argument.
  89004. */
  89005. static int walkWindowList(Walker *pWalker, Window *pList){
  89006. Window *pWin;
  89007. for(pWin=pList; pWin; pWin=pWin->pNextWin){
  89008. if( sqlite3WalkExprList(pWalker, pWin->pOrderBy) ) return WRC_Abort;
  89009. if( sqlite3WalkExprList(pWalker, pWin->pPartition) ) return WRC_Abort;
  89010. if( sqlite3WalkExpr(pWalker, pWin->pFilter) ) return WRC_Abort;
  89011. }
  89012. return WRC_Continue;
  89013. }
  89014. #endif
  89015. /*
  89016. ** Walk an expression tree. Invoke the callback once for each node
  89017. ** of the expression, while descending. (In other words, the callback
  89018. ** is invoked before visiting children.)
  89019. **
  89020. ** The return value from the callback should be one of the WRC_*
  89021. ** constants to specify how to proceed with the walk.
  89022. **
  89023. ** WRC_Continue Continue descending down the tree.
  89024. **
  89025. ** WRC_Prune Do not descend into child nodes, but allow
  89026. ** the walk to continue with sibling nodes.
  89027. **
  89028. ** WRC_Abort Do no more callbacks. Unwind the stack and
  89029. ** return from the top-level walk call.
  89030. **
  89031. ** The return value from this routine is WRC_Abort to abandon the tree walk
  89032. ** and WRC_Continue to continue.
  89033. */
  89034. static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
  89035. int rc;
  89036. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  89037. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  89038. while(1){
  89039. rc = pWalker->xExprCallback(pWalker, pExpr);
  89040. if( rc ) return rc & WRC_Abort;
  89041. if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
  89042. if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  89043. assert( pExpr->x.pList==0 || pExpr->pRight==0 );
  89044. if( pExpr->pRight ){
  89045. pExpr = pExpr->pRight;
  89046. continue;
  89047. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  89048. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  89049. }else if( pExpr->x.pList ){
  89050. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  89051. }
  89052. #ifndef SQLITE_OMIT_WINDOWFUNC
  89053. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  89054. if( walkWindowList(pWalker, pExpr->y.pWin) ) return WRC_Abort;
  89055. }
  89056. #endif
  89057. }
  89058. break;
  89059. }
  89060. return WRC_Continue;
  89061. }
  89062. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  89063. return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
  89064. }
  89065. /*
  89066. ** Call sqlite3WalkExpr() for every expression in list p or until
  89067. ** an abort request is seen.
  89068. */
  89069. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  89070. int i;
  89071. struct ExprList_item *pItem;
  89072. if( p ){
  89073. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  89074. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  89075. }
  89076. }
  89077. return WRC_Continue;
  89078. }
  89079. /*
  89080. ** Walk all expressions associated with SELECT statement p. Do
  89081. ** not invoke the SELECT callback on p, but do (of course) invoke
  89082. ** any expr callbacks and SELECT callbacks that come from subqueries.
  89083. ** Return WRC_Abort or WRC_Continue.
  89084. */
  89085. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  89086. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  89087. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  89088. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  89089. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  89090. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  89091. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  89092. #if !defined(SQLITE_OMIT_WINDOWFUNC) && !defined(SQLITE_OMIT_ALTERTABLE)
  89093. {
  89094. Parse *pParse = pWalker->pParse;
  89095. if( pParse && IN_RENAME_OBJECT ){
  89096. int rc = walkWindowList(pWalker, p->pWinDefn);
  89097. assert( rc==WRC_Continue );
  89098. return rc;
  89099. }
  89100. }
  89101. #endif
  89102. return WRC_Continue;
  89103. }
  89104. /*
  89105. ** Walk the parse trees associated with all subqueries in the
  89106. ** FROM clause of SELECT statement p. Do not invoke the select
  89107. ** callback on p, but do invoke it on each FROM clause subquery
  89108. ** and on any subqueries further down in the tree. Return
  89109. ** WRC_Abort or WRC_Continue;
  89110. */
  89111. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  89112. SrcList *pSrc;
  89113. int i;
  89114. struct SrcList_item *pItem;
  89115. pSrc = p->pSrc;
  89116. assert( pSrc!=0 );
  89117. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  89118. if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  89119. return WRC_Abort;
  89120. }
  89121. if( pItem->fg.isTabFunc
  89122. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  89123. ){
  89124. return WRC_Abort;
  89125. }
  89126. }
  89127. return WRC_Continue;
  89128. }
  89129. /*
  89130. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  89131. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  89132. ** on the compound select chain, p->pPrior.
  89133. **
  89134. ** If it is not NULL, the xSelectCallback() callback is invoked before
  89135. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  89136. ** method is invoked following the walk of the expressions and FROM clause,
  89137. ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
  89138. ** and if the expressions and FROM clause both return WRC_Continue;
  89139. **
  89140. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  89141. ** there is an abort request.
  89142. **
  89143. ** If the Walker does not have an xSelectCallback() then this routine
  89144. ** is a no-op returning WRC_Continue.
  89145. */
  89146. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  89147. int rc;
  89148. if( p==0 ) return WRC_Continue;
  89149. if( pWalker->xSelectCallback==0 ) return WRC_Continue;
  89150. do{
  89151. rc = pWalker->xSelectCallback(pWalker, p);
  89152. if( rc ) return rc & WRC_Abort;
  89153. if( sqlite3WalkSelectExpr(pWalker, p)
  89154. || sqlite3WalkSelectFrom(pWalker, p)
  89155. ){
  89156. return WRC_Abort;
  89157. }
  89158. if( pWalker->xSelectCallback2 ){
  89159. pWalker->xSelectCallback2(pWalker, p);
  89160. }
  89161. p = p->pPrior;
  89162. }while( p!=0 );
  89163. return WRC_Continue;
  89164. }
  89165. /************** End of walker.c **********************************************/
  89166. /************** Begin file resolve.c *****************************************/
  89167. /*
  89168. ** 2008 August 18
  89169. **
  89170. ** The author disclaims copyright to this source code. In place of
  89171. ** a legal notice, here is a blessing:
  89172. **
  89173. ** May you do good and not evil.
  89174. ** May you find forgiveness for yourself and forgive others.
  89175. ** May you share freely, never taking more than you give.
  89176. **
  89177. *************************************************************************
  89178. **
  89179. ** This file contains routines used for walking the parser tree and
  89180. ** resolve all identifiers by associating them with a particular
  89181. ** table and column.
  89182. */
  89183. /* #include "sqliteInt.h" */
  89184. /*
  89185. ** Walk the expression tree pExpr and increase the aggregate function
  89186. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  89187. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  89188. ** outer query into an inner subquery.
  89189. **
  89190. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  89191. ** is a helper function - a callback for the tree walker.
  89192. */
  89193. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  89194. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  89195. return WRC_Continue;
  89196. }
  89197. static void incrAggFunctionDepth(Expr *pExpr, int N){
  89198. if( N>0 ){
  89199. Walker w;
  89200. memset(&w, 0, sizeof(w));
  89201. w.xExprCallback = incrAggDepth;
  89202. w.u.n = N;
  89203. sqlite3WalkExpr(&w, pExpr);
  89204. }
  89205. }
  89206. /*
  89207. ** Turn the pExpr expression into an alias for the iCol-th column of the
  89208. ** result set in pEList.
  89209. **
  89210. ** If the reference is followed by a COLLATE operator, then make sure
  89211. ** the COLLATE operator is preserved. For example:
  89212. **
  89213. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  89214. **
  89215. ** Should be transformed into:
  89216. **
  89217. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  89218. **
  89219. ** The nSubquery parameter specifies how many levels of subquery the
  89220. ** alias is removed from the original expression. The usual value is
  89221. ** zero but it might be more if the alias is contained within a subquery
  89222. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  89223. ** structures must be increased by the nSubquery amount.
  89224. */
  89225. static void resolveAlias(
  89226. Parse *pParse, /* Parsing context */
  89227. ExprList *pEList, /* A result set */
  89228. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  89229. Expr *pExpr, /* Transform this into an alias to the result set */
  89230. const char *zType, /* "GROUP" or "ORDER" or "" */
  89231. int nSubquery /* Number of subqueries that the label is moving */
  89232. ){
  89233. Expr *pOrig; /* The iCol-th column of the result set */
  89234. Expr *pDup; /* Copy of pOrig */
  89235. sqlite3 *db; /* The database connection */
  89236. assert( iCol>=0 && iCol<pEList->nExpr );
  89237. pOrig = pEList->a[iCol].pExpr;
  89238. assert( pOrig!=0 );
  89239. db = pParse->db;
  89240. pDup = sqlite3ExprDup(db, pOrig, 0);
  89241. if( pDup!=0 ){
  89242. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  89243. if( pExpr->op==TK_COLLATE ){
  89244. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  89245. }
  89246. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  89247. ** prevents ExprDelete() from deleting the Expr structure itself,
  89248. ** allowing it to be repopulated by the memcpy() on the following line.
  89249. ** The pExpr->u.zToken might point into memory that will be freed by the
  89250. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  89251. ** make a copy of the token before doing the sqlite3DbFree().
  89252. */
  89253. ExprSetProperty(pExpr, EP_Static);
  89254. sqlite3ExprDelete(db, pExpr);
  89255. memcpy(pExpr, pDup, sizeof(*pExpr));
  89256. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  89257. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  89258. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  89259. pExpr->flags |= EP_MemToken;
  89260. }
  89261. sqlite3DbFree(db, pDup);
  89262. }
  89263. ExprSetProperty(pExpr, EP_Alias);
  89264. }
  89265. /*
  89266. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  89267. **
  89268. ** Return FALSE if the USING clause is NULL or if it does not contain
  89269. ** zCol.
  89270. */
  89271. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  89272. if( pUsing ){
  89273. int k;
  89274. for(k=0; k<pUsing->nId; k++){
  89275. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  89276. }
  89277. }
  89278. return 0;
  89279. }
  89280. /*
  89281. ** Subqueries stores the original database, table and column names for their
  89282. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  89283. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  89284. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  89285. ** match anything.
  89286. */
  89287. SQLITE_PRIVATE int sqlite3MatchSpanName(
  89288. const char *zSpan,
  89289. const char *zCol,
  89290. const char *zTab,
  89291. const char *zDb
  89292. ){
  89293. int n;
  89294. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  89295. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  89296. return 0;
  89297. }
  89298. zSpan += n+1;
  89299. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  89300. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  89301. return 0;
  89302. }
  89303. zSpan += n+1;
  89304. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  89305. return 0;
  89306. }
  89307. return 1;
  89308. }
  89309. /*
  89310. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  89311. ** that name in the set of source tables in pSrcList and make the pExpr
  89312. ** expression node refer back to that source column. The following changes
  89313. ** are made to pExpr:
  89314. **
  89315. ** pExpr->iDb Set the index in db->aDb[] of the database X
  89316. ** (even if X is implied).
  89317. ** pExpr->iTable Set to the cursor number for the table obtained
  89318. ** from pSrcList.
  89319. ** pExpr->y.pTab Points to the Table structure of X.Y (even if
  89320. ** X and/or Y are implied.)
  89321. ** pExpr->iColumn Set to the column number within the table.
  89322. ** pExpr->op Set to TK_COLUMN.
  89323. ** pExpr->pLeft Any expression this points to is deleted
  89324. ** pExpr->pRight Any expression this points to is deleted.
  89325. **
  89326. ** The zDb variable is the name of the database (the "X"). This value may be
  89327. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  89328. ** can be used. The zTable variable is the name of the table (the "Y"). This
  89329. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  89330. ** means that the form of the name is Z and that columns from any table
  89331. ** can be used.
  89332. **
  89333. ** If the name cannot be resolved unambiguously, leave an error message
  89334. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  89335. */
  89336. static int lookupName(
  89337. Parse *pParse, /* The parsing context */
  89338. const char *zDb, /* Name of the database containing table, or NULL */
  89339. const char *zTab, /* Name of table containing column, or NULL */
  89340. const char *zCol, /* Name of the column. */
  89341. NameContext *pNC, /* The name context used to resolve the name */
  89342. Expr *pExpr /* Make this EXPR node point to the selected column */
  89343. ){
  89344. int i, j; /* Loop counters */
  89345. int cnt = 0; /* Number of matching column names */
  89346. int cntTab = 0; /* Number of matching table names */
  89347. int nSubquery = 0; /* How many levels of subquery */
  89348. sqlite3 *db = pParse->db; /* The database connection */
  89349. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  89350. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  89351. NameContext *pTopNC = pNC; /* First namecontext in the list */
  89352. Schema *pSchema = 0; /* Schema of the expression */
  89353. int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
  89354. Table *pTab = 0; /* Table hold the row */
  89355. Column *pCol; /* A column of pTab */
  89356. assert( pNC ); /* the name context cannot be NULL. */
  89357. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  89358. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  89359. /* Initialize the node to no-match */
  89360. pExpr->iTable = -1;
  89361. ExprSetVVAProperty(pExpr, EP_NoReduce);
  89362. /* Translate the schema name in zDb into a pointer to the corresponding
  89363. ** schema. If not found, pSchema will remain NULL and nothing will match
  89364. ** resulting in an appropriate error message toward the end of this routine
  89365. */
  89366. if( zDb ){
  89367. testcase( pNC->ncFlags & NC_PartIdx );
  89368. testcase( pNC->ncFlags & NC_IsCheck );
  89369. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  89370. /* Silently ignore database qualifiers inside CHECK constraints and
  89371. ** partial indices. Do not raise errors because that might break
  89372. ** legacy and because it does not hurt anything to just ignore the
  89373. ** database name. */
  89374. zDb = 0;
  89375. }else{
  89376. for(i=0; i<db->nDb; i++){
  89377. assert( db->aDb[i].zDbSName );
  89378. if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
  89379. pSchema = db->aDb[i].pSchema;
  89380. break;
  89381. }
  89382. }
  89383. }
  89384. }
  89385. /* Start at the inner-most context and move outward until a match is found */
  89386. assert( pNC && cnt==0 );
  89387. do{
  89388. ExprList *pEList;
  89389. SrcList *pSrcList = pNC->pSrcList;
  89390. if( pSrcList ){
  89391. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  89392. pTab = pItem->pTab;
  89393. assert( pTab!=0 && pTab->zName!=0 );
  89394. assert( pTab->nCol>0 );
  89395. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  89396. int hit = 0;
  89397. pEList = pItem->pSelect->pEList;
  89398. for(j=0; j<pEList->nExpr; j++){
  89399. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  89400. cnt++;
  89401. cntTab = 2;
  89402. pMatch = pItem;
  89403. pExpr->iColumn = j;
  89404. hit = 1;
  89405. }
  89406. }
  89407. if( hit || zTab==0 ) continue;
  89408. }
  89409. if( zDb && pTab->pSchema!=pSchema ){
  89410. continue;
  89411. }
  89412. if( zTab ){
  89413. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  89414. assert( zTabName!=0 );
  89415. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  89416. continue;
  89417. }
  89418. if( IN_RENAME_OBJECT && pItem->zAlias ){
  89419. sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
  89420. }
  89421. }
  89422. if( 0==(cntTab++) ){
  89423. pMatch = pItem;
  89424. }
  89425. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  89426. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  89427. /* If there has been exactly one prior match and this match
  89428. ** is for the right-hand table of a NATURAL JOIN or is in a
  89429. ** USING clause, then skip this match.
  89430. */
  89431. if( cnt==1 ){
  89432. if( pItem->fg.jointype & JT_NATURAL ) continue;
  89433. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  89434. }
  89435. cnt++;
  89436. pMatch = pItem;
  89437. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  89438. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  89439. break;
  89440. }
  89441. }
  89442. }
  89443. if( pMatch ){
  89444. pExpr->iTable = pMatch->iCursor;
  89445. pExpr->y.pTab = pMatch->pTab;
  89446. /* RIGHT JOIN not (yet) supported */
  89447. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  89448. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  89449. ExprSetProperty(pExpr, EP_CanBeNull);
  89450. }
  89451. pSchema = pExpr->y.pTab->pSchema;
  89452. }
  89453. } /* if( pSrcList ) */
  89454. #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
  89455. /* If we have not already resolved the name, then maybe
  89456. ** it is a new.* or old.* trigger argument reference. Or
  89457. ** maybe it is an excluded.* from an upsert.
  89458. */
  89459. if( zDb==0 && zTab!=0 && cntTab==0 ){
  89460. pTab = 0;
  89461. #ifndef SQLITE_OMIT_TRIGGER
  89462. if( pParse->pTriggerTab!=0 ){
  89463. int op = pParse->eTriggerOp;
  89464. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  89465. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  89466. pExpr->iTable = 1;
  89467. pTab = pParse->pTriggerTab;
  89468. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  89469. pExpr->iTable = 0;
  89470. pTab = pParse->pTriggerTab;
  89471. }
  89472. }
  89473. #endif /* SQLITE_OMIT_TRIGGER */
  89474. #ifndef SQLITE_OMIT_UPSERT
  89475. if( (pNC->ncFlags & NC_UUpsert)!=0 ){
  89476. Upsert *pUpsert = pNC->uNC.pUpsert;
  89477. if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
  89478. pTab = pUpsert->pUpsertSrc->a[0].pTab;
  89479. pExpr->iTable = 2;
  89480. }
  89481. }
  89482. #endif /* SQLITE_OMIT_UPSERT */
  89483. if( pTab ){
  89484. int iCol;
  89485. pSchema = pTab->pSchema;
  89486. cntTab++;
  89487. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  89488. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  89489. if( iCol==pTab->iPKey ){
  89490. iCol = -1;
  89491. }
  89492. break;
  89493. }
  89494. }
  89495. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  89496. /* IMP: R-51414-32910 */
  89497. iCol = -1;
  89498. }
  89499. if( iCol<pTab->nCol ){
  89500. cnt++;
  89501. #ifndef SQLITE_OMIT_UPSERT
  89502. if( pExpr->iTable==2 ){
  89503. testcase( iCol==(-1) );
  89504. if( IN_RENAME_OBJECT ){
  89505. pExpr->iColumn = iCol;
  89506. pExpr->y.pTab = pTab;
  89507. eNewExprOp = TK_COLUMN;
  89508. }else{
  89509. pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;
  89510. eNewExprOp = TK_REGISTER;
  89511. ExprSetProperty(pExpr, EP_Alias);
  89512. }
  89513. }else
  89514. #endif /* SQLITE_OMIT_UPSERT */
  89515. {
  89516. #ifndef SQLITE_OMIT_TRIGGER
  89517. if( iCol<0 ){
  89518. pExpr->affinity = SQLITE_AFF_INTEGER;
  89519. }else if( pExpr->iTable==0 ){
  89520. testcase( iCol==31 );
  89521. testcase( iCol==32 );
  89522. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  89523. }else{
  89524. testcase( iCol==31 );
  89525. testcase( iCol==32 );
  89526. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  89527. }
  89528. pExpr->y.pTab = pTab;
  89529. pExpr->iColumn = (i16)iCol;
  89530. eNewExprOp = TK_TRIGGER;
  89531. #endif /* SQLITE_OMIT_TRIGGER */
  89532. }
  89533. }
  89534. }
  89535. }
  89536. #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
  89537. /*
  89538. ** Perhaps the name is a reference to the ROWID
  89539. */
  89540. if( cnt==0
  89541. && cntTab==1
  89542. && pMatch
  89543. && (pNC->ncFlags & NC_IdxExpr)==0
  89544. && sqlite3IsRowid(zCol)
  89545. && VisibleRowid(pMatch->pTab)
  89546. ){
  89547. cnt = 1;
  89548. pExpr->iColumn = -1;
  89549. pExpr->affinity = SQLITE_AFF_INTEGER;
  89550. }
  89551. /*
  89552. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  89553. ** might refer to an result-set alias. This happens, for example, when
  89554. ** we are resolving names in the WHERE clause of the following command:
  89555. **
  89556. ** SELECT a+b AS x FROM table WHERE x<10;
  89557. **
  89558. ** In cases like this, replace pExpr with a copy of the expression that
  89559. ** forms the result set entry ("a+b" in the example) and return immediately.
  89560. ** Note that the expression in the result set should have already been
  89561. ** resolved by the time the WHERE clause is resolved.
  89562. **
  89563. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  89564. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  89565. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  89566. ** is supported for backwards compatibility only. Hence, we issue a warning
  89567. ** on sqlite3_log() whenever the capability is used.
  89568. */
  89569. if( (pNC->ncFlags & NC_UEList)!=0
  89570. && cnt==0
  89571. && zTab==0
  89572. ){
  89573. pEList = pNC->uNC.pEList;
  89574. assert( pEList!=0 );
  89575. for(j=0; j<pEList->nExpr; j++){
  89576. char *zAs = pEList->a[j].zName;
  89577. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  89578. Expr *pOrig;
  89579. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  89580. assert( pExpr->x.pList==0 );
  89581. assert( pExpr->x.pSelect==0 );
  89582. pOrig = pEList->a[j].pExpr;
  89583. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  89584. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  89585. return WRC_Abort;
  89586. }
  89587. if( (pNC->ncFlags&NC_AllowWin)==0 && ExprHasProperty(pOrig, EP_Win) ){
  89588. sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
  89589. return WRC_Abort;
  89590. }
  89591. if( sqlite3ExprVectorSize(pOrig)!=1 ){
  89592. sqlite3ErrorMsg(pParse, "row value misused");
  89593. return WRC_Abort;
  89594. }
  89595. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  89596. cnt = 1;
  89597. pMatch = 0;
  89598. assert( zTab==0 && zDb==0 );
  89599. if( IN_RENAME_OBJECT ){
  89600. sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
  89601. }
  89602. goto lookupname_end;
  89603. }
  89604. }
  89605. }
  89606. /* Advance to the next name context. The loop will exit when either
  89607. ** we have a match (cnt>0) or when we run out of name contexts.
  89608. */
  89609. if( cnt ) break;
  89610. pNC = pNC->pNext;
  89611. nSubquery++;
  89612. }while( pNC );
  89613. /*
  89614. ** If X and Y are NULL (in other words if only the column name Z is
  89615. ** supplied) and the value of Z is enclosed in double-quotes, then
  89616. ** Z is a string literal if it doesn't match any column names. In that
  89617. ** case, we need to return right away and not make any changes to
  89618. ** pExpr.
  89619. **
  89620. ** Because no reference was made to outer contexts, the pNC->nRef
  89621. ** fields are not changed in any context.
  89622. */
  89623. if( cnt==0 && zTab==0 ){
  89624. assert( pExpr->op==TK_ID );
  89625. if( ExprHasProperty(pExpr,EP_DblQuoted) ){
  89626. /* If a double-quoted identifier does not match any known column name,
  89627. ** then treat it as a string.
  89628. **
  89629. ** This hack was added in the early days of SQLite in a misguided attempt
  89630. ** to be compatible with MySQL 3.x, which used double-quotes for strings.
  89631. ** I now sorely regret putting in this hack. The effect of this hack is
  89632. ** that misspelled identifier names are silently converted into strings
  89633. ** rather than causing an error, to the frustration of countless
  89634. ** programmers. To all those frustrated programmers, my apologies.
  89635. **
  89636. ** Someday, I hope to get rid of this hack. Unfortunately there is
  89637. ** a huge amount of legacy SQL that uses it. So for now, we just
  89638. ** issue a warning.
  89639. */
  89640. sqlite3_log(SQLITE_WARNING,
  89641. "double-quoted string literal: \"%w\"", zCol);
  89642. #ifdef SQLITE_ENABLE_NORMALIZE
  89643. sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
  89644. #endif
  89645. pExpr->op = TK_STRING;
  89646. pExpr->y.pTab = 0;
  89647. return WRC_Prune;
  89648. }
  89649. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  89650. return WRC_Prune;
  89651. }
  89652. }
  89653. /*
  89654. ** cnt==0 means there was not match. cnt>1 means there were two or
  89655. ** more matches. Either way, we have an error.
  89656. */
  89657. if( cnt!=1 ){
  89658. const char *zErr;
  89659. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  89660. if( zDb ){
  89661. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  89662. }else if( zTab ){
  89663. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  89664. }else{
  89665. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  89666. }
  89667. pParse->checkSchema = 1;
  89668. pTopNC->nErr++;
  89669. }
  89670. /* If a column from a table in pSrcList is referenced, then record
  89671. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  89672. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  89673. ** column number is greater than the number of bits in the bitmask
  89674. ** then set the high-order bit of the bitmask.
  89675. */
  89676. if( pExpr->iColumn>=0 && pMatch!=0 ){
  89677. int n = pExpr->iColumn;
  89678. testcase( n==BMS-1 );
  89679. if( n>=BMS ){
  89680. n = BMS-1;
  89681. }
  89682. assert( pMatch->iCursor==pExpr->iTable );
  89683. pMatch->colUsed |= ((Bitmask)1)<<n;
  89684. }
  89685. /* Clean up and return
  89686. */
  89687. sqlite3ExprDelete(db, pExpr->pLeft);
  89688. pExpr->pLeft = 0;
  89689. sqlite3ExprDelete(db, pExpr->pRight);
  89690. pExpr->pRight = 0;
  89691. pExpr->op = eNewExprOp;
  89692. ExprSetProperty(pExpr, EP_Leaf);
  89693. lookupname_end:
  89694. if( cnt==1 ){
  89695. assert( pNC!=0 );
  89696. if( !ExprHasProperty(pExpr, EP_Alias) ){
  89697. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  89698. }
  89699. /* Increment the nRef value on all name contexts from TopNC up to
  89700. ** the point where the name matched. */
  89701. for(;;){
  89702. assert( pTopNC!=0 );
  89703. pTopNC->nRef++;
  89704. if( pTopNC==pNC ) break;
  89705. pTopNC = pTopNC->pNext;
  89706. }
  89707. return WRC_Prune;
  89708. } else {
  89709. return WRC_Abort;
  89710. }
  89711. }
  89712. /*
  89713. ** Allocate and return a pointer to an expression to load the column iCol
  89714. ** from datasource iSrc in SrcList pSrc.
  89715. */
  89716. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  89717. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  89718. if( p ){
  89719. struct SrcList_item *pItem = &pSrc->a[iSrc];
  89720. p->y.pTab = pItem->pTab;
  89721. p->iTable = pItem->iCursor;
  89722. if( p->y.pTab->iPKey==iCol ){
  89723. p->iColumn = -1;
  89724. }else{
  89725. p->iColumn = (ynVar)iCol;
  89726. testcase( iCol==BMS );
  89727. testcase( iCol==BMS-1 );
  89728. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  89729. }
  89730. }
  89731. return p;
  89732. }
  89733. /*
  89734. ** Report an error that an expression is not valid for some set of
  89735. ** pNC->ncFlags values determined by validMask.
  89736. */
  89737. static void notValid(
  89738. Parse *pParse, /* Leave error message here */
  89739. NameContext *pNC, /* The name context */
  89740. const char *zMsg, /* Type of error */
  89741. int validMask /* Set of contexts for which prohibited */
  89742. ){
  89743. assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
  89744. if( (pNC->ncFlags & validMask)!=0 ){
  89745. const char *zIn = "partial index WHERE clauses";
  89746. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  89747. #ifndef SQLITE_OMIT_CHECK
  89748. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  89749. #endif
  89750. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  89751. }
  89752. }
  89753. /*
  89754. ** Expression p should encode a floating point value between 1.0 and 0.0.
  89755. ** Return 1024 times this value. Or return -1 if p is not a floating point
  89756. ** value between 1.0 and 0.0.
  89757. */
  89758. static int exprProbability(Expr *p){
  89759. double r = -1.0;
  89760. if( p->op!=TK_FLOAT ) return -1;
  89761. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  89762. assert( r>=0.0 );
  89763. if( r>1.0 ) return -1;
  89764. return (int)(r*134217728.0);
  89765. }
  89766. /*
  89767. ** This routine is callback for sqlite3WalkExpr().
  89768. **
  89769. ** Resolve symbolic names into TK_COLUMN operators for the current
  89770. ** node in the expression tree. Return 0 to continue the search down
  89771. ** the tree or 2 to abort the tree walk.
  89772. **
  89773. ** This routine also does error checking and name resolution for
  89774. ** function names. The operator for aggregate functions is changed
  89775. ** to TK_AGG_FUNCTION.
  89776. */
  89777. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  89778. NameContext *pNC;
  89779. Parse *pParse;
  89780. pNC = pWalker->u.pNC;
  89781. assert( pNC!=0 );
  89782. pParse = pNC->pParse;
  89783. assert( pParse==pWalker->pParse );
  89784. #ifndef NDEBUG
  89785. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  89786. SrcList *pSrcList = pNC->pSrcList;
  89787. int i;
  89788. for(i=0; i<pNC->pSrcList->nSrc; i++){
  89789. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  89790. }
  89791. }
  89792. #endif
  89793. switch( pExpr->op ){
  89794. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  89795. /* The special operator TK_ROW means use the rowid for the first
  89796. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  89797. ** clause processing on UPDATE and DELETE statements.
  89798. */
  89799. case TK_ROW: {
  89800. SrcList *pSrcList = pNC->pSrcList;
  89801. struct SrcList_item *pItem;
  89802. assert( pSrcList && pSrcList->nSrc==1 );
  89803. pItem = pSrcList->a;
  89804. assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );
  89805. pExpr->op = TK_COLUMN;
  89806. pExpr->y.pTab = pItem->pTab;
  89807. pExpr->iTable = pItem->iCursor;
  89808. pExpr->iColumn = -1;
  89809. pExpr->affinity = SQLITE_AFF_INTEGER;
  89810. break;
  89811. }
  89812. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  89813. && !defined(SQLITE_OMIT_SUBQUERY) */
  89814. /* A column name: ID
  89815. ** Or table name and column name: ID.ID
  89816. ** Or a database, table and column: ID.ID.ID
  89817. **
  89818. ** The TK_ID and TK_OUT cases are combined so that there will only
  89819. ** be one call to lookupName(). Then the compiler will in-line
  89820. ** lookupName() for a size reduction and performance increase.
  89821. */
  89822. case TK_ID:
  89823. case TK_DOT: {
  89824. const char *zColumn;
  89825. const char *zTable;
  89826. const char *zDb;
  89827. Expr *pRight;
  89828. if( pExpr->op==TK_ID ){
  89829. zDb = 0;
  89830. zTable = 0;
  89831. zColumn = pExpr->u.zToken;
  89832. }else{
  89833. Expr *pLeft = pExpr->pLeft;
  89834. notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
  89835. pRight = pExpr->pRight;
  89836. if( pRight->op==TK_ID ){
  89837. zDb = 0;
  89838. }else{
  89839. assert( pRight->op==TK_DOT );
  89840. zDb = pLeft->u.zToken;
  89841. pLeft = pRight->pLeft;
  89842. pRight = pRight->pRight;
  89843. }
  89844. zTable = pLeft->u.zToken;
  89845. zColumn = pRight->u.zToken;
  89846. if( IN_RENAME_OBJECT ){
  89847. sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
  89848. sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
  89849. }
  89850. }
  89851. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  89852. }
  89853. /* Resolve function names
  89854. */
  89855. case TK_FUNCTION: {
  89856. ExprList *pList = pExpr->x.pList; /* The argument list */
  89857. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  89858. int no_such_func = 0; /* True if no such function exists */
  89859. int wrong_num_args = 0; /* True if wrong number of arguments */
  89860. int is_agg = 0; /* True if is an aggregate function */
  89861. int nId; /* Number of characters in function name */
  89862. const char *zId; /* The function name. */
  89863. FuncDef *pDef; /* Information about the function */
  89864. u8 enc = ENC(pParse->db); /* The database encoding */
  89865. int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
  89866. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  89867. zId = pExpr->u.zToken;
  89868. nId = sqlite3Strlen30(zId);
  89869. pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
  89870. if( pDef==0 ){
  89871. pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
  89872. if( pDef==0 ){
  89873. no_such_func = 1;
  89874. }else{
  89875. wrong_num_args = 1;
  89876. }
  89877. }else{
  89878. is_agg = pDef->xFinalize!=0;
  89879. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  89880. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  89881. if( n==2 ){
  89882. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  89883. if( pExpr->iTable<0 ){
  89884. sqlite3ErrorMsg(pParse,
  89885. "second argument to likelihood() must be a "
  89886. "constant between 0.0 and 1.0");
  89887. pNC->nErr++;
  89888. }
  89889. }else{
  89890. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  89891. ** equivalent to likelihood(X, 0.0625).
  89892. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  89893. ** short-hand for likelihood(X,0.0625).
  89894. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  89895. ** for likelihood(X,0.9375).
  89896. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  89897. ** to likelihood(X,0.9375). */
  89898. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  89899. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  89900. }
  89901. }
  89902. #ifndef SQLITE_OMIT_AUTHORIZATION
  89903. {
  89904. int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
  89905. if( auth!=SQLITE_OK ){
  89906. if( auth==SQLITE_DENY ){
  89907. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  89908. pDef->zName);
  89909. pNC->nErr++;
  89910. }
  89911. pExpr->op = TK_NULL;
  89912. return WRC_Prune;
  89913. }
  89914. }
  89915. #endif
  89916. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  89917. /* For the purposes of the EP_ConstFunc flag, date and time
  89918. ** functions and other functions that change slowly are considered
  89919. ** constant because they are constant for the duration of one query */
  89920. ExprSetProperty(pExpr,EP_ConstFunc);
  89921. }
  89922. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  89923. /* Date/time functions that use 'now', and other functions like
  89924. ** sqlite_version() that might change over time cannot be used
  89925. ** in an index. */
  89926. notValid(pParse, pNC, "non-deterministic functions",
  89927. NC_IdxExpr|NC_PartIdx);
  89928. }
  89929. if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
  89930. && pParse->nested==0
  89931. && sqlite3Config.bInternalFunctions==0
  89932. ){
  89933. /* Internal-use-only functions are disallowed unless the
  89934. ** SQL is being compiled using sqlite3NestedParse() */
  89935. no_such_func = 1;
  89936. pDef = 0;
  89937. }
  89938. }
  89939. if( 0==IN_RENAME_OBJECT ){
  89940. #ifndef SQLITE_OMIT_WINDOWFUNC
  89941. assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
  89942. || (pDef->xValue==0 && pDef->xInverse==0)
  89943. || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
  89944. );
  89945. if( pDef && pDef->xValue==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
  89946. sqlite3ErrorMsg(pParse,
  89947. "%.*s() may not be used as a window function", nId, zId
  89948. );
  89949. pNC->nErr++;
  89950. }else if(
  89951. (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
  89952. || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pExpr->y.pWin)
  89953. || (is_agg && pExpr->y.pWin && (pNC->ncFlags & NC_AllowWin)==0)
  89954. ){
  89955. const char *zType;
  89956. if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pExpr->y.pWin ){
  89957. zType = "window";
  89958. }else{
  89959. zType = "aggregate";
  89960. }
  89961. sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId);
  89962. pNC->nErr++;
  89963. is_agg = 0;
  89964. }
  89965. #else
  89966. if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
  89967. sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId);
  89968. pNC->nErr++;
  89969. is_agg = 0;
  89970. }
  89971. #endif
  89972. else if( no_such_func && pParse->db->init.busy==0
  89973. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  89974. && pParse->explain==0
  89975. #endif
  89976. ){
  89977. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  89978. pNC->nErr++;
  89979. }else if( wrong_num_args ){
  89980. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  89981. nId, zId);
  89982. pNC->nErr++;
  89983. }
  89984. if( is_agg ){
  89985. /* Window functions may not be arguments of aggregate functions.
  89986. ** Or arguments of other window functions. But aggregate functions
  89987. ** may be arguments for window functions. */
  89988. #ifndef SQLITE_OMIT_WINDOWFUNC
  89989. pNC->ncFlags &= ~(NC_AllowWin | (!pExpr->y.pWin ? NC_AllowAgg : 0));
  89990. #else
  89991. pNC->ncFlags &= ~NC_AllowAgg;
  89992. #endif
  89993. }
  89994. }
  89995. sqlite3WalkExprList(pWalker, pList);
  89996. if( is_agg ){
  89997. #ifndef SQLITE_OMIT_WINDOWFUNC
  89998. if( pExpr->y.pWin ){
  89999. Select *pSel = pNC->pWinSelect;
  90000. sqlite3WindowUpdate(pParse, pSel->pWinDefn, pExpr->y.pWin, pDef);
  90001. sqlite3WalkExprList(pWalker, pExpr->y.pWin->pPartition);
  90002. sqlite3WalkExprList(pWalker, pExpr->y.pWin->pOrderBy);
  90003. sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
  90004. if( 0==pSel->pWin
  90005. || 0==sqlite3WindowCompare(pParse, pSel->pWin, pExpr->y.pWin)
  90006. ){
  90007. pExpr->y.pWin->pNextWin = pSel->pWin;
  90008. pSel->pWin = pExpr->y.pWin;
  90009. }
  90010. pNC->ncFlags |= NC_HasWin;
  90011. }else
  90012. #endif /* SQLITE_OMIT_WINDOWFUNC */
  90013. {
  90014. NameContext *pNC2 = pNC;
  90015. pExpr->op = TK_AGG_FUNCTION;
  90016. pExpr->op2 = 0;
  90017. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  90018. pExpr->op2++;
  90019. pNC2 = pNC2->pNext;
  90020. }
  90021. assert( pDef!=0 );
  90022. if( pNC2 ){
  90023. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  90024. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  90025. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  90026. }
  90027. }
  90028. pNC->ncFlags |= savedAllowFlags;
  90029. }
  90030. /* FIX ME: Compute pExpr->affinity based on the expected return
  90031. ** type of the function
  90032. */
  90033. return WRC_Prune;
  90034. }
  90035. #ifndef SQLITE_OMIT_SUBQUERY
  90036. case TK_SELECT:
  90037. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  90038. #endif
  90039. case TK_IN: {
  90040. testcase( pExpr->op==TK_IN );
  90041. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  90042. int nRef = pNC->nRef;
  90043. notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  90044. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  90045. assert( pNC->nRef>=nRef );
  90046. if( nRef!=pNC->nRef ){
  90047. ExprSetProperty(pExpr, EP_VarSelect);
  90048. pNC->ncFlags |= NC_VarSelect;
  90049. }
  90050. }
  90051. break;
  90052. }
  90053. case TK_VARIABLE: {
  90054. notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  90055. break;
  90056. }
  90057. case TK_IS:
  90058. case TK_ISNOT: {
  90059. Expr *pRight;
  90060. assert( !ExprHasProperty(pExpr, EP_Reduced) );
  90061. /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
  90062. ** and "x IS NOT FALSE". */
  90063. if( (pRight = pExpr->pRight)->op==TK_ID ){
  90064. int rc = resolveExprStep(pWalker, pRight);
  90065. if( rc==WRC_Abort ) return WRC_Abort;
  90066. if( pRight->op==TK_TRUEFALSE ){
  90067. pExpr->op2 = pExpr->op;
  90068. pExpr->op = TK_TRUTH;
  90069. return WRC_Continue;
  90070. }
  90071. }
  90072. /* Fall thru */
  90073. }
  90074. case TK_BETWEEN:
  90075. case TK_EQ:
  90076. case TK_NE:
  90077. case TK_LT:
  90078. case TK_LE:
  90079. case TK_GT:
  90080. case TK_GE: {
  90081. int nLeft, nRight;
  90082. if( pParse->db->mallocFailed ) break;
  90083. assert( pExpr->pLeft!=0 );
  90084. nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
  90085. if( pExpr->op==TK_BETWEEN ){
  90086. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
  90087. if( nRight==nLeft ){
  90088. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
  90089. }
  90090. }else{
  90091. assert( pExpr->pRight!=0 );
  90092. nRight = sqlite3ExprVectorSize(pExpr->pRight);
  90093. }
  90094. if( nLeft!=nRight ){
  90095. testcase( pExpr->op==TK_EQ );
  90096. testcase( pExpr->op==TK_NE );
  90097. testcase( pExpr->op==TK_LT );
  90098. testcase( pExpr->op==TK_LE );
  90099. testcase( pExpr->op==TK_GT );
  90100. testcase( pExpr->op==TK_GE );
  90101. testcase( pExpr->op==TK_IS );
  90102. testcase( pExpr->op==TK_ISNOT );
  90103. testcase( pExpr->op==TK_BETWEEN );
  90104. sqlite3ErrorMsg(pParse, "row value misused");
  90105. }
  90106. break;
  90107. }
  90108. }
  90109. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  90110. }
  90111. /*
  90112. ** pEList is a list of expressions which are really the result set of the
  90113. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  90114. ** This routine checks to see if pE is a simple identifier which corresponds
  90115. ** to the AS-name of one of the terms of the expression list. If it is,
  90116. ** this routine return an integer between 1 and N where N is the number of
  90117. ** elements in pEList, corresponding to the matching entry. If there is
  90118. ** no match, or if pE is not a simple identifier, then this routine
  90119. ** return 0.
  90120. **
  90121. ** pEList has been resolved. pE has not.
  90122. */
  90123. static int resolveAsName(
  90124. Parse *pParse, /* Parsing context for error messages */
  90125. ExprList *pEList, /* List of expressions to scan */
  90126. Expr *pE /* Expression we are trying to match */
  90127. ){
  90128. int i; /* Loop counter */
  90129. UNUSED_PARAMETER(pParse);
  90130. if( pE->op==TK_ID ){
  90131. char *zCol = pE->u.zToken;
  90132. for(i=0; i<pEList->nExpr; i++){
  90133. char *zAs = pEList->a[i].zName;
  90134. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  90135. return i+1;
  90136. }
  90137. }
  90138. }
  90139. return 0;
  90140. }
  90141. /*
  90142. ** pE is a pointer to an expression which is a single term in the
  90143. ** ORDER BY of a compound SELECT. The expression has not been
  90144. ** name resolved.
  90145. **
  90146. ** At the point this routine is called, we already know that the
  90147. ** ORDER BY term is not an integer index into the result set. That
  90148. ** case is handled by the calling routine.
  90149. **
  90150. ** Attempt to match pE against result set columns in the left-most
  90151. ** SELECT statement. Return the index i of the matching column,
  90152. ** as an indication to the caller that it should sort by the i-th column.
  90153. ** The left-most column is 1. In other words, the value returned is the
  90154. ** same integer value that would be used in the SQL statement to indicate
  90155. ** the column.
  90156. **
  90157. ** If there is no match, return 0. Return -1 if an error occurs.
  90158. */
  90159. static int resolveOrderByTermToExprList(
  90160. Parse *pParse, /* Parsing context for error messages */
  90161. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  90162. Expr *pE /* The specific ORDER BY term */
  90163. ){
  90164. int i; /* Loop counter */
  90165. ExprList *pEList; /* The columns of the result set */
  90166. NameContext nc; /* Name context for resolving pE */
  90167. sqlite3 *db; /* Database connection */
  90168. int rc; /* Return code from subprocedures */
  90169. u8 savedSuppErr; /* Saved value of db->suppressErr */
  90170. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  90171. pEList = pSelect->pEList;
  90172. /* Resolve all names in the ORDER BY term expression
  90173. */
  90174. memset(&nc, 0, sizeof(nc));
  90175. nc.pParse = pParse;
  90176. nc.pSrcList = pSelect->pSrc;
  90177. nc.uNC.pEList = pEList;
  90178. nc.ncFlags = NC_AllowAgg|NC_UEList;
  90179. nc.nErr = 0;
  90180. db = pParse->db;
  90181. savedSuppErr = db->suppressErr;
  90182. db->suppressErr = 1;
  90183. rc = sqlite3ResolveExprNames(&nc, pE);
  90184. db->suppressErr = savedSuppErr;
  90185. if( rc ) return 0;
  90186. /* Try to match the ORDER BY expression against an expression
  90187. ** in the result set. Return an 1-based index of the matching
  90188. ** result-set entry.
  90189. */
  90190. for(i=0; i<pEList->nExpr; i++){
  90191. if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
  90192. return i+1;
  90193. }
  90194. }
  90195. /* If no match, return 0. */
  90196. return 0;
  90197. }
  90198. /*
  90199. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  90200. */
  90201. static void resolveOutOfRangeError(
  90202. Parse *pParse, /* The error context into which to write the error */
  90203. const char *zType, /* "ORDER" or "GROUP" */
  90204. int i, /* The index (1-based) of the term out of range */
  90205. int mx /* Largest permissible value of i */
  90206. ){
  90207. sqlite3ErrorMsg(pParse,
  90208. "%r %s BY term out of range - should be "
  90209. "between 1 and %d", i, zType, mx);
  90210. }
  90211. /*
  90212. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  90213. ** each term of the ORDER BY clause is a constant integer between 1
  90214. ** and N where N is the number of columns in the compound SELECT.
  90215. **
  90216. ** ORDER BY terms that are already an integer between 1 and N are
  90217. ** unmodified. ORDER BY terms that are integers outside the range of
  90218. ** 1 through N generate an error. ORDER BY terms that are expressions
  90219. ** are matched against result set expressions of compound SELECT
  90220. ** beginning with the left-most SELECT and working toward the right.
  90221. ** At the first match, the ORDER BY expression is transformed into
  90222. ** the integer column number.
  90223. **
  90224. ** Return the number of errors seen.
  90225. */
  90226. static int resolveCompoundOrderBy(
  90227. Parse *pParse, /* Parsing context. Leave error messages here */
  90228. Select *pSelect /* The SELECT statement containing the ORDER BY */
  90229. ){
  90230. int i;
  90231. ExprList *pOrderBy;
  90232. ExprList *pEList;
  90233. sqlite3 *db;
  90234. int moreToDo = 1;
  90235. pOrderBy = pSelect->pOrderBy;
  90236. if( pOrderBy==0 ) return 0;
  90237. db = pParse->db;
  90238. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  90239. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  90240. return 1;
  90241. }
  90242. for(i=0; i<pOrderBy->nExpr; i++){
  90243. pOrderBy->a[i].done = 0;
  90244. }
  90245. pSelect->pNext = 0;
  90246. while( pSelect->pPrior ){
  90247. pSelect->pPrior->pNext = pSelect;
  90248. pSelect = pSelect->pPrior;
  90249. }
  90250. while( pSelect && moreToDo ){
  90251. struct ExprList_item *pItem;
  90252. moreToDo = 0;
  90253. pEList = pSelect->pEList;
  90254. assert( pEList!=0 );
  90255. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  90256. int iCol = -1;
  90257. Expr *pE, *pDup;
  90258. if( pItem->done ) continue;
  90259. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  90260. if( sqlite3ExprIsInteger(pE, &iCol) ){
  90261. if( iCol<=0 || iCol>pEList->nExpr ){
  90262. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  90263. return 1;
  90264. }
  90265. }else{
  90266. iCol = resolveAsName(pParse, pEList, pE);
  90267. if( iCol==0 ){
  90268. /* Now test if expression pE matches one of the values returned
  90269. ** by pSelect. In the usual case this is done by duplicating the
  90270. ** expression, resolving any symbols in it, and then comparing
  90271. ** it against each expression returned by the SELECT statement.
  90272. ** Once the comparisons are finished, the duplicate expression
  90273. ** is deleted.
  90274. **
  90275. ** Or, if this is running as part of an ALTER TABLE operation,
  90276. ** resolve the symbols in the actual expression, not a duplicate.
  90277. ** And, if one of the comparisons is successful, leave the expression
  90278. ** as is instead of transforming it to an integer as in the usual
  90279. ** case. This allows the code in alter.c to modify column
  90280. ** refererences within the ORDER BY expression as required. */
  90281. if( IN_RENAME_OBJECT ){
  90282. pDup = pE;
  90283. }else{
  90284. pDup = sqlite3ExprDup(db, pE, 0);
  90285. }
  90286. if( !db->mallocFailed ){
  90287. assert(pDup);
  90288. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  90289. }
  90290. if( !IN_RENAME_OBJECT ){
  90291. sqlite3ExprDelete(db, pDup);
  90292. }
  90293. }
  90294. }
  90295. if( iCol>0 ){
  90296. /* Convert the ORDER BY term into an integer column number iCol,
  90297. ** taking care to preserve the COLLATE clause if it exists */
  90298. if( !IN_RENAME_OBJECT ){
  90299. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  90300. if( pNew==0 ) return 1;
  90301. pNew->flags |= EP_IntValue;
  90302. pNew->u.iValue = iCol;
  90303. if( pItem->pExpr==pE ){
  90304. pItem->pExpr = pNew;
  90305. }else{
  90306. Expr *pParent = pItem->pExpr;
  90307. assert( pParent->op==TK_COLLATE );
  90308. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  90309. assert( pParent->pLeft==pE );
  90310. pParent->pLeft = pNew;
  90311. }
  90312. sqlite3ExprDelete(db, pE);
  90313. pItem->u.x.iOrderByCol = (u16)iCol;
  90314. }
  90315. pItem->done = 1;
  90316. }else{
  90317. moreToDo = 1;
  90318. }
  90319. }
  90320. pSelect = pSelect->pNext;
  90321. }
  90322. for(i=0; i<pOrderBy->nExpr; i++){
  90323. if( pOrderBy->a[i].done==0 ){
  90324. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  90325. "column in the result set", i+1);
  90326. return 1;
  90327. }
  90328. }
  90329. return 0;
  90330. }
  90331. /*
  90332. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  90333. ** the SELECT statement pSelect. If any term is reference to a
  90334. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  90335. ** field) then convert that term into a copy of the corresponding result set
  90336. ** column.
  90337. **
  90338. ** If any errors are detected, add an error message to pParse and
  90339. ** return non-zero. Return zero if no errors are seen.
  90340. */
  90341. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  90342. Parse *pParse, /* Parsing context. Leave error messages here */
  90343. Select *pSelect, /* The SELECT statement containing the clause */
  90344. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  90345. const char *zType /* "ORDER" or "GROUP" */
  90346. ){
  90347. int i;
  90348. sqlite3 *db = pParse->db;
  90349. ExprList *pEList;
  90350. struct ExprList_item *pItem;
  90351. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  90352. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  90353. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  90354. return 1;
  90355. }
  90356. pEList = pSelect->pEList;
  90357. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  90358. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  90359. if( pItem->u.x.iOrderByCol ){
  90360. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  90361. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  90362. return 1;
  90363. }
  90364. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  90365. zType,0);
  90366. }
  90367. }
  90368. return 0;
  90369. }
  90370. #ifndef SQLITE_OMIT_WINDOWFUNC
  90371. /*
  90372. ** Walker callback for resolveRemoveWindows().
  90373. */
  90374. static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
  90375. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  90376. Window **pp;
  90377. for(pp=&pWalker->u.pSelect->pWin; *pp; pp=&(*pp)->pNextWin){
  90378. if( *pp==pExpr->y.pWin ){
  90379. *pp = (*pp)->pNextWin;
  90380. break;
  90381. }
  90382. }
  90383. }
  90384. return WRC_Continue;
  90385. }
  90386. /*
  90387. ** Remove any Window objects owned by the expression pExpr from the
  90388. ** Select.pWin list of Select object pSelect.
  90389. */
  90390. static void resolveRemoveWindows(Select *pSelect, Expr *pExpr){
  90391. Walker sWalker;
  90392. memset(&sWalker, 0, sizeof(Walker));
  90393. sWalker.xExprCallback = resolveRemoveWindowsCb;
  90394. sWalker.u.pSelect = pSelect;
  90395. sqlite3WalkExpr(&sWalker, pExpr);
  90396. }
  90397. #else
  90398. # define resolveRemoveWindows(x,y)
  90399. #endif
  90400. /*
  90401. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  90402. ** The Name context of the SELECT statement is pNC. zType is either
  90403. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  90404. **
  90405. ** This routine resolves each term of the clause into an expression.
  90406. ** If the order-by term is an integer I between 1 and N (where N is the
  90407. ** number of columns in the result set of the SELECT) then the expression
  90408. ** in the resolution is a copy of the I-th result-set expression. If
  90409. ** the order-by term is an identifier that corresponds to the AS-name of
  90410. ** a result-set expression, then the term resolves to a copy of the
  90411. ** result-set expression. Otherwise, the expression is resolved in
  90412. ** the usual way - using sqlite3ResolveExprNames().
  90413. **
  90414. ** This routine returns the number of errors. If errors occur, then
  90415. ** an appropriate error message might be left in pParse. (OOM errors
  90416. ** excepted.)
  90417. */
  90418. static int resolveOrderGroupBy(
  90419. NameContext *pNC, /* The name context of the SELECT statement */
  90420. Select *pSelect, /* The SELECT statement holding pOrderBy */
  90421. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  90422. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  90423. ){
  90424. int i, j; /* Loop counters */
  90425. int iCol; /* Column number */
  90426. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  90427. Parse *pParse; /* Parsing context */
  90428. int nResult; /* Number of terms in the result set */
  90429. if( pOrderBy==0 ) return 0;
  90430. nResult = pSelect->pEList->nExpr;
  90431. pParse = pNC->pParse;
  90432. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  90433. Expr *pE = pItem->pExpr;
  90434. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  90435. if( zType[0]!='G' ){
  90436. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  90437. if( iCol>0 ){
  90438. /* If an AS-name match is found, mark this ORDER BY column as being
  90439. ** a copy of the iCol-th result-set column. The subsequent call to
  90440. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  90441. ** copy of the iCol-th result-set expression. */
  90442. pItem->u.x.iOrderByCol = (u16)iCol;
  90443. continue;
  90444. }
  90445. }
  90446. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  90447. /* The ORDER BY term is an integer constant. Again, set the column
  90448. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  90449. ** order-by term to a copy of the result-set expression */
  90450. if( iCol<1 || iCol>0xffff ){
  90451. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  90452. return 1;
  90453. }
  90454. pItem->u.x.iOrderByCol = (u16)iCol;
  90455. continue;
  90456. }
  90457. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  90458. pItem->u.x.iOrderByCol = 0;
  90459. if( sqlite3ResolveExprNames(pNC, pE) ){
  90460. return 1;
  90461. }
  90462. for(j=0; j<pSelect->pEList->nExpr; j++){
  90463. if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  90464. /* Since this expresion is being changed into a reference
  90465. ** to an identical expression in the result set, remove all Window
  90466. ** objects belonging to the expression from the Select.pWin list. */
  90467. resolveRemoveWindows(pSelect, pE);
  90468. pItem->u.x.iOrderByCol = j+1;
  90469. }
  90470. }
  90471. }
  90472. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  90473. }
  90474. /*
  90475. ** Resolve names in the SELECT statement p and all of its descendants.
  90476. */
  90477. static int resolveSelectStep(Walker *pWalker, Select *p){
  90478. NameContext *pOuterNC; /* Context that contains this SELECT */
  90479. NameContext sNC; /* Name context of this SELECT */
  90480. int isCompound; /* True if p is a compound select */
  90481. int nCompound; /* Number of compound terms processed so far */
  90482. Parse *pParse; /* Parsing context */
  90483. int i; /* Loop counter */
  90484. ExprList *pGroupBy; /* The GROUP BY clause */
  90485. Select *pLeftmost; /* Left-most of SELECT of a compound */
  90486. sqlite3 *db; /* Database connection */
  90487. assert( p!=0 );
  90488. if( p->selFlags & SF_Resolved ){
  90489. return WRC_Prune;
  90490. }
  90491. pOuterNC = pWalker->u.pNC;
  90492. pParse = pWalker->pParse;
  90493. db = pParse->db;
  90494. /* Normally sqlite3SelectExpand() will be called first and will have
  90495. ** already expanded this SELECT. However, if this is a subquery within
  90496. ** an expression, sqlite3ResolveExprNames() will be called without a
  90497. ** prior call to sqlite3SelectExpand(). When that happens, let
  90498. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  90499. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  90500. ** this routine in the correct order.
  90501. */
  90502. if( (p->selFlags & SF_Expanded)==0 ){
  90503. sqlite3SelectPrep(pParse, p, pOuterNC);
  90504. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  90505. }
  90506. isCompound = p->pPrior!=0;
  90507. nCompound = 0;
  90508. pLeftmost = p;
  90509. while( p ){
  90510. assert( (p->selFlags & SF_Expanded)!=0 );
  90511. assert( (p->selFlags & SF_Resolved)==0 );
  90512. p->selFlags |= SF_Resolved;
  90513. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  90514. ** are not allowed to refer to any names, so pass an empty NameContext.
  90515. */
  90516. memset(&sNC, 0, sizeof(sNC));
  90517. sNC.pParse = pParse;
  90518. sNC.pWinSelect = p;
  90519. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
  90520. return WRC_Abort;
  90521. }
  90522. /* If the SF_Converted flags is set, then this Select object was
  90523. ** was created by the convertCompoundSelectToSubquery() function.
  90524. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  90525. ** as if it were part of the sub-query, not the parent. This block
  90526. ** moves the pOrderBy down to the sub-query. It will be moved back
  90527. ** after the names have been resolved. */
  90528. if( p->selFlags & SF_Converted ){
  90529. Select *pSub = p->pSrc->a[0].pSelect;
  90530. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  90531. assert( pSub->pPrior && pSub->pOrderBy==0 );
  90532. pSub->pOrderBy = p->pOrderBy;
  90533. p->pOrderBy = 0;
  90534. }
  90535. /* Recursively resolve names in all subqueries
  90536. */
  90537. for(i=0; i<p->pSrc->nSrc; i++){
  90538. struct SrcList_item *pItem = &p->pSrc->a[i];
  90539. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
  90540. NameContext *pNC; /* Used to iterate name contexts */
  90541. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  90542. const char *zSavedContext = pParse->zAuthContext;
  90543. /* Count the total number of references to pOuterNC and all of its
  90544. ** parent contexts. After resolving references to expressions in
  90545. ** pItem->pSelect, check if this value has changed. If so, then
  90546. ** SELECT statement pItem->pSelect must be correlated. Set the
  90547. ** pItem->fg.isCorrelated flag if this is the case. */
  90548. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  90549. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  90550. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  90551. pParse->zAuthContext = zSavedContext;
  90552. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  90553. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  90554. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  90555. pItem->fg.isCorrelated = (nRef!=0);
  90556. }
  90557. }
  90558. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  90559. ** resolve the result-set expression list.
  90560. */
  90561. sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
  90562. sNC.pSrcList = p->pSrc;
  90563. sNC.pNext = pOuterNC;
  90564. /* Resolve names in the result set. */
  90565. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  90566. sNC.ncFlags &= ~NC_AllowWin;
  90567. /* If there are no aggregate functions in the result-set, and no GROUP BY
  90568. ** expression, do not allow aggregates in any of the other expressions.
  90569. */
  90570. assert( (p->selFlags & SF_Aggregate)==0 );
  90571. pGroupBy = p->pGroupBy;
  90572. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  90573. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  90574. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  90575. }else{
  90576. sNC.ncFlags &= ~NC_AllowAgg;
  90577. }
  90578. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  90579. */
  90580. if( p->pHaving && !pGroupBy ){
  90581. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  90582. return WRC_Abort;
  90583. }
  90584. /* Add the output column list to the name-context before parsing the
  90585. ** other expressions in the SELECT statement. This is so that
  90586. ** expressions in the WHERE clause (etc.) can refer to expressions by
  90587. ** aliases in the result set.
  90588. **
  90589. ** Minor point: If this is the case, then the expression will be
  90590. ** re-evaluated for each reference to it.
  90591. */
  90592. assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 );
  90593. sNC.uNC.pEList = p->pEList;
  90594. sNC.ncFlags |= NC_UEList;
  90595. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  90596. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  90597. /* Resolve names in table-valued-function arguments */
  90598. for(i=0; i<p->pSrc->nSrc; i++){
  90599. struct SrcList_item *pItem = &p->pSrc->a[i];
  90600. if( pItem->fg.isTabFunc
  90601. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  90602. ){
  90603. return WRC_Abort;
  90604. }
  90605. }
  90606. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  90607. ** outer queries
  90608. */
  90609. sNC.pNext = 0;
  90610. sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
  90611. /* If this is a converted compound query, move the ORDER BY clause from
  90612. ** the sub-query back to the parent query. At this point each term
  90613. ** within the ORDER BY clause has been transformed to an integer value.
  90614. ** These integers will be replaced by copies of the corresponding result
  90615. ** set expressions by the call to resolveOrderGroupBy() below. */
  90616. if( p->selFlags & SF_Converted ){
  90617. Select *pSub = p->pSrc->a[0].pSelect;
  90618. p->pOrderBy = pSub->pOrderBy;
  90619. pSub->pOrderBy = 0;
  90620. }
  90621. /* Process the ORDER BY clause for singleton SELECT statements.
  90622. ** The ORDER BY clause for compounds SELECT statements is handled
  90623. ** below, after all of the result-sets for all of the elements of
  90624. ** the compound have been resolved.
  90625. **
  90626. ** If there is an ORDER BY clause on a term of a compound-select other
  90627. ** than the right-most term, then that is a syntax error. But the error
  90628. ** is not detected until much later, and so we need to go ahead and
  90629. ** resolve those symbols on the incorrect ORDER BY for consistency.
  90630. */
  90631. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  90632. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  90633. ){
  90634. return WRC_Abort;
  90635. }
  90636. if( db->mallocFailed ){
  90637. return WRC_Abort;
  90638. }
  90639. sNC.ncFlags &= ~NC_AllowWin;
  90640. /* Resolve the GROUP BY clause. At the same time, make sure
  90641. ** the GROUP BY clause does not contain aggregate functions.
  90642. */
  90643. if( pGroupBy ){
  90644. struct ExprList_item *pItem;
  90645. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  90646. return WRC_Abort;
  90647. }
  90648. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  90649. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  90650. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  90651. "the GROUP BY clause");
  90652. return WRC_Abort;
  90653. }
  90654. }
  90655. }
  90656. #ifndef SQLITE_OMIT_WINDOWFUNC
  90657. if( IN_RENAME_OBJECT ){
  90658. Window *pWin;
  90659. for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
  90660. if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
  90661. || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
  90662. ){
  90663. return WRC_Abort;
  90664. }
  90665. }
  90666. }
  90667. #endif
  90668. /* If this is part of a compound SELECT, check that it has the right
  90669. ** number of expressions in the select list. */
  90670. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  90671. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  90672. return WRC_Abort;
  90673. }
  90674. /* Advance to the next term of the compound
  90675. */
  90676. p = p->pPrior;
  90677. nCompound++;
  90678. }
  90679. /* Resolve the ORDER BY on a compound SELECT after all terms of
  90680. ** the compound have been resolved.
  90681. */
  90682. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  90683. return WRC_Abort;
  90684. }
  90685. return WRC_Prune;
  90686. }
  90687. /*
  90688. ** This routine walks an expression tree and resolves references to
  90689. ** table columns and result-set columns. At the same time, do error
  90690. ** checking on function usage and set a flag if any aggregate functions
  90691. ** are seen.
  90692. **
  90693. ** To resolve table columns references we look for nodes (or subtrees) of the
  90694. ** form X.Y.Z or Y.Z or just Z where
  90695. **
  90696. ** X: The name of a database. Ex: "main" or "temp" or
  90697. ** the symbolic name assigned to an ATTACH-ed database.
  90698. **
  90699. ** Y: The name of a table in a FROM clause. Or in a trigger
  90700. ** one of the special names "old" or "new".
  90701. **
  90702. ** Z: The name of a column in table Y.
  90703. **
  90704. ** The node at the root of the subtree is modified as follows:
  90705. **
  90706. ** Expr.op Changed to TK_COLUMN
  90707. ** Expr.pTab Points to the Table object for X.Y
  90708. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  90709. ** Expr.iTable The VDBE cursor number for X.Y
  90710. **
  90711. **
  90712. ** To resolve result-set references, look for expression nodes of the
  90713. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  90714. ** size of an AS clause in the result-set of a SELECT. The Z expression
  90715. ** is replaced by a copy of the left-hand side of the result-set expression.
  90716. ** Table-name and function resolution occurs on the substituted expression
  90717. ** tree. For example, in:
  90718. **
  90719. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  90720. **
  90721. ** The "x" term of the order by is replaced by "a+b" to render:
  90722. **
  90723. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  90724. **
  90725. ** Function calls are checked to make sure that the function is
  90726. ** defined and that the correct number of arguments are specified.
  90727. ** If the function is an aggregate function, then the NC_HasAgg flag is
  90728. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  90729. ** If an expression contains aggregate functions then the EP_Agg
  90730. ** property on the expression is set.
  90731. **
  90732. ** An error message is left in pParse if anything is amiss. The number
  90733. ** if errors is returned.
  90734. */
  90735. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  90736. NameContext *pNC, /* Namespace to resolve expressions in. */
  90737. Expr *pExpr /* The expression to be analyzed. */
  90738. ){
  90739. u16 savedHasAgg;
  90740. Walker w;
  90741. if( pExpr==0 ) return SQLITE_OK;
  90742. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
  90743. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
  90744. w.pParse = pNC->pParse;
  90745. w.xExprCallback = resolveExprStep;
  90746. w.xSelectCallback = resolveSelectStep;
  90747. w.xSelectCallback2 = 0;
  90748. w.u.pNC = pNC;
  90749. #if SQLITE_MAX_EXPR_DEPTH>0
  90750. w.pParse->nHeight += pExpr->nHeight;
  90751. if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
  90752. return SQLITE_ERROR;
  90753. }
  90754. #endif
  90755. sqlite3WalkExpr(&w, pExpr);
  90756. #if SQLITE_MAX_EXPR_DEPTH>0
  90757. w.pParse->nHeight -= pExpr->nHeight;
  90758. #endif
  90759. assert( EP_Agg==NC_HasAgg );
  90760. assert( EP_Win==NC_HasWin );
  90761. testcase( pNC->ncFlags & NC_HasAgg );
  90762. testcase( pNC->ncFlags & NC_HasWin );
  90763. ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
  90764. pNC->ncFlags |= savedHasAgg;
  90765. return pNC->nErr>0 || w.pParse->nErr>0;
  90766. }
  90767. /*
  90768. ** Resolve all names for all expression in an expression list. This is
  90769. ** just like sqlite3ResolveExprNames() except that it works for an expression
  90770. ** list rather than a single expression.
  90771. */
  90772. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  90773. NameContext *pNC, /* Namespace to resolve expressions in. */
  90774. ExprList *pList /* The expression list to be analyzed. */
  90775. ){
  90776. int i;
  90777. if( pList ){
  90778. for(i=0; i<pList->nExpr; i++){
  90779. if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
  90780. }
  90781. }
  90782. return WRC_Continue;
  90783. }
  90784. /*
  90785. ** Resolve all names in all expressions of a SELECT and in all
  90786. ** decendents of the SELECT, including compounds off of p->pPrior,
  90787. ** subqueries in expressions, and subqueries used as FROM clause
  90788. ** terms.
  90789. **
  90790. ** See sqlite3ResolveExprNames() for a description of the kinds of
  90791. ** transformations that occur.
  90792. **
  90793. ** All SELECT statements should have been expanded using
  90794. ** sqlite3SelectExpand() prior to invoking this routine.
  90795. */
  90796. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  90797. Parse *pParse, /* The parser context */
  90798. Select *p, /* The SELECT statement being coded. */
  90799. NameContext *pOuterNC /* Name context for parent SELECT statement */
  90800. ){
  90801. Walker w;
  90802. assert( p!=0 );
  90803. w.xExprCallback = resolveExprStep;
  90804. w.xSelectCallback = resolveSelectStep;
  90805. w.xSelectCallback2 = 0;
  90806. w.pParse = pParse;
  90807. w.u.pNC = pOuterNC;
  90808. sqlite3WalkSelect(&w, p);
  90809. }
  90810. /*
  90811. ** Resolve names in expressions that can only reference a single table
  90812. ** or which cannot reference any tables at all. Examples:
  90813. **
  90814. ** (1) CHECK constraints
  90815. ** (2) WHERE clauses on partial indices
  90816. ** (3) Expressions in indexes on expressions
  90817. ** (4) Expression arguments to VACUUM INTO.
  90818. **
  90819. ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
  90820. ** nodes of the expression is set to -1 and the Expr.iColumn value is
  90821. ** set to the column number. In case (4), TK_COLUMN nodes cause an error.
  90822. **
  90823. ** Any errors cause an error message to be set in pParse.
  90824. */
  90825. SQLITE_PRIVATE int sqlite3ResolveSelfReference(
  90826. Parse *pParse, /* Parsing context */
  90827. Table *pTab, /* The table being referenced, or NULL */
  90828. int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr, or 0 */
  90829. Expr *pExpr, /* Expression to resolve. May be NULL. */
  90830. ExprList *pList /* Expression list to resolve. May be NULL. */
  90831. ){
  90832. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  90833. NameContext sNC; /* Name context for pParse->pNewTable */
  90834. int rc;
  90835. assert( type==0 || pTab!=0 );
  90836. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr || pTab==0 );
  90837. memset(&sNC, 0, sizeof(sNC));
  90838. memset(&sSrc, 0, sizeof(sSrc));
  90839. if( pTab ){
  90840. sSrc.nSrc = 1;
  90841. sSrc.a[0].zName = pTab->zName;
  90842. sSrc.a[0].pTab = pTab;
  90843. sSrc.a[0].iCursor = -1;
  90844. }
  90845. sNC.pParse = pParse;
  90846. sNC.pSrcList = &sSrc;
  90847. sNC.ncFlags = type;
  90848. if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
  90849. if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
  90850. return rc;
  90851. }
  90852. /************** End of resolve.c *********************************************/
  90853. /************** Begin file expr.c ********************************************/
  90854. /*
  90855. ** 2001 September 15
  90856. **
  90857. ** The author disclaims copyright to this source code. In place of
  90858. ** a legal notice, here is a blessing:
  90859. **
  90860. ** May you do good and not evil.
  90861. ** May you find forgiveness for yourself and forgive others.
  90862. ** May you share freely, never taking more than you give.
  90863. **
  90864. *************************************************************************
  90865. ** This file contains routines used for analyzing expressions and
  90866. ** for generating VDBE code that evaluates expressions in SQLite.
  90867. */
  90868. /* #include "sqliteInt.h" */
  90869. /* Forward declarations */
  90870. static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
  90871. static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
  90872. /*
  90873. ** Return the affinity character for a single column of a table.
  90874. */
  90875. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
  90876. assert( iCol<pTab->nCol );
  90877. return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  90878. }
  90879. /*
  90880. ** Return the 'affinity' of the expression pExpr if any.
  90881. **
  90882. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  90883. ** or a sub-select with a column as the return value, then the
  90884. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  90885. ** indicating no affinity for the expression.
  90886. **
  90887. ** i.e. the WHERE clause expressions in the following statements all
  90888. ** have an affinity:
  90889. **
  90890. ** CREATE TABLE t1(a);
  90891. ** SELECT * FROM t1 WHERE a;
  90892. ** SELECT a AS b FROM t1 WHERE b;
  90893. ** SELECT * FROM t1 WHERE (select a from t1);
  90894. */
  90895. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  90896. int op;
  90897. pExpr = sqlite3ExprSkipCollate(pExpr);
  90898. if( pExpr->flags & EP_Generic ) return 0;
  90899. op = pExpr->op;
  90900. if( op==TK_SELECT ){
  90901. assert( pExpr->flags&EP_xIsSelect );
  90902. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  90903. }
  90904. if( op==TK_REGISTER ) op = pExpr->op2;
  90905. #ifndef SQLITE_OMIT_CAST
  90906. if( op==TK_CAST ){
  90907. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  90908. return sqlite3AffinityType(pExpr->u.zToken, 0);
  90909. }
  90910. #endif
  90911. if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
  90912. return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
  90913. }
  90914. if( op==TK_SELECT_COLUMN ){
  90915. assert( pExpr->pLeft->flags&EP_xIsSelect );
  90916. return sqlite3ExprAffinity(
  90917. pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
  90918. );
  90919. }
  90920. return pExpr->affinity;
  90921. }
  90922. /*
  90923. ** Set the collating sequence for expression pExpr to be the collating
  90924. ** sequence named by pToken. Return a pointer to a new Expr node that
  90925. ** implements the COLLATE operator.
  90926. **
  90927. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  90928. ** and the pExpr parameter is returned unchanged.
  90929. */
  90930. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  90931. Parse *pParse, /* Parsing context */
  90932. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  90933. const Token *pCollName, /* Name of collating sequence */
  90934. int dequote /* True to dequote pCollName */
  90935. ){
  90936. if( pCollName->n>0 ){
  90937. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  90938. if( pNew ){
  90939. pNew->pLeft = pExpr;
  90940. pNew->flags |= EP_Collate|EP_Skip;
  90941. pExpr = pNew;
  90942. }
  90943. }
  90944. return pExpr;
  90945. }
  90946. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  90947. Token s;
  90948. assert( zC!=0 );
  90949. sqlite3TokenInit(&s, (char*)zC);
  90950. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  90951. }
  90952. /*
  90953. ** Skip over any TK_COLLATE operators and any unlikely()
  90954. ** or likelihood() function at the root of an expression.
  90955. */
  90956. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  90957. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  90958. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  90959. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  90960. assert( pExpr->x.pList->nExpr>0 );
  90961. assert( pExpr->op==TK_FUNCTION );
  90962. pExpr = pExpr->x.pList->a[0].pExpr;
  90963. }else{
  90964. assert( pExpr->op==TK_COLLATE );
  90965. pExpr = pExpr->pLeft;
  90966. }
  90967. }
  90968. return pExpr;
  90969. }
  90970. /*
  90971. ** Return the collation sequence for the expression pExpr. If
  90972. ** there is no defined collating sequence, return NULL.
  90973. **
  90974. ** See also: sqlite3ExprNNCollSeq()
  90975. **
  90976. ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
  90977. ** default collation if pExpr has no defined collation.
  90978. **
  90979. ** The collating sequence might be determined by a COLLATE operator
  90980. ** or by the presence of a column with a defined collating sequence.
  90981. ** COLLATE operators take first precedence. Left operands take
  90982. ** precedence over right operands.
  90983. */
  90984. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  90985. sqlite3 *db = pParse->db;
  90986. CollSeq *pColl = 0;
  90987. Expr *p = pExpr;
  90988. while( p ){
  90989. int op = p->op;
  90990. if( p->flags & EP_Generic ) break;
  90991. if( op==TK_REGISTER ) op = p->op2;
  90992. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
  90993. && p->y.pTab!=0
  90994. ){
  90995. /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
  90996. ** a TK_COLUMN but was previously evaluated and cached in a register */
  90997. int j = p->iColumn;
  90998. if( j>=0 ){
  90999. const char *zColl = p->y.pTab->aCol[j].zColl;
  91000. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  91001. }
  91002. break;
  91003. }
  91004. if( op==TK_CAST || op==TK_UPLUS ){
  91005. p = p->pLeft;
  91006. continue;
  91007. }
  91008. if( op==TK_COLLATE ){
  91009. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  91010. break;
  91011. }
  91012. if( p->flags & EP_Collate ){
  91013. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  91014. p = p->pLeft;
  91015. }else{
  91016. Expr *pNext = p->pRight;
  91017. /* The Expr.x union is never used at the same time as Expr.pRight */
  91018. assert( p->x.pList==0 || p->pRight==0 );
  91019. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  91020. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  91021. ** least one EP_Collate. Thus the following two ALWAYS. */
  91022. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  91023. int i;
  91024. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  91025. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  91026. pNext = p->x.pList->a[i].pExpr;
  91027. break;
  91028. }
  91029. }
  91030. }
  91031. p = pNext;
  91032. }
  91033. }else{
  91034. break;
  91035. }
  91036. }
  91037. if( sqlite3CheckCollSeq(pParse, pColl) ){
  91038. pColl = 0;
  91039. }
  91040. return pColl;
  91041. }
  91042. /*
  91043. ** Return the collation sequence for the expression pExpr. If
  91044. ** there is no defined collating sequence, return a pointer to the
  91045. ** defautl collation sequence.
  91046. **
  91047. ** See also: sqlite3ExprCollSeq()
  91048. **
  91049. ** The sqlite3ExprCollSeq() routine works the same except that it
  91050. ** returns NULL if there is no defined collation.
  91051. */
  91052. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
  91053. CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
  91054. if( p==0 ) p = pParse->db->pDfltColl;
  91055. assert( p!=0 );
  91056. return p;
  91057. }
  91058. /*
  91059. ** Return TRUE if the two expressions have equivalent collating sequences.
  91060. */
  91061. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
  91062. CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
  91063. CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
  91064. return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
  91065. }
  91066. /*
  91067. ** pExpr is an operand of a comparison operator. aff2 is the
  91068. ** type affinity of the other operand. This routine returns the
  91069. ** type affinity that should be used for the comparison operator.
  91070. */
  91071. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  91072. char aff1 = sqlite3ExprAffinity(pExpr);
  91073. if( aff1 && aff2 ){
  91074. /* Both sides of the comparison are columns. If one has numeric
  91075. ** affinity, use that. Otherwise use no affinity.
  91076. */
  91077. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  91078. return SQLITE_AFF_NUMERIC;
  91079. }else{
  91080. return SQLITE_AFF_BLOB;
  91081. }
  91082. }else if( !aff1 && !aff2 ){
  91083. /* Neither side of the comparison is a column. Compare the
  91084. ** results directly.
  91085. */
  91086. return SQLITE_AFF_BLOB;
  91087. }else{
  91088. /* One side is a column, the other is not. Use the columns affinity. */
  91089. assert( aff1==0 || aff2==0 );
  91090. return (aff1 + aff2);
  91091. }
  91092. }
  91093. /*
  91094. ** pExpr is a comparison operator. Return the type affinity that should
  91095. ** be applied to both operands prior to doing the comparison.
  91096. */
  91097. static char comparisonAffinity(Expr *pExpr){
  91098. char aff;
  91099. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  91100. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  91101. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  91102. assert( pExpr->pLeft );
  91103. aff = sqlite3ExprAffinity(pExpr->pLeft);
  91104. if( pExpr->pRight ){
  91105. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  91106. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  91107. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  91108. }else if( aff==0 ){
  91109. aff = SQLITE_AFF_BLOB;
  91110. }
  91111. return aff;
  91112. }
  91113. /*
  91114. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  91115. ** idx_affinity is the affinity of an indexed column. Return true
  91116. ** if the index with affinity idx_affinity may be used to implement
  91117. ** the comparison in pExpr.
  91118. */
  91119. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  91120. char aff = comparisonAffinity(pExpr);
  91121. switch( aff ){
  91122. case SQLITE_AFF_BLOB:
  91123. return 1;
  91124. case SQLITE_AFF_TEXT:
  91125. return idx_affinity==SQLITE_AFF_TEXT;
  91126. default:
  91127. return sqlite3IsNumericAffinity(idx_affinity);
  91128. }
  91129. }
  91130. /*
  91131. ** Return the P5 value that should be used for a binary comparison
  91132. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  91133. */
  91134. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  91135. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  91136. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  91137. return aff;
  91138. }
  91139. /*
  91140. ** Return a pointer to the collation sequence that should be used by
  91141. ** a binary comparison operator comparing pLeft and pRight.
  91142. **
  91143. ** If the left hand expression has a collating sequence type, then it is
  91144. ** used. Otherwise the collation sequence for the right hand expression
  91145. ** is used, or the default (BINARY) if neither expression has a collating
  91146. ** type.
  91147. **
  91148. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  91149. ** it is not considered.
  91150. */
  91151. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  91152. Parse *pParse,
  91153. Expr *pLeft,
  91154. Expr *pRight
  91155. ){
  91156. CollSeq *pColl;
  91157. assert( pLeft );
  91158. if( pLeft->flags & EP_Collate ){
  91159. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  91160. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  91161. pColl = sqlite3ExprCollSeq(pParse, pRight);
  91162. }else{
  91163. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  91164. if( !pColl ){
  91165. pColl = sqlite3ExprCollSeq(pParse, pRight);
  91166. }
  91167. }
  91168. return pColl;
  91169. }
  91170. /*
  91171. ** Generate code for a comparison operator.
  91172. */
  91173. static int codeCompare(
  91174. Parse *pParse, /* The parsing (and code generating) context */
  91175. Expr *pLeft, /* The left operand */
  91176. Expr *pRight, /* The right operand */
  91177. int opcode, /* The comparison opcode */
  91178. int in1, int in2, /* Register holding operands */
  91179. int dest, /* Jump here if true. */
  91180. int jumpIfNull /* If true, jump if either operand is NULL */
  91181. ){
  91182. int p5;
  91183. int addr;
  91184. CollSeq *p4;
  91185. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  91186. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  91187. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  91188. (void*)p4, P4_COLLSEQ);
  91189. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  91190. return addr;
  91191. }
  91192. /*
  91193. ** Return true if expression pExpr is a vector, or false otherwise.
  91194. **
  91195. ** A vector is defined as any expression that results in two or more
  91196. ** columns of result. Every TK_VECTOR node is an vector because the
  91197. ** parser will not generate a TK_VECTOR with fewer than two entries.
  91198. ** But a TK_SELECT might be either a vector or a scalar. It is only
  91199. ** considered a vector if it has two or more result columns.
  91200. */
  91201. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
  91202. return sqlite3ExprVectorSize(pExpr)>1;
  91203. }
  91204. /*
  91205. ** If the expression passed as the only argument is of type TK_VECTOR
  91206. ** return the number of expressions in the vector. Or, if the expression
  91207. ** is a sub-select, return the number of columns in the sub-select. For
  91208. ** any other type of expression, return 1.
  91209. */
  91210. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
  91211. u8 op = pExpr->op;
  91212. if( op==TK_REGISTER ) op = pExpr->op2;
  91213. if( op==TK_VECTOR ){
  91214. return pExpr->x.pList->nExpr;
  91215. }else if( op==TK_SELECT ){
  91216. return pExpr->x.pSelect->pEList->nExpr;
  91217. }else{
  91218. return 1;
  91219. }
  91220. }
  91221. /*
  91222. ** Return a pointer to a subexpression of pVector that is the i-th
  91223. ** column of the vector (numbered starting with 0). The caller must
  91224. ** ensure that i is within range.
  91225. **
  91226. ** If pVector is really a scalar (and "scalar" here includes subqueries
  91227. ** that return a single column!) then return pVector unmodified.
  91228. **
  91229. ** pVector retains ownership of the returned subexpression.
  91230. **
  91231. ** If the vector is a (SELECT ...) then the expression returned is
  91232. ** just the expression for the i-th term of the result set, and may
  91233. ** not be ready for evaluation because the table cursor has not yet
  91234. ** been positioned.
  91235. */
  91236. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
  91237. assert( i<sqlite3ExprVectorSize(pVector) );
  91238. if( sqlite3ExprIsVector(pVector) ){
  91239. assert( pVector->op2==0 || pVector->op==TK_REGISTER );
  91240. if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
  91241. return pVector->x.pSelect->pEList->a[i].pExpr;
  91242. }else{
  91243. return pVector->x.pList->a[i].pExpr;
  91244. }
  91245. }
  91246. return pVector;
  91247. }
  91248. /*
  91249. ** Compute and return a new Expr object which when passed to
  91250. ** sqlite3ExprCode() will generate all necessary code to compute
  91251. ** the iField-th column of the vector expression pVector.
  91252. **
  91253. ** It is ok for pVector to be a scalar (as long as iField==0).
  91254. ** In that case, this routine works like sqlite3ExprDup().
  91255. **
  91256. ** The caller owns the returned Expr object and is responsible for
  91257. ** ensuring that the returned value eventually gets freed.
  91258. **
  91259. ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
  91260. ** then the returned object will reference pVector and so pVector must remain
  91261. ** valid for the life of the returned object. If pVector is a TK_VECTOR
  91262. ** or a scalar expression, then it can be deleted as soon as this routine
  91263. ** returns.
  91264. **
  91265. ** A trick to cause a TK_SELECT pVector to be deleted together with
  91266. ** the returned Expr object is to attach the pVector to the pRight field
  91267. ** of the returned TK_SELECT_COLUMN Expr object.
  91268. */
  91269. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
  91270. Parse *pParse, /* Parsing context */
  91271. Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
  91272. int iField /* Which column of the vector to return */
  91273. ){
  91274. Expr *pRet;
  91275. if( pVector->op==TK_SELECT ){
  91276. assert( pVector->flags & EP_xIsSelect );
  91277. /* The TK_SELECT_COLUMN Expr node:
  91278. **
  91279. ** pLeft: pVector containing TK_SELECT. Not deleted.
  91280. ** pRight: not used. But recursively deleted.
  91281. ** iColumn: Index of a column in pVector
  91282. ** iTable: 0 or the number of columns on the LHS of an assignment
  91283. ** pLeft->iTable: First in an array of register holding result, or 0
  91284. ** if the result is not yet computed.
  91285. **
  91286. ** sqlite3ExprDelete() specifically skips the recursive delete of
  91287. ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
  91288. ** can be attached to pRight to cause this node to take ownership of
  91289. ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
  91290. ** with the same pLeft pointer to the pVector, but only one of them
  91291. ** will own the pVector.
  91292. */
  91293. pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
  91294. if( pRet ){
  91295. pRet->iColumn = iField;
  91296. pRet->pLeft = pVector;
  91297. }
  91298. assert( pRet==0 || pRet->iTable==0 );
  91299. }else{
  91300. if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
  91301. pRet = sqlite3ExprDup(pParse->db, pVector, 0);
  91302. sqlite3RenameTokenRemap(pParse, pRet, pVector);
  91303. }
  91304. return pRet;
  91305. }
  91306. /*
  91307. ** If expression pExpr is of type TK_SELECT, generate code to evaluate
  91308. ** it. Return the register in which the result is stored (or, if the
  91309. ** sub-select returns more than one column, the first in an array
  91310. ** of registers in which the result is stored).
  91311. **
  91312. ** If pExpr is not a TK_SELECT expression, return 0.
  91313. */
  91314. static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
  91315. int reg = 0;
  91316. #ifndef SQLITE_OMIT_SUBQUERY
  91317. if( pExpr->op==TK_SELECT ){
  91318. reg = sqlite3CodeSubselect(pParse, pExpr);
  91319. }
  91320. #endif
  91321. return reg;
  91322. }
  91323. /*
  91324. ** Argument pVector points to a vector expression - either a TK_VECTOR
  91325. ** or TK_SELECT that returns more than one column. This function returns
  91326. ** the register number of a register that contains the value of
  91327. ** element iField of the vector.
  91328. **
  91329. ** If pVector is a TK_SELECT expression, then code for it must have
  91330. ** already been generated using the exprCodeSubselect() routine. In this
  91331. ** case parameter regSelect should be the first in an array of registers
  91332. ** containing the results of the sub-select.
  91333. **
  91334. ** If pVector is of type TK_VECTOR, then code for the requested field
  91335. ** is generated. In this case (*pRegFree) may be set to the number of
  91336. ** a temporary register to be freed by the caller before returning.
  91337. **
  91338. ** Before returning, output parameter (*ppExpr) is set to point to the
  91339. ** Expr object corresponding to element iElem of the vector.
  91340. */
  91341. static int exprVectorRegister(
  91342. Parse *pParse, /* Parse context */
  91343. Expr *pVector, /* Vector to extract element from */
  91344. int iField, /* Field to extract from pVector */
  91345. int regSelect, /* First in array of registers */
  91346. Expr **ppExpr, /* OUT: Expression element */
  91347. int *pRegFree /* OUT: Temp register to free */
  91348. ){
  91349. u8 op = pVector->op;
  91350. assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
  91351. if( op==TK_REGISTER ){
  91352. *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
  91353. return pVector->iTable+iField;
  91354. }
  91355. if( op==TK_SELECT ){
  91356. *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
  91357. return regSelect+iField;
  91358. }
  91359. *ppExpr = pVector->x.pList->a[iField].pExpr;
  91360. return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
  91361. }
  91362. /*
  91363. ** Expression pExpr is a comparison between two vector values. Compute
  91364. ** the result of the comparison (1, 0, or NULL) and write that
  91365. ** result into register dest.
  91366. **
  91367. ** The caller must satisfy the following preconditions:
  91368. **
  91369. ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
  91370. ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
  91371. ** otherwise: op==pExpr->op and p5==0
  91372. */
  91373. static void codeVectorCompare(
  91374. Parse *pParse, /* Code generator context */
  91375. Expr *pExpr, /* The comparison operation */
  91376. int dest, /* Write results into this register */
  91377. u8 op, /* Comparison operator */
  91378. u8 p5 /* SQLITE_NULLEQ or zero */
  91379. ){
  91380. Vdbe *v = pParse->pVdbe;
  91381. Expr *pLeft = pExpr->pLeft;
  91382. Expr *pRight = pExpr->pRight;
  91383. int nLeft = sqlite3ExprVectorSize(pLeft);
  91384. int i;
  91385. int regLeft = 0;
  91386. int regRight = 0;
  91387. u8 opx = op;
  91388. int addrDone = sqlite3VdbeMakeLabel(pParse);
  91389. if( nLeft!=sqlite3ExprVectorSize(pRight) ){
  91390. sqlite3ErrorMsg(pParse, "row value misused");
  91391. return;
  91392. }
  91393. assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
  91394. || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
  91395. || pExpr->op==TK_LT || pExpr->op==TK_GT
  91396. || pExpr->op==TK_LE || pExpr->op==TK_GE
  91397. );
  91398. assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
  91399. || (pExpr->op==TK_ISNOT && op==TK_NE) );
  91400. assert( p5==0 || pExpr->op!=op );
  91401. assert( p5==SQLITE_NULLEQ || pExpr->op==op );
  91402. p5 |= SQLITE_STOREP2;
  91403. if( opx==TK_LE ) opx = TK_LT;
  91404. if( opx==TK_GE ) opx = TK_GT;
  91405. regLeft = exprCodeSubselect(pParse, pLeft);
  91406. regRight = exprCodeSubselect(pParse, pRight);
  91407. for(i=0; 1 /*Loop exits by "break"*/; i++){
  91408. int regFree1 = 0, regFree2 = 0;
  91409. Expr *pL, *pR;
  91410. int r1, r2;
  91411. assert( i>=0 && i<nLeft );
  91412. r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
  91413. r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
  91414. codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
  91415. testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  91416. testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  91417. testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  91418. testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  91419. testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  91420. testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  91421. sqlite3ReleaseTempReg(pParse, regFree1);
  91422. sqlite3ReleaseTempReg(pParse, regFree2);
  91423. if( i==nLeft-1 ){
  91424. break;
  91425. }
  91426. if( opx==TK_EQ ){
  91427. sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
  91428. p5 |= SQLITE_KEEPNULL;
  91429. }else if( opx==TK_NE ){
  91430. sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
  91431. p5 |= SQLITE_KEEPNULL;
  91432. }else{
  91433. assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
  91434. sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
  91435. VdbeCoverageIf(v, op==TK_LT);
  91436. VdbeCoverageIf(v, op==TK_GT);
  91437. VdbeCoverageIf(v, op==TK_LE);
  91438. VdbeCoverageIf(v, op==TK_GE);
  91439. if( i==nLeft-2 ) opx = op;
  91440. }
  91441. }
  91442. sqlite3VdbeResolveLabel(v, addrDone);
  91443. }
  91444. #if SQLITE_MAX_EXPR_DEPTH>0
  91445. /*
  91446. ** Check that argument nHeight is less than or equal to the maximum
  91447. ** expression depth allowed. If it is not, leave an error message in
  91448. ** pParse.
  91449. */
  91450. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  91451. int rc = SQLITE_OK;
  91452. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  91453. if( nHeight>mxHeight ){
  91454. sqlite3ErrorMsg(pParse,
  91455. "Expression tree is too large (maximum depth %d)", mxHeight
  91456. );
  91457. rc = SQLITE_ERROR;
  91458. }
  91459. return rc;
  91460. }
  91461. /* The following three functions, heightOfExpr(), heightOfExprList()
  91462. ** and heightOfSelect(), are used to determine the maximum height
  91463. ** of any expression tree referenced by the structure passed as the
  91464. ** first argument.
  91465. **
  91466. ** If this maximum height is greater than the current value pointed
  91467. ** to by pnHeight, the second parameter, then set *pnHeight to that
  91468. ** value.
  91469. */
  91470. static void heightOfExpr(Expr *p, int *pnHeight){
  91471. if( p ){
  91472. if( p->nHeight>*pnHeight ){
  91473. *pnHeight = p->nHeight;
  91474. }
  91475. }
  91476. }
  91477. static void heightOfExprList(ExprList *p, int *pnHeight){
  91478. if( p ){
  91479. int i;
  91480. for(i=0; i<p->nExpr; i++){
  91481. heightOfExpr(p->a[i].pExpr, pnHeight);
  91482. }
  91483. }
  91484. }
  91485. static void heightOfSelect(Select *pSelect, int *pnHeight){
  91486. Select *p;
  91487. for(p=pSelect; p; p=p->pPrior){
  91488. heightOfExpr(p->pWhere, pnHeight);
  91489. heightOfExpr(p->pHaving, pnHeight);
  91490. heightOfExpr(p->pLimit, pnHeight);
  91491. heightOfExprList(p->pEList, pnHeight);
  91492. heightOfExprList(p->pGroupBy, pnHeight);
  91493. heightOfExprList(p->pOrderBy, pnHeight);
  91494. }
  91495. }
  91496. /*
  91497. ** Set the Expr.nHeight variable in the structure passed as an
  91498. ** argument. An expression with no children, Expr.pList or
  91499. ** Expr.pSelect member has a height of 1. Any other expression
  91500. ** has a height equal to the maximum height of any other
  91501. ** referenced Expr plus one.
  91502. **
  91503. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  91504. ** if appropriate.
  91505. */
  91506. static void exprSetHeight(Expr *p){
  91507. int nHeight = 0;
  91508. heightOfExpr(p->pLeft, &nHeight);
  91509. heightOfExpr(p->pRight, &nHeight);
  91510. if( ExprHasProperty(p, EP_xIsSelect) ){
  91511. heightOfSelect(p->x.pSelect, &nHeight);
  91512. }else if( p->x.pList ){
  91513. heightOfExprList(p->x.pList, &nHeight);
  91514. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  91515. }
  91516. p->nHeight = nHeight + 1;
  91517. }
  91518. /*
  91519. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  91520. ** the height is greater than the maximum allowed expression depth,
  91521. ** leave an error in pParse.
  91522. **
  91523. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  91524. ** Expr.flags.
  91525. */
  91526. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  91527. if( pParse->nErr ) return;
  91528. exprSetHeight(p);
  91529. sqlite3ExprCheckHeight(pParse, p->nHeight);
  91530. }
  91531. /*
  91532. ** Return the maximum height of any expression tree referenced
  91533. ** by the select statement passed as an argument.
  91534. */
  91535. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  91536. int nHeight = 0;
  91537. heightOfSelect(p, &nHeight);
  91538. return nHeight;
  91539. }
  91540. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  91541. /*
  91542. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  91543. ** Expr.flags.
  91544. */
  91545. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  91546. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  91547. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  91548. }
  91549. }
  91550. #define exprSetHeight(y)
  91551. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  91552. /*
  91553. ** This routine is the core allocator for Expr nodes.
  91554. **
  91555. ** Construct a new expression node and return a pointer to it. Memory
  91556. ** for this node and for the pToken argument is a single allocation
  91557. ** obtained from sqlite3DbMalloc(). The calling function
  91558. ** is responsible for making sure the node eventually gets freed.
  91559. **
  91560. ** If dequote is true, then the token (if it exists) is dequoted.
  91561. ** If dequote is false, no dequoting is performed. The deQuote
  91562. ** parameter is ignored if pToken is NULL or if the token does not
  91563. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  91564. ** then the EP_DblQuoted flag is set on the expression node.
  91565. **
  91566. ** Special case: If op==TK_INTEGER and pToken points to a string that
  91567. ** can be translated into a 32-bit integer, then the token is not
  91568. ** stored in u.zToken. Instead, the integer values is written
  91569. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  91570. ** is allocated to hold the integer text and the dequote flag is ignored.
  91571. */
  91572. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  91573. sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
  91574. int op, /* Expression opcode */
  91575. const Token *pToken, /* Token argument. Might be NULL */
  91576. int dequote /* True to dequote */
  91577. ){
  91578. Expr *pNew;
  91579. int nExtra = 0;
  91580. int iValue = 0;
  91581. assert( db!=0 );
  91582. if( pToken ){
  91583. if( op!=TK_INTEGER || pToken->z==0
  91584. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  91585. nExtra = pToken->n+1;
  91586. assert( iValue>=0 );
  91587. }
  91588. }
  91589. pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
  91590. if( pNew ){
  91591. memset(pNew, 0, sizeof(Expr));
  91592. pNew->op = (u8)op;
  91593. pNew->iAgg = -1;
  91594. if( pToken ){
  91595. if( nExtra==0 ){
  91596. pNew->flags |= EP_IntValue|EP_Leaf;
  91597. pNew->u.iValue = iValue;
  91598. }else{
  91599. pNew->u.zToken = (char*)&pNew[1];
  91600. assert( pToken->z!=0 || pToken->n==0 );
  91601. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  91602. pNew->u.zToken[pToken->n] = 0;
  91603. if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
  91604. sqlite3DequoteExpr(pNew);
  91605. }
  91606. }
  91607. }
  91608. #if SQLITE_MAX_EXPR_DEPTH>0
  91609. pNew->nHeight = 1;
  91610. #endif
  91611. }
  91612. return pNew;
  91613. }
  91614. /*
  91615. ** Allocate a new expression node from a zero-terminated token that has
  91616. ** already been dequoted.
  91617. */
  91618. SQLITE_PRIVATE Expr *sqlite3Expr(
  91619. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  91620. int op, /* Expression opcode */
  91621. const char *zToken /* Token argument. Might be NULL */
  91622. ){
  91623. Token x;
  91624. x.z = zToken;
  91625. x.n = sqlite3Strlen30(zToken);
  91626. return sqlite3ExprAlloc(db, op, &x, 0);
  91627. }
  91628. /*
  91629. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  91630. **
  91631. ** If pRoot==NULL that means that a memory allocation error has occurred.
  91632. ** In that case, delete the subtrees pLeft and pRight.
  91633. */
  91634. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  91635. sqlite3 *db,
  91636. Expr *pRoot,
  91637. Expr *pLeft,
  91638. Expr *pRight
  91639. ){
  91640. if( pRoot==0 ){
  91641. assert( db->mallocFailed );
  91642. sqlite3ExprDelete(db, pLeft);
  91643. sqlite3ExprDelete(db, pRight);
  91644. }else{
  91645. if( pRight ){
  91646. pRoot->pRight = pRight;
  91647. pRoot->flags |= EP_Propagate & pRight->flags;
  91648. }
  91649. if( pLeft ){
  91650. pRoot->pLeft = pLeft;
  91651. pRoot->flags |= EP_Propagate & pLeft->flags;
  91652. }
  91653. exprSetHeight(pRoot);
  91654. }
  91655. }
  91656. /*
  91657. ** Allocate an Expr node which joins as many as two subtrees.
  91658. **
  91659. ** One or both of the subtrees can be NULL. Return a pointer to the new
  91660. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  91661. ** free the subtrees and return NULL.
  91662. */
  91663. SQLITE_PRIVATE Expr *sqlite3PExpr(
  91664. Parse *pParse, /* Parsing context */
  91665. int op, /* Expression opcode */
  91666. Expr *pLeft, /* Left operand */
  91667. Expr *pRight /* Right operand */
  91668. ){
  91669. Expr *p;
  91670. if( op==TK_AND && pParse->nErr==0 && !IN_RENAME_OBJECT ){
  91671. /* Take advantage of short-circuit false optimization for AND */
  91672. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  91673. }else{
  91674. p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
  91675. if( p ){
  91676. memset(p, 0, sizeof(Expr));
  91677. p->op = op & 0xff;
  91678. p->iAgg = -1;
  91679. }
  91680. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  91681. }
  91682. if( p ) {
  91683. sqlite3ExprCheckHeight(pParse, p->nHeight);
  91684. }
  91685. return p;
  91686. }
  91687. /*
  91688. ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
  91689. ** do a memory allocation failure) then delete the pSelect object.
  91690. */
  91691. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
  91692. if( pExpr ){
  91693. pExpr->x.pSelect = pSelect;
  91694. ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
  91695. sqlite3ExprSetHeightAndFlags(pParse, pExpr);
  91696. }else{
  91697. assert( pParse->db->mallocFailed );
  91698. sqlite3SelectDelete(pParse->db, pSelect);
  91699. }
  91700. }
  91701. /*
  91702. ** If the expression is always either TRUE or FALSE (respectively),
  91703. ** then return 1. If one cannot determine the truth value of the
  91704. ** expression at compile-time return 0.
  91705. **
  91706. ** This is an optimization. If is OK to return 0 here even if
  91707. ** the expression really is always false or false (a false negative).
  91708. ** But it is a bug to return 1 if the expression might have different
  91709. ** boolean values in different circumstances (a false positive.)
  91710. **
  91711. ** Note that if the expression is part of conditional for a
  91712. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  91713. ** is it true or false, so always return 0.
  91714. */
  91715. static int exprAlwaysTrue(Expr *p){
  91716. int v = 0;
  91717. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  91718. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  91719. return v!=0;
  91720. }
  91721. static int exprAlwaysFalse(Expr *p){
  91722. int v = 0;
  91723. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  91724. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  91725. return v==0;
  91726. }
  91727. /*
  91728. ** Join two expressions using an AND operator. If either expression is
  91729. ** NULL, then just return the other expression.
  91730. **
  91731. ** If one side or the other of the AND is known to be false, then instead
  91732. ** of returning an AND expression, just return a constant expression with
  91733. ** a value of false.
  91734. */
  91735. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  91736. if( pLeft==0 ){
  91737. return pRight;
  91738. }else if( pRight==0 ){
  91739. return pLeft;
  91740. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  91741. sqlite3ExprDelete(db, pLeft);
  91742. sqlite3ExprDelete(db, pRight);
  91743. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  91744. }else{
  91745. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  91746. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  91747. return pNew;
  91748. }
  91749. }
  91750. /*
  91751. ** Construct a new expression node for a function with multiple
  91752. ** arguments.
  91753. */
  91754. SQLITE_PRIVATE Expr *sqlite3ExprFunction(
  91755. Parse *pParse, /* Parsing context */
  91756. ExprList *pList, /* Argument list */
  91757. Token *pToken, /* Name of the function */
  91758. int eDistinct /* SF_Distinct or SF_ALL or 0 */
  91759. ){
  91760. Expr *pNew;
  91761. sqlite3 *db = pParse->db;
  91762. assert( pToken );
  91763. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  91764. if( pNew==0 ){
  91765. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  91766. return 0;
  91767. }
  91768. if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  91769. sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
  91770. }
  91771. pNew->x.pList = pList;
  91772. ExprSetProperty(pNew, EP_HasFunc);
  91773. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  91774. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  91775. if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
  91776. return pNew;
  91777. }
  91778. /*
  91779. ** Assign a variable number to an expression that encodes a wildcard
  91780. ** in the original SQL statement.
  91781. **
  91782. ** Wildcards consisting of a single "?" are assigned the next sequential
  91783. ** variable number.
  91784. **
  91785. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  91786. ** sure "nnn" is not too big to avoid a denial of service attack when
  91787. ** the SQL statement comes from an external source.
  91788. **
  91789. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  91790. ** as the previous instance of the same wildcard. Or if this is the first
  91791. ** instance of the wildcard, the next sequential variable number is
  91792. ** assigned.
  91793. */
  91794. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
  91795. sqlite3 *db = pParse->db;
  91796. const char *z;
  91797. ynVar x;
  91798. if( pExpr==0 ) return;
  91799. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  91800. z = pExpr->u.zToken;
  91801. assert( z!=0 );
  91802. assert( z[0]!=0 );
  91803. assert( n==(u32)sqlite3Strlen30(z) );
  91804. if( z[1]==0 ){
  91805. /* Wildcard of the form "?". Assign the next variable number */
  91806. assert( z[0]=='?' );
  91807. x = (ynVar)(++pParse->nVar);
  91808. }else{
  91809. int doAdd = 0;
  91810. if( z[0]=='?' ){
  91811. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  91812. ** use it as the variable number */
  91813. i64 i;
  91814. int bOk;
  91815. if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
  91816. i = z[1]-'0'; /* The common case of ?N for a single digit N */
  91817. bOk = 1;
  91818. }else{
  91819. bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  91820. }
  91821. testcase( i==0 );
  91822. testcase( i==1 );
  91823. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  91824. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  91825. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  91826. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  91827. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  91828. return;
  91829. }
  91830. x = (ynVar)i;
  91831. if( x>pParse->nVar ){
  91832. pParse->nVar = (int)x;
  91833. doAdd = 1;
  91834. }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
  91835. doAdd = 1;
  91836. }
  91837. }else{
  91838. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  91839. ** number as the prior appearance of the same name, or if the name
  91840. ** has never appeared before, reuse the same variable number
  91841. */
  91842. x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
  91843. if( x==0 ){
  91844. x = (ynVar)(++pParse->nVar);
  91845. doAdd = 1;
  91846. }
  91847. }
  91848. if( doAdd ){
  91849. pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
  91850. }
  91851. }
  91852. pExpr->iColumn = x;
  91853. if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  91854. sqlite3ErrorMsg(pParse, "too many SQL variables");
  91855. }
  91856. }
  91857. /*
  91858. ** Recursively delete an expression tree.
  91859. */
  91860. static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
  91861. assert( p!=0 );
  91862. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  91863. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  91864. assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
  91865. assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
  91866. || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
  91867. #ifdef SQLITE_DEBUG
  91868. if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
  91869. assert( p->pLeft==0 );
  91870. assert( p->pRight==0 );
  91871. assert( p->x.pSelect==0 );
  91872. }
  91873. #endif
  91874. if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
  91875. /* The Expr.x union is never used at the same time as Expr.pRight */
  91876. assert( p->x.pList==0 || p->pRight==0 );
  91877. if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
  91878. if( p->pRight ){
  91879. sqlite3ExprDeleteNN(db, p->pRight);
  91880. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  91881. sqlite3SelectDelete(db, p->x.pSelect);
  91882. }else{
  91883. sqlite3ExprListDelete(db, p->x.pList);
  91884. }
  91885. if( ExprHasProperty(p, EP_WinFunc) ){
  91886. assert( p->op==TK_FUNCTION );
  91887. sqlite3WindowDelete(db, p->y.pWin);
  91888. }
  91889. }
  91890. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  91891. if( !ExprHasProperty(p, EP_Static) ){
  91892. sqlite3DbFreeNN(db, p);
  91893. }
  91894. }
  91895. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  91896. if( p ) sqlite3ExprDeleteNN(db, p);
  91897. }
  91898. /*
  91899. ** Return the number of bytes allocated for the expression structure
  91900. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  91901. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  91902. */
  91903. static int exprStructSize(Expr *p){
  91904. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  91905. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  91906. return EXPR_FULLSIZE;
  91907. }
  91908. /*
  91909. ** Copy the complete content of an Expr node, taking care not to read
  91910. ** past the end of the structure for a reduced-size version of the source
  91911. ** Expr.
  91912. */
  91913. static void exprNodeCopy(Expr *pDest, Expr *pSrc){
  91914. memset(pDest, 0, sizeof(Expr));
  91915. memcpy(pDest, pSrc, exprStructSize(pSrc));
  91916. }
  91917. /*
  91918. ** The dupedExpr*Size() routines each return the number of bytes required
  91919. ** to store a copy of an expression or expression tree. They differ in
  91920. ** how much of the tree is measured.
  91921. **
  91922. ** dupedExprStructSize() Size of only the Expr structure
  91923. ** dupedExprNodeSize() Size of Expr + space for token
  91924. ** dupedExprSize() Expr + token + subtree components
  91925. **
  91926. ***************************************************************************
  91927. **
  91928. ** The dupedExprStructSize() function returns two values OR-ed together:
  91929. ** (1) the space required for a copy of the Expr structure only and
  91930. ** (2) the EP_xxx flags that indicate what the structure size should be.
  91931. ** The return values is always one of:
  91932. **
  91933. ** EXPR_FULLSIZE
  91934. ** EXPR_REDUCEDSIZE | EP_Reduced
  91935. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  91936. **
  91937. ** The size of the structure can be found by masking the return value
  91938. ** of this routine with 0xfff. The flags can be found by masking the
  91939. ** return value with EP_Reduced|EP_TokenOnly.
  91940. **
  91941. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  91942. ** (unreduced) Expr objects as they or originally constructed by the parser.
  91943. ** During expression analysis, extra information is computed and moved into
  91944. ** later parts of the Expr object and that extra information might get chopped
  91945. ** off if the expression is reduced. Note also that it does not work to
  91946. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  91947. ** to reduce a pristine expression tree from the parser. The implementation
  91948. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  91949. ** to enforce this constraint.
  91950. */
  91951. static int dupedExprStructSize(Expr *p, int flags){
  91952. int nSize;
  91953. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  91954. assert( EXPR_FULLSIZE<=0xfff );
  91955. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  91956. if( 0==flags || p->op==TK_SELECT_COLUMN
  91957. #ifndef SQLITE_OMIT_WINDOWFUNC
  91958. || ExprHasProperty(p, EP_WinFunc)
  91959. #endif
  91960. ){
  91961. nSize = EXPR_FULLSIZE;
  91962. }else{
  91963. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  91964. assert( !ExprHasProperty(p, EP_FromJoin) );
  91965. assert( !ExprHasProperty(p, EP_MemToken) );
  91966. assert( !ExprHasProperty(p, EP_NoReduce) );
  91967. if( p->pLeft || p->x.pList ){
  91968. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  91969. }else{
  91970. assert( p->pRight==0 );
  91971. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  91972. }
  91973. }
  91974. return nSize;
  91975. }
  91976. /*
  91977. ** This function returns the space in bytes required to store the copy
  91978. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  91979. ** string is defined.)
  91980. */
  91981. static int dupedExprNodeSize(Expr *p, int flags){
  91982. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  91983. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  91984. nByte += sqlite3Strlen30NN(p->u.zToken)+1;
  91985. }
  91986. return ROUND8(nByte);
  91987. }
  91988. /*
  91989. ** Return the number of bytes required to create a duplicate of the
  91990. ** expression passed as the first argument. The second argument is a
  91991. ** mask containing EXPRDUP_XXX flags.
  91992. **
  91993. ** The value returned includes space to create a copy of the Expr struct
  91994. ** itself and the buffer referred to by Expr.u.zToken, if any.
  91995. **
  91996. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  91997. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  91998. ** and Expr.pRight variables (but not for any structures pointed to or
  91999. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  92000. */
  92001. static int dupedExprSize(Expr *p, int flags){
  92002. int nByte = 0;
  92003. if( p ){
  92004. nByte = dupedExprNodeSize(p, flags);
  92005. if( flags&EXPRDUP_REDUCE ){
  92006. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  92007. }
  92008. }
  92009. return nByte;
  92010. }
  92011. /*
  92012. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  92013. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  92014. ** to store the copy of expression p, the copies of p->u.zToken
  92015. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  92016. ** if any. Before returning, *pzBuffer is set to the first byte past the
  92017. ** portion of the buffer copied into by this function.
  92018. */
  92019. static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
  92020. Expr *pNew; /* Value to return */
  92021. u8 *zAlloc; /* Memory space from which to build Expr object */
  92022. u32 staticFlag; /* EP_Static if space not obtained from malloc */
  92023. assert( db!=0 );
  92024. assert( p );
  92025. assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
  92026. assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
  92027. /* Figure out where to write the new Expr structure. */
  92028. if( pzBuffer ){
  92029. zAlloc = *pzBuffer;
  92030. staticFlag = EP_Static;
  92031. }else{
  92032. zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
  92033. staticFlag = 0;
  92034. }
  92035. pNew = (Expr *)zAlloc;
  92036. if( pNew ){
  92037. /* Set nNewSize to the size allocated for the structure pointed to
  92038. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  92039. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  92040. ** by the copy of the p->u.zToken string (if any).
  92041. */
  92042. const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
  92043. const int nNewSize = nStructSize & 0xfff;
  92044. int nToken;
  92045. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  92046. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  92047. }else{
  92048. nToken = 0;
  92049. }
  92050. if( dupFlags ){
  92051. assert( ExprHasProperty(p, EP_Reduced)==0 );
  92052. memcpy(zAlloc, p, nNewSize);
  92053. }else{
  92054. u32 nSize = (u32)exprStructSize(p);
  92055. memcpy(zAlloc, p, nSize);
  92056. if( nSize<EXPR_FULLSIZE ){
  92057. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  92058. }
  92059. }
  92060. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  92061. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  92062. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  92063. pNew->flags |= staticFlag;
  92064. /* Copy the p->u.zToken string, if any. */
  92065. if( nToken ){
  92066. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  92067. memcpy(zToken, p->u.zToken, nToken);
  92068. }
  92069. if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
  92070. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  92071. if( ExprHasProperty(p, EP_xIsSelect) ){
  92072. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
  92073. }else{
  92074. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
  92075. }
  92076. }
  92077. /* Fill in pNew->pLeft and pNew->pRight. */
  92078. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
  92079. zAlloc += dupedExprNodeSize(p, dupFlags);
  92080. if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
  92081. pNew->pLeft = p->pLeft ?
  92082. exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
  92083. pNew->pRight = p->pRight ?
  92084. exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
  92085. }
  92086. #ifndef SQLITE_OMIT_WINDOWFUNC
  92087. if( ExprHasProperty(p, EP_WinFunc) ){
  92088. pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
  92089. assert( ExprHasProperty(pNew, EP_WinFunc) );
  92090. }
  92091. #endif /* SQLITE_OMIT_WINDOWFUNC */
  92092. if( pzBuffer ){
  92093. *pzBuffer = zAlloc;
  92094. }
  92095. }else{
  92096. if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  92097. if( pNew->op==TK_SELECT_COLUMN ){
  92098. pNew->pLeft = p->pLeft;
  92099. assert( p->iColumn==0 || p->pRight==0 );
  92100. assert( p->pRight==0 || p->pRight==p->pLeft );
  92101. }else{
  92102. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  92103. }
  92104. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  92105. }
  92106. }
  92107. }
  92108. return pNew;
  92109. }
  92110. /*
  92111. ** Create and return a deep copy of the object passed as the second
  92112. ** argument. If an OOM condition is encountered, NULL is returned
  92113. ** and the db->mallocFailed flag set.
  92114. */
  92115. #ifndef SQLITE_OMIT_CTE
  92116. static With *withDup(sqlite3 *db, With *p){
  92117. With *pRet = 0;
  92118. if( p ){
  92119. sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  92120. pRet = sqlite3DbMallocZero(db, nByte);
  92121. if( pRet ){
  92122. int i;
  92123. pRet->nCte = p->nCte;
  92124. for(i=0; i<p->nCte; i++){
  92125. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  92126. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  92127. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  92128. }
  92129. }
  92130. }
  92131. return pRet;
  92132. }
  92133. #else
  92134. # define withDup(x,y) 0
  92135. #endif
  92136. #ifndef SQLITE_OMIT_WINDOWFUNC
  92137. /*
  92138. ** The gatherSelectWindows() procedure and its helper routine
  92139. ** gatherSelectWindowsCallback() are used to scan all the expressions
  92140. ** an a newly duplicated SELECT statement and gather all of the Window
  92141. ** objects found there, assembling them onto the linked list at Select->pWin.
  92142. */
  92143. static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
  92144. if( pExpr->op==TK_FUNCTION && pExpr->y.pWin!=0 ){
  92145. assert( ExprHasProperty(pExpr, EP_WinFunc) );
  92146. pExpr->y.pWin->pNextWin = pWalker->u.pSelect->pWin;
  92147. pWalker->u.pSelect->pWin = pExpr->y.pWin;
  92148. }
  92149. return WRC_Continue;
  92150. }
  92151. static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
  92152. return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
  92153. }
  92154. static void gatherSelectWindows(Select *p){
  92155. Walker w;
  92156. w.xExprCallback = gatherSelectWindowsCallback;
  92157. w.xSelectCallback = gatherSelectWindowsSelectCallback;
  92158. w.xSelectCallback2 = 0;
  92159. w.pParse = 0;
  92160. w.u.pSelect = p;
  92161. sqlite3WalkSelect(&w, p);
  92162. }
  92163. #endif
  92164. /*
  92165. ** The following group of routines make deep copies of expressions,
  92166. ** expression lists, ID lists, and select statements. The copies can
  92167. ** be deleted (by being passed to their respective ...Delete() routines)
  92168. ** without effecting the originals.
  92169. **
  92170. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  92171. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  92172. ** by subsequent calls to sqlite*ListAppend() routines.
  92173. **
  92174. ** Any tables that the SrcList might point to are not duplicated.
  92175. **
  92176. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  92177. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  92178. ** truncated version of the usual Expr structure that will be stored as
  92179. ** part of the in-memory representation of the database schema.
  92180. */
  92181. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  92182. assert( flags==0 || flags==EXPRDUP_REDUCE );
  92183. return p ? exprDup(db, p, flags, 0) : 0;
  92184. }
  92185. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  92186. ExprList *pNew;
  92187. struct ExprList_item *pItem, *pOldItem;
  92188. int i;
  92189. Expr *pPriorSelectCol = 0;
  92190. assert( db!=0 );
  92191. if( p==0 ) return 0;
  92192. pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
  92193. if( pNew==0 ) return 0;
  92194. pNew->nExpr = p->nExpr;
  92195. pItem = pNew->a;
  92196. pOldItem = p->a;
  92197. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  92198. Expr *pOldExpr = pOldItem->pExpr;
  92199. Expr *pNewExpr;
  92200. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  92201. if( pOldExpr
  92202. && pOldExpr->op==TK_SELECT_COLUMN
  92203. && (pNewExpr = pItem->pExpr)!=0
  92204. ){
  92205. assert( pNewExpr->iColumn==0 || i>0 );
  92206. if( pNewExpr->iColumn==0 ){
  92207. assert( pOldExpr->pLeft==pOldExpr->pRight );
  92208. pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
  92209. }else{
  92210. assert( i>0 );
  92211. assert( pItem[-1].pExpr!=0 );
  92212. assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
  92213. assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
  92214. pNewExpr->pLeft = pPriorSelectCol;
  92215. }
  92216. }
  92217. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  92218. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  92219. pItem->sortOrder = pOldItem->sortOrder;
  92220. pItem->done = 0;
  92221. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  92222. pItem->bSorterRef = pOldItem->bSorterRef;
  92223. pItem->u = pOldItem->u;
  92224. }
  92225. return pNew;
  92226. }
  92227. /*
  92228. ** If cursors, triggers, views and subqueries are all omitted from
  92229. ** the build, then none of the following routines, except for
  92230. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  92231. ** called with a NULL argument.
  92232. */
  92233. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  92234. || !defined(SQLITE_OMIT_SUBQUERY)
  92235. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  92236. SrcList *pNew;
  92237. int i;
  92238. int nByte;
  92239. assert( db!=0 );
  92240. if( p==0 ) return 0;
  92241. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  92242. pNew = sqlite3DbMallocRawNN(db, nByte );
  92243. if( pNew==0 ) return 0;
  92244. pNew->nSrc = pNew->nAlloc = p->nSrc;
  92245. for(i=0; i<p->nSrc; i++){
  92246. struct SrcList_item *pNewItem = &pNew->a[i];
  92247. struct SrcList_item *pOldItem = &p->a[i];
  92248. Table *pTab;
  92249. pNewItem->pSchema = pOldItem->pSchema;
  92250. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  92251. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  92252. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  92253. pNewItem->fg = pOldItem->fg;
  92254. pNewItem->iCursor = pOldItem->iCursor;
  92255. pNewItem->addrFillSub = pOldItem->addrFillSub;
  92256. pNewItem->regReturn = pOldItem->regReturn;
  92257. if( pNewItem->fg.isIndexedBy ){
  92258. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  92259. }
  92260. pNewItem->pIBIndex = pOldItem->pIBIndex;
  92261. if( pNewItem->fg.isTabFunc ){
  92262. pNewItem->u1.pFuncArg =
  92263. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  92264. }
  92265. pTab = pNewItem->pTab = pOldItem->pTab;
  92266. if( pTab ){
  92267. pTab->nTabRef++;
  92268. }
  92269. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  92270. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  92271. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  92272. pNewItem->colUsed = pOldItem->colUsed;
  92273. }
  92274. return pNew;
  92275. }
  92276. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  92277. IdList *pNew;
  92278. int i;
  92279. assert( db!=0 );
  92280. if( p==0 ) return 0;
  92281. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  92282. if( pNew==0 ) return 0;
  92283. pNew->nId = p->nId;
  92284. pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
  92285. if( pNew->a==0 ){
  92286. sqlite3DbFreeNN(db, pNew);
  92287. return 0;
  92288. }
  92289. /* Note that because the size of the allocation for p->a[] is not
  92290. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  92291. ** on the duplicate created by this function. */
  92292. for(i=0; i<p->nId; i++){
  92293. struct IdList_item *pNewItem = &pNew->a[i];
  92294. struct IdList_item *pOldItem = &p->a[i];
  92295. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  92296. pNewItem->idx = pOldItem->idx;
  92297. }
  92298. return pNew;
  92299. }
  92300. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
  92301. Select *pRet = 0;
  92302. Select *pNext = 0;
  92303. Select **pp = &pRet;
  92304. Select *p;
  92305. assert( db!=0 );
  92306. for(p=pDup; p; p=p->pPrior){
  92307. Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
  92308. if( pNew==0 ) break;
  92309. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  92310. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  92311. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  92312. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  92313. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  92314. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  92315. pNew->op = p->op;
  92316. pNew->pNext = pNext;
  92317. pNew->pPrior = 0;
  92318. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  92319. pNew->iLimit = 0;
  92320. pNew->iOffset = 0;
  92321. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  92322. pNew->addrOpenEphm[0] = -1;
  92323. pNew->addrOpenEphm[1] = -1;
  92324. pNew->nSelectRow = p->nSelectRow;
  92325. pNew->pWith = withDup(db, p->pWith);
  92326. #ifndef SQLITE_OMIT_WINDOWFUNC
  92327. pNew->pWin = 0;
  92328. pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
  92329. if( p->pWin ) gatherSelectWindows(pNew);
  92330. #endif
  92331. pNew->selId = p->selId;
  92332. *pp = pNew;
  92333. pp = &pNew->pPrior;
  92334. pNext = pNew;
  92335. }
  92336. return pRet;
  92337. }
  92338. #else
  92339. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  92340. assert( p==0 );
  92341. return 0;
  92342. }
  92343. #endif
  92344. /*
  92345. ** Add a new element to the end of an expression list. If pList is
  92346. ** initially NULL, then create a new expression list.
  92347. **
  92348. ** The pList argument must be either NULL or a pointer to an ExprList
  92349. ** obtained from a prior call to sqlite3ExprListAppend(). This routine
  92350. ** may not be used with an ExprList obtained from sqlite3ExprListDup().
  92351. ** Reason: This routine assumes that the number of slots in pList->a[]
  92352. ** is a power of two. That is true for sqlite3ExprListAppend() returns
  92353. ** but is not necessarily true from the return value of sqlite3ExprListDup().
  92354. **
  92355. ** If a memory allocation error occurs, the entire list is freed and
  92356. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  92357. ** that the new entry was successfully appended.
  92358. */
  92359. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  92360. Parse *pParse, /* Parsing context */
  92361. ExprList *pList, /* List to which to append. Might be NULL */
  92362. Expr *pExpr /* Expression to be appended. Might be NULL */
  92363. ){
  92364. struct ExprList_item *pItem;
  92365. sqlite3 *db = pParse->db;
  92366. assert( db!=0 );
  92367. if( pList==0 ){
  92368. pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
  92369. if( pList==0 ){
  92370. goto no_mem;
  92371. }
  92372. pList->nExpr = 0;
  92373. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  92374. ExprList *pNew;
  92375. pNew = sqlite3DbRealloc(db, pList,
  92376. sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
  92377. if( pNew==0 ){
  92378. goto no_mem;
  92379. }
  92380. pList = pNew;
  92381. }
  92382. pItem = &pList->a[pList->nExpr++];
  92383. assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
  92384. assert( offsetof(struct ExprList_item,pExpr)==0 );
  92385. memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
  92386. pItem->pExpr = pExpr;
  92387. return pList;
  92388. no_mem:
  92389. /* Avoid leaking memory if malloc has failed. */
  92390. sqlite3ExprDelete(db, pExpr);
  92391. sqlite3ExprListDelete(db, pList);
  92392. return 0;
  92393. }
  92394. /*
  92395. ** pColumns and pExpr form a vector assignment which is part of the SET
  92396. ** clause of an UPDATE statement. Like this:
  92397. **
  92398. ** (a,b,c) = (expr1,expr2,expr3)
  92399. ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
  92400. **
  92401. ** For each term of the vector assignment, append new entries to the
  92402. ** expression list pList. In the case of a subquery on the RHS, append
  92403. ** TK_SELECT_COLUMN expressions.
  92404. */
  92405. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
  92406. Parse *pParse, /* Parsing context */
  92407. ExprList *pList, /* List to which to append. Might be NULL */
  92408. IdList *pColumns, /* List of names of LHS of the assignment */
  92409. Expr *pExpr /* Vector expression to be appended. Might be NULL */
  92410. ){
  92411. sqlite3 *db = pParse->db;
  92412. int n;
  92413. int i;
  92414. int iFirst = pList ? pList->nExpr : 0;
  92415. /* pColumns can only be NULL due to an OOM but an OOM will cause an
  92416. ** exit prior to this routine being invoked */
  92417. if( NEVER(pColumns==0) ) goto vector_append_error;
  92418. if( pExpr==0 ) goto vector_append_error;
  92419. /* If the RHS is a vector, then we can immediately check to see that
  92420. ** the size of the RHS and LHS match. But if the RHS is a SELECT,
  92421. ** wildcards ("*") in the result set of the SELECT must be expanded before
  92422. ** we can do the size check, so defer the size check until code generation.
  92423. */
  92424. if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
  92425. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  92426. pColumns->nId, n);
  92427. goto vector_append_error;
  92428. }
  92429. for(i=0; i<pColumns->nId; i++){
  92430. Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
  92431. pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
  92432. if( pList ){
  92433. assert( pList->nExpr==iFirst+i+1 );
  92434. pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
  92435. pColumns->a[i].zName = 0;
  92436. }
  92437. }
  92438. if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
  92439. Expr *pFirst = pList->a[iFirst].pExpr;
  92440. assert( pFirst!=0 );
  92441. assert( pFirst->op==TK_SELECT_COLUMN );
  92442. /* Store the SELECT statement in pRight so it will be deleted when
  92443. ** sqlite3ExprListDelete() is called */
  92444. pFirst->pRight = pExpr;
  92445. pExpr = 0;
  92446. /* Remember the size of the LHS in iTable so that we can check that
  92447. ** the RHS and LHS sizes match during code generation. */
  92448. pFirst->iTable = pColumns->nId;
  92449. }
  92450. vector_append_error:
  92451. if( IN_RENAME_OBJECT ){
  92452. sqlite3RenameExprUnmap(pParse, pExpr);
  92453. }
  92454. sqlite3ExprDelete(db, pExpr);
  92455. sqlite3IdListDelete(db, pColumns);
  92456. return pList;
  92457. }
  92458. /*
  92459. ** Set the sort order for the last element on the given ExprList.
  92460. */
  92461. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
  92462. if( p==0 ) return;
  92463. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
  92464. assert( p->nExpr>0 );
  92465. if( iSortOrder<0 ){
  92466. assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
  92467. return;
  92468. }
  92469. p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
  92470. }
  92471. /*
  92472. ** Set the ExprList.a[].zName element of the most recently added item
  92473. ** on the expression list.
  92474. **
  92475. ** pList might be NULL following an OOM error. But pName should never be
  92476. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  92477. ** is set.
  92478. */
  92479. SQLITE_PRIVATE void sqlite3ExprListSetName(
  92480. Parse *pParse, /* Parsing context */
  92481. ExprList *pList, /* List to which to add the span. */
  92482. Token *pName, /* Name to be added */
  92483. int dequote /* True to cause the name to be dequoted */
  92484. ){
  92485. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  92486. if( pList ){
  92487. struct ExprList_item *pItem;
  92488. assert( pList->nExpr>0 );
  92489. pItem = &pList->a[pList->nExpr-1];
  92490. assert( pItem->zName==0 );
  92491. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  92492. if( dequote ) sqlite3Dequote(pItem->zName);
  92493. if( IN_RENAME_OBJECT ){
  92494. sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
  92495. }
  92496. }
  92497. }
  92498. /*
  92499. ** Set the ExprList.a[].zSpan element of the most recently added item
  92500. ** on the expression list.
  92501. **
  92502. ** pList might be NULL following an OOM error. But pSpan should never be
  92503. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  92504. ** is set.
  92505. */
  92506. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  92507. Parse *pParse, /* Parsing context */
  92508. ExprList *pList, /* List to which to add the span. */
  92509. const char *zStart, /* Start of the span */
  92510. const char *zEnd /* End of the span */
  92511. ){
  92512. sqlite3 *db = pParse->db;
  92513. assert( pList!=0 || db->mallocFailed!=0 );
  92514. if( pList ){
  92515. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  92516. assert( pList->nExpr>0 );
  92517. sqlite3DbFree(db, pItem->zSpan);
  92518. pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
  92519. }
  92520. }
  92521. /*
  92522. ** If the expression list pEList contains more than iLimit elements,
  92523. ** leave an error message in pParse.
  92524. */
  92525. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  92526. Parse *pParse,
  92527. ExprList *pEList,
  92528. const char *zObject
  92529. ){
  92530. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  92531. testcase( pEList && pEList->nExpr==mx );
  92532. testcase( pEList && pEList->nExpr==mx+1 );
  92533. if( pEList && pEList->nExpr>mx ){
  92534. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  92535. }
  92536. }
  92537. /*
  92538. ** Delete an entire expression list.
  92539. */
  92540. static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
  92541. int i = pList->nExpr;
  92542. struct ExprList_item *pItem = pList->a;
  92543. assert( pList->nExpr>0 );
  92544. do{
  92545. sqlite3ExprDelete(db, pItem->pExpr);
  92546. sqlite3DbFree(db, pItem->zName);
  92547. sqlite3DbFree(db, pItem->zSpan);
  92548. pItem++;
  92549. }while( --i>0 );
  92550. sqlite3DbFreeNN(db, pList);
  92551. }
  92552. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  92553. if( pList ) exprListDeleteNN(db, pList);
  92554. }
  92555. /*
  92556. ** Return the bitwise-OR of all Expr.flags fields in the given
  92557. ** ExprList.
  92558. */
  92559. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  92560. int i;
  92561. u32 m = 0;
  92562. assert( pList!=0 );
  92563. for(i=0; i<pList->nExpr; i++){
  92564. Expr *pExpr = pList->a[i].pExpr;
  92565. assert( pExpr!=0 );
  92566. m |= pExpr->flags;
  92567. }
  92568. return m;
  92569. }
  92570. /*
  92571. ** This is a SELECT-node callback for the expression walker that
  92572. ** always "fails". By "fail" in this case, we mean set
  92573. ** pWalker->eCode to zero and abort.
  92574. **
  92575. ** This callback is used by multiple expression walkers.
  92576. */
  92577. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
  92578. UNUSED_PARAMETER(NotUsed);
  92579. pWalker->eCode = 0;
  92580. return WRC_Abort;
  92581. }
  92582. /*
  92583. ** If the input expression is an ID with the name "true" or "false"
  92584. ** then convert it into an TK_TRUEFALSE term. Return non-zero if
  92585. ** the conversion happened, and zero if the expression is unaltered.
  92586. */
  92587. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
  92588. assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
  92589. if( !ExprHasProperty(pExpr, EP_Quoted)
  92590. && (sqlite3StrICmp(pExpr->u.zToken, "true")==0
  92591. || sqlite3StrICmp(pExpr->u.zToken, "false")==0)
  92592. ){
  92593. pExpr->op = TK_TRUEFALSE;
  92594. return 1;
  92595. }
  92596. return 0;
  92597. }
  92598. /*
  92599. ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
  92600. ** and 0 if it is FALSE.
  92601. */
  92602. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){
  92603. assert( pExpr->op==TK_TRUEFALSE );
  92604. assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
  92605. || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
  92606. return pExpr->u.zToken[4]==0;
  92607. }
  92608. /*
  92609. ** These routines are Walker callbacks used to check expressions to
  92610. ** see if they are "constant" for some definition of constant. The
  92611. ** Walker.eCode value determines the type of "constant" we are looking
  92612. ** for.
  92613. **
  92614. ** These callback routines are used to implement the following:
  92615. **
  92616. ** sqlite3ExprIsConstant() pWalker->eCode==1
  92617. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  92618. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  92619. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  92620. **
  92621. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  92622. ** is found to not be a constant.
  92623. **
  92624. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  92625. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  92626. ** an existing schema and 4 when processing a new statement. A bound
  92627. ** parameter raises an error for new statements, but is silently converted
  92628. ** to NULL for existing schemas. This allows sqlite_master tables that
  92629. ** contain a bound parameter because they were generated by older versions
  92630. ** of SQLite to be parsed by newer versions of SQLite without raising a
  92631. ** malformed schema error.
  92632. */
  92633. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  92634. /* If pWalker->eCode is 2 then any term of the expression that comes from
  92635. ** the ON or USING clauses of a left join disqualifies the expression
  92636. ** from being considered constant. */
  92637. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  92638. pWalker->eCode = 0;
  92639. return WRC_Abort;
  92640. }
  92641. switch( pExpr->op ){
  92642. /* Consider functions to be constant if all their arguments are constant
  92643. ** and either pWalker->eCode==4 or 5 or the function has the
  92644. ** SQLITE_FUNC_CONST flag. */
  92645. case TK_FUNCTION:
  92646. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  92647. return WRC_Continue;
  92648. }else{
  92649. pWalker->eCode = 0;
  92650. return WRC_Abort;
  92651. }
  92652. case TK_ID:
  92653. /* Convert "true" or "false" in a DEFAULT clause into the
  92654. ** appropriate TK_TRUEFALSE operator */
  92655. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  92656. return WRC_Prune;
  92657. }
  92658. /* Fall thru */
  92659. case TK_COLUMN:
  92660. case TK_AGG_FUNCTION:
  92661. case TK_AGG_COLUMN:
  92662. testcase( pExpr->op==TK_ID );
  92663. testcase( pExpr->op==TK_COLUMN );
  92664. testcase( pExpr->op==TK_AGG_FUNCTION );
  92665. testcase( pExpr->op==TK_AGG_COLUMN );
  92666. if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
  92667. return WRC_Continue;
  92668. }
  92669. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  92670. return WRC_Continue;
  92671. }
  92672. /* Fall through */
  92673. case TK_IF_NULL_ROW:
  92674. case TK_REGISTER:
  92675. testcase( pExpr->op==TK_REGISTER );
  92676. testcase( pExpr->op==TK_IF_NULL_ROW );
  92677. pWalker->eCode = 0;
  92678. return WRC_Abort;
  92679. case TK_VARIABLE:
  92680. if( pWalker->eCode==5 ){
  92681. /* Silently convert bound parameters that appear inside of CREATE
  92682. ** statements into a NULL when parsing the CREATE statement text out
  92683. ** of the sqlite_master table */
  92684. pExpr->op = TK_NULL;
  92685. }else if( pWalker->eCode==4 ){
  92686. /* A bound parameter in a CREATE statement that originates from
  92687. ** sqlite3_prepare() causes an error */
  92688. pWalker->eCode = 0;
  92689. return WRC_Abort;
  92690. }
  92691. /* Fall through */
  92692. default:
  92693. testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
  92694. testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
  92695. return WRC_Continue;
  92696. }
  92697. }
  92698. static int exprIsConst(Expr *p, int initFlag, int iCur){
  92699. Walker w;
  92700. w.eCode = initFlag;
  92701. w.xExprCallback = exprNodeIsConstant;
  92702. w.xSelectCallback = sqlite3SelectWalkFail;
  92703. #ifdef SQLITE_DEBUG
  92704. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  92705. #endif
  92706. w.u.iCur = iCur;
  92707. sqlite3WalkExpr(&w, p);
  92708. return w.eCode;
  92709. }
  92710. /*
  92711. ** Walk an expression tree. Return non-zero if the expression is constant
  92712. ** and 0 if it involves variables or function calls.
  92713. **
  92714. ** For the purposes of this function, a double-quoted string (ex: "abc")
  92715. ** is considered a variable but a single-quoted string (ex: 'abc') is
  92716. ** a constant.
  92717. */
  92718. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  92719. return exprIsConst(p, 1, 0);
  92720. }
  92721. /*
  92722. ** Walk an expression tree. Return non-zero if
  92723. **
  92724. ** (1) the expression is constant, and
  92725. ** (2) the expression does originate in the ON or USING clause
  92726. ** of a LEFT JOIN, and
  92727. ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
  92728. ** operands created by the constant propagation optimization.
  92729. **
  92730. ** When this routine returns true, it indicates that the expression
  92731. ** can be added to the pParse->pConstExpr list and evaluated once when
  92732. ** the prepared statement starts up. See sqlite3ExprCodeAtInit().
  92733. */
  92734. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  92735. return exprIsConst(p, 2, 0);
  92736. }
  92737. /*
  92738. ** Walk an expression tree. Return non-zero if the expression is constant
  92739. ** for any single row of the table with cursor iCur. In other words, the
  92740. ** expression must not refer to any non-deterministic function nor any
  92741. ** table other than iCur.
  92742. */
  92743. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  92744. return exprIsConst(p, 3, iCur);
  92745. }
  92746. /*
  92747. ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
  92748. */
  92749. static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
  92750. ExprList *pGroupBy = pWalker->u.pGroupBy;
  92751. int i;
  92752. /* Check if pExpr is identical to any GROUP BY term. If so, consider
  92753. ** it constant. */
  92754. for(i=0; i<pGroupBy->nExpr; i++){
  92755. Expr *p = pGroupBy->a[i].pExpr;
  92756. if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
  92757. CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
  92758. if( sqlite3IsBinary(pColl) ){
  92759. return WRC_Prune;
  92760. }
  92761. }
  92762. }
  92763. /* Check if pExpr is a sub-select. If so, consider it variable. */
  92764. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  92765. pWalker->eCode = 0;
  92766. return WRC_Abort;
  92767. }
  92768. return exprNodeIsConstant(pWalker, pExpr);
  92769. }
  92770. /*
  92771. ** Walk the expression tree passed as the first argument. Return non-zero
  92772. ** if the expression consists entirely of constants or copies of terms
  92773. ** in pGroupBy that sort with the BINARY collation sequence.
  92774. **
  92775. ** This routine is used to determine if a term of the HAVING clause can
  92776. ** be promoted into the WHERE clause. In order for such a promotion to work,
  92777. ** the value of the HAVING clause term must be the same for all members of
  92778. ** a "group". The requirement that the GROUP BY term must be BINARY
  92779. ** assumes that no other collating sequence will have a finer-grained
  92780. ** grouping than binary. In other words (A=B COLLATE binary) implies
  92781. ** A=B in every other collating sequence. The requirement that the
  92782. ** GROUP BY be BINARY is stricter than necessary. It would also work
  92783. ** to promote HAVING clauses that use the same alternative collating
  92784. ** sequence as the GROUP BY term, but that is much harder to check,
  92785. ** alternative collating sequences are uncommon, and this is only an
  92786. ** optimization, so we take the easy way out and simply require the
  92787. ** GROUP BY to use the BINARY collating sequence.
  92788. */
  92789. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
  92790. Walker w;
  92791. w.eCode = 1;
  92792. w.xExprCallback = exprNodeIsConstantOrGroupBy;
  92793. w.xSelectCallback = 0;
  92794. w.u.pGroupBy = pGroupBy;
  92795. w.pParse = pParse;
  92796. sqlite3WalkExpr(&w, p);
  92797. return w.eCode;
  92798. }
  92799. /*
  92800. ** Walk an expression tree. Return non-zero if the expression is constant
  92801. ** or a function call with constant arguments. Return and 0 if there
  92802. ** are any variables.
  92803. **
  92804. ** For the purposes of this function, a double-quoted string (ex: "abc")
  92805. ** is considered a variable but a single-quoted string (ex: 'abc') is
  92806. ** a constant.
  92807. */
  92808. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  92809. assert( isInit==0 || isInit==1 );
  92810. return exprIsConst(p, 4+isInit, 0);
  92811. }
  92812. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  92813. /*
  92814. ** Walk an expression tree. Return 1 if the expression contains a
  92815. ** subquery of some kind. Return 0 if there are no subqueries.
  92816. */
  92817. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
  92818. Walker w;
  92819. w.eCode = 1;
  92820. w.xExprCallback = sqlite3ExprWalkNoop;
  92821. w.xSelectCallback = sqlite3SelectWalkFail;
  92822. #ifdef SQLITE_DEBUG
  92823. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  92824. #endif
  92825. sqlite3WalkExpr(&w, p);
  92826. return w.eCode==0;
  92827. }
  92828. #endif
  92829. /*
  92830. ** If the expression p codes a constant integer that is small enough
  92831. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  92832. ** in *pValue. If the expression is not an integer or if it is too big
  92833. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  92834. */
  92835. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  92836. int rc = 0;
  92837. if( p==0 ) return 0; /* Can only happen following on OOM */
  92838. /* If an expression is an integer literal that fits in a signed 32-bit
  92839. ** integer, then the EP_IntValue flag will have already been set */
  92840. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  92841. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  92842. if( p->flags & EP_IntValue ){
  92843. *pValue = p->u.iValue;
  92844. return 1;
  92845. }
  92846. switch( p->op ){
  92847. case TK_UPLUS: {
  92848. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  92849. break;
  92850. }
  92851. case TK_UMINUS: {
  92852. int v;
  92853. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  92854. assert( v!=(-2147483647-1) );
  92855. *pValue = -v;
  92856. rc = 1;
  92857. }
  92858. break;
  92859. }
  92860. default: break;
  92861. }
  92862. return rc;
  92863. }
  92864. /*
  92865. ** Return FALSE if there is no chance that the expression can be NULL.
  92866. **
  92867. ** If the expression might be NULL or if the expression is too complex
  92868. ** to tell return TRUE.
  92869. **
  92870. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  92871. ** when we know that a value cannot be NULL. Hence, a false positive
  92872. ** (returning TRUE when in fact the expression can never be NULL) might
  92873. ** be a small performance hit but is otherwise harmless. On the other
  92874. ** hand, a false negative (returning FALSE when the result could be NULL)
  92875. ** will likely result in an incorrect answer. So when in doubt, return
  92876. ** TRUE.
  92877. */
  92878. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  92879. u8 op;
  92880. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
  92881. p = p->pLeft;
  92882. }
  92883. op = p->op;
  92884. if( op==TK_REGISTER ) op = p->op2;
  92885. switch( op ){
  92886. case TK_INTEGER:
  92887. case TK_STRING:
  92888. case TK_FLOAT:
  92889. case TK_BLOB:
  92890. return 0;
  92891. case TK_COLUMN:
  92892. return ExprHasProperty(p, EP_CanBeNull) ||
  92893. p->y.pTab==0 || /* Reference to column of index on expression */
  92894. (p->iColumn>=0 && p->y.pTab->aCol[p->iColumn].notNull==0);
  92895. default:
  92896. return 1;
  92897. }
  92898. }
  92899. /*
  92900. ** Return TRUE if the given expression is a constant which would be
  92901. ** unchanged by OP_Affinity with the affinity given in the second
  92902. ** argument.
  92903. **
  92904. ** This routine is used to determine if the OP_Affinity operation
  92905. ** can be omitted. When in doubt return FALSE. A false negative
  92906. ** is harmless. A false positive, however, can result in the wrong
  92907. ** answer.
  92908. */
  92909. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  92910. u8 op;
  92911. if( aff==SQLITE_AFF_BLOB ) return 1;
  92912. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  92913. op = p->op;
  92914. if( op==TK_REGISTER ) op = p->op2;
  92915. switch( op ){
  92916. case TK_INTEGER: {
  92917. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  92918. }
  92919. case TK_FLOAT: {
  92920. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  92921. }
  92922. case TK_STRING: {
  92923. return aff==SQLITE_AFF_TEXT;
  92924. }
  92925. case TK_BLOB: {
  92926. return 1;
  92927. }
  92928. case TK_COLUMN: {
  92929. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  92930. return p->iColumn<0
  92931. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  92932. }
  92933. default: {
  92934. return 0;
  92935. }
  92936. }
  92937. }
  92938. /*
  92939. ** Return TRUE if the given string is a row-id column name.
  92940. */
  92941. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  92942. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  92943. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  92944. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  92945. return 0;
  92946. }
  92947. /*
  92948. ** pX is the RHS of an IN operator. If pX is a SELECT statement
  92949. ** that can be simplified to a direct table access, then return
  92950. ** a pointer to the SELECT statement. If pX is not a SELECT statement,
  92951. ** or if the SELECT statement needs to be manifested into a transient
  92952. ** table, then return NULL.
  92953. */
  92954. #ifndef SQLITE_OMIT_SUBQUERY
  92955. static Select *isCandidateForInOpt(Expr *pX){
  92956. Select *p;
  92957. SrcList *pSrc;
  92958. ExprList *pEList;
  92959. Table *pTab;
  92960. int i;
  92961. if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
  92962. if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
  92963. p = pX->x.pSelect;
  92964. if( p->pPrior ) return 0; /* Not a compound SELECT */
  92965. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  92966. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  92967. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  92968. return 0; /* No DISTINCT keyword and no aggregate functions */
  92969. }
  92970. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  92971. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  92972. if( p->pWhere ) return 0; /* Has no WHERE clause */
  92973. pSrc = p->pSrc;
  92974. assert( pSrc!=0 );
  92975. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  92976. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  92977. pTab = pSrc->a[0].pTab;
  92978. assert( pTab!=0 );
  92979. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  92980. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  92981. pEList = p->pEList;
  92982. assert( pEList!=0 );
  92983. /* All SELECT results must be columns. */
  92984. for(i=0; i<pEList->nExpr; i++){
  92985. Expr *pRes = pEList->a[i].pExpr;
  92986. if( pRes->op!=TK_COLUMN ) return 0;
  92987. assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
  92988. }
  92989. return p;
  92990. }
  92991. #endif /* SQLITE_OMIT_SUBQUERY */
  92992. #ifndef SQLITE_OMIT_SUBQUERY
  92993. /*
  92994. ** Generate code that checks the left-most column of index table iCur to see if
  92995. ** it contains any NULL entries. Cause the register at regHasNull to be set
  92996. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  92997. ** to be set to NULL if iCur contains one or more NULL values.
  92998. */
  92999. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  93000. int addr1;
  93001. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  93002. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  93003. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  93004. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  93005. VdbeComment((v, "first_entry_in(%d)", iCur));
  93006. sqlite3VdbeJumpHere(v, addr1);
  93007. }
  93008. #endif
  93009. #ifndef SQLITE_OMIT_SUBQUERY
  93010. /*
  93011. ** The argument is an IN operator with a list (not a subquery) on the
  93012. ** right-hand side. Return TRUE if that list is constant.
  93013. */
  93014. static int sqlite3InRhsIsConstant(Expr *pIn){
  93015. Expr *pLHS;
  93016. int res;
  93017. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  93018. pLHS = pIn->pLeft;
  93019. pIn->pLeft = 0;
  93020. res = sqlite3ExprIsConstant(pIn);
  93021. pIn->pLeft = pLHS;
  93022. return res;
  93023. }
  93024. #endif
  93025. /*
  93026. ** This function is used by the implementation of the IN (...) operator.
  93027. ** The pX parameter is the expression on the RHS of the IN operator, which
  93028. ** might be either a list of expressions or a subquery.
  93029. **
  93030. ** The job of this routine is to find or create a b-tree object that can
  93031. ** be used either to test for membership in the RHS set or to iterate through
  93032. ** all members of the RHS set, skipping duplicates.
  93033. **
  93034. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  93035. ** and pX->iTable is set to the index of that cursor.
  93036. **
  93037. ** The returned value of this function indicates the b-tree type, as follows:
  93038. **
  93039. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  93040. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  93041. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  93042. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  93043. ** populated epheremal table.
  93044. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  93045. ** implemented as a sequence of comparisons.
  93046. **
  93047. ** An existing b-tree might be used if the RHS expression pX is a simple
  93048. ** subquery such as:
  93049. **
  93050. ** SELECT <column1>, <column2>... FROM <table>
  93051. **
  93052. ** If the RHS of the IN operator is a list or a more complex subquery, then
  93053. ** an ephemeral table might need to be generated from the RHS and then
  93054. ** pX->iTable made to point to the ephemeral table instead of an
  93055. ** existing table.
  93056. **
  93057. ** The inFlags parameter must contain, at a minimum, one of the bits
  93058. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
  93059. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
  93060. ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
  93061. ** be used to loop over all values of the RHS of the IN operator.
  93062. **
  93063. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  93064. ** through the set members) then the b-tree must not contain duplicates.
  93065. ** An epheremal table will be created unless the selected columns are guaranteed
  93066. ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
  93067. ** a UNIQUE constraint or index.
  93068. **
  93069. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  93070. ** for fast set membership tests) then an epheremal table must
  93071. ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
  93072. ** index can be found with the specified <columns> as its left-most.
  93073. **
  93074. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  93075. ** if the RHS of the IN operator is a list (not a subquery) then this
  93076. ** routine might decide that creating an ephemeral b-tree for membership
  93077. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  93078. ** calling routine should implement the IN operator using a sequence
  93079. ** of Eq or Ne comparison operations.
  93080. **
  93081. ** When the b-tree is being used for membership tests, the calling function
  93082. ** might need to know whether or not the RHS side of the IN operator
  93083. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  93084. ** if there is any chance that the (...) might contain a NULL value at
  93085. ** runtime, then a register is allocated and the register number written
  93086. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  93087. ** NULL value, then *prRhsHasNull is left unchanged.
  93088. **
  93089. ** If a register is allocated and its location stored in *prRhsHasNull, then
  93090. ** the value in that register will be NULL if the b-tree contains one or more
  93091. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  93092. ** NULL values.
  93093. **
  93094. ** If the aiMap parameter is not NULL, it must point to an array containing
  93095. ** one element for each column returned by the SELECT statement on the RHS
  93096. ** of the IN(...) operator. The i'th entry of the array is populated with the
  93097. ** offset of the index column that matches the i'th column returned by the
  93098. ** SELECT. For example, if the expression and selected index are:
  93099. **
  93100. ** (?,?,?) IN (SELECT a, b, c FROM t1)
  93101. ** CREATE INDEX i1 ON t1(b, c, a);
  93102. **
  93103. ** then aiMap[] is populated with {2, 0, 1}.
  93104. */
  93105. #ifndef SQLITE_OMIT_SUBQUERY
  93106. SQLITE_PRIVATE int sqlite3FindInIndex(
  93107. Parse *pParse, /* Parsing context */
  93108. Expr *pX, /* The right-hand side (RHS) of the IN operator */
  93109. u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
  93110. int *prRhsHasNull, /* Register holding NULL status. See notes */
  93111. int *aiMap, /* Mapping from Index fields to RHS fields */
  93112. int *piTab /* OUT: index to use */
  93113. ){
  93114. Select *p; /* SELECT to the right of IN operator */
  93115. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  93116. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  93117. int mustBeUnique; /* True if RHS must be unique */
  93118. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  93119. assert( pX->op==TK_IN );
  93120. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  93121. /* If the RHS of this IN(...) operator is a SELECT, and if it matters
  93122. ** whether or not the SELECT result contains NULL values, check whether
  93123. ** or not NULL is actually possible (it may not be, for example, due
  93124. ** to NOT NULL constraints in the schema). If no NULL values are possible,
  93125. ** set prRhsHasNull to 0 before continuing. */
  93126. if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
  93127. int i;
  93128. ExprList *pEList = pX->x.pSelect->pEList;
  93129. for(i=0; i<pEList->nExpr; i++){
  93130. if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
  93131. }
  93132. if( i==pEList->nExpr ){
  93133. prRhsHasNull = 0;
  93134. }
  93135. }
  93136. /* Check to see if an existing table or index can be used to
  93137. ** satisfy the query. This is preferable to generating a new
  93138. ** ephemeral table. */
  93139. if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
  93140. sqlite3 *db = pParse->db; /* Database connection */
  93141. Table *pTab; /* Table <table>. */
  93142. i16 iDb; /* Database idx for pTab */
  93143. ExprList *pEList = p->pEList;
  93144. int nExpr = pEList->nExpr;
  93145. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  93146. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  93147. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  93148. pTab = p->pSrc->a[0].pTab;
  93149. /* Code an OP_Transaction and OP_TableLock for <table>. */
  93150. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  93151. sqlite3CodeVerifySchema(pParse, iDb);
  93152. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  93153. assert(v); /* sqlite3GetVdbe() has always been previously called */
  93154. if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
  93155. /* The "x IN (SELECT rowid FROM table)" case */
  93156. int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
  93157. VdbeCoverage(v);
  93158. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  93159. eType = IN_INDEX_ROWID;
  93160. ExplainQueryPlan((pParse, 0,
  93161. "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
  93162. sqlite3VdbeJumpHere(v, iAddr);
  93163. }else{
  93164. Index *pIdx; /* Iterator variable */
  93165. int affinity_ok = 1;
  93166. int i;
  93167. /* Check that the affinity that will be used to perform each
  93168. ** comparison is the same as the affinity of each column in table
  93169. ** on the RHS of the IN operator. If it not, it is not possible to
  93170. ** use any index of the RHS table. */
  93171. for(i=0; i<nExpr && affinity_ok; i++){
  93172. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  93173. int iCol = pEList->a[i].pExpr->iColumn;
  93174. char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
  93175. char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
  93176. testcase( cmpaff==SQLITE_AFF_BLOB );
  93177. testcase( cmpaff==SQLITE_AFF_TEXT );
  93178. switch( cmpaff ){
  93179. case SQLITE_AFF_BLOB:
  93180. break;
  93181. case SQLITE_AFF_TEXT:
  93182. /* sqlite3CompareAffinity() only returns TEXT if one side or the
  93183. ** other has no affinity and the other side is TEXT. Hence,
  93184. ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
  93185. ** and for the term on the LHS of the IN to have no affinity. */
  93186. assert( idxaff==SQLITE_AFF_TEXT );
  93187. break;
  93188. default:
  93189. affinity_ok = sqlite3IsNumericAffinity(idxaff);
  93190. }
  93191. }
  93192. if( affinity_ok ){
  93193. /* Search for an existing index that will work for this IN operator */
  93194. for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
  93195. Bitmask colUsed; /* Columns of the index used */
  93196. Bitmask mCol; /* Mask for the current column */
  93197. if( pIdx->nColumn<nExpr ) continue;
  93198. if( pIdx->pPartIdxWhere!=0 ) continue;
  93199. /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
  93200. ** BITMASK(nExpr) without overflowing */
  93201. testcase( pIdx->nColumn==BMS-2 );
  93202. testcase( pIdx->nColumn==BMS-1 );
  93203. if( pIdx->nColumn>=BMS-1 ) continue;
  93204. if( mustBeUnique ){
  93205. if( pIdx->nKeyCol>nExpr
  93206. ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
  93207. ){
  93208. continue; /* This index is not unique over the IN RHS columns */
  93209. }
  93210. }
  93211. colUsed = 0; /* Columns of index used so far */
  93212. for(i=0; i<nExpr; i++){
  93213. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  93214. Expr *pRhs = pEList->a[i].pExpr;
  93215. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  93216. int j;
  93217. assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
  93218. for(j=0; j<nExpr; j++){
  93219. if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
  93220. assert( pIdx->azColl[j] );
  93221. if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
  93222. continue;
  93223. }
  93224. break;
  93225. }
  93226. if( j==nExpr ) break;
  93227. mCol = MASKBIT(j);
  93228. if( mCol & colUsed ) break; /* Each column used only once */
  93229. colUsed |= mCol;
  93230. if( aiMap ) aiMap[i] = j;
  93231. }
  93232. assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
  93233. if( colUsed==(MASKBIT(nExpr)-1) ){
  93234. /* If we reach this point, that means the index pIdx is usable */
  93235. int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  93236. ExplainQueryPlan((pParse, 0,
  93237. "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
  93238. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  93239. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  93240. VdbeComment((v, "%s", pIdx->zName));
  93241. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  93242. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  93243. if( prRhsHasNull ){
  93244. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  93245. i64 mask = (1<<nExpr)-1;
  93246. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
  93247. iTab, 0, 0, (u8*)&mask, P4_INT64);
  93248. #endif
  93249. *prRhsHasNull = ++pParse->nMem;
  93250. if( nExpr==1 ){
  93251. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  93252. }
  93253. }
  93254. sqlite3VdbeJumpHere(v, iAddr);
  93255. }
  93256. } /* End loop over indexes */
  93257. } /* End if( affinity_ok ) */
  93258. } /* End if not an rowid index */
  93259. } /* End attempt to optimize using an index */
  93260. /* If no preexisting index is available for the IN clause
  93261. ** and IN_INDEX_NOOP is an allowed reply
  93262. ** and the RHS of the IN operator is a list, not a subquery
  93263. ** and the RHS is not constant or has two or fewer terms,
  93264. ** then it is not worth creating an ephemeral table to evaluate
  93265. ** the IN operator so return IN_INDEX_NOOP.
  93266. */
  93267. if( eType==0
  93268. && (inFlags & IN_INDEX_NOOP_OK)
  93269. && !ExprHasProperty(pX, EP_xIsSelect)
  93270. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  93271. ){
  93272. eType = IN_INDEX_NOOP;
  93273. }
  93274. if( eType==0 ){
  93275. /* Could not find an existing table or index to use as the RHS b-tree.
  93276. ** We will have to generate an ephemeral table to do the job.
  93277. */
  93278. u32 savedNQueryLoop = pParse->nQueryLoop;
  93279. int rMayHaveNull = 0;
  93280. eType = IN_INDEX_EPH;
  93281. if( inFlags & IN_INDEX_LOOP ){
  93282. pParse->nQueryLoop = 0;
  93283. }else if( prRhsHasNull ){
  93284. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  93285. }
  93286. assert( pX->op==TK_IN );
  93287. sqlite3CodeRhsOfIN(pParse, pX, iTab);
  93288. if( rMayHaveNull ){
  93289. sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
  93290. }
  93291. pParse->nQueryLoop = savedNQueryLoop;
  93292. }
  93293. if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
  93294. int i, n;
  93295. n = sqlite3ExprVectorSize(pX->pLeft);
  93296. for(i=0; i<n; i++) aiMap[i] = i;
  93297. }
  93298. *piTab = iTab;
  93299. return eType;
  93300. }
  93301. #endif
  93302. #ifndef SQLITE_OMIT_SUBQUERY
  93303. /*
  93304. ** Argument pExpr is an (?, ?...) IN(...) expression. This
  93305. ** function allocates and returns a nul-terminated string containing
  93306. ** the affinities to be used for each column of the comparison.
  93307. **
  93308. ** It is the responsibility of the caller to ensure that the returned
  93309. ** string is eventually freed using sqlite3DbFree().
  93310. */
  93311. static char *exprINAffinity(Parse *pParse, Expr *pExpr){
  93312. Expr *pLeft = pExpr->pLeft;
  93313. int nVal = sqlite3ExprVectorSize(pLeft);
  93314. Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
  93315. char *zRet;
  93316. assert( pExpr->op==TK_IN );
  93317. zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
  93318. if( zRet ){
  93319. int i;
  93320. for(i=0; i<nVal; i++){
  93321. Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
  93322. char a = sqlite3ExprAffinity(pA);
  93323. if( pSelect ){
  93324. zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
  93325. }else{
  93326. zRet[i] = a;
  93327. }
  93328. }
  93329. zRet[nVal] = '\0';
  93330. }
  93331. return zRet;
  93332. }
  93333. #endif
  93334. #ifndef SQLITE_OMIT_SUBQUERY
  93335. /*
  93336. ** Load the Parse object passed as the first argument with an error
  93337. ** message of the form:
  93338. **
  93339. ** "sub-select returns N columns - expected M"
  93340. */
  93341. SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
  93342. const char *zFmt = "sub-select returns %d columns - expected %d";
  93343. sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
  93344. }
  93345. #endif
  93346. /*
  93347. ** Expression pExpr is a vector that has been used in a context where
  93348. ** it is not permitted. If pExpr is a sub-select vector, this routine
  93349. ** loads the Parse object with a message of the form:
  93350. **
  93351. ** "sub-select returns N columns - expected 1"
  93352. **
  93353. ** Or, if it is a regular scalar vector:
  93354. **
  93355. ** "row value misused"
  93356. */
  93357. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
  93358. #ifndef SQLITE_OMIT_SUBQUERY
  93359. if( pExpr->flags & EP_xIsSelect ){
  93360. sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
  93361. }else
  93362. #endif
  93363. {
  93364. sqlite3ErrorMsg(pParse, "row value misused");
  93365. }
  93366. }
  93367. #ifndef SQLITE_OMIT_SUBQUERY
  93368. /*
  93369. ** Generate code that will construct an ephemeral table containing all terms
  93370. ** in the RHS of an IN operator. The IN operator can be in either of two
  93371. ** forms:
  93372. **
  93373. ** x IN (4,5,11) -- IN operator with list on right-hand side
  93374. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  93375. **
  93376. ** The pExpr parameter is the IN operator. The cursor number for the
  93377. ** constructed ephermeral table is returned. The first time the ephemeral
  93378. ** table is computed, the cursor number is also stored in pExpr->iTable,
  93379. ** however the cursor number returned might not be the same, as it might
  93380. ** have been duplicated using OP_OpenDup.
  93381. **
  93382. ** If the LHS expression ("x" in the examples) is a column value, or
  93383. ** the SELECT statement returns a column value, then the affinity of that
  93384. ** column is used to build the index keys. If both 'x' and the
  93385. ** SELECT... statement are columns, then numeric affinity is used
  93386. ** if either column has NUMERIC or INTEGER affinity. If neither
  93387. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  93388. ** is used.
  93389. */
  93390. SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
  93391. Parse *pParse, /* Parsing context */
  93392. Expr *pExpr, /* The IN operator */
  93393. int iTab /* Use this cursor number */
  93394. ){
  93395. int addrOnce = 0; /* Address of the OP_Once instruction at top */
  93396. int addr; /* Address of OP_OpenEphemeral instruction */
  93397. Expr *pLeft; /* the LHS of the IN operator */
  93398. KeyInfo *pKeyInfo = 0; /* Key information */
  93399. int nVal; /* Size of vector pLeft */
  93400. Vdbe *v; /* The prepared statement under construction */
  93401. v = pParse->pVdbe;
  93402. assert( v!=0 );
  93403. /* The evaluation of the IN must be repeated every time it
  93404. ** is encountered if any of the following is true:
  93405. **
  93406. ** * The right-hand side is a correlated subquery
  93407. ** * The right-hand side is an expression list containing variables
  93408. ** * We are inside a trigger
  93409. **
  93410. ** If all of the above are false, then we can compute the RHS just once
  93411. ** and reuse it many names.
  93412. */
  93413. if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
  93414. /* Reuse of the RHS is allowed */
  93415. /* If this routine has already been coded, but the previous code
  93416. ** might not have been invoked yet, so invoke it now as a subroutine.
  93417. */
  93418. if( ExprHasProperty(pExpr, EP_Subrtn) ){
  93419. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  93420. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  93421. ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
  93422. pExpr->x.pSelect->selId));
  93423. }
  93424. sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
  93425. pExpr->y.sub.iAddr);
  93426. sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
  93427. sqlite3VdbeJumpHere(v, addrOnce);
  93428. return;
  93429. }
  93430. /* Begin coding the subroutine */
  93431. ExprSetProperty(pExpr, EP_Subrtn);
  93432. pExpr->y.sub.regReturn = ++pParse->nMem;
  93433. pExpr->y.sub.iAddr =
  93434. sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
  93435. VdbeComment((v, "return address"));
  93436. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  93437. }
  93438. /* Check to see if this is a vector IN operator */
  93439. pLeft = pExpr->pLeft;
  93440. nVal = sqlite3ExprVectorSize(pLeft);
  93441. /* Construct the ephemeral table that will contain the content of
  93442. ** RHS of the IN operator.
  93443. */
  93444. pExpr->iTable = iTab;
  93445. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
  93446. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  93447. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  93448. VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
  93449. }else{
  93450. VdbeComment((v, "RHS of IN operator"));
  93451. }
  93452. #endif
  93453. pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
  93454. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  93455. /* Case 1: expr IN (SELECT ...)
  93456. **
  93457. ** Generate code to write the results of the select into the temporary
  93458. ** table allocated and opened above.
  93459. */
  93460. Select *pSelect = pExpr->x.pSelect;
  93461. ExprList *pEList = pSelect->pEList;
  93462. ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
  93463. addrOnce?"":"CORRELATED ", pSelect->selId
  93464. ));
  93465. /* If the LHS and RHS of the IN operator do not match, that
  93466. ** error will have been caught long before we reach this point. */
  93467. if( ALWAYS(pEList->nExpr==nVal) ){
  93468. SelectDest dest;
  93469. int i;
  93470. sqlite3SelectDestInit(&dest, SRT_Set, iTab);
  93471. dest.zAffSdst = exprINAffinity(pParse, pExpr);
  93472. pSelect->iLimit = 0;
  93473. testcase( pSelect->selFlags & SF_Distinct );
  93474. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  93475. if( sqlite3Select(pParse, pSelect, &dest) ){
  93476. sqlite3DbFree(pParse->db, dest.zAffSdst);
  93477. sqlite3KeyInfoUnref(pKeyInfo);
  93478. return;
  93479. }
  93480. sqlite3DbFree(pParse->db, dest.zAffSdst);
  93481. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  93482. assert( pEList!=0 );
  93483. assert( pEList->nExpr>0 );
  93484. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  93485. for(i=0; i<nVal; i++){
  93486. Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
  93487. pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
  93488. pParse, p, pEList->a[i].pExpr
  93489. );
  93490. }
  93491. }
  93492. }else if( ALWAYS(pExpr->x.pList!=0) ){
  93493. /* Case 2: expr IN (exprlist)
  93494. **
  93495. ** For each expression, build an index key from the evaluation and
  93496. ** store it in the temporary table. If <expr> is a column, then use
  93497. ** that columns affinity when building index keys. If <expr> is not
  93498. ** a column, use numeric affinity.
  93499. */
  93500. char affinity; /* Affinity of the LHS of the IN */
  93501. int i;
  93502. ExprList *pList = pExpr->x.pList;
  93503. struct ExprList_item *pItem;
  93504. int r1, r2, r3;
  93505. affinity = sqlite3ExprAffinity(pLeft);
  93506. if( !affinity ){
  93507. affinity = SQLITE_AFF_BLOB;
  93508. }
  93509. if( pKeyInfo ){
  93510. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  93511. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  93512. }
  93513. /* Loop through each expression in <exprlist>. */
  93514. r1 = sqlite3GetTempReg(pParse);
  93515. r2 = sqlite3GetTempReg(pParse);
  93516. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  93517. Expr *pE2 = pItem->pExpr;
  93518. /* If the expression is not constant then we will need to
  93519. ** disable the test that was generated above that makes sure
  93520. ** this code only executes once. Because for a non-constant
  93521. ** expression we need to rerun this code each time.
  93522. */
  93523. if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
  93524. sqlite3VdbeChangeToNoop(v, addrOnce);
  93525. addrOnce = 0;
  93526. }
  93527. /* Evaluate the expression and insert it into the temp table */
  93528. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  93529. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  93530. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r3, 1);
  93531. }
  93532. sqlite3ReleaseTempReg(pParse, r1);
  93533. sqlite3ReleaseTempReg(pParse, r2);
  93534. }
  93535. if( pKeyInfo ){
  93536. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  93537. }
  93538. if( addrOnce ){
  93539. sqlite3VdbeJumpHere(v, addrOnce);
  93540. /* Subroutine return */
  93541. sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
  93542. sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
  93543. }
  93544. }
  93545. #endif /* SQLITE_OMIT_SUBQUERY */
  93546. /*
  93547. ** Generate code for scalar subqueries used as a subquery expression
  93548. ** or EXISTS operator:
  93549. **
  93550. ** (SELECT a FROM b) -- subquery
  93551. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  93552. **
  93553. ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
  93554. **
  93555. ** The register that holds the result. For a multi-column SELECT,
  93556. ** the result is stored in a contiguous array of registers and the
  93557. ** return value is the register of the left-most result column.
  93558. ** Return 0 if an error occurs.
  93559. */
  93560. #ifndef SQLITE_OMIT_SUBQUERY
  93561. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
  93562. int addrOnce = 0; /* Address of OP_Once at top of subroutine */
  93563. int rReg = 0; /* Register storing resulting */
  93564. Select *pSel; /* SELECT statement to encode */
  93565. SelectDest dest; /* How to deal with SELECT result */
  93566. int nReg; /* Registers to allocate */
  93567. Expr *pLimit; /* New limit expression */
  93568. Vdbe *v = pParse->pVdbe;
  93569. assert( v!=0 );
  93570. testcase( pExpr->op==TK_EXISTS );
  93571. testcase( pExpr->op==TK_SELECT );
  93572. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  93573. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  93574. pSel = pExpr->x.pSelect;
  93575. /* The evaluation of the EXISTS/SELECT must be repeated every time it
  93576. ** is encountered if any of the following is true:
  93577. **
  93578. ** * The right-hand side is a correlated subquery
  93579. ** * The right-hand side is an expression list containing variables
  93580. ** * We are inside a trigger
  93581. **
  93582. ** If all of the above are false, then we can run this code just once
  93583. ** save the results, and reuse the same result on subsequent invocations.
  93584. */
  93585. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  93586. /* If this routine has already been coded, then invoke it as a
  93587. ** subroutine. */
  93588. if( ExprHasProperty(pExpr, EP_Subrtn) ){
  93589. ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
  93590. sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
  93591. pExpr->y.sub.iAddr);
  93592. return pExpr->iTable;
  93593. }
  93594. /* Begin coding the subroutine */
  93595. ExprSetProperty(pExpr, EP_Subrtn);
  93596. pExpr->y.sub.regReturn = ++pParse->nMem;
  93597. pExpr->y.sub.iAddr =
  93598. sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
  93599. VdbeComment((v, "return address"));
  93600. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  93601. }
  93602. /* For a SELECT, generate code to put the values for all columns of
  93603. ** the first row into an array of registers and return the index of
  93604. ** the first register.
  93605. **
  93606. ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
  93607. ** into a register and return that register number.
  93608. **
  93609. ** In both cases, the query is augmented with "LIMIT 1". Any
  93610. ** preexisting limit is discarded in place of the new LIMIT 1.
  93611. */
  93612. ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
  93613. addrOnce?"":"CORRELATED ", pSel->selId));
  93614. nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
  93615. sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
  93616. pParse->nMem += nReg;
  93617. if( pExpr->op==TK_SELECT ){
  93618. dest.eDest = SRT_Mem;
  93619. dest.iSdst = dest.iSDParm;
  93620. dest.nSdst = nReg;
  93621. sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
  93622. VdbeComment((v, "Init subquery result"));
  93623. }else{
  93624. dest.eDest = SRT_Exists;
  93625. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  93626. VdbeComment((v, "Init EXISTS result"));
  93627. }
  93628. pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[1], 0);
  93629. if( pSel->pLimit ){
  93630. sqlite3ExprDelete(pParse->db, pSel->pLimit->pLeft);
  93631. pSel->pLimit->pLeft = pLimit;
  93632. }else{
  93633. pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
  93634. }
  93635. pSel->iLimit = 0;
  93636. if( sqlite3Select(pParse, pSel, &dest) ){
  93637. return 0;
  93638. }
  93639. pExpr->iTable = rReg = dest.iSDParm;
  93640. ExprSetVVAProperty(pExpr, EP_NoReduce);
  93641. if( addrOnce ){
  93642. sqlite3VdbeJumpHere(v, addrOnce);
  93643. /* Subroutine return */
  93644. sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
  93645. sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
  93646. }
  93647. return rReg;
  93648. }
  93649. #endif /* SQLITE_OMIT_SUBQUERY */
  93650. #ifndef SQLITE_OMIT_SUBQUERY
  93651. /*
  93652. ** Expr pIn is an IN(...) expression. This function checks that the
  93653. ** sub-select on the RHS of the IN() operator has the same number of
  93654. ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
  93655. ** a sub-query, that the LHS is a vector of size 1.
  93656. */
  93657. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
  93658. int nVector = sqlite3ExprVectorSize(pIn->pLeft);
  93659. if( (pIn->flags & EP_xIsSelect) ){
  93660. if( nVector!=pIn->x.pSelect->pEList->nExpr ){
  93661. sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
  93662. return 1;
  93663. }
  93664. }else if( nVector!=1 ){
  93665. sqlite3VectorErrorMsg(pParse, pIn->pLeft);
  93666. return 1;
  93667. }
  93668. return 0;
  93669. }
  93670. #endif
  93671. #ifndef SQLITE_OMIT_SUBQUERY
  93672. /*
  93673. ** Generate code for an IN expression.
  93674. **
  93675. ** x IN (SELECT ...)
  93676. ** x IN (value, value, ...)
  93677. **
  93678. ** The left-hand side (LHS) is a scalar or vector expression. The
  93679. ** right-hand side (RHS) is an array of zero or more scalar values, or a
  93680. ** subquery. If the RHS is a subquery, the number of result columns must
  93681. ** match the number of columns in the vector on the LHS. If the RHS is
  93682. ** a list of values, the LHS must be a scalar.
  93683. **
  93684. ** The IN operator is true if the LHS value is contained within the RHS.
  93685. ** The result is false if the LHS is definitely not in the RHS. The
  93686. ** result is NULL if the presence of the LHS in the RHS cannot be
  93687. ** determined due to NULLs.
  93688. **
  93689. ** This routine generates code that jumps to destIfFalse if the LHS is not
  93690. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  93691. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  93692. ** within the RHS then fall through.
  93693. **
  93694. ** See the separate in-operator.md documentation file in the canonical
  93695. ** SQLite source tree for additional information.
  93696. */
  93697. static void sqlite3ExprCodeIN(
  93698. Parse *pParse, /* Parsing and code generating context */
  93699. Expr *pExpr, /* The IN expression */
  93700. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  93701. int destIfNull /* Jump here if the results are unknown due to NULLs */
  93702. ){
  93703. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  93704. int eType; /* Type of the RHS */
  93705. int rLhs; /* Register(s) holding the LHS values */
  93706. int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
  93707. Vdbe *v; /* Statement under construction */
  93708. int *aiMap = 0; /* Map from vector field to index column */
  93709. char *zAff = 0; /* Affinity string for comparisons */
  93710. int nVector; /* Size of vectors for this IN operator */
  93711. int iDummy; /* Dummy parameter to exprCodeVector() */
  93712. Expr *pLeft; /* The LHS of the IN operator */
  93713. int i; /* loop counter */
  93714. int destStep2; /* Where to jump when NULLs seen in step 2 */
  93715. int destStep6 = 0; /* Start of code for Step 6 */
  93716. int addrTruthOp; /* Address of opcode that determines the IN is true */
  93717. int destNotNull; /* Jump here if a comparison is not true in step 6 */
  93718. int addrTop; /* Top of the step-6 loop */
  93719. int iTab = 0; /* Index to use */
  93720. pLeft = pExpr->pLeft;
  93721. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  93722. zAff = exprINAffinity(pParse, pExpr);
  93723. nVector = sqlite3ExprVectorSize(pExpr->pLeft);
  93724. aiMap = (int*)sqlite3DbMallocZero(
  93725. pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
  93726. );
  93727. if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
  93728. /* Attempt to compute the RHS. After this step, if anything other than
  93729. ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
  93730. ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
  93731. ** the RHS has not yet been coded. */
  93732. v = pParse->pVdbe;
  93733. assert( v!=0 ); /* OOM detected prior to this routine */
  93734. VdbeNoopComment((v, "begin IN expr"));
  93735. eType = sqlite3FindInIndex(pParse, pExpr,
  93736. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  93737. destIfFalse==destIfNull ? 0 : &rRhsHasNull,
  93738. aiMap, &iTab);
  93739. assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
  93740. || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
  93741. );
  93742. #ifdef SQLITE_DEBUG
  93743. /* Confirm that aiMap[] contains nVector integer values between 0 and
  93744. ** nVector-1. */
  93745. for(i=0; i<nVector; i++){
  93746. int j, cnt;
  93747. for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
  93748. assert( cnt==1 );
  93749. }
  93750. #endif
  93751. /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
  93752. ** vector, then it is stored in an array of nVector registers starting
  93753. ** at r1.
  93754. **
  93755. ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
  93756. ** so that the fields are in the same order as an existing index. The
  93757. ** aiMap[] array contains a mapping from the original LHS field order to
  93758. ** the field order that matches the RHS index.
  93759. */
  93760. rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
  93761. for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
  93762. if( i==nVector ){
  93763. /* LHS fields are not reordered */
  93764. rLhs = rLhsOrig;
  93765. }else{
  93766. /* Need to reorder the LHS fields according to aiMap */
  93767. rLhs = sqlite3GetTempRange(pParse, nVector);
  93768. for(i=0; i<nVector; i++){
  93769. sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
  93770. }
  93771. }
  93772. /* If sqlite3FindInIndex() did not find or create an index that is
  93773. ** suitable for evaluating the IN operator, then evaluate using a
  93774. ** sequence of comparisons.
  93775. **
  93776. ** This is step (1) in the in-operator.md optimized algorithm.
  93777. */
  93778. if( eType==IN_INDEX_NOOP ){
  93779. ExprList *pList = pExpr->x.pList;
  93780. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  93781. int labelOk = sqlite3VdbeMakeLabel(pParse);
  93782. int r2, regToFree;
  93783. int regCkNull = 0;
  93784. int ii;
  93785. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  93786. if( destIfNull!=destIfFalse ){
  93787. regCkNull = sqlite3GetTempReg(pParse);
  93788. sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
  93789. }
  93790. for(ii=0; ii<pList->nExpr; ii++){
  93791. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  93792. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  93793. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  93794. }
  93795. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  93796. sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
  93797. (void*)pColl, P4_COLLSEQ);
  93798. VdbeCoverageIf(v, ii<pList->nExpr-1);
  93799. VdbeCoverageIf(v, ii==pList->nExpr-1);
  93800. sqlite3VdbeChangeP5(v, zAff[0]);
  93801. }else{
  93802. assert( destIfNull==destIfFalse );
  93803. sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
  93804. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  93805. sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
  93806. }
  93807. sqlite3ReleaseTempReg(pParse, regToFree);
  93808. }
  93809. if( regCkNull ){
  93810. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  93811. sqlite3VdbeGoto(v, destIfFalse);
  93812. }
  93813. sqlite3VdbeResolveLabel(v, labelOk);
  93814. sqlite3ReleaseTempReg(pParse, regCkNull);
  93815. goto sqlite3ExprCodeIN_finished;
  93816. }
  93817. /* Step 2: Check to see if the LHS contains any NULL columns. If the
  93818. ** LHS does contain NULLs then the result must be either FALSE or NULL.
  93819. ** We will then skip the binary search of the RHS.
  93820. */
  93821. if( destIfNull==destIfFalse ){
  93822. destStep2 = destIfFalse;
  93823. }else{
  93824. destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
  93825. }
  93826. for(i=0; i<nVector; i++){
  93827. Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
  93828. if( sqlite3ExprCanBeNull(p) ){
  93829. sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
  93830. VdbeCoverage(v);
  93831. }
  93832. }
  93833. /* Step 3. The LHS is now known to be non-NULL. Do the binary search
  93834. ** of the RHS using the LHS as a probe. If found, the result is
  93835. ** true.
  93836. */
  93837. if( eType==IN_INDEX_ROWID ){
  93838. /* In this case, the RHS is the ROWID of table b-tree and so we also
  93839. ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
  93840. ** into a single opcode. */
  93841. sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
  93842. VdbeCoverage(v);
  93843. addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
  93844. }else{
  93845. sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
  93846. if( destIfFalse==destIfNull ){
  93847. /* Combine Step 3 and Step 5 into a single opcode */
  93848. sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
  93849. rLhs, nVector); VdbeCoverage(v);
  93850. goto sqlite3ExprCodeIN_finished;
  93851. }
  93852. /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
  93853. addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
  93854. rLhs, nVector); VdbeCoverage(v);
  93855. }
  93856. /* Step 4. If the RHS is known to be non-NULL and we did not find
  93857. ** an match on the search above, then the result must be FALSE.
  93858. */
  93859. if( rRhsHasNull && nVector==1 ){
  93860. sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
  93861. VdbeCoverage(v);
  93862. }
  93863. /* Step 5. If we do not care about the difference between NULL and
  93864. ** FALSE, then just return false.
  93865. */
  93866. if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
  93867. /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
  93868. ** If any comparison is NULL, then the result is NULL. If all
  93869. ** comparisons are FALSE then the final result is FALSE.
  93870. **
  93871. ** For a scalar LHS, it is sufficient to check just the first row
  93872. ** of the RHS.
  93873. */
  93874. if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
  93875. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
  93876. VdbeCoverage(v);
  93877. if( nVector>1 ){
  93878. destNotNull = sqlite3VdbeMakeLabel(pParse);
  93879. }else{
  93880. /* For nVector==1, combine steps 6 and 7 by immediately returning
  93881. ** FALSE if the first comparison is not NULL */
  93882. destNotNull = destIfFalse;
  93883. }
  93884. for(i=0; i<nVector; i++){
  93885. Expr *p;
  93886. CollSeq *pColl;
  93887. int r3 = sqlite3GetTempReg(pParse);
  93888. p = sqlite3VectorFieldSubexpr(pLeft, i);
  93889. pColl = sqlite3ExprCollSeq(pParse, p);
  93890. sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
  93891. sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
  93892. (void*)pColl, P4_COLLSEQ);
  93893. VdbeCoverage(v);
  93894. sqlite3ReleaseTempReg(pParse, r3);
  93895. }
  93896. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  93897. if( nVector>1 ){
  93898. sqlite3VdbeResolveLabel(v, destNotNull);
  93899. sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
  93900. VdbeCoverage(v);
  93901. /* Step 7: If we reach this point, we know that the result must
  93902. ** be false. */
  93903. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  93904. }
  93905. /* Jumps here in order to return true. */
  93906. sqlite3VdbeJumpHere(v, addrTruthOp);
  93907. sqlite3ExprCodeIN_finished:
  93908. if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
  93909. VdbeComment((v, "end IN expr"));
  93910. sqlite3ExprCodeIN_oom_error:
  93911. sqlite3DbFree(pParse->db, aiMap);
  93912. sqlite3DbFree(pParse->db, zAff);
  93913. }
  93914. #endif /* SQLITE_OMIT_SUBQUERY */
  93915. #ifndef SQLITE_OMIT_FLOATING_POINT
  93916. /*
  93917. ** Generate an instruction that will put the floating point
  93918. ** value described by z[0..n-1] into register iMem.
  93919. **
  93920. ** The z[] string will probably not be zero-terminated. But the
  93921. ** z[n] character is guaranteed to be something that does not look
  93922. ** like the continuation of the number.
  93923. */
  93924. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  93925. if( ALWAYS(z!=0) ){
  93926. double value;
  93927. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  93928. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  93929. if( negateFlag ) value = -value;
  93930. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  93931. }
  93932. }
  93933. #endif
  93934. /*
  93935. ** Generate an instruction that will put the integer describe by
  93936. ** text z[0..n-1] into register iMem.
  93937. **
  93938. ** Expr.u.zToken is always UTF8 and zero-terminated.
  93939. */
  93940. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  93941. Vdbe *v = pParse->pVdbe;
  93942. if( pExpr->flags & EP_IntValue ){
  93943. int i = pExpr->u.iValue;
  93944. assert( i>=0 );
  93945. if( negFlag ) i = -i;
  93946. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  93947. }else{
  93948. int c;
  93949. i64 value;
  93950. const char *z = pExpr->u.zToken;
  93951. assert( z!=0 );
  93952. c = sqlite3DecOrHexToI64(z, &value);
  93953. if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
  93954. #ifdef SQLITE_OMIT_FLOATING_POINT
  93955. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  93956. #else
  93957. #ifndef SQLITE_OMIT_HEX_INTEGER
  93958. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  93959. sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
  93960. }else
  93961. #endif
  93962. {
  93963. codeReal(v, z, negFlag, iMem);
  93964. }
  93965. #endif
  93966. }else{
  93967. if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
  93968. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  93969. }
  93970. }
  93971. }
  93972. /* Generate code that will load into register regOut a value that is
  93973. ** appropriate for the iIdxCol-th column of index pIdx.
  93974. */
  93975. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  93976. Parse *pParse, /* The parsing context */
  93977. Index *pIdx, /* The index whose column is to be loaded */
  93978. int iTabCur, /* Cursor pointing to a table row */
  93979. int iIdxCol, /* The column of the index to be loaded */
  93980. int regOut /* Store the index column value in this register */
  93981. ){
  93982. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  93983. if( iTabCol==XN_EXPR ){
  93984. assert( pIdx->aColExpr );
  93985. assert( pIdx->aColExpr->nExpr>iIdxCol );
  93986. pParse->iSelfTab = iTabCur + 1;
  93987. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  93988. pParse->iSelfTab = 0;
  93989. }else{
  93990. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  93991. iTabCol, regOut);
  93992. }
  93993. }
  93994. /*
  93995. ** Generate code to extract the value of the iCol-th column of a table.
  93996. */
  93997. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  93998. Vdbe *v, /* The VDBE under construction */
  93999. Table *pTab, /* The table containing the value */
  94000. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  94001. int iCol, /* Index of the column to extract */
  94002. int regOut /* Extract the value into this register */
  94003. ){
  94004. if( pTab==0 ){
  94005. sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
  94006. return;
  94007. }
  94008. if( iCol<0 || iCol==pTab->iPKey ){
  94009. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  94010. }else{
  94011. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  94012. int x = iCol;
  94013. if( !HasRowid(pTab) && !IsVirtual(pTab) ){
  94014. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  94015. }
  94016. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  94017. }
  94018. if( iCol>=0 ){
  94019. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  94020. }
  94021. }
  94022. /*
  94023. ** Generate code that will extract the iColumn-th column from
  94024. ** table pTab and store the column value in register iReg.
  94025. **
  94026. ** There must be an open cursor to pTab in iTable when this routine
  94027. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  94028. */
  94029. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  94030. Parse *pParse, /* Parsing and code generating context */
  94031. Table *pTab, /* Description of the table we are reading from */
  94032. int iColumn, /* Index of the table column */
  94033. int iTable, /* The cursor pointing to the table */
  94034. int iReg, /* Store results here */
  94035. u8 p5 /* P5 value for OP_Column + FLAGS */
  94036. ){
  94037. Vdbe *v = pParse->pVdbe;
  94038. assert( v!=0 );
  94039. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  94040. if( p5 ){
  94041. sqlite3VdbeChangeP5(v, p5);
  94042. }
  94043. return iReg;
  94044. }
  94045. /*
  94046. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  94047. ** over to iTo..iTo+nReg-1.
  94048. */
  94049. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  94050. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  94051. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  94052. }
  94053. /*
  94054. ** Convert a scalar expression node to a TK_REGISTER referencing
  94055. ** register iReg. The caller must ensure that iReg already contains
  94056. ** the correct value for the expression.
  94057. */
  94058. static void exprToRegister(Expr *p, int iReg){
  94059. p->op2 = p->op;
  94060. p->op = TK_REGISTER;
  94061. p->iTable = iReg;
  94062. ExprClearProperty(p, EP_Skip);
  94063. }
  94064. /*
  94065. ** Evaluate an expression (either a vector or a scalar expression) and store
  94066. ** the result in continguous temporary registers. Return the index of
  94067. ** the first register used to store the result.
  94068. **
  94069. ** If the returned result register is a temporary scalar, then also write
  94070. ** that register number into *piFreeable. If the returned result register
  94071. ** is not a temporary or if the expression is a vector set *piFreeable
  94072. ** to 0.
  94073. */
  94074. static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
  94075. int iResult;
  94076. int nResult = sqlite3ExprVectorSize(p);
  94077. if( nResult==1 ){
  94078. iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
  94079. }else{
  94080. *piFreeable = 0;
  94081. if( p->op==TK_SELECT ){
  94082. #if SQLITE_OMIT_SUBQUERY
  94083. iResult = 0;
  94084. #else
  94085. iResult = sqlite3CodeSubselect(pParse, p);
  94086. #endif
  94087. }else{
  94088. int i;
  94089. iResult = pParse->nMem+1;
  94090. pParse->nMem += nResult;
  94091. for(i=0; i<nResult; i++){
  94092. sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
  94093. }
  94094. }
  94095. }
  94096. return iResult;
  94097. }
  94098. /*
  94099. ** Generate code into the current Vdbe to evaluate the given
  94100. ** expression. Attempt to store the results in register "target".
  94101. ** Return the register where results are stored.
  94102. **
  94103. ** With this routine, there is no guarantee that results will
  94104. ** be stored in target. The result might be stored in some other
  94105. ** register if it is convenient to do so. The calling function
  94106. ** must check the return code and move the results to the desired
  94107. ** register.
  94108. */
  94109. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  94110. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  94111. int op; /* The opcode being coded */
  94112. int inReg = target; /* Results stored in register inReg */
  94113. int regFree1 = 0; /* If non-zero free this temporary register */
  94114. int regFree2 = 0; /* If non-zero free this temporary register */
  94115. int r1, r2; /* Various register numbers */
  94116. Expr tempX; /* Temporary expression node */
  94117. int p5 = 0;
  94118. assert( target>0 && target<=pParse->nMem );
  94119. if( v==0 ){
  94120. assert( pParse->db->mallocFailed );
  94121. return 0;
  94122. }
  94123. expr_code_doover:
  94124. if( pExpr==0 ){
  94125. op = TK_NULL;
  94126. }else{
  94127. op = pExpr->op;
  94128. }
  94129. switch( op ){
  94130. case TK_AGG_COLUMN: {
  94131. AggInfo *pAggInfo = pExpr->pAggInfo;
  94132. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  94133. if( !pAggInfo->directMode ){
  94134. assert( pCol->iMem>0 );
  94135. return pCol->iMem;
  94136. }else if( pAggInfo->useSortingIdx ){
  94137. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  94138. pCol->iSorterColumn, target);
  94139. return target;
  94140. }
  94141. /* Otherwise, fall thru into the TK_COLUMN case */
  94142. }
  94143. case TK_COLUMN: {
  94144. int iTab = pExpr->iTable;
  94145. if( ExprHasProperty(pExpr, EP_FixedCol) ){
  94146. /* This COLUMN expression is really a constant due to WHERE clause
  94147. ** constraints, and that constant is coded by the pExpr->pLeft
  94148. ** expresssion. However, make sure the constant has the correct
  94149. ** datatype by applying the Affinity of the table column to the
  94150. ** constant.
  94151. */
  94152. int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
  94153. int aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
  94154. if( aff!=SQLITE_AFF_BLOB ){
  94155. static const char zAff[] = "B\000C\000D\000E";
  94156. assert( SQLITE_AFF_BLOB=='A' );
  94157. assert( SQLITE_AFF_TEXT=='B' );
  94158. if( iReg!=target ){
  94159. sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
  94160. iReg = target;
  94161. }
  94162. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
  94163. &zAff[(aff-'B')*2], P4_STATIC);
  94164. }
  94165. return iReg;
  94166. }
  94167. if( iTab<0 ){
  94168. if( pParse->iSelfTab<0 ){
  94169. /* Generating CHECK constraints or inserting into partial index */
  94170. return pExpr->iColumn - pParse->iSelfTab;
  94171. }else{
  94172. /* Coding an expression that is part of an index where column names
  94173. ** in the index refer to the table to which the index belongs */
  94174. iTab = pParse->iSelfTab - 1;
  94175. }
  94176. }
  94177. return sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
  94178. pExpr->iColumn, iTab, target,
  94179. pExpr->op2);
  94180. }
  94181. case TK_INTEGER: {
  94182. codeInteger(pParse, pExpr, 0, target);
  94183. return target;
  94184. }
  94185. case TK_TRUEFALSE: {
  94186. sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
  94187. return target;
  94188. }
  94189. #ifndef SQLITE_OMIT_FLOATING_POINT
  94190. case TK_FLOAT: {
  94191. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94192. codeReal(v, pExpr->u.zToken, 0, target);
  94193. return target;
  94194. }
  94195. #endif
  94196. case TK_STRING: {
  94197. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94198. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  94199. return target;
  94200. }
  94201. case TK_NULL: {
  94202. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  94203. return target;
  94204. }
  94205. #ifndef SQLITE_OMIT_BLOB_LITERAL
  94206. case TK_BLOB: {
  94207. int n;
  94208. const char *z;
  94209. char *zBlob;
  94210. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94211. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  94212. assert( pExpr->u.zToken[1]=='\'' );
  94213. z = &pExpr->u.zToken[2];
  94214. n = sqlite3Strlen30(z) - 1;
  94215. assert( z[n]=='\'' );
  94216. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  94217. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  94218. return target;
  94219. }
  94220. #endif
  94221. case TK_VARIABLE: {
  94222. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94223. assert( pExpr->u.zToken!=0 );
  94224. assert( pExpr->u.zToken[0]!=0 );
  94225. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  94226. if( pExpr->u.zToken[1]!=0 ){
  94227. const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
  94228. assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
  94229. pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
  94230. sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
  94231. }
  94232. return target;
  94233. }
  94234. case TK_REGISTER: {
  94235. return pExpr->iTable;
  94236. }
  94237. #ifndef SQLITE_OMIT_CAST
  94238. case TK_CAST: {
  94239. /* Expressions of the form: CAST(pLeft AS token) */
  94240. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  94241. if( inReg!=target ){
  94242. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  94243. inReg = target;
  94244. }
  94245. sqlite3VdbeAddOp2(v, OP_Cast, target,
  94246. sqlite3AffinityType(pExpr->u.zToken, 0));
  94247. return inReg;
  94248. }
  94249. #endif /* SQLITE_OMIT_CAST */
  94250. case TK_IS:
  94251. case TK_ISNOT:
  94252. op = (op==TK_IS) ? TK_EQ : TK_NE;
  94253. p5 = SQLITE_NULLEQ;
  94254. /* fall-through */
  94255. case TK_LT:
  94256. case TK_LE:
  94257. case TK_GT:
  94258. case TK_GE:
  94259. case TK_NE:
  94260. case TK_EQ: {
  94261. Expr *pLeft = pExpr->pLeft;
  94262. if( sqlite3ExprIsVector(pLeft) ){
  94263. codeVectorCompare(pParse, pExpr, target, op, p5);
  94264. }else{
  94265. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  94266. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  94267. codeCompare(pParse, pLeft, pExpr->pRight, op,
  94268. r1, r2, inReg, SQLITE_STOREP2 | p5);
  94269. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  94270. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  94271. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  94272. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  94273. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  94274. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  94275. testcase( regFree1==0 );
  94276. testcase( regFree2==0 );
  94277. }
  94278. break;
  94279. }
  94280. case TK_AND:
  94281. case TK_OR:
  94282. case TK_PLUS:
  94283. case TK_STAR:
  94284. case TK_MINUS:
  94285. case TK_REM:
  94286. case TK_BITAND:
  94287. case TK_BITOR:
  94288. case TK_SLASH:
  94289. case TK_LSHIFT:
  94290. case TK_RSHIFT:
  94291. case TK_CONCAT: {
  94292. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  94293. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  94294. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  94295. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  94296. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  94297. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  94298. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  94299. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  94300. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  94301. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  94302. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  94303. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94304. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  94305. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  94306. testcase( regFree1==0 );
  94307. testcase( regFree2==0 );
  94308. break;
  94309. }
  94310. case TK_UMINUS: {
  94311. Expr *pLeft = pExpr->pLeft;
  94312. assert( pLeft );
  94313. if( pLeft->op==TK_INTEGER ){
  94314. codeInteger(pParse, pLeft, 1, target);
  94315. return target;
  94316. #ifndef SQLITE_OMIT_FLOATING_POINT
  94317. }else if( pLeft->op==TK_FLOAT ){
  94318. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94319. codeReal(v, pLeft->u.zToken, 1, target);
  94320. return target;
  94321. #endif
  94322. }else{
  94323. tempX.op = TK_INTEGER;
  94324. tempX.flags = EP_IntValue|EP_TokenOnly;
  94325. tempX.u.iValue = 0;
  94326. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  94327. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  94328. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  94329. testcase( regFree2==0 );
  94330. }
  94331. break;
  94332. }
  94333. case TK_BITNOT:
  94334. case TK_NOT: {
  94335. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  94336. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  94337. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94338. testcase( regFree1==0 );
  94339. sqlite3VdbeAddOp2(v, op, r1, inReg);
  94340. break;
  94341. }
  94342. case TK_TRUTH: {
  94343. int isTrue; /* IS TRUE or IS NOT TRUE */
  94344. int bNormal; /* IS TRUE or IS FALSE */
  94345. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94346. testcase( regFree1==0 );
  94347. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  94348. bNormal = pExpr->op2==TK_IS;
  94349. testcase( isTrue && bNormal);
  94350. testcase( !isTrue && bNormal);
  94351. sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
  94352. break;
  94353. }
  94354. case TK_ISNULL:
  94355. case TK_NOTNULL: {
  94356. int addr;
  94357. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  94358. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  94359. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  94360. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  94361. testcase( regFree1==0 );
  94362. addr = sqlite3VdbeAddOp1(v, op, r1);
  94363. VdbeCoverageIf(v, op==TK_ISNULL);
  94364. VdbeCoverageIf(v, op==TK_NOTNULL);
  94365. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  94366. sqlite3VdbeJumpHere(v, addr);
  94367. break;
  94368. }
  94369. case TK_AGG_FUNCTION: {
  94370. AggInfo *pInfo = pExpr->pAggInfo;
  94371. if( pInfo==0 ){
  94372. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94373. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  94374. }else{
  94375. return pInfo->aFunc[pExpr->iAgg].iMem;
  94376. }
  94377. break;
  94378. }
  94379. case TK_FUNCTION: {
  94380. ExprList *pFarg; /* List of function arguments */
  94381. int nFarg; /* Number of function arguments */
  94382. FuncDef *pDef; /* The function definition object */
  94383. const char *zId; /* The function name */
  94384. u32 constMask = 0; /* Mask of function arguments that are constant */
  94385. int i; /* Loop counter */
  94386. sqlite3 *db = pParse->db; /* The database connection */
  94387. u8 enc = ENC(db); /* The text encoding used by this database */
  94388. CollSeq *pColl = 0; /* A collating sequence */
  94389. #ifndef SQLITE_OMIT_WINDOWFUNC
  94390. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  94391. return pExpr->y.pWin->regResult;
  94392. }
  94393. #endif
  94394. if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
  94395. /* SQL functions can be expensive. So try to move constant functions
  94396. ** out of the inner loop, even if that means an extra OP_Copy. */
  94397. return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  94398. }
  94399. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  94400. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  94401. pFarg = 0;
  94402. }else{
  94403. pFarg = pExpr->x.pList;
  94404. }
  94405. nFarg = pFarg ? pFarg->nExpr : 0;
  94406. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94407. zId = pExpr->u.zToken;
  94408. pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
  94409. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  94410. if( pDef==0 && pParse->explain ){
  94411. pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
  94412. }
  94413. #endif
  94414. if( pDef==0 || pDef->xFinalize!=0 ){
  94415. sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
  94416. break;
  94417. }
  94418. /* Attempt a direct implementation of the built-in COALESCE() and
  94419. ** IFNULL() functions. This avoids unnecessary evaluation of
  94420. ** arguments past the first non-NULL argument.
  94421. */
  94422. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  94423. int endCoalesce = sqlite3VdbeMakeLabel(pParse);
  94424. assert( nFarg>=2 );
  94425. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  94426. for(i=1; i<nFarg; i++){
  94427. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  94428. VdbeCoverage(v);
  94429. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  94430. }
  94431. sqlite3VdbeResolveLabel(v, endCoalesce);
  94432. break;
  94433. }
  94434. /* The UNLIKELY() function is a no-op. The result is the value
  94435. ** of the first argument.
  94436. */
  94437. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  94438. assert( nFarg>=1 );
  94439. return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  94440. }
  94441. #ifdef SQLITE_DEBUG
  94442. /* The AFFINITY() function evaluates to a string that describes
  94443. ** the type affinity of the argument. This is used for testing of
  94444. ** the SQLite type logic.
  94445. */
  94446. if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
  94447. const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
  94448. char aff;
  94449. assert( nFarg==1 );
  94450. aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
  94451. sqlite3VdbeLoadString(v, target,
  94452. aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
  94453. return target;
  94454. }
  94455. #endif
  94456. for(i=0; i<nFarg; i++){
  94457. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  94458. testcase( i==31 );
  94459. constMask |= MASKBIT32(i);
  94460. }
  94461. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  94462. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  94463. }
  94464. }
  94465. if( pFarg ){
  94466. if( constMask ){
  94467. r1 = pParse->nMem+1;
  94468. pParse->nMem += nFarg;
  94469. }else{
  94470. r1 = sqlite3GetTempRange(pParse, nFarg);
  94471. }
  94472. /* For length() and typeof() functions with a column argument,
  94473. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  94474. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  94475. ** loading.
  94476. */
  94477. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  94478. u8 exprOp;
  94479. assert( nFarg==1 );
  94480. assert( pFarg->a[0].pExpr!=0 );
  94481. exprOp = pFarg->a[0].pExpr->op;
  94482. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  94483. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  94484. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  94485. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  94486. pFarg->a[0].pExpr->op2 =
  94487. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  94488. }
  94489. }
  94490. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  94491. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  94492. }else{
  94493. r1 = 0;
  94494. }
  94495. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94496. /* Possibly overload the function if the first argument is
  94497. ** a virtual table column.
  94498. **
  94499. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  94500. ** second argument, not the first, as the argument to test to
  94501. ** see if it is a column in a virtual table. This is done because
  94502. ** the left operand of infix functions (the operand we want to
  94503. ** control overloading) ends up as the second argument to the
  94504. ** function. The expression "A glob B" is equivalent to
  94505. ** "glob(B,A). We want to use the A in "A glob B" to test
  94506. ** for function overloading. But we use the B term in "glob(B,A)".
  94507. */
  94508. if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
  94509. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  94510. }else if( nFarg>0 ){
  94511. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  94512. }
  94513. #endif
  94514. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  94515. if( !pColl ) pColl = db->pDfltColl;
  94516. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  94517. }
  94518. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  94519. if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
  94520. Expr *pArg = pFarg->a[0].pExpr;
  94521. if( pArg->op==TK_COLUMN ){
  94522. sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
  94523. }else{
  94524. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  94525. }
  94526. }else
  94527. #endif
  94528. {
  94529. sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
  94530. constMask, r1, target, (char*)pDef, P4_FUNCDEF);
  94531. sqlite3VdbeChangeP5(v, (u8)nFarg);
  94532. }
  94533. if( nFarg && constMask==0 ){
  94534. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  94535. }
  94536. return target;
  94537. }
  94538. #ifndef SQLITE_OMIT_SUBQUERY
  94539. case TK_EXISTS:
  94540. case TK_SELECT: {
  94541. int nCol;
  94542. testcase( op==TK_EXISTS );
  94543. testcase( op==TK_SELECT );
  94544. if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
  94545. sqlite3SubselectError(pParse, nCol, 1);
  94546. }else{
  94547. return sqlite3CodeSubselect(pParse, pExpr);
  94548. }
  94549. break;
  94550. }
  94551. case TK_SELECT_COLUMN: {
  94552. int n;
  94553. if( pExpr->pLeft->iTable==0 ){
  94554. pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
  94555. }
  94556. assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
  94557. if( pExpr->iTable
  94558. && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
  94559. ){
  94560. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  94561. pExpr->iTable, n);
  94562. }
  94563. return pExpr->pLeft->iTable + pExpr->iColumn;
  94564. }
  94565. case TK_IN: {
  94566. int destIfFalse = sqlite3VdbeMakeLabel(pParse);
  94567. int destIfNull = sqlite3VdbeMakeLabel(pParse);
  94568. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  94569. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  94570. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  94571. sqlite3VdbeResolveLabel(v, destIfFalse);
  94572. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  94573. sqlite3VdbeResolveLabel(v, destIfNull);
  94574. return target;
  94575. }
  94576. #endif /* SQLITE_OMIT_SUBQUERY */
  94577. /*
  94578. ** x BETWEEN y AND z
  94579. **
  94580. ** This is equivalent to
  94581. **
  94582. ** x>=y AND x<=z
  94583. **
  94584. ** X is stored in pExpr->pLeft.
  94585. ** Y is stored in pExpr->pList->a[0].pExpr.
  94586. ** Z is stored in pExpr->pList->a[1].pExpr.
  94587. */
  94588. case TK_BETWEEN: {
  94589. exprCodeBetween(pParse, pExpr, target, 0, 0);
  94590. return target;
  94591. }
  94592. case TK_SPAN:
  94593. case TK_COLLATE:
  94594. case TK_UPLUS: {
  94595. pExpr = pExpr->pLeft;
  94596. goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
  94597. }
  94598. case TK_TRIGGER: {
  94599. /* If the opcode is TK_TRIGGER, then the expression is a reference
  94600. ** to a column in the new.* or old.* pseudo-tables available to
  94601. ** trigger programs. In this case Expr.iTable is set to 1 for the
  94602. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  94603. ** is set to the column of the pseudo-table to read, or to -1 to
  94604. ** read the rowid field.
  94605. **
  94606. ** The expression is implemented using an OP_Param opcode. The p1
  94607. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  94608. ** to reference another column of the old.* pseudo-table, where
  94609. ** i is the index of the column. For a new.rowid reference, p1 is
  94610. ** set to (n+1), where n is the number of columns in each pseudo-table.
  94611. ** For a reference to any other column in the new.* pseudo-table, p1
  94612. ** is set to (n+2+i), where n and i are as defined previously. For
  94613. ** example, if the table on which triggers are being fired is
  94614. ** declared as:
  94615. **
  94616. ** CREATE TABLE t1(a, b);
  94617. **
  94618. ** Then p1 is interpreted as follows:
  94619. **
  94620. ** p1==0 -> old.rowid p1==3 -> new.rowid
  94621. ** p1==1 -> old.a p1==4 -> new.a
  94622. ** p1==2 -> old.b p1==5 -> new.b
  94623. */
  94624. Table *pTab = pExpr->y.pTab;
  94625. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  94626. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  94627. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  94628. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  94629. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  94630. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  94631. VdbeComment((v, "r[%d]=%s.%s", target,
  94632. (pExpr->iTable ? "new" : "old"),
  94633. (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[pExpr->iColumn].zName)
  94634. ));
  94635. #ifndef SQLITE_OMIT_FLOATING_POINT
  94636. /* If the column has REAL affinity, it may currently be stored as an
  94637. ** integer. Use OP_RealAffinity to make sure it is really real.
  94638. **
  94639. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  94640. ** floating point when extracting it from the record. */
  94641. if( pExpr->iColumn>=0
  94642. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  94643. ){
  94644. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  94645. }
  94646. #endif
  94647. break;
  94648. }
  94649. case TK_VECTOR: {
  94650. sqlite3ErrorMsg(pParse, "row value misused");
  94651. break;
  94652. }
  94653. case TK_IF_NULL_ROW: {
  94654. int addrINR;
  94655. addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
  94656. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  94657. sqlite3VdbeJumpHere(v, addrINR);
  94658. sqlite3VdbeChangeP3(v, addrINR, inReg);
  94659. break;
  94660. }
  94661. /*
  94662. ** Form A:
  94663. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  94664. **
  94665. ** Form B:
  94666. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  94667. **
  94668. ** Form A is can be transformed into the equivalent form B as follows:
  94669. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  94670. ** WHEN x=eN THEN rN ELSE y END
  94671. **
  94672. ** X (if it exists) is in pExpr->pLeft.
  94673. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  94674. ** odd. The Y is also optional. If the number of elements in x.pList
  94675. ** is even, then Y is omitted and the "otherwise" result is NULL.
  94676. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  94677. **
  94678. ** The result of the expression is the Ri for the first matching Ei,
  94679. ** or if there is no matching Ei, the ELSE term Y, or if there is
  94680. ** no ELSE term, NULL.
  94681. */
  94682. default: assert( op==TK_CASE ); {
  94683. int endLabel; /* GOTO label for end of CASE stmt */
  94684. int nextCase; /* GOTO label for next WHEN clause */
  94685. int nExpr; /* 2x number of WHEN terms */
  94686. int i; /* Loop counter */
  94687. ExprList *pEList; /* List of WHEN terms */
  94688. struct ExprList_item *aListelem; /* Array of WHEN terms */
  94689. Expr opCompare; /* The X==Ei expression */
  94690. Expr *pX; /* The X expression */
  94691. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  94692. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  94693. assert(pExpr->x.pList->nExpr > 0);
  94694. pEList = pExpr->x.pList;
  94695. aListelem = pEList->a;
  94696. nExpr = pEList->nExpr;
  94697. endLabel = sqlite3VdbeMakeLabel(pParse);
  94698. if( (pX = pExpr->pLeft)!=0 ){
  94699. exprNodeCopy(&tempX, pX);
  94700. testcase( pX->op==TK_COLUMN );
  94701. exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
  94702. testcase( regFree1==0 );
  94703. memset(&opCompare, 0, sizeof(opCompare));
  94704. opCompare.op = TK_EQ;
  94705. opCompare.pLeft = &tempX;
  94706. pTest = &opCompare;
  94707. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  94708. ** The value in regFree1 might get SCopy-ed into the file result.
  94709. ** So make sure that the regFree1 register is not reused for other
  94710. ** purposes and possibly overwritten. */
  94711. regFree1 = 0;
  94712. }
  94713. for(i=0; i<nExpr-1; i=i+2){
  94714. if( pX ){
  94715. assert( pTest!=0 );
  94716. opCompare.pRight = aListelem[i].pExpr;
  94717. }else{
  94718. pTest = aListelem[i].pExpr;
  94719. }
  94720. nextCase = sqlite3VdbeMakeLabel(pParse);
  94721. testcase( pTest->op==TK_COLUMN );
  94722. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  94723. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  94724. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  94725. sqlite3VdbeGoto(v, endLabel);
  94726. sqlite3VdbeResolveLabel(v, nextCase);
  94727. }
  94728. if( (nExpr&1)!=0 ){
  94729. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  94730. }else{
  94731. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  94732. }
  94733. sqlite3VdbeResolveLabel(v, endLabel);
  94734. break;
  94735. }
  94736. #ifndef SQLITE_OMIT_TRIGGER
  94737. case TK_RAISE: {
  94738. assert( pExpr->affinity==OE_Rollback
  94739. || pExpr->affinity==OE_Abort
  94740. || pExpr->affinity==OE_Fail
  94741. || pExpr->affinity==OE_Ignore
  94742. );
  94743. if( !pParse->pTriggerTab ){
  94744. sqlite3ErrorMsg(pParse,
  94745. "RAISE() may only be used within a trigger-program");
  94746. return 0;
  94747. }
  94748. if( pExpr->affinity==OE_Abort ){
  94749. sqlite3MayAbort(pParse);
  94750. }
  94751. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  94752. if( pExpr->affinity==OE_Ignore ){
  94753. sqlite3VdbeAddOp4(
  94754. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  94755. VdbeCoverage(v);
  94756. }else{
  94757. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  94758. pExpr->affinity, pExpr->u.zToken, 0, 0);
  94759. }
  94760. break;
  94761. }
  94762. #endif
  94763. }
  94764. sqlite3ReleaseTempReg(pParse, regFree1);
  94765. sqlite3ReleaseTempReg(pParse, regFree2);
  94766. return inReg;
  94767. }
  94768. /*
  94769. ** Factor out the code of the given expression to initialization time.
  94770. **
  94771. ** If regDest>=0 then the result is always stored in that register and the
  94772. ** result is not reusable. If regDest<0 then this routine is free to
  94773. ** store the value whereever it wants. The register where the expression
  94774. ** is stored is returned. When regDest<0, two identical expressions will
  94775. ** code to the same register.
  94776. */
  94777. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
  94778. Parse *pParse, /* Parsing context */
  94779. Expr *pExpr, /* The expression to code when the VDBE initializes */
  94780. int regDest /* Store the value in this register */
  94781. ){
  94782. ExprList *p;
  94783. assert( ConstFactorOk(pParse) );
  94784. p = pParse->pConstExpr;
  94785. if( regDest<0 && p ){
  94786. struct ExprList_item *pItem;
  94787. int i;
  94788. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  94789. if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
  94790. return pItem->u.iConstExprReg;
  94791. }
  94792. }
  94793. }
  94794. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  94795. p = sqlite3ExprListAppend(pParse, p, pExpr);
  94796. if( p ){
  94797. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  94798. pItem->reusable = regDest<0;
  94799. if( regDest<0 ) regDest = ++pParse->nMem;
  94800. pItem->u.iConstExprReg = regDest;
  94801. }
  94802. pParse->pConstExpr = p;
  94803. return regDest;
  94804. }
  94805. /*
  94806. ** Generate code to evaluate an expression and store the results
  94807. ** into a register. Return the register number where the results
  94808. ** are stored.
  94809. **
  94810. ** If the register is a temporary register that can be deallocated,
  94811. ** then write its number into *pReg. If the result register is not
  94812. ** a temporary, then set *pReg to zero.
  94813. **
  94814. ** If pExpr is a constant, then this routine might generate this
  94815. ** code to fill the register in the initialization section of the
  94816. ** VDBE program, in order to factor it out of the evaluation loop.
  94817. */
  94818. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  94819. int r2;
  94820. pExpr = sqlite3ExprSkipCollate(pExpr);
  94821. if( ConstFactorOk(pParse)
  94822. && pExpr->op!=TK_REGISTER
  94823. && sqlite3ExprIsConstantNotJoin(pExpr)
  94824. ){
  94825. *pReg = 0;
  94826. r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  94827. }else{
  94828. int r1 = sqlite3GetTempReg(pParse);
  94829. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  94830. if( r2==r1 ){
  94831. *pReg = r1;
  94832. }else{
  94833. sqlite3ReleaseTempReg(pParse, r1);
  94834. *pReg = 0;
  94835. }
  94836. }
  94837. return r2;
  94838. }
  94839. /*
  94840. ** Generate code that will evaluate expression pExpr and store the
  94841. ** results in register target. The results are guaranteed to appear
  94842. ** in register target.
  94843. */
  94844. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  94845. int inReg;
  94846. assert( target>0 && target<=pParse->nMem );
  94847. if( pExpr && pExpr->op==TK_REGISTER ){
  94848. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  94849. }else{
  94850. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  94851. assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  94852. if( inReg!=target && pParse->pVdbe ){
  94853. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  94854. }
  94855. }
  94856. }
  94857. /*
  94858. ** Make a transient copy of expression pExpr and then code it using
  94859. ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
  94860. ** except that the input expression is guaranteed to be unchanged.
  94861. */
  94862. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
  94863. sqlite3 *db = pParse->db;
  94864. pExpr = sqlite3ExprDup(db, pExpr, 0);
  94865. if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
  94866. sqlite3ExprDelete(db, pExpr);
  94867. }
  94868. /*
  94869. ** Generate code that will evaluate expression pExpr and store the
  94870. ** results in register target. The results are guaranteed to appear
  94871. ** in register target. If the expression is constant, then this routine
  94872. ** might choose to code the expression at initialization time.
  94873. */
  94874. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  94875. if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
  94876. sqlite3ExprCodeAtInit(pParse, pExpr, target);
  94877. }else{
  94878. sqlite3ExprCode(pParse, pExpr, target);
  94879. }
  94880. }
  94881. /*
  94882. ** Generate code that evaluates the given expression and puts the result
  94883. ** in register target.
  94884. **
  94885. ** Also make a copy of the expression results into another "cache" register
  94886. ** and modify the expression so that the next time it is evaluated,
  94887. ** the result is a copy of the cache register.
  94888. **
  94889. ** This routine is used for expressions that are used multiple
  94890. ** times. They are evaluated once and the results of the expression
  94891. ** are reused.
  94892. */
  94893. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  94894. Vdbe *v = pParse->pVdbe;
  94895. int iMem;
  94896. assert( target>0 );
  94897. assert( pExpr->op!=TK_REGISTER );
  94898. sqlite3ExprCode(pParse, pExpr, target);
  94899. iMem = ++pParse->nMem;
  94900. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  94901. exprToRegister(pExpr, iMem);
  94902. }
  94903. /*
  94904. ** Generate code that pushes the value of every element of the given
  94905. ** expression list into a sequence of registers beginning at target.
  94906. **
  94907. ** Return the number of elements evaluated. The number returned will
  94908. ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
  94909. ** is defined.
  94910. **
  94911. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  94912. ** filled using OP_SCopy. OP_Copy must be used instead.
  94913. **
  94914. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  94915. ** factored out into initialization code.
  94916. **
  94917. ** The SQLITE_ECEL_REF flag means that expressions in the list with
  94918. ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
  94919. ** in registers at srcReg, and so the value can be copied from there.
  94920. ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
  94921. ** are simply omitted rather than being copied from srcReg.
  94922. */
  94923. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  94924. Parse *pParse, /* Parsing context */
  94925. ExprList *pList, /* The expression list to be coded */
  94926. int target, /* Where to write results */
  94927. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  94928. u8 flags /* SQLITE_ECEL_* flags */
  94929. ){
  94930. struct ExprList_item *pItem;
  94931. int i, j, n;
  94932. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  94933. Vdbe *v = pParse->pVdbe;
  94934. assert( pList!=0 );
  94935. assert( target>0 );
  94936. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  94937. n = pList->nExpr;
  94938. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  94939. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  94940. Expr *pExpr = pItem->pExpr;
  94941. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  94942. if( pItem->bSorterRef ){
  94943. i--;
  94944. n--;
  94945. }else
  94946. #endif
  94947. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
  94948. if( flags & SQLITE_ECEL_OMITREF ){
  94949. i--;
  94950. n--;
  94951. }else{
  94952. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  94953. }
  94954. }else if( (flags & SQLITE_ECEL_FACTOR)!=0
  94955. && sqlite3ExprIsConstantNotJoin(pExpr)
  94956. ){
  94957. sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
  94958. }else{
  94959. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  94960. if( inReg!=target+i ){
  94961. VdbeOp *pOp;
  94962. if( copyOp==OP_Copy
  94963. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  94964. && pOp->p1+pOp->p3+1==inReg
  94965. && pOp->p2+pOp->p3+1==target+i
  94966. ){
  94967. pOp->p3++;
  94968. }else{
  94969. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  94970. }
  94971. }
  94972. }
  94973. }
  94974. return n;
  94975. }
  94976. /*
  94977. ** Generate code for a BETWEEN operator.
  94978. **
  94979. ** x BETWEEN y AND z
  94980. **
  94981. ** The above is equivalent to
  94982. **
  94983. ** x>=y AND x<=z
  94984. **
  94985. ** Code it as such, taking care to do the common subexpression
  94986. ** elimination of x.
  94987. **
  94988. ** The xJumpIf parameter determines details:
  94989. **
  94990. ** NULL: Store the boolean result in reg[dest]
  94991. ** sqlite3ExprIfTrue: Jump to dest if true
  94992. ** sqlite3ExprIfFalse: Jump to dest if false
  94993. **
  94994. ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
  94995. */
  94996. static void exprCodeBetween(
  94997. Parse *pParse, /* Parsing and code generating context */
  94998. Expr *pExpr, /* The BETWEEN expression */
  94999. int dest, /* Jump destination or storage location */
  95000. void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
  95001. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  95002. ){
  95003. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  95004. Expr compLeft; /* The x>=y term */
  95005. Expr compRight; /* The x<=z term */
  95006. Expr exprX; /* The x subexpression */
  95007. int regFree1 = 0; /* Temporary use register */
  95008. memset(&compLeft, 0, sizeof(Expr));
  95009. memset(&compRight, 0, sizeof(Expr));
  95010. memset(&exprAnd, 0, sizeof(Expr));
  95011. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  95012. exprNodeCopy(&exprX, pExpr->pLeft);
  95013. exprAnd.op = TK_AND;
  95014. exprAnd.pLeft = &compLeft;
  95015. exprAnd.pRight = &compRight;
  95016. compLeft.op = TK_GE;
  95017. compLeft.pLeft = &exprX;
  95018. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  95019. compRight.op = TK_LE;
  95020. compRight.pLeft = &exprX;
  95021. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  95022. exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
  95023. if( xJump ){
  95024. xJump(pParse, &exprAnd, dest, jumpIfNull);
  95025. }else{
  95026. /* Mark the expression is being from the ON or USING clause of a join
  95027. ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
  95028. ** it into the Parse.pConstExpr list. We should use a new bit for this,
  95029. ** for clarity, but we are out of bits in the Expr.flags field so we
  95030. ** have to reuse the EP_FromJoin bit. Bummer. */
  95031. exprX.flags |= EP_FromJoin;
  95032. sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
  95033. }
  95034. sqlite3ReleaseTempReg(pParse, regFree1);
  95035. /* Ensure adequate test coverage */
  95036. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
  95037. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
  95038. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
  95039. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
  95040. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
  95041. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
  95042. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
  95043. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
  95044. testcase( xJump==0 );
  95045. }
  95046. /*
  95047. ** Generate code for a boolean expression such that a jump is made
  95048. ** to the label "dest" if the expression is true but execution
  95049. ** continues straight thru if the expression is false.
  95050. **
  95051. ** If the expression evaluates to NULL (neither true nor false), then
  95052. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  95053. **
  95054. ** This code depends on the fact that certain token values (ex: TK_EQ)
  95055. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  95056. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  95057. ** the make process cause these values to align. Assert()s in the code
  95058. ** below verify that the numbers are aligned correctly.
  95059. */
  95060. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  95061. Vdbe *v = pParse->pVdbe;
  95062. int op = 0;
  95063. int regFree1 = 0;
  95064. int regFree2 = 0;
  95065. int r1, r2;
  95066. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  95067. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  95068. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  95069. op = pExpr->op;
  95070. switch( op ){
  95071. case TK_AND: {
  95072. int d2 = sqlite3VdbeMakeLabel(pParse);
  95073. testcase( jumpIfNull==0 );
  95074. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  95075. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  95076. sqlite3VdbeResolveLabel(v, d2);
  95077. break;
  95078. }
  95079. case TK_OR: {
  95080. testcase( jumpIfNull==0 );
  95081. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  95082. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  95083. break;
  95084. }
  95085. case TK_NOT: {
  95086. testcase( jumpIfNull==0 );
  95087. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  95088. break;
  95089. }
  95090. case TK_TRUTH: {
  95091. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  95092. int isTrue; /* IS TRUE or IS NOT TRUE */
  95093. testcase( jumpIfNull==0 );
  95094. isNot = pExpr->op2==TK_ISNOT;
  95095. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  95096. testcase( isTrue && isNot );
  95097. testcase( !isTrue && isNot );
  95098. if( isTrue ^ isNot ){
  95099. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  95100. isNot ? SQLITE_JUMPIFNULL : 0);
  95101. }else{
  95102. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  95103. isNot ? SQLITE_JUMPIFNULL : 0);
  95104. }
  95105. break;
  95106. }
  95107. case TK_IS:
  95108. case TK_ISNOT:
  95109. testcase( op==TK_IS );
  95110. testcase( op==TK_ISNOT );
  95111. op = (op==TK_IS) ? TK_EQ : TK_NE;
  95112. jumpIfNull = SQLITE_NULLEQ;
  95113. /* Fall thru */
  95114. case TK_LT:
  95115. case TK_LE:
  95116. case TK_GT:
  95117. case TK_GE:
  95118. case TK_NE:
  95119. case TK_EQ: {
  95120. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  95121. testcase( jumpIfNull==0 );
  95122. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  95123. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  95124. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  95125. r1, r2, dest, jumpIfNull);
  95126. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  95127. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  95128. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  95129. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  95130. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  95131. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  95132. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  95133. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  95134. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  95135. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  95136. testcase( regFree1==0 );
  95137. testcase( regFree2==0 );
  95138. break;
  95139. }
  95140. case TK_ISNULL:
  95141. case TK_NOTNULL: {
  95142. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  95143. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  95144. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  95145. sqlite3VdbeAddOp2(v, op, r1, dest);
  95146. VdbeCoverageIf(v, op==TK_ISNULL);
  95147. VdbeCoverageIf(v, op==TK_NOTNULL);
  95148. testcase( regFree1==0 );
  95149. break;
  95150. }
  95151. case TK_BETWEEN: {
  95152. testcase( jumpIfNull==0 );
  95153. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
  95154. break;
  95155. }
  95156. #ifndef SQLITE_OMIT_SUBQUERY
  95157. case TK_IN: {
  95158. int destIfFalse = sqlite3VdbeMakeLabel(pParse);
  95159. int destIfNull = jumpIfNull ? dest : destIfFalse;
  95160. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  95161. sqlite3VdbeGoto(v, dest);
  95162. sqlite3VdbeResolveLabel(v, destIfFalse);
  95163. break;
  95164. }
  95165. #endif
  95166. default: {
  95167. default_expr:
  95168. if( exprAlwaysTrue(pExpr) ){
  95169. sqlite3VdbeGoto(v, dest);
  95170. }else if( exprAlwaysFalse(pExpr) ){
  95171. /* No-op */
  95172. }else{
  95173. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  95174. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  95175. VdbeCoverage(v);
  95176. testcase( regFree1==0 );
  95177. testcase( jumpIfNull==0 );
  95178. }
  95179. break;
  95180. }
  95181. }
  95182. sqlite3ReleaseTempReg(pParse, regFree1);
  95183. sqlite3ReleaseTempReg(pParse, regFree2);
  95184. }
  95185. /*
  95186. ** Generate code for a boolean expression such that a jump is made
  95187. ** to the label "dest" if the expression is false but execution
  95188. ** continues straight thru if the expression is true.
  95189. **
  95190. ** If the expression evaluates to NULL (neither true nor false) then
  95191. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  95192. ** is 0.
  95193. */
  95194. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  95195. Vdbe *v = pParse->pVdbe;
  95196. int op = 0;
  95197. int regFree1 = 0;
  95198. int regFree2 = 0;
  95199. int r1, r2;
  95200. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  95201. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  95202. if( pExpr==0 ) return;
  95203. /* The value of pExpr->op and op are related as follows:
  95204. **
  95205. ** pExpr->op op
  95206. ** --------- ----------
  95207. ** TK_ISNULL OP_NotNull
  95208. ** TK_NOTNULL OP_IsNull
  95209. ** TK_NE OP_Eq
  95210. ** TK_EQ OP_Ne
  95211. ** TK_GT OP_Le
  95212. ** TK_LE OP_Gt
  95213. ** TK_GE OP_Lt
  95214. ** TK_LT OP_Ge
  95215. **
  95216. ** For other values of pExpr->op, op is undefined and unused.
  95217. ** The value of TK_ and OP_ constants are arranged such that we
  95218. ** can compute the mapping above using the following expression.
  95219. ** Assert()s verify that the computation is correct.
  95220. */
  95221. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  95222. /* Verify correct alignment of TK_ and OP_ constants
  95223. */
  95224. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  95225. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  95226. assert( pExpr->op!=TK_NE || op==OP_Eq );
  95227. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  95228. assert( pExpr->op!=TK_LT || op==OP_Ge );
  95229. assert( pExpr->op!=TK_LE || op==OP_Gt );
  95230. assert( pExpr->op!=TK_GT || op==OP_Le );
  95231. assert( pExpr->op!=TK_GE || op==OP_Lt );
  95232. switch( pExpr->op ){
  95233. case TK_AND: {
  95234. testcase( jumpIfNull==0 );
  95235. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  95236. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  95237. break;
  95238. }
  95239. case TK_OR: {
  95240. int d2 = sqlite3VdbeMakeLabel(pParse);
  95241. testcase( jumpIfNull==0 );
  95242. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  95243. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  95244. sqlite3VdbeResolveLabel(v, d2);
  95245. break;
  95246. }
  95247. case TK_NOT: {
  95248. testcase( jumpIfNull==0 );
  95249. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  95250. break;
  95251. }
  95252. case TK_TRUTH: {
  95253. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  95254. int isTrue; /* IS TRUE or IS NOT TRUE */
  95255. testcase( jumpIfNull==0 );
  95256. isNot = pExpr->op2==TK_ISNOT;
  95257. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  95258. testcase( isTrue && isNot );
  95259. testcase( !isTrue && isNot );
  95260. if( isTrue ^ isNot ){
  95261. /* IS TRUE and IS NOT FALSE */
  95262. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  95263. isNot ? 0 : SQLITE_JUMPIFNULL);
  95264. }else{
  95265. /* IS FALSE and IS NOT TRUE */
  95266. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  95267. isNot ? 0 : SQLITE_JUMPIFNULL);
  95268. }
  95269. break;
  95270. }
  95271. case TK_IS:
  95272. case TK_ISNOT:
  95273. testcase( pExpr->op==TK_IS );
  95274. testcase( pExpr->op==TK_ISNOT );
  95275. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  95276. jumpIfNull = SQLITE_NULLEQ;
  95277. /* Fall thru */
  95278. case TK_LT:
  95279. case TK_LE:
  95280. case TK_GT:
  95281. case TK_GE:
  95282. case TK_NE:
  95283. case TK_EQ: {
  95284. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  95285. testcase( jumpIfNull==0 );
  95286. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  95287. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  95288. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  95289. r1, r2, dest, jumpIfNull);
  95290. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  95291. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  95292. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  95293. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  95294. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  95295. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  95296. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  95297. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  95298. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  95299. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  95300. testcase( regFree1==0 );
  95301. testcase( regFree2==0 );
  95302. break;
  95303. }
  95304. case TK_ISNULL:
  95305. case TK_NOTNULL: {
  95306. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  95307. sqlite3VdbeAddOp2(v, op, r1, dest);
  95308. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  95309. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  95310. testcase( regFree1==0 );
  95311. break;
  95312. }
  95313. case TK_BETWEEN: {
  95314. testcase( jumpIfNull==0 );
  95315. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
  95316. break;
  95317. }
  95318. #ifndef SQLITE_OMIT_SUBQUERY
  95319. case TK_IN: {
  95320. if( jumpIfNull ){
  95321. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  95322. }else{
  95323. int destIfNull = sqlite3VdbeMakeLabel(pParse);
  95324. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  95325. sqlite3VdbeResolveLabel(v, destIfNull);
  95326. }
  95327. break;
  95328. }
  95329. #endif
  95330. default: {
  95331. default_expr:
  95332. if( exprAlwaysFalse(pExpr) ){
  95333. sqlite3VdbeGoto(v, dest);
  95334. }else if( exprAlwaysTrue(pExpr) ){
  95335. /* no-op */
  95336. }else{
  95337. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  95338. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  95339. VdbeCoverage(v);
  95340. testcase( regFree1==0 );
  95341. testcase( jumpIfNull==0 );
  95342. }
  95343. break;
  95344. }
  95345. }
  95346. sqlite3ReleaseTempReg(pParse, regFree1);
  95347. sqlite3ReleaseTempReg(pParse, regFree2);
  95348. }
  95349. /*
  95350. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  95351. ** code generation, and that copy is deleted after code generation. This
  95352. ** ensures that the original pExpr is unchanged.
  95353. */
  95354. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  95355. sqlite3 *db = pParse->db;
  95356. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  95357. if( db->mallocFailed==0 ){
  95358. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  95359. }
  95360. sqlite3ExprDelete(db, pCopy);
  95361. }
  95362. /*
  95363. ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
  95364. ** type of expression.
  95365. **
  95366. ** If pExpr is a simple SQL value - an integer, real, string, blob
  95367. ** or NULL value - then the VDBE currently being prepared is configured
  95368. ** to re-prepare each time a new value is bound to variable pVar.
  95369. **
  95370. ** Additionally, if pExpr is a simple SQL value and the value is the
  95371. ** same as that currently bound to variable pVar, non-zero is returned.
  95372. ** Otherwise, if the values are not the same or if pExpr is not a simple
  95373. ** SQL value, zero is returned.
  95374. */
  95375. static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
  95376. int res = 0;
  95377. int iVar;
  95378. sqlite3_value *pL, *pR = 0;
  95379. sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
  95380. if( pR ){
  95381. iVar = pVar->iColumn;
  95382. sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
  95383. pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
  95384. if( pL ){
  95385. if( sqlite3_value_type(pL)==SQLITE_TEXT ){
  95386. sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
  95387. }
  95388. res = 0==sqlite3MemCompare(pL, pR, 0);
  95389. }
  95390. sqlite3ValueFree(pR);
  95391. sqlite3ValueFree(pL);
  95392. }
  95393. return res;
  95394. }
  95395. /*
  95396. ** Do a deep comparison of two expression trees. Return 0 if the two
  95397. ** expressions are completely identical. Return 1 if they differ only
  95398. ** by a COLLATE operator at the top level. Return 2 if there are differences
  95399. ** other than the top-level COLLATE operator.
  95400. **
  95401. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  95402. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  95403. **
  95404. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  95405. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  95406. **
  95407. ** Sometimes this routine will return 2 even if the two expressions
  95408. ** really are equivalent. If we cannot prove that the expressions are
  95409. ** identical, we return 2 just to be safe. So if this routine
  95410. ** returns 2, then you do not really know for certain if the two
  95411. ** expressions are the same. But if you get a 0 or 1 return, then you
  95412. ** can be sure the expressions are the same. In the places where
  95413. ** this routine is used, it does not hurt to get an extra 2 - that
  95414. ** just might result in some slightly slower code. But returning
  95415. ** an incorrect 0 or 1 could lead to a malfunction.
  95416. **
  95417. ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
  95418. ** pParse->pReprepare can be matched against literals in pB. The
  95419. ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
  95420. ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
  95421. ** Argument pParse should normally be NULL. If it is not NULL and pA or
  95422. ** pB causes a return value of 2.
  95423. */
  95424. SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
  95425. u32 combinedFlags;
  95426. if( pA==0 || pB==0 ){
  95427. return pB==pA ? 0 : 2;
  95428. }
  95429. if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
  95430. return 0;
  95431. }
  95432. combinedFlags = pA->flags | pB->flags;
  95433. if( combinedFlags & EP_IntValue ){
  95434. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  95435. return 0;
  95436. }
  95437. return 2;
  95438. }
  95439. if( pA->op!=pB->op || pA->op==TK_RAISE ){
  95440. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
  95441. return 1;
  95442. }
  95443. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
  95444. return 1;
  95445. }
  95446. return 2;
  95447. }
  95448. if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
  95449. if( pA->op==TK_FUNCTION ){
  95450. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  95451. #ifndef SQLITE_OMIT_WINDOWFUNC
  95452. /* Justification for the assert():
  95453. ** window functions have p->op==TK_FUNCTION but aggregate functions
  95454. ** have p->op==TK_AGG_FUNCTION. So any comparison between an aggregate
  95455. ** function and a window function should have failed before reaching
  95456. ** this point. And, it is not possible to have a window function and
  95457. ** a scalar function with the same name and number of arguments. So
  95458. ** if we reach this point, either A and B both window functions or
  95459. ** neither are a window functions. */
  95460. assert( ExprHasProperty(pA,EP_WinFunc)==ExprHasProperty(pB,EP_WinFunc) );
  95461. if( ExprHasProperty(pA,EP_WinFunc) ){
  95462. if( sqlite3WindowCompare(pParse,pA->y.pWin,pB->y.pWin)!=0 ) return 2;
  95463. }
  95464. #endif
  95465. }else if( pA->op==TK_NULL ){
  95466. return 0;
  95467. }else if( pA->op==TK_COLLATE ){
  95468. if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  95469. }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  95470. return 2;
  95471. }
  95472. }
  95473. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  95474. if( (combinedFlags & EP_TokenOnly)==0 ){
  95475. if( combinedFlags & EP_xIsSelect ) return 2;
  95476. if( (combinedFlags & EP_FixedCol)==0
  95477. && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
  95478. if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
  95479. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  95480. if( pA->op!=TK_STRING
  95481. && pA->op!=TK_TRUEFALSE
  95482. && (combinedFlags & EP_Reduced)==0
  95483. ){
  95484. if( pA->iColumn!=pB->iColumn ) return 2;
  95485. if( pA->iTable!=pB->iTable
  95486. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  95487. }
  95488. }
  95489. return 0;
  95490. }
  95491. /*
  95492. ** Compare two ExprList objects. Return 0 if they are identical and
  95493. ** non-zero if they differ in any way.
  95494. **
  95495. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  95496. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  95497. **
  95498. ** This routine might return non-zero for equivalent ExprLists. The
  95499. ** only consequence will be disabled optimizations. But this routine
  95500. ** must never return 0 if the two ExprList objects are different, or
  95501. ** a malfunction will result.
  95502. **
  95503. ** Two NULL pointers are considered to be the same. But a NULL pointer
  95504. ** always differs from a non-NULL pointer.
  95505. */
  95506. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  95507. int i;
  95508. if( pA==0 && pB==0 ) return 0;
  95509. if( pA==0 || pB==0 ) return 1;
  95510. if( pA->nExpr!=pB->nExpr ) return 1;
  95511. for(i=0; i<pA->nExpr; i++){
  95512. Expr *pExprA = pA->a[i].pExpr;
  95513. Expr *pExprB = pB->a[i].pExpr;
  95514. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  95515. if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
  95516. }
  95517. return 0;
  95518. }
  95519. /*
  95520. ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
  95521. ** are ignored.
  95522. */
  95523. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
  95524. return sqlite3ExprCompare(0,
  95525. sqlite3ExprSkipCollate(pA),
  95526. sqlite3ExprSkipCollate(pB),
  95527. iTab);
  95528. }
  95529. /*
  95530. ** Return true if we can prove the pE2 will always be true if pE1 is
  95531. ** true. Return false if we cannot complete the proof or if pE2 might
  95532. ** be false. Examples:
  95533. **
  95534. ** pE1: x==5 pE2: x==5 Result: true
  95535. ** pE1: x>0 pE2: x==5 Result: false
  95536. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  95537. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  95538. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  95539. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  95540. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  95541. **
  95542. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  95543. ** Expr.iTable<0 then assume a table number given by iTab.
  95544. **
  95545. ** If pParse is not NULL, then the values of bound variables in pE1 are
  95546. ** compared against literal values in pE2 and pParse->pVdbe->expmask is
  95547. ** modified to record which bound variables are referenced. If pParse
  95548. ** is NULL, then false will be returned if pE1 contains any bound variables.
  95549. **
  95550. ** When in doubt, return false. Returning true might give a performance
  95551. ** improvement. Returning false might cause a performance reduction, but
  95552. ** it will always give the correct answer and is hence always safe.
  95553. */
  95554. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
  95555. if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
  95556. return 1;
  95557. }
  95558. if( pE2->op==TK_OR
  95559. && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
  95560. || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
  95561. ){
  95562. return 1;
  95563. }
  95564. if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
  95565. Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
  95566. testcase( pX!=pE1->pLeft );
  95567. if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
  95568. }
  95569. return 0;
  95570. }
  95571. /*
  95572. ** This is the Expr node callback for sqlite3ExprImpliesNotNullRow().
  95573. ** If the expression node requires that the table at pWalker->iCur
  95574. ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
  95575. **
  95576. ** This routine controls an optimization. False positives (setting
  95577. ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
  95578. ** (never setting pWalker->eCode) is a harmless missed optimization.
  95579. */
  95580. static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
  95581. testcase( pExpr->op==TK_AGG_COLUMN );
  95582. testcase( pExpr->op==TK_AGG_FUNCTION );
  95583. if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
  95584. switch( pExpr->op ){
  95585. case TK_ISNOT:
  95586. case TK_NOT:
  95587. case TK_ISNULL:
  95588. case TK_NOTNULL:
  95589. case TK_IS:
  95590. case TK_OR:
  95591. case TK_CASE:
  95592. case TK_IN:
  95593. case TK_FUNCTION:
  95594. testcase( pExpr->op==TK_ISNOT );
  95595. testcase( pExpr->op==TK_NOT );
  95596. testcase( pExpr->op==TK_ISNULL );
  95597. testcase( pExpr->op==TK_NOTNULL );
  95598. testcase( pExpr->op==TK_IS );
  95599. testcase( pExpr->op==TK_OR );
  95600. testcase( pExpr->op==TK_CASE );
  95601. testcase( pExpr->op==TK_IN );
  95602. testcase( pExpr->op==TK_FUNCTION );
  95603. return WRC_Prune;
  95604. case TK_COLUMN:
  95605. if( pWalker->u.iCur==pExpr->iTable ){
  95606. pWalker->eCode = 1;
  95607. return WRC_Abort;
  95608. }
  95609. return WRC_Prune;
  95610. /* Virtual tables are allowed to use constraints like x=NULL. So
  95611. ** a term of the form x=y does not prove that y is not null if x
  95612. ** is the column of a virtual table */
  95613. case TK_EQ:
  95614. case TK_NE:
  95615. case TK_LT:
  95616. case TK_LE:
  95617. case TK_GT:
  95618. case TK_GE:
  95619. testcase( pExpr->op==TK_EQ );
  95620. testcase( pExpr->op==TK_NE );
  95621. testcase( pExpr->op==TK_LT );
  95622. testcase( pExpr->op==TK_LE );
  95623. testcase( pExpr->op==TK_GT );
  95624. testcase( pExpr->op==TK_GE );
  95625. if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab))
  95626. || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab))
  95627. ){
  95628. return WRC_Prune;
  95629. }
  95630. default:
  95631. return WRC_Continue;
  95632. }
  95633. }
  95634. /*
  95635. ** Return true (non-zero) if expression p can only be true if at least
  95636. ** one column of table iTab is non-null. In other words, return true
  95637. ** if expression p will always be NULL or false if every column of iTab
  95638. ** is NULL.
  95639. **
  95640. ** False negatives are acceptable. In other words, it is ok to return
  95641. ** zero even if expression p will never be true of every column of iTab
  95642. ** is NULL. A false negative is merely a missed optimization opportunity.
  95643. **
  95644. ** False positives are not allowed, however. A false positive may result
  95645. ** in an incorrect answer.
  95646. **
  95647. ** Terms of p that are marked with EP_FromJoin (and hence that come from
  95648. ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
  95649. **
  95650. ** This routine is used to check if a LEFT JOIN can be converted into
  95651. ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
  95652. ** clause requires that some column of the right table of the LEFT JOIN
  95653. ** be non-NULL, then the LEFT JOIN can be safely converted into an
  95654. ** ordinary join.
  95655. */
  95656. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
  95657. Walker w;
  95658. p = sqlite3ExprSkipCollate(p);
  95659. while( p ){
  95660. if( p->op==TK_NOTNULL ){
  95661. p = p->pLeft;
  95662. }else if( p->op==TK_AND ){
  95663. if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
  95664. p = p->pRight;
  95665. }else{
  95666. break;
  95667. }
  95668. }
  95669. w.xExprCallback = impliesNotNullRow;
  95670. w.xSelectCallback = 0;
  95671. w.xSelectCallback2 = 0;
  95672. w.eCode = 0;
  95673. w.u.iCur = iTab;
  95674. sqlite3WalkExpr(&w, p);
  95675. return w.eCode;
  95676. }
  95677. /*
  95678. ** An instance of the following structure is used by the tree walker
  95679. ** to determine if an expression can be evaluated by reference to the
  95680. ** index only, without having to do a search for the corresponding
  95681. ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
  95682. ** is the cursor for the table.
  95683. */
  95684. struct IdxCover {
  95685. Index *pIdx; /* The index to be tested for coverage */
  95686. int iCur; /* Cursor number for the table corresponding to the index */
  95687. };
  95688. /*
  95689. ** Check to see if there are references to columns in table
  95690. ** pWalker->u.pIdxCover->iCur can be satisfied using the index
  95691. ** pWalker->u.pIdxCover->pIdx.
  95692. */
  95693. static int exprIdxCover(Walker *pWalker, Expr *pExpr){
  95694. if( pExpr->op==TK_COLUMN
  95695. && pExpr->iTable==pWalker->u.pIdxCover->iCur
  95696. && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
  95697. ){
  95698. pWalker->eCode = 1;
  95699. return WRC_Abort;
  95700. }
  95701. return WRC_Continue;
  95702. }
  95703. /*
  95704. ** Determine if an index pIdx on table with cursor iCur contains will
  95705. ** the expression pExpr. Return true if the index does cover the
  95706. ** expression and false if the pExpr expression references table columns
  95707. ** that are not found in the index pIdx.
  95708. **
  95709. ** An index covering an expression means that the expression can be
  95710. ** evaluated using only the index and without having to lookup the
  95711. ** corresponding table entry.
  95712. */
  95713. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
  95714. Expr *pExpr, /* The index to be tested */
  95715. int iCur, /* The cursor number for the corresponding table */
  95716. Index *pIdx /* The index that might be used for coverage */
  95717. ){
  95718. Walker w;
  95719. struct IdxCover xcov;
  95720. memset(&w, 0, sizeof(w));
  95721. xcov.iCur = iCur;
  95722. xcov.pIdx = pIdx;
  95723. w.xExprCallback = exprIdxCover;
  95724. w.u.pIdxCover = &xcov;
  95725. sqlite3WalkExpr(&w, pExpr);
  95726. return !w.eCode;
  95727. }
  95728. /*
  95729. ** An instance of the following structure is used by the tree walker
  95730. ** to count references to table columns in the arguments of an
  95731. ** aggregate function, in order to implement the
  95732. ** sqlite3FunctionThisSrc() routine.
  95733. */
  95734. struct SrcCount {
  95735. SrcList *pSrc; /* One particular FROM clause in a nested query */
  95736. int nThis; /* Number of references to columns in pSrcList */
  95737. int nOther; /* Number of references to columns in other FROM clauses */
  95738. };
  95739. /*
  95740. ** Count the number of references to columns.
  95741. */
  95742. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  95743. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  95744. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  95745. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  95746. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  95747. ** NEVER() will need to be removed. */
  95748. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  95749. int i;
  95750. struct SrcCount *p = pWalker->u.pSrcCount;
  95751. SrcList *pSrc = p->pSrc;
  95752. int nSrc = pSrc ? pSrc->nSrc : 0;
  95753. for(i=0; i<nSrc; i++){
  95754. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  95755. }
  95756. if( i<nSrc ){
  95757. p->nThis++;
  95758. }else{
  95759. p->nOther++;
  95760. }
  95761. }
  95762. return WRC_Continue;
  95763. }
  95764. /*
  95765. ** Determine if any of the arguments to the pExpr Function reference
  95766. ** pSrcList. Return true if they do. Also return true if the function
  95767. ** has no arguments or has only constant arguments. Return false if pExpr
  95768. ** references columns but not columns of tables found in pSrcList.
  95769. */
  95770. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  95771. Walker w;
  95772. struct SrcCount cnt;
  95773. assert( pExpr->op==TK_AGG_FUNCTION );
  95774. w.xExprCallback = exprSrcCount;
  95775. w.xSelectCallback = 0;
  95776. w.u.pSrcCount = &cnt;
  95777. cnt.pSrc = pSrcList;
  95778. cnt.nThis = 0;
  95779. cnt.nOther = 0;
  95780. sqlite3WalkExprList(&w, pExpr->x.pList);
  95781. return cnt.nThis>0 || cnt.nOther==0;
  95782. }
  95783. /*
  95784. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  95785. ** the new element. Return a negative number if malloc fails.
  95786. */
  95787. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  95788. int i;
  95789. pInfo->aCol = sqlite3ArrayAllocate(
  95790. db,
  95791. pInfo->aCol,
  95792. sizeof(pInfo->aCol[0]),
  95793. &pInfo->nColumn,
  95794. &i
  95795. );
  95796. return i;
  95797. }
  95798. /*
  95799. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  95800. ** the new element. Return a negative number if malloc fails.
  95801. */
  95802. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  95803. int i;
  95804. pInfo->aFunc = sqlite3ArrayAllocate(
  95805. db,
  95806. pInfo->aFunc,
  95807. sizeof(pInfo->aFunc[0]),
  95808. &pInfo->nFunc,
  95809. &i
  95810. );
  95811. return i;
  95812. }
  95813. /*
  95814. ** This is the xExprCallback for a tree walker. It is used to
  95815. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  95816. ** for additional information.
  95817. */
  95818. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  95819. int i;
  95820. NameContext *pNC = pWalker->u.pNC;
  95821. Parse *pParse = pNC->pParse;
  95822. SrcList *pSrcList = pNC->pSrcList;
  95823. AggInfo *pAggInfo = pNC->uNC.pAggInfo;
  95824. assert( pNC->ncFlags & NC_UAggInfo );
  95825. switch( pExpr->op ){
  95826. case TK_AGG_COLUMN:
  95827. case TK_COLUMN: {
  95828. testcase( pExpr->op==TK_AGG_COLUMN );
  95829. testcase( pExpr->op==TK_COLUMN );
  95830. /* Check to see if the column is in one of the tables in the FROM
  95831. ** clause of the aggregate query */
  95832. if( ALWAYS(pSrcList!=0) ){
  95833. struct SrcList_item *pItem = pSrcList->a;
  95834. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  95835. struct AggInfo_col *pCol;
  95836. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  95837. if( pExpr->iTable==pItem->iCursor ){
  95838. /* If we reach this point, it means that pExpr refers to a table
  95839. ** that is in the FROM clause of the aggregate query.
  95840. **
  95841. ** Make an entry for the column in pAggInfo->aCol[] if there
  95842. ** is not an entry there already.
  95843. */
  95844. int k;
  95845. pCol = pAggInfo->aCol;
  95846. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  95847. if( pCol->iTable==pExpr->iTable &&
  95848. pCol->iColumn==pExpr->iColumn ){
  95849. break;
  95850. }
  95851. }
  95852. if( (k>=pAggInfo->nColumn)
  95853. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  95854. ){
  95855. pCol = &pAggInfo->aCol[k];
  95856. pCol->pTab = pExpr->y.pTab;
  95857. pCol->iTable = pExpr->iTable;
  95858. pCol->iColumn = pExpr->iColumn;
  95859. pCol->iMem = ++pParse->nMem;
  95860. pCol->iSorterColumn = -1;
  95861. pCol->pExpr = pExpr;
  95862. if( pAggInfo->pGroupBy ){
  95863. int j, n;
  95864. ExprList *pGB = pAggInfo->pGroupBy;
  95865. struct ExprList_item *pTerm = pGB->a;
  95866. n = pGB->nExpr;
  95867. for(j=0; j<n; j++, pTerm++){
  95868. Expr *pE = pTerm->pExpr;
  95869. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  95870. pE->iColumn==pExpr->iColumn ){
  95871. pCol->iSorterColumn = j;
  95872. break;
  95873. }
  95874. }
  95875. }
  95876. if( pCol->iSorterColumn<0 ){
  95877. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  95878. }
  95879. }
  95880. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  95881. ** because it was there before or because we just created it).
  95882. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  95883. ** pAggInfo->aCol[] entry.
  95884. */
  95885. ExprSetVVAProperty(pExpr, EP_NoReduce);
  95886. pExpr->pAggInfo = pAggInfo;
  95887. pExpr->op = TK_AGG_COLUMN;
  95888. pExpr->iAgg = (i16)k;
  95889. break;
  95890. } /* endif pExpr->iTable==pItem->iCursor */
  95891. } /* end loop over pSrcList */
  95892. }
  95893. return WRC_Prune;
  95894. }
  95895. case TK_AGG_FUNCTION: {
  95896. if( (pNC->ncFlags & NC_InAggFunc)==0
  95897. && pWalker->walkerDepth==pExpr->op2
  95898. ){
  95899. /* Check to see if pExpr is a duplicate of another aggregate
  95900. ** function that is already in the pAggInfo structure
  95901. */
  95902. struct AggInfo_func *pItem = pAggInfo->aFunc;
  95903. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  95904. if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
  95905. break;
  95906. }
  95907. }
  95908. if( i>=pAggInfo->nFunc ){
  95909. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  95910. */
  95911. u8 enc = ENC(pParse->db);
  95912. i = addAggInfoFunc(pParse->db, pAggInfo);
  95913. if( i>=0 ){
  95914. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  95915. pItem = &pAggInfo->aFunc[i];
  95916. pItem->pExpr = pExpr;
  95917. pItem->iMem = ++pParse->nMem;
  95918. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  95919. pItem->pFunc = sqlite3FindFunction(pParse->db,
  95920. pExpr->u.zToken,
  95921. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  95922. if( pExpr->flags & EP_Distinct ){
  95923. pItem->iDistinct = pParse->nTab++;
  95924. }else{
  95925. pItem->iDistinct = -1;
  95926. }
  95927. }
  95928. }
  95929. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  95930. */
  95931. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  95932. ExprSetVVAProperty(pExpr, EP_NoReduce);
  95933. pExpr->iAgg = (i16)i;
  95934. pExpr->pAggInfo = pAggInfo;
  95935. return WRC_Prune;
  95936. }else{
  95937. return WRC_Continue;
  95938. }
  95939. }
  95940. }
  95941. return WRC_Continue;
  95942. }
  95943. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  95944. UNUSED_PARAMETER(pSelect);
  95945. pWalker->walkerDepth++;
  95946. return WRC_Continue;
  95947. }
  95948. static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
  95949. UNUSED_PARAMETER(pSelect);
  95950. pWalker->walkerDepth--;
  95951. }
  95952. /*
  95953. ** Analyze the pExpr expression looking for aggregate functions and
  95954. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  95955. ** points to. Additional entries are made on the AggInfo object as
  95956. ** necessary.
  95957. **
  95958. ** This routine should only be called after the expression has been
  95959. ** analyzed by sqlite3ResolveExprNames().
  95960. */
  95961. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  95962. Walker w;
  95963. w.xExprCallback = analyzeAggregate;
  95964. w.xSelectCallback = analyzeAggregatesInSelect;
  95965. w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
  95966. w.walkerDepth = 0;
  95967. w.u.pNC = pNC;
  95968. w.pParse = 0;
  95969. assert( pNC->pSrcList!=0 );
  95970. sqlite3WalkExpr(&w, pExpr);
  95971. }
  95972. /*
  95973. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  95974. ** expression list. Return the number of errors.
  95975. **
  95976. ** If an error is found, the analysis is cut short.
  95977. */
  95978. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  95979. struct ExprList_item *pItem;
  95980. int i;
  95981. if( pList ){
  95982. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  95983. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  95984. }
  95985. }
  95986. }
  95987. /*
  95988. ** Allocate a single new register for use to hold some intermediate result.
  95989. */
  95990. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  95991. if( pParse->nTempReg==0 ){
  95992. return ++pParse->nMem;
  95993. }
  95994. return pParse->aTempReg[--pParse->nTempReg];
  95995. }
  95996. /*
  95997. ** Deallocate a register, making available for reuse for some other
  95998. ** purpose.
  95999. */
  96000. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  96001. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  96002. pParse->aTempReg[pParse->nTempReg++] = iReg;
  96003. }
  96004. }
  96005. /*
  96006. ** Allocate or deallocate a block of nReg consecutive registers.
  96007. */
  96008. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  96009. int i, n;
  96010. if( nReg==1 ) return sqlite3GetTempReg(pParse);
  96011. i = pParse->iRangeReg;
  96012. n = pParse->nRangeReg;
  96013. if( nReg<=n ){
  96014. pParse->iRangeReg += nReg;
  96015. pParse->nRangeReg -= nReg;
  96016. }else{
  96017. i = pParse->nMem+1;
  96018. pParse->nMem += nReg;
  96019. }
  96020. return i;
  96021. }
  96022. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  96023. if( nReg==1 ){
  96024. sqlite3ReleaseTempReg(pParse, iReg);
  96025. return;
  96026. }
  96027. if( nReg>pParse->nRangeReg ){
  96028. pParse->nRangeReg = nReg;
  96029. pParse->iRangeReg = iReg;
  96030. }
  96031. }
  96032. /*
  96033. ** Mark all temporary registers as being unavailable for reuse.
  96034. */
  96035. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  96036. pParse->nTempReg = 0;
  96037. pParse->nRangeReg = 0;
  96038. }
  96039. /*
  96040. ** Validate that no temporary register falls within the range of
  96041. ** iFirst..iLast, inclusive. This routine is only call from within assert()
  96042. ** statements.
  96043. */
  96044. #ifdef SQLITE_DEBUG
  96045. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  96046. int i;
  96047. if( pParse->nRangeReg>0
  96048. && pParse->iRangeReg+pParse->nRangeReg > iFirst
  96049. && pParse->iRangeReg <= iLast
  96050. ){
  96051. return 0;
  96052. }
  96053. for(i=0; i<pParse->nTempReg; i++){
  96054. if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
  96055. return 0;
  96056. }
  96057. }
  96058. return 1;
  96059. }
  96060. #endif /* SQLITE_DEBUG */
  96061. /************** End of expr.c ************************************************/
  96062. /************** Begin file alter.c *******************************************/
  96063. /*
  96064. ** 2005 February 15
  96065. **
  96066. ** The author disclaims copyright to this source code. In place of
  96067. ** a legal notice, here is a blessing:
  96068. **
  96069. ** May you do good and not evil.
  96070. ** May you find forgiveness for yourself and forgive others.
  96071. ** May you share freely, never taking more than you give.
  96072. **
  96073. *************************************************************************
  96074. ** This file contains C code routines that used to generate VDBE code
  96075. ** that implements the ALTER TABLE command.
  96076. */
  96077. /* #include "sqliteInt.h" */
  96078. /*
  96079. ** The code in this file only exists if we are not omitting the
  96080. ** ALTER TABLE logic from the build.
  96081. */
  96082. #ifndef SQLITE_OMIT_ALTERTABLE
  96083. /*
  96084. ** Parameter zName is the name of a table that is about to be altered
  96085. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  96086. ** If the table is a system table, this function leaves an error message
  96087. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  96088. **
  96089. ** Or, if zName is not a system table, zero is returned.
  96090. */
  96091. static int isAlterableTable(Parse *pParse, Table *pTab){
  96092. if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
  96093. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96094. || ( (pTab->tabFlags & TF_Shadow)
  96095. && (pParse->db->flags & SQLITE_Defensive)
  96096. && pParse->db->nVdbeExec==0
  96097. )
  96098. #endif
  96099. ){
  96100. sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
  96101. return 1;
  96102. }
  96103. return 0;
  96104. }
  96105. /*
  96106. ** Generate code to verify that the schemas of database zDb and, if
  96107. ** bTemp is not true, database "temp", can still be parsed. This is
  96108. ** called at the end of the generation of an ALTER TABLE ... RENAME ...
  96109. ** statement to ensure that the operation has not rendered any schema
  96110. ** objects unusable.
  96111. */
  96112. static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
  96113. sqlite3NestedParse(pParse,
  96114. "SELECT 1 "
  96115. "FROM \"%w\".%s "
  96116. "WHERE name NOT LIKE 'sqlite_%%'"
  96117. " AND sql NOT LIKE 'create virtual%%'"
  96118. " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
  96119. zDb, MASTER_NAME,
  96120. zDb, bTemp
  96121. );
  96122. if( bTemp==0 ){
  96123. sqlite3NestedParse(pParse,
  96124. "SELECT 1 "
  96125. "FROM temp.%s "
  96126. "WHERE name NOT LIKE 'sqlite_%%'"
  96127. " AND sql NOT LIKE 'create virtual%%'"
  96128. " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
  96129. MASTER_NAME, zDb
  96130. );
  96131. }
  96132. }
  96133. /*
  96134. ** Generate code to reload the schema for database iDb. And, if iDb!=1, for
  96135. ** the temp database as well.
  96136. */
  96137. static void renameReloadSchema(Parse *pParse, int iDb){
  96138. Vdbe *v = pParse->pVdbe;
  96139. if( v ){
  96140. sqlite3ChangeCookie(pParse, iDb);
  96141. sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
  96142. if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
  96143. }
  96144. }
  96145. /*
  96146. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  96147. ** command.
  96148. */
  96149. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  96150. Parse *pParse, /* Parser context. */
  96151. SrcList *pSrc, /* The table to rename. */
  96152. Token *pName /* The new table name. */
  96153. ){
  96154. int iDb; /* Database that contains the table */
  96155. char *zDb; /* Name of database iDb */
  96156. Table *pTab; /* Table being renamed */
  96157. char *zName = 0; /* NULL-terminated version of pName */
  96158. sqlite3 *db = pParse->db; /* Database connection */
  96159. int nTabName; /* Number of UTF-8 characters in zTabName */
  96160. const char *zTabName; /* Original name of the table */
  96161. Vdbe *v;
  96162. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  96163. u32 savedDbFlags; /* Saved value of db->mDbFlags */
  96164. savedDbFlags = db->mDbFlags;
  96165. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  96166. assert( pSrc->nSrc==1 );
  96167. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  96168. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  96169. if( !pTab ) goto exit_rename_table;
  96170. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  96171. zDb = db->aDb[iDb].zDbSName;
  96172. db->mDbFlags |= DBFLAG_PreferBuiltin;
  96173. /* Get a NULL terminated version of the new table name. */
  96174. zName = sqlite3NameFromToken(db, pName);
  96175. if( !zName ) goto exit_rename_table;
  96176. /* Check that a table or index named 'zName' does not already exist
  96177. ** in database iDb. If so, this is an error.
  96178. */
  96179. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  96180. sqlite3ErrorMsg(pParse,
  96181. "there is already another table or index with this name: %s", zName);
  96182. goto exit_rename_table;
  96183. }
  96184. /* Make sure it is not a system table being altered, or a reserved name
  96185. ** that the table is being renamed to.
  96186. */
  96187. if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
  96188. goto exit_rename_table;
  96189. }
  96190. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  96191. exit_rename_table;
  96192. }
  96193. #ifndef SQLITE_OMIT_VIEW
  96194. if( pTab->pSelect ){
  96195. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  96196. goto exit_rename_table;
  96197. }
  96198. #endif
  96199. #ifndef SQLITE_OMIT_AUTHORIZATION
  96200. /* Invoke the authorization callback. */
  96201. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  96202. goto exit_rename_table;
  96203. }
  96204. #endif
  96205. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96206. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  96207. goto exit_rename_table;
  96208. }
  96209. if( IsVirtual(pTab) ){
  96210. pVTab = sqlite3GetVTable(db, pTab);
  96211. if( pVTab->pVtab->pModule->xRename==0 ){
  96212. pVTab = 0;
  96213. }
  96214. }
  96215. #endif
  96216. /* Begin a transaction for database iDb. Then modify the schema cookie
  96217. ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
  96218. ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
  96219. ** nested SQL may raise an exception. */
  96220. v = sqlite3GetVdbe(pParse);
  96221. if( v==0 ){
  96222. goto exit_rename_table;
  96223. }
  96224. sqlite3MayAbort(pParse);
  96225. /* figure out how many UTF-8 characters are in zName */
  96226. zTabName = pTab->zName;
  96227. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  96228. /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
  96229. ** the schema to use the new table name. */
  96230. sqlite3NestedParse(pParse,
  96231. "UPDATE \"%w\".%s SET "
  96232. "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
  96233. "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
  96234. "AND name NOT LIKE 'sqlite_%%'"
  96235. , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
  96236. );
  96237. /* Update the tbl_name and name columns of the sqlite_master table
  96238. ** as required. */
  96239. sqlite3NestedParse(pParse,
  96240. "UPDATE %Q.%s SET "
  96241. "tbl_name = %Q, "
  96242. "name = CASE "
  96243. "WHEN type='table' THEN %Q "
  96244. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  96245. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  96246. "ELSE name END "
  96247. "WHERE tbl_name=%Q COLLATE nocase AND "
  96248. "(type='table' OR type='index' OR type='trigger');",
  96249. zDb, MASTER_NAME,
  96250. zName, zName, zName,
  96251. nTabName, zTabName
  96252. );
  96253. #ifndef SQLITE_OMIT_AUTOINCREMENT
  96254. /* If the sqlite_sequence table exists in this database, then update
  96255. ** it with the new table name.
  96256. */
  96257. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  96258. sqlite3NestedParse(pParse,
  96259. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  96260. zDb, zName, pTab->zName);
  96261. }
  96262. #endif
  96263. /* If the table being renamed is not itself part of the temp database,
  96264. ** edit view and trigger definitions within the temp database
  96265. ** as required. */
  96266. if( iDb!=1 ){
  96267. sqlite3NestedParse(pParse,
  96268. "UPDATE sqlite_temp_master SET "
  96269. "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
  96270. "tbl_name = "
  96271. "CASE WHEN tbl_name=%Q COLLATE nocase AND "
  96272. " sqlite_rename_test(%Q, sql, type, name, 1) "
  96273. "THEN %Q ELSE tbl_name END "
  96274. "WHERE type IN ('view', 'trigger')"
  96275. , zDb, zTabName, zName, zTabName, zDb, zName);
  96276. }
  96277. /* If this is a virtual table, invoke the xRename() function if
  96278. ** one is defined. The xRename() callback will modify the names
  96279. ** of any resources used by the v-table implementation (including other
  96280. ** SQLite tables) that are identified by the name of the virtual table.
  96281. */
  96282. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96283. if( pVTab ){
  96284. int i = ++pParse->nMem;
  96285. sqlite3VdbeLoadString(v, i, zName);
  96286. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  96287. }
  96288. #endif
  96289. renameReloadSchema(pParse, iDb);
  96290. renameTestSchema(pParse, zDb, iDb==1);
  96291. exit_rename_table:
  96292. sqlite3SrcListDelete(db, pSrc);
  96293. sqlite3DbFree(db, zName);
  96294. db->mDbFlags = savedDbFlags;
  96295. }
  96296. /*
  96297. ** This function is called after an "ALTER TABLE ... ADD" statement
  96298. ** has been parsed. Argument pColDef contains the text of the new
  96299. ** column definition.
  96300. **
  96301. ** The Table structure pParse->pNewTable was extended to include
  96302. ** the new column during parsing.
  96303. */
  96304. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  96305. Table *pNew; /* Copy of pParse->pNewTable */
  96306. Table *pTab; /* Table being altered */
  96307. int iDb; /* Database number */
  96308. const char *zDb; /* Database name */
  96309. const char *zTab; /* Table name */
  96310. char *zCol; /* Null-terminated column definition */
  96311. Column *pCol; /* The new column */
  96312. Expr *pDflt; /* Default value for the new column */
  96313. sqlite3 *db; /* The database connection; */
  96314. Vdbe *v; /* The prepared statement under construction */
  96315. int r1; /* Temporary registers */
  96316. db = pParse->db;
  96317. if( pParse->nErr || db->mallocFailed ) return;
  96318. pNew = pParse->pNewTable;
  96319. assert( pNew );
  96320. assert( sqlite3BtreeHoldsAllMutexes(db) );
  96321. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  96322. zDb = db->aDb[iDb].zDbSName;
  96323. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  96324. pCol = &pNew->aCol[pNew->nCol-1];
  96325. pDflt = pCol->pDflt;
  96326. pTab = sqlite3FindTable(db, zTab, zDb);
  96327. assert( pTab );
  96328. #ifndef SQLITE_OMIT_AUTHORIZATION
  96329. /* Invoke the authorization callback. */
  96330. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  96331. return;
  96332. }
  96333. #endif
  96334. /* If the default value for the new column was specified with a
  96335. ** literal NULL, then set pDflt to 0. This simplifies checking
  96336. ** for an SQL NULL default below.
  96337. */
  96338. assert( pDflt==0 || pDflt->op==TK_SPAN );
  96339. if( pDflt && pDflt->pLeft->op==TK_NULL ){
  96340. pDflt = 0;
  96341. }
  96342. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  96343. ** If there is a NOT NULL constraint, then the default value for the
  96344. ** column must not be NULL.
  96345. */
  96346. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  96347. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  96348. return;
  96349. }
  96350. if( pNew->pIndex ){
  96351. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  96352. return;
  96353. }
  96354. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  96355. sqlite3ErrorMsg(pParse,
  96356. "Cannot add a REFERENCES column with non-NULL default value");
  96357. return;
  96358. }
  96359. if( pCol->notNull && !pDflt ){
  96360. sqlite3ErrorMsg(pParse,
  96361. "Cannot add a NOT NULL column with default value NULL");
  96362. return;
  96363. }
  96364. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  96365. ** can handle (i.e. not CURRENT_TIME etc.)
  96366. */
  96367. if( pDflt ){
  96368. sqlite3_value *pVal = 0;
  96369. int rc;
  96370. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  96371. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  96372. if( rc!=SQLITE_OK ){
  96373. assert( db->mallocFailed == 1 );
  96374. return;
  96375. }
  96376. if( !pVal ){
  96377. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  96378. return;
  96379. }
  96380. sqlite3ValueFree(pVal);
  96381. }
  96382. /* Modify the CREATE TABLE statement. */
  96383. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  96384. if( zCol ){
  96385. char *zEnd = &zCol[pColDef->n-1];
  96386. u32 savedDbFlags = db->mDbFlags;
  96387. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  96388. *zEnd-- = '\0';
  96389. }
  96390. db->mDbFlags |= DBFLAG_PreferBuiltin;
  96391. sqlite3NestedParse(pParse,
  96392. "UPDATE \"%w\".%s SET "
  96393. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  96394. "WHERE type = 'table' AND name = %Q",
  96395. zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
  96396. zTab
  96397. );
  96398. sqlite3DbFree(db, zCol);
  96399. db->mDbFlags = savedDbFlags;
  96400. }
  96401. /* Make sure the schema version is at least 3. But do not upgrade
  96402. ** from less than 3 to 4, as that will corrupt any preexisting DESC
  96403. ** index.
  96404. */
  96405. v = sqlite3GetVdbe(pParse);
  96406. if( v ){
  96407. r1 = sqlite3GetTempReg(pParse);
  96408. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  96409. sqlite3VdbeUsesBtree(v, iDb);
  96410. sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
  96411. sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
  96412. VdbeCoverage(v);
  96413. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
  96414. sqlite3ReleaseTempReg(pParse, r1);
  96415. }
  96416. /* Reload the table definition */
  96417. renameReloadSchema(pParse, iDb);
  96418. }
  96419. /*
  96420. ** This function is called by the parser after the table-name in
  96421. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  96422. ** pSrc is the full-name of the table being altered.
  96423. **
  96424. ** This routine makes a (partial) copy of the Table structure
  96425. ** for the table being altered and sets Parse.pNewTable to point
  96426. ** to it. Routines called by the parser as the column definition
  96427. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  96428. ** the copy. The copy of the Table structure is deleted by tokenize.c
  96429. ** after parsing is finished.
  96430. **
  96431. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  96432. ** coding the "ALTER TABLE ... ADD" statement.
  96433. */
  96434. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  96435. Table *pNew;
  96436. Table *pTab;
  96437. int iDb;
  96438. int i;
  96439. int nAlloc;
  96440. sqlite3 *db = pParse->db;
  96441. /* Look up the table being altered. */
  96442. assert( pParse->pNewTable==0 );
  96443. assert( sqlite3BtreeHoldsAllMutexes(db) );
  96444. if( db->mallocFailed ) goto exit_begin_add_column;
  96445. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  96446. if( !pTab ) goto exit_begin_add_column;
  96447. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96448. if( IsVirtual(pTab) ){
  96449. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  96450. goto exit_begin_add_column;
  96451. }
  96452. #endif
  96453. /* Make sure this is not an attempt to ALTER a view. */
  96454. if( pTab->pSelect ){
  96455. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  96456. goto exit_begin_add_column;
  96457. }
  96458. if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
  96459. goto exit_begin_add_column;
  96460. }
  96461. assert( pTab->addColOffset>0 );
  96462. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  96463. /* Put a copy of the Table struct in Parse.pNewTable for the
  96464. ** sqlite3AddColumn() function and friends to modify. But modify
  96465. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  96466. ** prefix, we insure that the name will not collide with an existing
  96467. ** table because user table are not allowed to have the "sqlite_"
  96468. ** prefix on their name.
  96469. */
  96470. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  96471. if( !pNew ) goto exit_begin_add_column;
  96472. pParse->pNewTable = pNew;
  96473. pNew->nTabRef = 1;
  96474. pNew->nCol = pTab->nCol;
  96475. assert( pNew->nCol>0 );
  96476. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  96477. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  96478. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  96479. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  96480. if( !pNew->aCol || !pNew->zName ){
  96481. assert( db->mallocFailed );
  96482. goto exit_begin_add_column;
  96483. }
  96484. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  96485. for(i=0; i<pNew->nCol; i++){
  96486. Column *pCol = &pNew->aCol[i];
  96487. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  96488. pCol->zColl = 0;
  96489. pCol->pDflt = 0;
  96490. }
  96491. pNew->pSchema = db->aDb[iDb].pSchema;
  96492. pNew->addColOffset = pTab->addColOffset;
  96493. pNew->nTabRef = 1;
  96494. exit_begin_add_column:
  96495. sqlite3SrcListDelete(db, pSrc);
  96496. return;
  96497. }
  96498. /*
  96499. ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
  96500. ** command. This function checks if the table is a view or virtual
  96501. ** table (columns of views or virtual tables may not be renamed). If so,
  96502. ** it loads an error message into pParse and returns non-zero.
  96503. **
  96504. ** Or, if pTab is not a view or virtual table, zero is returned.
  96505. */
  96506. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  96507. static int isRealTable(Parse *pParse, Table *pTab){
  96508. const char *zType = 0;
  96509. #ifndef SQLITE_OMIT_VIEW
  96510. if( pTab->pSelect ){
  96511. zType = "view";
  96512. }
  96513. #endif
  96514. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96515. if( IsVirtual(pTab) ){
  96516. zType = "virtual table";
  96517. }
  96518. #endif
  96519. if( zType ){
  96520. sqlite3ErrorMsg(
  96521. pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
  96522. );
  96523. return 1;
  96524. }
  96525. return 0;
  96526. }
  96527. #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  96528. # define isRealTable(x,y) (0)
  96529. #endif
  96530. /*
  96531. ** Handles the following parser reduction:
  96532. **
  96533. ** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
  96534. */
  96535. SQLITE_PRIVATE void sqlite3AlterRenameColumn(
  96536. Parse *pParse, /* Parsing context */
  96537. SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
  96538. Token *pOld, /* Name of column being changed */
  96539. Token *pNew /* New column name */
  96540. ){
  96541. sqlite3 *db = pParse->db; /* Database connection */
  96542. Table *pTab; /* Table being updated */
  96543. int iCol; /* Index of column being renamed */
  96544. char *zOld = 0; /* Old column name */
  96545. char *zNew = 0; /* New column name */
  96546. const char *zDb; /* Name of schema containing the table */
  96547. int iSchema; /* Index of the schema */
  96548. int bQuote; /* True to quote the new name */
  96549. /* Locate the table to be altered */
  96550. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  96551. if( !pTab ) goto exit_rename_column;
  96552. /* Cannot alter a system table */
  96553. if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
  96554. if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
  96555. /* Which schema holds the table to be altered */
  96556. iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
  96557. assert( iSchema>=0 );
  96558. zDb = db->aDb[iSchema].zDbSName;
  96559. #ifndef SQLITE_OMIT_AUTHORIZATION
  96560. /* Invoke the authorization callback. */
  96561. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  96562. goto exit_rename_column;
  96563. }
  96564. #endif
  96565. /* Make sure the old name really is a column name in the table to be
  96566. ** altered. Set iCol to be the index of the column being renamed */
  96567. zOld = sqlite3NameFromToken(db, pOld);
  96568. if( !zOld ) goto exit_rename_column;
  96569. for(iCol=0; iCol<pTab->nCol; iCol++){
  96570. if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
  96571. }
  96572. if( iCol==pTab->nCol ){
  96573. sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
  96574. goto exit_rename_column;
  96575. }
  96576. /* Do the rename operation using a recursive UPDATE statement that
  96577. ** uses the sqlite_rename_column() SQL function to compute the new
  96578. ** CREATE statement text for the sqlite_master table.
  96579. */
  96580. sqlite3MayAbort(pParse);
  96581. zNew = sqlite3NameFromToken(db, pNew);
  96582. if( !zNew ) goto exit_rename_column;
  96583. assert( pNew->n>0 );
  96584. bQuote = sqlite3Isquote(pNew->z[0]);
  96585. sqlite3NestedParse(pParse,
  96586. "UPDATE \"%w\".%s SET "
  96587. "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
  96588. "WHERE name NOT LIKE 'sqlite_%%' AND (type != 'index' OR tbl_name = %Q)"
  96589. " AND sql NOT LIKE 'create virtual%%'",
  96590. zDb, MASTER_NAME,
  96591. zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
  96592. pTab->zName
  96593. );
  96594. sqlite3NestedParse(pParse,
  96595. "UPDATE temp.%s SET "
  96596. "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
  96597. "WHERE type IN ('trigger', 'view')",
  96598. MASTER_NAME,
  96599. zDb, pTab->zName, iCol, zNew, bQuote
  96600. );
  96601. /* Drop and reload the database schema. */
  96602. renameReloadSchema(pParse, iSchema);
  96603. renameTestSchema(pParse, zDb, iSchema==1);
  96604. exit_rename_column:
  96605. sqlite3SrcListDelete(db, pSrc);
  96606. sqlite3DbFree(db, zOld);
  96607. sqlite3DbFree(db, zNew);
  96608. return;
  96609. }
  96610. /*
  96611. ** Each RenameToken object maps an element of the parse tree into
  96612. ** the token that generated that element. The parse tree element
  96613. ** might be one of:
  96614. **
  96615. ** * A pointer to an Expr that represents an ID
  96616. ** * The name of a table column in Column.zName
  96617. **
  96618. ** A list of RenameToken objects can be constructed during parsing.
  96619. ** Each new object is created by sqlite3RenameTokenMap().
  96620. ** As the parse tree is transformed, the sqlite3RenameTokenRemap()
  96621. ** routine is used to keep the mapping current.
  96622. **
  96623. ** After the parse finishes, renameTokenFind() routine can be used
  96624. ** to look up the actual token value that created some element in
  96625. ** the parse tree.
  96626. */
  96627. struct RenameToken {
  96628. void *p; /* Parse tree element created by token t */
  96629. Token t; /* The token that created parse tree element p */
  96630. RenameToken *pNext; /* Next is a list of all RenameToken objects */
  96631. };
  96632. /*
  96633. ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
  96634. ** down into the Walker.
  96635. */
  96636. typedef struct RenameCtx RenameCtx;
  96637. struct RenameCtx {
  96638. RenameToken *pList; /* List of tokens to overwrite */
  96639. int nList; /* Number of tokens in pList */
  96640. int iCol; /* Index of column being renamed */
  96641. Table *pTab; /* Table being ALTERed */
  96642. const char *zOld; /* Old column name */
  96643. };
  96644. #ifdef SQLITE_DEBUG
  96645. /*
  96646. ** This function is only for debugging. It performs two tasks:
  96647. **
  96648. ** 1. Checks that pointer pPtr does not already appear in the
  96649. ** rename-token list.
  96650. **
  96651. ** 2. Dereferences each pointer in the rename-token list.
  96652. **
  96653. ** The second is most effective when debugging under valgrind or
  96654. ** address-sanitizer or similar. If any of these pointers no longer
  96655. ** point to valid objects, an exception is raised by the memory-checking
  96656. ** tool.
  96657. **
  96658. ** The point of this is to prevent comparisons of invalid pointer values.
  96659. ** Even though this always seems to work, it is undefined according to the
  96660. ** C standard. Example of undefined comparison:
  96661. **
  96662. ** sqlite3_free(x);
  96663. ** if( x==y ) ...
  96664. **
  96665. ** Technically, as x no longer points into a valid object or to the byte
  96666. ** following a valid object, it may not be used in comparison operations.
  96667. */
  96668. static void renameTokenCheckAll(Parse *pParse, void *pPtr){
  96669. if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
  96670. RenameToken *p;
  96671. u8 i = 0;
  96672. for(p=pParse->pRename; p; p=p->pNext){
  96673. if( p->p ){
  96674. assert( p->p!=pPtr );
  96675. i += *(u8*)(p->p);
  96676. }
  96677. }
  96678. }
  96679. }
  96680. #else
  96681. # define renameTokenCheckAll(x,y)
  96682. #endif
  96683. /*
  96684. ** Remember that the parser tree element pPtr was created using
  96685. ** the token pToken.
  96686. **
  96687. ** In other words, construct a new RenameToken object and add it
  96688. ** to the list of RenameToken objects currently being built up
  96689. ** in pParse->pRename.
  96690. **
  96691. ** The pPtr argument is returned so that this routine can be used
  96692. ** with tail recursion in tokenExpr() routine, for a small performance
  96693. ** improvement.
  96694. */
  96695. SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
  96696. RenameToken *pNew;
  96697. assert( pPtr || pParse->db->mallocFailed );
  96698. renameTokenCheckAll(pParse, pPtr);
  96699. pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
  96700. if( pNew ){
  96701. pNew->p = pPtr;
  96702. pNew->t = *pToken;
  96703. pNew->pNext = pParse->pRename;
  96704. pParse->pRename = pNew;
  96705. }
  96706. return pPtr;
  96707. }
  96708. /*
  96709. ** It is assumed that there is already a RenameToken object associated
  96710. ** with parse tree element pFrom. This function remaps the associated token
  96711. ** to parse tree element pTo.
  96712. */
  96713. SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
  96714. RenameToken *p;
  96715. renameTokenCheckAll(pParse, pTo);
  96716. for(p=pParse->pRename; p; p=p->pNext){
  96717. if( p->p==pFrom ){
  96718. p->p = pTo;
  96719. break;
  96720. }
  96721. }
  96722. }
  96723. /*
  96724. ** Walker callback used by sqlite3RenameExprUnmap().
  96725. */
  96726. static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
  96727. Parse *pParse = pWalker->pParse;
  96728. sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
  96729. return WRC_Continue;
  96730. }
  96731. /*
  96732. ** Remove all nodes that are part of expression pExpr from the rename list.
  96733. */
  96734. SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
  96735. Walker sWalker;
  96736. memset(&sWalker, 0, sizeof(Walker));
  96737. sWalker.pParse = pParse;
  96738. sWalker.xExprCallback = renameUnmapExprCb;
  96739. sqlite3WalkExpr(&sWalker, pExpr);
  96740. }
  96741. /*
  96742. ** Remove all nodes that are part of expression-list pEList from the
  96743. ** rename list.
  96744. */
  96745. SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
  96746. if( pEList ){
  96747. int i;
  96748. Walker sWalker;
  96749. memset(&sWalker, 0, sizeof(Walker));
  96750. sWalker.pParse = pParse;
  96751. sWalker.xExprCallback = renameUnmapExprCb;
  96752. sqlite3WalkExprList(&sWalker, pEList);
  96753. for(i=0; i<pEList->nExpr; i++){
  96754. sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
  96755. }
  96756. }
  96757. }
  96758. /*
  96759. ** Free the list of RenameToken objects given in the second argument
  96760. */
  96761. static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
  96762. RenameToken *pNext;
  96763. RenameToken *p;
  96764. for(p=pToken; p; p=pNext){
  96765. pNext = p->pNext;
  96766. sqlite3DbFree(db, p);
  96767. }
  96768. }
  96769. /*
  96770. ** Search the Parse object passed as the first argument for a RenameToken
  96771. ** object associated with parse tree element pPtr. If found, remove it
  96772. ** from the Parse object and add it to the list maintained by the
  96773. ** RenameCtx object passed as the second argument.
  96774. */
  96775. static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
  96776. RenameToken **pp;
  96777. assert( pPtr!=0 );
  96778. for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
  96779. if( (*pp)->p==pPtr ){
  96780. RenameToken *pToken = *pp;
  96781. *pp = pToken->pNext;
  96782. pToken->pNext = pCtx->pList;
  96783. pCtx->pList = pToken;
  96784. pCtx->nList++;
  96785. break;
  96786. }
  96787. }
  96788. }
  96789. /*
  96790. ** Iterate through the Select objects that are part of WITH clauses attached
  96791. ** to select statement pSelect.
  96792. */
  96793. static void renameWalkWith(Walker *pWalker, Select *pSelect){
  96794. if( pSelect->pWith ){
  96795. int i;
  96796. for(i=0; i<pSelect->pWith->nCte; i++){
  96797. Select *p = pSelect->pWith->a[i].pSelect;
  96798. NameContext sNC;
  96799. memset(&sNC, 0, sizeof(sNC));
  96800. sNC.pParse = pWalker->pParse;
  96801. sqlite3SelectPrep(sNC.pParse, p, &sNC);
  96802. sqlite3WalkSelect(pWalker, p);
  96803. }
  96804. }
  96805. }
  96806. /*
  96807. ** This is a Walker select callback. It does nothing. It is only required
  96808. ** because without a dummy callback, sqlite3WalkExpr() and similar do not
  96809. ** descend into sub-select statements.
  96810. */
  96811. static int renameColumnSelectCb(Walker *pWalker, Select *p){
  96812. renameWalkWith(pWalker, p);
  96813. return WRC_Continue;
  96814. }
  96815. /*
  96816. ** This is a Walker expression callback.
  96817. **
  96818. ** For every TK_COLUMN node in the expression tree, search to see
  96819. ** if the column being references is the column being renamed by an
  96820. ** ALTER TABLE statement. If it is, then attach its associated
  96821. ** RenameToken object to the list of RenameToken objects being
  96822. ** constructed in RenameCtx object at pWalker->u.pRename.
  96823. */
  96824. static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
  96825. RenameCtx *p = pWalker->u.pRename;
  96826. if( pExpr->op==TK_TRIGGER
  96827. && pExpr->iColumn==p->iCol
  96828. && pWalker->pParse->pTriggerTab==p->pTab
  96829. ){
  96830. renameTokenFind(pWalker->pParse, p, (void*)pExpr);
  96831. }else if( pExpr->op==TK_COLUMN
  96832. && pExpr->iColumn==p->iCol
  96833. && p->pTab==pExpr->y.pTab
  96834. ){
  96835. renameTokenFind(pWalker->pParse, p, (void*)pExpr);
  96836. }
  96837. return WRC_Continue;
  96838. }
  96839. /*
  96840. ** The RenameCtx contains a list of tokens that reference a column that
  96841. ** is being renamed by an ALTER TABLE statement. Return the "last"
  96842. ** RenameToken in the RenameCtx and remove that RenameToken from the
  96843. ** RenameContext. "Last" means the last RenameToken encountered when
  96844. ** the input SQL is parsed from left to right. Repeated calls to this routine
  96845. ** return all column name tokens in the order that they are encountered
  96846. ** in the SQL statement.
  96847. */
  96848. static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
  96849. RenameToken *pBest = pCtx->pList;
  96850. RenameToken *pToken;
  96851. RenameToken **pp;
  96852. for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
  96853. if( pToken->t.z>pBest->t.z ) pBest = pToken;
  96854. }
  96855. for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
  96856. *pp = pBest->pNext;
  96857. return pBest;
  96858. }
  96859. /*
  96860. ** An error occured while parsing or otherwise processing a database
  96861. ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
  96862. ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
  96863. ** sub-routine is currently stored in pParse->zErrMsg. This function
  96864. ** adds context to the error message and then stores it in pCtx.
  96865. */
  96866. static void renameColumnParseError(
  96867. sqlite3_context *pCtx,
  96868. int bPost,
  96869. sqlite3_value *pType,
  96870. sqlite3_value *pObject,
  96871. Parse *pParse
  96872. ){
  96873. const char *zT = (const char*)sqlite3_value_text(pType);
  96874. const char *zN = (const char*)sqlite3_value_text(pObject);
  96875. char *zErr;
  96876. zErr = sqlite3_mprintf("error in %s %s%s: %s",
  96877. zT, zN, (bPost ? " after rename" : ""),
  96878. pParse->zErrMsg
  96879. );
  96880. sqlite3_result_error(pCtx, zErr, -1);
  96881. sqlite3_free(zErr);
  96882. }
  96883. /*
  96884. ** For each name in the the expression-list pEList (i.e. each
  96885. ** pEList->a[i].zName) that matches the string in zOld, extract the
  96886. ** corresponding rename-token from Parse object pParse and add it
  96887. ** to the RenameCtx pCtx.
  96888. */
  96889. static void renameColumnElistNames(
  96890. Parse *pParse,
  96891. RenameCtx *pCtx,
  96892. ExprList *pEList,
  96893. const char *zOld
  96894. ){
  96895. if( pEList ){
  96896. int i;
  96897. for(i=0; i<pEList->nExpr; i++){
  96898. char *zName = pEList->a[i].zName;
  96899. if( 0==sqlite3_stricmp(zName, zOld) ){
  96900. renameTokenFind(pParse, pCtx, (void*)zName);
  96901. }
  96902. }
  96903. }
  96904. }
  96905. /*
  96906. ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
  96907. ** that matches the string in zOld, extract the corresponding rename-token
  96908. ** from Parse object pParse and add it to the RenameCtx pCtx.
  96909. */
  96910. static void renameColumnIdlistNames(
  96911. Parse *pParse,
  96912. RenameCtx *pCtx,
  96913. IdList *pIdList,
  96914. const char *zOld
  96915. ){
  96916. if( pIdList ){
  96917. int i;
  96918. for(i=0; i<pIdList->nId; i++){
  96919. char *zName = pIdList->a[i].zName;
  96920. if( 0==sqlite3_stricmp(zName, zOld) ){
  96921. renameTokenFind(pParse, pCtx, (void*)zName);
  96922. }
  96923. }
  96924. }
  96925. }
  96926. /*
  96927. ** Parse the SQL statement zSql using Parse object (*p). The Parse object
  96928. ** is initialized by this function before it is used.
  96929. */
  96930. static int renameParseSql(
  96931. Parse *p, /* Memory to use for Parse object */
  96932. const char *zDb, /* Name of schema SQL belongs to */
  96933. int bTable, /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
  96934. sqlite3 *db, /* Database handle */
  96935. const char *zSql, /* SQL to parse */
  96936. int bTemp /* True if SQL is from temp schema */
  96937. ){
  96938. int rc;
  96939. char *zErr = 0;
  96940. db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
  96941. /* Parse the SQL statement passed as the first argument. If no error
  96942. ** occurs and the parse does not result in a new table, index or
  96943. ** trigger object, the database must be corrupt. */
  96944. memset(p, 0, sizeof(Parse));
  96945. p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
  96946. p->db = db;
  96947. p->nQueryLoop = 1;
  96948. rc = sqlite3RunParser(p, zSql, &zErr);
  96949. assert( p->zErrMsg==0 );
  96950. assert( rc!=SQLITE_OK || zErr==0 );
  96951. p->zErrMsg = zErr;
  96952. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  96953. if( rc==SQLITE_OK
  96954. && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
  96955. ){
  96956. rc = SQLITE_CORRUPT_BKPT;
  96957. }
  96958. #ifdef SQLITE_DEBUG
  96959. /* Ensure that all mappings in the Parse.pRename list really do map to
  96960. ** a part of the input string. */
  96961. if( rc==SQLITE_OK ){
  96962. int nSql = sqlite3Strlen30(zSql);
  96963. RenameToken *pToken;
  96964. for(pToken=p->pRename; pToken; pToken=pToken->pNext){
  96965. assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
  96966. }
  96967. }
  96968. #endif
  96969. db->init.iDb = 0;
  96970. return rc;
  96971. }
  96972. /*
  96973. ** This function edits SQL statement zSql, replacing each token identified
  96974. ** by the linked list pRename with the text of zNew. If argument bQuote is
  96975. ** true, then zNew is always quoted first. If no error occurs, the result
  96976. ** is loaded into context object pCtx as the result.
  96977. **
  96978. ** Or, if an error occurs (i.e. an OOM condition), an error is left in
  96979. ** pCtx and an SQLite error code returned.
  96980. */
  96981. static int renameEditSql(
  96982. sqlite3_context *pCtx, /* Return result here */
  96983. RenameCtx *pRename, /* Rename context */
  96984. const char *zSql, /* SQL statement to edit */
  96985. const char *zNew, /* New token text */
  96986. int bQuote /* True to always quote token */
  96987. ){
  96988. int nNew = sqlite3Strlen30(zNew);
  96989. int nSql = sqlite3Strlen30(zSql);
  96990. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  96991. int rc = SQLITE_OK;
  96992. char *zQuot;
  96993. char *zOut;
  96994. int nQuot;
  96995. /* Set zQuot to point to a buffer containing a quoted copy of the
  96996. ** identifier zNew. If the corresponding identifier in the original
  96997. ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
  96998. ** point to zQuot so that all substitutions are made using the
  96999. ** quoted version of the new column name. */
  97000. zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
  97001. if( zQuot==0 ){
  97002. return SQLITE_NOMEM;
  97003. }else{
  97004. nQuot = sqlite3Strlen30(zQuot);
  97005. }
  97006. if( bQuote ){
  97007. zNew = zQuot;
  97008. nNew = nQuot;
  97009. }
  97010. /* At this point pRename->pList contains a list of RenameToken objects
  97011. ** corresponding to all tokens in the input SQL that must be replaced
  97012. ** with the new column name. All that remains is to construct and
  97013. ** return the edited SQL string. */
  97014. assert( nQuot>=nNew );
  97015. zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
  97016. if( zOut ){
  97017. int nOut = nSql;
  97018. memcpy(zOut, zSql, nSql);
  97019. while( pRename->pList ){
  97020. int iOff; /* Offset of token to replace in zOut */
  97021. RenameToken *pBest = renameColumnTokenNext(pRename);
  97022. u32 nReplace;
  97023. const char *zReplace;
  97024. if( sqlite3IsIdChar(*pBest->t.z) ){
  97025. nReplace = nNew;
  97026. zReplace = zNew;
  97027. }else{
  97028. nReplace = nQuot;
  97029. zReplace = zQuot;
  97030. }
  97031. iOff = pBest->t.z - zSql;
  97032. if( pBest->t.n!=nReplace ){
  97033. memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
  97034. nOut - (iOff + pBest->t.n)
  97035. );
  97036. nOut += nReplace - pBest->t.n;
  97037. zOut[nOut] = '\0';
  97038. }
  97039. memcpy(&zOut[iOff], zReplace, nReplace);
  97040. sqlite3DbFree(db, pBest);
  97041. }
  97042. sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
  97043. sqlite3DbFree(db, zOut);
  97044. }else{
  97045. rc = SQLITE_NOMEM;
  97046. }
  97047. sqlite3_free(zQuot);
  97048. return rc;
  97049. }
  97050. /*
  97051. ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
  97052. ** it was read from the schema of database zDb. Return SQLITE_OK if
  97053. ** successful. Otherwise, return an SQLite error code and leave an error
  97054. ** message in the Parse object.
  97055. */
  97056. static int renameResolveTrigger(Parse *pParse, const char *zDb){
  97057. sqlite3 *db = pParse->db;
  97058. Trigger *pNew = pParse->pNewTrigger;
  97059. TriggerStep *pStep;
  97060. NameContext sNC;
  97061. int rc = SQLITE_OK;
  97062. memset(&sNC, 0, sizeof(sNC));
  97063. sNC.pParse = pParse;
  97064. assert( pNew->pTabSchema );
  97065. pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
  97066. db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
  97067. );
  97068. pParse->eTriggerOp = pNew->op;
  97069. /* ALWAYS() because if the table of the trigger does not exist, the
  97070. ** error would have been hit before this point */
  97071. if( ALWAYS(pParse->pTriggerTab) ){
  97072. rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
  97073. }
  97074. /* Resolve symbols in WHEN clause */
  97075. if( rc==SQLITE_OK && pNew->pWhen ){
  97076. rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
  97077. }
  97078. for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
  97079. if( pStep->pSelect ){
  97080. sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
  97081. if( pParse->nErr ) rc = pParse->rc;
  97082. }
  97083. if( rc==SQLITE_OK && pStep->zTarget ){
  97084. Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
  97085. if( pTarget==0 ){
  97086. rc = SQLITE_ERROR;
  97087. }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
  97088. SrcList sSrc;
  97089. memset(&sSrc, 0, sizeof(sSrc));
  97090. sSrc.nSrc = 1;
  97091. sSrc.a[0].zName = pStep->zTarget;
  97092. sSrc.a[0].pTab = pTarget;
  97093. sNC.pSrcList = &sSrc;
  97094. if( pStep->pWhere ){
  97095. rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
  97096. }
  97097. if( rc==SQLITE_OK ){
  97098. rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
  97099. }
  97100. assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
  97101. if( pStep->pUpsert ){
  97102. Upsert *pUpsert = pStep->pUpsert;
  97103. assert( rc==SQLITE_OK );
  97104. pUpsert->pUpsertSrc = &sSrc;
  97105. sNC.uNC.pUpsert = pUpsert;
  97106. sNC.ncFlags = NC_UUpsert;
  97107. rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
  97108. if( rc==SQLITE_OK ){
  97109. ExprList *pUpsertSet = pUpsert->pUpsertSet;
  97110. rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
  97111. }
  97112. if( rc==SQLITE_OK ){
  97113. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
  97114. }
  97115. if( rc==SQLITE_OK ){
  97116. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
  97117. }
  97118. sNC.ncFlags = 0;
  97119. }
  97120. sNC.pSrcList = 0;
  97121. }
  97122. }
  97123. }
  97124. return rc;
  97125. }
  97126. /*
  97127. ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
  97128. ** objects that are part of the trigger passed as the second argument.
  97129. */
  97130. static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
  97131. TriggerStep *pStep;
  97132. /* Find tokens to edit in WHEN clause */
  97133. sqlite3WalkExpr(pWalker, pTrigger->pWhen);
  97134. /* Find tokens to edit in trigger steps */
  97135. for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
  97136. sqlite3WalkSelect(pWalker, pStep->pSelect);
  97137. sqlite3WalkExpr(pWalker, pStep->pWhere);
  97138. sqlite3WalkExprList(pWalker, pStep->pExprList);
  97139. if( pStep->pUpsert ){
  97140. Upsert *pUpsert = pStep->pUpsert;
  97141. sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
  97142. sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
  97143. sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
  97144. sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
  97145. }
  97146. }
  97147. }
  97148. /*
  97149. ** Free the contents of Parse object (*pParse). Do not free the memory
  97150. ** occupied by the Parse object itself.
  97151. */
  97152. static void renameParseCleanup(Parse *pParse){
  97153. sqlite3 *db = pParse->db;
  97154. Index *pIdx;
  97155. if( pParse->pVdbe ){
  97156. sqlite3VdbeFinalize(pParse->pVdbe);
  97157. }
  97158. sqlite3DeleteTable(db, pParse->pNewTable);
  97159. while( (pIdx = pParse->pNewIndex)!=0 ){
  97160. pParse->pNewIndex = pIdx->pNext;
  97161. sqlite3FreeIndex(db, pIdx);
  97162. }
  97163. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  97164. sqlite3DbFree(db, pParse->zErrMsg);
  97165. renameTokenFree(db, pParse->pRename);
  97166. sqlite3ParserReset(pParse);
  97167. }
  97168. /*
  97169. ** SQL function:
  97170. **
  97171. ** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
  97172. **
  97173. ** 0. zSql: SQL statement to rewrite
  97174. ** 1. type: Type of object ("table", "view" etc.)
  97175. ** 2. object: Name of object
  97176. ** 3. Database: Database name (e.g. "main")
  97177. ** 4. Table: Table name
  97178. ** 5. iCol: Index of column to rename
  97179. ** 6. zNew: New column name
  97180. ** 7. bQuote: Non-zero if the new column name should be quoted.
  97181. ** 8. bTemp: True if zSql comes from temp schema
  97182. **
  97183. ** Do a column rename operation on the CREATE statement given in zSql.
  97184. ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
  97185. ** into zNew. The name should be quoted if bQuote is true.
  97186. **
  97187. ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
  97188. ** It is only accessible to SQL created using sqlite3NestedParse(). It is
  97189. ** not reachable from ordinary SQL passed into sqlite3_prepare().
  97190. */
  97191. static void renameColumnFunc(
  97192. sqlite3_context *context,
  97193. int NotUsed,
  97194. sqlite3_value **argv
  97195. ){
  97196. sqlite3 *db = sqlite3_context_db_handle(context);
  97197. RenameCtx sCtx;
  97198. const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  97199. const char *zDb = (const char*)sqlite3_value_text(argv[3]);
  97200. const char *zTable = (const char*)sqlite3_value_text(argv[4]);
  97201. int iCol = sqlite3_value_int(argv[5]);
  97202. const char *zNew = (const char*)sqlite3_value_text(argv[6]);
  97203. int bQuote = sqlite3_value_int(argv[7]);
  97204. int bTemp = sqlite3_value_int(argv[8]);
  97205. const char *zOld;
  97206. int rc;
  97207. Parse sParse;
  97208. Walker sWalker;
  97209. Index *pIdx;
  97210. int i;
  97211. Table *pTab;
  97212. #ifndef SQLITE_OMIT_AUTHORIZATION
  97213. sqlite3_xauth xAuth = db->xAuth;
  97214. #endif
  97215. UNUSED_PARAMETER(NotUsed);
  97216. if( zSql==0 ) return;
  97217. if( zTable==0 ) return;
  97218. if( zNew==0 ) return;
  97219. if( iCol<0 ) return;
  97220. sqlite3BtreeEnterAll(db);
  97221. pTab = sqlite3FindTable(db, zTable, zDb);
  97222. if( pTab==0 || iCol>=pTab->nCol ){
  97223. sqlite3BtreeLeaveAll(db);
  97224. return;
  97225. }
  97226. zOld = pTab->aCol[iCol].zName;
  97227. memset(&sCtx, 0, sizeof(sCtx));
  97228. sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
  97229. #ifndef SQLITE_OMIT_AUTHORIZATION
  97230. db->xAuth = 0;
  97231. #endif
  97232. rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
  97233. /* Find tokens that need to be replaced. */
  97234. memset(&sWalker, 0, sizeof(Walker));
  97235. sWalker.pParse = &sParse;
  97236. sWalker.xExprCallback = renameColumnExprCb;
  97237. sWalker.xSelectCallback = renameColumnSelectCb;
  97238. sWalker.u.pRename = &sCtx;
  97239. sCtx.pTab = pTab;
  97240. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  97241. if( sParse.pNewTable ){
  97242. Select *pSelect = sParse.pNewTable->pSelect;
  97243. if( pSelect ){
  97244. sParse.rc = SQLITE_OK;
  97245. sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
  97246. rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
  97247. if( rc==SQLITE_OK ){
  97248. sqlite3WalkSelect(&sWalker, pSelect);
  97249. }
  97250. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  97251. }else{
  97252. /* A regular table */
  97253. int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
  97254. FKey *pFKey;
  97255. assert( sParse.pNewTable->pSelect==0 );
  97256. sCtx.pTab = sParse.pNewTable;
  97257. if( bFKOnly==0 ){
  97258. renameTokenFind(
  97259. &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
  97260. );
  97261. if( sCtx.iCol<0 ){
  97262. renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
  97263. }
  97264. sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
  97265. for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
  97266. sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
  97267. }
  97268. for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
  97269. sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
  97270. }
  97271. }
  97272. for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  97273. for(i=0; i<pFKey->nCol; i++){
  97274. if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
  97275. renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
  97276. }
  97277. if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
  97278. && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
  97279. ){
  97280. renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
  97281. }
  97282. }
  97283. }
  97284. }
  97285. }else if( sParse.pNewIndex ){
  97286. sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
  97287. sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
  97288. }else{
  97289. /* A trigger */
  97290. TriggerStep *pStep;
  97291. rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
  97292. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  97293. for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
  97294. if( pStep->zTarget ){
  97295. Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
  97296. if( pTarget==pTab ){
  97297. if( pStep->pUpsert ){
  97298. ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
  97299. renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
  97300. }
  97301. renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
  97302. renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
  97303. }
  97304. }
  97305. }
  97306. /* Find tokens to edit in UPDATE OF clause */
  97307. if( sParse.pTriggerTab==pTab ){
  97308. renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
  97309. }
  97310. /* Find tokens to edit in various expressions and selects */
  97311. renameWalkTrigger(&sWalker, sParse.pNewTrigger);
  97312. }
  97313. assert( rc==SQLITE_OK );
  97314. rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
  97315. renameColumnFunc_done:
  97316. if( rc!=SQLITE_OK ){
  97317. if( sParse.zErrMsg ){
  97318. renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
  97319. }else{
  97320. sqlite3_result_error_code(context, rc);
  97321. }
  97322. }
  97323. renameParseCleanup(&sParse);
  97324. renameTokenFree(db, sCtx.pList);
  97325. #ifndef SQLITE_OMIT_AUTHORIZATION
  97326. db->xAuth = xAuth;
  97327. #endif
  97328. sqlite3BtreeLeaveAll(db);
  97329. }
  97330. /*
  97331. ** Walker expression callback used by "RENAME TABLE".
  97332. */
  97333. static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
  97334. RenameCtx *p = pWalker->u.pRename;
  97335. if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
  97336. renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
  97337. }
  97338. return WRC_Continue;
  97339. }
  97340. /*
  97341. ** Walker select callback used by "RENAME TABLE".
  97342. */
  97343. static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
  97344. int i;
  97345. RenameCtx *p = pWalker->u.pRename;
  97346. SrcList *pSrc = pSelect->pSrc;
  97347. if( pSrc==0 ){
  97348. assert( pWalker->pParse->db->mallocFailed );
  97349. return WRC_Abort;
  97350. }
  97351. for(i=0; i<pSrc->nSrc; i++){
  97352. struct SrcList_item *pItem = &pSrc->a[i];
  97353. if( pItem->pTab==p->pTab ){
  97354. renameTokenFind(pWalker->pParse, p, pItem->zName);
  97355. }
  97356. }
  97357. renameWalkWith(pWalker, pSelect);
  97358. return WRC_Continue;
  97359. }
  97360. /*
  97361. ** This C function implements an SQL user function that is used by SQL code
  97362. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  97363. ** of any foreign key constraints that use the table being renamed as the
  97364. ** parent table. It is passed three arguments:
  97365. **
  97366. ** 0: The database containing the table being renamed.
  97367. ** 1. type: Type of object ("table", "view" etc.)
  97368. ** 2. object: Name of object
  97369. ** 3: The complete text of the schema statement being modified,
  97370. ** 4: The old name of the table being renamed, and
  97371. ** 5: The new name of the table being renamed.
  97372. ** 6: True if the schema statement comes from the temp db.
  97373. **
  97374. ** It returns the new schema statement. For example:
  97375. **
  97376. ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
  97377. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  97378. */
  97379. static void renameTableFunc(
  97380. sqlite3_context *context,
  97381. int NotUsed,
  97382. sqlite3_value **argv
  97383. ){
  97384. sqlite3 *db = sqlite3_context_db_handle(context);
  97385. const char *zDb = (const char*)sqlite3_value_text(argv[0]);
  97386. const char *zInput = (const char*)sqlite3_value_text(argv[3]);
  97387. const char *zOld = (const char*)sqlite3_value_text(argv[4]);
  97388. const char *zNew = (const char*)sqlite3_value_text(argv[5]);
  97389. int bTemp = sqlite3_value_int(argv[6]);
  97390. UNUSED_PARAMETER(NotUsed);
  97391. if( zInput && zOld && zNew ){
  97392. Parse sParse;
  97393. int rc;
  97394. int bQuote = 1;
  97395. RenameCtx sCtx;
  97396. Walker sWalker;
  97397. #ifndef SQLITE_OMIT_AUTHORIZATION
  97398. sqlite3_xauth xAuth = db->xAuth;
  97399. db->xAuth = 0;
  97400. #endif
  97401. sqlite3BtreeEnterAll(db);
  97402. memset(&sCtx, 0, sizeof(RenameCtx));
  97403. sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
  97404. memset(&sWalker, 0, sizeof(Walker));
  97405. sWalker.pParse = &sParse;
  97406. sWalker.xExprCallback = renameTableExprCb;
  97407. sWalker.xSelectCallback = renameTableSelectCb;
  97408. sWalker.u.pRename = &sCtx;
  97409. rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
  97410. if( rc==SQLITE_OK ){
  97411. int isLegacy = (db->flags & SQLITE_LegacyAlter);
  97412. if( sParse.pNewTable ){
  97413. Table *pTab = sParse.pNewTable;
  97414. if( pTab->pSelect ){
  97415. if( isLegacy==0 ){
  97416. NameContext sNC;
  97417. memset(&sNC, 0, sizeof(sNC));
  97418. sNC.pParse = &sParse;
  97419. sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
  97420. if( sParse.nErr ) rc = sParse.rc;
  97421. sqlite3WalkSelect(&sWalker, pTab->pSelect);
  97422. }
  97423. }else{
  97424. /* Modify any FK definitions to point to the new table. */
  97425. #ifndef SQLITE_OMIT_FOREIGN_KEY
  97426. if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
  97427. FKey *pFKey;
  97428. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  97429. if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
  97430. renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
  97431. }
  97432. }
  97433. }
  97434. #endif
  97435. /* If this is the table being altered, fix any table refs in CHECK
  97436. ** expressions. Also update the name that appears right after the
  97437. ** "CREATE [VIRTUAL] TABLE" bit. */
  97438. if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
  97439. sCtx.pTab = pTab;
  97440. if( isLegacy==0 ){
  97441. sqlite3WalkExprList(&sWalker, pTab->pCheck);
  97442. }
  97443. renameTokenFind(&sParse, &sCtx, pTab->zName);
  97444. }
  97445. }
  97446. }
  97447. else if( sParse.pNewIndex ){
  97448. renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
  97449. if( isLegacy==0 ){
  97450. sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
  97451. }
  97452. }
  97453. #ifndef SQLITE_OMIT_TRIGGER
  97454. else{
  97455. Trigger *pTrigger = sParse.pNewTrigger;
  97456. TriggerStep *pStep;
  97457. if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
  97458. && sCtx.pTab->pSchema==pTrigger->pTabSchema
  97459. ){
  97460. renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
  97461. }
  97462. if( isLegacy==0 ){
  97463. rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
  97464. if( rc==SQLITE_OK ){
  97465. renameWalkTrigger(&sWalker, pTrigger);
  97466. for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
  97467. if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
  97468. renameTokenFind(&sParse, &sCtx, pStep->zTarget);
  97469. }
  97470. }
  97471. }
  97472. }
  97473. }
  97474. #endif
  97475. }
  97476. if( rc==SQLITE_OK ){
  97477. rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
  97478. }
  97479. if( rc!=SQLITE_OK ){
  97480. if( sParse.zErrMsg ){
  97481. renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
  97482. }else{
  97483. sqlite3_result_error_code(context, rc);
  97484. }
  97485. }
  97486. renameParseCleanup(&sParse);
  97487. renameTokenFree(db, sCtx.pList);
  97488. sqlite3BtreeLeaveAll(db);
  97489. #ifndef SQLITE_OMIT_AUTHORIZATION
  97490. db->xAuth = xAuth;
  97491. #endif
  97492. }
  97493. return;
  97494. }
  97495. /*
  97496. ** An SQL user function that checks that there are no parse or symbol
  97497. ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
  97498. ** After an ALTER TABLE .. RENAME operation is performed and the schema
  97499. ** reloaded, this function is called on each SQL statement in the schema
  97500. ** to ensure that it is still usable.
  97501. **
  97502. ** 0: Database name ("main", "temp" etc.).
  97503. ** 1: SQL statement.
  97504. ** 2: Object type ("view", "table", "trigger" or "index").
  97505. ** 3: Object name.
  97506. ** 4: True if object is from temp schema.
  97507. **
  97508. ** Unless it finds an error, this function normally returns NULL. However, it
  97509. ** returns integer value 1 if:
  97510. **
  97511. ** * the SQL argument creates a trigger, and
  97512. ** * the table that the trigger is attached to is in database zDb.
  97513. */
  97514. static void renameTableTest(
  97515. sqlite3_context *context,
  97516. int NotUsed,
  97517. sqlite3_value **argv
  97518. ){
  97519. sqlite3 *db = sqlite3_context_db_handle(context);
  97520. char const *zDb = (const char*)sqlite3_value_text(argv[0]);
  97521. char const *zInput = (const char*)sqlite3_value_text(argv[1]);
  97522. int bTemp = sqlite3_value_int(argv[4]);
  97523. int isLegacy = (db->flags & SQLITE_LegacyAlter);
  97524. #ifndef SQLITE_OMIT_AUTHORIZATION
  97525. sqlite3_xauth xAuth = db->xAuth;
  97526. db->xAuth = 0;
  97527. #endif
  97528. UNUSED_PARAMETER(NotUsed);
  97529. if( zDb && zInput ){
  97530. int rc;
  97531. Parse sParse;
  97532. rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
  97533. if( rc==SQLITE_OK ){
  97534. if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
  97535. NameContext sNC;
  97536. memset(&sNC, 0, sizeof(sNC));
  97537. sNC.pParse = &sParse;
  97538. sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
  97539. if( sParse.nErr ) rc = sParse.rc;
  97540. }
  97541. else if( sParse.pNewTrigger ){
  97542. if( isLegacy==0 ){
  97543. rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
  97544. }
  97545. if( rc==SQLITE_OK ){
  97546. int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
  97547. int i2 = sqlite3FindDbName(db, zDb);
  97548. if( i1==i2 ) sqlite3_result_int(context, 1);
  97549. }
  97550. }
  97551. }
  97552. if( rc!=SQLITE_OK ){
  97553. renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
  97554. }
  97555. renameParseCleanup(&sParse);
  97556. }
  97557. #ifndef SQLITE_OMIT_AUTHORIZATION
  97558. db->xAuth = xAuth;
  97559. #endif
  97560. }
  97561. /*
  97562. ** Register built-in functions used to help implement ALTER TABLE
  97563. */
  97564. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  97565. static FuncDef aAlterTableFuncs[] = {
  97566. INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
  97567. INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
  97568. INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
  97569. };
  97570. sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
  97571. }
  97572. #endif /* SQLITE_ALTER_TABLE */
  97573. /************** End of alter.c ***********************************************/
  97574. /************** Begin file analyze.c *****************************************/
  97575. /*
  97576. ** 2005-07-08
  97577. **
  97578. ** The author disclaims copyright to this source code. In place of
  97579. ** a legal notice, here is a blessing:
  97580. **
  97581. ** May you do good and not evil.
  97582. ** May you find forgiveness for yourself and forgive others.
  97583. ** May you share freely, never taking more than you give.
  97584. **
  97585. *************************************************************************
  97586. ** This file contains code associated with the ANALYZE command.
  97587. **
  97588. ** The ANALYZE command gather statistics about the content of tables
  97589. ** and indices. These statistics are made available to the query planner
  97590. ** to help it make better decisions about how to perform queries.
  97591. **
  97592. ** The following system tables are or have been supported:
  97593. **
  97594. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  97595. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  97596. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  97597. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  97598. **
  97599. ** Additional tables might be added in future releases of SQLite.
  97600. ** The sqlite_stat2 table is not created or used unless the SQLite version
  97601. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  97602. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  97603. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  97604. ** created and used by SQLite versions 3.7.9 and later and with
  97605. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  97606. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  97607. ** version of sqlite_stat3 and is only available when compiled with
  97608. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  97609. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  97610. ** are both enabled, then STAT4 takes precedence.
  97611. **
  97612. ** For most applications, sqlite_stat1 provides all the statistics required
  97613. ** for the query planner to make good choices.
  97614. **
  97615. ** Format of sqlite_stat1:
  97616. **
  97617. ** There is normally one row per index, with the index identified by the
  97618. ** name in the idx column. The tbl column is the name of the table to
  97619. ** which the index belongs. In each such row, the stat column will be
  97620. ** a string consisting of a list of integers. The first integer in this
  97621. ** list is the number of rows in the index. (This is the same as the
  97622. ** number of rows in the table, except for partial indices.) The second
  97623. ** integer is the average number of rows in the index that have the same
  97624. ** value in the first column of the index. The third integer is the average
  97625. ** number of rows in the index that have the same value for the first two
  97626. ** columns. The N-th integer (for N>1) is the average number of rows in
  97627. ** the index which have the same value for the first N-1 columns. For
  97628. ** a K-column index, there will be K+1 integers in the stat column. If
  97629. ** the index is unique, then the last integer will be 1.
  97630. **
  97631. ** The list of integers in the stat column can optionally be followed
  97632. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  97633. ** must be separated from the last integer by a single space. If the
  97634. ** "unordered" keyword is present, then the query planner assumes that
  97635. ** the index is unordered and will not use the index for a range query.
  97636. **
  97637. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  97638. ** column contains a single integer which is the (estimated) number of
  97639. ** rows in the table identified by sqlite_stat1.tbl.
  97640. **
  97641. ** Format of sqlite_stat2:
  97642. **
  97643. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  97644. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  97645. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  97646. ** about the distribution of keys within an index. The index is identified by
  97647. ** the "idx" column and the "tbl" column is the name of the table to which
  97648. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  97649. ** table for each index.
  97650. **
  97651. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  97652. ** inclusive are samples of the left-most key value in the index taken at
  97653. ** evenly spaced points along the index. Let the number of samples be S
  97654. ** (10 in the standard build) and let C be the number of rows in the index.
  97655. ** Then the sampled rows are given by:
  97656. **
  97657. ** rownumber = (i*C*2 + C)/(S*2)
  97658. **
  97659. ** For i between 0 and S-1. Conceptually, the index space is divided into
  97660. ** S uniform buckets and the samples are the middle row from each bucket.
  97661. **
  97662. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  97663. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  97664. ** writes the sqlite_stat2 table. This version of SQLite only supports
  97665. ** sqlite_stat3.
  97666. **
  97667. ** Format for sqlite_stat3:
  97668. **
  97669. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  97670. ** sqlite_stat4 format will be described first. Further information
  97671. ** about sqlite_stat3 follows the sqlite_stat4 description.
  97672. **
  97673. ** Format for sqlite_stat4:
  97674. **
  97675. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  97676. ** to aid the query planner in choosing good indices based on the values
  97677. ** that indexed columns are compared against in the WHERE clauses of
  97678. ** queries.
  97679. **
  97680. ** The sqlite_stat4 table contains multiple entries for each index.
  97681. ** The idx column names the index and the tbl column is the table of the
  97682. ** index. If the idx and tbl columns are the same, then the sample is
  97683. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  97684. ** binary encoding of a key from the index. The nEq column is a
  97685. ** list of integers. The first integer is the approximate number
  97686. ** of entries in the index whose left-most column exactly matches
  97687. ** the left-most column of the sample. The second integer in nEq
  97688. ** is the approximate number of entries in the index where the
  97689. ** first two columns match the first two columns of the sample.
  97690. ** And so forth. nLt is another list of integers that show the approximate
  97691. ** number of entries that are strictly less than the sample. The first
  97692. ** integer in nLt contains the number of entries in the index where the
  97693. ** left-most column is less than the left-most column of the sample.
  97694. ** The K-th integer in the nLt entry is the number of index entries
  97695. ** where the first K columns are less than the first K columns of the
  97696. ** sample. The nDLt column is like nLt except that it contains the
  97697. ** number of distinct entries in the index that are less than the
  97698. ** sample.
  97699. **
  97700. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  97701. ** The ANALYZE command will typically generate sqlite_stat4 tables
  97702. ** that contain between 10 and 40 samples which are distributed across
  97703. ** the key space, though not uniformly, and which include samples with
  97704. ** large nEq values.
  97705. **
  97706. ** Format for sqlite_stat3 redux:
  97707. **
  97708. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  97709. ** looks at the left-most column of the index. The sqlite_stat3.sample
  97710. ** column contains the actual value of the left-most column instead
  97711. ** of a blob encoding of the complete index key as is found in
  97712. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  97713. ** all contain just a single integer which is the same as the first
  97714. ** integer in the equivalent columns in sqlite_stat4.
  97715. */
  97716. #ifndef SQLITE_OMIT_ANALYZE
  97717. /* #include "sqliteInt.h" */
  97718. #if defined(SQLITE_ENABLE_STAT4)
  97719. # define IsStat4 1
  97720. # define IsStat3 0
  97721. #elif defined(SQLITE_ENABLE_STAT3)
  97722. # define IsStat4 0
  97723. # define IsStat3 1
  97724. #else
  97725. # define IsStat4 0
  97726. # define IsStat3 0
  97727. # undef SQLITE_STAT4_SAMPLES
  97728. # define SQLITE_STAT4_SAMPLES 1
  97729. #endif
  97730. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  97731. /*
  97732. ** This routine generates code that opens the sqlite_statN tables.
  97733. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  97734. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  97735. ** appropriate compile-time options are provided.
  97736. **
  97737. ** If the sqlite_statN tables do not previously exist, it is created.
  97738. **
  97739. ** Argument zWhere may be a pointer to a buffer containing a table name,
  97740. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  97741. ** the sqlite_statN tables associated with the named table are deleted.
  97742. ** If zWhere==0, then code is generated to delete all stat table entries.
  97743. */
  97744. static void openStatTable(
  97745. Parse *pParse, /* Parsing context */
  97746. int iDb, /* The database we are looking in */
  97747. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  97748. const char *zWhere, /* Delete entries for this table or index */
  97749. const char *zWhereType /* Either "tbl" or "idx" */
  97750. ){
  97751. static const struct {
  97752. const char *zName;
  97753. const char *zCols;
  97754. } aTable[] = {
  97755. { "sqlite_stat1", "tbl,idx,stat" },
  97756. #if defined(SQLITE_ENABLE_STAT4)
  97757. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  97758. { "sqlite_stat3", 0 },
  97759. #elif defined(SQLITE_ENABLE_STAT3)
  97760. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  97761. { "sqlite_stat4", 0 },
  97762. #else
  97763. { "sqlite_stat3", 0 },
  97764. { "sqlite_stat4", 0 },
  97765. #endif
  97766. };
  97767. int i;
  97768. sqlite3 *db = pParse->db;
  97769. Db *pDb;
  97770. Vdbe *v = sqlite3GetVdbe(pParse);
  97771. int aRoot[ArraySize(aTable)];
  97772. u8 aCreateTbl[ArraySize(aTable)];
  97773. if( v==0 ) return;
  97774. assert( sqlite3BtreeHoldsAllMutexes(db) );
  97775. assert( sqlite3VdbeDb(v)==db );
  97776. pDb = &db->aDb[iDb];
  97777. /* Create new statistic tables if they do not exist, or clear them
  97778. ** if they do already exist.
  97779. */
  97780. for(i=0; i<ArraySize(aTable); i++){
  97781. const char *zTab = aTable[i].zName;
  97782. Table *pStat;
  97783. if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
  97784. if( aTable[i].zCols ){
  97785. /* The sqlite_statN table does not exist. Create it. Note that a
  97786. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  97787. ** of the new table in register pParse->regRoot. This is important
  97788. ** because the OpenWrite opcode below will be needing it. */
  97789. sqlite3NestedParse(pParse,
  97790. "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
  97791. );
  97792. aRoot[i] = pParse->regRoot;
  97793. aCreateTbl[i] = OPFLAG_P2ISREG;
  97794. }
  97795. }else{
  97796. /* The table already exists. If zWhere is not NULL, delete all entries
  97797. ** associated with the table zWhere. If zWhere is NULL, delete the
  97798. ** entire contents of the table. */
  97799. aRoot[i] = pStat->tnum;
  97800. aCreateTbl[i] = 0;
  97801. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  97802. if( zWhere ){
  97803. sqlite3NestedParse(pParse,
  97804. "DELETE FROM %Q.%s WHERE %s=%Q",
  97805. pDb->zDbSName, zTab, zWhereType, zWhere
  97806. );
  97807. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  97808. }else if( db->xPreUpdateCallback ){
  97809. sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
  97810. #endif
  97811. }else{
  97812. /* The sqlite_stat[134] table already exists. Delete all rows. */
  97813. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  97814. }
  97815. }
  97816. }
  97817. /* Open the sqlite_stat[134] tables for writing. */
  97818. for(i=0; aTable[i].zCols; i++){
  97819. assert( i<ArraySize(aTable) );
  97820. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  97821. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  97822. VdbeComment((v, aTable[i].zName));
  97823. }
  97824. }
  97825. /*
  97826. ** Recommended number of samples for sqlite_stat4
  97827. */
  97828. #ifndef SQLITE_STAT4_SAMPLES
  97829. # define SQLITE_STAT4_SAMPLES 24
  97830. #endif
  97831. /*
  97832. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  97833. ** share an instance of the following structure to hold their state
  97834. ** information.
  97835. */
  97836. typedef struct Stat4Accum Stat4Accum;
  97837. typedef struct Stat4Sample Stat4Sample;
  97838. struct Stat4Sample {
  97839. tRowcnt *anEq; /* sqlite_stat4.nEq */
  97840. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  97841. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97842. tRowcnt *anLt; /* sqlite_stat4.nLt */
  97843. union {
  97844. i64 iRowid; /* Rowid in main table of the key */
  97845. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  97846. } u;
  97847. u32 nRowid; /* Sizeof aRowid[] */
  97848. u8 isPSample; /* True if a periodic sample */
  97849. int iCol; /* If !isPSample, the reason for inclusion */
  97850. u32 iHash; /* Tiebreaker hash */
  97851. #endif
  97852. };
  97853. struct Stat4Accum {
  97854. tRowcnt nRow; /* Number of rows in the entire table */
  97855. tRowcnt nPSample; /* How often to do a periodic sample */
  97856. int nCol; /* Number of columns in index + pk/rowid */
  97857. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  97858. int mxSample; /* Maximum number of samples to accumulate */
  97859. Stat4Sample current; /* Current row as a Stat4Sample */
  97860. u32 iPrn; /* Pseudo-random number used for sampling */
  97861. Stat4Sample *aBest; /* Array of nCol best samples */
  97862. int iMin; /* Index in a[] of entry with minimum score */
  97863. int nSample; /* Current number of samples */
  97864. int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
  97865. int iGet; /* Index of current sample accessed by stat_get() */
  97866. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  97867. sqlite3 *db; /* Database connection, for malloc() */
  97868. };
  97869. /* Reclaim memory used by a Stat4Sample
  97870. */
  97871. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97872. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  97873. assert( db!=0 );
  97874. if( p->nRowid ){
  97875. sqlite3DbFree(db, p->u.aRowid);
  97876. p->nRowid = 0;
  97877. }
  97878. }
  97879. #endif
  97880. /* Initialize the BLOB value of a ROWID
  97881. */
  97882. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97883. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  97884. assert( db!=0 );
  97885. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  97886. p->u.aRowid = sqlite3DbMallocRawNN(db, n);
  97887. if( p->u.aRowid ){
  97888. p->nRowid = n;
  97889. memcpy(p->u.aRowid, pData, n);
  97890. }else{
  97891. p->nRowid = 0;
  97892. }
  97893. }
  97894. #endif
  97895. /* Initialize the INTEGER value of a ROWID.
  97896. */
  97897. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97898. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  97899. assert( db!=0 );
  97900. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  97901. p->nRowid = 0;
  97902. p->u.iRowid = iRowid;
  97903. }
  97904. #endif
  97905. /*
  97906. ** Copy the contents of object (*pFrom) into (*pTo).
  97907. */
  97908. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97909. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  97910. pTo->isPSample = pFrom->isPSample;
  97911. pTo->iCol = pFrom->iCol;
  97912. pTo->iHash = pFrom->iHash;
  97913. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  97914. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  97915. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  97916. if( pFrom->nRowid ){
  97917. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  97918. }else{
  97919. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  97920. }
  97921. }
  97922. #endif
  97923. /*
  97924. ** Reclaim all memory of a Stat4Accum structure.
  97925. */
  97926. static void stat4Destructor(void *pOld){
  97927. Stat4Accum *p = (Stat4Accum*)pOld;
  97928. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97929. int i;
  97930. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  97931. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  97932. sampleClear(p->db, &p->current);
  97933. #endif
  97934. sqlite3DbFree(p->db, p);
  97935. }
  97936. /*
  97937. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  97938. ** are:
  97939. ** N: The number of columns in the index including the rowid/pk (note 1)
  97940. ** K: The number of columns in the index excluding the rowid/pk.
  97941. ** C: The number of rows in the index (note 2)
  97942. **
  97943. ** Note 1: In the special case of the covering index that implements a
  97944. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  97945. ** total number of columns in the table.
  97946. **
  97947. ** Note 2: C is only used for STAT3 and STAT4.
  97948. **
  97949. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  97950. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  97951. ** PRIMARY KEY of the table. The covering index that implements the
  97952. ** original WITHOUT ROWID table as N==K as a special case.
  97953. **
  97954. ** This routine allocates the Stat4Accum object in heap memory. The return
  97955. ** value is a pointer to the Stat4Accum object. The datatype of the
  97956. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  97957. ** object.
  97958. */
  97959. static void statInit(
  97960. sqlite3_context *context,
  97961. int argc,
  97962. sqlite3_value **argv
  97963. ){
  97964. Stat4Accum *p;
  97965. int nCol; /* Number of columns in index being sampled */
  97966. int nKeyCol; /* Number of key columns */
  97967. int nColUp; /* nCol rounded up for alignment */
  97968. int n; /* Bytes of space to allocate */
  97969. sqlite3 *db; /* Database connection */
  97970. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97971. int mxSample = SQLITE_STAT4_SAMPLES;
  97972. #endif
  97973. /* Decode the three function arguments */
  97974. UNUSED_PARAMETER(argc);
  97975. nCol = sqlite3_value_int(argv[0]);
  97976. assert( nCol>0 );
  97977. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  97978. nKeyCol = sqlite3_value_int(argv[1]);
  97979. assert( nKeyCol<=nCol );
  97980. assert( nKeyCol>0 );
  97981. /* Allocate the space required for the Stat4Accum object */
  97982. n = sizeof(*p)
  97983. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  97984. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  97985. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97986. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  97987. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  97988. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  97989. #endif
  97990. ;
  97991. db = sqlite3_context_db_handle(context);
  97992. p = sqlite3DbMallocZero(db, n);
  97993. if( p==0 ){
  97994. sqlite3_result_error_nomem(context);
  97995. return;
  97996. }
  97997. p->db = db;
  97998. p->nRow = 0;
  97999. p->nCol = nCol;
  98000. p->nKeyCol = nKeyCol;
  98001. p->current.anDLt = (tRowcnt*)&p[1];
  98002. p->current.anEq = &p->current.anDLt[nColUp];
  98003. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98004. {
  98005. u8 *pSpace; /* Allocated space not yet assigned */
  98006. int i; /* Used to iterate through p->aSample[] */
  98007. p->iGet = -1;
  98008. p->mxSample = mxSample;
  98009. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  98010. p->current.anLt = &p->current.anEq[nColUp];
  98011. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  98012. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  98013. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  98014. p->aBest = &p->a[mxSample];
  98015. pSpace = (u8*)(&p->a[mxSample+nCol]);
  98016. for(i=0; i<(mxSample+nCol); i++){
  98017. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  98018. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  98019. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  98020. }
  98021. assert( (pSpace - (u8*)p)==n );
  98022. for(i=0; i<nCol; i++){
  98023. p->aBest[i].iCol = i;
  98024. }
  98025. }
  98026. #endif
  98027. /* Return a pointer to the allocated object to the caller. Note that
  98028. ** only the pointer (the 2nd parameter) matters. The size of the object
  98029. ** (given by the 3rd parameter) is never used and can be any positive
  98030. ** value. */
  98031. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  98032. }
  98033. static const FuncDef statInitFuncdef = {
  98034. 2+IsStat34, /* nArg */
  98035. SQLITE_UTF8, /* funcFlags */
  98036. 0, /* pUserData */
  98037. 0, /* pNext */
  98038. statInit, /* xSFunc */
  98039. 0, /* xFinalize */
  98040. 0, 0, /* xValue, xInverse */
  98041. "stat_init", /* zName */
  98042. {0}
  98043. };
  98044. #ifdef SQLITE_ENABLE_STAT4
  98045. /*
  98046. ** pNew and pOld are both candidate non-periodic samples selected for
  98047. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  98048. ** considering only any trailing columns and the sample hash value, this
  98049. ** function returns true if sample pNew is to be preferred over pOld.
  98050. ** In other words, if we assume that the cardinalities of the selected
  98051. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  98052. **
  98053. ** This function assumes that for each argument sample, the contents of
  98054. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  98055. */
  98056. static int sampleIsBetterPost(
  98057. Stat4Accum *pAccum,
  98058. Stat4Sample *pNew,
  98059. Stat4Sample *pOld
  98060. ){
  98061. int nCol = pAccum->nCol;
  98062. int i;
  98063. assert( pNew->iCol==pOld->iCol );
  98064. for(i=pNew->iCol+1; i<nCol; i++){
  98065. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  98066. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  98067. }
  98068. if( pNew->iHash>pOld->iHash ) return 1;
  98069. return 0;
  98070. }
  98071. #endif
  98072. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98073. /*
  98074. ** Return true if pNew is to be preferred over pOld.
  98075. **
  98076. ** This function assumes that for each argument sample, the contents of
  98077. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  98078. */
  98079. static int sampleIsBetter(
  98080. Stat4Accum *pAccum,
  98081. Stat4Sample *pNew,
  98082. Stat4Sample *pOld
  98083. ){
  98084. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  98085. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  98086. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  98087. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  98088. if( (nEqNew>nEqOld) ) return 1;
  98089. #ifdef SQLITE_ENABLE_STAT4
  98090. if( nEqNew==nEqOld ){
  98091. if( pNew->iCol<pOld->iCol ) return 1;
  98092. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  98093. }
  98094. return 0;
  98095. #else
  98096. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  98097. #endif
  98098. }
  98099. /*
  98100. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  98101. ** remove the least desirable sample from p->a[] to make room.
  98102. */
  98103. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  98104. Stat4Sample *pSample = 0;
  98105. int i;
  98106. assert( IsStat4 || nEqZero==0 );
  98107. #ifdef SQLITE_ENABLE_STAT4
  98108. /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
  98109. ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
  98110. ** other words, if nMaxEqZero is n, then it is guaranteed that there
  98111. ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
  98112. if( nEqZero>p->nMaxEqZero ){
  98113. p->nMaxEqZero = nEqZero;
  98114. }
  98115. if( pNew->isPSample==0 ){
  98116. Stat4Sample *pUpgrade = 0;
  98117. assert( pNew->anEq[pNew->iCol]>0 );
  98118. /* This sample is being added because the prefix that ends in column
  98119. ** iCol occurs many times in the table. However, if we have already
  98120. ** added a sample that shares this prefix, there is no need to add
  98121. ** this one. Instead, upgrade the priority of the highest priority
  98122. ** existing sample that shares this prefix. */
  98123. for(i=p->nSample-1; i>=0; i--){
  98124. Stat4Sample *pOld = &p->a[i];
  98125. if( pOld->anEq[pNew->iCol]==0 ){
  98126. if( pOld->isPSample ) return;
  98127. assert( pOld->iCol>pNew->iCol );
  98128. assert( sampleIsBetter(p, pNew, pOld) );
  98129. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  98130. pUpgrade = pOld;
  98131. }
  98132. }
  98133. }
  98134. if( pUpgrade ){
  98135. pUpgrade->iCol = pNew->iCol;
  98136. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  98137. goto find_new_min;
  98138. }
  98139. }
  98140. #endif
  98141. /* If necessary, remove sample iMin to make room for the new sample. */
  98142. if( p->nSample>=p->mxSample ){
  98143. Stat4Sample *pMin = &p->a[p->iMin];
  98144. tRowcnt *anEq = pMin->anEq;
  98145. tRowcnt *anLt = pMin->anLt;
  98146. tRowcnt *anDLt = pMin->anDLt;
  98147. sampleClear(p->db, pMin);
  98148. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  98149. pSample = &p->a[p->nSample-1];
  98150. pSample->nRowid = 0;
  98151. pSample->anEq = anEq;
  98152. pSample->anDLt = anDLt;
  98153. pSample->anLt = anLt;
  98154. p->nSample = p->mxSample-1;
  98155. }
  98156. /* The "rows less-than" for the rowid column must be greater than that
  98157. ** for the last sample in the p->a[] array. Otherwise, the samples would
  98158. ** be out of order. */
  98159. #ifdef SQLITE_ENABLE_STAT4
  98160. assert( p->nSample==0
  98161. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  98162. #endif
  98163. /* Insert the new sample */
  98164. pSample = &p->a[p->nSample];
  98165. sampleCopy(p, pSample, pNew);
  98166. p->nSample++;
  98167. /* Zero the first nEqZero entries in the anEq[] array. */
  98168. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  98169. #ifdef SQLITE_ENABLE_STAT4
  98170. find_new_min:
  98171. #endif
  98172. if( p->nSample>=p->mxSample ){
  98173. int iMin = -1;
  98174. for(i=0; i<p->mxSample; i++){
  98175. if( p->a[i].isPSample ) continue;
  98176. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  98177. iMin = i;
  98178. }
  98179. }
  98180. assert( iMin>=0 );
  98181. p->iMin = iMin;
  98182. }
  98183. }
  98184. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  98185. /*
  98186. ** Field iChng of the index being scanned has changed. So at this point
  98187. ** p->current contains a sample that reflects the previous row of the
  98188. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  98189. ** correct at this point.
  98190. */
  98191. static void samplePushPrevious(Stat4Accum *p, int iChng){
  98192. #ifdef SQLITE_ENABLE_STAT4
  98193. int i;
  98194. /* Check if any samples from the aBest[] array should be pushed
  98195. ** into IndexSample.a[] at this point. */
  98196. for(i=(p->nCol-2); i>=iChng; i--){
  98197. Stat4Sample *pBest = &p->aBest[i];
  98198. pBest->anEq[i] = p->current.anEq[i];
  98199. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  98200. sampleInsert(p, pBest, i);
  98201. }
  98202. }
  98203. /* Check that no sample contains an anEq[] entry with an index of
  98204. ** p->nMaxEqZero or greater set to zero. */
  98205. for(i=p->nSample-1; i>=0; i--){
  98206. int j;
  98207. for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
  98208. }
  98209. /* Update the anEq[] fields of any samples already collected. */
  98210. if( iChng<p->nMaxEqZero ){
  98211. for(i=p->nSample-1; i>=0; i--){
  98212. int j;
  98213. for(j=iChng; j<p->nCol; j++){
  98214. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  98215. }
  98216. }
  98217. p->nMaxEqZero = iChng;
  98218. }
  98219. #endif
  98220. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  98221. if( iChng==0 ){
  98222. tRowcnt nLt = p->current.anLt[0];
  98223. tRowcnt nEq = p->current.anEq[0];
  98224. /* Check if this is to be a periodic sample. If so, add it. */
  98225. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  98226. p->current.isPSample = 1;
  98227. sampleInsert(p, &p->current, 0);
  98228. p->current.isPSample = 0;
  98229. }else
  98230. /* Or if it is a non-periodic sample. Add it in this case too. */
  98231. if( p->nSample<p->mxSample
  98232. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  98233. ){
  98234. sampleInsert(p, &p->current, 0);
  98235. }
  98236. }
  98237. #endif
  98238. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  98239. UNUSED_PARAMETER( p );
  98240. UNUSED_PARAMETER( iChng );
  98241. #endif
  98242. }
  98243. /*
  98244. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  98245. ** Arguments:
  98246. **
  98247. ** P Pointer to the Stat4Accum object created by stat_init()
  98248. ** C Index of left-most column to differ from previous row
  98249. ** R Rowid for the current row. Might be a key record for
  98250. ** WITHOUT ROWID tables.
  98251. **
  98252. ** This SQL function always returns NULL. It's purpose it to accumulate
  98253. ** statistical data and/or samples in the Stat4Accum object about the
  98254. ** index being analyzed. The stat_get() SQL function will later be used to
  98255. ** extract relevant information for constructing the sqlite_statN tables.
  98256. **
  98257. ** The R parameter is only used for STAT3 and STAT4
  98258. */
  98259. static void statPush(
  98260. sqlite3_context *context,
  98261. int argc,
  98262. sqlite3_value **argv
  98263. ){
  98264. int i;
  98265. /* The three function arguments */
  98266. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  98267. int iChng = sqlite3_value_int(argv[1]);
  98268. UNUSED_PARAMETER( argc );
  98269. UNUSED_PARAMETER( context );
  98270. assert( p->nCol>0 );
  98271. assert( iChng<p->nCol );
  98272. if( p->nRow==0 ){
  98273. /* This is the first call to this function. Do initialization. */
  98274. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  98275. }else{
  98276. /* Second and subsequent calls get processed here */
  98277. samplePushPrevious(p, iChng);
  98278. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  98279. ** to the current row of the index. */
  98280. for(i=0; i<iChng; i++){
  98281. p->current.anEq[i]++;
  98282. }
  98283. for(i=iChng; i<p->nCol; i++){
  98284. p->current.anDLt[i]++;
  98285. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98286. p->current.anLt[i] += p->current.anEq[i];
  98287. #endif
  98288. p->current.anEq[i] = 1;
  98289. }
  98290. }
  98291. p->nRow++;
  98292. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98293. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  98294. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  98295. }else{
  98296. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  98297. sqlite3_value_blob(argv[2]));
  98298. }
  98299. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  98300. #endif
  98301. #ifdef SQLITE_ENABLE_STAT4
  98302. {
  98303. tRowcnt nLt = p->current.anLt[p->nCol-1];
  98304. /* Check if this is to be a periodic sample. If so, add it. */
  98305. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  98306. p->current.isPSample = 1;
  98307. p->current.iCol = 0;
  98308. sampleInsert(p, &p->current, p->nCol-1);
  98309. p->current.isPSample = 0;
  98310. }
  98311. /* Update the aBest[] array. */
  98312. for(i=0; i<(p->nCol-1); i++){
  98313. p->current.iCol = i;
  98314. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  98315. sampleCopy(p, &p->aBest[i], &p->current);
  98316. }
  98317. }
  98318. }
  98319. #endif
  98320. }
  98321. static const FuncDef statPushFuncdef = {
  98322. 2+IsStat34, /* nArg */
  98323. SQLITE_UTF8, /* funcFlags */
  98324. 0, /* pUserData */
  98325. 0, /* pNext */
  98326. statPush, /* xSFunc */
  98327. 0, /* xFinalize */
  98328. 0, 0, /* xValue, xInverse */
  98329. "stat_push", /* zName */
  98330. {0}
  98331. };
  98332. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  98333. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  98334. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  98335. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  98336. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  98337. /*
  98338. ** Implementation of the stat_get(P,J) SQL function. This routine is
  98339. ** used to query statistical information that has been gathered into
  98340. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  98341. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  98342. ** The content to returned is determined by the parameter J
  98343. ** which is one of the STAT_GET_xxxx values defined above.
  98344. **
  98345. ** The stat_get(P,J) function is not available to generic SQL. It is
  98346. ** inserted as part of a manually constructed bytecode program. (See
  98347. ** the callStatGet() routine below.) It is guaranteed that the P
  98348. ** parameter will always be a poiner to a Stat4Accum object, never a
  98349. ** NULL.
  98350. **
  98351. ** If neither STAT3 nor STAT4 are enabled, then J is always
  98352. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  98353. ** a one-parameter function, stat_get(P), that always returns the
  98354. ** stat1 table entry information.
  98355. */
  98356. static void statGet(
  98357. sqlite3_context *context,
  98358. int argc,
  98359. sqlite3_value **argv
  98360. ){
  98361. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  98362. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98363. /* STAT3 and STAT4 have a parameter on this routine. */
  98364. int eCall = sqlite3_value_int(argv[1]);
  98365. assert( argc==2 );
  98366. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  98367. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  98368. || eCall==STAT_GET_NDLT
  98369. );
  98370. if( eCall==STAT_GET_STAT1 )
  98371. #else
  98372. assert( argc==1 );
  98373. #endif
  98374. {
  98375. /* Return the value to store in the "stat" column of the sqlite_stat1
  98376. ** table for this index.
  98377. **
  98378. ** The value is a string composed of a list of integers describing
  98379. ** the index. The first integer in the list is the total number of
  98380. ** entries in the index. There is one additional integer in the list
  98381. ** for each indexed column. This additional integer is an estimate of
  98382. ** the number of rows matched by a stabbing query on the index using
  98383. ** a key with the corresponding number of fields. In other words,
  98384. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  98385. ** "100 10 2", then SQLite estimates that:
  98386. **
  98387. ** * the index contains 100 rows,
  98388. ** * "WHERE a=?" matches 10 rows, and
  98389. ** * "WHERE a=? AND b=?" matches 2 rows.
  98390. **
  98391. ** If D is the count of distinct values and K is the total number of
  98392. ** rows, then each estimate is computed as:
  98393. **
  98394. ** I = (K+D-1)/D
  98395. */
  98396. char *z;
  98397. int i;
  98398. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  98399. if( zRet==0 ){
  98400. sqlite3_result_error_nomem(context);
  98401. return;
  98402. }
  98403. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  98404. z = zRet + sqlite3Strlen30(zRet);
  98405. for(i=0; i<p->nKeyCol; i++){
  98406. u64 nDistinct = p->current.anDLt[i] + 1;
  98407. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  98408. sqlite3_snprintf(24, z, " %llu", iVal);
  98409. z += sqlite3Strlen30(z);
  98410. assert( p->current.anEq[i] );
  98411. }
  98412. assert( z[0]=='\0' && z>zRet );
  98413. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  98414. }
  98415. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98416. else if( eCall==STAT_GET_ROWID ){
  98417. if( p->iGet<0 ){
  98418. samplePushPrevious(p, 0);
  98419. p->iGet = 0;
  98420. }
  98421. if( p->iGet<p->nSample ){
  98422. Stat4Sample *pS = p->a + p->iGet;
  98423. if( pS->nRowid==0 ){
  98424. sqlite3_result_int64(context, pS->u.iRowid);
  98425. }else{
  98426. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  98427. SQLITE_TRANSIENT);
  98428. }
  98429. }
  98430. }else{
  98431. tRowcnt *aCnt = 0;
  98432. assert( p->iGet<p->nSample );
  98433. switch( eCall ){
  98434. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  98435. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  98436. default: {
  98437. aCnt = p->a[p->iGet].anDLt;
  98438. p->iGet++;
  98439. break;
  98440. }
  98441. }
  98442. if( IsStat3 ){
  98443. sqlite3_result_int64(context, (i64)aCnt[0]);
  98444. }else{
  98445. char *zRet = sqlite3MallocZero(p->nCol * 25);
  98446. if( zRet==0 ){
  98447. sqlite3_result_error_nomem(context);
  98448. }else{
  98449. int i;
  98450. char *z = zRet;
  98451. for(i=0; i<p->nCol; i++){
  98452. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  98453. z += sqlite3Strlen30(z);
  98454. }
  98455. assert( z[0]=='\0' && z>zRet );
  98456. z[-1] = '\0';
  98457. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  98458. }
  98459. }
  98460. }
  98461. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  98462. #ifndef SQLITE_DEBUG
  98463. UNUSED_PARAMETER( argc );
  98464. #endif
  98465. }
  98466. static const FuncDef statGetFuncdef = {
  98467. 1+IsStat34, /* nArg */
  98468. SQLITE_UTF8, /* funcFlags */
  98469. 0, /* pUserData */
  98470. 0, /* pNext */
  98471. statGet, /* xSFunc */
  98472. 0, /* xFinalize */
  98473. 0, 0, /* xValue, xInverse */
  98474. "stat_get", /* zName */
  98475. {0}
  98476. };
  98477. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  98478. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  98479. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98480. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  98481. #elif SQLITE_DEBUG
  98482. assert( iParam==STAT_GET_STAT1 );
  98483. #else
  98484. UNUSED_PARAMETER( iParam );
  98485. #endif
  98486. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
  98487. (char*)&statGetFuncdef, P4_FUNCDEF);
  98488. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  98489. }
  98490. /*
  98491. ** Generate code to do an analysis of all indices associated with
  98492. ** a single table.
  98493. */
  98494. static void analyzeOneTable(
  98495. Parse *pParse, /* Parser context */
  98496. Table *pTab, /* Table whose indices are to be analyzed */
  98497. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  98498. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  98499. int iMem, /* Available memory locations begin here */
  98500. int iTab /* Next available cursor */
  98501. ){
  98502. sqlite3 *db = pParse->db; /* Database handle */
  98503. Index *pIdx; /* An index to being analyzed */
  98504. int iIdxCur; /* Cursor open on index being analyzed */
  98505. int iTabCur; /* Table cursor */
  98506. Vdbe *v; /* The virtual machine being built up */
  98507. int i; /* Loop counter */
  98508. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  98509. int iDb; /* Index of database containing pTab */
  98510. u8 needTableCnt = 1; /* True to count the table */
  98511. int regNewRowid = iMem++; /* Rowid for the inserted record */
  98512. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  98513. int regChng = iMem++; /* Index of changed index field */
  98514. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98515. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  98516. #endif
  98517. int regTemp = iMem++; /* Temporary use register */
  98518. int regTabname = iMem++; /* Register containing table name */
  98519. int regIdxname = iMem++; /* Register containing index name */
  98520. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  98521. int regPrev = iMem; /* MUST BE LAST (see below) */
  98522. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  98523. Table *pStat1 = 0;
  98524. #endif
  98525. pParse->nMem = MAX(pParse->nMem, iMem);
  98526. v = sqlite3GetVdbe(pParse);
  98527. if( v==0 || NEVER(pTab==0) ){
  98528. return;
  98529. }
  98530. if( pTab->tnum==0 ){
  98531. /* Do not gather statistics on views or virtual tables */
  98532. return;
  98533. }
  98534. if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
  98535. /* Do not gather statistics on system tables */
  98536. return;
  98537. }
  98538. assert( sqlite3BtreeHoldsAllMutexes(db) );
  98539. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  98540. assert( iDb>=0 );
  98541. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98542. #ifndef SQLITE_OMIT_AUTHORIZATION
  98543. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  98544. db->aDb[iDb].zDbSName ) ){
  98545. return;
  98546. }
  98547. #endif
  98548. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  98549. if( db->xPreUpdateCallback ){
  98550. pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
  98551. if( pStat1==0 ) return;
  98552. pStat1->zName = (char*)&pStat1[1];
  98553. memcpy(pStat1->zName, "sqlite_stat1", 13);
  98554. pStat1->nCol = 3;
  98555. pStat1->iPKey = -1;
  98556. sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);
  98557. }
  98558. #endif
  98559. /* Establish a read-lock on the table at the shared-cache level.
  98560. ** Open a read-only cursor on the table. Also allocate a cursor number
  98561. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  98562. ** this time though. */
  98563. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  98564. iTabCur = iTab++;
  98565. iIdxCur = iTab++;
  98566. pParse->nTab = MAX(pParse->nTab, iTab);
  98567. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  98568. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  98569. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  98570. int nCol; /* Number of columns in pIdx. "N" */
  98571. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  98572. int addrNextRow; /* Address of "next_row:" */
  98573. const char *zIdxName; /* Name of the index */
  98574. int nColTest; /* Number of columns to test for changes */
  98575. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  98576. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  98577. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  98578. nCol = pIdx->nKeyCol;
  98579. zIdxName = pTab->zName;
  98580. nColTest = nCol - 1;
  98581. }else{
  98582. nCol = pIdx->nColumn;
  98583. zIdxName = pIdx->zName;
  98584. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  98585. }
  98586. /* Populate the register containing the index name. */
  98587. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  98588. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  98589. /*
  98590. ** Pseudo-code for loop that calls stat_push():
  98591. **
  98592. ** Rewind csr
  98593. ** if eof(csr) goto end_of_scan;
  98594. ** regChng = 0
  98595. ** goto chng_addr_0;
  98596. **
  98597. ** next_row:
  98598. ** regChng = 0
  98599. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  98600. ** regChng = 1
  98601. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  98602. ** ...
  98603. ** regChng = N
  98604. ** goto chng_addr_N
  98605. **
  98606. ** chng_addr_0:
  98607. ** regPrev(0) = idx(0)
  98608. ** chng_addr_1:
  98609. ** regPrev(1) = idx(1)
  98610. ** ...
  98611. **
  98612. ** endDistinctTest:
  98613. ** regRowid = idx(rowid)
  98614. ** stat_push(P, regChng, regRowid)
  98615. ** Next csr
  98616. ** if !eof(csr) goto next_row;
  98617. **
  98618. ** end_of_scan:
  98619. */
  98620. /* Make sure there are enough memory cells allocated to accommodate
  98621. ** the regPrev array and a trailing rowid (the rowid slot is required
  98622. ** when building a record to insert into the sample column of
  98623. ** the sqlite_stat4 table. */
  98624. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  98625. /* Open a read-only cursor on the index being analyzed. */
  98626. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  98627. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  98628. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  98629. VdbeComment((v, "%s", pIdx->zName));
  98630. /* Invoke the stat_init() function. The arguments are:
  98631. **
  98632. ** (1) the number of columns in the index including the rowid
  98633. ** (or for a WITHOUT ROWID table, the number of PK columns),
  98634. ** (2) the number of columns in the key without the rowid/pk
  98635. ** (3) the number of rows in the index,
  98636. **
  98637. **
  98638. ** The third argument is only used for STAT3 and STAT4
  98639. */
  98640. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98641. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  98642. #endif
  98643. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  98644. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  98645. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
  98646. (char*)&statInitFuncdef, P4_FUNCDEF);
  98647. sqlite3VdbeChangeP5(v, 2+IsStat34);
  98648. /* Implementation of the following:
  98649. **
  98650. ** Rewind csr
  98651. ** if eof(csr) goto end_of_scan;
  98652. ** regChng = 0
  98653. ** goto next_push_0;
  98654. **
  98655. */
  98656. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  98657. VdbeCoverage(v);
  98658. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  98659. addrNextRow = sqlite3VdbeCurrentAddr(v);
  98660. if( nColTest>0 ){
  98661. int endDistinctTest = sqlite3VdbeMakeLabel(pParse);
  98662. int *aGotoChng; /* Array of jump instruction addresses */
  98663. aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
  98664. if( aGotoChng==0 ) continue;
  98665. /*
  98666. ** next_row:
  98667. ** regChng = 0
  98668. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  98669. ** regChng = 1
  98670. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  98671. ** ...
  98672. ** regChng = N
  98673. ** goto endDistinctTest
  98674. */
  98675. sqlite3VdbeAddOp0(v, OP_Goto);
  98676. addrNextRow = sqlite3VdbeCurrentAddr(v);
  98677. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  98678. /* For a single-column UNIQUE index, once we have found a non-NULL
  98679. ** row, we know that all the rest will be distinct, so skip
  98680. ** subsequent distinctness tests. */
  98681. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  98682. VdbeCoverage(v);
  98683. }
  98684. for(i=0; i<nColTest; i++){
  98685. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  98686. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  98687. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  98688. aGotoChng[i] =
  98689. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  98690. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  98691. VdbeCoverage(v);
  98692. }
  98693. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  98694. sqlite3VdbeGoto(v, endDistinctTest);
  98695. /*
  98696. ** chng_addr_0:
  98697. ** regPrev(0) = idx(0)
  98698. ** chng_addr_1:
  98699. ** regPrev(1) = idx(1)
  98700. ** ...
  98701. */
  98702. sqlite3VdbeJumpHere(v, addrNextRow-1);
  98703. for(i=0; i<nColTest; i++){
  98704. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  98705. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  98706. }
  98707. sqlite3VdbeResolveLabel(v, endDistinctTest);
  98708. sqlite3DbFree(db, aGotoChng);
  98709. }
  98710. /*
  98711. ** chng_addr_N:
  98712. ** regRowid = idx(rowid) // STAT34 only
  98713. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  98714. ** Next csr
  98715. ** if !eof(csr) goto next_row;
  98716. */
  98717. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98718. assert( regRowid==(regStat4+2) );
  98719. if( HasRowid(pTab) ){
  98720. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  98721. }else{
  98722. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  98723. int j, k, regKey;
  98724. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  98725. for(j=0; j<pPk->nKeyCol; j++){
  98726. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  98727. assert( k>=0 && k<pIdx->nColumn );
  98728. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  98729. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  98730. }
  98731. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  98732. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  98733. }
  98734. #endif
  98735. assert( regChng==(regStat4+1) );
  98736. sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
  98737. (char*)&statPushFuncdef, P4_FUNCDEF);
  98738. sqlite3VdbeChangeP5(v, 2+IsStat34);
  98739. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  98740. /* Add the entry to the stat1 table. */
  98741. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  98742. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  98743. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  98744. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  98745. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  98746. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  98747. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  98748. #endif
  98749. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  98750. /* Add the entries to the stat3 or stat4 table. */
  98751. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98752. {
  98753. int regEq = regStat1;
  98754. int regLt = regStat1+1;
  98755. int regDLt = regStat1+2;
  98756. int regSample = regStat1+3;
  98757. int regCol = regStat1+4;
  98758. int regSampleRowid = regCol + nCol;
  98759. int addrNext;
  98760. int addrIsNull;
  98761. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  98762. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  98763. addrNext = sqlite3VdbeCurrentAddr(v);
  98764. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  98765. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  98766. VdbeCoverage(v);
  98767. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  98768. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  98769. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  98770. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  98771. VdbeCoverage(v);
  98772. #ifdef SQLITE_ENABLE_STAT3
  98773. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
  98774. #else
  98775. for(i=0; i<nCol; i++){
  98776. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  98777. }
  98778. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  98779. #endif
  98780. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  98781. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  98782. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  98783. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  98784. sqlite3VdbeJumpHere(v, addrIsNull);
  98785. }
  98786. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  98787. /* End of analysis */
  98788. sqlite3VdbeJumpHere(v, addrRewind);
  98789. }
  98790. /* Create a single sqlite_stat1 entry containing NULL as the index
  98791. ** name and the row count as the content.
  98792. */
  98793. if( pOnlyIdx==0 && needTableCnt ){
  98794. VdbeComment((v, "%s", pTab->zName));
  98795. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  98796. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  98797. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  98798. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  98799. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  98800. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  98801. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  98802. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  98803. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  98804. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  98805. #endif
  98806. sqlite3VdbeJumpHere(v, jZeroRows);
  98807. }
  98808. }
  98809. /*
  98810. ** Generate code that will cause the most recent index analysis to
  98811. ** be loaded into internal hash tables where is can be used.
  98812. */
  98813. static void loadAnalysis(Parse *pParse, int iDb){
  98814. Vdbe *v = sqlite3GetVdbe(pParse);
  98815. if( v ){
  98816. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  98817. }
  98818. }
  98819. /*
  98820. ** Generate code that will do an analysis of an entire database
  98821. */
  98822. static void analyzeDatabase(Parse *pParse, int iDb){
  98823. sqlite3 *db = pParse->db;
  98824. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  98825. HashElem *k;
  98826. int iStatCur;
  98827. int iMem;
  98828. int iTab;
  98829. sqlite3BeginWriteOperation(pParse, 0, iDb);
  98830. iStatCur = pParse->nTab;
  98831. pParse->nTab += 3;
  98832. openStatTable(pParse, iDb, iStatCur, 0, 0);
  98833. iMem = pParse->nMem+1;
  98834. iTab = pParse->nTab;
  98835. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98836. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  98837. Table *pTab = (Table*)sqliteHashData(k);
  98838. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  98839. }
  98840. loadAnalysis(pParse, iDb);
  98841. }
  98842. /*
  98843. ** Generate code that will do an analysis of a single table in
  98844. ** a database. If pOnlyIdx is not NULL then it is a single index
  98845. ** in pTab that should be analyzed.
  98846. */
  98847. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  98848. int iDb;
  98849. int iStatCur;
  98850. assert( pTab!=0 );
  98851. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  98852. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  98853. sqlite3BeginWriteOperation(pParse, 0, iDb);
  98854. iStatCur = pParse->nTab;
  98855. pParse->nTab += 3;
  98856. if( pOnlyIdx ){
  98857. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  98858. }else{
  98859. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  98860. }
  98861. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  98862. loadAnalysis(pParse, iDb);
  98863. }
  98864. /*
  98865. ** Generate code for the ANALYZE command. The parser calls this routine
  98866. ** when it recognizes an ANALYZE command.
  98867. **
  98868. ** ANALYZE -- 1
  98869. ** ANALYZE <database> -- 2
  98870. ** ANALYZE ?<database>.?<tablename> -- 3
  98871. **
  98872. ** Form 1 causes all indices in all attached databases to be analyzed.
  98873. ** Form 2 analyzes all indices the single database named.
  98874. ** Form 3 analyzes all indices associated with the named table.
  98875. */
  98876. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  98877. sqlite3 *db = pParse->db;
  98878. int iDb;
  98879. int i;
  98880. char *z, *zDb;
  98881. Table *pTab;
  98882. Index *pIdx;
  98883. Token *pTableName;
  98884. Vdbe *v;
  98885. /* Read the database schema. If an error occurs, leave an error message
  98886. ** and code in pParse and return NULL. */
  98887. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  98888. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  98889. return;
  98890. }
  98891. assert( pName2!=0 || pName1==0 );
  98892. if( pName1==0 ){
  98893. /* Form 1: Analyze everything */
  98894. for(i=0; i<db->nDb; i++){
  98895. if( i==1 ) continue; /* Do not analyze the TEMP database */
  98896. analyzeDatabase(pParse, i);
  98897. }
  98898. }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
  98899. /* Analyze the schema named as the argument */
  98900. analyzeDatabase(pParse, iDb);
  98901. }else{
  98902. /* Form 3: Analyze the table or index named as an argument */
  98903. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  98904. if( iDb>=0 ){
  98905. zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
  98906. z = sqlite3NameFromToken(db, pTableName);
  98907. if( z ){
  98908. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  98909. analyzeTable(pParse, pIdx->pTable, pIdx);
  98910. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  98911. analyzeTable(pParse, pTab, 0);
  98912. }
  98913. sqlite3DbFree(db, z);
  98914. }
  98915. }
  98916. }
  98917. if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
  98918. sqlite3VdbeAddOp0(v, OP_Expire);
  98919. }
  98920. }
  98921. /*
  98922. ** Used to pass information from the analyzer reader through to the
  98923. ** callback routine.
  98924. */
  98925. typedef struct analysisInfo analysisInfo;
  98926. struct analysisInfo {
  98927. sqlite3 *db;
  98928. const char *zDatabase;
  98929. };
  98930. /*
  98931. ** The first argument points to a nul-terminated string containing a
  98932. ** list of space separated integers. Read the first nOut of these into
  98933. ** the array aOut[].
  98934. */
  98935. static void decodeIntArray(
  98936. char *zIntArray, /* String containing int array to decode */
  98937. int nOut, /* Number of slots in aOut[] */
  98938. tRowcnt *aOut, /* Store integers here */
  98939. LogEst *aLog, /* Or, if aOut==0, here */
  98940. Index *pIndex /* Handle extra flags for this index, if not NULL */
  98941. ){
  98942. char *z = zIntArray;
  98943. int c;
  98944. int i;
  98945. tRowcnt v;
  98946. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98947. if( z==0 ) z = "";
  98948. #else
  98949. assert( z!=0 );
  98950. #endif
  98951. for(i=0; *z && i<nOut; i++){
  98952. v = 0;
  98953. while( (c=z[0])>='0' && c<='9' ){
  98954. v = v*10 + c - '0';
  98955. z++;
  98956. }
  98957. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  98958. if( aOut ) aOut[i] = v;
  98959. if( aLog ) aLog[i] = sqlite3LogEst(v);
  98960. #else
  98961. assert( aOut==0 );
  98962. UNUSED_PARAMETER(aOut);
  98963. assert( aLog!=0 );
  98964. aLog[i] = sqlite3LogEst(v);
  98965. #endif
  98966. if( *z==' ' ) z++;
  98967. }
  98968. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  98969. assert( pIndex!=0 ); {
  98970. #else
  98971. if( pIndex ){
  98972. #endif
  98973. pIndex->bUnordered = 0;
  98974. pIndex->noSkipScan = 0;
  98975. while( z[0] ){
  98976. if( sqlite3_strglob("unordered*", z)==0 ){
  98977. pIndex->bUnordered = 1;
  98978. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  98979. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  98980. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  98981. pIndex->noSkipScan = 1;
  98982. }
  98983. #ifdef SQLITE_ENABLE_COSTMULT
  98984. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  98985. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  98986. }
  98987. #endif
  98988. while( z[0]!=0 && z[0]!=' ' ) z++;
  98989. while( z[0]==' ' ) z++;
  98990. }
  98991. }
  98992. }
  98993. /*
  98994. ** This callback is invoked once for each index when reading the
  98995. ** sqlite_stat1 table.
  98996. **
  98997. ** argv[0] = name of the table
  98998. ** argv[1] = name of the index (might be NULL)
  98999. ** argv[2] = results of analysis - on integer for each column
  99000. **
  99001. ** Entries for which argv[1]==NULL simply record the number of rows in
  99002. ** the table.
  99003. */
  99004. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  99005. analysisInfo *pInfo = (analysisInfo*)pData;
  99006. Index *pIndex;
  99007. Table *pTable;
  99008. const char *z;
  99009. assert( argc==3 );
  99010. UNUSED_PARAMETER2(NotUsed, argc);
  99011. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  99012. return 0;
  99013. }
  99014. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  99015. if( pTable==0 ){
  99016. return 0;
  99017. }
  99018. if( argv[1]==0 ){
  99019. pIndex = 0;
  99020. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  99021. pIndex = sqlite3PrimaryKeyIndex(pTable);
  99022. }else{
  99023. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  99024. }
  99025. z = argv[2];
  99026. if( pIndex ){
  99027. tRowcnt *aiRowEst = 0;
  99028. int nCol = pIndex->nKeyCol+1;
  99029. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99030. /* Index.aiRowEst may already be set here if there are duplicate
  99031. ** sqlite_stat1 entries for this index. In that case just clobber
  99032. ** the old data with the new instead of allocating a new array. */
  99033. if( pIndex->aiRowEst==0 ){
  99034. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  99035. if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
  99036. }
  99037. aiRowEst = pIndex->aiRowEst;
  99038. #endif
  99039. pIndex->bUnordered = 0;
  99040. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  99041. pIndex->hasStat1 = 1;
  99042. if( pIndex->pPartIdxWhere==0 ){
  99043. pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  99044. pTable->tabFlags |= TF_HasStat1;
  99045. }
  99046. }else{
  99047. Index fakeIdx;
  99048. fakeIdx.szIdxRow = pTable->szTabRow;
  99049. #ifdef SQLITE_ENABLE_COSTMULT
  99050. fakeIdx.pTable = pTable;
  99051. #endif
  99052. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  99053. pTable->szTabRow = fakeIdx.szIdxRow;
  99054. pTable->tabFlags |= TF_HasStat1;
  99055. }
  99056. return 0;
  99057. }
  99058. /*
  99059. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  99060. ** and its contents.
  99061. */
  99062. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  99063. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99064. if( pIdx->aSample ){
  99065. int j;
  99066. for(j=0; j<pIdx->nSample; j++){
  99067. IndexSample *p = &pIdx->aSample[j];
  99068. sqlite3DbFree(db, p->p);
  99069. }
  99070. sqlite3DbFree(db, pIdx->aSample);
  99071. }
  99072. if( db && db->pnBytesFreed==0 ){
  99073. pIdx->nSample = 0;
  99074. pIdx->aSample = 0;
  99075. }
  99076. #else
  99077. UNUSED_PARAMETER(db);
  99078. UNUSED_PARAMETER(pIdx);
  99079. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  99080. }
  99081. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99082. /*
  99083. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  99084. ** stored in pIdx->aSample[].
  99085. */
  99086. static void initAvgEq(Index *pIdx){
  99087. if( pIdx ){
  99088. IndexSample *aSample = pIdx->aSample;
  99089. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  99090. int iCol;
  99091. int nCol = 1;
  99092. if( pIdx->nSampleCol>1 ){
  99093. /* If this is stat4 data, then calculate aAvgEq[] values for all
  99094. ** sample columns except the last. The last is always set to 1, as
  99095. ** once the trailing PK fields are considered all index keys are
  99096. ** unique. */
  99097. nCol = pIdx->nSampleCol-1;
  99098. pIdx->aAvgEq[nCol] = 1;
  99099. }
  99100. for(iCol=0; iCol<nCol; iCol++){
  99101. int nSample = pIdx->nSample;
  99102. int i; /* Used to iterate through samples */
  99103. tRowcnt sumEq = 0; /* Sum of the nEq values */
  99104. tRowcnt avgEq = 0;
  99105. tRowcnt nRow; /* Number of rows in index */
  99106. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  99107. i64 nDist100; /* Number of distinct values in index */
  99108. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  99109. nRow = pFinal->anLt[iCol];
  99110. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  99111. nSample--;
  99112. }else{
  99113. nRow = pIdx->aiRowEst[0];
  99114. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  99115. }
  99116. pIdx->nRowEst0 = nRow;
  99117. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  99118. ** occur in the stat4 table for this index. Set sumEq to the sum of
  99119. ** the nEq values for column iCol for the same set (adding the value
  99120. ** only once where there exist duplicate prefixes). */
  99121. for(i=0; i<nSample; i++){
  99122. if( i==(pIdx->nSample-1)
  99123. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  99124. ){
  99125. sumEq += aSample[i].anEq[iCol];
  99126. nSum100 += 100;
  99127. }
  99128. }
  99129. if( nDist100>nSum100 && sumEq<nRow ){
  99130. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  99131. }
  99132. if( avgEq==0 ) avgEq = 1;
  99133. pIdx->aAvgEq[iCol] = avgEq;
  99134. }
  99135. }
  99136. }
  99137. /*
  99138. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  99139. ** is supplied instead, find the PRIMARY KEY index for that table.
  99140. */
  99141. static Index *findIndexOrPrimaryKey(
  99142. sqlite3 *db,
  99143. const char *zName,
  99144. const char *zDb
  99145. ){
  99146. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  99147. if( pIdx==0 ){
  99148. Table *pTab = sqlite3FindTable(db, zName, zDb);
  99149. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  99150. }
  99151. return pIdx;
  99152. }
  99153. /*
  99154. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  99155. ** into the relevant Index.aSample[] arrays.
  99156. **
  99157. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  99158. ** data equivalent to the following (statements are different for stat3,
  99159. ** see the caller of this function for details):
  99160. **
  99161. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  99162. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  99163. **
  99164. ** where %Q is replaced with the database name before the SQL is executed.
  99165. */
  99166. static int loadStatTbl(
  99167. sqlite3 *db, /* Database handle */
  99168. int bStat3, /* Assume single column records only */
  99169. const char *zSql1, /* SQL statement 1 (see above) */
  99170. const char *zSql2, /* SQL statement 2 (see above) */
  99171. const char *zDb /* Database name (e.g. "main") */
  99172. ){
  99173. int rc; /* Result codes from subroutines */
  99174. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  99175. char *zSql; /* Text of the SQL statement */
  99176. Index *pPrevIdx = 0; /* Previous index in the loop */
  99177. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  99178. assert( db->lookaside.bDisable );
  99179. zSql = sqlite3MPrintf(db, zSql1, zDb);
  99180. if( !zSql ){
  99181. return SQLITE_NOMEM_BKPT;
  99182. }
  99183. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  99184. sqlite3DbFree(db, zSql);
  99185. if( rc ) return rc;
  99186. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  99187. int nIdxCol = 1; /* Number of columns in stat4 records */
  99188. char *zIndex; /* Index name */
  99189. Index *pIdx; /* Pointer to the index object */
  99190. int nSample; /* Number of samples */
  99191. int nByte; /* Bytes of space required */
  99192. int i; /* Bytes of space required */
  99193. tRowcnt *pSpace;
  99194. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  99195. if( zIndex==0 ) continue;
  99196. nSample = sqlite3_column_int(pStmt, 1);
  99197. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  99198. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  99199. /* Index.nSample is non-zero at this point if data has already been
  99200. ** loaded from the stat4 table. In this case ignore stat3 data. */
  99201. if( pIdx==0 || pIdx->nSample ) continue;
  99202. if( bStat3==0 ){
  99203. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  99204. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  99205. nIdxCol = pIdx->nKeyCol;
  99206. }else{
  99207. nIdxCol = pIdx->nColumn;
  99208. }
  99209. }
  99210. pIdx->nSampleCol = nIdxCol;
  99211. nByte = sizeof(IndexSample) * nSample;
  99212. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  99213. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  99214. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  99215. if( pIdx->aSample==0 ){
  99216. sqlite3_finalize(pStmt);
  99217. return SQLITE_NOMEM_BKPT;
  99218. }
  99219. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  99220. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  99221. for(i=0; i<nSample; i++){
  99222. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  99223. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  99224. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  99225. }
  99226. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  99227. }
  99228. rc = sqlite3_finalize(pStmt);
  99229. if( rc ) return rc;
  99230. zSql = sqlite3MPrintf(db, zSql2, zDb);
  99231. if( !zSql ){
  99232. return SQLITE_NOMEM_BKPT;
  99233. }
  99234. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  99235. sqlite3DbFree(db, zSql);
  99236. if( rc ) return rc;
  99237. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  99238. char *zIndex; /* Index name */
  99239. Index *pIdx; /* Pointer to the index object */
  99240. int nCol = 1; /* Number of columns in index */
  99241. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  99242. if( zIndex==0 ) continue;
  99243. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  99244. if( pIdx==0 ) continue;
  99245. /* This next condition is true if data has already been loaded from
  99246. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  99247. nCol = pIdx->nSampleCol;
  99248. if( bStat3 && nCol>1 ) continue;
  99249. if( pIdx!=pPrevIdx ){
  99250. initAvgEq(pPrevIdx);
  99251. pPrevIdx = pIdx;
  99252. }
  99253. pSample = &pIdx->aSample[pIdx->nSample];
  99254. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  99255. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  99256. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  99257. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  99258. ** This is in case the sample record is corrupted. In that case, the
  99259. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  99260. ** end of the allocated buffer before it realizes it is dealing with
  99261. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  99262. ** a buffer overread. */
  99263. pSample->n = sqlite3_column_bytes(pStmt, 4);
  99264. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  99265. if( pSample->p==0 ){
  99266. sqlite3_finalize(pStmt);
  99267. return SQLITE_NOMEM_BKPT;
  99268. }
  99269. if( pSample->n ){
  99270. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  99271. }
  99272. pIdx->nSample++;
  99273. }
  99274. rc = sqlite3_finalize(pStmt);
  99275. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  99276. return rc;
  99277. }
  99278. /*
  99279. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  99280. ** the Index.aSample[] arrays of all indices.
  99281. */
  99282. static int loadStat4(sqlite3 *db, const char *zDb){
  99283. int rc = SQLITE_OK; /* Result codes from subroutines */
  99284. assert( db->lookaside.bDisable );
  99285. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  99286. rc = loadStatTbl(db, 0,
  99287. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  99288. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  99289. zDb
  99290. );
  99291. }
  99292. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  99293. rc = loadStatTbl(db, 1,
  99294. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  99295. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  99296. zDb
  99297. );
  99298. }
  99299. return rc;
  99300. }
  99301. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  99302. /*
  99303. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  99304. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  99305. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  99306. ** Index.aSample[] arrays.
  99307. **
  99308. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  99309. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  99310. ** during compilation and the sqlite_stat3/4 table is present, no data is
  99311. ** read from it.
  99312. **
  99313. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  99314. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  99315. ** returned. However, in this case, data is read from the sqlite_stat1
  99316. ** table (if it is present) before returning.
  99317. **
  99318. ** If an OOM error occurs, this function always sets db->mallocFailed.
  99319. ** This means if the caller does not care about other errors, the return
  99320. ** code may be ignored.
  99321. */
  99322. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  99323. analysisInfo sInfo;
  99324. HashElem *i;
  99325. char *zSql;
  99326. int rc = SQLITE_OK;
  99327. Schema *pSchema = db->aDb[iDb].pSchema;
  99328. assert( iDb>=0 && iDb<db->nDb );
  99329. assert( db->aDb[iDb].pBt!=0 );
  99330. /* Clear any prior statistics */
  99331. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99332. for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
  99333. Table *pTab = sqliteHashData(i);
  99334. pTab->tabFlags &= ~TF_HasStat1;
  99335. }
  99336. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  99337. Index *pIdx = sqliteHashData(i);
  99338. pIdx->hasStat1 = 0;
  99339. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99340. sqlite3DeleteIndexSamples(db, pIdx);
  99341. pIdx->aSample = 0;
  99342. #endif
  99343. }
  99344. /* Load new statistics out of the sqlite_stat1 table */
  99345. sInfo.db = db;
  99346. sInfo.zDatabase = db->aDb[iDb].zDbSName;
  99347. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
  99348. zSql = sqlite3MPrintf(db,
  99349. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  99350. if( zSql==0 ){
  99351. rc = SQLITE_NOMEM_BKPT;
  99352. }else{
  99353. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  99354. sqlite3DbFree(db, zSql);
  99355. }
  99356. }
  99357. /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
  99358. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99359. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  99360. Index *pIdx = sqliteHashData(i);
  99361. if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
  99362. }
  99363. /* Load the statistics from the sqlite_stat4 table. */
  99364. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  99365. if( rc==SQLITE_OK ){
  99366. db->lookaside.bDisable++;
  99367. rc = loadStat4(db, sInfo.zDatabase);
  99368. db->lookaside.bDisable--;
  99369. }
  99370. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  99371. Index *pIdx = sqliteHashData(i);
  99372. sqlite3_free(pIdx->aiRowEst);
  99373. pIdx->aiRowEst = 0;
  99374. }
  99375. #endif
  99376. if( rc==SQLITE_NOMEM ){
  99377. sqlite3OomFault(db);
  99378. }
  99379. return rc;
  99380. }
  99381. #endif /* SQLITE_OMIT_ANALYZE */
  99382. /************** End of analyze.c *********************************************/
  99383. /************** Begin file attach.c ******************************************/
  99384. /*
  99385. ** 2003 April 6
  99386. **
  99387. ** The author disclaims copyright to this source code. In place of
  99388. ** a legal notice, here is a blessing:
  99389. **
  99390. ** May you do good and not evil.
  99391. ** May you find forgiveness for yourself and forgive others.
  99392. ** May you share freely, never taking more than you give.
  99393. **
  99394. *************************************************************************
  99395. ** This file contains code used to implement the ATTACH and DETACH commands.
  99396. */
  99397. /* #include "sqliteInt.h" */
  99398. #ifndef SQLITE_OMIT_ATTACH
  99399. /*
  99400. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  99401. ** is slightly different from resolving a normal SQL expression, because simple
  99402. ** identifiers are treated as strings, not possible column names or aliases.
  99403. **
  99404. ** i.e. if the parser sees:
  99405. **
  99406. ** ATTACH DATABASE abc AS def
  99407. **
  99408. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  99409. ** looking for columns of the same name.
  99410. **
  99411. ** This only applies to the root node of pExpr, so the statement:
  99412. **
  99413. ** ATTACH DATABASE abc||def AS 'db2'
  99414. **
  99415. ** will fail because neither abc or def can be resolved.
  99416. */
  99417. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  99418. {
  99419. int rc = SQLITE_OK;
  99420. if( pExpr ){
  99421. if( pExpr->op!=TK_ID ){
  99422. rc = sqlite3ResolveExprNames(pName, pExpr);
  99423. }else{
  99424. pExpr->op = TK_STRING;
  99425. }
  99426. }
  99427. return rc;
  99428. }
  99429. /*
  99430. ** An SQL user-function registered to do the work of an ATTACH statement. The
  99431. ** three arguments to the function come directly from an attach statement:
  99432. **
  99433. ** ATTACH DATABASE x AS y KEY z
  99434. **
  99435. ** SELECT sqlite_attach(x, y, z)
  99436. **
  99437. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  99438. ** third argument.
  99439. **
  99440. ** If the db->init.reopenMemdb flags is set, then instead of attaching a
  99441. ** new database, close the database on db->init.iDb and reopen it as an
  99442. ** empty MemDB.
  99443. */
  99444. static void attachFunc(
  99445. sqlite3_context *context,
  99446. int NotUsed,
  99447. sqlite3_value **argv
  99448. ){
  99449. int i;
  99450. int rc = 0;
  99451. sqlite3 *db = sqlite3_context_db_handle(context);
  99452. const char *zName;
  99453. const char *zFile;
  99454. char *zPath = 0;
  99455. char *zErr = 0;
  99456. unsigned int flags;
  99457. Db *aNew; /* New array of Db pointers */
  99458. Db *pNew; /* Db object for the newly attached database */
  99459. char *zErrDyn = 0;
  99460. sqlite3_vfs *pVfs;
  99461. UNUSED_PARAMETER(NotUsed);
  99462. zFile = (const char *)sqlite3_value_text(argv[0]);
  99463. zName = (const char *)sqlite3_value_text(argv[1]);
  99464. if( zFile==0 ) zFile = "";
  99465. if( zName==0 ) zName = "";
  99466. #ifdef SQLITE_ENABLE_DESERIALIZE
  99467. # define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb)
  99468. #else
  99469. # define REOPEN_AS_MEMDB(db) (0)
  99470. #endif
  99471. if( REOPEN_AS_MEMDB(db) ){
  99472. /* This is not a real ATTACH. Instead, this routine is being called
  99473. ** from sqlite3_deserialize() to close database db->init.iDb and
  99474. ** reopen it as a MemDB */
  99475. pVfs = sqlite3_vfs_find("memdb");
  99476. if( pVfs==0 ) return;
  99477. pNew = &db->aDb[db->init.iDb];
  99478. if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
  99479. pNew->pBt = 0;
  99480. pNew->pSchema = 0;
  99481. rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
  99482. }else{
  99483. /* This is a real ATTACH
  99484. **
  99485. ** Check for the following errors:
  99486. **
  99487. ** * Too many attached databases,
  99488. ** * Transaction currently open
  99489. ** * Specified database name already being used.
  99490. */
  99491. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  99492. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  99493. db->aLimit[SQLITE_LIMIT_ATTACHED]
  99494. );
  99495. goto attach_error;
  99496. }
  99497. for(i=0; i<db->nDb; i++){
  99498. char *z = db->aDb[i].zDbSName;
  99499. assert( z && zName );
  99500. if( sqlite3StrICmp(z, zName)==0 ){
  99501. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  99502. goto attach_error;
  99503. }
  99504. }
  99505. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  99506. ** hash tables.
  99507. */
  99508. if( db->aDb==db->aDbStatic ){
  99509. aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
  99510. if( aNew==0 ) return;
  99511. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  99512. }else{
  99513. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  99514. if( aNew==0 ) return;
  99515. }
  99516. db->aDb = aNew;
  99517. pNew = &db->aDb[db->nDb];
  99518. memset(pNew, 0, sizeof(*pNew));
  99519. /* Open the database file. If the btree is successfully opened, use
  99520. ** it to obtain the database schema. At this point the schema may
  99521. ** or may not be initialized.
  99522. */
  99523. flags = db->openFlags;
  99524. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  99525. if( rc!=SQLITE_OK ){
  99526. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  99527. sqlite3_result_error(context, zErr, -1);
  99528. sqlite3_free(zErr);
  99529. return;
  99530. }
  99531. assert( pVfs );
  99532. flags |= SQLITE_OPEN_MAIN_DB;
  99533. rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
  99534. db->nDb++;
  99535. pNew->zDbSName = sqlite3DbStrDup(db, zName);
  99536. }
  99537. db->noSharedCache = 0;
  99538. if( rc==SQLITE_CONSTRAINT ){
  99539. rc = SQLITE_ERROR;
  99540. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  99541. }else if( rc==SQLITE_OK ){
  99542. Pager *pPager;
  99543. pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
  99544. if( !pNew->pSchema ){
  99545. rc = SQLITE_NOMEM_BKPT;
  99546. }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
  99547. zErrDyn = sqlite3MPrintf(db,
  99548. "attached databases must use the same text encoding as main database");
  99549. rc = SQLITE_ERROR;
  99550. }
  99551. sqlite3BtreeEnter(pNew->pBt);
  99552. pPager = sqlite3BtreePager(pNew->pBt);
  99553. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  99554. sqlite3BtreeSecureDelete(pNew->pBt,
  99555. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  99556. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  99557. sqlite3BtreeSetPagerFlags(pNew->pBt,
  99558. PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
  99559. #endif
  99560. sqlite3BtreeLeave(pNew->pBt);
  99561. }
  99562. pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  99563. if( rc==SQLITE_OK && pNew->zDbSName==0 ){
  99564. rc = SQLITE_NOMEM_BKPT;
  99565. }
  99566. #ifdef SQLITE_HAS_CODEC
  99567. if( rc==SQLITE_OK ){
  99568. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  99569. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  99570. int nKey;
  99571. char *zKey;
  99572. int t = sqlite3_value_type(argv[2]);
  99573. switch( t ){
  99574. case SQLITE_INTEGER:
  99575. case SQLITE_FLOAT:
  99576. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  99577. rc = SQLITE_ERROR;
  99578. break;
  99579. case SQLITE_TEXT:
  99580. case SQLITE_BLOB:
  99581. nKey = sqlite3_value_bytes(argv[2]);
  99582. zKey = (char *)sqlite3_value_blob(argv[2]);
  99583. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  99584. break;
  99585. case SQLITE_NULL:
  99586. /* No key specified. Use the key from URI filename, or if none,
  99587. ** use the key from the main database. */
  99588. if( sqlite3CodecQueryParameters(db, zName, zPath)==0 ){
  99589. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  99590. if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  99591. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  99592. }
  99593. }
  99594. break;
  99595. }
  99596. }
  99597. #endif
  99598. sqlite3_free( zPath );
  99599. /* If the file was opened successfully, read the schema for the new database.
  99600. ** If this fails, or if opening the file failed, then close the file and
  99601. ** remove the entry from the db->aDb[] array. i.e. put everything back the
  99602. ** way we found it.
  99603. */
  99604. if( rc==SQLITE_OK ){
  99605. sqlite3BtreeEnterAll(db);
  99606. db->init.iDb = 0;
  99607. db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
  99608. if( !REOPEN_AS_MEMDB(db) ){
  99609. rc = sqlite3Init(db, &zErrDyn);
  99610. }
  99611. sqlite3BtreeLeaveAll(db);
  99612. assert( zErrDyn==0 || rc!=SQLITE_OK );
  99613. }
  99614. #ifdef SQLITE_USER_AUTHENTICATION
  99615. if( rc==SQLITE_OK && !REOPEN_AS_MEMDB(db) ){
  99616. u8 newAuth = 0;
  99617. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  99618. if( newAuth<db->auth.authLevel ){
  99619. rc = SQLITE_AUTH_USER;
  99620. }
  99621. }
  99622. #endif
  99623. if( rc ){
  99624. if( !REOPEN_AS_MEMDB(db) ){
  99625. int iDb = db->nDb - 1;
  99626. assert( iDb>=2 );
  99627. if( db->aDb[iDb].pBt ){
  99628. sqlite3BtreeClose(db->aDb[iDb].pBt);
  99629. db->aDb[iDb].pBt = 0;
  99630. db->aDb[iDb].pSchema = 0;
  99631. }
  99632. sqlite3ResetAllSchemasOfConnection(db);
  99633. db->nDb = iDb;
  99634. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  99635. sqlite3OomFault(db);
  99636. sqlite3DbFree(db, zErrDyn);
  99637. zErrDyn = sqlite3MPrintf(db, "out of memory");
  99638. }else if( zErrDyn==0 ){
  99639. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  99640. }
  99641. }
  99642. goto attach_error;
  99643. }
  99644. return;
  99645. attach_error:
  99646. /* Return an error if we get here */
  99647. if( zErrDyn ){
  99648. sqlite3_result_error(context, zErrDyn, -1);
  99649. sqlite3DbFree(db, zErrDyn);
  99650. }
  99651. if( rc ) sqlite3_result_error_code(context, rc);
  99652. }
  99653. /*
  99654. ** An SQL user-function registered to do the work of an DETACH statement. The
  99655. ** three arguments to the function come directly from a detach statement:
  99656. **
  99657. ** DETACH DATABASE x
  99658. **
  99659. ** SELECT sqlite_detach(x)
  99660. */
  99661. static void detachFunc(
  99662. sqlite3_context *context,
  99663. int NotUsed,
  99664. sqlite3_value **argv
  99665. ){
  99666. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  99667. sqlite3 *db = sqlite3_context_db_handle(context);
  99668. int i;
  99669. Db *pDb = 0;
  99670. char zErr[128];
  99671. UNUSED_PARAMETER(NotUsed);
  99672. if( zName==0 ) zName = "";
  99673. for(i=0; i<db->nDb; i++){
  99674. pDb = &db->aDb[i];
  99675. if( pDb->pBt==0 ) continue;
  99676. if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
  99677. }
  99678. if( i>=db->nDb ){
  99679. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  99680. goto detach_error;
  99681. }
  99682. if( i<2 ){
  99683. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  99684. goto detach_error;
  99685. }
  99686. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  99687. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  99688. goto detach_error;
  99689. }
  99690. sqlite3BtreeClose(pDb->pBt);
  99691. pDb->pBt = 0;
  99692. pDb->pSchema = 0;
  99693. sqlite3CollapseDatabaseArray(db);
  99694. return;
  99695. detach_error:
  99696. sqlite3_result_error(context, zErr, -1);
  99697. }
  99698. /*
  99699. ** This procedure generates VDBE code for a single invocation of either the
  99700. ** sqlite_detach() or sqlite_attach() SQL user functions.
  99701. */
  99702. static void codeAttach(
  99703. Parse *pParse, /* The parser context */
  99704. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  99705. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  99706. Expr *pAuthArg, /* Expression to pass to authorization callback */
  99707. Expr *pFilename, /* Name of database file */
  99708. Expr *pDbname, /* Name of the database to use internally */
  99709. Expr *pKey /* Database key for encryption extension */
  99710. ){
  99711. int rc;
  99712. NameContext sName;
  99713. Vdbe *v;
  99714. sqlite3* db = pParse->db;
  99715. int regArgs;
  99716. if( pParse->nErr ) goto attach_end;
  99717. memset(&sName, 0, sizeof(NameContext));
  99718. sName.pParse = pParse;
  99719. if(
  99720. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  99721. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  99722. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  99723. ){
  99724. goto attach_end;
  99725. }
  99726. #ifndef SQLITE_OMIT_AUTHORIZATION
  99727. if( pAuthArg ){
  99728. char *zAuthArg;
  99729. if( pAuthArg->op==TK_STRING ){
  99730. zAuthArg = pAuthArg->u.zToken;
  99731. }else{
  99732. zAuthArg = 0;
  99733. }
  99734. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  99735. if(rc!=SQLITE_OK ){
  99736. goto attach_end;
  99737. }
  99738. }
  99739. #endif /* SQLITE_OMIT_AUTHORIZATION */
  99740. v = sqlite3GetVdbe(pParse);
  99741. regArgs = sqlite3GetTempRange(pParse, 4);
  99742. sqlite3ExprCode(pParse, pFilename, regArgs);
  99743. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  99744. sqlite3ExprCode(pParse, pKey, regArgs+2);
  99745. assert( v || db->mallocFailed );
  99746. if( v ){
  99747. sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
  99748. (char *)pFunc, P4_FUNCDEF);
  99749. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  99750. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  99751. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  99752. ** statement only). For DETACH, set it to false (expire all existing
  99753. ** statements).
  99754. */
  99755. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  99756. }
  99757. attach_end:
  99758. sqlite3ExprDelete(db, pFilename);
  99759. sqlite3ExprDelete(db, pDbname);
  99760. sqlite3ExprDelete(db, pKey);
  99761. }
  99762. /*
  99763. ** Called by the parser to compile a DETACH statement.
  99764. **
  99765. ** DETACH pDbname
  99766. */
  99767. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  99768. static const FuncDef detach_func = {
  99769. 1, /* nArg */
  99770. SQLITE_UTF8, /* funcFlags */
  99771. 0, /* pUserData */
  99772. 0, /* pNext */
  99773. detachFunc, /* xSFunc */
  99774. 0, /* xFinalize */
  99775. 0, 0, /* xValue, xInverse */
  99776. "sqlite_detach", /* zName */
  99777. {0}
  99778. };
  99779. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  99780. }
  99781. /*
  99782. ** Called by the parser to compile an ATTACH statement.
  99783. **
  99784. ** ATTACH p AS pDbname KEY pKey
  99785. */
  99786. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  99787. static const FuncDef attach_func = {
  99788. 3, /* nArg */
  99789. SQLITE_UTF8, /* funcFlags */
  99790. 0, /* pUserData */
  99791. 0, /* pNext */
  99792. attachFunc, /* xSFunc */
  99793. 0, /* xFinalize */
  99794. 0, 0, /* xValue, xInverse */
  99795. "sqlite_attach", /* zName */
  99796. {0}
  99797. };
  99798. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  99799. }
  99800. #endif /* SQLITE_OMIT_ATTACH */
  99801. /*
  99802. ** Initialize a DbFixer structure. This routine must be called prior
  99803. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  99804. */
  99805. SQLITE_PRIVATE void sqlite3FixInit(
  99806. DbFixer *pFix, /* The fixer to be initialized */
  99807. Parse *pParse, /* Error messages will be written here */
  99808. int iDb, /* This is the database that must be used */
  99809. const char *zType, /* "view", "trigger", or "index" */
  99810. const Token *pName /* Name of the view, trigger, or index */
  99811. ){
  99812. sqlite3 *db;
  99813. db = pParse->db;
  99814. assert( db->nDb>iDb );
  99815. pFix->pParse = pParse;
  99816. pFix->zDb = db->aDb[iDb].zDbSName;
  99817. pFix->pSchema = db->aDb[iDb].pSchema;
  99818. pFix->zType = zType;
  99819. pFix->pName = pName;
  99820. pFix->bVarOnly = (iDb==1);
  99821. }
  99822. /*
  99823. ** The following set of routines walk through the parse tree and assign
  99824. ** a specific database to all table references where the database name
  99825. ** was left unspecified in the original SQL statement. The pFix structure
  99826. ** must have been initialized by a prior call to sqlite3FixInit().
  99827. **
  99828. ** These routines are used to make sure that an index, trigger, or
  99829. ** view in one database does not refer to objects in a different database.
  99830. ** (Exception: indices, triggers, and views in the TEMP database are
  99831. ** allowed to refer to anything.) If a reference is explicitly made
  99832. ** to an object in a different database, an error message is added to
  99833. ** pParse->zErrMsg and these routines return non-zero. If everything
  99834. ** checks out, these routines return 0.
  99835. */
  99836. SQLITE_PRIVATE int sqlite3FixSrcList(
  99837. DbFixer *pFix, /* Context of the fixation */
  99838. SrcList *pList /* The Source list to check and modify */
  99839. ){
  99840. int i;
  99841. const char *zDb;
  99842. struct SrcList_item *pItem;
  99843. if( NEVER(pList==0) ) return 0;
  99844. zDb = pFix->zDb;
  99845. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  99846. if( pFix->bVarOnly==0 ){
  99847. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  99848. sqlite3ErrorMsg(pFix->pParse,
  99849. "%s %T cannot reference objects in database %s",
  99850. pFix->zType, pFix->pName, pItem->zDatabase);
  99851. return 1;
  99852. }
  99853. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  99854. pItem->zDatabase = 0;
  99855. pItem->pSchema = pFix->pSchema;
  99856. }
  99857. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  99858. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  99859. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  99860. #endif
  99861. if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){
  99862. return 1;
  99863. }
  99864. }
  99865. return 0;
  99866. }
  99867. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  99868. SQLITE_PRIVATE int sqlite3FixSelect(
  99869. DbFixer *pFix, /* Context of the fixation */
  99870. Select *pSelect /* The SELECT statement to be fixed to one database */
  99871. ){
  99872. while( pSelect ){
  99873. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  99874. return 1;
  99875. }
  99876. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  99877. return 1;
  99878. }
  99879. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  99880. return 1;
  99881. }
  99882. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  99883. return 1;
  99884. }
  99885. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  99886. return 1;
  99887. }
  99888. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  99889. return 1;
  99890. }
  99891. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  99892. return 1;
  99893. }
  99894. if( pSelect->pWith ){
  99895. int i;
  99896. for(i=0; i<pSelect->pWith->nCte; i++){
  99897. if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
  99898. return 1;
  99899. }
  99900. }
  99901. }
  99902. pSelect = pSelect->pPrior;
  99903. }
  99904. return 0;
  99905. }
  99906. SQLITE_PRIVATE int sqlite3FixExpr(
  99907. DbFixer *pFix, /* Context of the fixation */
  99908. Expr *pExpr /* The expression to be fixed to one database */
  99909. ){
  99910. while( pExpr ){
  99911. if( pExpr->op==TK_VARIABLE ){
  99912. if( pFix->pParse->db->init.busy ){
  99913. pExpr->op = TK_NULL;
  99914. }else{
  99915. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  99916. return 1;
  99917. }
  99918. }
  99919. if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
  99920. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  99921. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  99922. }else{
  99923. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  99924. }
  99925. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  99926. return 1;
  99927. }
  99928. pExpr = pExpr->pLeft;
  99929. }
  99930. return 0;
  99931. }
  99932. SQLITE_PRIVATE int sqlite3FixExprList(
  99933. DbFixer *pFix, /* Context of the fixation */
  99934. ExprList *pList /* The expression to be fixed to one database */
  99935. ){
  99936. int i;
  99937. struct ExprList_item *pItem;
  99938. if( pList==0 ) return 0;
  99939. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  99940. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  99941. return 1;
  99942. }
  99943. }
  99944. return 0;
  99945. }
  99946. #endif
  99947. #ifndef SQLITE_OMIT_TRIGGER
  99948. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  99949. DbFixer *pFix, /* Context of the fixation */
  99950. TriggerStep *pStep /* The trigger step be fixed to one database */
  99951. ){
  99952. while( pStep ){
  99953. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  99954. return 1;
  99955. }
  99956. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  99957. return 1;
  99958. }
  99959. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  99960. return 1;
  99961. }
  99962. #ifndef SQLITE_OMIT_UPSERT
  99963. if( pStep->pUpsert ){
  99964. Upsert *pUp = pStep->pUpsert;
  99965. if( sqlite3FixExprList(pFix, pUp->pUpsertTarget)
  99966. || sqlite3FixExpr(pFix, pUp->pUpsertTargetWhere)
  99967. || sqlite3FixExprList(pFix, pUp->pUpsertSet)
  99968. || sqlite3FixExpr(pFix, pUp->pUpsertWhere)
  99969. ){
  99970. return 1;
  99971. }
  99972. }
  99973. #endif
  99974. pStep = pStep->pNext;
  99975. }
  99976. return 0;
  99977. }
  99978. #endif
  99979. /************** End of attach.c **********************************************/
  99980. /************** Begin file auth.c ********************************************/
  99981. /*
  99982. ** 2003 January 11
  99983. **
  99984. ** The author disclaims copyright to this source code. In place of
  99985. ** a legal notice, here is a blessing:
  99986. **
  99987. ** May you do good and not evil.
  99988. ** May you find forgiveness for yourself and forgive others.
  99989. ** May you share freely, never taking more than you give.
  99990. **
  99991. *************************************************************************
  99992. ** This file contains code used to implement the sqlite3_set_authorizer()
  99993. ** API. This facility is an optional feature of the library. Embedded
  99994. ** systems that do not need this facility may omit it by recompiling
  99995. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  99996. */
  99997. /* #include "sqliteInt.h" */
  99998. /*
  99999. ** All of the code in this file may be omitted by defining a single
  100000. ** macro.
  100001. */
  100002. #ifndef SQLITE_OMIT_AUTHORIZATION
  100003. /*
  100004. ** Set or clear the access authorization function.
  100005. **
  100006. ** The access authorization function is be called during the compilation
  100007. ** phase to verify that the user has read and/or write access permission on
  100008. ** various fields of the database. The first argument to the auth function
  100009. ** is a copy of the 3rd argument to this routine. The second argument
  100010. ** to the auth function is one of these constants:
  100011. **
  100012. ** SQLITE_CREATE_INDEX
  100013. ** SQLITE_CREATE_TABLE
  100014. ** SQLITE_CREATE_TEMP_INDEX
  100015. ** SQLITE_CREATE_TEMP_TABLE
  100016. ** SQLITE_CREATE_TEMP_TRIGGER
  100017. ** SQLITE_CREATE_TEMP_VIEW
  100018. ** SQLITE_CREATE_TRIGGER
  100019. ** SQLITE_CREATE_VIEW
  100020. ** SQLITE_DELETE
  100021. ** SQLITE_DROP_INDEX
  100022. ** SQLITE_DROP_TABLE
  100023. ** SQLITE_DROP_TEMP_INDEX
  100024. ** SQLITE_DROP_TEMP_TABLE
  100025. ** SQLITE_DROP_TEMP_TRIGGER
  100026. ** SQLITE_DROP_TEMP_VIEW
  100027. ** SQLITE_DROP_TRIGGER
  100028. ** SQLITE_DROP_VIEW
  100029. ** SQLITE_INSERT
  100030. ** SQLITE_PRAGMA
  100031. ** SQLITE_READ
  100032. ** SQLITE_SELECT
  100033. ** SQLITE_TRANSACTION
  100034. ** SQLITE_UPDATE
  100035. **
  100036. ** The third and fourth arguments to the auth function are the name of
  100037. ** the table and the column that are being accessed. The auth function
  100038. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  100039. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  100040. ** means that the SQL statement will never-run - the sqlite3_exec() call
  100041. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  100042. ** should run but attempts to read the specified column will return NULL
  100043. ** and attempts to write the column will be ignored.
  100044. **
  100045. ** Setting the auth function to NULL disables this hook. The default
  100046. ** setting of the auth function is NULL.
  100047. */
  100048. SQLITE_API int sqlite3_set_authorizer(
  100049. sqlite3 *db,
  100050. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  100051. void *pArg
  100052. ){
  100053. #ifdef SQLITE_ENABLE_API_ARMOR
  100054. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  100055. #endif
  100056. sqlite3_mutex_enter(db->mutex);
  100057. db->xAuth = (sqlite3_xauth)xAuth;
  100058. db->pAuthArg = pArg;
  100059. sqlite3ExpirePreparedStatements(db, 0);
  100060. sqlite3_mutex_leave(db->mutex);
  100061. return SQLITE_OK;
  100062. }
  100063. /*
  100064. ** Write an error message into pParse->zErrMsg that explains that the
  100065. ** user-supplied authorization function returned an illegal value.
  100066. */
  100067. static void sqliteAuthBadReturnCode(Parse *pParse){
  100068. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  100069. pParse->rc = SQLITE_ERROR;
  100070. }
  100071. /*
  100072. ** Invoke the authorization callback for permission to read column zCol from
  100073. ** table zTab in database zDb. This function assumes that an authorization
  100074. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  100075. **
  100076. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  100077. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  100078. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  100079. */
  100080. SQLITE_PRIVATE int sqlite3AuthReadCol(
  100081. Parse *pParse, /* The parser context */
  100082. const char *zTab, /* Table name */
  100083. const char *zCol, /* Column name */
  100084. int iDb /* Index of containing database. */
  100085. ){
  100086. sqlite3 *db = pParse->db; /* Database handle */
  100087. char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
  100088. int rc; /* Auth callback return code */
  100089. if( db->init.busy ) return SQLITE_OK;
  100090. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  100091. #ifdef SQLITE_USER_AUTHENTICATION
  100092. ,db->auth.zAuthUser
  100093. #endif
  100094. );
  100095. if( rc==SQLITE_DENY ){
  100096. char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
  100097. if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
  100098. sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
  100099. pParse->rc = SQLITE_AUTH;
  100100. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  100101. sqliteAuthBadReturnCode(pParse);
  100102. }
  100103. return rc;
  100104. }
  100105. /*
  100106. ** The pExpr should be a TK_COLUMN expression. The table referred to
  100107. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  100108. ** Check to see if it is OK to read this particular column.
  100109. **
  100110. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  100111. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  100112. ** then generate an error.
  100113. */
  100114. SQLITE_PRIVATE void sqlite3AuthRead(
  100115. Parse *pParse, /* The parser context */
  100116. Expr *pExpr, /* The expression to check authorization on */
  100117. Schema *pSchema, /* The schema of the expression */
  100118. SrcList *pTabList /* All table that pExpr might refer to */
  100119. ){
  100120. sqlite3 *db = pParse->db;
  100121. Table *pTab = 0; /* The table being read */
  100122. const char *zCol; /* Name of the column of the table */
  100123. int iSrc; /* Index in pTabList->a[] of table being read */
  100124. int iDb; /* The index of the database the expression refers to */
  100125. int iCol; /* Index of column in table */
  100126. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  100127. assert( !IN_RENAME_OBJECT || db->xAuth==0 );
  100128. if( db->xAuth==0 ) return;
  100129. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  100130. if( iDb<0 ){
  100131. /* An attempt to read a column out of a subquery or other
  100132. ** temporary table. */
  100133. return;
  100134. }
  100135. if( pExpr->op==TK_TRIGGER ){
  100136. pTab = pParse->pTriggerTab;
  100137. }else{
  100138. assert( pTabList );
  100139. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  100140. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  100141. pTab = pTabList->a[iSrc].pTab;
  100142. break;
  100143. }
  100144. }
  100145. }
  100146. iCol = pExpr->iColumn;
  100147. if( NEVER(pTab==0) ) return;
  100148. if( iCol>=0 ){
  100149. assert( iCol<pTab->nCol );
  100150. zCol = pTab->aCol[iCol].zName;
  100151. }else if( pTab->iPKey>=0 ){
  100152. assert( pTab->iPKey<pTab->nCol );
  100153. zCol = pTab->aCol[pTab->iPKey].zName;
  100154. }else{
  100155. zCol = "ROWID";
  100156. }
  100157. assert( iDb>=0 && iDb<db->nDb );
  100158. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  100159. pExpr->op = TK_NULL;
  100160. }
  100161. }
  100162. /*
  100163. ** Do an authorization check using the code and arguments given. Return
  100164. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  100165. ** is returned, then the error count and error message in pParse are
  100166. ** modified appropriately.
  100167. */
  100168. SQLITE_PRIVATE int sqlite3AuthCheck(
  100169. Parse *pParse,
  100170. int code,
  100171. const char *zArg1,
  100172. const char *zArg2,
  100173. const char *zArg3
  100174. ){
  100175. sqlite3 *db = pParse->db;
  100176. int rc;
  100177. /* Don't do any authorization checks if the database is initialising
  100178. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  100179. */
  100180. assert( !IN_RENAME_OBJECT || db->xAuth==0 );
  100181. if( db->init.busy || IN_SPECIAL_PARSE ){
  100182. return SQLITE_OK;
  100183. }
  100184. if( db->xAuth==0 ){
  100185. return SQLITE_OK;
  100186. }
  100187. /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
  100188. ** callback are either NULL pointers or zero-terminated strings that
  100189. ** contain additional details about the action to be authorized.
  100190. **
  100191. ** The following testcase() macros show that any of the 3rd through 6th
  100192. ** parameters can be either NULL or a string. */
  100193. testcase( zArg1==0 );
  100194. testcase( zArg2==0 );
  100195. testcase( zArg3==0 );
  100196. testcase( pParse->zAuthContext==0 );
  100197. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  100198. #ifdef SQLITE_USER_AUTHENTICATION
  100199. ,db->auth.zAuthUser
  100200. #endif
  100201. );
  100202. if( rc==SQLITE_DENY ){
  100203. sqlite3ErrorMsg(pParse, "not authorized");
  100204. pParse->rc = SQLITE_AUTH;
  100205. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  100206. rc = SQLITE_DENY;
  100207. sqliteAuthBadReturnCode(pParse);
  100208. }
  100209. return rc;
  100210. }
  100211. /*
  100212. ** Push an authorization context. After this routine is called, the
  100213. ** zArg3 argument to authorization callbacks will be zContext until
  100214. ** popped. Or if pParse==0, this routine is a no-op.
  100215. */
  100216. SQLITE_PRIVATE void sqlite3AuthContextPush(
  100217. Parse *pParse,
  100218. AuthContext *pContext,
  100219. const char *zContext
  100220. ){
  100221. assert( pParse );
  100222. pContext->pParse = pParse;
  100223. pContext->zAuthContext = pParse->zAuthContext;
  100224. pParse->zAuthContext = zContext;
  100225. }
  100226. /*
  100227. ** Pop an authorization context that was previously pushed
  100228. ** by sqlite3AuthContextPush
  100229. */
  100230. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  100231. if( pContext->pParse ){
  100232. pContext->pParse->zAuthContext = pContext->zAuthContext;
  100233. pContext->pParse = 0;
  100234. }
  100235. }
  100236. #endif /* SQLITE_OMIT_AUTHORIZATION */
  100237. /************** End of auth.c ************************************************/
  100238. /************** Begin file build.c *******************************************/
  100239. /*
  100240. ** 2001 September 15
  100241. **
  100242. ** The author disclaims copyright to this source code. In place of
  100243. ** a legal notice, here is a blessing:
  100244. **
  100245. ** May you do good and not evil.
  100246. ** May you find forgiveness for yourself and forgive others.
  100247. ** May you share freely, never taking more than you give.
  100248. **
  100249. *************************************************************************
  100250. ** This file contains C code routines that are called by the SQLite parser
  100251. ** when syntax rules are reduced. The routines in this file handle the
  100252. ** following kinds of SQL syntax:
  100253. **
  100254. ** CREATE TABLE
  100255. ** DROP TABLE
  100256. ** CREATE INDEX
  100257. ** DROP INDEX
  100258. ** creating ID lists
  100259. ** BEGIN TRANSACTION
  100260. ** COMMIT
  100261. ** ROLLBACK
  100262. */
  100263. /* #include "sqliteInt.h" */
  100264. #ifndef SQLITE_OMIT_SHARED_CACHE
  100265. /*
  100266. ** The TableLock structure is only used by the sqlite3TableLock() and
  100267. ** codeTableLocks() functions.
  100268. */
  100269. struct TableLock {
  100270. int iDb; /* The database containing the table to be locked */
  100271. int iTab; /* The root page of the table to be locked */
  100272. u8 isWriteLock; /* True for write lock. False for a read lock */
  100273. const char *zLockName; /* Name of the table */
  100274. };
  100275. /*
  100276. ** Record the fact that we want to lock a table at run-time.
  100277. **
  100278. ** The table to be locked has root page iTab and is found in database iDb.
  100279. ** A read or a write lock can be taken depending on isWritelock.
  100280. **
  100281. ** This routine just records the fact that the lock is desired. The
  100282. ** code to make the lock occur is generated by a later call to
  100283. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  100284. */
  100285. SQLITE_PRIVATE void sqlite3TableLock(
  100286. Parse *pParse, /* Parsing context */
  100287. int iDb, /* Index of the database containing the table to lock */
  100288. int iTab, /* Root page number of the table to be locked */
  100289. u8 isWriteLock, /* True for a write lock */
  100290. const char *zName /* Name of the table to be locked */
  100291. ){
  100292. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  100293. int i;
  100294. int nBytes;
  100295. TableLock *p;
  100296. assert( iDb>=0 );
  100297. if( iDb==1 ) return;
  100298. if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
  100299. for(i=0; i<pToplevel->nTableLock; i++){
  100300. p = &pToplevel->aTableLock[i];
  100301. if( p->iDb==iDb && p->iTab==iTab ){
  100302. p->isWriteLock = (p->isWriteLock || isWriteLock);
  100303. return;
  100304. }
  100305. }
  100306. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  100307. pToplevel->aTableLock =
  100308. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  100309. if( pToplevel->aTableLock ){
  100310. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  100311. p->iDb = iDb;
  100312. p->iTab = iTab;
  100313. p->isWriteLock = isWriteLock;
  100314. p->zLockName = zName;
  100315. }else{
  100316. pToplevel->nTableLock = 0;
  100317. sqlite3OomFault(pToplevel->db);
  100318. }
  100319. }
  100320. /*
  100321. ** Code an OP_TableLock instruction for each table locked by the
  100322. ** statement (configured by calls to sqlite3TableLock()).
  100323. */
  100324. static void codeTableLocks(Parse *pParse){
  100325. int i;
  100326. Vdbe *pVdbe;
  100327. pVdbe = sqlite3GetVdbe(pParse);
  100328. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  100329. for(i=0; i<pParse->nTableLock; i++){
  100330. TableLock *p = &pParse->aTableLock[i];
  100331. int p1 = p->iDb;
  100332. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  100333. p->zLockName, P4_STATIC);
  100334. }
  100335. }
  100336. #else
  100337. #define codeTableLocks(x)
  100338. #endif
  100339. /*
  100340. ** Return TRUE if the given yDbMask object is empty - if it contains no
  100341. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  100342. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  100343. */
  100344. #if SQLITE_MAX_ATTACHED>30
  100345. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  100346. int i;
  100347. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  100348. return 1;
  100349. }
  100350. #endif
  100351. /*
  100352. ** This routine is called after a single SQL statement has been
  100353. ** parsed and a VDBE program to execute that statement has been
  100354. ** prepared. This routine puts the finishing touches on the
  100355. ** VDBE program and resets the pParse structure for the next
  100356. ** parse.
  100357. **
  100358. ** Note that if an error occurred, it might be the case that
  100359. ** no VDBE code was generated.
  100360. */
  100361. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  100362. sqlite3 *db;
  100363. Vdbe *v;
  100364. assert( pParse->pToplevel==0 );
  100365. db = pParse->db;
  100366. if( pParse->nested ) return;
  100367. if( db->mallocFailed || pParse->nErr ){
  100368. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  100369. return;
  100370. }
  100371. /* Begin by generating some termination code at the end of the
  100372. ** vdbe program
  100373. */
  100374. v = sqlite3GetVdbe(pParse);
  100375. assert( !pParse->isMultiWrite
  100376. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  100377. if( v ){
  100378. sqlite3VdbeAddOp0(v, OP_Halt);
  100379. #if SQLITE_USER_AUTHENTICATION
  100380. if( pParse->nTableLock>0 && db->init.busy==0 ){
  100381. sqlite3UserAuthInit(db);
  100382. if( db->auth.authLevel<UAUTH_User ){
  100383. sqlite3ErrorMsg(pParse, "user not authenticated");
  100384. pParse->rc = SQLITE_AUTH_USER;
  100385. return;
  100386. }
  100387. }
  100388. #endif
  100389. /* The cookie mask contains one bit for each database file open.
  100390. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  100391. ** set for each database that is used. Generate code to start a
  100392. ** transaction on each used database and to verify the schema cookie
  100393. ** on each used database.
  100394. */
  100395. if( db->mallocFailed==0
  100396. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  100397. ){
  100398. int iDb, i;
  100399. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  100400. sqlite3VdbeJumpHere(v, 0);
  100401. for(iDb=0; iDb<db->nDb; iDb++){
  100402. Schema *pSchema;
  100403. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  100404. sqlite3VdbeUsesBtree(v, iDb);
  100405. pSchema = db->aDb[iDb].pSchema;
  100406. sqlite3VdbeAddOp4Int(v,
  100407. OP_Transaction, /* Opcode */
  100408. iDb, /* P1 */
  100409. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  100410. pSchema->schema_cookie, /* P3 */
  100411. pSchema->iGeneration /* P4 */
  100412. );
  100413. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  100414. VdbeComment((v,
  100415. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  100416. }
  100417. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100418. for(i=0; i<pParse->nVtabLock; i++){
  100419. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  100420. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  100421. }
  100422. pParse->nVtabLock = 0;
  100423. #endif
  100424. /* Once all the cookies have been verified and transactions opened,
  100425. ** obtain the required table-locks. This is a no-op unless the
  100426. ** shared-cache feature is enabled.
  100427. */
  100428. codeTableLocks(pParse);
  100429. /* Initialize any AUTOINCREMENT data structures required.
  100430. */
  100431. sqlite3AutoincrementBegin(pParse);
  100432. /* Code constant expressions that where factored out of inner loops */
  100433. if( pParse->pConstExpr ){
  100434. ExprList *pEL = pParse->pConstExpr;
  100435. pParse->okConstFactor = 0;
  100436. for(i=0; i<pEL->nExpr; i++){
  100437. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  100438. }
  100439. }
  100440. /* Finally, jump back to the beginning of the executable code. */
  100441. sqlite3VdbeGoto(v, 1);
  100442. }
  100443. }
  100444. /* Get the VDBE program ready for execution
  100445. */
  100446. if( v && pParse->nErr==0 && !db->mallocFailed ){
  100447. /* A minimum of one cursor is required if autoincrement is used
  100448. * See ticket [a696379c1f08866] */
  100449. assert( pParse->pAinc==0 || pParse->nTab>0 );
  100450. sqlite3VdbeMakeReady(v, pParse);
  100451. pParse->rc = SQLITE_DONE;
  100452. }else{
  100453. pParse->rc = SQLITE_ERROR;
  100454. }
  100455. }
  100456. /*
  100457. ** Run the parser and code generator recursively in order to generate
  100458. ** code for the SQL statement given onto the end of the pParse context
  100459. ** currently under construction. When the parser is run recursively
  100460. ** this way, the final OP_Halt is not appended and other initialization
  100461. ** and finalization steps are omitted because those are handling by the
  100462. ** outermost parser.
  100463. **
  100464. ** Not everything is nestable. This facility is designed to permit
  100465. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  100466. ** care if you decide to try to use this routine for some other purposes.
  100467. */
  100468. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  100469. va_list ap;
  100470. char *zSql;
  100471. char *zErrMsg = 0;
  100472. sqlite3 *db = pParse->db;
  100473. char saveBuf[PARSE_TAIL_SZ];
  100474. if( pParse->nErr ) return;
  100475. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  100476. va_start(ap, zFormat);
  100477. zSql = sqlite3VMPrintf(db, zFormat, ap);
  100478. va_end(ap);
  100479. if( zSql==0 ){
  100480. /* This can result either from an OOM or because the formatted string
  100481. ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
  100482. ** an error */
  100483. if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
  100484. pParse->nErr++;
  100485. return;
  100486. }
  100487. pParse->nested++;
  100488. memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
  100489. memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
  100490. sqlite3RunParser(pParse, zSql, &zErrMsg);
  100491. sqlite3DbFree(db, zErrMsg);
  100492. sqlite3DbFree(db, zSql);
  100493. memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
  100494. pParse->nested--;
  100495. }
  100496. #if SQLITE_USER_AUTHENTICATION
  100497. /*
  100498. ** Return TRUE if zTable is the name of the system table that stores the
  100499. ** list of users and their access credentials.
  100500. */
  100501. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  100502. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  100503. }
  100504. #endif
  100505. /*
  100506. ** Locate the in-memory structure that describes a particular database
  100507. ** table given the name of that table and (optionally) the name of the
  100508. ** database containing the table. Return NULL if not found.
  100509. **
  100510. ** If zDatabase is 0, all databases are searched for the table and the
  100511. ** first matching table is returned. (No checking for duplicate table
  100512. ** names is done.) The search order is TEMP first, then MAIN, then any
  100513. ** auxiliary databases added using the ATTACH command.
  100514. **
  100515. ** See also sqlite3LocateTable().
  100516. */
  100517. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  100518. Table *p = 0;
  100519. int i;
  100520. /* All mutexes are required for schema access. Make sure we hold them. */
  100521. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  100522. #if SQLITE_USER_AUTHENTICATION
  100523. /* Only the admin user is allowed to know that the sqlite_user table
  100524. ** exists */
  100525. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  100526. return 0;
  100527. }
  100528. #endif
  100529. while(1){
  100530. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  100531. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  100532. if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
  100533. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  100534. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  100535. if( p ) return p;
  100536. }
  100537. }
  100538. /* Not found. If the name we were looking for was temp.sqlite_master
  100539. ** then change the name to sqlite_temp_master and try again. */
  100540. if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
  100541. if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
  100542. zName = TEMP_MASTER_NAME;
  100543. }
  100544. return 0;
  100545. }
  100546. /*
  100547. ** Locate the in-memory structure that describes a particular database
  100548. ** table given the name of that table and (optionally) the name of the
  100549. ** database containing the table. Return NULL if not found. Also leave an
  100550. ** error message in pParse->zErrMsg.
  100551. **
  100552. ** The difference between this routine and sqlite3FindTable() is that this
  100553. ** routine leaves an error message in pParse->zErrMsg where
  100554. ** sqlite3FindTable() does not.
  100555. */
  100556. SQLITE_PRIVATE Table *sqlite3LocateTable(
  100557. Parse *pParse, /* context in which to report errors */
  100558. u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
  100559. const char *zName, /* Name of the table we are looking for */
  100560. const char *zDbase /* Name of the database. Might be NULL */
  100561. ){
  100562. Table *p;
  100563. sqlite3 *db = pParse->db;
  100564. /* Read the database schema. If an error occurs, leave an error message
  100565. ** and code in pParse and return NULL. */
  100566. if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
  100567. && SQLITE_OK!=sqlite3ReadSchema(pParse)
  100568. ){
  100569. return 0;
  100570. }
  100571. p = sqlite3FindTable(db, zName, zDbase);
  100572. if( p==0 ){
  100573. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100574. /* If zName is the not the name of a table in the schema created using
  100575. ** CREATE, then check to see if it is the name of an virtual table that
  100576. ** can be an eponymous virtual table. */
  100577. if( pParse->disableVtab==0 ){
  100578. Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
  100579. if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
  100580. pMod = sqlite3PragmaVtabRegister(db, zName);
  100581. }
  100582. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  100583. return pMod->pEpoTab;
  100584. }
  100585. }
  100586. #endif
  100587. if( flags & LOCATE_NOERR ) return 0;
  100588. pParse->checkSchema = 1;
  100589. }else if( IsVirtual(p) && pParse->disableVtab ){
  100590. p = 0;
  100591. }
  100592. if( p==0 ){
  100593. const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
  100594. if( zDbase ){
  100595. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  100596. }else{
  100597. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  100598. }
  100599. }
  100600. return p;
  100601. }
  100602. /*
  100603. ** Locate the table identified by *p.
  100604. **
  100605. ** This is a wrapper around sqlite3LocateTable(). The difference between
  100606. ** sqlite3LocateTable() and this function is that this function restricts
  100607. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  100608. ** non-NULL if it is part of a view or trigger program definition. See
  100609. ** sqlite3FixSrcList() for details.
  100610. */
  100611. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  100612. Parse *pParse,
  100613. u32 flags,
  100614. struct SrcList_item *p
  100615. ){
  100616. const char *zDb;
  100617. assert( p->pSchema==0 || p->zDatabase==0 );
  100618. if( p->pSchema ){
  100619. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  100620. zDb = pParse->db->aDb[iDb].zDbSName;
  100621. }else{
  100622. zDb = p->zDatabase;
  100623. }
  100624. return sqlite3LocateTable(pParse, flags, p->zName, zDb);
  100625. }
  100626. /*
  100627. ** Locate the in-memory structure that describes
  100628. ** a particular index given the name of that index
  100629. ** and the name of the database that contains the index.
  100630. ** Return NULL if not found.
  100631. **
  100632. ** If zDatabase is 0, all databases are searched for the
  100633. ** table and the first matching index is returned. (No checking
  100634. ** for duplicate index names is done.) The search order is
  100635. ** TEMP first, then MAIN, then any auxiliary databases added
  100636. ** using the ATTACH command.
  100637. */
  100638. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  100639. Index *p = 0;
  100640. int i;
  100641. /* All mutexes are required for schema access. Make sure we hold them. */
  100642. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  100643. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  100644. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  100645. Schema *pSchema = db->aDb[j].pSchema;
  100646. assert( pSchema );
  100647. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
  100648. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  100649. p = sqlite3HashFind(&pSchema->idxHash, zName);
  100650. if( p ) break;
  100651. }
  100652. return p;
  100653. }
  100654. /*
  100655. ** Reclaim the memory used by an index
  100656. */
  100657. SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3 *db, Index *p){
  100658. #ifndef SQLITE_OMIT_ANALYZE
  100659. sqlite3DeleteIndexSamples(db, p);
  100660. #endif
  100661. sqlite3ExprDelete(db, p->pPartIdxWhere);
  100662. sqlite3ExprListDelete(db, p->aColExpr);
  100663. sqlite3DbFree(db, p->zColAff);
  100664. if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
  100665. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  100666. sqlite3_free(p->aiRowEst);
  100667. #endif
  100668. sqlite3DbFree(db, p);
  100669. }
  100670. /*
  100671. ** For the index called zIdxName which is found in the database iDb,
  100672. ** unlike that index from its Table then remove the index from
  100673. ** the index hash table and free all memory structures associated
  100674. ** with the index.
  100675. */
  100676. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  100677. Index *pIndex;
  100678. Hash *pHash;
  100679. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100680. pHash = &db->aDb[iDb].pSchema->idxHash;
  100681. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  100682. if( ALWAYS(pIndex) ){
  100683. if( pIndex->pTable->pIndex==pIndex ){
  100684. pIndex->pTable->pIndex = pIndex->pNext;
  100685. }else{
  100686. Index *p;
  100687. /* Justification of ALWAYS(); The index must be on the list of
  100688. ** indices. */
  100689. p = pIndex->pTable->pIndex;
  100690. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  100691. if( ALWAYS(p && p->pNext==pIndex) ){
  100692. p->pNext = pIndex->pNext;
  100693. }
  100694. }
  100695. sqlite3FreeIndex(db, pIndex);
  100696. }
  100697. db->mDbFlags |= DBFLAG_SchemaChange;
  100698. }
  100699. /*
  100700. ** Look through the list of open database files in db->aDb[] and if
  100701. ** any have been closed, remove them from the list. Reallocate the
  100702. ** db->aDb[] structure to a smaller size, if possible.
  100703. **
  100704. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  100705. ** are never candidates for being collapsed.
  100706. */
  100707. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  100708. int i, j;
  100709. for(i=j=2; i<db->nDb; i++){
  100710. struct Db *pDb = &db->aDb[i];
  100711. if( pDb->pBt==0 ){
  100712. sqlite3DbFree(db, pDb->zDbSName);
  100713. pDb->zDbSName = 0;
  100714. continue;
  100715. }
  100716. if( j<i ){
  100717. db->aDb[j] = db->aDb[i];
  100718. }
  100719. j++;
  100720. }
  100721. db->nDb = j;
  100722. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  100723. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  100724. sqlite3DbFree(db, db->aDb);
  100725. db->aDb = db->aDbStatic;
  100726. }
  100727. }
  100728. /*
  100729. ** Reset the schema for the database at index iDb. Also reset the
  100730. ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
  100731. ** Deferred resets may be run by calling with iDb<0.
  100732. */
  100733. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  100734. int i;
  100735. assert( iDb<db->nDb );
  100736. if( iDb>=0 ){
  100737. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100738. DbSetProperty(db, iDb, DB_ResetWanted);
  100739. DbSetProperty(db, 1, DB_ResetWanted);
  100740. db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
  100741. }
  100742. if( db->nSchemaLock==0 ){
  100743. for(i=0; i<db->nDb; i++){
  100744. if( DbHasProperty(db, i, DB_ResetWanted) ){
  100745. sqlite3SchemaClear(db->aDb[i].pSchema);
  100746. }
  100747. }
  100748. }
  100749. }
  100750. /*
  100751. ** Erase all schema information from all attached databases (including
  100752. ** "main" and "temp") for a single database connection.
  100753. */
  100754. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  100755. int i;
  100756. sqlite3BtreeEnterAll(db);
  100757. for(i=0; i<db->nDb; i++){
  100758. Db *pDb = &db->aDb[i];
  100759. if( pDb->pSchema ){
  100760. if( db->nSchemaLock==0 ){
  100761. sqlite3SchemaClear(pDb->pSchema);
  100762. }else{
  100763. DbSetProperty(db, i, DB_ResetWanted);
  100764. }
  100765. }
  100766. }
  100767. db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
  100768. sqlite3VtabUnlockList(db);
  100769. sqlite3BtreeLeaveAll(db);
  100770. if( db->nSchemaLock==0 ){
  100771. sqlite3CollapseDatabaseArray(db);
  100772. }
  100773. }
  100774. /*
  100775. ** This routine is called when a commit occurs.
  100776. */
  100777. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  100778. db->mDbFlags &= ~DBFLAG_SchemaChange;
  100779. }
  100780. /*
  100781. ** Delete memory allocated for the column names of a table or view (the
  100782. ** Table.aCol[] array).
  100783. */
  100784. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  100785. int i;
  100786. Column *pCol;
  100787. assert( pTable!=0 );
  100788. if( (pCol = pTable->aCol)!=0 ){
  100789. for(i=0; i<pTable->nCol; i++, pCol++){
  100790. sqlite3DbFree(db, pCol->zName);
  100791. sqlite3ExprDelete(db, pCol->pDflt);
  100792. sqlite3DbFree(db, pCol->zColl);
  100793. }
  100794. sqlite3DbFree(db, pTable->aCol);
  100795. }
  100796. }
  100797. /*
  100798. ** Remove the memory data structures associated with the given
  100799. ** Table. No changes are made to disk by this routine.
  100800. **
  100801. ** This routine just deletes the data structure. It does not unlink
  100802. ** the table data structure from the hash table. But it does destroy
  100803. ** memory structures of the indices and foreign keys associated with
  100804. ** the table.
  100805. **
  100806. ** The db parameter is optional. It is needed if the Table object
  100807. ** contains lookaside memory. (Table objects in the schema do not use
  100808. ** lookaside memory, but some ephemeral Table objects do.) Or the
  100809. ** db parameter can be used with db->pnBytesFreed to measure the memory
  100810. ** used by the Table object.
  100811. */
  100812. static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
  100813. Index *pIndex, *pNext;
  100814. #ifdef SQLITE_DEBUG
  100815. /* Record the number of outstanding lookaside allocations in schema Tables
  100816. ** prior to doing any free() operations. Since schema Tables do not use
  100817. ** lookaside, this number should not change. */
  100818. int nLookaside = 0;
  100819. if( db && (pTable->tabFlags & TF_Ephemeral)==0 ){
  100820. nLookaside = sqlite3LookasideUsed(db, 0);
  100821. }
  100822. #endif
  100823. /* Delete all indices associated with this table. */
  100824. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  100825. pNext = pIndex->pNext;
  100826. assert( pIndex->pSchema==pTable->pSchema
  100827. || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
  100828. if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
  100829. char *zName = pIndex->zName;
  100830. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  100831. &pIndex->pSchema->idxHash, zName, 0
  100832. );
  100833. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  100834. assert( pOld==pIndex || pOld==0 );
  100835. }
  100836. sqlite3FreeIndex(db, pIndex);
  100837. }
  100838. /* Delete any foreign keys attached to this table. */
  100839. sqlite3FkDelete(db, pTable);
  100840. /* Delete the Table structure itself.
  100841. */
  100842. sqlite3DeleteColumnNames(db, pTable);
  100843. sqlite3DbFree(db, pTable->zName);
  100844. sqlite3DbFree(db, pTable->zColAff);
  100845. sqlite3SelectDelete(db, pTable->pSelect);
  100846. sqlite3ExprListDelete(db, pTable->pCheck);
  100847. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100848. sqlite3VtabClear(db, pTable);
  100849. #endif
  100850. sqlite3DbFree(db, pTable);
  100851. /* Verify that no lookaside memory was used by schema tables */
  100852. assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
  100853. }
  100854. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  100855. /* Do not delete the table until the reference count reaches zero. */
  100856. if( !pTable ) return;
  100857. if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
  100858. deleteTable(db, pTable);
  100859. }
  100860. /*
  100861. ** Unlink the given table from the hash tables and the delete the
  100862. ** table structure with all its indices and foreign keys.
  100863. */
  100864. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  100865. Table *p;
  100866. Db *pDb;
  100867. assert( db!=0 );
  100868. assert( iDb>=0 && iDb<db->nDb );
  100869. assert( zTabName );
  100870. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100871. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  100872. pDb = &db->aDb[iDb];
  100873. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  100874. sqlite3DeleteTable(db, p);
  100875. db->mDbFlags |= DBFLAG_SchemaChange;
  100876. }
  100877. /*
  100878. ** Given a token, return a string that consists of the text of that
  100879. ** token. Space to hold the returned string
  100880. ** is obtained from sqliteMalloc() and must be freed by the calling
  100881. ** function.
  100882. **
  100883. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  100884. ** surround the body of the token are removed.
  100885. **
  100886. ** Tokens are often just pointers into the original SQL text and so
  100887. ** are not \000 terminated and are not persistent. The returned string
  100888. ** is \000 terminated and is persistent.
  100889. */
  100890. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  100891. char *zName;
  100892. if( pName ){
  100893. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  100894. sqlite3Dequote(zName);
  100895. }else{
  100896. zName = 0;
  100897. }
  100898. return zName;
  100899. }
  100900. /*
  100901. ** Open the sqlite_master table stored in database number iDb for
  100902. ** writing. The table is opened using cursor 0.
  100903. */
  100904. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  100905. Vdbe *v = sqlite3GetVdbe(p);
  100906. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
  100907. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  100908. if( p->nTab==0 ){
  100909. p->nTab = 1;
  100910. }
  100911. }
  100912. /*
  100913. ** Parameter zName points to a nul-terminated buffer containing the name
  100914. ** of a database ("main", "temp" or the name of an attached db). This
  100915. ** function returns the index of the named database in db->aDb[], or
  100916. ** -1 if the named db cannot be found.
  100917. */
  100918. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  100919. int i = -1; /* Database number */
  100920. if( zName ){
  100921. Db *pDb;
  100922. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  100923. if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
  100924. /* "main" is always an acceptable alias for the primary database
  100925. ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
  100926. if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
  100927. }
  100928. }
  100929. return i;
  100930. }
  100931. /*
  100932. ** The token *pName contains the name of a database (either "main" or
  100933. ** "temp" or the name of an attached db). This routine returns the
  100934. ** index of the named database in db->aDb[], or -1 if the named db
  100935. ** does not exist.
  100936. */
  100937. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  100938. int i; /* Database number */
  100939. char *zName; /* Name we are searching for */
  100940. zName = sqlite3NameFromToken(db, pName);
  100941. i = sqlite3FindDbName(db, zName);
  100942. sqlite3DbFree(db, zName);
  100943. return i;
  100944. }
  100945. /* The table or view or trigger name is passed to this routine via tokens
  100946. ** pName1 and pName2. If the table name was fully qualified, for example:
  100947. **
  100948. ** CREATE TABLE xxx.yyy (...);
  100949. **
  100950. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  100951. ** the table name is not fully qualified, i.e.:
  100952. **
  100953. ** CREATE TABLE yyy(...);
  100954. **
  100955. ** Then pName1 is set to "yyy" and pName2 is "".
  100956. **
  100957. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  100958. ** pName2) that stores the unqualified table name. The index of the
  100959. ** database "xxx" is returned.
  100960. */
  100961. SQLITE_PRIVATE int sqlite3TwoPartName(
  100962. Parse *pParse, /* Parsing and code generating context */
  100963. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  100964. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  100965. Token **pUnqual /* Write the unqualified object name here */
  100966. ){
  100967. int iDb; /* Database holding the object */
  100968. sqlite3 *db = pParse->db;
  100969. assert( pName2!=0 );
  100970. if( pName2->n>0 ){
  100971. if( db->init.busy ) {
  100972. sqlite3ErrorMsg(pParse, "corrupt database");
  100973. return -1;
  100974. }
  100975. *pUnqual = pName2;
  100976. iDb = sqlite3FindDb(db, pName1);
  100977. if( iDb<0 ){
  100978. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  100979. return -1;
  100980. }
  100981. }else{
  100982. assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT
  100983. || (db->mDbFlags & DBFLAG_Vacuum)!=0);
  100984. iDb = db->init.iDb;
  100985. *pUnqual = pName1;
  100986. }
  100987. return iDb;
  100988. }
  100989. /*
  100990. ** True if PRAGMA writable_schema is ON
  100991. */
  100992. SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3 *db){
  100993. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
  100994. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  100995. SQLITE_WriteSchema );
  100996. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  100997. SQLITE_Defensive );
  100998. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  100999. (SQLITE_WriteSchema|SQLITE_Defensive) );
  101000. return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
  101001. }
  101002. /*
  101003. ** This routine is used to check if the UTF-8 string zName is a legal
  101004. ** unqualified name for a new schema object (table, index, view or
  101005. ** trigger). All names are legal except those that begin with the string
  101006. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  101007. ** is reserved for internal use.
  101008. */
  101009. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  101010. if( !pParse->db->init.busy && pParse->nested==0
  101011. && sqlite3WritableSchema(pParse->db)==0
  101012. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  101013. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  101014. return SQLITE_ERROR;
  101015. }
  101016. return SQLITE_OK;
  101017. }
  101018. /*
  101019. ** Return the PRIMARY KEY index of a table
  101020. */
  101021. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  101022. Index *p;
  101023. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  101024. return p;
  101025. }
  101026. /*
  101027. ** Return the column of index pIdx that corresponds to table
  101028. ** column iCol. Return -1 if not found.
  101029. */
  101030. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  101031. int i;
  101032. for(i=0; i<pIdx->nColumn; i++){
  101033. if( iCol==pIdx->aiColumn[i] ) return i;
  101034. }
  101035. return -1;
  101036. }
  101037. /*
  101038. ** Begin constructing a new table representation in memory. This is
  101039. ** the first of several action routines that get called in response
  101040. ** to a CREATE TABLE statement. In particular, this routine is called
  101041. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  101042. ** flag is true if the table should be stored in the auxiliary database
  101043. ** file instead of in the main database file. This is normally the case
  101044. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  101045. ** CREATE and TABLE.
  101046. **
  101047. ** The new table record is initialized and put in pParse->pNewTable.
  101048. ** As more of the CREATE TABLE statement is parsed, additional action
  101049. ** routines will be called to add more information to this record.
  101050. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  101051. ** is called to complete the construction of the new table record.
  101052. */
  101053. SQLITE_PRIVATE void sqlite3StartTable(
  101054. Parse *pParse, /* Parser context */
  101055. Token *pName1, /* First part of the name of the table or view */
  101056. Token *pName2, /* Second part of the name of the table or view */
  101057. int isTemp, /* True if this is a TEMP table */
  101058. int isView, /* True if this is a VIEW */
  101059. int isVirtual, /* True if this is a VIRTUAL table */
  101060. int noErr /* Do nothing if table already exists */
  101061. ){
  101062. Table *pTable;
  101063. char *zName = 0; /* The name of the new table */
  101064. sqlite3 *db = pParse->db;
  101065. Vdbe *v;
  101066. int iDb; /* Database number to create the table in */
  101067. Token *pName; /* Unqualified name of the table to create */
  101068. if( db->init.busy && db->init.newTnum==1 ){
  101069. /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
  101070. iDb = db->init.iDb;
  101071. zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
  101072. pName = pName1;
  101073. }else{
  101074. /* The common case */
  101075. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  101076. if( iDb<0 ) return;
  101077. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  101078. /* If creating a temp table, the name may not be qualified. Unless
  101079. ** the database name is "temp" anyway. */
  101080. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  101081. return;
  101082. }
  101083. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  101084. zName = sqlite3NameFromToken(db, pName);
  101085. if( IN_RENAME_OBJECT ){
  101086. sqlite3RenameTokenMap(pParse, (void*)zName, pName);
  101087. }
  101088. }
  101089. pParse->sNameToken = *pName;
  101090. if( zName==0 ) return;
  101091. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  101092. goto begin_table_error;
  101093. }
  101094. if( db->init.iDb==1 ) isTemp = 1;
  101095. #ifndef SQLITE_OMIT_AUTHORIZATION
  101096. assert( isTemp==0 || isTemp==1 );
  101097. assert( isView==0 || isView==1 );
  101098. {
  101099. static const u8 aCode[] = {
  101100. SQLITE_CREATE_TABLE,
  101101. SQLITE_CREATE_TEMP_TABLE,
  101102. SQLITE_CREATE_VIEW,
  101103. SQLITE_CREATE_TEMP_VIEW
  101104. };
  101105. char *zDb = db->aDb[iDb].zDbSName;
  101106. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  101107. goto begin_table_error;
  101108. }
  101109. if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
  101110. zName, 0, zDb) ){
  101111. goto begin_table_error;
  101112. }
  101113. }
  101114. #endif
  101115. /* Make sure the new table name does not collide with an existing
  101116. ** index or table name in the same database. Issue an error message if
  101117. ** it does. The exception is if the statement being parsed was passed
  101118. ** to an sqlite3_declare_vtab() call. In that case only the column names
  101119. ** and types will be used, so there is no need to test for namespace
  101120. ** collisions.
  101121. */
  101122. if( !IN_SPECIAL_PARSE ){
  101123. char *zDb = db->aDb[iDb].zDbSName;
  101124. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  101125. goto begin_table_error;
  101126. }
  101127. pTable = sqlite3FindTable(db, zName, zDb);
  101128. if( pTable ){
  101129. if( !noErr ){
  101130. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  101131. }else{
  101132. assert( !db->init.busy || CORRUPT_DB );
  101133. sqlite3CodeVerifySchema(pParse, iDb);
  101134. }
  101135. goto begin_table_error;
  101136. }
  101137. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  101138. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  101139. goto begin_table_error;
  101140. }
  101141. }
  101142. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  101143. if( pTable==0 ){
  101144. assert( db->mallocFailed );
  101145. pParse->rc = SQLITE_NOMEM_BKPT;
  101146. pParse->nErr++;
  101147. goto begin_table_error;
  101148. }
  101149. pTable->zName = zName;
  101150. pTable->iPKey = -1;
  101151. pTable->pSchema = db->aDb[iDb].pSchema;
  101152. pTable->nTabRef = 1;
  101153. #ifdef SQLITE_DEFAULT_ROWEST
  101154. pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
  101155. #else
  101156. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  101157. #endif
  101158. assert( pParse->pNewTable==0 );
  101159. pParse->pNewTable = pTable;
  101160. /* If this is the magic sqlite_sequence table used by autoincrement,
  101161. ** then record a pointer to this table in the main database structure
  101162. ** so that INSERT can find the table easily.
  101163. */
  101164. #ifndef SQLITE_OMIT_AUTOINCREMENT
  101165. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  101166. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101167. pTable->pSchema->pSeqTab = pTable;
  101168. }
  101169. #endif
  101170. /* Begin generating the code that will insert the table record into
  101171. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  101172. ** and allocate the record number for the table entry now. Before any
  101173. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  101174. ** indices to be created and the table record must come before the
  101175. ** indices. Hence, the record number for the table must be allocated
  101176. ** now.
  101177. */
  101178. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  101179. int addr1;
  101180. int fileFormat;
  101181. int reg1, reg2, reg3;
  101182. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  101183. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  101184. sqlite3BeginWriteOperation(pParse, 1, iDb);
  101185. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101186. if( isVirtual ){
  101187. sqlite3VdbeAddOp0(v, OP_VBegin);
  101188. }
  101189. #endif
  101190. /* If the file format and encoding in the database have not been set,
  101191. ** set them now.
  101192. */
  101193. reg1 = pParse->regRowid = ++pParse->nMem;
  101194. reg2 = pParse->regRoot = ++pParse->nMem;
  101195. reg3 = ++pParse->nMem;
  101196. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  101197. sqlite3VdbeUsesBtree(v, iDb);
  101198. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  101199. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  101200. 1 : SQLITE_MAX_FILE_FORMAT;
  101201. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
  101202. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
  101203. sqlite3VdbeJumpHere(v, addr1);
  101204. /* This just creates a place-holder record in the sqlite_master table.
  101205. ** The record created does not contain anything yet. It will be replaced
  101206. ** by the real entry in code generated at sqlite3EndTable().
  101207. **
  101208. ** The rowid for the new entry is left in register pParse->regRowid.
  101209. ** The root page number of the new table is left in reg pParse->regRoot.
  101210. ** The rowid and root page number values are needed by the code that
  101211. ** sqlite3EndTable will generate.
  101212. */
  101213. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  101214. if( isView || isVirtual ){
  101215. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  101216. }else
  101217. #endif
  101218. {
  101219. pParse->addrCrTab =
  101220. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
  101221. }
  101222. sqlite3OpenMasterTable(pParse, iDb);
  101223. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  101224. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  101225. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  101226. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  101227. sqlite3VdbeAddOp0(v, OP_Close);
  101228. }
  101229. /* Normal (non-error) return. */
  101230. return;
  101231. /* If an error occurs, we jump here */
  101232. begin_table_error:
  101233. sqlite3DbFree(db, zName);
  101234. return;
  101235. }
  101236. /* Set properties of a table column based on the (magical)
  101237. ** name of the column.
  101238. */
  101239. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  101240. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
  101241. if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
  101242. pCol->colFlags |= COLFLAG_HIDDEN;
  101243. }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
  101244. pTab->tabFlags |= TF_OOOHidden;
  101245. }
  101246. }
  101247. #endif
  101248. /*
  101249. ** Add a new column to the table currently being constructed.
  101250. **
  101251. ** The parser calls this routine once for each column declaration
  101252. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  101253. ** first to get things going. Then this routine is called for each
  101254. ** column.
  101255. */
  101256. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
  101257. Table *p;
  101258. int i;
  101259. char *z;
  101260. char *zType;
  101261. Column *pCol;
  101262. sqlite3 *db = pParse->db;
  101263. if( (p = pParse->pNewTable)==0 ) return;
  101264. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  101265. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  101266. return;
  101267. }
  101268. z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
  101269. if( z==0 ) return;
  101270. if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
  101271. memcpy(z, pName->z, pName->n);
  101272. z[pName->n] = 0;
  101273. sqlite3Dequote(z);
  101274. for(i=0; i<p->nCol; i++){
  101275. if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
  101276. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  101277. sqlite3DbFree(db, z);
  101278. return;
  101279. }
  101280. }
  101281. if( (p->nCol & 0x7)==0 ){
  101282. Column *aNew;
  101283. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  101284. if( aNew==0 ){
  101285. sqlite3DbFree(db, z);
  101286. return;
  101287. }
  101288. p->aCol = aNew;
  101289. }
  101290. pCol = &p->aCol[p->nCol];
  101291. memset(pCol, 0, sizeof(p->aCol[0]));
  101292. pCol->zName = z;
  101293. sqlite3ColumnPropertiesFromName(p, pCol);
  101294. if( pType->n==0 ){
  101295. /* If there is no type specified, columns have the default affinity
  101296. ** 'BLOB' with a default size of 4 bytes. */
  101297. pCol->affinity = SQLITE_AFF_BLOB;
  101298. pCol->szEst = 1;
  101299. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  101300. if( 4>=sqlite3GlobalConfig.szSorterRef ){
  101301. pCol->colFlags |= COLFLAG_SORTERREF;
  101302. }
  101303. #endif
  101304. }else{
  101305. zType = z + sqlite3Strlen30(z) + 1;
  101306. memcpy(zType, pType->z, pType->n);
  101307. zType[pType->n] = 0;
  101308. sqlite3Dequote(zType);
  101309. pCol->affinity = sqlite3AffinityType(zType, pCol);
  101310. pCol->colFlags |= COLFLAG_HASTYPE;
  101311. }
  101312. p->nCol++;
  101313. pParse->constraintName.n = 0;
  101314. }
  101315. /*
  101316. ** This routine is called by the parser while in the middle of
  101317. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  101318. ** been seen on a column. This routine sets the notNull flag on
  101319. ** the column currently under construction.
  101320. */
  101321. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  101322. Table *p;
  101323. Column *pCol;
  101324. p = pParse->pNewTable;
  101325. if( p==0 || NEVER(p->nCol<1) ) return;
  101326. pCol = &p->aCol[p->nCol-1];
  101327. pCol->notNull = (u8)onError;
  101328. p->tabFlags |= TF_HasNotNull;
  101329. /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
  101330. ** on this column. */
  101331. if( pCol->colFlags & COLFLAG_UNIQUE ){
  101332. Index *pIdx;
  101333. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  101334. assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
  101335. if( pIdx->aiColumn[0]==p->nCol-1 ){
  101336. pIdx->uniqNotNull = 1;
  101337. }
  101338. }
  101339. }
  101340. }
  101341. /*
  101342. ** Scan the column type name zType (length nType) and return the
  101343. ** associated affinity type.
  101344. **
  101345. ** This routine does a case-independent search of zType for the
  101346. ** substrings in the following table. If one of the substrings is
  101347. ** found, the corresponding affinity is returned. If zType contains
  101348. ** more than one of the substrings, entries toward the top of
  101349. ** the table take priority. For example, if zType is 'BLOBINT',
  101350. ** SQLITE_AFF_INTEGER is returned.
  101351. **
  101352. ** Substring | Affinity
  101353. ** --------------------------------
  101354. ** 'INT' | SQLITE_AFF_INTEGER
  101355. ** 'CHAR' | SQLITE_AFF_TEXT
  101356. ** 'CLOB' | SQLITE_AFF_TEXT
  101357. ** 'TEXT' | SQLITE_AFF_TEXT
  101358. ** 'BLOB' | SQLITE_AFF_BLOB
  101359. ** 'REAL' | SQLITE_AFF_REAL
  101360. ** 'FLOA' | SQLITE_AFF_REAL
  101361. ** 'DOUB' | SQLITE_AFF_REAL
  101362. **
  101363. ** If none of the substrings in the above table are found,
  101364. ** SQLITE_AFF_NUMERIC is returned.
  101365. */
  101366. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, Column *pCol){
  101367. u32 h = 0;
  101368. char aff = SQLITE_AFF_NUMERIC;
  101369. const char *zChar = 0;
  101370. assert( zIn!=0 );
  101371. while( zIn[0] ){
  101372. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  101373. zIn++;
  101374. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  101375. aff = SQLITE_AFF_TEXT;
  101376. zChar = zIn;
  101377. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  101378. aff = SQLITE_AFF_TEXT;
  101379. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  101380. aff = SQLITE_AFF_TEXT;
  101381. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  101382. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  101383. aff = SQLITE_AFF_BLOB;
  101384. if( zIn[0]=='(' ) zChar = zIn;
  101385. #ifndef SQLITE_OMIT_FLOATING_POINT
  101386. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  101387. && aff==SQLITE_AFF_NUMERIC ){
  101388. aff = SQLITE_AFF_REAL;
  101389. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  101390. && aff==SQLITE_AFF_NUMERIC ){
  101391. aff = SQLITE_AFF_REAL;
  101392. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  101393. && aff==SQLITE_AFF_NUMERIC ){
  101394. aff = SQLITE_AFF_REAL;
  101395. #endif
  101396. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  101397. aff = SQLITE_AFF_INTEGER;
  101398. break;
  101399. }
  101400. }
  101401. /* If pCol is not NULL, store an estimate of the field size. The
  101402. ** estimate is scaled so that the size of an integer is 1. */
  101403. if( pCol ){
  101404. int v = 0; /* default size is approx 4 bytes */
  101405. if( aff<SQLITE_AFF_NUMERIC ){
  101406. if( zChar ){
  101407. while( zChar[0] ){
  101408. if( sqlite3Isdigit(zChar[0]) ){
  101409. /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  101410. sqlite3GetInt32(zChar, &v);
  101411. break;
  101412. }
  101413. zChar++;
  101414. }
  101415. }else{
  101416. v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  101417. }
  101418. }
  101419. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  101420. if( v>=sqlite3GlobalConfig.szSorterRef ){
  101421. pCol->colFlags |= COLFLAG_SORTERREF;
  101422. }
  101423. #endif
  101424. v = v/4 + 1;
  101425. if( v>255 ) v = 255;
  101426. pCol->szEst = v;
  101427. }
  101428. return aff;
  101429. }
  101430. /*
  101431. ** The expression is the default value for the most recently added column
  101432. ** of the table currently under construction.
  101433. **
  101434. ** Default value expressions must be constant. Raise an exception if this
  101435. ** is not the case.
  101436. **
  101437. ** This routine is called by the parser while in the middle of
  101438. ** parsing a CREATE TABLE statement.
  101439. */
  101440. SQLITE_PRIVATE void sqlite3AddDefaultValue(
  101441. Parse *pParse, /* Parsing context */
  101442. Expr *pExpr, /* The parsed expression of the default value */
  101443. const char *zStart, /* Start of the default value text */
  101444. const char *zEnd /* First character past end of defaut value text */
  101445. ){
  101446. Table *p;
  101447. Column *pCol;
  101448. sqlite3 *db = pParse->db;
  101449. p = pParse->pNewTable;
  101450. if( p!=0 ){
  101451. pCol = &(p->aCol[p->nCol-1]);
  101452. if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
  101453. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  101454. pCol->zName);
  101455. }else{
  101456. /* A copy of pExpr is used instead of the original, as pExpr contains
  101457. ** tokens that point to volatile memory.
  101458. */
  101459. Expr x;
  101460. sqlite3ExprDelete(db, pCol->pDflt);
  101461. memset(&x, 0, sizeof(x));
  101462. x.op = TK_SPAN;
  101463. x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
  101464. x.pLeft = pExpr;
  101465. x.flags = EP_Skip;
  101466. pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
  101467. sqlite3DbFree(db, x.u.zToken);
  101468. }
  101469. }
  101470. if( IN_RENAME_OBJECT ){
  101471. sqlite3RenameExprUnmap(pParse, pExpr);
  101472. }
  101473. sqlite3ExprDelete(db, pExpr);
  101474. }
  101475. /*
  101476. ** Backwards Compatibility Hack:
  101477. **
  101478. ** Historical versions of SQLite accepted strings as column names in
  101479. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  101480. **
  101481. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  101482. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  101483. **
  101484. ** This is goofy. But to preserve backwards compatibility we continue to
  101485. ** accept it. This routine does the necessary conversion. It converts
  101486. ** the expression given in its argument from a TK_STRING into a TK_ID
  101487. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  101488. ** If the epxression is anything other than TK_STRING, the expression is
  101489. ** unchanged.
  101490. */
  101491. static void sqlite3StringToId(Expr *p){
  101492. if( p->op==TK_STRING ){
  101493. p->op = TK_ID;
  101494. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  101495. p->pLeft->op = TK_ID;
  101496. }
  101497. }
  101498. /*
  101499. ** Designate the PRIMARY KEY for the table. pList is a list of names
  101500. ** of columns that form the primary key. If pList is NULL, then the
  101501. ** most recently added column of the table is the primary key.
  101502. **
  101503. ** A table can have at most one primary key. If the table already has
  101504. ** a primary key (and this is the second primary key) then create an
  101505. ** error.
  101506. **
  101507. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  101508. ** then we will try to use that column as the rowid. Set the Table.iPKey
  101509. ** field of the table under construction to be the index of the
  101510. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  101511. ** no INTEGER PRIMARY KEY.
  101512. **
  101513. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  101514. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  101515. */
  101516. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  101517. Parse *pParse, /* Parsing context */
  101518. ExprList *pList, /* List of field names to be indexed */
  101519. int onError, /* What to do with a uniqueness conflict */
  101520. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  101521. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  101522. ){
  101523. Table *pTab = pParse->pNewTable;
  101524. Column *pCol = 0;
  101525. int iCol = -1, i;
  101526. int nTerm;
  101527. if( pTab==0 ) goto primary_key_exit;
  101528. if( pTab->tabFlags & TF_HasPrimaryKey ){
  101529. sqlite3ErrorMsg(pParse,
  101530. "table \"%s\" has more than one primary key", pTab->zName);
  101531. goto primary_key_exit;
  101532. }
  101533. pTab->tabFlags |= TF_HasPrimaryKey;
  101534. if( pList==0 ){
  101535. iCol = pTab->nCol - 1;
  101536. pCol = &pTab->aCol[iCol];
  101537. pCol->colFlags |= COLFLAG_PRIMKEY;
  101538. nTerm = 1;
  101539. }else{
  101540. nTerm = pList->nExpr;
  101541. for(i=0; i<nTerm; i++){
  101542. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  101543. assert( pCExpr!=0 );
  101544. sqlite3StringToId(pCExpr);
  101545. if( pCExpr->op==TK_ID ){
  101546. const char *zCName = pCExpr->u.zToken;
  101547. for(iCol=0; iCol<pTab->nCol; iCol++){
  101548. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  101549. pCol = &pTab->aCol[iCol];
  101550. pCol->colFlags |= COLFLAG_PRIMKEY;
  101551. break;
  101552. }
  101553. }
  101554. }
  101555. }
  101556. }
  101557. if( nTerm==1
  101558. && pCol
  101559. && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
  101560. && sortOrder!=SQLITE_SO_DESC
  101561. ){
  101562. if( IN_RENAME_OBJECT && pList ){
  101563. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  101564. sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
  101565. }
  101566. pTab->iPKey = iCol;
  101567. pTab->keyConf = (u8)onError;
  101568. assert( autoInc==0 || autoInc==1 );
  101569. pTab->tabFlags |= autoInc*TF_Autoincrement;
  101570. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  101571. }else if( autoInc ){
  101572. #ifndef SQLITE_OMIT_AUTOINCREMENT
  101573. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  101574. "INTEGER PRIMARY KEY");
  101575. #endif
  101576. }else{
  101577. sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  101578. 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
  101579. pList = 0;
  101580. }
  101581. primary_key_exit:
  101582. sqlite3ExprListDelete(pParse->db, pList);
  101583. return;
  101584. }
  101585. /*
  101586. ** Add a new CHECK constraint to the table currently under construction.
  101587. */
  101588. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  101589. Parse *pParse, /* Parsing context */
  101590. Expr *pCheckExpr /* The check expression */
  101591. ){
  101592. #ifndef SQLITE_OMIT_CHECK
  101593. Table *pTab = pParse->pNewTable;
  101594. sqlite3 *db = pParse->db;
  101595. if( pTab && !IN_DECLARE_VTAB
  101596. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  101597. ){
  101598. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  101599. if( pParse->constraintName.n ){
  101600. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  101601. }
  101602. }else
  101603. #endif
  101604. {
  101605. sqlite3ExprDelete(pParse->db, pCheckExpr);
  101606. }
  101607. }
  101608. /*
  101609. ** Set the collation function of the most recently parsed table column
  101610. ** to the CollSeq given.
  101611. */
  101612. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  101613. Table *p;
  101614. int i;
  101615. char *zColl; /* Dequoted name of collation sequence */
  101616. sqlite3 *db;
  101617. if( (p = pParse->pNewTable)==0 ) return;
  101618. i = p->nCol-1;
  101619. db = pParse->db;
  101620. zColl = sqlite3NameFromToken(db, pToken);
  101621. if( !zColl ) return;
  101622. if( sqlite3LocateCollSeq(pParse, zColl) ){
  101623. Index *pIdx;
  101624. sqlite3DbFree(db, p->aCol[i].zColl);
  101625. p->aCol[i].zColl = zColl;
  101626. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  101627. ** then an index may have been created on this column before the
  101628. ** collation type was added. Correct this if it is the case.
  101629. */
  101630. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  101631. assert( pIdx->nKeyCol==1 );
  101632. if( pIdx->aiColumn[0]==i ){
  101633. pIdx->azColl[0] = p->aCol[i].zColl;
  101634. }
  101635. }
  101636. }else{
  101637. sqlite3DbFree(db, zColl);
  101638. }
  101639. }
  101640. /*
  101641. ** This function returns the collation sequence for database native text
  101642. ** encoding identified by the string zName, length nName.
  101643. **
  101644. ** If the requested collation sequence is not available, or not available
  101645. ** in the database native encoding, the collation factory is invoked to
  101646. ** request it. If the collation factory does not supply such a sequence,
  101647. ** and the sequence is available in another text encoding, then that is
  101648. ** returned instead.
  101649. **
  101650. ** If no versions of the requested collations sequence are available, or
  101651. ** another error occurs, NULL is returned and an error message written into
  101652. ** pParse.
  101653. **
  101654. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  101655. ** invokes the collation factory if the named collation cannot be found
  101656. ** and generates an error message.
  101657. **
  101658. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  101659. */
  101660. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  101661. sqlite3 *db = pParse->db;
  101662. u8 enc = ENC(db);
  101663. u8 initbusy = db->init.busy;
  101664. CollSeq *pColl;
  101665. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  101666. if( !initbusy && (!pColl || !pColl->xCmp) ){
  101667. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  101668. }
  101669. return pColl;
  101670. }
  101671. /*
  101672. ** Generate code that will increment the schema cookie.
  101673. **
  101674. ** The schema cookie is used to determine when the schema for the
  101675. ** database changes. After each schema change, the cookie value
  101676. ** changes. When a process first reads the schema it records the
  101677. ** cookie. Thereafter, whenever it goes to access the database,
  101678. ** it checks the cookie to make sure the schema has not changed
  101679. ** since it was last read.
  101680. **
  101681. ** This plan is not completely bullet-proof. It is possible for
  101682. ** the schema to change multiple times and for the cookie to be
  101683. ** set back to prior value. But schema changes are infrequent
  101684. ** and the probability of hitting the same cookie value is only
  101685. ** 1 chance in 2^32. So we're safe enough.
  101686. **
  101687. ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
  101688. ** the schema-version whenever the schema changes.
  101689. */
  101690. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  101691. sqlite3 *db = pParse->db;
  101692. Vdbe *v = pParse->pVdbe;
  101693. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101694. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
  101695. (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
  101696. }
  101697. /*
  101698. ** Measure the number of characters needed to output the given
  101699. ** identifier. The number returned includes any quotes used
  101700. ** but does not include the null terminator.
  101701. **
  101702. ** The estimate is conservative. It might be larger that what is
  101703. ** really needed.
  101704. */
  101705. static int identLength(const char *z){
  101706. int n;
  101707. for(n=0; *z; n++, z++){
  101708. if( *z=='"' ){ n++; }
  101709. }
  101710. return n + 2;
  101711. }
  101712. /*
  101713. ** The first parameter is a pointer to an output buffer. The second
  101714. ** parameter is a pointer to an integer that contains the offset at
  101715. ** which to write into the output buffer. This function copies the
  101716. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  101717. ** to the specified offset in the buffer and updates *pIdx to refer
  101718. ** to the first byte after the last byte written before returning.
  101719. **
  101720. ** If the string zSignedIdent consists entirely of alpha-numeric
  101721. ** characters, does not begin with a digit and is not an SQL keyword,
  101722. ** then it is copied to the output buffer exactly as it is. Otherwise,
  101723. ** it is quoted using double-quotes.
  101724. */
  101725. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  101726. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  101727. int i, j, needQuote;
  101728. i = *pIdx;
  101729. for(j=0; zIdent[j]; j++){
  101730. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  101731. }
  101732. needQuote = sqlite3Isdigit(zIdent[0])
  101733. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  101734. || zIdent[j]!=0
  101735. || j==0;
  101736. if( needQuote ) z[i++] = '"';
  101737. for(j=0; zIdent[j]; j++){
  101738. z[i++] = zIdent[j];
  101739. if( zIdent[j]=='"' ) z[i++] = '"';
  101740. }
  101741. if( needQuote ) z[i++] = '"';
  101742. z[i] = 0;
  101743. *pIdx = i;
  101744. }
  101745. /*
  101746. ** Generate a CREATE TABLE statement appropriate for the given
  101747. ** table. Memory to hold the text of the statement is obtained
  101748. ** from sqliteMalloc() and must be freed by the calling function.
  101749. */
  101750. static char *createTableStmt(sqlite3 *db, Table *p){
  101751. int i, k, n;
  101752. char *zStmt;
  101753. char *zSep, *zSep2, *zEnd;
  101754. Column *pCol;
  101755. n = 0;
  101756. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  101757. n += identLength(pCol->zName) + 5;
  101758. }
  101759. n += identLength(p->zName);
  101760. if( n<50 ){
  101761. zSep = "";
  101762. zSep2 = ",";
  101763. zEnd = ")";
  101764. }else{
  101765. zSep = "\n ";
  101766. zSep2 = ",\n ";
  101767. zEnd = "\n)";
  101768. }
  101769. n += 35 + 6*p->nCol;
  101770. zStmt = sqlite3DbMallocRaw(0, n);
  101771. if( zStmt==0 ){
  101772. sqlite3OomFault(db);
  101773. return 0;
  101774. }
  101775. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  101776. k = sqlite3Strlen30(zStmt);
  101777. identPut(zStmt, &k, p->zName);
  101778. zStmt[k++] = '(';
  101779. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  101780. static const char * const azType[] = {
  101781. /* SQLITE_AFF_BLOB */ "",
  101782. /* SQLITE_AFF_TEXT */ " TEXT",
  101783. /* SQLITE_AFF_NUMERIC */ " NUM",
  101784. /* SQLITE_AFF_INTEGER */ " INT",
  101785. /* SQLITE_AFF_REAL */ " REAL"
  101786. };
  101787. int len;
  101788. const char *zType;
  101789. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  101790. k += sqlite3Strlen30(&zStmt[k]);
  101791. zSep = zSep2;
  101792. identPut(zStmt, &k, pCol->zName);
  101793. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  101794. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  101795. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  101796. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  101797. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  101798. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  101799. testcase( pCol->affinity==SQLITE_AFF_REAL );
  101800. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  101801. len = sqlite3Strlen30(zType);
  101802. assert( pCol->affinity==SQLITE_AFF_BLOB
  101803. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  101804. memcpy(&zStmt[k], zType, len);
  101805. k += len;
  101806. assert( k<=n );
  101807. }
  101808. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  101809. return zStmt;
  101810. }
  101811. /*
  101812. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  101813. ** on success and SQLITE_NOMEM on an OOM error.
  101814. */
  101815. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  101816. char *zExtra;
  101817. int nByte;
  101818. if( pIdx->nColumn>=N ) return SQLITE_OK;
  101819. assert( pIdx->isResized==0 );
  101820. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  101821. zExtra = sqlite3DbMallocZero(db, nByte);
  101822. if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
  101823. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  101824. pIdx->azColl = (const char**)zExtra;
  101825. zExtra += sizeof(char*)*N;
  101826. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  101827. pIdx->aiColumn = (i16*)zExtra;
  101828. zExtra += sizeof(i16)*N;
  101829. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  101830. pIdx->aSortOrder = (u8*)zExtra;
  101831. pIdx->nColumn = N;
  101832. pIdx->isResized = 1;
  101833. return SQLITE_OK;
  101834. }
  101835. /*
  101836. ** Estimate the total row width for a table.
  101837. */
  101838. static void estimateTableWidth(Table *pTab){
  101839. unsigned wTable = 0;
  101840. const Column *pTabCol;
  101841. int i;
  101842. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  101843. wTable += pTabCol->szEst;
  101844. }
  101845. if( pTab->iPKey<0 ) wTable++;
  101846. pTab->szTabRow = sqlite3LogEst(wTable*4);
  101847. }
  101848. /*
  101849. ** Estimate the average size of a row for an index.
  101850. */
  101851. static void estimateIndexWidth(Index *pIdx){
  101852. unsigned wIndex = 0;
  101853. int i;
  101854. const Column *aCol = pIdx->pTable->aCol;
  101855. for(i=0; i<pIdx->nColumn; i++){
  101856. i16 x = pIdx->aiColumn[i];
  101857. assert( x<pIdx->pTable->nCol );
  101858. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  101859. }
  101860. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  101861. }
  101862. /* Return true if value x is found any of the first nCol entries of aiCol[]
  101863. */
  101864. static int hasColumn(const i16 *aiCol, int nCol, int x){
  101865. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  101866. return 0;
  101867. }
  101868. /* Recompute the colNotIdxed field of the Index.
  101869. **
  101870. ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
  101871. ** columns that are within the first 63 columns of the table. The
  101872. ** high-order bit of colNotIdxed is always 1. All unindexed columns
  101873. ** of the table have a 1.
  101874. **
  101875. ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
  101876. ** to determine if the index is covering index.
  101877. */
  101878. static void recomputeColumnsNotIndexed(Index *pIdx){
  101879. Bitmask m = 0;
  101880. int j;
  101881. for(j=pIdx->nColumn-1; j>=0; j--){
  101882. int x = pIdx->aiColumn[j];
  101883. if( x>=0 ){
  101884. testcase( x==BMS-1 );
  101885. testcase( x==BMS-2 );
  101886. if( x<BMS-1 ) m |= MASKBIT(x);
  101887. }
  101888. }
  101889. pIdx->colNotIdxed = ~m;
  101890. assert( (pIdx->colNotIdxed>>63)==1 );
  101891. }
  101892. /*
  101893. ** This routine runs at the end of parsing a CREATE TABLE statement that
  101894. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  101895. ** internal schema data structures and the generated VDBE code so that they
  101896. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  101897. ** Changes include:
  101898. **
  101899. ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  101900. ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
  101901. ** into BTREE_BLOBKEY.
  101902. ** (3) Bypass the creation of the sqlite_master table entry
  101903. ** for the PRIMARY KEY as the primary key index is now
  101904. ** identified by the sqlite_master table entry of the table itself.
  101905. ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
  101906. ** schema to the rootpage from the main table.
  101907. ** (5) Add all table columns to the PRIMARY KEY Index object
  101908. ** so that the PRIMARY KEY is a covering index. The surplus
  101909. ** columns are part of KeyInfo.nAllField and are not used for
  101910. ** sorting or lookup or uniqueness checks.
  101911. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  101912. ** indices with the PRIMARY KEY columns.
  101913. **
  101914. ** For virtual tables, only (1) is performed.
  101915. */
  101916. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  101917. Index *pIdx;
  101918. Index *pPk;
  101919. int nPk;
  101920. int i, j;
  101921. sqlite3 *db = pParse->db;
  101922. Vdbe *v = pParse->pVdbe;
  101923. /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
  101924. */
  101925. if( !db->init.imposterTable ){
  101926. for(i=0; i<pTab->nCol; i++){
  101927. if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
  101928. pTab->aCol[i].notNull = OE_Abort;
  101929. }
  101930. }
  101931. }
  101932. /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
  101933. ** into BTREE_BLOBKEY.
  101934. */
  101935. if( pParse->addrCrTab ){
  101936. assert( v );
  101937. sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
  101938. }
  101939. /* Locate the PRIMARY KEY index. Or, if this table was originally
  101940. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  101941. */
  101942. if( pTab->iPKey>=0 ){
  101943. ExprList *pList;
  101944. Token ipkToken;
  101945. sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
  101946. pList = sqlite3ExprListAppend(pParse, 0,
  101947. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  101948. if( pList==0 ) return;
  101949. pList->a[0].sortOrder = pParse->iPkSortOrder;
  101950. assert( pParse->pNewTable==pTab );
  101951. sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
  101952. SQLITE_IDXTYPE_PRIMARYKEY);
  101953. if( db->mallocFailed || pParse->nErr ) return;
  101954. pPk = sqlite3PrimaryKeyIndex(pTab);
  101955. pTab->iPKey = -1;
  101956. }else{
  101957. pPk = sqlite3PrimaryKeyIndex(pTab);
  101958. assert( pPk!=0 );
  101959. /*
  101960. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  101961. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  101962. ** code assumes the PRIMARY KEY contains no repeated columns.
  101963. */
  101964. for(i=j=1; i<pPk->nKeyCol; i++){
  101965. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  101966. pPk->nColumn--;
  101967. }else{
  101968. pPk->aiColumn[j++] = pPk->aiColumn[i];
  101969. }
  101970. }
  101971. pPk->nKeyCol = j;
  101972. }
  101973. assert( pPk!=0 );
  101974. pPk->isCovering = 1;
  101975. if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
  101976. nPk = pPk->nKeyCol;
  101977. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  101978. ** table entry. This is only required if currently generating VDBE
  101979. ** code for a CREATE TABLE (not when parsing one as part of reading
  101980. ** a database schema). */
  101981. if( v && pPk->tnum>0 ){
  101982. assert( db->init.busy==0 );
  101983. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  101984. }
  101985. /* The root page of the PRIMARY KEY is the table root page */
  101986. pPk->tnum = pTab->tnum;
  101987. /* Update the in-memory representation of all UNIQUE indices by converting
  101988. ** the final rowid column into one or more columns of the PRIMARY KEY.
  101989. */
  101990. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  101991. int n;
  101992. if( IsPrimaryKeyIndex(pIdx) ) continue;
  101993. for(i=n=0; i<nPk; i++){
  101994. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  101995. }
  101996. if( n==0 ){
  101997. /* This index is a superset of the primary key */
  101998. pIdx->nColumn = pIdx->nKeyCol;
  101999. continue;
  102000. }
  102001. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  102002. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  102003. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  102004. pIdx->aiColumn[j] = pPk->aiColumn[i];
  102005. pIdx->azColl[j] = pPk->azColl[i];
  102006. j++;
  102007. }
  102008. }
  102009. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  102010. assert( pIdx->nColumn>=j );
  102011. }
  102012. /* Add all table columns to the PRIMARY KEY index
  102013. */
  102014. if( nPk<pTab->nCol ){
  102015. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  102016. for(i=0, j=nPk; i<pTab->nCol; i++){
  102017. if( !hasColumn(pPk->aiColumn, j, i) ){
  102018. assert( j<pPk->nColumn );
  102019. pPk->aiColumn[j] = i;
  102020. pPk->azColl[j] = sqlite3StrBINARY;
  102021. j++;
  102022. }
  102023. }
  102024. assert( pPk->nColumn==j );
  102025. assert( pTab->nCol==j );
  102026. }else{
  102027. pPk->nColumn = pTab->nCol;
  102028. }
  102029. recomputeColumnsNotIndexed(pPk);
  102030. }
  102031. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102032. /*
  102033. ** Return true if zName is a shadow table name in the current database
  102034. ** connection.
  102035. **
  102036. ** zName is temporarily modified while this routine is running, but is
  102037. ** restored to its original value prior to this routine returning.
  102038. */
  102039. static int isShadowTableName(sqlite3 *db, char *zName){
  102040. char *zTail; /* Pointer to the last "_" in zName */
  102041. Table *pTab; /* Table that zName is a shadow of */
  102042. Module *pMod; /* Module for the virtual table */
  102043. zTail = strrchr(zName, '_');
  102044. if( zTail==0 ) return 0;
  102045. *zTail = 0;
  102046. pTab = sqlite3FindTable(db, zName, 0);
  102047. *zTail = '_';
  102048. if( pTab==0 ) return 0;
  102049. if( !IsVirtual(pTab) ) return 0;
  102050. pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
  102051. if( pMod==0 ) return 0;
  102052. if( pMod->pModule->iVersion<3 ) return 0;
  102053. if( pMod->pModule->xShadowName==0 ) return 0;
  102054. return pMod->pModule->xShadowName(zTail+1);
  102055. }
  102056. #else
  102057. # define isShadowTableName(x,y) 0
  102058. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  102059. /*
  102060. ** This routine is called to report the final ")" that terminates
  102061. ** a CREATE TABLE statement.
  102062. **
  102063. ** The table structure that other action routines have been building
  102064. ** is added to the internal hash tables, assuming no errors have
  102065. ** occurred.
  102066. **
  102067. ** An entry for the table is made in the master table on disk, unless
  102068. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  102069. ** it means we are reading the sqlite_master table because we just
  102070. ** connected to the database or because the sqlite_master table has
  102071. ** recently changed, so the entry for this table already exists in
  102072. ** the sqlite_master table. We do not want to create it again.
  102073. **
  102074. ** If the pSelect argument is not NULL, it means that this routine
  102075. ** was called to create a table generated from a
  102076. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  102077. ** the new table will match the result set of the SELECT.
  102078. */
  102079. SQLITE_PRIVATE void sqlite3EndTable(
  102080. Parse *pParse, /* Parse context */
  102081. Token *pCons, /* The ',' token after the last column defn. */
  102082. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  102083. u8 tabOpts, /* Extra table options. Usually 0. */
  102084. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  102085. ){
  102086. Table *p; /* The new table */
  102087. sqlite3 *db = pParse->db; /* The database connection */
  102088. int iDb; /* Database in which the table lives */
  102089. Index *pIdx; /* An implied index of the table */
  102090. if( pEnd==0 && pSelect==0 ){
  102091. return;
  102092. }
  102093. assert( !db->mallocFailed );
  102094. p = pParse->pNewTable;
  102095. if( p==0 ) return;
  102096. if( pSelect==0 && isShadowTableName(db, p->zName) ){
  102097. p->tabFlags |= TF_Shadow;
  102098. }
  102099. /* If the db->init.busy is 1 it means we are reading the SQL off the
  102100. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  102101. ** So do not write to the disk again. Extract the root page number
  102102. ** for the table from the db->init.newTnum field. (The page number
  102103. ** should have been put there by the sqliteOpenCb routine.)
  102104. **
  102105. ** If the root page number is 1, that means this is the sqlite_master
  102106. ** table itself. So mark it read-only.
  102107. */
  102108. if( db->init.busy ){
  102109. if( pSelect ){
  102110. sqlite3ErrorMsg(pParse, "");
  102111. return;
  102112. }
  102113. p->tnum = db->init.newTnum;
  102114. if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
  102115. }
  102116. assert( (p->tabFlags & TF_HasPrimaryKey)==0
  102117. || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
  102118. assert( (p->tabFlags & TF_HasPrimaryKey)!=0
  102119. || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
  102120. /* Special processing for WITHOUT ROWID Tables */
  102121. if( tabOpts & TF_WithoutRowid ){
  102122. if( (p->tabFlags & TF_Autoincrement) ){
  102123. sqlite3ErrorMsg(pParse,
  102124. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  102125. return;
  102126. }
  102127. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  102128. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  102129. }else{
  102130. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  102131. convertToWithoutRowidTable(pParse, p);
  102132. }
  102133. }
  102134. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  102135. #ifndef SQLITE_OMIT_CHECK
  102136. /* Resolve names in all CHECK constraint expressions.
  102137. */
  102138. if( p->pCheck ){
  102139. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  102140. }
  102141. #endif /* !defined(SQLITE_OMIT_CHECK) */
  102142. /* Estimate the average row size for the table and for all implied indices */
  102143. estimateTableWidth(p);
  102144. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  102145. estimateIndexWidth(pIdx);
  102146. }
  102147. /* If not initializing, then create a record for the new table
  102148. ** in the SQLITE_MASTER table of the database.
  102149. **
  102150. ** If this is a TEMPORARY table, write the entry into the auxiliary
  102151. ** file instead of into the main database file.
  102152. */
  102153. if( !db->init.busy ){
  102154. int n;
  102155. Vdbe *v;
  102156. char *zType; /* "view" or "table" */
  102157. char *zType2; /* "VIEW" or "TABLE" */
  102158. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  102159. v = sqlite3GetVdbe(pParse);
  102160. if( NEVER(v==0) ) return;
  102161. sqlite3VdbeAddOp1(v, OP_Close, 0);
  102162. /*
  102163. ** Initialize zType for the new view or table.
  102164. */
  102165. if( p->pSelect==0 ){
  102166. /* A regular table */
  102167. zType = "table";
  102168. zType2 = "TABLE";
  102169. #ifndef SQLITE_OMIT_VIEW
  102170. }else{
  102171. /* A view */
  102172. zType = "view";
  102173. zType2 = "VIEW";
  102174. #endif
  102175. }
  102176. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  102177. ** statement to populate the new table. The root-page number for the
  102178. ** new table is in register pParse->regRoot.
  102179. **
  102180. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  102181. ** suitable state to query for the column names and types to be used
  102182. ** by the new table.
  102183. **
  102184. ** A shared-cache write-lock is not required to write to the new table,
  102185. ** as a schema-lock must have already been obtained to create it. Since
  102186. ** a schema-lock excludes all other database users, the write-lock would
  102187. ** be redundant.
  102188. */
  102189. if( pSelect ){
  102190. SelectDest dest; /* Where the SELECT should store results */
  102191. int regYield; /* Register holding co-routine entry-point */
  102192. int addrTop; /* Top of the co-routine */
  102193. int regRec; /* A record to be insert into the new table */
  102194. int regRowid; /* Rowid of the next row to insert */
  102195. int addrInsLoop; /* Top of the loop for inserting rows */
  102196. Table *pSelTab; /* A table that describes the SELECT results */
  102197. regYield = ++pParse->nMem;
  102198. regRec = ++pParse->nMem;
  102199. regRowid = ++pParse->nMem;
  102200. assert(pParse->nTab==1);
  102201. sqlite3MayAbort(pParse);
  102202. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  102203. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  102204. pParse->nTab = 2;
  102205. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  102206. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  102207. if( pParse->nErr ) return;
  102208. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  102209. if( pSelTab==0 ) return;
  102210. assert( p->aCol==0 );
  102211. p->nCol = pSelTab->nCol;
  102212. p->aCol = pSelTab->aCol;
  102213. pSelTab->nCol = 0;
  102214. pSelTab->aCol = 0;
  102215. sqlite3DeleteTable(db, pSelTab);
  102216. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  102217. sqlite3Select(pParse, pSelect, &dest);
  102218. if( pParse->nErr ) return;
  102219. sqlite3VdbeEndCoroutine(v, regYield);
  102220. sqlite3VdbeJumpHere(v, addrTop - 1);
  102221. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  102222. VdbeCoverage(v);
  102223. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  102224. sqlite3TableAffinity(v, p, 0);
  102225. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  102226. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  102227. sqlite3VdbeGoto(v, addrInsLoop);
  102228. sqlite3VdbeJumpHere(v, addrInsLoop);
  102229. sqlite3VdbeAddOp1(v, OP_Close, 1);
  102230. }
  102231. /* Compute the complete text of the CREATE statement */
  102232. if( pSelect ){
  102233. zStmt = createTableStmt(db, p);
  102234. }else{
  102235. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  102236. n = (int)(pEnd2->z - pParse->sNameToken.z);
  102237. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  102238. zStmt = sqlite3MPrintf(db,
  102239. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  102240. );
  102241. }
  102242. /* A slot for the record has already been allocated in the
  102243. ** SQLITE_MASTER table. We just need to update that slot with all
  102244. ** the information we've collected.
  102245. */
  102246. sqlite3NestedParse(pParse,
  102247. "UPDATE %Q.%s "
  102248. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  102249. "WHERE rowid=#%d",
  102250. db->aDb[iDb].zDbSName, MASTER_NAME,
  102251. zType,
  102252. p->zName,
  102253. p->zName,
  102254. pParse->regRoot,
  102255. zStmt,
  102256. pParse->regRowid
  102257. );
  102258. sqlite3DbFree(db, zStmt);
  102259. sqlite3ChangeCookie(pParse, iDb);
  102260. #ifndef SQLITE_OMIT_AUTOINCREMENT
  102261. /* Check to see if we need to create an sqlite_sequence table for
  102262. ** keeping track of autoincrement keys.
  102263. */
  102264. if( (p->tabFlags & TF_Autoincrement)!=0 ){
  102265. Db *pDb = &db->aDb[iDb];
  102266. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  102267. if( pDb->pSchema->pSeqTab==0 ){
  102268. sqlite3NestedParse(pParse,
  102269. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  102270. pDb->zDbSName
  102271. );
  102272. }
  102273. }
  102274. #endif
  102275. /* Reparse everything to update our internal data structures */
  102276. sqlite3VdbeAddParseSchemaOp(v, iDb,
  102277. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  102278. }
  102279. /* Add the table to the in-memory representation of the database.
  102280. */
  102281. if( db->init.busy ){
  102282. Table *pOld;
  102283. Schema *pSchema = p->pSchema;
  102284. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  102285. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  102286. if( pOld ){
  102287. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  102288. sqlite3OomFault(db);
  102289. return;
  102290. }
  102291. pParse->pNewTable = 0;
  102292. db->mDbFlags |= DBFLAG_SchemaChange;
  102293. #ifndef SQLITE_OMIT_ALTERTABLE
  102294. if( !p->pSelect ){
  102295. const char *zName = (const char *)pParse->sNameToken.z;
  102296. int nName;
  102297. assert( !pSelect && pCons && pEnd );
  102298. if( pCons->z==0 ){
  102299. pCons = pEnd;
  102300. }
  102301. nName = (int)((const char *)pCons->z - zName);
  102302. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  102303. }
  102304. #endif
  102305. }
  102306. }
  102307. #ifndef SQLITE_OMIT_VIEW
  102308. /*
  102309. ** The parser calls this routine in order to create a new VIEW
  102310. */
  102311. SQLITE_PRIVATE void sqlite3CreateView(
  102312. Parse *pParse, /* The parsing context */
  102313. Token *pBegin, /* The CREATE token that begins the statement */
  102314. Token *pName1, /* The token that holds the name of the view */
  102315. Token *pName2, /* The token that holds the name of the view */
  102316. ExprList *pCNames, /* Optional list of view column names */
  102317. Select *pSelect, /* A SELECT statement that will become the new view */
  102318. int isTemp, /* TRUE for a TEMPORARY view */
  102319. int noErr /* Suppress error messages if VIEW already exists */
  102320. ){
  102321. Table *p;
  102322. int n;
  102323. const char *z;
  102324. Token sEnd;
  102325. DbFixer sFix;
  102326. Token *pName = 0;
  102327. int iDb;
  102328. sqlite3 *db = pParse->db;
  102329. if( pParse->nVar>0 ){
  102330. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  102331. goto create_view_fail;
  102332. }
  102333. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  102334. p = pParse->pNewTable;
  102335. if( p==0 || pParse->nErr ) goto create_view_fail;
  102336. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  102337. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  102338. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  102339. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  102340. /* Make a copy of the entire SELECT statement that defines the view.
  102341. ** This will force all the Expr.token.z values to be dynamically
  102342. ** allocated rather than point to the input string - which means that
  102343. ** they will persist after the current sqlite3_exec() call returns.
  102344. */
  102345. if( IN_RENAME_OBJECT ){
  102346. p->pSelect = pSelect;
  102347. pSelect = 0;
  102348. }else{
  102349. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  102350. }
  102351. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  102352. if( db->mallocFailed ) goto create_view_fail;
  102353. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  102354. ** the end.
  102355. */
  102356. sEnd = pParse->sLastToken;
  102357. assert( sEnd.z[0]!=0 || sEnd.n==0 );
  102358. if( sEnd.z[0]!=';' ){
  102359. sEnd.z += sEnd.n;
  102360. }
  102361. sEnd.n = 0;
  102362. n = (int)(sEnd.z - pBegin->z);
  102363. assert( n>0 );
  102364. z = pBegin->z;
  102365. while( sqlite3Isspace(z[n-1]) ){ n--; }
  102366. sEnd.z = &z[n-1];
  102367. sEnd.n = 1;
  102368. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  102369. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  102370. create_view_fail:
  102371. sqlite3SelectDelete(db, pSelect);
  102372. if( IN_RENAME_OBJECT ){
  102373. sqlite3RenameExprlistUnmap(pParse, pCNames);
  102374. }
  102375. sqlite3ExprListDelete(db, pCNames);
  102376. return;
  102377. }
  102378. #endif /* SQLITE_OMIT_VIEW */
  102379. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  102380. /*
  102381. ** The Table structure pTable is really a VIEW. Fill in the names of
  102382. ** the columns of the view in the pTable structure. Return the number
  102383. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  102384. */
  102385. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  102386. Table *pSelTab; /* A fake table from which we get the result set */
  102387. Select *pSel; /* Copy of the SELECT that implements the view */
  102388. int nErr = 0; /* Number of errors encountered */
  102389. int n; /* Temporarily holds the number of cursors assigned */
  102390. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  102391. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102392. int rc;
  102393. #endif
  102394. #ifndef SQLITE_OMIT_AUTHORIZATION
  102395. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  102396. #endif
  102397. assert( pTable );
  102398. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102399. db->nSchemaLock++;
  102400. rc = sqlite3VtabCallConnect(pParse, pTable);
  102401. db->nSchemaLock--;
  102402. if( rc ){
  102403. return 1;
  102404. }
  102405. if( IsVirtual(pTable) ) return 0;
  102406. #endif
  102407. #ifndef SQLITE_OMIT_VIEW
  102408. /* A positive nCol means the columns names for this view are
  102409. ** already known.
  102410. */
  102411. if( pTable->nCol>0 ) return 0;
  102412. /* A negative nCol is a special marker meaning that we are currently
  102413. ** trying to compute the column names. If we enter this routine with
  102414. ** a negative nCol, it means two or more views form a loop, like this:
  102415. **
  102416. ** CREATE VIEW one AS SELECT * FROM two;
  102417. ** CREATE VIEW two AS SELECT * FROM one;
  102418. **
  102419. ** Actually, the error above is now caught prior to reaching this point.
  102420. ** But the following test is still important as it does come up
  102421. ** in the following:
  102422. **
  102423. ** CREATE TABLE main.ex1(a);
  102424. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  102425. ** SELECT * FROM temp.ex1;
  102426. */
  102427. if( pTable->nCol<0 ){
  102428. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  102429. return 1;
  102430. }
  102431. assert( pTable->nCol>=0 );
  102432. /* If we get this far, it means we need to compute the table names.
  102433. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  102434. ** "*" elements in the results set of the view and will assign cursors
  102435. ** to the elements of the FROM clause. But we do not want these changes
  102436. ** to be permanent. So the computation is done on a copy of the SELECT
  102437. ** statement that defines the view.
  102438. */
  102439. assert( pTable->pSelect );
  102440. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  102441. if( pSel ){
  102442. #ifndef SQLITE_OMIT_ALTERTABLE
  102443. u8 eParseMode = pParse->eParseMode;
  102444. pParse->eParseMode = PARSE_MODE_NORMAL;
  102445. #endif
  102446. n = pParse->nTab;
  102447. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  102448. pTable->nCol = -1;
  102449. db->lookaside.bDisable++;
  102450. #ifndef SQLITE_OMIT_AUTHORIZATION
  102451. xAuth = db->xAuth;
  102452. db->xAuth = 0;
  102453. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  102454. db->xAuth = xAuth;
  102455. #else
  102456. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  102457. #endif
  102458. pParse->nTab = n;
  102459. if( pTable->pCheck ){
  102460. /* CREATE VIEW name(arglist) AS ...
  102461. ** The names of the columns in the table are taken from
  102462. ** arglist which is stored in pTable->pCheck. The pCheck field
  102463. ** normally holds CHECK constraints on an ordinary table, but for
  102464. ** a VIEW it holds the list of column names.
  102465. */
  102466. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  102467. &pTable->nCol, &pTable->aCol);
  102468. if( db->mallocFailed==0
  102469. && pParse->nErr==0
  102470. && pTable->nCol==pSel->pEList->nExpr
  102471. ){
  102472. sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
  102473. }
  102474. }else if( pSelTab ){
  102475. /* CREATE VIEW name AS... without an argument list. Construct
  102476. ** the column names from the SELECT statement that defines the view.
  102477. */
  102478. assert( pTable->aCol==0 );
  102479. pTable->nCol = pSelTab->nCol;
  102480. pTable->aCol = pSelTab->aCol;
  102481. pSelTab->nCol = 0;
  102482. pSelTab->aCol = 0;
  102483. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  102484. }else{
  102485. pTable->nCol = 0;
  102486. nErr++;
  102487. }
  102488. sqlite3DeleteTable(db, pSelTab);
  102489. sqlite3SelectDelete(db, pSel);
  102490. db->lookaside.bDisable--;
  102491. #ifndef SQLITE_OMIT_ALTERTABLE
  102492. pParse->eParseMode = eParseMode;
  102493. #endif
  102494. } else {
  102495. nErr++;
  102496. }
  102497. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  102498. if( db->mallocFailed ){
  102499. sqlite3DeleteColumnNames(db, pTable);
  102500. pTable->aCol = 0;
  102501. pTable->nCol = 0;
  102502. }
  102503. #endif /* SQLITE_OMIT_VIEW */
  102504. return nErr;
  102505. }
  102506. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  102507. #ifndef SQLITE_OMIT_VIEW
  102508. /*
  102509. ** Clear the column names from every VIEW in database idx.
  102510. */
  102511. static void sqliteViewResetAll(sqlite3 *db, int idx){
  102512. HashElem *i;
  102513. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  102514. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  102515. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  102516. Table *pTab = sqliteHashData(i);
  102517. if( pTab->pSelect ){
  102518. sqlite3DeleteColumnNames(db, pTab);
  102519. pTab->aCol = 0;
  102520. pTab->nCol = 0;
  102521. }
  102522. }
  102523. DbClearProperty(db, idx, DB_UnresetViews);
  102524. }
  102525. #else
  102526. # define sqliteViewResetAll(A,B)
  102527. #endif /* SQLITE_OMIT_VIEW */
  102528. /*
  102529. ** This function is called by the VDBE to adjust the internal schema
  102530. ** used by SQLite when the btree layer moves a table root page. The
  102531. ** root-page of a table or index in database iDb has changed from iFrom
  102532. ** to iTo.
  102533. **
  102534. ** Ticket #1728: The symbol table might still contain information
  102535. ** on tables and/or indices that are the process of being deleted.
  102536. ** If you are unlucky, one of those deleted indices or tables might
  102537. ** have the same rootpage number as the real table or index that is
  102538. ** being moved. So we cannot stop searching after the first match
  102539. ** because the first match might be for one of the deleted indices
  102540. ** or tables and not the table/index that is actually being moved.
  102541. ** We must continue looping until all tables and indices with
  102542. ** rootpage==iFrom have been converted to have a rootpage of iTo
  102543. ** in order to be certain that we got the right one.
  102544. */
  102545. #ifndef SQLITE_OMIT_AUTOVACUUM
  102546. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  102547. HashElem *pElem;
  102548. Hash *pHash;
  102549. Db *pDb;
  102550. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  102551. pDb = &db->aDb[iDb];
  102552. pHash = &pDb->pSchema->tblHash;
  102553. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  102554. Table *pTab = sqliteHashData(pElem);
  102555. if( pTab->tnum==iFrom ){
  102556. pTab->tnum = iTo;
  102557. }
  102558. }
  102559. pHash = &pDb->pSchema->idxHash;
  102560. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  102561. Index *pIdx = sqliteHashData(pElem);
  102562. if( pIdx->tnum==iFrom ){
  102563. pIdx->tnum = iTo;
  102564. }
  102565. }
  102566. }
  102567. #endif
  102568. /*
  102569. ** Write code to erase the table with root-page iTable from database iDb.
  102570. ** Also write code to modify the sqlite_master table and internal schema
  102571. ** if a root-page of another table is moved by the btree-layer whilst
  102572. ** erasing iTable (this can happen with an auto-vacuum database).
  102573. */
  102574. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  102575. Vdbe *v = sqlite3GetVdbe(pParse);
  102576. int r1 = sqlite3GetTempReg(pParse);
  102577. if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
  102578. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  102579. sqlite3MayAbort(pParse);
  102580. #ifndef SQLITE_OMIT_AUTOVACUUM
  102581. /* OP_Destroy stores an in integer r1. If this integer
  102582. ** is non-zero, then it is the root page number of a table moved to
  102583. ** location iTable. The following code modifies the sqlite_master table to
  102584. ** reflect this.
  102585. **
  102586. ** The "#NNN" in the SQL is a special constant that means whatever value
  102587. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  102588. ** token for additional information.
  102589. */
  102590. sqlite3NestedParse(pParse,
  102591. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  102592. pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
  102593. #endif
  102594. sqlite3ReleaseTempReg(pParse, r1);
  102595. }
  102596. /*
  102597. ** Write VDBE code to erase table pTab and all associated indices on disk.
  102598. ** Code to update the sqlite_master tables and internal schema definitions
  102599. ** in case a root-page belonging to another table is moved by the btree layer
  102600. ** is also added (this can happen with an auto-vacuum database).
  102601. */
  102602. static void destroyTable(Parse *pParse, Table *pTab){
  102603. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  102604. ** is not defined), then it is important to call OP_Destroy on the
  102605. ** table and index root-pages in order, starting with the numerically
  102606. ** largest root-page number. This guarantees that none of the root-pages
  102607. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  102608. ** following were coded:
  102609. **
  102610. ** OP_Destroy 4 0
  102611. ** ...
  102612. ** OP_Destroy 5 0
  102613. **
  102614. ** and root page 5 happened to be the largest root-page number in the
  102615. ** database, then root page 5 would be moved to page 4 by the
  102616. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  102617. ** a free-list page.
  102618. */
  102619. int iTab = pTab->tnum;
  102620. int iDestroyed = 0;
  102621. while( 1 ){
  102622. Index *pIdx;
  102623. int iLargest = 0;
  102624. if( iDestroyed==0 || iTab<iDestroyed ){
  102625. iLargest = iTab;
  102626. }
  102627. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  102628. int iIdx = pIdx->tnum;
  102629. assert( pIdx->pSchema==pTab->pSchema );
  102630. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  102631. iLargest = iIdx;
  102632. }
  102633. }
  102634. if( iLargest==0 ){
  102635. return;
  102636. }else{
  102637. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  102638. assert( iDb>=0 && iDb<pParse->db->nDb );
  102639. destroyRootPage(pParse, iLargest, iDb);
  102640. iDestroyed = iLargest;
  102641. }
  102642. }
  102643. }
  102644. /*
  102645. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  102646. ** after a DROP INDEX or DROP TABLE command.
  102647. */
  102648. static void sqlite3ClearStatTables(
  102649. Parse *pParse, /* The parsing context */
  102650. int iDb, /* The database number */
  102651. const char *zType, /* "idx" or "tbl" */
  102652. const char *zName /* Name of index or table */
  102653. ){
  102654. int i;
  102655. const char *zDbName = pParse->db->aDb[iDb].zDbSName;
  102656. for(i=1; i<=4; i++){
  102657. char zTab[24];
  102658. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  102659. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  102660. sqlite3NestedParse(pParse,
  102661. "DELETE FROM %Q.%s WHERE %s=%Q",
  102662. zDbName, zTab, zType, zName
  102663. );
  102664. }
  102665. }
  102666. }
  102667. /*
  102668. ** Generate code to drop a table.
  102669. */
  102670. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  102671. Vdbe *v;
  102672. sqlite3 *db = pParse->db;
  102673. Trigger *pTrigger;
  102674. Db *pDb = &db->aDb[iDb];
  102675. v = sqlite3GetVdbe(pParse);
  102676. assert( v!=0 );
  102677. sqlite3BeginWriteOperation(pParse, 1, iDb);
  102678. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102679. if( IsVirtual(pTab) ){
  102680. sqlite3VdbeAddOp0(v, OP_VBegin);
  102681. }
  102682. #endif
  102683. /* Drop all triggers associated with the table being dropped. Code
  102684. ** is generated to remove entries from sqlite_master and/or
  102685. ** sqlite_temp_master if required.
  102686. */
  102687. pTrigger = sqlite3TriggerList(pParse, pTab);
  102688. while( pTrigger ){
  102689. assert( pTrigger->pSchema==pTab->pSchema ||
  102690. pTrigger->pSchema==db->aDb[1].pSchema );
  102691. sqlite3DropTriggerPtr(pParse, pTrigger);
  102692. pTrigger = pTrigger->pNext;
  102693. }
  102694. #ifndef SQLITE_OMIT_AUTOINCREMENT
  102695. /* Remove any entries of the sqlite_sequence table associated with
  102696. ** the table being dropped. This is done before the table is dropped
  102697. ** at the btree level, in case the sqlite_sequence table needs to
  102698. ** move as a result of the drop (can happen in auto-vacuum mode).
  102699. */
  102700. if( pTab->tabFlags & TF_Autoincrement ){
  102701. sqlite3NestedParse(pParse,
  102702. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  102703. pDb->zDbSName, pTab->zName
  102704. );
  102705. }
  102706. #endif
  102707. /* Drop all SQLITE_MASTER table and index entries that refer to the
  102708. ** table. The program name loops through the master table and deletes
  102709. ** every row that refers to a table of the same name as the one being
  102710. ** dropped. Triggers are handled separately because a trigger can be
  102711. ** created in the temp database that refers to a table in another
  102712. ** database.
  102713. */
  102714. sqlite3NestedParse(pParse,
  102715. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  102716. pDb->zDbSName, MASTER_NAME, pTab->zName);
  102717. if( !isView && !IsVirtual(pTab) ){
  102718. destroyTable(pParse, pTab);
  102719. }
  102720. /* Remove the table entry from SQLite's internal schema and modify
  102721. ** the schema cookie.
  102722. */
  102723. if( IsVirtual(pTab) ){
  102724. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  102725. sqlite3MayAbort(pParse);
  102726. }
  102727. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  102728. sqlite3ChangeCookie(pParse, iDb);
  102729. sqliteViewResetAll(db, iDb);
  102730. }
  102731. /*
  102732. ** This routine is called to do the work of a DROP TABLE statement.
  102733. ** pName is the name of the table to be dropped.
  102734. */
  102735. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  102736. Table *pTab;
  102737. Vdbe *v;
  102738. sqlite3 *db = pParse->db;
  102739. int iDb;
  102740. if( db->mallocFailed ){
  102741. goto exit_drop_table;
  102742. }
  102743. assert( pParse->nErr==0 );
  102744. assert( pName->nSrc==1 );
  102745. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  102746. if( noErr ) db->suppressErr++;
  102747. assert( isView==0 || isView==LOCATE_VIEW );
  102748. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  102749. if( noErr ) db->suppressErr--;
  102750. if( pTab==0 ){
  102751. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  102752. goto exit_drop_table;
  102753. }
  102754. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102755. assert( iDb>=0 && iDb<db->nDb );
  102756. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  102757. ** it is initialized.
  102758. */
  102759. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  102760. goto exit_drop_table;
  102761. }
  102762. #ifndef SQLITE_OMIT_AUTHORIZATION
  102763. {
  102764. int code;
  102765. const char *zTab = SCHEMA_TABLE(iDb);
  102766. const char *zDb = db->aDb[iDb].zDbSName;
  102767. const char *zArg2 = 0;
  102768. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  102769. goto exit_drop_table;
  102770. }
  102771. if( isView ){
  102772. if( !OMIT_TEMPDB && iDb==1 ){
  102773. code = SQLITE_DROP_TEMP_VIEW;
  102774. }else{
  102775. code = SQLITE_DROP_VIEW;
  102776. }
  102777. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102778. }else if( IsVirtual(pTab) ){
  102779. code = SQLITE_DROP_VTABLE;
  102780. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  102781. #endif
  102782. }else{
  102783. if( !OMIT_TEMPDB && iDb==1 ){
  102784. code = SQLITE_DROP_TEMP_TABLE;
  102785. }else{
  102786. code = SQLITE_DROP_TABLE;
  102787. }
  102788. }
  102789. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  102790. goto exit_drop_table;
  102791. }
  102792. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  102793. goto exit_drop_table;
  102794. }
  102795. }
  102796. #endif
  102797. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  102798. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  102799. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  102800. goto exit_drop_table;
  102801. }
  102802. #ifndef SQLITE_OMIT_VIEW
  102803. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  102804. ** on a table.
  102805. */
  102806. if( isView && pTab->pSelect==0 ){
  102807. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  102808. goto exit_drop_table;
  102809. }
  102810. if( !isView && pTab->pSelect ){
  102811. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  102812. goto exit_drop_table;
  102813. }
  102814. #endif
  102815. /* Generate code to remove the table from the master table
  102816. ** on disk.
  102817. */
  102818. v = sqlite3GetVdbe(pParse);
  102819. if( v ){
  102820. sqlite3BeginWriteOperation(pParse, 1, iDb);
  102821. if( !isView ){
  102822. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  102823. sqlite3FkDropTable(pParse, pName, pTab);
  102824. }
  102825. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  102826. }
  102827. exit_drop_table:
  102828. sqlite3SrcListDelete(db, pName);
  102829. }
  102830. /*
  102831. ** This routine is called to create a new foreign key on the table
  102832. ** currently under construction. pFromCol determines which columns
  102833. ** in the current table point to the foreign key. If pFromCol==0 then
  102834. ** connect the key to the last column inserted. pTo is the name of
  102835. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  102836. ** of tables in the parent pTo table. flags contains all
  102837. ** information about the conflict resolution algorithms specified
  102838. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  102839. **
  102840. ** An FKey structure is created and added to the table currently
  102841. ** under construction in the pParse->pNewTable field.
  102842. **
  102843. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  102844. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  102845. */
  102846. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  102847. Parse *pParse, /* Parsing context */
  102848. ExprList *pFromCol, /* Columns in this table that point to other table */
  102849. Token *pTo, /* Name of the other table */
  102850. ExprList *pToCol, /* Columns in the other table */
  102851. int flags /* Conflict resolution algorithms. */
  102852. ){
  102853. sqlite3 *db = pParse->db;
  102854. #ifndef SQLITE_OMIT_FOREIGN_KEY
  102855. FKey *pFKey = 0;
  102856. FKey *pNextTo;
  102857. Table *p = pParse->pNewTable;
  102858. int nByte;
  102859. int i;
  102860. int nCol;
  102861. char *z;
  102862. assert( pTo!=0 );
  102863. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  102864. if( pFromCol==0 ){
  102865. int iCol = p->nCol-1;
  102866. if( NEVER(iCol<0) ) goto fk_end;
  102867. if( pToCol && pToCol->nExpr!=1 ){
  102868. sqlite3ErrorMsg(pParse, "foreign key on %s"
  102869. " should reference only one column of table %T",
  102870. p->aCol[iCol].zName, pTo);
  102871. goto fk_end;
  102872. }
  102873. nCol = 1;
  102874. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  102875. sqlite3ErrorMsg(pParse,
  102876. "number of columns in foreign key does not match the number of "
  102877. "columns in the referenced table");
  102878. goto fk_end;
  102879. }else{
  102880. nCol = pFromCol->nExpr;
  102881. }
  102882. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  102883. if( pToCol ){
  102884. for(i=0; i<pToCol->nExpr; i++){
  102885. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  102886. }
  102887. }
  102888. pFKey = sqlite3DbMallocZero(db, nByte );
  102889. if( pFKey==0 ){
  102890. goto fk_end;
  102891. }
  102892. pFKey->pFrom = p;
  102893. pFKey->pNextFrom = p->pFKey;
  102894. z = (char*)&pFKey->aCol[nCol];
  102895. pFKey->zTo = z;
  102896. if( IN_RENAME_OBJECT ){
  102897. sqlite3RenameTokenMap(pParse, (void*)z, pTo);
  102898. }
  102899. memcpy(z, pTo->z, pTo->n);
  102900. z[pTo->n] = 0;
  102901. sqlite3Dequote(z);
  102902. z += pTo->n+1;
  102903. pFKey->nCol = nCol;
  102904. if( pFromCol==0 ){
  102905. pFKey->aCol[0].iFrom = p->nCol-1;
  102906. }else{
  102907. for(i=0; i<nCol; i++){
  102908. int j;
  102909. for(j=0; j<p->nCol; j++){
  102910. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  102911. pFKey->aCol[i].iFrom = j;
  102912. break;
  102913. }
  102914. }
  102915. if( j>=p->nCol ){
  102916. sqlite3ErrorMsg(pParse,
  102917. "unknown column \"%s\" in foreign key definition",
  102918. pFromCol->a[i].zName);
  102919. goto fk_end;
  102920. }
  102921. if( IN_RENAME_OBJECT ){
  102922. sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zName);
  102923. }
  102924. }
  102925. }
  102926. if( pToCol ){
  102927. for(i=0; i<nCol; i++){
  102928. int n = sqlite3Strlen30(pToCol->a[i].zName);
  102929. pFKey->aCol[i].zCol = z;
  102930. if( IN_RENAME_OBJECT ){
  102931. sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zName);
  102932. }
  102933. memcpy(z, pToCol->a[i].zName, n);
  102934. z[n] = 0;
  102935. z += n+1;
  102936. }
  102937. }
  102938. pFKey->isDeferred = 0;
  102939. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  102940. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  102941. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  102942. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  102943. pFKey->zTo, (void *)pFKey
  102944. );
  102945. if( pNextTo==pFKey ){
  102946. sqlite3OomFault(db);
  102947. goto fk_end;
  102948. }
  102949. if( pNextTo ){
  102950. assert( pNextTo->pPrevTo==0 );
  102951. pFKey->pNextTo = pNextTo;
  102952. pNextTo->pPrevTo = pFKey;
  102953. }
  102954. /* Link the foreign key to the table as the last step.
  102955. */
  102956. p->pFKey = pFKey;
  102957. pFKey = 0;
  102958. fk_end:
  102959. sqlite3DbFree(db, pFKey);
  102960. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  102961. sqlite3ExprListDelete(db, pFromCol);
  102962. sqlite3ExprListDelete(db, pToCol);
  102963. }
  102964. /*
  102965. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  102966. ** clause is seen as part of a foreign key definition. The isDeferred
  102967. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  102968. ** The behavior of the most recently created foreign key is adjusted
  102969. ** accordingly.
  102970. */
  102971. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  102972. #ifndef SQLITE_OMIT_FOREIGN_KEY
  102973. Table *pTab;
  102974. FKey *pFKey;
  102975. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  102976. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  102977. pFKey->isDeferred = (u8)isDeferred;
  102978. #endif
  102979. }
  102980. /*
  102981. ** Generate code that will erase and refill index *pIdx. This is
  102982. ** used to initialize a newly created index or to recompute the
  102983. ** content of an index in response to a REINDEX command.
  102984. **
  102985. ** if memRootPage is not negative, it means that the index is newly
  102986. ** created. The register specified by memRootPage contains the
  102987. ** root page number of the index. If memRootPage is negative, then
  102988. ** the index already exists and must be cleared before being refilled and
  102989. ** the root page number of the index is taken from pIndex->tnum.
  102990. */
  102991. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  102992. Table *pTab = pIndex->pTable; /* The table that is indexed */
  102993. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  102994. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  102995. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  102996. int addr1; /* Address of top of loop */
  102997. int addr2; /* Address to jump to for next iteration */
  102998. int tnum; /* Root page of index */
  102999. int iPartIdxLabel; /* Jump to this label to skip a row */
  103000. Vdbe *v; /* Generate code into this virtual machine */
  103001. KeyInfo *pKey; /* KeyInfo for index */
  103002. int regRecord; /* Register holding assembled index record */
  103003. sqlite3 *db = pParse->db; /* The database connection */
  103004. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  103005. #ifndef SQLITE_OMIT_AUTHORIZATION
  103006. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  103007. db->aDb[iDb].zDbSName ) ){
  103008. return;
  103009. }
  103010. #endif
  103011. /* Require a write-lock on the table to perform this operation */
  103012. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  103013. v = sqlite3GetVdbe(pParse);
  103014. if( v==0 ) return;
  103015. if( memRootPage>=0 ){
  103016. tnum = memRootPage;
  103017. }else{
  103018. tnum = pIndex->tnum;
  103019. }
  103020. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  103021. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  103022. /* Open the sorter cursor if we are to use one. */
  103023. iSorter = pParse->nTab++;
  103024. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  103025. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  103026. /* Open the table. Loop through all rows of the table, inserting index
  103027. ** records into the sorter. */
  103028. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  103029. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  103030. regRecord = sqlite3GetTempReg(pParse);
  103031. sqlite3MultiWrite(pParse);
  103032. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  103033. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  103034. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  103035. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  103036. sqlite3VdbeJumpHere(v, addr1);
  103037. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  103038. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  103039. (char *)pKey, P4_KEYINFO);
  103040. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  103041. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  103042. if( IsUniqueIndex(pIndex) ){
  103043. int j2 = sqlite3VdbeGoto(v, 1);
  103044. addr2 = sqlite3VdbeCurrentAddr(v);
  103045. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  103046. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  103047. pIndex->nKeyCol); VdbeCoverage(v);
  103048. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  103049. sqlite3VdbeJumpHere(v, j2);
  103050. }else{
  103051. addr2 = sqlite3VdbeCurrentAddr(v);
  103052. }
  103053. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  103054. sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
  103055. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  103056. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  103057. sqlite3ReleaseTempReg(pParse, regRecord);
  103058. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  103059. sqlite3VdbeJumpHere(v, addr1);
  103060. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  103061. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  103062. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  103063. }
  103064. /*
  103065. ** Allocate heap space to hold an Index object with nCol columns.
  103066. **
  103067. ** Increase the allocation size to provide an extra nExtra bytes
  103068. ** of 8-byte aligned space after the Index object and return a
  103069. ** pointer to this extra space in *ppExtra.
  103070. */
  103071. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  103072. sqlite3 *db, /* Database connection */
  103073. i16 nCol, /* Total number of columns in the index */
  103074. int nExtra, /* Number of bytes of extra space to alloc */
  103075. char **ppExtra /* Pointer to the "extra" space */
  103076. ){
  103077. Index *p; /* Allocated index object */
  103078. int nByte; /* Bytes of space for Index object + arrays */
  103079. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  103080. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  103081. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  103082. sizeof(i16)*nCol + /* Index.aiColumn */
  103083. sizeof(u8)*nCol); /* Index.aSortOrder */
  103084. p = sqlite3DbMallocZero(db, nByte + nExtra);
  103085. if( p ){
  103086. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  103087. p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  103088. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  103089. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  103090. p->aSortOrder = (u8*)pExtra;
  103091. p->nColumn = nCol;
  103092. p->nKeyCol = nCol - 1;
  103093. *ppExtra = ((char*)p) + nByte;
  103094. }
  103095. return p;
  103096. }
  103097. /*
  103098. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  103099. ** and pTblList is the name of the table that is to be indexed. Both will
  103100. ** be NULL for a primary key or an index that is created to satisfy a
  103101. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  103102. ** as the table to be indexed. pParse->pNewTable is a table that is
  103103. ** currently being constructed by a CREATE TABLE statement.
  103104. **
  103105. ** pList is a list of columns to be indexed. pList will be NULL if this
  103106. ** is a primary key or unique-constraint on the most recent column added
  103107. ** to the table currently under construction.
  103108. */
  103109. SQLITE_PRIVATE void sqlite3CreateIndex(
  103110. Parse *pParse, /* All information about this parse */
  103111. Token *pName1, /* First part of index name. May be NULL */
  103112. Token *pName2, /* Second part of index name. May be NULL */
  103113. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  103114. ExprList *pList, /* A list of columns to be indexed */
  103115. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  103116. Token *pStart, /* The CREATE token that begins this statement */
  103117. Expr *pPIWhere, /* WHERE clause for partial indices */
  103118. int sortOrder, /* Sort order of primary key when pList==NULL */
  103119. int ifNotExist, /* Omit error if index already exists */
  103120. u8 idxType /* The index type */
  103121. ){
  103122. Table *pTab = 0; /* Table to be indexed */
  103123. Index *pIndex = 0; /* The index to be created */
  103124. char *zName = 0; /* Name of the index */
  103125. int nName; /* Number of characters in zName */
  103126. int i, j;
  103127. DbFixer sFix; /* For assigning database names to pTable */
  103128. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  103129. sqlite3 *db = pParse->db;
  103130. Db *pDb; /* The specific table containing the indexed database */
  103131. int iDb; /* Index of the database that is being written */
  103132. Token *pName = 0; /* Unqualified name of the index to create */
  103133. struct ExprList_item *pListItem; /* For looping over pList */
  103134. int nExtra = 0; /* Space allocated for zExtra[] */
  103135. int nExtraCol; /* Number of extra columns needed */
  103136. char *zExtra = 0; /* Extra space after the Index object */
  103137. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  103138. if( db->mallocFailed || pParse->nErr>0 ){
  103139. goto exit_create_index;
  103140. }
  103141. if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
  103142. goto exit_create_index;
  103143. }
  103144. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  103145. goto exit_create_index;
  103146. }
  103147. /*
  103148. ** Find the table that is to be indexed. Return early if not found.
  103149. */
  103150. if( pTblName!=0 ){
  103151. /* Use the two-part index name to determine the database
  103152. ** to search for the table. 'Fix' the table name to this db
  103153. ** before looking up the table.
  103154. */
  103155. assert( pName1 && pName2 );
  103156. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  103157. if( iDb<0 ) goto exit_create_index;
  103158. assert( pName && pName->z );
  103159. #ifndef SQLITE_OMIT_TEMPDB
  103160. /* If the index name was unqualified, check if the table
  103161. ** is a temp table. If so, set the database to 1. Do not do this
  103162. ** if initialising a database schema.
  103163. */
  103164. if( !db->init.busy ){
  103165. pTab = sqlite3SrcListLookup(pParse, pTblName);
  103166. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  103167. iDb = 1;
  103168. }
  103169. }
  103170. #endif
  103171. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  103172. if( sqlite3FixSrcList(&sFix, pTblName) ){
  103173. /* Because the parser constructs pTblName from a single identifier,
  103174. ** sqlite3FixSrcList can never fail. */
  103175. assert(0);
  103176. }
  103177. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  103178. assert( db->mallocFailed==0 || pTab==0 );
  103179. if( pTab==0 ) goto exit_create_index;
  103180. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  103181. sqlite3ErrorMsg(pParse,
  103182. "cannot create a TEMP index on non-TEMP table \"%s\"",
  103183. pTab->zName);
  103184. goto exit_create_index;
  103185. }
  103186. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  103187. }else{
  103188. assert( pName==0 );
  103189. assert( pStart==0 );
  103190. pTab = pParse->pNewTable;
  103191. if( !pTab ) goto exit_create_index;
  103192. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  103193. }
  103194. pDb = &db->aDb[iDb];
  103195. assert( pTab!=0 );
  103196. assert( pParse->nErr==0 );
  103197. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  103198. && db->init.busy==0
  103199. && pTblName!=0
  103200. #if SQLITE_USER_AUTHENTICATION
  103201. && sqlite3UserAuthTable(pTab->zName)==0
  103202. #endif
  103203. #ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
  103204. && sqlite3StrICmp(&pTab->zName[7],"master")!=0
  103205. #endif
  103206. ){
  103207. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  103208. goto exit_create_index;
  103209. }
  103210. #ifndef SQLITE_OMIT_VIEW
  103211. if( pTab->pSelect ){
  103212. sqlite3ErrorMsg(pParse, "views may not be indexed");
  103213. goto exit_create_index;
  103214. }
  103215. #endif
  103216. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103217. if( IsVirtual(pTab) ){
  103218. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  103219. goto exit_create_index;
  103220. }
  103221. #endif
  103222. /*
  103223. ** Find the name of the index. Make sure there is not already another
  103224. ** index or table with the same name.
  103225. **
  103226. ** Exception: If we are reading the names of permanent indices from the
  103227. ** sqlite_master table (because some other process changed the schema) and
  103228. ** one of the index names collides with the name of a temporary table or
  103229. ** index, then we will continue to process this index.
  103230. **
  103231. ** If pName==0 it means that we are
  103232. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  103233. ** own name.
  103234. */
  103235. if( pName ){
  103236. zName = sqlite3NameFromToken(db, pName);
  103237. if( zName==0 ) goto exit_create_index;
  103238. assert( pName->z!=0 );
  103239. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  103240. goto exit_create_index;
  103241. }
  103242. if( !IN_RENAME_OBJECT ){
  103243. if( !db->init.busy ){
  103244. if( sqlite3FindTable(db, zName, 0)!=0 ){
  103245. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  103246. goto exit_create_index;
  103247. }
  103248. }
  103249. if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
  103250. if( !ifNotExist ){
  103251. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  103252. }else{
  103253. assert( !db->init.busy );
  103254. sqlite3CodeVerifySchema(pParse, iDb);
  103255. }
  103256. goto exit_create_index;
  103257. }
  103258. }
  103259. }else{
  103260. int n;
  103261. Index *pLoop;
  103262. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  103263. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  103264. if( zName==0 ){
  103265. goto exit_create_index;
  103266. }
  103267. /* Automatic index names generated from within sqlite3_declare_vtab()
  103268. ** must have names that are distinct from normal automatic index names.
  103269. ** The following statement converts "sqlite3_autoindex..." into
  103270. ** "sqlite3_butoindex..." in order to make the names distinct.
  103271. ** The "vtab_err.test" test demonstrates the need of this statement. */
  103272. if( IN_SPECIAL_PARSE ) zName[7]++;
  103273. }
  103274. /* Check for authorization to create an index.
  103275. */
  103276. #ifndef SQLITE_OMIT_AUTHORIZATION
  103277. if( !IN_RENAME_OBJECT ){
  103278. const char *zDb = pDb->zDbSName;
  103279. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  103280. goto exit_create_index;
  103281. }
  103282. i = SQLITE_CREATE_INDEX;
  103283. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  103284. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  103285. goto exit_create_index;
  103286. }
  103287. }
  103288. #endif
  103289. /* If pList==0, it means this routine was called to make a primary
  103290. ** key out of the last column added to the table under construction.
  103291. ** So create a fake list to simulate this.
  103292. */
  103293. if( pList==0 ){
  103294. Token prevCol;
  103295. Column *pCol = &pTab->aCol[pTab->nCol-1];
  103296. pCol->colFlags |= COLFLAG_UNIQUE;
  103297. sqlite3TokenInit(&prevCol, pCol->zName);
  103298. pList = sqlite3ExprListAppend(pParse, 0,
  103299. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  103300. if( pList==0 ) goto exit_create_index;
  103301. assert( pList->nExpr==1 );
  103302. sqlite3ExprListSetSortOrder(pList, sortOrder);
  103303. }else{
  103304. sqlite3ExprListCheckLength(pParse, pList, "index");
  103305. if( pParse->nErr ) goto exit_create_index;
  103306. }
  103307. /* Figure out how many bytes of space are required to store explicitly
  103308. ** specified collation sequence names.
  103309. */
  103310. for(i=0; i<pList->nExpr; i++){
  103311. Expr *pExpr = pList->a[i].pExpr;
  103312. assert( pExpr!=0 );
  103313. if( pExpr->op==TK_COLLATE ){
  103314. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  103315. }
  103316. }
  103317. /*
  103318. ** Allocate the index structure.
  103319. */
  103320. nName = sqlite3Strlen30(zName);
  103321. nExtraCol = pPk ? pPk->nKeyCol : 1;
  103322. assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
  103323. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  103324. nName + nExtra + 1, &zExtra);
  103325. if( db->mallocFailed ){
  103326. goto exit_create_index;
  103327. }
  103328. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  103329. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  103330. pIndex->zName = zExtra;
  103331. zExtra += nName + 1;
  103332. memcpy(pIndex->zName, zName, nName+1);
  103333. pIndex->pTable = pTab;
  103334. pIndex->onError = (u8)onError;
  103335. pIndex->uniqNotNull = onError!=OE_None;
  103336. pIndex->idxType = idxType;
  103337. pIndex->pSchema = db->aDb[iDb].pSchema;
  103338. pIndex->nKeyCol = pList->nExpr;
  103339. if( pPIWhere ){
  103340. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  103341. pIndex->pPartIdxWhere = pPIWhere;
  103342. pPIWhere = 0;
  103343. }
  103344. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  103345. /* Check to see if we should honor DESC requests on index columns
  103346. */
  103347. if( pDb->pSchema->file_format>=4 ){
  103348. sortOrderMask = -1; /* Honor DESC */
  103349. }else{
  103350. sortOrderMask = 0; /* Ignore DESC */
  103351. }
  103352. /* Analyze the list of expressions that form the terms of the index and
  103353. ** report any errors. In the common case where the expression is exactly
  103354. ** a table column, store that column in aiColumn[]. For general expressions,
  103355. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  103356. **
  103357. ** TODO: Issue a warning if two or more columns of the index are identical.
  103358. ** TODO: Issue a warning if the table primary key is used as part of the
  103359. ** index key.
  103360. */
  103361. pListItem = pList->a;
  103362. if( IN_RENAME_OBJECT ){
  103363. pIndex->aColExpr = pList;
  103364. pList = 0;
  103365. }
  103366. for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
  103367. Expr *pCExpr; /* The i-th index expression */
  103368. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  103369. const char *zColl; /* Collation sequence name */
  103370. sqlite3StringToId(pListItem->pExpr);
  103371. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  103372. if( pParse->nErr ) goto exit_create_index;
  103373. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  103374. if( pCExpr->op!=TK_COLUMN ){
  103375. if( pTab==pParse->pNewTable ){
  103376. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  103377. "UNIQUE constraints");
  103378. goto exit_create_index;
  103379. }
  103380. if( pIndex->aColExpr==0 ){
  103381. pIndex->aColExpr = pList;
  103382. pList = 0;
  103383. }
  103384. j = XN_EXPR;
  103385. pIndex->aiColumn[i] = XN_EXPR;
  103386. pIndex->uniqNotNull = 0;
  103387. }else{
  103388. j = pCExpr->iColumn;
  103389. assert( j<=0x7fff );
  103390. if( j<0 ){
  103391. j = pTab->iPKey;
  103392. }else if( pTab->aCol[j].notNull==0 ){
  103393. pIndex->uniqNotNull = 0;
  103394. }
  103395. pIndex->aiColumn[i] = (i16)j;
  103396. }
  103397. zColl = 0;
  103398. if( pListItem->pExpr->op==TK_COLLATE ){
  103399. int nColl;
  103400. zColl = pListItem->pExpr->u.zToken;
  103401. nColl = sqlite3Strlen30(zColl) + 1;
  103402. assert( nExtra>=nColl );
  103403. memcpy(zExtra, zColl, nColl);
  103404. zColl = zExtra;
  103405. zExtra += nColl;
  103406. nExtra -= nColl;
  103407. }else if( j>=0 ){
  103408. zColl = pTab->aCol[j].zColl;
  103409. }
  103410. if( !zColl ) zColl = sqlite3StrBINARY;
  103411. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  103412. goto exit_create_index;
  103413. }
  103414. pIndex->azColl[i] = zColl;
  103415. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  103416. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  103417. }
  103418. /* Append the table key to the end of the index. For WITHOUT ROWID
  103419. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  103420. ** normal tables (when pPk==0) this will be the rowid.
  103421. */
  103422. if( pPk ){
  103423. for(j=0; j<pPk->nKeyCol; j++){
  103424. int x = pPk->aiColumn[j];
  103425. assert( x>=0 );
  103426. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  103427. pIndex->nColumn--;
  103428. }else{
  103429. pIndex->aiColumn[i] = x;
  103430. pIndex->azColl[i] = pPk->azColl[j];
  103431. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  103432. i++;
  103433. }
  103434. }
  103435. assert( i==pIndex->nColumn );
  103436. }else{
  103437. pIndex->aiColumn[i] = XN_ROWID;
  103438. pIndex->azColl[i] = sqlite3StrBINARY;
  103439. }
  103440. sqlite3DefaultRowEst(pIndex);
  103441. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  103442. /* If this index contains every column of its table, then mark
  103443. ** it as a covering index */
  103444. assert( HasRowid(pTab)
  103445. || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
  103446. recomputeColumnsNotIndexed(pIndex);
  103447. if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
  103448. pIndex->isCovering = 1;
  103449. for(j=0; j<pTab->nCol; j++){
  103450. if( j==pTab->iPKey ) continue;
  103451. if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
  103452. pIndex->isCovering = 0;
  103453. break;
  103454. }
  103455. }
  103456. if( pTab==pParse->pNewTable ){
  103457. /* This routine has been called to create an automatic index as a
  103458. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  103459. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  103460. ** i.e. one of:
  103461. **
  103462. ** CREATE TABLE t(x PRIMARY KEY, y);
  103463. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  103464. **
  103465. ** Either way, check to see if the table already has such an index. If
  103466. ** so, don't bother creating this one. This only applies to
  103467. ** automatically created indices. Users can do as they wish with
  103468. ** explicit indices.
  103469. **
  103470. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  103471. ** (and thus suppressing the second one) even if they have different
  103472. ** sort orders.
  103473. **
  103474. ** If there are different collating sequences or if the columns of
  103475. ** the constraint occur in different orders, then the constraints are
  103476. ** considered distinct and both result in separate indices.
  103477. */
  103478. Index *pIdx;
  103479. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  103480. int k;
  103481. assert( IsUniqueIndex(pIdx) );
  103482. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  103483. assert( IsUniqueIndex(pIndex) );
  103484. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  103485. for(k=0; k<pIdx->nKeyCol; k++){
  103486. const char *z1;
  103487. const char *z2;
  103488. assert( pIdx->aiColumn[k]>=0 );
  103489. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  103490. z1 = pIdx->azColl[k];
  103491. z2 = pIndex->azColl[k];
  103492. if( sqlite3StrICmp(z1, z2) ) break;
  103493. }
  103494. if( k==pIdx->nKeyCol ){
  103495. if( pIdx->onError!=pIndex->onError ){
  103496. /* This constraint creates the same index as a previous
  103497. ** constraint specified somewhere in the CREATE TABLE statement.
  103498. ** However the ON CONFLICT clauses are different. If both this
  103499. ** constraint and the previous equivalent constraint have explicit
  103500. ** ON CONFLICT clauses this is an error. Otherwise, use the
  103501. ** explicitly specified behavior for the index.
  103502. */
  103503. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  103504. sqlite3ErrorMsg(pParse,
  103505. "conflicting ON CONFLICT clauses specified", 0);
  103506. }
  103507. if( pIdx->onError==OE_Default ){
  103508. pIdx->onError = pIndex->onError;
  103509. }
  103510. }
  103511. if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
  103512. if( IN_RENAME_OBJECT ){
  103513. pIndex->pNext = pParse->pNewIndex;
  103514. pParse->pNewIndex = pIndex;
  103515. pIndex = 0;
  103516. }
  103517. goto exit_create_index;
  103518. }
  103519. }
  103520. }
  103521. if( !IN_RENAME_OBJECT ){
  103522. /* Link the new Index structure to its table and to the other
  103523. ** in-memory database structures.
  103524. */
  103525. assert( pParse->nErr==0 );
  103526. if( db->init.busy ){
  103527. Index *p;
  103528. assert( !IN_SPECIAL_PARSE );
  103529. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  103530. if( pTblName!=0 ){
  103531. pIndex->tnum = db->init.newTnum;
  103532. if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
  103533. sqlite3ErrorMsg(pParse, "invalid rootpage");
  103534. pParse->rc = SQLITE_CORRUPT_BKPT;
  103535. goto exit_create_index;
  103536. }
  103537. }
  103538. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  103539. pIndex->zName, pIndex);
  103540. if( p ){
  103541. assert( p==pIndex ); /* Malloc must have failed */
  103542. sqlite3OomFault(db);
  103543. goto exit_create_index;
  103544. }
  103545. db->mDbFlags |= DBFLAG_SchemaChange;
  103546. }
  103547. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  103548. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  103549. ** emit code to allocate the index rootpage on disk and make an entry for
  103550. ** the index in the sqlite_master table and populate the index with
  103551. ** content. But, do not do this if we are simply reading the sqlite_master
  103552. ** table to parse the schema, or if this index is the PRIMARY KEY index
  103553. ** of a WITHOUT ROWID table.
  103554. **
  103555. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  103556. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  103557. ** has just been created, it contains no data and the index initialization
  103558. ** step can be skipped.
  103559. */
  103560. else if( HasRowid(pTab) || pTblName!=0 ){
  103561. Vdbe *v;
  103562. char *zStmt;
  103563. int iMem = ++pParse->nMem;
  103564. v = sqlite3GetVdbe(pParse);
  103565. if( v==0 ) goto exit_create_index;
  103566. sqlite3BeginWriteOperation(pParse, 1, iDb);
  103567. /* Create the rootpage for the index using CreateIndex. But before
  103568. ** doing so, code a Noop instruction and store its address in
  103569. ** Index.tnum. This is required in case this index is actually a
  103570. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  103571. ** that case the convertToWithoutRowidTable() routine will replace
  103572. ** the Noop with a Goto to jump over the VDBE code generated below. */
  103573. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  103574. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
  103575. /* Gather the complete text of the CREATE INDEX statement into
  103576. ** the zStmt variable
  103577. */
  103578. if( pStart ){
  103579. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  103580. if( pName->z[n-1]==';' ) n--;
  103581. /* A named index with an explicit CREATE INDEX statement */
  103582. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  103583. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  103584. }else{
  103585. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  103586. /* zStmt = sqlite3MPrintf(""); */
  103587. zStmt = 0;
  103588. }
  103589. /* Add an entry in sqlite_master for this index
  103590. */
  103591. sqlite3NestedParse(pParse,
  103592. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  103593. db->aDb[iDb].zDbSName, MASTER_NAME,
  103594. pIndex->zName,
  103595. pTab->zName,
  103596. iMem,
  103597. zStmt
  103598. );
  103599. sqlite3DbFree(db, zStmt);
  103600. /* Fill the index with data and reparse the schema. Code an OP_Expire
  103601. ** to invalidate all pre-compiled statements.
  103602. */
  103603. if( pTblName ){
  103604. sqlite3RefillIndex(pParse, pIndex, iMem);
  103605. sqlite3ChangeCookie(pParse, iDb);
  103606. sqlite3VdbeAddParseSchemaOp(v, iDb,
  103607. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  103608. sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
  103609. }
  103610. sqlite3VdbeJumpHere(v, pIndex->tnum);
  103611. }
  103612. }
  103613. /* When adding an index to the list of indices for a table, make
  103614. ** sure all indices labeled OE_Replace come after all those labeled
  103615. ** OE_Ignore. This is necessary for the correct constraint check
  103616. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  103617. ** UPDATE and INSERT statements.
  103618. */
  103619. if( db->init.busy || pTblName==0 ){
  103620. if( onError!=OE_Replace || pTab->pIndex==0
  103621. || pTab->pIndex->onError==OE_Replace){
  103622. pIndex->pNext = pTab->pIndex;
  103623. pTab->pIndex = pIndex;
  103624. }else{
  103625. Index *pOther = pTab->pIndex;
  103626. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  103627. pOther = pOther->pNext;
  103628. }
  103629. pIndex->pNext = pOther->pNext;
  103630. pOther->pNext = pIndex;
  103631. }
  103632. pIndex = 0;
  103633. }
  103634. else if( IN_RENAME_OBJECT ){
  103635. assert( pParse->pNewIndex==0 );
  103636. pParse->pNewIndex = pIndex;
  103637. pIndex = 0;
  103638. }
  103639. /* Clean up before exiting */
  103640. exit_create_index:
  103641. if( pIndex ) sqlite3FreeIndex(db, pIndex);
  103642. sqlite3ExprDelete(db, pPIWhere);
  103643. sqlite3ExprListDelete(db, pList);
  103644. sqlite3SrcListDelete(db, pTblName);
  103645. sqlite3DbFree(db, zName);
  103646. }
  103647. /*
  103648. ** Fill the Index.aiRowEst[] array with default information - information
  103649. ** to be used when we have not run the ANALYZE command.
  103650. **
  103651. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  103652. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  103653. ** number of rows in the table that match any particular value of the
  103654. ** first column of the index. aiRowEst[2] is an estimate of the number
  103655. ** of rows that match any particular combination of the first 2 columns
  103656. ** of the index. And so forth. It must always be the case that
  103657. *
  103658. ** aiRowEst[N]<=aiRowEst[N-1]
  103659. ** aiRowEst[N]>=1
  103660. **
  103661. ** Apart from that, we have little to go on besides intuition as to
  103662. ** how aiRowEst[] should be initialized. The numbers generated here
  103663. ** are based on typical values found in actual indices.
  103664. */
  103665. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  103666. /* 10, 9, 8, 7, 6 */
  103667. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  103668. LogEst *a = pIdx->aiRowLogEst;
  103669. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  103670. int i;
  103671. /* Indexes with default row estimates should not have stat1 data */
  103672. assert( !pIdx->hasStat1 );
  103673. /* Set the first entry (number of rows in the index) to the estimated
  103674. ** number of rows in the table, or half the number of rows in the table
  103675. ** for a partial index. But do not let the estimate drop below 10. */
  103676. a[0] = pIdx->pTable->nRowLogEst;
  103677. if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
  103678. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  103679. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  103680. ** 6 and each subsequent value (if any) is 5. */
  103681. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  103682. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  103683. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  103684. }
  103685. assert( 0==sqlite3LogEst(1) );
  103686. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  103687. }
  103688. /*
  103689. ** This routine will drop an existing named index. This routine
  103690. ** implements the DROP INDEX statement.
  103691. */
  103692. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  103693. Index *pIndex;
  103694. Vdbe *v;
  103695. sqlite3 *db = pParse->db;
  103696. int iDb;
  103697. assert( pParse->nErr==0 ); /* Never called with prior errors */
  103698. if( db->mallocFailed ){
  103699. goto exit_drop_index;
  103700. }
  103701. assert( pName->nSrc==1 );
  103702. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  103703. goto exit_drop_index;
  103704. }
  103705. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  103706. if( pIndex==0 ){
  103707. if( !ifExists ){
  103708. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  103709. }else{
  103710. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  103711. }
  103712. pParse->checkSchema = 1;
  103713. goto exit_drop_index;
  103714. }
  103715. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  103716. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  103717. "or PRIMARY KEY constraint cannot be dropped", 0);
  103718. goto exit_drop_index;
  103719. }
  103720. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  103721. #ifndef SQLITE_OMIT_AUTHORIZATION
  103722. {
  103723. int code = SQLITE_DROP_INDEX;
  103724. Table *pTab = pIndex->pTable;
  103725. const char *zDb = db->aDb[iDb].zDbSName;
  103726. const char *zTab = SCHEMA_TABLE(iDb);
  103727. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  103728. goto exit_drop_index;
  103729. }
  103730. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  103731. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  103732. goto exit_drop_index;
  103733. }
  103734. }
  103735. #endif
  103736. /* Generate code to remove the index and from the master table */
  103737. v = sqlite3GetVdbe(pParse);
  103738. if( v ){
  103739. sqlite3BeginWriteOperation(pParse, 1, iDb);
  103740. sqlite3NestedParse(pParse,
  103741. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  103742. db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
  103743. );
  103744. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  103745. sqlite3ChangeCookie(pParse, iDb);
  103746. destroyRootPage(pParse, pIndex->tnum, iDb);
  103747. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  103748. }
  103749. exit_drop_index:
  103750. sqlite3SrcListDelete(db, pName);
  103751. }
  103752. /*
  103753. ** pArray is a pointer to an array of objects. Each object in the
  103754. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  103755. ** to extend the array so that there is space for a new object at the end.
  103756. **
  103757. ** When this function is called, *pnEntry contains the current size of
  103758. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  103759. ** in total).
  103760. **
  103761. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  103762. ** space allocated for the new object is zeroed, *pnEntry updated to
  103763. ** reflect the new size of the array and a pointer to the new allocation
  103764. ** returned. *pIdx is set to the index of the new array entry in this case.
  103765. **
  103766. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  103767. ** unchanged and a copy of pArray returned.
  103768. */
  103769. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  103770. sqlite3 *db, /* Connection to notify of malloc failures */
  103771. void *pArray, /* Array of objects. Might be reallocated */
  103772. int szEntry, /* Size of each object in the array */
  103773. int *pnEntry, /* Number of objects currently in use */
  103774. int *pIdx /* Write the index of a new slot here */
  103775. ){
  103776. char *z;
  103777. sqlite3_int64 n = *pIdx = *pnEntry;
  103778. if( (n & (n-1))==0 ){
  103779. sqlite3_int64 sz = (n==0) ? 1 : 2*n;
  103780. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  103781. if( pNew==0 ){
  103782. *pIdx = -1;
  103783. return pArray;
  103784. }
  103785. pArray = pNew;
  103786. }
  103787. z = (char*)pArray;
  103788. memset(&z[n * szEntry], 0, szEntry);
  103789. ++*pnEntry;
  103790. return pArray;
  103791. }
  103792. /*
  103793. ** Append a new element to the given IdList. Create a new IdList if
  103794. ** need be.
  103795. **
  103796. ** A new IdList is returned, or NULL if malloc() fails.
  103797. */
  103798. SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
  103799. sqlite3 *db = pParse->db;
  103800. int i;
  103801. if( pList==0 ){
  103802. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  103803. if( pList==0 ) return 0;
  103804. }
  103805. pList->a = sqlite3ArrayAllocate(
  103806. db,
  103807. pList->a,
  103808. sizeof(pList->a[0]),
  103809. &pList->nId,
  103810. &i
  103811. );
  103812. if( i<0 ){
  103813. sqlite3IdListDelete(db, pList);
  103814. return 0;
  103815. }
  103816. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  103817. if( IN_RENAME_OBJECT && pList->a[i].zName ){
  103818. sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
  103819. }
  103820. return pList;
  103821. }
  103822. /*
  103823. ** Delete an IdList.
  103824. */
  103825. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  103826. int i;
  103827. if( pList==0 ) return;
  103828. for(i=0; i<pList->nId; i++){
  103829. sqlite3DbFree(db, pList->a[i].zName);
  103830. }
  103831. sqlite3DbFree(db, pList->a);
  103832. sqlite3DbFreeNN(db, pList);
  103833. }
  103834. /*
  103835. ** Return the index in pList of the identifier named zId. Return -1
  103836. ** if not found.
  103837. */
  103838. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  103839. int i;
  103840. if( pList==0 ) return -1;
  103841. for(i=0; i<pList->nId; i++){
  103842. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  103843. }
  103844. return -1;
  103845. }
  103846. /*
  103847. ** Maximum size of a SrcList object.
  103848. ** The SrcList object is used to represent the FROM clause of a
  103849. ** SELECT statement, and the query planner cannot deal with more
  103850. ** than 64 tables in a join. So any value larger than 64 here
  103851. ** is sufficient for most uses. Smaller values, like say 10, are
  103852. ** appropriate for small and memory-limited applications.
  103853. */
  103854. #ifndef SQLITE_MAX_SRCLIST
  103855. # define SQLITE_MAX_SRCLIST 200
  103856. #endif
  103857. /*
  103858. ** Expand the space allocated for the given SrcList object by
  103859. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  103860. ** New slots are zeroed.
  103861. **
  103862. ** For example, suppose a SrcList initially contains two entries: A,B.
  103863. ** To append 3 new entries onto the end, do this:
  103864. **
  103865. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  103866. **
  103867. ** After the call above it would contain: A, B, nil, nil, nil.
  103868. ** If the iStart argument had been 1 instead of 2, then the result
  103869. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  103870. ** the iStart value would be 0. The result then would
  103871. ** be: nil, nil, nil, A, B.
  103872. **
  103873. ** If a memory allocation fails or the SrcList becomes too large, leave
  103874. ** the original SrcList unchanged, return NULL, and leave an error message
  103875. ** in pParse.
  103876. */
  103877. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  103878. Parse *pParse, /* Parsing context into which errors are reported */
  103879. SrcList *pSrc, /* The SrcList to be enlarged */
  103880. int nExtra, /* Number of new slots to add to pSrc->a[] */
  103881. int iStart /* Index in pSrc->a[] of first new slot */
  103882. ){
  103883. int i;
  103884. /* Sanity checking on calling parameters */
  103885. assert( iStart>=0 );
  103886. assert( nExtra>=1 );
  103887. assert( pSrc!=0 );
  103888. assert( iStart<=pSrc->nSrc );
  103889. /* Allocate additional space if needed */
  103890. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  103891. SrcList *pNew;
  103892. sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
  103893. sqlite3 *db = pParse->db;
  103894. if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
  103895. sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
  103896. SQLITE_MAX_SRCLIST);
  103897. return 0;
  103898. }
  103899. if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
  103900. pNew = sqlite3DbRealloc(db, pSrc,
  103901. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  103902. if( pNew==0 ){
  103903. assert( db->mallocFailed );
  103904. return 0;
  103905. }
  103906. pSrc = pNew;
  103907. pSrc->nAlloc = nAlloc;
  103908. }
  103909. /* Move existing slots that come after the newly inserted slots
  103910. ** out of the way */
  103911. for(i=pSrc->nSrc-1; i>=iStart; i--){
  103912. pSrc->a[i+nExtra] = pSrc->a[i];
  103913. }
  103914. pSrc->nSrc += nExtra;
  103915. /* Zero the newly allocated slots */
  103916. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  103917. for(i=iStart; i<iStart+nExtra; i++){
  103918. pSrc->a[i].iCursor = -1;
  103919. }
  103920. /* Return a pointer to the enlarged SrcList */
  103921. return pSrc;
  103922. }
  103923. /*
  103924. ** Append a new table name to the given SrcList. Create a new SrcList if
  103925. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  103926. **
  103927. ** A SrcList is returned, or NULL if there is an OOM error or if the
  103928. ** SrcList grows to large. The returned
  103929. ** SrcList might be the same as the SrcList that was input or it might be
  103930. ** a new one. If an OOM error does occurs, then the prior value of pList
  103931. ** that is input to this routine is automatically freed.
  103932. **
  103933. ** If pDatabase is not null, it means that the table has an optional
  103934. ** database name prefix. Like this: "database.table". The pDatabase
  103935. ** points to the table name and the pTable points to the database name.
  103936. ** The SrcList.a[].zName field is filled with the table name which might
  103937. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  103938. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  103939. ** or with NULL if no database is specified.
  103940. **
  103941. ** In other words, if call like this:
  103942. **
  103943. ** sqlite3SrcListAppend(D,A,B,0);
  103944. **
  103945. ** Then B is a table name and the database name is unspecified. If called
  103946. ** like this:
  103947. **
  103948. ** sqlite3SrcListAppend(D,A,B,C);
  103949. **
  103950. ** Then C is the table name and B is the database name. If C is defined
  103951. ** then so is B. In other words, we never have a case where:
  103952. **
  103953. ** sqlite3SrcListAppend(D,A,0,C);
  103954. **
  103955. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  103956. ** before being added to the SrcList.
  103957. */
  103958. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  103959. Parse *pParse, /* Parsing context, in which errors are reported */
  103960. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  103961. Token *pTable, /* Table to append */
  103962. Token *pDatabase /* Database of the table */
  103963. ){
  103964. struct SrcList_item *pItem;
  103965. sqlite3 *db;
  103966. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  103967. assert( pParse!=0 );
  103968. assert( pParse->db!=0 );
  103969. db = pParse->db;
  103970. if( pList==0 ){
  103971. pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
  103972. if( pList==0 ) return 0;
  103973. pList->nAlloc = 1;
  103974. pList->nSrc = 1;
  103975. memset(&pList->a[0], 0, sizeof(pList->a[0]));
  103976. pList->a[0].iCursor = -1;
  103977. }else{
  103978. SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
  103979. if( pNew==0 ){
  103980. sqlite3SrcListDelete(db, pList);
  103981. return 0;
  103982. }else{
  103983. pList = pNew;
  103984. }
  103985. }
  103986. pItem = &pList->a[pList->nSrc-1];
  103987. if( pDatabase && pDatabase->z==0 ){
  103988. pDatabase = 0;
  103989. }
  103990. if( pDatabase ){
  103991. pItem->zName = sqlite3NameFromToken(db, pDatabase);
  103992. pItem->zDatabase = sqlite3NameFromToken(db, pTable);
  103993. }else{
  103994. pItem->zName = sqlite3NameFromToken(db, pTable);
  103995. pItem->zDatabase = 0;
  103996. }
  103997. return pList;
  103998. }
  103999. /*
  104000. ** Assign VdbeCursor index numbers to all tables in a SrcList
  104001. */
  104002. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  104003. int i;
  104004. struct SrcList_item *pItem;
  104005. assert(pList || pParse->db->mallocFailed );
  104006. if( pList ){
  104007. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  104008. if( pItem->iCursor>=0 ) break;
  104009. pItem->iCursor = pParse->nTab++;
  104010. if( pItem->pSelect ){
  104011. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  104012. }
  104013. }
  104014. }
  104015. }
  104016. /*
  104017. ** Delete an entire SrcList including all its substructure.
  104018. */
  104019. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  104020. int i;
  104021. struct SrcList_item *pItem;
  104022. if( pList==0 ) return;
  104023. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  104024. sqlite3DbFree(db, pItem->zDatabase);
  104025. sqlite3DbFree(db, pItem->zName);
  104026. sqlite3DbFree(db, pItem->zAlias);
  104027. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  104028. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  104029. sqlite3DeleteTable(db, pItem->pTab);
  104030. sqlite3SelectDelete(db, pItem->pSelect);
  104031. sqlite3ExprDelete(db, pItem->pOn);
  104032. sqlite3IdListDelete(db, pItem->pUsing);
  104033. }
  104034. sqlite3DbFreeNN(db, pList);
  104035. }
  104036. /*
  104037. ** This routine is called by the parser to add a new term to the
  104038. ** end of a growing FROM clause. The "p" parameter is the part of
  104039. ** the FROM clause that has already been constructed. "p" is NULL
  104040. ** if this is the first term of the FROM clause. pTable and pDatabase
  104041. ** are the name of the table and database named in the FROM clause term.
  104042. ** pDatabase is NULL if the database name qualifier is missing - the
  104043. ** usual case. If the term has an alias, then pAlias points to the
  104044. ** alias token. If the term is a subquery, then pSubquery is the
  104045. ** SELECT statement that the subquery encodes. The pTable and
  104046. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  104047. ** parameters are the content of the ON and USING clauses.
  104048. **
  104049. ** Return a new SrcList which encodes is the FROM with the new
  104050. ** term added.
  104051. */
  104052. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  104053. Parse *pParse, /* Parsing context */
  104054. SrcList *p, /* The left part of the FROM clause already seen */
  104055. Token *pTable, /* Name of the table to add to the FROM clause */
  104056. Token *pDatabase, /* Name of the database containing pTable */
  104057. Token *pAlias, /* The right-hand side of the AS subexpression */
  104058. Select *pSubquery, /* A subquery used in place of a table name */
  104059. Expr *pOn, /* The ON clause of a join */
  104060. IdList *pUsing /* The USING clause of a join */
  104061. ){
  104062. struct SrcList_item *pItem;
  104063. sqlite3 *db = pParse->db;
  104064. if( !p && (pOn || pUsing) ){
  104065. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  104066. (pOn ? "ON" : "USING")
  104067. );
  104068. goto append_from_error;
  104069. }
  104070. p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
  104071. if( p==0 ){
  104072. goto append_from_error;
  104073. }
  104074. assert( p->nSrc>0 );
  104075. pItem = &p->a[p->nSrc-1];
  104076. assert( (pTable==0)==(pDatabase==0) );
  104077. assert( pItem->zName==0 || pDatabase!=0 );
  104078. if( IN_RENAME_OBJECT && pItem->zName ){
  104079. Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
  104080. sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
  104081. }
  104082. assert( pAlias!=0 );
  104083. if( pAlias->n ){
  104084. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  104085. }
  104086. pItem->pSelect = pSubquery;
  104087. pItem->pOn = pOn;
  104088. pItem->pUsing = pUsing;
  104089. return p;
  104090. append_from_error:
  104091. assert( p==0 );
  104092. sqlite3ExprDelete(db, pOn);
  104093. sqlite3IdListDelete(db, pUsing);
  104094. sqlite3SelectDelete(db, pSubquery);
  104095. return 0;
  104096. }
  104097. /*
  104098. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  104099. ** element of the source-list passed as the second argument.
  104100. */
  104101. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  104102. assert( pIndexedBy!=0 );
  104103. if( p && pIndexedBy->n>0 ){
  104104. struct SrcList_item *pItem;
  104105. assert( p->nSrc>0 );
  104106. pItem = &p->a[p->nSrc-1];
  104107. assert( pItem->fg.notIndexed==0 );
  104108. assert( pItem->fg.isIndexedBy==0 );
  104109. assert( pItem->fg.isTabFunc==0 );
  104110. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  104111. /* A "NOT INDEXED" clause was supplied. See parse.y
  104112. ** construct "indexed_opt" for details. */
  104113. pItem->fg.notIndexed = 1;
  104114. }else{
  104115. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  104116. pItem->fg.isIndexedBy = 1;
  104117. }
  104118. }
  104119. }
  104120. /*
  104121. ** Add the list of function arguments to the SrcList entry for a
  104122. ** table-valued-function.
  104123. */
  104124. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  104125. if( p ){
  104126. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  104127. assert( pItem->fg.notIndexed==0 );
  104128. assert( pItem->fg.isIndexedBy==0 );
  104129. assert( pItem->fg.isTabFunc==0 );
  104130. pItem->u1.pFuncArg = pList;
  104131. pItem->fg.isTabFunc = 1;
  104132. }else{
  104133. sqlite3ExprListDelete(pParse->db, pList);
  104134. }
  104135. }
  104136. /*
  104137. ** When building up a FROM clause in the parser, the join operator
  104138. ** is initially attached to the left operand. But the code generator
  104139. ** expects the join operator to be on the right operand. This routine
  104140. ** Shifts all join operators from left to right for an entire FROM
  104141. ** clause.
  104142. **
  104143. ** Example: Suppose the join is like this:
  104144. **
  104145. ** A natural cross join B
  104146. **
  104147. ** The operator is "natural cross join". The A and B operands are stored
  104148. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  104149. ** operator with A. This routine shifts that operator over to B.
  104150. */
  104151. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  104152. if( p ){
  104153. int i;
  104154. for(i=p->nSrc-1; i>0; i--){
  104155. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  104156. }
  104157. p->a[0].fg.jointype = 0;
  104158. }
  104159. }
  104160. /*
  104161. ** Generate VDBE code for a BEGIN statement.
  104162. */
  104163. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  104164. sqlite3 *db;
  104165. Vdbe *v;
  104166. int i;
  104167. assert( pParse!=0 );
  104168. db = pParse->db;
  104169. assert( db!=0 );
  104170. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  104171. return;
  104172. }
  104173. v = sqlite3GetVdbe(pParse);
  104174. if( !v ) return;
  104175. if( type!=TK_DEFERRED ){
  104176. for(i=0; i<db->nDb; i++){
  104177. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  104178. sqlite3VdbeUsesBtree(v, i);
  104179. }
  104180. }
  104181. sqlite3VdbeAddOp0(v, OP_AutoCommit);
  104182. }
  104183. /*
  104184. ** Generate VDBE code for a COMMIT or ROLLBACK statement.
  104185. ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
  104186. ** code is generated for a COMMIT.
  104187. */
  104188. SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
  104189. Vdbe *v;
  104190. int isRollback;
  104191. assert( pParse!=0 );
  104192. assert( pParse->db!=0 );
  104193. assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
  104194. isRollback = eType==TK_ROLLBACK;
  104195. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
  104196. isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
  104197. return;
  104198. }
  104199. v = sqlite3GetVdbe(pParse);
  104200. if( v ){
  104201. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
  104202. }
  104203. }
  104204. /*
  104205. ** This function is called by the parser when it parses a command to create,
  104206. ** release or rollback an SQL savepoint.
  104207. */
  104208. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  104209. char *zName = sqlite3NameFromToken(pParse->db, pName);
  104210. if( zName ){
  104211. Vdbe *v = sqlite3GetVdbe(pParse);
  104212. #ifndef SQLITE_OMIT_AUTHORIZATION
  104213. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  104214. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  104215. #endif
  104216. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  104217. sqlite3DbFree(pParse->db, zName);
  104218. return;
  104219. }
  104220. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  104221. }
  104222. }
  104223. /*
  104224. ** Make sure the TEMP database is open and available for use. Return
  104225. ** the number of errors. Leave any error messages in the pParse structure.
  104226. */
  104227. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  104228. sqlite3 *db = pParse->db;
  104229. if( db->aDb[1].pBt==0 && !pParse->explain ){
  104230. int rc;
  104231. Btree *pBt;
  104232. static const int flags =
  104233. SQLITE_OPEN_READWRITE |
  104234. SQLITE_OPEN_CREATE |
  104235. SQLITE_OPEN_EXCLUSIVE |
  104236. SQLITE_OPEN_DELETEONCLOSE |
  104237. SQLITE_OPEN_TEMP_DB;
  104238. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  104239. if( rc!=SQLITE_OK ){
  104240. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  104241. "file for storing temporary tables");
  104242. pParse->rc = rc;
  104243. return 1;
  104244. }
  104245. db->aDb[1].pBt = pBt;
  104246. assert( db->aDb[1].pSchema );
  104247. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  104248. sqlite3OomFault(db);
  104249. return 1;
  104250. }
  104251. }
  104252. return 0;
  104253. }
  104254. /*
  104255. ** Record the fact that the schema cookie will need to be verified
  104256. ** for database iDb. The code to actually verify the schema cookie
  104257. ** will occur at the end of the top-level VDBE and will be generated
  104258. ** later, by sqlite3FinishCoding().
  104259. */
  104260. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  104261. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  104262. assert( iDb>=0 && iDb<pParse->db->nDb );
  104263. assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
  104264. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  104265. assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
  104266. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  104267. DbMaskSet(pToplevel->cookieMask, iDb);
  104268. if( !OMIT_TEMPDB && iDb==1 ){
  104269. sqlite3OpenTempDatabase(pToplevel);
  104270. }
  104271. }
  104272. }
  104273. /*
  104274. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  104275. ** attached database. Otherwise, invoke it for the database named zDb only.
  104276. */
  104277. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  104278. sqlite3 *db = pParse->db;
  104279. int i;
  104280. for(i=0; i<db->nDb; i++){
  104281. Db *pDb = &db->aDb[i];
  104282. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
  104283. sqlite3CodeVerifySchema(pParse, i);
  104284. }
  104285. }
  104286. }
  104287. /*
  104288. ** Generate VDBE code that prepares for doing an operation that
  104289. ** might change the database.
  104290. **
  104291. ** This routine starts a new transaction if we are not already within
  104292. ** a transaction. If we are already within a transaction, then a checkpoint
  104293. ** is set if the setStatement parameter is true. A checkpoint should
  104294. ** be set for operations that might fail (due to a constraint) part of
  104295. ** the way through and which will need to undo some writes without having to
  104296. ** rollback the whole transaction. For operations where all constraints
  104297. ** can be checked before any changes are made to the database, it is never
  104298. ** necessary to undo a write and the checkpoint should not be set.
  104299. */
  104300. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  104301. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  104302. sqlite3CodeVerifySchema(pParse, iDb);
  104303. DbMaskSet(pToplevel->writeMask, iDb);
  104304. pToplevel->isMultiWrite |= setStatement;
  104305. }
  104306. /*
  104307. ** Indicate that the statement currently under construction might write
  104308. ** more than one entry (example: deleting one row then inserting another,
  104309. ** inserting multiple rows in a table, or inserting a row and index entries.)
  104310. ** If an abort occurs after some of these writes have completed, then it will
  104311. ** be necessary to undo the completed writes.
  104312. */
  104313. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  104314. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  104315. pToplevel->isMultiWrite = 1;
  104316. }
  104317. /*
  104318. ** The code generator calls this routine if is discovers that it is
  104319. ** possible to abort a statement prior to completion. In order to
  104320. ** perform this abort without corrupting the database, we need to make
  104321. ** sure that the statement is protected by a statement transaction.
  104322. **
  104323. ** Technically, we only need to set the mayAbort flag if the
  104324. ** isMultiWrite flag was previously set. There is a time dependency
  104325. ** such that the abort must occur after the multiwrite. This makes
  104326. ** some statements involving the REPLACE conflict resolution algorithm
  104327. ** go a little faster. But taking advantage of this time dependency
  104328. ** makes it more difficult to prove that the code is correct (in
  104329. ** particular, it prevents us from writing an effective
  104330. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  104331. ** to take the safe route and skip the optimization.
  104332. */
  104333. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  104334. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  104335. pToplevel->mayAbort = 1;
  104336. }
  104337. /*
  104338. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  104339. ** error. The onError parameter determines which (if any) of the statement
  104340. ** and/or current transaction is rolled back.
  104341. */
  104342. SQLITE_PRIVATE void sqlite3HaltConstraint(
  104343. Parse *pParse, /* Parsing context */
  104344. int errCode, /* extended error code */
  104345. int onError, /* Constraint type */
  104346. char *p4, /* Error message */
  104347. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  104348. u8 p5Errmsg /* P5_ErrMsg type */
  104349. ){
  104350. Vdbe *v = sqlite3GetVdbe(pParse);
  104351. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  104352. if( onError==OE_Abort ){
  104353. sqlite3MayAbort(pParse);
  104354. }
  104355. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  104356. sqlite3VdbeChangeP5(v, p5Errmsg);
  104357. }
  104358. /*
  104359. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  104360. */
  104361. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  104362. Parse *pParse, /* Parsing context */
  104363. int onError, /* Constraint type */
  104364. Index *pIdx /* The index that triggers the constraint */
  104365. ){
  104366. char *zErr;
  104367. int j;
  104368. StrAccum errMsg;
  104369. Table *pTab = pIdx->pTable;
  104370. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
  104371. pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
  104372. if( pIdx->aColExpr ){
  104373. sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
  104374. }else{
  104375. for(j=0; j<pIdx->nKeyCol; j++){
  104376. char *zCol;
  104377. assert( pIdx->aiColumn[j]>=0 );
  104378. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  104379. if( j ) sqlite3_str_append(&errMsg, ", ", 2);
  104380. sqlite3_str_appendall(&errMsg, pTab->zName);
  104381. sqlite3_str_append(&errMsg, ".", 1);
  104382. sqlite3_str_appendall(&errMsg, zCol);
  104383. }
  104384. }
  104385. zErr = sqlite3StrAccumFinish(&errMsg);
  104386. sqlite3HaltConstraint(pParse,
  104387. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  104388. : SQLITE_CONSTRAINT_UNIQUE,
  104389. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  104390. }
  104391. /*
  104392. ** Code an OP_Halt due to non-unique rowid.
  104393. */
  104394. SQLITE_PRIVATE void sqlite3RowidConstraint(
  104395. Parse *pParse, /* Parsing context */
  104396. int onError, /* Conflict resolution algorithm */
  104397. Table *pTab /* The table with the non-unique rowid */
  104398. ){
  104399. char *zMsg;
  104400. int rc;
  104401. if( pTab->iPKey>=0 ){
  104402. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  104403. pTab->aCol[pTab->iPKey].zName);
  104404. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  104405. }else{
  104406. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  104407. rc = SQLITE_CONSTRAINT_ROWID;
  104408. }
  104409. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  104410. P5_ConstraintUnique);
  104411. }
  104412. /*
  104413. ** Check to see if pIndex uses the collating sequence pColl. Return
  104414. ** true if it does and false if it does not.
  104415. */
  104416. #ifndef SQLITE_OMIT_REINDEX
  104417. static int collationMatch(const char *zColl, Index *pIndex){
  104418. int i;
  104419. assert( zColl!=0 );
  104420. for(i=0; i<pIndex->nColumn; i++){
  104421. const char *z = pIndex->azColl[i];
  104422. assert( z!=0 || pIndex->aiColumn[i]<0 );
  104423. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  104424. return 1;
  104425. }
  104426. }
  104427. return 0;
  104428. }
  104429. #endif
  104430. /*
  104431. ** Recompute all indices of pTab that use the collating sequence pColl.
  104432. ** If pColl==0 then recompute all indices of pTab.
  104433. */
  104434. #ifndef SQLITE_OMIT_REINDEX
  104435. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  104436. if( !IsVirtual(pTab) ){
  104437. Index *pIndex; /* An index associated with pTab */
  104438. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  104439. if( zColl==0 || collationMatch(zColl, pIndex) ){
  104440. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  104441. sqlite3BeginWriteOperation(pParse, 0, iDb);
  104442. sqlite3RefillIndex(pParse, pIndex, -1);
  104443. }
  104444. }
  104445. }
  104446. }
  104447. #endif
  104448. /*
  104449. ** Recompute all indices of all tables in all databases where the
  104450. ** indices use the collating sequence pColl. If pColl==0 then recompute
  104451. ** all indices everywhere.
  104452. */
  104453. #ifndef SQLITE_OMIT_REINDEX
  104454. static void reindexDatabases(Parse *pParse, char const *zColl){
  104455. Db *pDb; /* A single database */
  104456. int iDb; /* The database index number */
  104457. sqlite3 *db = pParse->db; /* The database connection */
  104458. HashElem *k; /* For looping over tables in pDb */
  104459. Table *pTab; /* A table in the database */
  104460. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  104461. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  104462. assert( pDb!=0 );
  104463. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  104464. pTab = (Table*)sqliteHashData(k);
  104465. reindexTable(pParse, pTab, zColl);
  104466. }
  104467. }
  104468. }
  104469. #endif
  104470. /*
  104471. ** Generate code for the REINDEX command.
  104472. **
  104473. ** REINDEX -- 1
  104474. ** REINDEX <collation> -- 2
  104475. ** REINDEX ?<database>.?<tablename> -- 3
  104476. ** REINDEX ?<database>.?<indexname> -- 4
  104477. **
  104478. ** Form 1 causes all indices in all attached databases to be rebuilt.
  104479. ** Form 2 rebuilds all indices in all databases that use the named
  104480. ** collating function. Forms 3 and 4 rebuild the named index or all
  104481. ** indices associated with the named table.
  104482. */
  104483. #ifndef SQLITE_OMIT_REINDEX
  104484. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  104485. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  104486. char *z; /* Name of a table or index */
  104487. const char *zDb; /* Name of the database */
  104488. Table *pTab; /* A table in the database */
  104489. Index *pIndex; /* An index associated with pTab */
  104490. int iDb; /* The database index number */
  104491. sqlite3 *db = pParse->db; /* The database connection */
  104492. Token *pObjName; /* Name of the table or index to be reindexed */
  104493. /* Read the database schema. If an error occurs, leave an error message
  104494. ** and code in pParse and return NULL. */
  104495. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  104496. return;
  104497. }
  104498. if( pName1==0 ){
  104499. reindexDatabases(pParse, 0);
  104500. return;
  104501. }else if( NEVER(pName2==0) || pName2->z==0 ){
  104502. char *zColl;
  104503. assert( pName1->z );
  104504. zColl = sqlite3NameFromToken(pParse->db, pName1);
  104505. if( !zColl ) return;
  104506. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  104507. if( pColl ){
  104508. reindexDatabases(pParse, zColl);
  104509. sqlite3DbFree(db, zColl);
  104510. return;
  104511. }
  104512. sqlite3DbFree(db, zColl);
  104513. }
  104514. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  104515. if( iDb<0 ) return;
  104516. z = sqlite3NameFromToken(db, pObjName);
  104517. if( z==0 ) return;
  104518. zDb = db->aDb[iDb].zDbSName;
  104519. pTab = sqlite3FindTable(db, z, zDb);
  104520. if( pTab ){
  104521. reindexTable(pParse, pTab, 0);
  104522. sqlite3DbFree(db, z);
  104523. return;
  104524. }
  104525. pIndex = sqlite3FindIndex(db, z, zDb);
  104526. sqlite3DbFree(db, z);
  104527. if( pIndex ){
  104528. sqlite3BeginWriteOperation(pParse, 0, iDb);
  104529. sqlite3RefillIndex(pParse, pIndex, -1);
  104530. return;
  104531. }
  104532. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  104533. }
  104534. #endif
  104535. /*
  104536. ** Return a KeyInfo structure that is appropriate for the given Index.
  104537. **
  104538. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  104539. ** when it has finished using it.
  104540. */
  104541. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  104542. int i;
  104543. int nCol = pIdx->nColumn;
  104544. int nKey = pIdx->nKeyCol;
  104545. KeyInfo *pKey;
  104546. if( pParse->nErr ) return 0;
  104547. if( pIdx->uniqNotNull ){
  104548. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  104549. }else{
  104550. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  104551. }
  104552. if( pKey ){
  104553. assert( sqlite3KeyInfoIsWriteable(pKey) );
  104554. for(i=0; i<nCol; i++){
  104555. const char *zColl = pIdx->azColl[i];
  104556. pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
  104557. sqlite3LocateCollSeq(pParse, zColl);
  104558. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  104559. }
  104560. if( pParse->nErr ){
  104561. assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
  104562. if( pIdx->bNoQuery==0 ){
  104563. /* Deactivate the index because it contains an unknown collating
  104564. ** sequence. The only way to reactive the index is to reload the
  104565. ** schema. Adding the missing collating sequence later does not
  104566. ** reactive the index. The application had the chance to register
  104567. ** the missing index using the collation-needed callback. For
  104568. ** simplicity, SQLite will not give the application a second chance.
  104569. */
  104570. pIdx->bNoQuery = 1;
  104571. pParse->rc = SQLITE_ERROR_RETRY;
  104572. }
  104573. sqlite3KeyInfoUnref(pKey);
  104574. pKey = 0;
  104575. }
  104576. }
  104577. return pKey;
  104578. }
  104579. #ifndef SQLITE_OMIT_CTE
  104580. /*
  104581. ** This routine is invoked once per CTE by the parser while parsing a
  104582. ** WITH clause.
  104583. */
  104584. SQLITE_PRIVATE With *sqlite3WithAdd(
  104585. Parse *pParse, /* Parsing context */
  104586. With *pWith, /* Existing WITH clause, or NULL */
  104587. Token *pName, /* Name of the common-table */
  104588. ExprList *pArglist, /* Optional column name list for the table */
  104589. Select *pQuery /* Query used to initialize the table */
  104590. ){
  104591. sqlite3 *db = pParse->db;
  104592. With *pNew;
  104593. char *zName;
  104594. /* Check that the CTE name is unique within this WITH clause. If
  104595. ** not, store an error in the Parse structure. */
  104596. zName = sqlite3NameFromToken(pParse->db, pName);
  104597. if( zName && pWith ){
  104598. int i;
  104599. for(i=0; i<pWith->nCte; i++){
  104600. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  104601. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  104602. }
  104603. }
  104604. }
  104605. if( pWith ){
  104606. sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  104607. pNew = sqlite3DbRealloc(db, pWith, nByte);
  104608. }else{
  104609. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  104610. }
  104611. assert( (pNew!=0 && zName!=0) || db->mallocFailed );
  104612. if( db->mallocFailed ){
  104613. sqlite3ExprListDelete(db, pArglist);
  104614. sqlite3SelectDelete(db, pQuery);
  104615. sqlite3DbFree(db, zName);
  104616. pNew = pWith;
  104617. }else{
  104618. pNew->a[pNew->nCte].pSelect = pQuery;
  104619. pNew->a[pNew->nCte].pCols = pArglist;
  104620. pNew->a[pNew->nCte].zName = zName;
  104621. pNew->a[pNew->nCte].zCteErr = 0;
  104622. pNew->nCte++;
  104623. }
  104624. return pNew;
  104625. }
  104626. /*
  104627. ** Free the contents of the With object passed as the second argument.
  104628. */
  104629. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  104630. if( pWith ){
  104631. int i;
  104632. for(i=0; i<pWith->nCte; i++){
  104633. struct Cte *pCte = &pWith->a[i];
  104634. sqlite3ExprListDelete(db, pCte->pCols);
  104635. sqlite3SelectDelete(db, pCte->pSelect);
  104636. sqlite3DbFree(db, pCte->zName);
  104637. }
  104638. sqlite3DbFree(db, pWith);
  104639. }
  104640. }
  104641. #endif /* !defined(SQLITE_OMIT_CTE) */
  104642. /************** End of build.c ***********************************************/
  104643. /************** Begin file callback.c ****************************************/
  104644. /*
  104645. ** 2005 May 23
  104646. **
  104647. ** The author disclaims copyright to this source code. In place of
  104648. ** a legal notice, here is a blessing:
  104649. **
  104650. ** May you do good and not evil.
  104651. ** May you find forgiveness for yourself and forgive others.
  104652. ** May you share freely, never taking more than you give.
  104653. **
  104654. *************************************************************************
  104655. **
  104656. ** This file contains functions used to access the internal hash tables
  104657. ** of user defined functions and collation sequences.
  104658. */
  104659. /* #include "sqliteInt.h" */
  104660. /*
  104661. ** Invoke the 'collation needed' callback to request a collation sequence
  104662. ** in the encoding enc of name zName, length nName.
  104663. */
  104664. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  104665. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  104666. if( db->xCollNeeded ){
  104667. char *zExternal = sqlite3DbStrDup(db, zName);
  104668. if( !zExternal ) return;
  104669. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  104670. sqlite3DbFree(db, zExternal);
  104671. }
  104672. #ifndef SQLITE_OMIT_UTF16
  104673. if( db->xCollNeeded16 ){
  104674. char const *zExternal;
  104675. sqlite3_value *pTmp = sqlite3ValueNew(db);
  104676. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  104677. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  104678. if( zExternal ){
  104679. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  104680. }
  104681. sqlite3ValueFree(pTmp);
  104682. }
  104683. #endif
  104684. }
  104685. /*
  104686. ** This routine is called if the collation factory fails to deliver a
  104687. ** collation function in the best encoding but there may be other versions
  104688. ** of this collation function (for other text encodings) available. Use one
  104689. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  104690. ** possible.
  104691. */
  104692. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  104693. CollSeq *pColl2;
  104694. char *z = pColl->zName;
  104695. int i;
  104696. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  104697. for(i=0; i<3; i++){
  104698. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  104699. if( pColl2->xCmp!=0 ){
  104700. memcpy(pColl, pColl2, sizeof(CollSeq));
  104701. pColl->xDel = 0; /* Do not copy the destructor */
  104702. return SQLITE_OK;
  104703. }
  104704. }
  104705. return SQLITE_ERROR;
  104706. }
  104707. /*
  104708. ** This function is responsible for invoking the collation factory callback
  104709. ** or substituting a collation sequence of a different encoding when the
  104710. ** requested collation sequence is not available in the desired encoding.
  104711. **
  104712. ** If it is not NULL, then pColl must point to the database native encoding
  104713. ** collation sequence with name zName, length nName.
  104714. **
  104715. ** The return value is either the collation sequence to be used in database
  104716. ** db for collation type name zName, length nName, or NULL, if no collation
  104717. ** sequence can be found. If no collation is found, leave an error message.
  104718. **
  104719. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  104720. */
  104721. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  104722. Parse *pParse, /* Parsing context */
  104723. u8 enc, /* The desired encoding for the collating sequence */
  104724. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  104725. const char *zName /* Collating sequence name */
  104726. ){
  104727. CollSeq *p;
  104728. sqlite3 *db = pParse->db;
  104729. p = pColl;
  104730. if( !p ){
  104731. p = sqlite3FindCollSeq(db, enc, zName, 0);
  104732. }
  104733. if( !p || !p->xCmp ){
  104734. /* No collation sequence of this type for this encoding is registered.
  104735. ** Call the collation factory to see if it can supply us with one.
  104736. */
  104737. callCollNeeded(db, enc, zName);
  104738. p = sqlite3FindCollSeq(db, enc, zName, 0);
  104739. }
  104740. if( p && !p->xCmp && synthCollSeq(db, p) ){
  104741. p = 0;
  104742. }
  104743. assert( !p || p->xCmp );
  104744. if( p==0 ){
  104745. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  104746. pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
  104747. }
  104748. return p;
  104749. }
  104750. /*
  104751. ** This routine is called on a collation sequence before it is used to
  104752. ** check that it is defined. An undefined collation sequence exists when
  104753. ** a database is loaded that contains references to collation sequences
  104754. ** that have not been defined by sqlite3_create_collation() etc.
  104755. **
  104756. ** If required, this routine calls the 'collation needed' callback to
  104757. ** request a definition of the collating sequence. If this doesn't work,
  104758. ** an equivalent collating sequence that uses a text encoding different
  104759. ** from the main database is substituted, if one is available.
  104760. */
  104761. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  104762. if( pColl && pColl->xCmp==0 ){
  104763. const char *zName = pColl->zName;
  104764. sqlite3 *db = pParse->db;
  104765. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  104766. if( !p ){
  104767. return SQLITE_ERROR;
  104768. }
  104769. assert( p==pColl );
  104770. }
  104771. return SQLITE_OK;
  104772. }
  104773. /*
  104774. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  104775. ** specified by zName and nName is not found and parameter 'create' is
  104776. ** true, then create a new entry. Otherwise return NULL.
  104777. **
  104778. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  104779. ** array of three CollSeq structures. The first is the collation sequence
  104780. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  104781. **
  104782. ** Stored immediately after the three collation sequences is a copy of
  104783. ** the collation sequence name. A pointer to this string is stored in
  104784. ** each collation sequence structure.
  104785. */
  104786. static CollSeq *findCollSeqEntry(
  104787. sqlite3 *db, /* Database connection */
  104788. const char *zName, /* Name of the collating sequence */
  104789. int create /* Create a new entry if true */
  104790. ){
  104791. CollSeq *pColl;
  104792. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  104793. if( 0==pColl && create ){
  104794. int nName = sqlite3Strlen30(zName) + 1;
  104795. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
  104796. if( pColl ){
  104797. CollSeq *pDel = 0;
  104798. pColl[0].zName = (char*)&pColl[3];
  104799. pColl[0].enc = SQLITE_UTF8;
  104800. pColl[1].zName = (char*)&pColl[3];
  104801. pColl[1].enc = SQLITE_UTF16LE;
  104802. pColl[2].zName = (char*)&pColl[3];
  104803. pColl[2].enc = SQLITE_UTF16BE;
  104804. memcpy(pColl[0].zName, zName, nName);
  104805. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  104806. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  104807. ** return the pColl pointer to be deleted (because it wasn't added
  104808. ** to the hash table).
  104809. */
  104810. assert( pDel==0 || pDel==pColl );
  104811. if( pDel!=0 ){
  104812. sqlite3OomFault(db);
  104813. sqlite3DbFree(db, pDel);
  104814. pColl = 0;
  104815. }
  104816. }
  104817. }
  104818. return pColl;
  104819. }
  104820. /*
  104821. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  104822. ** Return the CollSeq* pointer for the collation sequence named zName
  104823. ** for the encoding 'enc' from the database 'db'.
  104824. **
  104825. ** If the entry specified is not found and 'create' is true, then create a
  104826. ** new entry. Otherwise return NULL.
  104827. **
  104828. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  104829. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  104830. ** if necessary and generates an error message if the collating sequence
  104831. ** cannot be found.
  104832. **
  104833. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  104834. */
  104835. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  104836. sqlite3 *db,
  104837. u8 enc,
  104838. const char *zName,
  104839. int create
  104840. ){
  104841. CollSeq *pColl;
  104842. if( zName ){
  104843. pColl = findCollSeqEntry(db, zName, create);
  104844. }else{
  104845. pColl = db->pDfltColl;
  104846. }
  104847. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  104848. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  104849. if( pColl ) pColl += enc-1;
  104850. return pColl;
  104851. }
  104852. /* During the search for the best function definition, this procedure
  104853. ** is called to test how well the function passed as the first argument
  104854. ** matches the request for a function with nArg arguments in a system
  104855. ** that uses encoding enc. The value returned indicates how well the
  104856. ** request is matched. A higher value indicates a better match.
  104857. **
  104858. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  104859. ** is also -1. In other words, we are searching for a function that
  104860. ** takes a variable number of arguments.
  104861. **
  104862. ** If nArg is -2 that means that we are searching for any function
  104863. ** regardless of the number of arguments it uses, so return a positive
  104864. ** match score for any
  104865. **
  104866. ** The returned value is always between 0 and 6, as follows:
  104867. **
  104868. ** 0: Not a match.
  104869. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  104870. ** 2: UTF16 byte order change required and function takes any number of args.
  104871. ** 3: encoding matches and function takes any number of arguments
  104872. ** 4: UTF8/16 conversion required - argument count matches exactly
  104873. ** 5: UTF16 byte order conversion required - argument count matches exactly
  104874. ** 6: Perfect match: encoding and argument count match exactly.
  104875. **
  104876. ** If nArg==(-2) then any function with a non-null xSFunc is
  104877. ** a perfect match and any function with xSFunc NULL is
  104878. ** a non-match.
  104879. */
  104880. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  104881. static int matchQuality(
  104882. FuncDef *p, /* The function we are evaluating for match quality */
  104883. int nArg, /* Desired number of arguments. (-1)==any */
  104884. u8 enc /* Desired text encoding */
  104885. ){
  104886. int match;
  104887. /* nArg of -2 is a special case */
  104888. if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
  104889. /* Wrong number of arguments means "no match" */
  104890. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  104891. /* Give a better score to a function with a specific number of arguments
  104892. ** than to function that accepts any number of arguments. */
  104893. if( p->nArg==nArg ){
  104894. match = 4;
  104895. }else{
  104896. match = 1;
  104897. }
  104898. /* Bonus points if the text encoding matches */
  104899. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  104900. match += 2; /* Exact encoding match */
  104901. }else if( (enc & p->funcFlags & 2)!=0 ){
  104902. match += 1; /* Both are UTF16, but with different byte orders */
  104903. }
  104904. return match;
  104905. }
  104906. /*
  104907. ** Search a FuncDefHash for a function with the given name. Return
  104908. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  104909. */
  104910. SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(
  104911. int h, /* Hash of the name */
  104912. const char *zFunc /* Name of function */
  104913. ){
  104914. FuncDef *p;
  104915. for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
  104916. if( sqlite3StrICmp(p->zName, zFunc)==0 ){
  104917. return p;
  104918. }
  104919. }
  104920. return 0;
  104921. }
  104922. /*
  104923. ** Insert a new FuncDef into a FuncDefHash hash table.
  104924. */
  104925. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
  104926. FuncDef *aDef, /* List of global functions to be inserted */
  104927. int nDef /* Length of the apDef[] list */
  104928. ){
  104929. int i;
  104930. for(i=0; i<nDef; i++){
  104931. FuncDef *pOther;
  104932. const char *zName = aDef[i].zName;
  104933. int nName = sqlite3Strlen30(zName);
  104934. int h = SQLITE_FUNC_HASH(zName[0], nName);
  104935. assert( zName[0]>='a' && zName[0]<='z' );
  104936. pOther = sqlite3FunctionSearch(h, zName);
  104937. if( pOther ){
  104938. assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
  104939. aDef[i].pNext = pOther->pNext;
  104940. pOther->pNext = &aDef[i];
  104941. }else{
  104942. aDef[i].pNext = 0;
  104943. aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
  104944. sqlite3BuiltinFunctions.a[h] = &aDef[i];
  104945. }
  104946. }
  104947. }
  104948. /*
  104949. ** Locate a user function given a name, a number of arguments and a flag
  104950. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  104951. ** pointer to the FuncDef structure that defines that function, or return
  104952. ** NULL if the function does not exist.
  104953. **
  104954. ** If the createFlag argument is true, then a new (blank) FuncDef
  104955. ** structure is created and liked into the "db" structure if a
  104956. ** no matching function previously existed.
  104957. **
  104958. ** If nArg is -2, then the first valid function found is returned. A
  104959. ** function is valid if xSFunc is non-zero. The nArg==(-2)
  104960. ** case is used to see if zName is a valid function name for some number
  104961. ** of arguments. If nArg is -2, then createFlag must be 0.
  104962. **
  104963. ** If createFlag is false, then a function with the required name and
  104964. ** number of arguments may be returned even if the eTextRep flag does not
  104965. ** match that requested.
  104966. */
  104967. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  104968. sqlite3 *db, /* An open database */
  104969. const char *zName, /* Name of the function. zero-terminated */
  104970. int nArg, /* Number of arguments. -1 means any number */
  104971. u8 enc, /* Preferred text encoding */
  104972. u8 createFlag /* Create new entry if true and does not otherwise exist */
  104973. ){
  104974. FuncDef *p; /* Iterator variable */
  104975. FuncDef *pBest = 0; /* Best match found so far */
  104976. int bestScore = 0; /* Score of best match */
  104977. int h; /* Hash value */
  104978. int nName; /* Length of the name */
  104979. assert( nArg>=(-2) );
  104980. assert( nArg>=(-1) || createFlag==0 );
  104981. nName = sqlite3Strlen30(zName);
  104982. /* First search for a match amongst the application-defined functions.
  104983. */
  104984. p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
  104985. while( p ){
  104986. int score = matchQuality(p, nArg, enc);
  104987. if( score>bestScore ){
  104988. pBest = p;
  104989. bestScore = score;
  104990. }
  104991. p = p->pNext;
  104992. }
  104993. /* If no match is found, search the built-in functions.
  104994. **
  104995. ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
  104996. ** functions even if a prior app-defined function was found. And give
  104997. ** priority to built-in functions.
  104998. **
  104999. ** Except, if createFlag is true, that means that we are trying to
  105000. ** install a new function. Whatever FuncDef structure is returned it will
  105001. ** have fields overwritten with new information appropriate for the
  105002. ** new function. But the FuncDefs for built-in functions are read-only.
  105003. ** So we must not search for built-ins when creating a new function.
  105004. */
  105005. if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
  105006. bestScore = 0;
  105007. h = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zName[0]], nName);
  105008. p = sqlite3FunctionSearch(h, zName);
  105009. while( p ){
  105010. int score = matchQuality(p, nArg, enc);
  105011. if( score>bestScore ){
  105012. pBest = p;
  105013. bestScore = score;
  105014. }
  105015. p = p->pNext;
  105016. }
  105017. }
  105018. /* If the createFlag parameter is true and the search did not reveal an
  105019. ** exact match for the name, number of arguments and encoding, then add a
  105020. ** new entry to the hash table and return it.
  105021. */
  105022. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  105023. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  105024. FuncDef *pOther;
  105025. u8 *z;
  105026. pBest->zName = (const char*)&pBest[1];
  105027. pBest->nArg = (u16)nArg;
  105028. pBest->funcFlags = enc;
  105029. memcpy((char*)&pBest[1], zName, nName+1);
  105030. for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];
  105031. pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
  105032. if( pOther==pBest ){
  105033. sqlite3DbFree(db, pBest);
  105034. sqlite3OomFault(db);
  105035. return 0;
  105036. }else{
  105037. pBest->pNext = pOther;
  105038. }
  105039. }
  105040. if( pBest && (pBest->xSFunc || createFlag) ){
  105041. return pBest;
  105042. }
  105043. return 0;
  105044. }
  105045. /*
  105046. ** Free all resources held by the schema structure. The void* argument points
  105047. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  105048. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  105049. ** of the schema hash tables).
  105050. **
  105051. ** The Schema.cache_size variable is not cleared.
  105052. */
  105053. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  105054. Hash temp1;
  105055. Hash temp2;
  105056. HashElem *pElem;
  105057. Schema *pSchema = (Schema *)p;
  105058. temp1 = pSchema->tblHash;
  105059. temp2 = pSchema->trigHash;
  105060. sqlite3HashInit(&pSchema->trigHash);
  105061. sqlite3HashClear(&pSchema->idxHash);
  105062. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  105063. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  105064. }
  105065. sqlite3HashClear(&temp2);
  105066. sqlite3HashInit(&pSchema->tblHash);
  105067. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  105068. Table *pTab = sqliteHashData(pElem);
  105069. sqlite3DeleteTable(0, pTab);
  105070. }
  105071. sqlite3HashClear(&temp1);
  105072. sqlite3HashClear(&pSchema->fkeyHash);
  105073. pSchema->pSeqTab = 0;
  105074. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  105075. pSchema->iGeneration++;
  105076. }
  105077. pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
  105078. }
  105079. /*
  105080. ** Find and return the schema associated with a BTree. Create
  105081. ** a new one if necessary.
  105082. */
  105083. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  105084. Schema * p;
  105085. if( pBt ){
  105086. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  105087. }else{
  105088. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  105089. }
  105090. if( !p ){
  105091. sqlite3OomFault(db);
  105092. }else if ( 0==p->file_format ){
  105093. sqlite3HashInit(&p->tblHash);
  105094. sqlite3HashInit(&p->idxHash);
  105095. sqlite3HashInit(&p->trigHash);
  105096. sqlite3HashInit(&p->fkeyHash);
  105097. p->enc = SQLITE_UTF8;
  105098. }
  105099. return p;
  105100. }
  105101. /************** End of callback.c ********************************************/
  105102. /************** Begin file delete.c ******************************************/
  105103. /*
  105104. ** 2001 September 15
  105105. **
  105106. ** The author disclaims copyright to this source code. In place of
  105107. ** a legal notice, here is a blessing:
  105108. **
  105109. ** May you do good and not evil.
  105110. ** May you find forgiveness for yourself and forgive others.
  105111. ** May you share freely, never taking more than you give.
  105112. **
  105113. *************************************************************************
  105114. ** This file contains C code routines that are called by the parser
  105115. ** in order to generate code for DELETE FROM statements.
  105116. */
  105117. /* #include "sqliteInt.h" */
  105118. /*
  105119. ** While a SrcList can in general represent multiple tables and subqueries
  105120. ** (as in the FROM clause of a SELECT statement) in this case it contains
  105121. ** the name of a single table, as one might find in an INSERT, DELETE,
  105122. ** or UPDATE statement. Look up that table in the symbol table and
  105123. ** return a pointer. Set an error message and return NULL if the table
  105124. ** name is not found or if any other error occurs.
  105125. **
  105126. ** The following fields are initialized appropriate in pSrc:
  105127. **
  105128. ** pSrc->a[0].pTab Pointer to the Table object
  105129. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  105130. **
  105131. */
  105132. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  105133. struct SrcList_item *pItem = pSrc->a;
  105134. Table *pTab;
  105135. assert( pItem && pSrc->nSrc==1 );
  105136. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  105137. sqlite3DeleteTable(pParse->db, pItem->pTab);
  105138. pItem->pTab = pTab;
  105139. if( pTab ){
  105140. pTab->nTabRef++;
  105141. }
  105142. if( sqlite3IndexedByLookup(pParse, pItem) ){
  105143. pTab = 0;
  105144. }
  105145. return pTab;
  105146. }
  105147. /* Return true if table pTab is read-only.
  105148. **
  105149. ** A table is read-only if any of the following are true:
  105150. **
  105151. ** 1) It is a virtual table and no implementation of the xUpdate method
  105152. ** has been provided
  105153. **
  105154. ** 2) It is a system table (i.e. sqlite_master), this call is not
  105155. ** part of a nested parse and writable_schema pragma has not
  105156. ** been specified
  105157. **
  105158. ** 3) The table is a shadow table, the database connection is in
  105159. ** defensive mode, and the current sqlite3_prepare()
  105160. ** is for a top-level SQL statement.
  105161. */
  105162. static int tabIsReadOnly(Parse *pParse, Table *pTab){
  105163. sqlite3 *db;
  105164. if( IsVirtual(pTab) ){
  105165. return sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0;
  105166. }
  105167. if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;
  105168. db = pParse->db;
  105169. if( (pTab->tabFlags & TF_Readonly)!=0 ){
  105170. return sqlite3WritableSchema(db)==0 && pParse->nested==0;
  105171. }
  105172. assert( pTab->tabFlags & TF_Shadow );
  105173. return (db->flags & SQLITE_Defensive)!=0
  105174. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105175. && db->pVtabCtx==0
  105176. #endif
  105177. && db->nVdbeExec==0;
  105178. }
  105179. /*
  105180. ** Check to make sure the given table is writable. If it is not
  105181. ** writable, generate an error message and return 1. If it is
  105182. ** writable return 0;
  105183. */
  105184. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  105185. if( tabIsReadOnly(pParse, pTab) ){
  105186. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  105187. return 1;
  105188. }
  105189. #ifndef SQLITE_OMIT_VIEW
  105190. if( !viewOk && pTab->pSelect ){
  105191. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  105192. return 1;
  105193. }
  105194. #endif
  105195. return 0;
  105196. }
  105197. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  105198. /*
  105199. ** Evaluate a view and store its result in an ephemeral table. The
  105200. ** pWhere argument is an optional WHERE clause that restricts the
  105201. ** set of rows in the view that are to be added to the ephemeral table.
  105202. */
  105203. SQLITE_PRIVATE void sqlite3MaterializeView(
  105204. Parse *pParse, /* Parsing context */
  105205. Table *pView, /* View definition */
  105206. Expr *pWhere, /* Optional WHERE clause to be added */
  105207. ExprList *pOrderBy, /* Optional ORDER BY clause */
  105208. Expr *pLimit, /* Optional LIMIT clause */
  105209. int iCur /* Cursor number for ephemeral table */
  105210. ){
  105211. SelectDest dest;
  105212. Select *pSel;
  105213. SrcList *pFrom;
  105214. sqlite3 *db = pParse->db;
  105215. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  105216. pWhere = sqlite3ExprDup(db, pWhere, 0);
  105217. pFrom = sqlite3SrcListAppend(pParse, 0, 0, 0);
  105218. if( pFrom ){
  105219. assert( pFrom->nSrc==1 );
  105220. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  105221. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
  105222. assert( pFrom->a[0].pOn==0 );
  105223. assert( pFrom->a[0].pUsing==0 );
  105224. }
  105225. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
  105226. SF_IncludeHidden, pLimit);
  105227. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  105228. sqlite3Select(pParse, pSel, &dest);
  105229. sqlite3SelectDelete(db, pSel);
  105230. }
  105231. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  105232. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  105233. /*
  105234. ** Generate an expression tree to implement the WHERE, ORDER BY,
  105235. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  105236. **
  105237. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  105238. ** \__________________________/
  105239. ** pLimitWhere (pInClause)
  105240. */
  105241. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  105242. Parse *pParse, /* The parser context */
  105243. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  105244. Expr *pWhere, /* The WHERE clause. May be null */
  105245. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  105246. Expr *pLimit, /* The LIMIT clause. May be null */
  105247. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  105248. ){
  105249. sqlite3 *db = pParse->db;
  105250. Expr *pLhs = NULL; /* LHS of IN(SELECT...) operator */
  105251. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  105252. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  105253. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  105254. Select *pSelect = NULL; /* Complete SELECT tree */
  105255. Table *pTab;
  105256. /* Check that there isn't an ORDER BY without a LIMIT clause.
  105257. */
  105258. if( pOrderBy && pLimit==0 ) {
  105259. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  105260. sqlite3ExprDelete(pParse->db, pWhere);
  105261. sqlite3ExprListDelete(pParse->db, pOrderBy);
  105262. return 0;
  105263. }
  105264. /* We only need to generate a select expression if there
  105265. ** is a limit/offset term to enforce.
  105266. */
  105267. if( pLimit == 0 ) {
  105268. return pWhere;
  105269. }
  105270. /* Generate a select expression tree to enforce the limit/offset
  105271. ** term for the DELETE or UPDATE statement. For example:
  105272. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  105273. ** becomes:
  105274. ** DELETE FROM table_a WHERE rowid IN (
  105275. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  105276. ** );
  105277. */
  105278. pTab = pSrc->a[0].pTab;
  105279. if( HasRowid(pTab) ){
  105280. pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  105281. pEList = sqlite3ExprListAppend(
  105282. pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
  105283. );
  105284. }else{
  105285. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  105286. if( pPk->nKeyCol==1 ){
  105287. const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;
  105288. pLhs = sqlite3Expr(db, TK_ID, zName);
  105289. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
  105290. }else{
  105291. int i;
  105292. for(i=0; i<pPk->nKeyCol; i++){
  105293. Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);
  105294. pEList = sqlite3ExprListAppend(pParse, pEList, p);
  105295. }
  105296. pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  105297. if( pLhs ){
  105298. pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
  105299. }
  105300. }
  105301. }
  105302. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  105303. ** and the SELECT subtree. */
  105304. pSrc->a[0].pTab = 0;
  105305. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  105306. pSrc->a[0].pTab = pTab;
  105307. pSrc->a[0].pIBIndex = 0;
  105308. /* generate the SELECT expression tree. */
  105309. pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
  105310. pOrderBy,0,pLimit
  105311. );
  105312. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  105313. pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
  105314. sqlite3PExprAddSelect(pParse, pInClause, pSelect);
  105315. return pInClause;
  105316. }
  105317. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  105318. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  105319. /*
  105320. ** Generate code for a DELETE FROM statement.
  105321. **
  105322. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  105323. ** \________/ \________________/
  105324. ** pTabList pWhere
  105325. */
  105326. SQLITE_PRIVATE void sqlite3DeleteFrom(
  105327. Parse *pParse, /* The parser context */
  105328. SrcList *pTabList, /* The table from which we should delete things */
  105329. Expr *pWhere, /* The WHERE clause. May be null */
  105330. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  105331. Expr *pLimit /* LIMIT clause. May be null */
  105332. ){
  105333. Vdbe *v; /* The virtual database engine */
  105334. Table *pTab; /* The table from which records will be deleted */
  105335. int i; /* Loop counter */
  105336. WhereInfo *pWInfo; /* Information about the WHERE clause */
  105337. Index *pIdx; /* For looping over indices of the table */
  105338. int iTabCur; /* Cursor number for the table */
  105339. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  105340. int iIdxCur = 0; /* Cursor number of the first index */
  105341. int nIdx; /* Number of indices */
  105342. sqlite3 *db; /* Main database structure */
  105343. AuthContext sContext; /* Authorization context */
  105344. NameContext sNC; /* Name context to resolve expressions in */
  105345. int iDb; /* Database number */
  105346. int memCnt = 0; /* Memory cell used for change counting */
  105347. int rcauth; /* Value returned by authorization callback */
  105348. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  105349. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  105350. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  105351. Index *pPk; /* The PRIMARY KEY index on the table */
  105352. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  105353. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  105354. int iKey; /* Memory cell holding key of row to be deleted */
  105355. i16 nKey; /* Number of memory cells in the row key */
  105356. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  105357. int iRowSet = 0; /* Register for rowset of rows to delete */
  105358. int addrBypass = 0; /* Address of jump over the delete logic */
  105359. int addrLoop = 0; /* Top of the delete loop */
  105360. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  105361. int bComplex; /* True if there are triggers or FKs or
  105362. ** subqueries in the WHERE clause */
  105363. #ifndef SQLITE_OMIT_TRIGGER
  105364. int isView; /* True if attempting to delete from a view */
  105365. Trigger *pTrigger; /* List of table triggers, if required */
  105366. #endif
  105367. memset(&sContext, 0, sizeof(sContext));
  105368. db = pParse->db;
  105369. if( pParse->nErr || db->mallocFailed ){
  105370. goto delete_from_cleanup;
  105371. }
  105372. assert( pTabList->nSrc==1 );
  105373. /* Locate the table which we want to delete. This table has to be
  105374. ** put in an SrcList structure because some of the subroutines we
  105375. ** will be calling are designed to work with multiple tables and expect
  105376. ** an SrcList* parameter instead of just a Table* parameter.
  105377. */
  105378. pTab = sqlite3SrcListLookup(pParse, pTabList);
  105379. if( pTab==0 ) goto delete_from_cleanup;
  105380. /* Figure out if we have any triggers and if the table being
  105381. ** deleted from is a view
  105382. */
  105383. #ifndef SQLITE_OMIT_TRIGGER
  105384. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  105385. isView = pTab->pSelect!=0;
  105386. #else
  105387. # define pTrigger 0
  105388. # define isView 0
  105389. #endif
  105390. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  105391. #ifdef SQLITE_OMIT_VIEW
  105392. # undef isView
  105393. # define isView 0
  105394. #endif
  105395. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  105396. if( !isView ){
  105397. pWhere = sqlite3LimitWhere(
  105398. pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
  105399. );
  105400. pOrderBy = 0;
  105401. pLimit = 0;
  105402. }
  105403. #endif
  105404. /* If pTab is really a view, make sure it has been initialized.
  105405. */
  105406. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  105407. goto delete_from_cleanup;
  105408. }
  105409. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  105410. goto delete_from_cleanup;
  105411. }
  105412. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  105413. assert( iDb<db->nDb );
  105414. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
  105415. db->aDb[iDb].zDbSName);
  105416. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  105417. if( rcauth==SQLITE_DENY ){
  105418. goto delete_from_cleanup;
  105419. }
  105420. assert(!isView || pTrigger);
  105421. /* Assign cursor numbers to the table and all its indices.
  105422. */
  105423. assert( pTabList->nSrc==1 );
  105424. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  105425. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  105426. pParse->nTab++;
  105427. }
  105428. /* Start the view context
  105429. */
  105430. if( isView ){
  105431. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  105432. }
  105433. /* Begin generating code.
  105434. */
  105435. v = sqlite3GetVdbe(pParse);
  105436. if( v==0 ){
  105437. goto delete_from_cleanup;
  105438. }
  105439. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  105440. sqlite3BeginWriteOperation(pParse, bComplex, iDb);
  105441. /* If we are trying to delete from a view, realize that view into
  105442. ** an ephemeral table.
  105443. */
  105444. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  105445. if( isView ){
  105446. sqlite3MaterializeView(pParse, pTab,
  105447. pWhere, pOrderBy, pLimit, iTabCur
  105448. );
  105449. iDataCur = iIdxCur = iTabCur;
  105450. pOrderBy = 0;
  105451. pLimit = 0;
  105452. }
  105453. #endif
  105454. /* Resolve the column names in the WHERE clause.
  105455. */
  105456. memset(&sNC, 0, sizeof(sNC));
  105457. sNC.pParse = pParse;
  105458. sNC.pSrcList = pTabList;
  105459. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  105460. goto delete_from_cleanup;
  105461. }
  105462. /* Initialize the counter of the number of rows deleted, if
  105463. ** we are counting rows.
  105464. */
  105465. if( (db->flags & SQLITE_CountRows)!=0
  105466. && !pParse->nested
  105467. && !pParse->pTriggerTab
  105468. ){
  105469. memCnt = ++pParse->nMem;
  105470. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  105471. }
  105472. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  105473. /* Special case: A DELETE without a WHERE clause deletes everything.
  105474. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  105475. ** this optimization caused the row change count (the value returned by
  105476. ** API function sqlite3_count_changes) to be set incorrectly.
  105477. **
  105478. ** The "rcauth==SQLITE_OK" terms is the
  105479. ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
  105480. ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
  105481. ** the truncate optimization is disabled and all rows are deleted
  105482. ** individually.
  105483. */
  105484. if( rcauth==SQLITE_OK
  105485. && pWhere==0
  105486. && !bComplex
  105487. && !IsVirtual(pTab)
  105488. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  105489. && db->xPreUpdateCallback==0
  105490. #endif
  105491. ){
  105492. assert( !isView );
  105493. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  105494. if( HasRowid(pTab) ){
  105495. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
  105496. pTab->zName, P4_STATIC);
  105497. }
  105498. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  105499. assert( pIdx->pSchema==pTab->pSchema );
  105500. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  105501. }
  105502. }else
  105503. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  105504. {
  105505. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
  105506. if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
  105507. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  105508. if( HasRowid(pTab) ){
  105509. /* For a rowid table, initialize the RowSet to an empty set */
  105510. pPk = 0;
  105511. nPk = 1;
  105512. iRowSet = ++pParse->nMem;
  105513. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  105514. }else{
  105515. /* For a WITHOUT ROWID table, create an ephemeral table used to
  105516. ** hold all primary keys for rows to be deleted. */
  105517. pPk = sqlite3PrimaryKeyIndex(pTab);
  105518. assert( pPk!=0 );
  105519. nPk = pPk->nKeyCol;
  105520. iPk = pParse->nMem+1;
  105521. pParse->nMem += nPk;
  105522. iEphCur = pParse->nTab++;
  105523. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  105524. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  105525. }
  105526. /* Construct a query to find the rowid or primary key for every row
  105527. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  105528. ** to indicate the strategy used to implement this delete:
  105529. **
  105530. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  105531. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  105532. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  105533. */
  105534. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  105535. if( pWInfo==0 ) goto delete_from_cleanup;
  105536. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  105537. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  105538. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  105539. if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
  105540. /* Keep track of the number of rows to be deleted */
  105541. if( memCnt ){
  105542. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  105543. }
  105544. /* Extract the rowid or primary key for the current row */
  105545. if( pPk ){
  105546. for(i=0; i<nPk; i++){
  105547. assert( pPk->aiColumn[i]>=0 );
  105548. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  105549. pPk->aiColumn[i], iPk+i);
  105550. }
  105551. iKey = iPk;
  105552. }else{
  105553. iKey = ++pParse->nMem;
  105554. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
  105555. }
  105556. if( eOnePass!=ONEPASS_OFF ){
  105557. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  105558. ** one, so just keep it in its register(s) and fall through to the
  105559. ** delete code. */
  105560. nKey = nPk; /* OP_Found will use an unpacked key */
  105561. aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
  105562. if( aToOpen==0 ){
  105563. sqlite3WhereEnd(pWInfo);
  105564. goto delete_from_cleanup;
  105565. }
  105566. memset(aToOpen, 1, nIdx+1);
  105567. aToOpen[nIdx+1] = 0;
  105568. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  105569. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  105570. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  105571. }else{
  105572. if( pPk ){
  105573. /* Add the PK key for this row to the temporary table */
  105574. iKey = ++pParse->nMem;
  105575. nKey = 0; /* Zero tells OP_Found to use a composite key */
  105576. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  105577. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  105578. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
  105579. }else{
  105580. /* Add the rowid of the row to be deleted to the RowSet */
  105581. nKey = 1; /* OP_DeferredSeek always uses a single rowid */
  105582. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  105583. }
  105584. }
  105585. /* If this DELETE cannot use the ONEPASS strategy, this is the
  105586. ** end of the WHERE loop */
  105587. if( eOnePass!=ONEPASS_OFF ){
  105588. addrBypass = sqlite3VdbeMakeLabel(pParse);
  105589. }else{
  105590. sqlite3WhereEnd(pWInfo);
  105591. }
  105592. /* Unless this is a view, open cursors for the table we are
  105593. ** deleting from and all its indices. If this is a view, then the
  105594. ** only effect this statement has is to fire the INSTEAD OF
  105595. ** triggers.
  105596. */
  105597. if( !isView ){
  105598. int iAddrOnce = 0;
  105599. if( eOnePass==ONEPASS_MULTI ){
  105600. iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  105601. }
  105602. testcase( IsVirtual(pTab) );
  105603. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
  105604. iTabCur, aToOpen, &iDataCur, &iIdxCur);
  105605. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  105606. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  105607. if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
  105608. }
  105609. /* Set up a loop over the rowids/primary-keys that were found in the
  105610. ** where-clause loop above.
  105611. */
  105612. if( eOnePass!=ONEPASS_OFF ){
  105613. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  105614. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  105615. assert( pPk!=0 || pTab->pSelect!=0 );
  105616. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  105617. VdbeCoverage(v);
  105618. }
  105619. }else if( pPk ){
  105620. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  105621. if( IsVirtual(pTab) ){
  105622. sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
  105623. }else{
  105624. sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
  105625. }
  105626. assert( nKey==0 ); /* OP_Found will use a composite key */
  105627. }else{
  105628. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  105629. VdbeCoverage(v);
  105630. assert( nKey==1 );
  105631. }
  105632. /* Delete the row */
  105633. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105634. if( IsVirtual(pTab) ){
  105635. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  105636. sqlite3VtabMakeWritable(pParse, pTab);
  105637. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  105638. sqlite3MayAbort(pParse);
  105639. if( eOnePass==ONEPASS_SINGLE ){
  105640. sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
  105641. if( sqlite3IsToplevel(pParse) ){
  105642. pParse->isMultiWrite = 0;
  105643. }
  105644. }
  105645. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  105646. sqlite3VdbeChangeP5(v, OE_Abort);
  105647. }else
  105648. #endif
  105649. {
  105650. int count = (pParse->nested==0); /* True to count changes */
  105651. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  105652. iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
  105653. }
  105654. /* End of the loop over all rowids/primary-keys. */
  105655. if( eOnePass!=ONEPASS_OFF ){
  105656. sqlite3VdbeResolveLabel(v, addrBypass);
  105657. sqlite3WhereEnd(pWInfo);
  105658. }else if( pPk ){
  105659. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  105660. sqlite3VdbeJumpHere(v, addrLoop);
  105661. }else{
  105662. sqlite3VdbeGoto(v, addrLoop);
  105663. sqlite3VdbeJumpHere(v, addrLoop);
  105664. }
  105665. } /* End non-truncate path */
  105666. /* Update the sqlite_sequence table by storing the content of the
  105667. ** maximum rowid counter values recorded while inserting into
  105668. ** autoincrement tables.
  105669. */
  105670. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  105671. sqlite3AutoincrementEnd(pParse);
  105672. }
  105673. /* Return the number of rows that were deleted. If this routine is
  105674. ** generating code because of a call to sqlite3NestedParse(), do not
  105675. ** invoke the callback function.
  105676. */
  105677. if( memCnt ){
  105678. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  105679. sqlite3VdbeSetNumCols(v, 1);
  105680. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  105681. }
  105682. delete_from_cleanup:
  105683. sqlite3AuthContextPop(&sContext);
  105684. sqlite3SrcListDelete(db, pTabList);
  105685. sqlite3ExprDelete(db, pWhere);
  105686. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  105687. sqlite3ExprListDelete(db, pOrderBy);
  105688. sqlite3ExprDelete(db, pLimit);
  105689. #endif
  105690. sqlite3DbFree(db, aToOpen);
  105691. return;
  105692. }
  105693. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  105694. ** they may interfere with compilation of other functions in this file
  105695. ** (or in another file, if this file becomes part of the amalgamation). */
  105696. #ifdef isView
  105697. #undef isView
  105698. #endif
  105699. #ifdef pTrigger
  105700. #undef pTrigger
  105701. #endif
  105702. /*
  105703. ** This routine generates VDBE code that causes a single row of a
  105704. ** single table to be deleted. Both the original table entry and
  105705. ** all indices are removed.
  105706. **
  105707. ** Preconditions:
  105708. **
  105709. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  105710. ** store for the table. (This will be either the table itself,
  105711. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  105712. ** of a WITHOUT ROWID table.)
  105713. **
  105714. ** 2. Read/write cursors for all indices of pTab must be open as
  105715. ** cursor number iIdxCur+i for the i-th index.
  105716. **
  105717. ** 3. The primary key for the row to be deleted must be stored in a
  105718. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  105719. ** that a search record formed from OP_MakeRecord is contained in the
  105720. ** single memory location iPk.
  105721. **
  105722. ** eMode:
  105723. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  105724. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  105725. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  105726. ** then this function must seek iDataCur to the entry identified by iPk
  105727. ** and nPk before reading from it.
  105728. **
  105729. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  105730. ** of a ONEPASS delete that affects multiple rows. In this case, if
  105731. ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
  105732. ** iDataCur, then its position should be preserved following the delete
  105733. ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
  105734. ** position of iDataCur should be preserved instead.
  105735. **
  105736. ** iIdxNoSeek:
  105737. ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
  105738. ** then it identifies an index cursor (from within array of cursors
  105739. ** starting at iIdxCur) that already points to the index entry to be deleted.
  105740. ** Except, this optimization is disabled if there are BEFORE triggers since
  105741. ** the trigger body might have moved the cursor.
  105742. */
  105743. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  105744. Parse *pParse, /* Parsing context */
  105745. Table *pTab, /* Table containing the row to be deleted */
  105746. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  105747. int iDataCur, /* Cursor from which column data is extracted */
  105748. int iIdxCur, /* First index cursor */
  105749. int iPk, /* First memory cell containing the PRIMARY KEY */
  105750. i16 nPk, /* Number of PRIMARY KEY memory cells */
  105751. u8 count, /* If non-zero, increment the row change counter */
  105752. u8 onconf, /* Default ON CONFLICT policy for triggers */
  105753. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  105754. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  105755. ){
  105756. Vdbe *v = pParse->pVdbe; /* Vdbe */
  105757. int iOld = 0; /* First register in OLD.* array */
  105758. int iLabel; /* Label resolved to end of generated code */
  105759. u8 opSeek; /* Seek opcode */
  105760. /* Vdbe is guaranteed to have been allocated by this stage. */
  105761. assert( v );
  105762. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  105763. iDataCur, iIdxCur, iPk, (int)nPk));
  105764. /* Seek cursor iCur to the row to delete. If this row no longer exists
  105765. ** (this can happen if a trigger program has already deleted it), do
  105766. ** not attempt to delete it or fire any DELETE triggers. */
  105767. iLabel = sqlite3VdbeMakeLabel(pParse);
  105768. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  105769. if( eMode==ONEPASS_OFF ){
  105770. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  105771. VdbeCoverageIf(v, opSeek==OP_NotExists);
  105772. VdbeCoverageIf(v, opSeek==OP_NotFound);
  105773. }
  105774. /* If there are any triggers to fire, allocate a range of registers to
  105775. ** use for the old.* references in the triggers. */
  105776. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  105777. u32 mask; /* Mask of OLD.* columns in use */
  105778. int iCol; /* Iterator used while populating OLD.* */
  105779. int addrStart; /* Start of BEFORE trigger programs */
  105780. /* TODO: Could use temporary registers here. Also could attempt to
  105781. ** avoid copying the contents of the rowid register. */
  105782. mask = sqlite3TriggerColmask(
  105783. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  105784. );
  105785. mask |= sqlite3FkOldmask(pParse, pTab);
  105786. iOld = pParse->nMem+1;
  105787. pParse->nMem += (1 + pTab->nCol);
  105788. /* Populate the OLD.* pseudo-table register array. These values will be
  105789. ** used by any BEFORE and AFTER triggers that exist. */
  105790. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  105791. for(iCol=0; iCol<pTab->nCol; iCol++){
  105792. testcase( mask!=0xffffffff && iCol==31 );
  105793. testcase( mask!=0xffffffff && iCol==32 );
  105794. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  105795. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  105796. }
  105797. }
  105798. /* Invoke BEFORE DELETE trigger programs. */
  105799. addrStart = sqlite3VdbeCurrentAddr(v);
  105800. sqlite3CodeRowTrigger(pParse, pTrigger,
  105801. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  105802. );
  105803. /* If any BEFORE triggers were coded, then seek the cursor to the
  105804. ** row to be deleted again. It may be that the BEFORE triggers moved
  105805. ** the cursor or already deleted the row that the cursor was
  105806. ** pointing to.
  105807. **
  105808. ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
  105809. ** may have moved that cursor.
  105810. */
  105811. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  105812. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  105813. VdbeCoverageIf(v, opSeek==OP_NotExists);
  105814. VdbeCoverageIf(v, opSeek==OP_NotFound);
  105815. testcase( iIdxNoSeek>=0 );
  105816. iIdxNoSeek = -1;
  105817. }
  105818. /* Do FK processing. This call checks that any FK constraints that
  105819. ** refer to this table (i.e. constraints attached to other tables)
  105820. ** are not violated by deleting this row. */
  105821. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  105822. }
  105823. /* Delete the index and table entries. Skip this step if pTab is really
  105824. ** a view (in which case the only effect of the DELETE statement is to
  105825. ** fire the INSTEAD OF triggers).
  105826. **
  105827. ** If variable 'count' is non-zero, then this OP_Delete instruction should
  105828. ** invoke the update-hook. The pre-update-hook, on the other hand should
  105829. ** be invoked unless table pTab is a system table. The difference is that
  105830. ** the update-hook is not invoked for rows removed by REPLACE, but the
  105831. ** pre-update-hook is.
  105832. */
  105833. if( pTab->pSelect==0 ){
  105834. u8 p5 = 0;
  105835. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  105836. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  105837. if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
  105838. sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
  105839. }
  105840. if( eMode!=ONEPASS_OFF ){
  105841. sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
  105842. }
  105843. if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
  105844. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  105845. }
  105846. if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
  105847. sqlite3VdbeChangeP5(v, p5);
  105848. }
  105849. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  105850. ** handle rows (possibly in other tables) that refer via a foreign key
  105851. ** to the row just deleted. */
  105852. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  105853. /* Invoke AFTER DELETE trigger programs. */
  105854. sqlite3CodeRowTrigger(pParse, pTrigger,
  105855. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  105856. );
  105857. /* Jump here if the row had already been deleted before any BEFORE
  105858. ** trigger programs were invoked. Or if a trigger program throws a
  105859. ** RAISE(IGNORE) exception. */
  105860. sqlite3VdbeResolveLabel(v, iLabel);
  105861. VdbeModuleComment((v, "END: GenRowDel()"));
  105862. }
  105863. /*
  105864. ** This routine generates VDBE code that causes the deletion of all
  105865. ** index entries associated with a single row of a single table, pTab
  105866. **
  105867. ** Preconditions:
  105868. **
  105869. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  105870. ** btree for the table pTab. (This will be either the table itself
  105871. ** for rowid tables or to the primary key index for WITHOUT ROWID
  105872. ** tables.)
  105873. **
  105874. ** 2. Read/write cursors for all indices of pTab must be open as
  105875. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  105876. ** index is the 0-th index.)
  105877. **
  105878. ** 3. The "iDataCur" cursor must be already be positioned on the row
  105879. ** that is to be deleted.
  105880. */
  105881. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  105882. Parse *pParse, /* Parsing and code generating context */
  105883. Table *pTab, /* Table containing the row to be deleted */
  105884. int iDataCur, /* Cursor of table holding data. */
  105885. int iIdxCur, /* First index cursor */
  105886. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  105887. int iIdxNoSeek /* Do not delete from this cursor */
  105888. ){
  105889. int i; /* Index loop counter */
  105890. int r1 = -1; /* Register holding an index key */
  105891. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  105892. Index *pIdx; /* Current index */
  105893. Index *pPrior = 0; /* Prior index */
  105894. Vdbe *v; /* The prepared statement under construction */
  105895. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  105896. v = pParse->pVdbe;
  105897. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  105898. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  105899. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  105900. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  105901. if( pIdx==pPk ) continue;
  105902. if( iIdxCur+i==iIdxNoSeek ) continue;
  105903. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  105904. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  105905. &iPartIdxLabel, pPrior, r1);
  105906. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  105907. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  105908. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  105909. pPrior = pIdx;
  105910. }
  105911. }
  105912. /*
  105913. ** Generate code that will assemble an index key and stores it in register
  105914. ** regOut. The key with be for index pIdx which is an index on pTab.
  105915. ** iCur is the index of a cursor open on the pTab table and pointing to
  105916. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  105917. ** iCur must be the cursor of the PRIMARY KEY index.
  105918. **
  105919. ** Return a register number which is the first in a block of
  105920. ** registers that holds the elements of the index key. The
  105921. ** block of registers has already been deallocated by the time
  105922. ** this routine returns.
  105923. **
  105924. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  105925. ** to that label if pIdx is a partial index that should be skipped.
  105926. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  105927. ** A partial index should be skipped if its WHERE clause evaluates
  105928. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  105929. ** will be set to zero which is an empty label that is ignored by
  105930. ** sqlite3ResolvePartIdxLabel().
  105931. **
  105932. ** The pPrior and regPrior parameters are used to implement a cache to
  105933. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  105934. ** a pointer to a different index for which an index key has just been
  105935. ** computed into register regPrior. If the current pIdx index is generating
  105936. ** its key into the same sequence of registers and if pPrior and pIdx share
  105937. ** a column in common, then the register corresponding to that column already
  105938. ** holds the correct value and the loading of that register is skipped.
  105939. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  105940. ** on a table with multiple indices, and especially with the ROWID or
  105941. ** PRIMARY KEY columns of the index.
  105942. */
  105943. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  105944. Parse *pParse, /* Parsing context */
  105945. Index *pIdx, /* The index for which to generate a key */
  105946. int iDataCur, /* Cursor number from which to take column data */
  105947. int regOut, /* Put the new key into this register if not 0 */
  105948. int prefixOnly, /* Compute only a unique prefix of the key */
  105949. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  105950. Index *pPrior, /* Previously generated index key */
  105951. int regPrior /* Register holding previous generated key */
  105952. ){
  105953. Vdbe *v = pParse->pVdbe;
  105954. int j;
  105955. int regBase;
  105956. int nCol;
  105957. if( piPartIdxLabel ){
  105958. if( pIdx->pPartIdxWhere ){
  105959. *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse);
  105960. pParse->iSelfTab = iDataCur + 1;
  105961. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  105962. SQLITE_JUMPIFNULL);
  105963. pParse->iSelfTab = 0;
  105964. }else{
  105965. *piPartIdxLabel = 0;
  105966. }
  105967. }
  105968. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  105969. regBase = sqlite3GetTempRange(pParse, nCol);
  105970. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  105971. for(j=0; j<nCol; j++){
  105972. if( pPrior
  105973. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  105974. && pPrior->aiColumn[j]!=XN_EXPR
  105975. ){
  105976. /* This column was already computed by the previous index */
  105977. continue;
  105978. }
  105979. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  105980. /* If the column affinity is REAL but the number is an integer, then it
  105981. ** might be stored in the table as an integer (using a compact
  105982. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  105983. ** But we are getting ready to store this value back into an index, where
  105984. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  105985. ** opcode if it is present */
  105986. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  105987. }
  105988. if( regOut ){
  105989. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  105990. if( pIdx->pTable->pSelect ){
  105991. const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
  105992. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  105993. }
  105994. }
  105995. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  105996. return regBase;
  105997. }
  105998. /*
  105999. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  106000. ** because it was a partial index, then this routine should be called to
  106001. ** resolve that label.
  106002. */
  106003. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  106004. if( iLabel ){
  106005. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  106006. }
  106007. }
  106008. /************** End of delete.c **********************************************/
  106009. /************** Begin file func.c ********************************************/
  106010. /*
  106011. ** 2002 February 23
  106012. **
  106013. ** The author disclaims copyright to this source code. In place of
  106014. ** a legal notice, here is a blessing:
  106015. **
  106016. ** May you do good and not evil.
  106017. ** May you find forgiveness for yourself and forgive others.
  106018. ** May you share freely, never taking more than you give.
  106019. **
  106020. *************************************************************************
  106021. ** This file contains the C-language implementations for many of the SQL
  106022. ** functions of SQLite. (Some function, and in particular the date and
  106023. ** time functions, are implemented separately.)
  106024. */
  106025. /* #include "sqliteInt.h" */
  106026. /* #include <stdlib.h> */
  106027. /* #include <assert.h> */
  106028. /* #include "vdbeInt.h" */
  106029. /*
  106030. ** Return the collating function associated with a function.
  106031. */
  106032. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  106033. VdbeOp *pOp;
  106034. assert( context->pVdbe!=0 );
  106035. pOp = &context->pVdbe->aOp[context->iOp-1];
  106036. assert( pOp->opcode==OP_CollSeq );
  106037. assert( pOp->p4type==P4_COLLSEQ );
  106038. return pOp->p4.pColl;
  106039. }
  106040. /*
  106041. ** Indicate that the accumulator load should be skipped on this
  106042. ** iteration of the aggregate loop.
  106043. */
  106044. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  106045. assert( context->isError<=0 );
  106046. context->isError = -1;
  106047. context->skipFlag = 1;
  106048. }
  106049. /*
  106050. ** Implementation of the non-aggregate min() and max() functions
  106051. */
  106052. static void minmaxFunc(
  106053. sqlite3_context *context,
  106054. int argc,
  106055. sqlite3_value **argv
  106056. ){
  106057. int i;
  106058. int mask; /* 0 for min() or 0xffffffff for max() */
  106059. int iBest;
  106060. CollSeq *pColl;
  106061. assert( argc>1 );
  106062. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  106063. pColl = sqlite3GetFuncCollSeq(context);
  106064. assert( pColl );
  106065. assert( mask==-1 || mask==0 );
  106066. iBest = 0;
  106067. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  106068. for(i=1; i<argc; i++){
  106069. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  106070. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  106071. testcase( mask==0 );
  106072. iBest = i;
  106073. }
  106074. }
  106075. sqlite3_result_value(context, argv[iBest]);
  106076. }
  106077. /*
  106078. ** Return the type of the argument.
  106079. */
  106080. static void typeofFunc(
  106081. sqlite3_context *context,
  106082. int NotUsed,
  106083. sqlite3_value **argv
  106084. ){
  106085. static const char *azType[] = { "integer", "real", "text", "blob", "null" };
  106086. int i = sqlite3_value_type(argv[0]) - 1;
  106087. UNUSED_PARAMETER(NotUsed);
  106088. assert( i>=0 && i<ArraySize(azType) );
  106089. assert( SQLITE_INTEGER==1 );
  106090. assert( SQLITE_FLOAT==2 );
  106091. assert( SQLITE_TEXT==3 );
  106092. assert( SQLITE_BLOB==4 );
  106093. assert( SQLITE_NULL==5 );
  106094. /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
  106095. ** the datatype code for the initial datatype of the sqlite3_value object
  106096. ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
  106097. ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
  106098. sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
  106099. }
  106100. /*
  106101. ** Implementation of the length() function
  106102. */
  106103. static void lengthFunc(
  106104. sqlite3_context *context,
  106105. int argc,
  106106. sqlite3_value **argv
  106107. ){
  106108. assert( argc==1 );
  106109. UNUSED_PARAMETER(argc);
  106110. switch( sqlite3_value_type(argv[0]) ){
  106111. case SQLITE_BLOB:
  106112. case SQLITE_INTEGER:
  106113. case SQLITE_FLOAT: {
  106114. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  106115. break;
  106116. }
  106117. case SQLITE_TEXT: {
  106118. const unsigned char *z = sqlite3_value_text(argv[0]);
  106119. const unsigned char *z0;
  106120. unsigned char c;
  106121. if( z==0 ) return;
  106122. z0 = z;
  106123. while( (c = *z)!=0 ){
  106124. z++;
  106125. if( c>=0xc0 ){
  106126. while( (*z & 0xc0)==0x80 ){ z++; z0++; }
  106127. }
  106128. }
  106129. sqlite3_result_int(context, (int)(z-z0));
  106130. break;
  106131. }
  106132. default: {
  106133. sqlite3_result_null(context);
  106134. break;
  106135. }
  106136. }
  106137. }
  106138. /*
  106139. ** Implementation of the abs() function.
  106140. **
  106141. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  106142. ** the numeric argument X.
  106143. */
  106144. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  106145. assert( argc==1 );
  106146. UNUSED_PARAMETER(argc);
  106147. switch( sqlite3_value_type(argv[0]) ){
  106148. case SQLITE_INTEGER: {
  106149. i64 iVal = sqlite3_value_int64(argv[0]);
  106150. if( iVal<0 ){
  106151. if( iVal==SMALLEST_INT64 ){
  106152. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  106153. ** then abs(X) throws an integer overflow error since there is no
  106154. ** equivalent positive 64-bit two complement value. */
  106155. sqlite3_result_error(context, "integer overflow", -1);
  106156. return;
  106157. }
  106158. iVal = -iVal;
  106159. }
  106160. sqlite3_result_int64(context, iVal);
  106161. break;
  106162. }
  106163. case SQLITE_NULL: {
  106164. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  106165. sqlite3_result_null(context);
  106166. break;
  106167. }
  106168. default: {
  106169. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  106170. ** something that can be converted into a number, we have:
  106171. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  106172. ** that cannot be converted to a numeric value.
  106173. */
  106174. double rVal = sqlite3_value_double(argv[0]);
  106175. if( rVal<0 ) rVal = -rVal;
  106176. sqlite3_result_double(context, rVal);
  106177. break;
  106178. }
  106179. }
  106180. }
  106181. /*
  106182. ** Implementation of the instr() function.
  106183. **
  106184. ** instr(haystack,needle) finds the first occurrence of needle
  106185. ** in haystack and returns the number of previous characters plus 1,
  106186. ** or 0 if needle does not occur within haystack.
  106187. **
  106188. ** If both haystack and needle are BLOBs, then the result is one more than
  106189. ** the number of bytes in haystack prior to the first occurrence of needle,
  106190. ** or 0 if needle never occurs in haystack.
  106191. */
  106192. static void instrFunc(
  106193. sqlite3_context *context,
  106194. int argc,
  106195. sqlite3_value **argv
  106196. ){
  106197. const unsigned char *zHaystack;
  106198. const unsigned char *zNeedle;
  106199. int nHaystack;
  106200. int nNeedle;
  106201. int typeHaystack, typeNeedle;
  106202. int N = 1;
  106203. int isText;
  106204. unsigned char firstChar;
  106205. UNUSED_PARAMETER(argc);
  106206. typeHaystack = sqlite3_value_type(argv[0]);
  106207. typeNeedle = sqlite3_value_type(argv[1]);
  106208. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  106209. nHaystack = sqlite3_value_bytes(argv[0]);
  106210. nNeedle = sqlite3_value_bytes(argv[1]);
  106211. if( nNeedle>0 ){
  106212. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  106213. zHaystack = sqlite3_value_blob(argv[0]);
  106214. zNeedle = sqlite3_value_blob(argv[1]);
  106215. isText = 0;
  106216. }else{
  106217. zHaystack = sqlite3_value_text(argv[0]);
  106218. zNeedle = sqlite3_value_text(argv[1]);
  106219. isText = 1;
  106220. }
  106221. if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
  106222. firstChar = zNeedle[0];
  106223. while( nNeedle<=nHaystack
  106224. && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0)
  106225. ){
  106226. N++;
  106227. do{
  106228. nHaystack--;
  106229. zHaystack++;
  106230. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  106231. }
  106232. if( nNeedle>nHaystack ) N = 0;
  106233. }
  106234. sqlite3_result_int(context, N);
  106235. }
  106236. /*
  106237. ** Implementation of the printf() function.
  106238. */
  106239. static void printfFunc(
  106240. sqlite3_context *context,
  106241. int argc,
  106242. sqlite3_value **argv
  106243. ){
  106244. PrintfArguments x;
  106245. StrAccum str;
  106246. const char *zFormat;
  106247. int n;
  106248. sqlite3 *db = sqlite3_context_db_handle(context);
  106249. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  106250. x.nArg = argc-1;
  106251. x.nUsed = 0;
  106252. x.apArg = argv+1;
  106253. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  106254. str.printfFlags = SQLITE_PRINTF_SQLFUNC;
  106255. sqlite3_str_appendf(&str, zFormat, &x);
  106256. n = str.nChar;
  106257. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  106258. SQLITE_DYNAMIC);
  106259. }
  106260. }
  106261. /*
  106262. ** Implementation of the substr() function.
  106263. **
  106264. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  106265. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  106266. ** of x. If x is text, then we actually count UTF-8 characters.
  106267. ** If x is a blob, then we count bytes.
  106268. **
  106269. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  106270. **
  106271. ** If p2 is negative, return the p2 characters preceding p1.
  106272. */
  106273. static void substrFunc(
  106274. sqlite3_context *context,
  106275. int argc,
  106276. sqlite3_value **argv
  106277. ){
  106278. const unsigned char *z;
  106279. const unsigned char *z2;
  106280. int len;
  106281. int p0type;
  106282. i64 p1, p2;
  106283. int negP2 = 0;
  106284. assert( argc==3 || argc==2 );
  106285. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  106286. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  106287. ){
  106288. return;
  106289. }
  106290. p0type = sqlite3_value_type(argv[0]);
  106291. p1 = sqlite3_value_int(argv[1]);
  106292. if( p0type==SQLITE_BLOB ){
  106293. len = sqlite3_value_bytes(argv[0]);
  106294. z = sqlite3_value_blob(argv[0]);
  106295. if( z==0 ) return;
  106296. assert( len==sqlite3_value_bytes(argv[0]) );
  106297. }else{
  106298. z = sqlite3_value_text(argv[0]);
  106299. if( z==0 ) return;
  106300. len = 0;
  106301. if( p1<0 ){
  106302. for(z2=z; *z2; len++){
  106303. SQLITE_SKIP_UTF8(z2);
  106304. }
  106305. }
  106306. }
  106307. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  106308. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  106309. ** as substr(X,1,N) - it returns the first N characters of X. This
  106310. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  106311. ** from 2009-02-02 for compatibility of applications that exploited the
  106312. ** old buggy behavior. */
  106313. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  106314. #endif
  106315. if( argc==3 ){
  106316. p2 = sqlite3_value_int(argv[2]);
  106317. if( p2<0 ){
  106318. p2 = -p2;
  106319. negP2 = 1;
  106320. }
  106321. }else{
  106322. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  106323. }
  106324. if( p1<0 ){
  106325. p1 += len;
  106326. if( p1<0 ){
  106327. p2 += p1;
  106328. if( p2<0 ) p2 = 0;
  106329. p1 = 0;
  106330. }
  106331. }else if( p1>0 ){
  106332. p1--;
  106333. }else if( p2>0 ){
  106334. p2--;
  106335. }
  106336. if( negP2 ){
  106337. p1 -= p2;
  106338. if( p1<0 ){
  106339. p2 += p1;
  106340. p1 = 0;
  106341. }
  106342. }
  106343. assert( p1>=0 && p2>=0 );
  106344. if( p0type!=SQLITE_BLOB ){
  106345. while( *z && p1 ){
  106346. SQLITE_SKIP_UTF8(z);
  106347. p1--;
  106348. }
  106349. for(z2=z; *z2 && p2; p2--){
  106350. SQLITE_SKIP_UTF8(z2);
  106351. }
  106352. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  106353. SQLITE_UTF8);
  106354. }else{
  106355. if( p1+p2>len ){
  106356. p2 = len-p1;
  106357. if( p2<0 ) p2 = 0;
  106358. }
  106359. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  106360. }
  106361. }
  106362. /*
  106363. ** Implementation of the round() function
  106364. */
  106365. #ifndef SQLITE_OMIT_FLOATING_POINT
  106366. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  106367. int n = 0;
  106368. double r;
  106369. char *zBuf;
  106370. assert( argc==1 || argc==2 );
  106371. if( argc==2 ){
  106372. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  106373. n = sqlite3_value_int(argv[1]);
  106374. if( n>30 ) n = 30;
  106375. if( n<0 ) n = 0;
  106376. }
  106377. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  106378. r = sqlite3_value_double(argv[0]);
  106379. /* If Y==0 and X will fit in a 64-bit int,
  106380. ** handle the rounding directly,
  106381. ** otherwise use printf.
  106382. */
  106383. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  106384. r = (double)((sqlite_int64)(r+0.5));
  106385. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  106386. r = -(double)((sqlite_int64)((-r)+0.5));
  106387. }else{
  106388. zBuf = sqlite3_mprintf("%.*f",n,r);
  106389. if( zBuf==0 ){
  106390. sqlite3_result_error_nomem(context);
  106391. return;
  106392. }
  106393. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  106394. sqlite3_free(zBuf);
  106395. }
  106396. sqlite3_result_double(context, r);
  106397. }
  106398. #endif
  106399. /*
  106400. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  106401. ** allocation fails, call sqlite3_result_error_nomem() to notify
  106402. ** the database handle that malloc() has failed and return NULL.
  106403. ** If nByte is larger than the maximum string or blob length, then
  106404. ** raise an SQLITE_TOOBIG exception and return NULL.
  106405. */
  106406. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  106407. char *z;
  106408. sqlite3 *db = sqlite3_context_db_handle(context);
  106409. assert( nByte>0 );
  106410. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  106411. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  106412. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  106413. sqlite3_result_error_toobig(context);
  106414. z = 0;
  106415. }else{
  106416. z = sqlite3Malloc(nByte);
  106417. if( !z ){
  106418. sqlite3_result_error_nomem(context);
  106419. }
  106420. }
  106421. return z;
  106422. }
  106423. /*
  106424. ** Implementation of the upper() and lower() SQL functions.
  106425. */
  106426. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  106427. char *z1;
  106428. const char *z2;
  106429. int i, n;
  106430. UNUSED_PARAMETER(argc);
  106431. z2 = (char*)sqlite3_value_text(argv[0]);
  106432. n = sqlite3_value_bytes(argv[0]);
  106433. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  106434. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  106435. if( z2 ){
  106436. z1 = contextMalloc(context, ((i64)n)+1);
  106437. if( z1 ){
  106438. for(i=0; i<n; i++){
  106439. z1[i] = (char)sqlite3Toupper(z2[i]);
  106440. }
  106441. sqlite3_result_text(context, z1, n, sqlite3_free);
  106442. }
  106443. }
  106444. }
  106445. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  106446. char *z1;
  106447. const char *z2;
  106448. int i, n;
  106449. UNUSED_PARAMETER(argc);
  106450. z2 = (char*)sqlite3_value_text(argv[0]);
  106451. n = sqlite3_value_bytes(argv[0]);
  106452. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  106453. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  106454. if( z2 ){
  106455. z1 = contextMalloc(context, ((i64)n)+1);
  106456. if( z1 ){
  106457. for(i=0; i<n; i++){
  106458. z1[i] = sqlite3Tolower(z2[i]);
  106459. }
  106460. sqlite3_result_text(context, z1, n, sqlite3_free);
  106461. }
  106462. }
  106463. }
  106464. /*
  106465. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  106466. ** as VDBE code so that unused argument values do not have to be computed.
  106467. ** However, we still need some kind of function implementation for this
  106468. ** routines in the function table. The noopFunc macro provides this.
  106469. ** noopFunc will never be called so it doesn't matter what the implementation
  106470. ** is. We might as well use the "version()" function as a substitute.
  106471. */
  106472. #define noopFunc versionFunc /* Substitute function - never called */
  106473. /*
  106474. ** Implementation of random(). Return a random integer.
  106475. */
  106476. static void randomFunc(
  106477. sqlite3_context *context,
  106478. int NotUsed,
  106479. sqlite3_value **NotUsed2
  106480. ){
  106481. sqlite_int64 r;
  106482. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  106483. sqlite3_randomness(sizeof(r), &r);
  106484. if( r<0 ){
  106485. /* We need to prevent a random number of 0x8000000000000000
  106486. ** (or -9223372036854775808) since when you do abs() of that
  106487. ** number of you get the same value back again. To do this
  106488. ** in a way that is testable, mask the sign bit off of negative
  106489. ** values, resulting in a positive value. Then take the
  106490. ** 2s complement of that positive value. The end result can
  106491. ** therefore be no less than -9223372036854775807.
  106492. */
  106493. r = -(r & LARGEST_INT64);
  106494. }
  106495. sqlite3_result_int64(context, r);
  106496. }
  106497. /*
  106498. ** Implementation of randomblob(N). Return a random blob
  106499. ** that is N bytes long.
  106500. */
  106501. static void randomBlob(
  106502. sqlite3_context *context,
  106503. int argc,
  106504. sqlite3_value **argv
  106505. ){
  106506. sqlite3_int64 n;
  106507. unsigned char *p;
  106508. assert( argc==1 );
  106509. UNUSED_PARAMETER(argc);
  106510. n = sqlite3_value_int64(argv[0]);
  106511. if( n<1 ){
  106512. n = 1;
  106513. }
  106514. p = contextMalloc(context, n);
  106515. if( p ){
  106516. sqlite3_randomness(n, p);
  106517. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  106518. }
  106519. }
  106520. /*
  106521. ** Implementation of the last_insert_rowid() SQL function. The return
  106522. ** value is the same as the sqlite3_last_insert_rowid() API function.
  106523. */
  106524. static void last_insert_rowid(
  106525. sqlite3_context *context,
  106526. int NotUsed,
  106527. sqlite3_value **NotUsed2
  106528. ){
  106529. sqlite3 *db = sqlite3_context_db_handle(context);
  106530. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  106531. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  106532. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  106533. ** function. */
  106534. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  106535. }
  106536. /*
  106537. ** Implementation of the changes() SQL function.
  106538. **
  106539. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  106540. ** around the sqlite3_changes() C/C++ function and hence follows the same
  106541. ** rules for counting changes.
  106542. */
  106543. static void changes(
  106544. sqlite3_context *context,
  106545. int NotUsed,
  106546. sqlite3_value **NotUsed2
  106547. ){
  106548. sqlite3 *db = sqlite3_context_db_handle(context);
  106549. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  106550. sqlite3_result_int(context, sqlite3_changes(db));
  106551. }
  106552. /*
  106553. ** Implementation of the total_changes() SQL function. The return value is
  106554. ** the same as the sqlite3_total_changes() API function.
  106555. */
  106556. static void total_changes(
  106557. sqlite3_context *context,
  106558. int NotUsed,
  106559. sqlite3_value **NotUsed2
  106560. ){
  106561. sqlite3 *db = sqlite3_context_db_handle(context);
  106562. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  106563. /* IMP: R-52756-41993 This function is a wrapper around the
  106564. ** sqlite3_total_changes() C/C++ interface. */
  106565. sqlite3_result_int(context, sqlite3_total_changes(db));
  106566. }
  106567. /*
  106568. ** A structure defining how to do GLOB-style comparisons.
  106569. */
  106570. struct compareInfo {
  106571. u8 matchAll; /* "*" or "%" */
  106572. u8 matchOne; /* "?" or "_" */
  106573. u8 matchSet; /* "[" or 0 */
  106574. u8 noCase; /* true to ignore case differences */
  106575. };
  106576. /*
  106577. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  106578. ** character is exactly one byte in size. Also, provde the Utf8Read()
  106579. ** macro for fast reading of the next character in the common case where
  106580. ** the next character is ASCII.
  106581. */
  106582. #if defined(SQLITE_EBCDIC)
  106583. # define sqlite3Utf8Read(A) (*((*A)++))
  106584. # define Utf8Read(A) (*(A++))
  106585. #else
  106586. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  106587. #endif
  106588. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  106589. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  106590. ** case. Thus 'a' LIKE 'A' would be true. */
  106591. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  106592. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  106593. ** is case sensitive causing 'a' LIKE 'A' to be false */
  106594. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  106595. /*
  106596. ** Possible error returns from patternMatch()
  106597. */
  106598. #define SQLITE_MATCH 0
  106599. #define SQLITE_NOMATCH 1
  106600. #define SQLITE_NOWILDCARDMATCH 2
  106601. /*
  106602. ** Compare two UTF-8 strings for equality where the first string is
  106603. ** a GLOB or LIKE expression. Return values:
  106604. **
  106605. ** SQLITE_MATCH: Match
  106606. ** SQLITE_NOMATCH: No match
  106607. ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
  106608. **
  106609. ** Globbing rules:
  106610. **
  106611. ** '*' Matches any sequence of zero or more characters.
  106612. **
  106613. ** '?' Matches exactly one character.
  106614. **
  106615. ** [...] Matches one character from the enclosed list of
  106616. ** characters.
  106617. **
  106618. ** [^...] Matches one character not in the enclosed list.
  106619. **
  106620. ** With the [...] and [^...] matching, a ']' character can be included
  106621. ** in the list by making it the first character after '[' or '^'. A
  106622. ** range of characters can be specified using '-'. Example:
  106623. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  106624. ** it the last character in the list.
  106625. **
  106626. ** Like matching rules:
  106627. **
  106628. ** '%' Matches any sequence of zero or more characters
  106629. **
  106630. *** '_' Matches any one character
  106631. **
  106632. ** Ec Where E is the "esc" character and c is any other
  106633. ** character, including '%', '_', and esc, match exactly c.
  106634. **
  106635. ** The comments within this routine usually assume glob matching.
  106636. **
  106637. ** This routine is usually quick, but can be N**2 in the worst case.
  106638. */
  106639. static int patternCompare(
  106640. const u8 *zPattern, /* The glob pattern */
  106641. const u8 *zString, /* The string to compare against the glob */
  106642. const struct compareInfo *pInfo, /* Information about how to do the compare */
  106643. u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
  106644. ){
  106645. u32 c, c2; /* Next pattern and input string chars */
  106646. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  106647. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  106648. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  106649. const u8 *zEscaped = 0; /* One past the last escaped input char */
  106650. while( (c = Utf8Read(zPattern))!=0 ){
  106651. if( c==matchAll ){ /* Match "*" */
  106652. /* Skip over multiple "*" characters in the pattern. If there
  106653. ** are also "?" characters, skip those as well, but consume a
  106654. ** single character of the input string for each "?" skipped */
  106655. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  106656. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  106657. return SQLITE_NOWILDCARDMATCH;
  106658. }
  106659. }
  106660. if( c==0 ){
  106661. return SQLITE_MATCH; /* "*" at the end of the pattern matches */
  106662. }else if( c==matchOther ){
  106663. if( pInfo->matchSet==0 ){
  106664. c = sqlite3Utf8Read(&zPattern);
  106665. if( c==0 ) return SQLITE_NOWILDCARDMATCH;
  106666. }else{
  106667. /* "[...]" immediately follows the "*". We have to do a slow
  106668. ** recursive search in this case, but it is an unusual case. */
  106669. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  106670. while( *zString ){
  106671. int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
  106672. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  106673. SQLITE_SKIP_UTF8(zString);
  106674. }
  106675. return SQLITE_NOWILDCARDMATCH;
  106676. }
  106677. }
  106678. /* At this point variable c contains the first character of the
  106679. ** pattern string past the "*". Search in the input string for the
  106680. ** first matching character and recursively continue the match from
  106681. ** that point.
  106682. **
  106683. ** For a case-insensitive search, set variable cx to be the same as
  106684. ** c but in the other case and search the input string for either
  106685. ** c or cx.
  106686. */
  106687. if( c<=0x80 ){
  106688. char zStop[3];
  106689. int bMatch;
  106690. if( noCase ){
  106691. zStop[0] = sqlite3Toupper(c);
  106692. zStop[1] = sqlite3Tolower(c);
  106693. zStop[2] = 0;
  106694. }else{
  106695. zStop[0] = c;
  106696. zStop[1] = 0;
  106697. }
  106698. while(1){
  106699. zString += strcspn((const char*)zString, zStop);
  106700. if( zString[0]==0 ) break;
  106701. zString++;
  106702. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  106703. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  106704. }
  106705. }else{
  106706. int bMatch;
  106707. while( (c2 = Utf8Read(zString))!=0 ){
  106708. if( c2!=c ) continue;
  106709. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  106710. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  106711. }
  106712. }
  106713. return SQLITE_NOWILDCARDMATCH;
  106714. }
  106715. if( c==matchOther ){
  106716. if( pInfo->matchSet==0 ){
  106717. c = sqlite3Utf8Read(&zPattern);
  106718. if( c==0 ) return SQLITE_NOMATCH;
  106719. zEscaped = zPattern;
  106720. }else{
  106721. u32 prior_c = 0;
  106722. int seen = 0;
  106723. int invert = 0;
  106724. c = sqlite3Utf8Read(&zString);
  106725. if( c==0 ) return SQLITE_NOMATCH;
  106726. c2 = sqlite3Utf8Read(&zPattern);
  106727. if( c2=='^' ){
  106728. invert = 1;
  106729. c2 = sqlite3Utf8Read(&zPattern);
  106730. }
  106731. if( c2==']' ){
  106732. if( c==']' ) seen = 1;
  106733. c2 = sqlite3Utf8Read(&zPattern);
  106734. }
  106735. while( c2 && c2!=']' ){
  106736. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  106737. c2 = sqlite3Utf8Read(&zPattern);
  106738. if( c>=prior_c && c<=c2 ) seen = 1;
  106739. prior_c = 0;
  106740. }else{
  106741. if( c==c2 ){
  106742. seen = 1;
  106743. }
  106744. prior_c = c2;
  106745. }
  106746. c2 = sqlite3Utf8Read(&zPattern);
  106747. }
  106748. if( c2==0 || (seen ^ invert)==0 ){
  106749. return SQLITE_NOMATCH;
  106750. }
  106751. continue;
  106752. }
  106753. }
  106754. c2 = Utf8Read(zString);
  106755. if( c==c2 ) continue;
  106756. if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
  106757. continue;
  106758. }
  106759. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  106760. return SQLITE_NOMATCH;
  106761. }
  106762. return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
  106763. }
  106764. /*
  106765. ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
  106766. ** non-zero if there is no match.
  106767. */
  106768. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  106769. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
  106770. }
  106771. /*
  106772. ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
  106773. ** a miss - like strcmp().
  106774. */
  106775. SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
  106776. return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
  106777. }
  106778. /*
  106779. ** Count the number of times that the LIKE operator (or GLOB which is
  106780. ** just a variation of LIKE) gets called. This is used for testing
  106781. ** only.
  106782. */
  106783. #ifdef SQLITE_TEST
  106784. SQLITE_API int sqlite3_like_count = 0;
  106785. #endif
  106786. /*
  106787. ** Implementation of the like() SQL function. This function implements
  106788. ** the build-in LIKE operator. The first argument to the function is the
  106789. ** pattern and the second argument is the string. So, the SQL statements:
  106790. **
  106791. ** A LIKE B
  106792. **
  106793. ** is implemented as like(B,A).
  106794. **
  106795. ** This same function (with a different compareInfo structure) computes
  106796. ** the GLOB operator.
  106797. */
  106798. static void likeFunc(
  106799. sqlite3_context *context,
  106800. int argc,
  106801. sqlite3_value **argv
  106802. ){
  106803. const unsigned char *zA, *zB;
  106804. u32 escape;
  106805. int nPat;
  106806. sqlite3 *db = sqlite3_context_db_handle(context);
  106807. struct compareInfo *pInfo = sqlite3_user_data(context);
  106808. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  106809. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  106810. || sqlite3_value_type(argv[1])==SQLITE_BLOB
  106811. ){
  106812. #ifdef SQLITE_TEST
  106813. sqlite3_like_count++;
  106814. #endif
  106815. sqlite3_result_int(context, 0);
  106816. return;
  106817. }
  106818. #endif
  106819. zB = sqlite3_value_text(argv[0]);
  106820. zA = sqlite3_value_text(argv[1]);
  106821. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  106822. ** of deep recursion and N*N behavior in patternCompare().
  106823. */
  106824. nPat = sqlite3_value_bytes(argv[0]);
  106825. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  106826. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  106827. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  106828. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  106829. return;
  106830. }
  106831. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  106832. if( argc==3 ){
  106833. /* The escape character string must consist of a single UTF-8 character.
  106834. ** Otherwise, return an error.
  106835. */
  106836. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  106837. if( zEsc==0 ) return;
  106838. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  106839. sqlite3_result_error(context,
  106840. "ESCAPE expression must be a single character", -1);
  106841. return;
  106842. }
  106843. escape = sqlite3Utf8Read(&zEsc);
  106844. }else{
  106845. escape = pInfo->matchSet;
  106846. }
  106847. if( zA && zB ){
  106848. #ifdef SQLITE_TEST
  106849. sqlite3_like_count++;
  106850. #endif
  106851. sqlite3_result_int(context,
  106852. patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
  106853. }
  106854. }
  106855. /*
  106856. ** Implementation of the NULLIF(x,y) function. The result is the first
  106857. ** argument if the arguments are different. The result is NULL if the
  106858. ** arguments are equal to each other.
  106859. */
  106860. static void nullifFunc(
  106861. sqlite3_context *context,
  106862. int NotUsed,
  106863. sqlite3_value **argv
  106864. ){
  106865. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  106866. UNUSED_PARAMETER(NotUsed);
  106867. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  106868. sqlite3_result_value(context, argv[0]);
  106869. }
  106870. }
  106871. /*
  106872. ** Implementation of the sqlite_version() function. The result is the version
  106873. ** of the SQLite library that is running.
  106874. */
  106875. static void versionFunc(
  106876. sqlite3_context *context,
  106877. int NotUsed,
  106878. sqlite3_value **NotUsed2
  106879. ){
  106880. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  106881. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  106882. ** sqlite3_libversion() C-interface. */
  106883. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  106884. }
  106885. /*
  106886. ** Implementation of the sqlite_source_id() function. The result is a string
  106887. ** that identifies the particular version of the source code used to build
  106888. ** SQLite.
  106889. */
  106890. static void sourceidFunc(
  106891. sqlite3_context *context,
  106892. int NotUsed,
  106893. sqlite3_value **NotUsed2
  106894. ){
  106895. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  106896. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  106897. ** sqlite3_sourceid() C interface. */
  106898. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  106899. }
  106900. /*
  106901. ** Implementation of the sqlite_log() function. This is a wrapper around
  106902. ** sqlite3_log(). The return value is NULL. The function exists purely for
  106903. ** its side-effects.
  106904. */
  106905. static void errlogFunc(
  106906. sqlite3_context *context,
  106907. int argc,
  106908. sqlite3_value **argv
  106909. ){
  106910. UNUSED_PARAMETER(argc);
  106911. UNUSED_PARAMETER(context);
  106912. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  106913. }
  106914. /*
  106915. ** Implementation of the sqlite_compileoption_used() function.
  106916. ** The result is an integer that identifies if the compiler option
  106917. ** was used to build SQLite.
  106918. */
  106919. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  106920. static void compileoptionusedFunc(
  106921. sqlite3_context *context,
  106922. int argc,
  106923. sqlite3_value **argv
  106924. ){
  106925. const char *zOptName;
  106926. assert( argc==1 );
  106927. UNUSED_PARAMETER(argc);
  106928. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  106929. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  106930. ** function.
  106931. */
  106932. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  106933. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  106934. }
  106935. }
  106936. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  106937. /*
  106938. ** Implementation of the sqlite_compileoption_get() function.
  106939. ** The result is a string that identifies the compiler options
  106940. ** used to build SQLite.
  106941. */
  106942. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  106943. static void compileoptiongetFunc(
  106944. sqlite3_context *context,
  106945. int argc,
  106946. sqlite3_value **argv
  106947. ){
  106948. int n;
  106949. assert( argc==1 );
  106950. UNUSED_PARAMETER(argc);
  106951. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  106952. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  106953. */
  106954. n = sqlite3_value_int(argv[0]);
  106955. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  106956. }
  106957. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  106958. /* Array for converting from half-bytes (nybbles) into ASCII hex
  106959. ** digits. */
  106960. static const char hexdigits[] = {
  106961. '0', '1', '2', '3', '4', '5', '6', '7',
  106962. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  106963. };
  106964. /*
  106965. ** Implementation of the QUOTE() function. This function takes a single
  106966. ** argument. If the argument is numeric, the return value is the same as
  106967. ** the argument. If the argument is NULL, the return value is the string
  106968. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  106969. ** single-quote escapes.
  106970. */
  106971. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  106972. assert( argc==1 );
  106973. UNUSED_PARAMETER(argc);
  106974. switch( sqlite3_value_type(argv[0]) ){
  106975. case SQLITE_FLOAT: {
  106976. double r1, r2;
  106977. char zBuf[50];
  106978. r1 = sqlite3_value_double(argv[0]);
  106979. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  106980. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  106981. if( r1!=r2 ){
  106982. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  106983. }
  106984. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  106985. break;
  106986. }
  106987. case SQLITE_INTEGER: {
  106988. sqlite3_result_value(context, argv[0]);
  106989. break;
  106990. }
  106991. case SQLITE_BLOB: {
  106992. char *zText = 0;
  106993. char const *zBlob = sqlite3_value_blob(argv[0]);
  106994. int nBlob = sqlite3_value_bytes(argv[0]);
  106995. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  106996. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  106997. if( zText ){
  106998. int i;
  106999. for(i=0; i<nBlob; i++){
  107000. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  107001. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  107002. }
  107003. zText[(nBlob*2)+2] = '\'';
  107004. zText[(nBlob*2)+3] = '\0';
  107005. zText[0] = 'X';
  107006. zText[1] = '\'';
  107007. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  107008. sqlite3_free(zText);
  107009. }
  107010. break;
  107011. }
  107012. case SQLITE_TEXT: {
  107013. int i,j;
  107014. u64 n;
  107015. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  107016. char *z;
  107017. if( zArg==0 ) return;
  107018. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  107019. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  107020. if( z ){
  107021. z[0] = '\'';
  107022. for(i=0, j=1; zArg[i]; i++){
  107023. z[j++] = zArg[i];
  107024. if( zArg[i]=='\'' ){
  107025. z[j++] = '\'';
  107026. }
  107027. }
  107028. z[j++] = '\'';
  107029. z[j] = 0;
  107030. sqlite3_result_text(context, z, j, sqlite3_free);
  107031. }
  107032. break;
  107033. }
  107034. default: {
  107035. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  107036. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  107037. break;
  107038. }
  107039. }
  107040. }
  107041. /*
  107042. ** The unicode() function. Return the integer unicode code-point value
  107043. ** for the first character of the input string.
  107044. */
  107045. static void unicodeFunc(
  107046. sqlite3_context *context,
  107047. int argc,
  107048. sqlite3_value **argv
  107049. ){
  107050. const unsigned char *z = sqlite3_value_text(argv[0]);
  107051. (void)argc;
  107052. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  107053. }
  107054. /*
  107055. ** The char() function takes zero or more arguments, each of which is
  107056. ** an integer. It constructs a string where each character of the string
  107057. ** is the unicode character for the corresponding integer argument.
  107058. */
  107059. static void charFunc(
  107060. sqlite3_context *context,
  107061. int argc,
  107062. sqlite3_value **argv
  107063. ){
  107064. unsigned char *z, *zOut;
  107065. int i;
  107066. zOut = z = sqlite3_malloc64( argc*4+1 );
  107067. if( z==0 ){
  107068. sqlite3_result_error_nomem(context);
  107069. return;
  107070. }
  107071. for(i=0; i<argc; i++){
  107072. sqlite3_int64 x;
  107073. unsigned c;
  107074. x = sqlite3_value_int64(argv[i]);
  107075. if( x<0 || x>0x10ffff ) x = 0xfffd;
  107076. c = (unsigned)(x & 0x1fffff);
  107077. if( c<0x00080 ){
  107078. *zOut++ = (u8)(c&0xFF);
  107079. }else if( c<0x00800 ){
  107080. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  107081. *zOut++ = 0x80 + (u8)(c & 0x3F);
  107082. }else if( c<0x10000 ){
  107083. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  107084. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  107085. *zOut++ = 0x80 + (u8)(c & 0x3F);
  107086. }else{
  107087. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  107088. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  107089. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  107090. *zOut++ = 0x80 + (u8)(c & 0x3F);
  107091. } \
  107092. }
  107093. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  107094. }
  107095. /*
  107096. ** The hex() function. Interpret the argument as a blob. Return
  107097. ** a hexadecimal rendering as text.
  107098. */
  107099. static void hexFunc(
  107100. sqlite3_context *context,
  107101. int argc,
  107102. sqlite3_value **argv
  107103. ){
  107104. int i, n;
  107105. const unsigned char *pBlob;
  107106. char *zHex, *z;
  107107. assert( argc==1 );
  107108. UNUSED_PARAMETER(argc);
  107109. pBlob = sqlite3_value_blob(argv[0]);
  107110. n = sqlite3_value_bytes(argv[0]);
  107111. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  107112. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  107113. if( zHex ){
  107114. for(i=0; i<n; i++, pBlob++){
  107115. unsigned char c = *pBlob;
  107116. *(z++) = hexdigits[(c>>4)&0xf];
  107117. *(z++) = hexdigits[c&0xf];
  107118. }
  107119. *z = 0;
  107120. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  107121. }
  107122. }
  107123. /*
  107124. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  107125. */
  107126. static void zeroblobFunc(
  107127. sqlite3_context *context,
  107128. int argc,
  107129. sqlite3_value **argv
  107130. ){
  107131. i64 n;
  107132. int rc;
  107133. assert( argc==1 );
  107134. UNUSED_PARAMETER(argc);
  107135. n = sqlite3_value_int64(argv[0]);
  107136. if( n<0 ) n = 0;
  107137. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  107138. if( rc ){
  107139. sqlite3_result_error_code(context, rc);
  107140. }
  107141. }
  107142. /*
  107143. ** The replace() function. Three arguments are all strings: call
  107144. ** them A, B, and C. The result is also a string which is derived
  107145. ** from A by replacing every occurrence of B with C. The match
  107146. ** must be exact. Collating sequences are not used.
  107147. */
  107148. static void replaceFunc(
  107149. sqlite3_context *context,
  107150. int argc,
  107151. sqlite3_value **argv
  107152. ){
  107153. const unsigned char *zStr; /* The input string A */
  107154. const unsigned char *zPattern; /* The pattern string B */
  107155. const unsigned char *zRep; /* The replacement string C */
  107156. unsigned char *zOut; /* The output */
  107157. int nStr; /* Size of zStr */
  107158. int nPattern; /* Size of zPattern */
  107159. int nRep; /* Size of zRep */
  107160. i64 nOut; /* Maximum size of zOut */
  107161. int loopLimit; /* Last zStr[] that might match zPattern[] */
  107162. int i, j; /* Loop counters */
  107163. unsigned cntExpand; /* Number zOut expansions */
  107164. sqlite3 *db = sqlite3_context_db_handle(context);
  107165. assert( argc==3 );
  107166. UNUSED_PARAMETER(argc);
  107167. zStr = sqlite3_value_text(argv[0]);
  107168. if( zStr==0 ) return;
  107169. nStr = sqlite3_value_bytes(argv[0]);
  107170. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  107171. zPattern = sqlite3_value_text(argv[1]);
  107172. if( zPattern==0 ){
  107173. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  107174. || sqlite3_context_db_handle(context)->mallocFailed );
  107175. return;
  107176. }
  107177. if( zPattern[0]==0 ){
  107178. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  107179. sqlite3_result_value(context, argv[0]);
  107180. return;
  107181. }
  107182. nPattern = sqlite3_value_bytes(argv[1]);
  107183. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  107184. zRep = sqlite3_value_text(argv[2]);
  107185. if( zRep==0 ) return;
  107186. nRep = sqlite3_value_bytes(argv[2]);
  107187. assert( zRep==sqlite3_value_text(argv[2]) );
  107188. nOut = nStr + 1;
  107189. assert( nOut<SQLITE_MAX_LENGTH );
  107190. zOut = contextMalloc(context, (i64)nOut);
  107191. if( zOut==0 ){
  107192. return;
  107193. }
  107194. loopLimit = nStr - nPattern;
  107195. cntExpand = 0;
  107196. for(i=j=0; i<=loopLimit; i++){
  107197. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  107198. zOut[j++] = zStr[i];
  107199. }else{
  107200. if( nRep>nPattern ){
  107201. nOut += nRep - nPattern;
  107202. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  107203. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  107204. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  107205. sqlite3_result_error_toobig(context);
  107206. sqlite3_free(zOut);
  107207. return;
  107208. }
  107209. cntExpand++;
  107210. if( (cntExpand&(cntExpand-1))==0 ){
  107211. /* Grow the size of the output buffer only on substitutions
  107212. ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
  107213. u8 *zOld;
  107214. zOld = zOut;
  107215. zOut = sqlite3_realloc64(zOut, (int)nOut + (nOut - nStr - 1));
  107216. if( zOut==0 ){
  107217. sqlite3_result_error_nomem(context);
  107218. sqlite3_free(zOld);
  107219. return;
  107220. }
  107221. }
  107222. }
  107223. memcpy(&zOut[j], zRep, nRep);
  107224. j += nRep;
  107225. i += nPattern-1;
  107226. }
  107227. }
  107228. assert( j+nStr-i+1<=nOut );
  107229. memcpy(&zOut[j], &zStr[i], nStr-i);
  107230. j += nStr - i;
  107231. assert( j<=nOut );
  107232. zOut[j] = 0;
  107233. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  107234. }
  107235. /*
  107236. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  107237. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  107238. */
  107239. static void trimFunc(
  107240. sqlite3_context *context,
  107241. int argc,
  107242. sqlite3_value **argv
  107243. ){
  107244. const unsigned char *zIn; /* Input string */
  107245. const unsigned char *zCharSet; /* Set of characters to trim */
  107246. int nIn; /* Number of bytes in input */
  107247. int flags; /* 1: trimleft 2: trimright 3: trim */
  107248. int i; /* Loop counter */
  107249. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  107250. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  107251. int nChar; /* Number of characters in zCharSet */
  107252. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  107253. return;
  107254. }
  107255. zIn = sqlite3_value_text(argv[0]);
  107256. if( zIn==0 ) return;
  107257. nIn = sqlite3_value_bytes(argv[0]);
  107258. assert( zIn==sqlite3_value_text(argv[0]) );
  107259. if( argc==1 ){
  107260. static const unsigned char lenOne[] = { 1 };
  107261. static unsigned char * const azOne[] = { (u8*)" " };
  107262. nChar = 1;
  107263. aLen = (u8*)lenOne;
  107264. azChar = (unsigned char **)azOne;
  107265. zCharSet = 0;
  107266. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  107267. return;
  107268. }else{
  107269. const unsigned char *z;
  107270. for(z=zCharSet, nChar=0; *z; nChar++){
  107271. SQLITE_SKIP_UTF8(z);
  107272. }
  107273. if( nChar>0 ){
  107274. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  107275. if( azChar==0 ){
  107276. return;
  107277. }
  107278. aLen = (unsigned char*)&azChar[nChar];
  107279. for(z=zCharSet, nChar=0; *z; nChar++){
  107280. azChar[nChar] = (unsigned char *)z;
  107281. SQLITE_SKIP_UTF8(z);
  107282. aLen[nChar] = (u8)(z - azChar[nChar]);
  107283. }
  107284. }
  107285. }
  107286. if( nChar>0 ){
  107287. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  107288. if( flags & 1 ){
  107289. while( nIn>0 ){
  107290. int len = 0;
  107291. for(i=0; i<nChar; i++){
  107292. len = aLen[i];
  107293. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  107294. }
  107295. if( i>=nChar ) break;
  107296. zIn += len;
  107297. nIn -= len;
  107298. }
  107299. }
  107300. if( flags & 2 ){
  107301. while( nIn>0 ){
  107302. int len = 0;
  107303. for(i=0; i<nChar; i++){
  107304. len = aLen[i];
  107305. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  107306. }
  107307. if( i>=nChar ) break;
  107308. nIn -= len;
  107309. }
  107310. }
  107311. if( zCharSet ){
  107312. sqlite3_free(azChar);
  107313. }
  107314. }
  107315. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  107316. }
  107317. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  107318. /*
  107319. ** The "unknown" function is automatically substituted in place of
  107320. ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
  107321. ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
  107322. ** When the "sqlite3" command-line shell is built using this functionality,
  107323. ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
  107324. ** involving application-defined functions to be examined in a generic
  107325. ** sqlite3 shell.
  107326. */
  107327. static void unknownFunc(
  107328. sqlite3_context *context,
  107329. int argc,
  107330. sqlite3_value **argv
  107331. ){
  107332. /* no-op */
  107333. }
  107334. #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
  107335. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  107336. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  107337. ** when SQLite is built.
  107338. */
  107339. #ifdef SQLITE_SOUNDEX
  107340. /*
  107341. ** Compute the soundex encoding of a word.
  107342. **
  107343. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  107344. ** soundex encoding of the string X.
  107345. */
  107346. static void soundexFunc(
  107347. sqlite3_context *context,
  107348. int argc,
  107349. sqlite3_value **argv
  107350. ){
  107351. char zResult[8];
  107352. const u8 *zIn;
  107353. int i, j;
  107354. static const unsigned char iCode[] = {
  107355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  107356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  107357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  107358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  107359. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  107360. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  107361. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  107362. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  107363. };
  107364. assert( argc==1 );
  107365. zIn = (u8*)sqlite3_value_text(argv[0]);
  107366. if( zIn==0 ) zIn = (u8*)"";
  107367. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  107368. if( zIn[i] ){
  107369. u8 prevcode = iCode[zIn[i]&0x7f];
  107370. zResult[0] = sqlite3Toupper(zIn[i]);
  107371. for(j=1; j<4 && zIn[i]; i++){
  107372. int code = iCode[zIn[i]&0x7f];
  107373. if( code>0 ){
  107374. if( code!=prevcode ){
  107375. prevcode = code;
  107376. zResult[j++] = code + '0';
  107377. }
  107378. }else{
  107379. prevcode = 0;
  107380. }
  107381. }
  107382. while( j<4 ){
  107383. zResult[j++] = '0';
  107384. }
  107385. zResult[j] = 0;
  107386. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  107387. }else{
  107388. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  107389. ** is NULL or contains no ASCII alphabetic characters. */
  107390. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  107391. }
  107392. }
  107393. #endif /* SQLITE_SOUNDEX */
  107394. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  107395. /*
  107396. ** A function that loads a shared-library extension then returns NULL.
  107397. */
  107398. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  107399. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  107400. const char *zProc;
  107401. sqlite3 *db = sqlite3_context_db_handle(context);
  107402. char *zErrMsg = 0;
  107403. /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
  107404. ** flag is set. See the sqlite3_enable_load_extension() API.
  107405. */
  107406. if( (db->flags & SQLITE_LoadExtFunc)==0 ){
  107407. sqlite3_result_error(context, "not authorized", -1);
  107408. return;
  107409. }
  107410. if( argc==2 ){
  107411. zProc = (const char *)sqlite3_value_text(argv[1]);
  107412. }else{
  107413. zProc = 0;
  107414. }
  107415. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  107416. sqlite3_result_error(context, zErrMsg, -1);
  107417. sqlite3_free(zErrMsg);
  107418. }
  107419. }
  107420. #endif
  107421. /*
  107422. ** An instance of the following structure holds the context of a
  107423. ** sum() or avg() aggregate computation.
  107424. */
  107425. typedef struct SumCtx SumCtx;
  107426. struct SumCtx {
  107427. double rSum; /* Floating point sum */
  107428. i64 iSum; /* Integer sum */
  107429. i64 cnt; /* Number of elements summed */
  107430. u8 overflow; /* True if integer overflow seen */
  107431. u8 approx; /* True if non-integer value was input to the sum */
  107432. };
  107433. /*
  107434. ** Routines used to compute the sum, average, and total.
  107435. **
  107436. ** The SUM() function follows the (broken) SQL standard which means
  107437. ** that it returns NULL if it sums over no inputs. TOTAL returns
  107438. ** 0.0 in that case. In addition, TOTAL always returns a float where
  107439. ** SUM might return an integer if it never encounters a floating point
  107440. ** value. TOTAL never fails, but SUM might through an exception if
  107441. ** it overflows an integer.
  107442. */
  107443. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  107444. SumCtx *p;
  107445. int type;
  107446. assert( argc==1 );
  107447. UNUSED_PARAMETER(argc);
  107448. p = sqlite3_aggregate_context(context, sizeof(*p));
  107449. type = sqlite3_value_numeric_type(argv[0]);
  107450. if( p && type!=SQLITE_NULL ){
  107451. p->cnt++;
  107452. if( type==SQLITE_INTEGER ){
  107453. i64 v = sqlite3_value_int64(argv[0]);
  107454. p->rSum += v;
  107455. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  107456. p->approx = p->overflow = 1;
  107457. }
  107458. }else{
  107459. p->rSum += sqlite3_value_double(argv[0]);
  107460. p->approx = 1;
  107461. }
  107462. }
  107463. }
  107464. #ifndef SQLITE_OMIT_WINDOWFUNC
  107465. static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){
  107466. SumCtx *p;
  107467. int type;
  107468. assert( argc==1 );
  107469. UNUSED_PARAMETER(argc);
  107470. p = sqlite3_aggregate_context(context, sizeof(*p));
  107471. type = sqlite3_value_numeric_type(argv[0]);
  107472. /* p is always non-NULL because sumStep() will have been called first
  107473. ** to initialize it */
  107474. if( ALWAYS(p) && type!=SQLITE_NULL ){
  107475. assert( p->cnt>0 );
  107476. p->cnt--;
  107477. assert( type==SQLITE_INTEGER || p->approx );
  107478. if( type==SQLITE_INTEGER && p->approx==0 ){
  107479. i64 v = sqlite3_value_int64(argv[0]);
  107480. p->rSum -= v;
  107481. p->iSum -= v;
  107482. }else{
  107483. p->rSum -= sqlite3_value_double(argv[0]);
  107484. }
  107485. }
  107486. }
  107487. #else
  107488. # define sumInverse 0
  107489. #endif /* SQLITE_OMIT_WINDOWFUNC */
  107490. static void sumFinalize(sqlite3_context *context){
  107491. SumCtx *p;
  107492. p = sqlite3_aggregate_context(context, 0);
  107493. if( p && p->cnt>0 ){
  107494. if( p->overflow ){
  107495. sqlite3_result_error(context,"integer overflow",-1);
  107496. }else if( p->approx ){
  107497. sqlite3_result_double(context, p->rSum);
  107498. }else{
  107499. sqlite3_result_int64(context, p->iSum);
  107500. }
  107501. }
  107502. }
  107503. static void avgFinalize(sqlite3_context *context){
  107504. SumCtx *p;
  107505. p = sqlite3_aggregate_context(context, 0);
  107506. if( p && p->cnt>0 ){
  107507. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  107508. }
  107509. }
  107510. static void totalFinalize(sqlite3_context *context){
  107511. SumCtx *p;
  107512. p = sqlite3_aggregate_context(context, 0);
  107513. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  107514. sqlite3_result_double(context, p ? p->rSum : (double)0);
  107515. }
  107516. /*
  107517. ** The following structure keeps track of state information for the
  107518. ** count() aggregate function.
  107519. */
  107520. typedef struct CountCtx CountCtx;
  107521. struct CountCtx {
  107522. i64 n;
  107523. #ifdef SQLITE_DEBUG
  107524. int bInverse; /* True if xInverse() ever called */
  107525. #endif
  107526. };
  107527. /*
  107528. ** Routines to implement the count() aggregate function.
  107529. */
  107530. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  107531. CountCtx *p;
  107532. p = sqlite3_aggregate_context(context, sizeof(*p));
  107533. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  107534. p->n++;
  107535. }
  107536. #ifndef SQLITE_OMIT_DEPRECATED
  107537. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  107538. ** sure it still operates correctly, verify that its count agrees with our
  107539. ** internal count when using count(*) and when the total count can be
  107540. ** expressed as a 32-bit integer. */
  107541. assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
  107542. || p->n==sqlite3_aggregate_count(context) );
  107543. #endif
  107544. }
  107545. static void countFinalize(sqlite3_context *context){
  107546. CountCtx *p;
  107547. p = sqlite3_aggregate_context(context, 0);
  107548. sqlite3_result_int64(context, p ? p->n : 0);
  107549. }
  107550. #ifndef SQLITE_OMIT_WINDOWFUNC
  107551. static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
  107552. CountCtx *p;
  107553. p = sqlite3_aggregate_context(ctx, sizeof(*p));
  107554. /* p is always non-NULL since countStep() will have been called first */
  107555. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){
  107556. p->n--;
  107557. #ifdef SQLITE_DEBUG
  107558. p->bInverse = 1;
  107559. #endif
  107560. }
  107561. }
  107562. #else
  107563. # define countInverse 0
  107564. #endif /* SQLITE_OMIT_WINDOWFUNC */
  107565. /*
  107566. ** Routines to implement min() and max() aggregate functions.
  107567. */
  107568. static void minmaxStep(
  107569. sqlite3_context *context,
  107570. int NotUsed,
  107571. sqlite3_value **argv
  107572. ){
  107573. Mem *pArg = (Mem *)argv[0];
  107574. Mem *pBest;
  107575. UNUSED_PARAMETER(NotUsed);
  107576. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  107577. if( !pBest ) return;
  107578. if( sqlite3_value_type(pArg)==SQLITE_NULL ){
  107579. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  107580. }else if( pBest->flags ){
  107581. int max;
  107582. int cmp;
  107583. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  107584. /* This step function is used for both the min() and max() aggregates,
  107585. ** the only difference between the two being that the sense of the
  107586. ** comparison is inverted. For the max() aggregate, the
  107587. ** sqlite3_user_data() function returns (void *)-1. For min() it
  107588. ** returns (void *)db, where db is the sqlite3* database pointer.
  107589. ** Therefore the next statement sets variable 'max' to 1 for the max()
  107590. ** aggregate, or 0 for min().
  107591. */
  107592. max = sqlite3_user_data(context)!=0;
  107593. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  107594. if( (max && cmp<0) || (!max && cmp>0) ){
  107595. sqlite3VdbeMemCopy(pBest, pArg);
  107596. }else{
  107597. sqlite3SkipAccumulatorLoad(context);
  107598. }
  107599. }else{
  107600. pBest->db = sqlite3_context_db_handle(context);
  107601. sqlite3VdbeMemCopy(pBest, pArg);
  107602. }
  107603. }
  107604. static void minMaxValueFinalize(sqlite3_context *context, int bValue){
  107605. sqlite3_value *pRes;
  107606. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  107607. if( pRes ){
  107608. if( pRes->flags ){
  107609. sqlite3_result_value(context, pRes);
  107610. }
  107611. if( bValue==0 ) sqlite3VdbeMemRelease(pRes);
  107612. }
  107613. }
  107614. #ifndef SQLITE_OMIT_WINDOWFUNC
  107615. static void minMaxValue(sqlite3_context *context){
  107616. minMaxValueFinalize(context, 1);
  107617. }
  107618. #else
  107619. # define minMaxValue 0
  107620. #endif /* SQLITE_OMIT_WINDOWFUNC */
  107621. static void minMaxFinalize(sqlite3_context *context){
  107622. minMaxValueFinalize(context, 0);
  107623. }
  107624. /*
  107625. ** group_concat(EXPR, ?SEPARATOR?)
  107626. */
  107627. static void groupConcatStep(
  107628. sqlite3_context *context,
  107629. int argc,
  107630. sqlite3_value **argv
  107631. ){
  107632. const char *zVal;
  107633. StrAccum *pAccum;
  107634. const char *zSep;
  107635. int nVal, nSep;
  107636. assert( argc==1 || argc==2 );
  107637. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  107638. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  107639. if( pAccum ){
  107640. sqlite3 *db = sqlite3_context_db_handle(context);
  107641. int firstTerm = pAccum->mxAlloc==0;
  107642. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  107643. if( !firstTerm ){
  107644. if( argc==2 ){
  107645. zSep = (char*)sqlite3_value_text(argv[1]);
  107646. nSep = sqlite3_value_bytes(argv[1]);
  107647. }else{
  107648. zSep = ",";
  107649. nSep = 1;
  107650. }
  107651. if( zSep ) sqlite3_str_append(pAccum, zSep, nSep);
  107652. }
  107653. zVal = (char*)sqlite3_value_text(argv[0]);
  107654. nVal = sqlite3_value_bytes(argv[0]);
  107655. if( zVal ) sqlite3_str_append(pAccum, zVal, nVal);
  107656. }
  107657. }
  107658. #ifndef SQLITE_OMIT_WINDOWFUNC
  107659. static void groupConcatInverse(
  107660. sqlite3_context *context,
  107661. int argc,
  107662. sqlite3_value **argv
  107663. ){
  107664. int n;
  107665. StrAccum *pAccum;
  107666. assert( argc==1 || argc==2 );
  107667. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  107668. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  107669. /* pAccum is always non-NULL since groupConcatStep() will have always
  107670. ** run frist to initialize it */
  107671. if( ALWAYS(pAccum) ){
  107672. n = sqlite3_value_bytes(argv[0]);
  107673. if( argc==2 ){
  107674. n += sqlite3_value_bytes(argv[1]);
  107675. }else{
  107676. n++;
  107677. }
  107678. if( n>=(int)pAccum->nChar ){
  107679. pAccum->nChar = 0;
  107680. }else{
  107681. pAccum->nChar -= n;
  107682. memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar);
  107683. }
  107684. if( pAccum->nChar==0 ) pAccum->mxAlloc = 0;
  107685. }
  107686. }
  107687. #else
  107688. # define groupConcatInverse 0
  107689. #endif /* SQLITE_OMIT_WINDOWFUNC */
  107690. static void groupConcatFinalize(sqlite3_context *context){
  107691. StrAccum *pAccum;
  107692. pAccum = sqlite3_aggregate_context(context, 0);
  107693. if( pAccum ){
  107694. if( pAccum->accError==SQLITE_TOOBIG ){
  107695. sqlite3_result_error_toobig(context);
  107696. }else if( pAccum->accError==SQLITE_NOMEM ){
  107697. sqlite3_result_error_nomem(context);
  107698. }else{
  107699. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  107700. sqlite3_free);
  107701. }
  107702. }
  107703. }
  107704. #ifndef SQLITE_OMIT_WINDOWFUNC
  107705. static void groupConcatValue(sqlite3_context *context){
  107706. sqlite3_str *pAccum;
  107707. pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0);
  107708. if( pAccum ){
  107709. if( pAccum->accError==SQLITE_TOOBIG ){
  107710. sqlite3_result_error_toobig(context);
  107711. }else if( pAccum->accError==SQLITE_NOMEM ){
  107712. sqlite3_result_error_nomem(context);
  107713. }else{
  107714. const char *zText = sqlite3_str_value(pAccum);
  107715. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  107716. }
  107717. }
  107718. }
  107719. #else
  107720. # define groupConcatValue 0
  107721. #endif /* SQLITE_OMIT_WINDOWFUNC */
  107722. /*
  107723. ** This routine does per-connection function registration. Most
  107724. ** of the built-in functions above are part of the global function set.
  107725. ** This routine only deals with those that are not global.
  107726. */
  107727. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
  107728. int rc = sqlite3_overload_function(db, "MATCH", 2);
  107729. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  107730. if( rc==SQLITE_NOMEM ){
  107731. sqlite3OomFault(db);
  107732. }
  107733. }
  107734. /*
  107735. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  107736. */
  107737. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  107738. FuncDef *pDef;
  107739. pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
  107740. if( ALWAYS(pDef) ){
  107741. pDef->funcFlags |= flagVal;
  107742. }
  107743. pDef = sqlite3FindFunction(db, zName, 3, SQLITE_UTF8, 0);
  107744. if( pDef ){
  107745. pDef->funcFlags |= flagVal;
  107746. }
  107747. }
  107748. /*
  107749. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  107750. ** parameter determines whether or not the LIKE operator is case
  107751. ** sensitive. GLOB is always case sensitive.
  107752. */
  107753. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  107754. struct compareInfo *pInfo;
  107755. if( caseSensitive ){
  107756. pInfo = (struct compareInfo*)&likeInfoAlt;
  107757. }else{
  107758. pInfo = (struct compareInfo*)&likeInfoNorm;
  107759. }
  107760. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
  107761. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
  107762. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  107763. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0, 0, 0);
  107764. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  107765. setLikeOptFlag(db, "like",
  107766. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  107767. }
  107768. /*
  107769. ** pExpr points to an expression which implements a function. If
  107770. ** it is appropriate to apply the LIKE optimization to that function
  107771. ** then set aWc[0] through aWc[2] to the wildcard characters and the
  107772. ** escape character and then return TRUE. If the function is not a
  107773. ** LIKE-style function then return FALSE.
  107774. **
  107775. ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
  107776. ** operator if c is a string literal that is exactly one byte in length.
  107777. ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
  107778. ** no ESCAPE clause.
  107779. **
  107780. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  107781. ** the function (default for LIKE). If the function makes the distinction
  107782. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  107783. ** false.
  107784. */
  107785. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  107786. FuncDef *pDef;
  107787. int nExpr;
  107788. if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
  107789. return 0;
  107790. }
  107791. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  107792. nExpr = pExpr->x.pList->nExpr;
  107793. pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
  107794. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  107795. return 0;
  107796. }
  107797. if( nExpr<3 ){
  107798. aWc[3] = 0;
  107799. }else{
  107800. Expr *pEscape = pExpr->x.pList->a[2].pExpr;
  107801. char *zEscape;
  107802. if( pEscape->op!=TK_STRING ) return 0;
  107803. zEscape = pEscape->u.zToken;
  107804. if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
  107805. aWc[3] = zEscape[0];
  107806. }
  107807. /* The memcpy() statement assumes that the wildcard characters are
  107808. ** the first three statements in the compareInfo structure. The
  107809. ** asserts() that follow verify that assumption
  107810. */
  107811. memcpy(aWc, pDef->pUserData, 3);
  107812. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  107813. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  107814. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  107815. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  107816. return 1;
  107817. }
  107818. /*
  107819. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  107820. ** to the global function hash table. This occurs at start-time (as
  107821. ** a consequence of calling sqlite3_initialize()).
  107822. **
  107823. ** After this routine runs
  107824. */
  107825. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
  107826. /*
  107827. ** The following array holds FuncDef structures for all of the functions
  107828. ** defined in this file.
  107829. **
  107830. ** The array cannot be constant since changes are made to the
  107831. ** FuncDef.pHash elements at start-time. The elements of this array
  107832. ** are read-only after initialization is complete.
  107833. **
  107834. ** For peak efficiency, put the most frequently used function last.
  107835. */
  107836. static FuncDef aBuiltinFunc[] = {
  107837. #ifdef SQLITE_SOUNDEX
  107838. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  107839. #endif
  107840. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  107841. VFUNCTION(load_extension, 1, 0, 0, loadExt ),
  107842. VFUNCTION(load_extension, 2, 0, 0, loadExt ),
  107843. #endif
  107844. #if SQLITE_USER_AUTHENTICATION
  107845. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  107846. #endif
  107847. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  107848. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  107849. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  107850. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  107851. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  107852. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  107853. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  107854. #ifdef SQLITE_DEBUG
  107855. FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY),
  107856. #endif
  107857. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  107858. FUNCTION2(sqlite_offset, 1, 0, 0, noopFunc, SQLITE_FUNC_OFFSET|
  107859. SQLITE_FUNC_TYPEOF),
  107860. #endif
  107861. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  107862. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  107863. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  107864. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  107865. FUNCTION(trim, 1, 3, 0, trimFunc ),
  107866. FUNCTION(trim, 2, 3, 0, trimFunc ),
  107867. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  107868. FUNCTION(min, 0, 0, 1, 0 ),
  107869. WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
  107870. SQLITE_FUNC_MINMAX ),
  107871. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  107872. FUNCTION(max, 0, 1, 1, 0 ),
  107873. WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
  107874. SQLITE_FUNC_MINMAX ),
  107875. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  107876. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  107877. FUNCTION(instr, 2, 0, 0, instrFunc ),
  107878. FUNCTION(printf, -1, 0, 0, printfFunc ),
  107879. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  107880. FUNCTION(char, -1, 0, 0, charFunc ),
  107881. FUNCTION(abs, 1, 0, 0, absFunc ),
  107882. #ifndef SQLITE_OMIT_FLOATING_POINT
  107883. FUNCTION(round, 1, 0, 0, roundFunc ),
  107884. FUNCTION(round, 2, 0, 0, roundFunc ),
  107885. #endif
  107886. FUNCTION(upper, 1, 0, 0, upperFunc ),
  107887. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  107888. FUNCTION(hex, 1, 0, 0, hexFunc ),
  107889. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  107890. VFUNCTION(random, 0, 0, 0, randomFunc ),
  107891. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  107892. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  107893. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  107894. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  107895. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  107896. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  107897. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  107898. VFUNCTION(changes, 0, 0, 0, changes ),
  107899. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  107900. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  107901. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  107902. FUNCTION(substr, 2, 0, 0, substrFunc ),
  107903. FUNCTION(substr, 3, 0, 0, substrFunc ),
  107904. WAGGREGATE(sum, 1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),
  107905. WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
  107906. WAGGREGATE(avg, 1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
  107907. WAGGREGATE(count, 0,0,0, countStep,
  107908. countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT ),
  107909. WAGGREGATE(count, 1,0,0, countStep,
  107910. countFinalize, countFinalize, countInverse, 0 ),
  107911. WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep,
  107912. groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
  107913. WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
  107914. groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
  107915. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  107916. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  107917. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  107918. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  107919. #else
  107920. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  107921. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  107922. #endif
  107923. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  107924. FUNCTION(unknown, -1, 0, 0, unknownFunc ),
  107925. #endif
  107926. FUNCTION(coalesce, 1, 0, 0, 0 ),
  107927. FUNCTION(coalesce, 0, 0, 0, 0 ),
  107928. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  107929. };
  107930. #ifndef SQLITE_OMIT_ALTERTABLE
  107931. sqlite3AlterFunctions();
  107932. #endif
  107933. sqlite3WindowFunctions();
  107934. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  107935. sqlite3AnalyzeFunctions();
  107936. #endif
  107937. sqlite3RegisterDateTimeFunctions();
  107938. sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
  107939. #if 0 /* Enable to print out how the built-in functions are hashed */
  107940. {
  107941. int i;
  107942. FuncDef *p;
  107943. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  107944. printf("FUNC-HASH %02d:", i);
  107945. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
  107946. int n = sqlite3Strlen30(p->zName);
  107947. int h = p->zName[0] + n;
  107948. printf(" %s(%d)", p->zName, h);
  107949. }
  107950. printf("\n");
  107951. }
  107952. }
  107953. #endif
  107954. }
  107955. /************** End of func.c ************************************************/
  107956. /************** Begin file fkey.c ********************************************/
  107957. /*
  107958. **
  107959. ** The author disclaims copyright to this source code. In place of
  107960. ** a legal notice, here is a blessing:
  107961. **
  107962. ** May you do good and not evil.
  107963. ** May you find forgiveness for yourself and forgive others.
  107964. ** May you share freely, never taking more than you give.
  107965. **
  107966. *************************************************************************
  107967. ** This file contains code used by the compiler to add foreign key
  107968. ** support to compiled SQL statements.
  107969. */
  107970. /* #include "sqliteInt.h" */
  107971. #ifndef SQLITE_OMIT_FOREIGN_KEY
  107972. #ifndef SQLITE_OMIT_TRIGGER
  107973. /*
  107974. ** Deferred and Immediate FKs
  107975. ** --------------------------
  107976. **
  107977. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  107978. ** If an immediate foreign key constraint is violated,
  107979. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  107980. ** statement transaction rolled back. If a
  107981. ** deferred foreign key constraint is violated, no action is taken
  107982. ** immediately. However if the application attempts to commit the
  107983. ** transaction before fixing the constraint violation, the attempt fails.
  107984. **
  107985. ** Deferred constraints are implemented using a simple counter associated
  107986. ** with the database handle. The counter is set to zero each time a
  107987. ** database transaction is opened. Each time a statement is executed
  107988. ** that causes a foreign key violation, the counter is incremented. Each
  107989. ** time a statement is executed that removes an existing violation from
  107990. ** the database, the counter is decremented. When the transaction is
  107991. ** committed, the commit fails if the current value of the counter is
  107992. ** greater than zero. This scheme has two big drawbacks:
  107993. **
  107994. ** * When a commit fails due to a deferred foreign key constraint,
  107995. ** there is no way to tell which foreign constraint is not satisfied,
  107996. ** or which row it is not satisfied for.
  107997. **
  107998. ** * If the database contains foreign key violations when the
  107999. ** transaction is opened, this may cause the mechanism to malfunction.
  108000. **
  108001. ** Despite these problems, this approach is adopted as it seems simpler
  108002. ** than the alternatives.
  108003. **
  108004. ** INSERT operations:
  108005. **
  108006. ** I.1) For each FK for which the table is the child table, search
  108007. ** the parent table for a match. If none is found increment the
  108008. ** constraint counter.
  108009. **
  108010. ** I.2) For each FK for which the table is the parent table,
  108011. ** search the child table for rows that correspond to the new
  108012. ** row in the parent table. Decrement the counter for each row
  108013. ** found (as the constraint is now satisfied).
  108014. **
  108015. ** DELETE operations:
  108016. **
  108017. ** D.1) For each FK for which the table is the child table,
  108018. ** search the parent table for a row that corresponds to the
  108019. ** deleted row in the child table. If such a row is not found,
  108020. ** decrement the counter.
  108021. **
  108022. ** D.2) For each FK for which the table is the parent table, search
  108023. ** the child table for rows that correspond to the deleted row
  108024. ** in the parent table. For each found increment the counter.
  108025. **
  108026. ** UPDATE operations:
  108027. **
  108028. ** An UPDATE command requires that all 4 steps above are taken, but only
  108029. ** for FK constraints for which the affected columns are actually
  108030. ** modified (values must be compared at runtime).
  108031. **
  108032. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  108033. ** This simplifies the implementation a bit.
  108034. **
  108035. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  108036. ** resolution is considered to delete rows before the new row is inserted.
  108037. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  108038. ** is thrown, even if the FK constraint would be satisfied after the new
  108039. ** row is inserted.
  108040. **
  108041. ** Immediate constraints are usually handled similarly. The only difference
  108042. ** is that the counter used is stored as part of each individual statement
  108043. ** object (struct Vdbe). If, after the statement has run, its immediate
  108044. ** constraint counter is greater than zero,
  108045. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  108046. ** and the statement transaction is rolled back. An exception is an INSERT
  108047. ** statement that inserts a single row only (no triggers). In this case,
  108048. ** instead of using a counter, an exception is thrown immediately if the
  108049. ** INSERT violates a foreign key constraint. This is necessary as such
  108050. ** an INSERT does not open a statement transaction.
  108051. **
  108052. ** TODO: How should dropping a table be handled? How should renaming a
  108053. ** table be handled?
  108054. **
  108055. **
  108056. ** Query API Notes
  108057. ** ---------------
  108058. **
  108059. ** Before coding an UPDATE or DELETE row operation, the code-generator
  108060. ** for those two operations needs to know whether or not the operation
  108061. ** requires any FK processing and, if so, which columns of the original
  108062. ** row are required by the FK processing VDBE code (i.e. if FKs were
  108063. ** implemented using triggers, which of the old.* columns would be
  108064. ** accessed). No information is required by the code-generator before
  108065. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  108066. ** generation code to query for this information are:
  108067. **
  108068. ** sqlite3FkRequired() - Test to see if FK processing is required.
  108069. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  108070. **
  108071. **
  108072. ** Externally accessible module functions
  108073. ** --------------------------------------
  108074. **
  108075. ** sqlite3FkCheck() - Check for foreign key violations.
  108076. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  108077. ** sqlite3FkDelete() - Delete an FKey structure.
  108078. */
  108079. /*
  108080. ** VDBE Calling Convention
  108081. ** -----------------------
  108082. **
  108083. ** Example:
  108084. **
  108085. ** For the following INSERT statement:
  108086. **
  108087. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  108088. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  108089. **
  108090. ** Register (x): 2 (type integer)
  108091. ** Register (x+1): 1 (type integer)
  108092. ** Register (x+2): NULL (type NULL)
  108093. ** Register (x+3): 3.1 (type real)
  108094. */
  108095. /*
  108096. ** A foreign key constraint requires that the key columns in the parent
  108097. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  108098. ** Given that pParent is the parent table for foreign key constraint pFKey,
  108099. ** search the schema for a unique index on the parent key columns.
  108100. **
  108101. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  108102. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  108103. ** is set to point to the unique index.
  108104. **
  108105. ** If the parent key consists of a single column (the foreign key constraint
  108106. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  108107. ** Otherwise, it is set to point to an allocated array of size N, where
  108108. ** N is the number of columns in the parent key. The first element of the
  108109. ** array is the index of the child table column that is mapped by the FK
  108110. ** constraint to the parent table column stored in the left-most column
  108111. ** of index *ppIdx. The second element of the array is the index of the
  108112. ** child table column that corresponds to the second left-most column of
  108113. ** *ppIdx, and so on.
  108114. **
  108115. ** If the required index cannot be found, either because:
  108116. **
  108117. ** 1) The named parent key columns do not exist, or
  108118. **
  108119. ** 2) The named parent key columns do exist, but are not subject to a
  108120. ** UNIQUE or PRIMARY KEY constraint, or
  108121. **
  108122. ** 3) No parent key columns were provided explicitly as part of the
  108123. ** foreign key definition, and the parent table does not have a
  108124. ** PRIMARY KEY, or
  108125. **
  108126. ** 4) No parent key columns were provided explicitly as part of the
  108127. ** foreign key definition, and the PRIMARY KEY of the parent table
  108128. ** consists of a different number of columns to the child key in
  108129. ** the child table.
  108130. **
  108131. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  108132. ** into pParse. If an OOM error occurs, non-zero is returned and the
  108133. ** pParse->db->mallocFailed flag is set.
  108134. */
  108135. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  108136. Parse *pParse, /* Parse context to store any error in */
  108137. Table *pParent, /* Parent table of FK constraint pFKey */
  108138. FKey *pFKey, /* Foreign key to find index for */
  108139. Index **ppIdx, /* OUT: Unique index on parent table */
  108140. int **paiCol /* OUT: Map of index columns in pFKey */
  108141. ){
  108142. Index *pIdx = 0; /* Value to return via *ppIdx */
  108143. int *aiCol = 0; /* Value to return via *paiCol */
  108144. int nCol = pFKey->nCol; /* Number of columns in parent key */
  108145. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  108146. /* The caller is responsible for zeroing output parameters. */
  108147. assert( ppIdx && *ppIdx==0 );
  108148. assert( !paiCol || *paiCol==0 );
  108149. assert( pParse );
  108150. /* If this is a non-composite (single column) foreign key, check if it
  108151. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  108152. ** and *paiCol set to zero and return early.
  108153. **
  108154. ** Otherwise, for a composite foreign key (more than one column), allocate
  108155. ** space for the aiCol array (returned via output parameter *paiCol).
  108156. ** Non-composite foreign keys do not require the aiCol array.
  108157. */
  108158. if( nCol==1 ){
  108159. /* The FK maps to the IPK if any of the following are true:
  108160. **
  108161. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  108162. ** mapped to the primary key of table pParent, or
  108163. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  108164. ** PRIMARY KEY.
  108165. */
  108166. if( pParent->iPKey>=0 ){
  108167. if( !zKey ) return 0;
  108168. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  108169. }
  108170. }else if( paiCol ){
  108171. assert( nCol>1 );
  108172. aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
  108173. if( !aiCol ) return 1;
  108174. *paiCol = aiCol;
  108175. }
  108176. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  108177. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
  108178. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  108179. ** of columns. If each indexed column corresponds to a foreign key
  108180. ** column of pFKey, then this index is a winner. */
  108181. if( zKey==0 ){
  108182. /* If zKey is NULL, then this foreign key is implicitly mapped to
  108183. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  108184. ** identified by the test. */
  108185. if( IsPrimaryKeyIndex(pIdx) ){
  108186. if( aiCol ){
  108187. int i;
  108188. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  108189. }
  108190. break;
  108191. }
  108192. }else{
  108193. /* If zKey is non-NULL, then this foreign key was declared to
  108194. ** map to an explicit list of columns in table pParent. Check if this
  108195. ** index matches those columns. Also, check that the index uses
  108196. ** the default collation sequences for each column. */
  108197. int i, j;
  108198. for(i=0; i<nCol; i++){
  108199. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  108200. const char *zDfltColl; /* Def. collation for column */
  108201. char *zIdxCol; /* Name of indexed column */
  108202. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  108203. /* If the index uses a collation sequence that is different from
  108204. ** the default collation sequence for the column, this index is
  108205. ** unusable. Bail out early in this case. */
  108206. zDfltColl = pParent->aCol[iCol].zColl;
  108207. if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
  108208. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  108209. zIdxCol = pParent->aCol[iCol].zName;
  108210. for(j=0; j<nCol; j++){
  108211. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  108212. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  108213. break;
  108214. }
  108215. }
  108216. if( j==nCol ) break;
  108217. }
  108218. if( i==nCol ) break; /* pIdx is usable */
  108219. }
  108220. }
  108221. }
  108222. if( !pIdx ){
  108223. if( !pParse->disableTriggers ){
  108224. sqlite3ErrorMsg(pParse,
  108225. "foreign key mismatch - \"%w\" referencing \"%w\"",
  108226. pFKey->pFrom->zName, pFKey->zTo);
  108227. }
  108228. sqlite3DbFree(pParse->db, aiCol);
  108229. return 1;
  108230. }
  108231. *ppIdx = pIdx;
  108232. return 0;
  108233. }
  108234. /*
  108235. ** This function is called when a row is inserted into or deleted from the
  108236. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  108237. ** on the child table of pFKey, this function is invoked twice for each row
  108238. ** affected - once to "delete" the old row, and then again to "insert" the
  108239. ** new row.
  108240. **
  108241. ** Each time it is called, this function generates VDBE code to locate the
  108242. ** row in the parent table that corresponds to the row being inserted into
  108243. ** or deleted from the child table. If the parent row can be found, no
  108244. ** special action is taken. Otherwise, if the parent row can *not* be
  108245. ** found in the parent table:
  108246. **
  108247. ** Operation | FK type | Action taken
  108248. ** --------------------------------------------------------------------------
  108249. ** INSERT immediate Increment the "immediate constraint counter".
  108250. **
  108251. ** DELETE immediate Decrement the "immediate constraint counter".
  108252. **
  108253. ** INSERT deferred Increment the "deferred constraint counter".
  108254. **
  108255. ** DELETE deferred Decrement the "deferred constraint counter".
  108256. **
  108257. ** These operations are identified in the comment at the top of this file
  108258. ** (fkey.c) as "I.1" and "D.1".
  108259. */
  108260. static void fkLookupParent(
  108261. Parse *pParse, /* Parse context */
  108262. int iDb, /* Index of database housing pTab */
  108263. Table *pTab, /* Parent table of FK pFKey */
  108264. Index *pIdx, /* Unique index on parent key columns in pTab */
  108265. FKey *pFKey, /* Foreign key constraint */
  108266. int *aiCol, /* Map from parent key columns to child table columns */
  108267. int regData, /* Address of array containing child table row */
  108268. int nIncr, /* Increment constraint counter by this */
  108269. int isIgnore /* If true, pretend pTab contains all NULL values */
  108270. ){
  108271. int i; /* Iterator variable */
  108272. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  108273. int iCur = pParse->nTab - 1; /* Cursor number to use */
  108274. int iOk = sqlite3VdbeMakeLabel(pParse); /* jump here if parent key found */
  108275. sqlite3VdbeVerifyAbortable(v,
  108276. (!pFKey->isDeferred
  108277. && !(pParse->db->flags & SQLITE_DeferFKs)
  108278. && !pParse->pToplevel
  108279. && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
  108280. /* If nIncr is less than zero, then check at runtime if there are any
  108281. ** outstanding constraints to resolve. If there are not, there is no need
  108282. ** to check if deleting this row resolves any outstanding violations.
  108283. **
  108284. ** Check if any of the key columns in the child table row are NULL. If
  108285. ** any are, then the constraint is considered satisfied. No need to
  108286. ** search for a matching row in the parent table. */
  108287. if( nIncr<0 ){
  108288. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  108289. VdbeCoverage(v);
  108290. }
  108291. for(i=0; i<pFKey->nCol; i++){
  108292. int iReg = aiCol[i] + regData + 1;
  108293. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  108294. }
  108295. if( isIgnore==0 ){
  108296. if( pIdx==0 ){
  108297. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  108298. ** column of the parent table (table pTab). */
  108299. int iMustBeInt; /* Address of MustBeInt instruction */
  108300. int regTemp = sqlite3GetTempReg(pParse);
  108301. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  108302. ** apply the affinity of the parent key). If this fails, then there
  108303. ** is no matching parent key. Before using MustBeInt, make a copy of
  108304. ** the value. Otherwise, the value inserted into the child key column
  108305. ** will have INTEGER affinity applied to it, which may not be correct. */
  108306. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  108307. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  108308. VdbeCoverage(v);
  108309. /* If the parent table is the same as the child table, and we are about
  108310. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  108311. ** then check if the row being inserted matches itself. If so, do not
  108312. ** increment the constraint-counter. */
  108313. if( pTab==pFKey->pFrom && nIncr==1 ){
  108314. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  108315. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  108316. }
  108317. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  108318. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  108319. sqlite3VdbeGoto(v, iOk);
  108320. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  108321. sqlite3VdbeJumpHere(v, iMustBeInt);
  108322. sqlite3ReleaseTempReg(pParse, regTemp);
  108323. }else{
  108324. int nCol = pFKey->nCol;
  108325. int regTemp = sqlite3GetTempRange(pParse, nCol);
  108326. int regRec = sqlite3GetTempReg(pParse);
  108327. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  108328. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  108329. for(i=0; i<nCol; i++){
  108330. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  108331. }
  108332. /* If the parent table is the same as the child table, and we are about
  108333. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  108334. ** then check if the row being inserted matches itself. If so, do not
  108335. ** increment the constraint-counter.
  108336. **
  108337. ** If any of the parent-key values are NULL, then the row cannot match
  108338. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  108339. ** of the parent-key values are NULL (at this point it is known that
  108340. ** none of the child key values are).
  108341. */
  108342. if( pTab==pFKey->pFrom && nIncr==1 ){
  108343. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  108344. for(i=0; i<nCol; i++){
  108345. int iChild = aiCol[i]+1+regData;
  108346. int iParent = pIdx->aiColumn[i]+1+regData;
  108347. assert( pIdx->aiColumn[i]>=0 );
  108348. assert( aiCol[i]!=pTab->iPKey );
  108349. if( pIdx->aiColumn[i]==pTab->iPKey ){
  108350. /* The parent key is a composite key that includes the IPK column */
  108351. iParent = regData;
  108352. }
  108353. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  108354. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  108355. }
  108356. sqlite3VdbeGoto(v, iOk);
  108357. }
  108358. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  108359. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  108360. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  108361. sqlite3ReleaseTempReg(pParse, regRec);
  108362. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  108363. }
  108364. }
  108365. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  108366. && !pParse->pToplevel
  108367. && !pParse->isMultiWrite
  108368. ){
  108369. /* Special case: If this is an INSERT statement that will insert exactly
  108370. ** one row into the table, raise a constraint immediately instead of
  108371. ** incrementing a counter. This is necessary as the VM code is being
  108372. ** generated for will not open a statement transaction. */
  108373. assert( nIncr==1 );
  108374. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  108375. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  108376. }else{
  108377. if( nIncr>0 && pFKey->isDeferred==0 ){
  108378. sqlite3MayAbort(pParse);
  108379. }
  108380. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  108381. }
  108382. sqlite3VdbeResolveLabel(v, iOk);
  108383. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  108384. }
  108385. /*
  108386. ** Return an Expr object that refers to a memory register corresponding
  108387. ** to column iCol of table pTab.
  108388. **
  108389. ** regBase is the first of an array of register that contains the data
  108390. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  108391. ** column. regBase+2 holds the second column, and so forth.
  108392. */
  108393. static Expr *exprTableRegister(
  108394. Parse *pParse, /* Parsing and code generating context */
  108395. Table *pTab, /* The table whose content is at r[regBase]... */
  108396. int regBase, /* Contents of table pTab */
  108397. i16 iCol /* Which column of pTab is desired */
  108398. ){
  108399. Expr *pExpr;
  108400. Column *pCol;
  108401. const char *zColl;
  108402. sqlite3 *db = pParse->db;
  108403. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  108404. if( pExpr ){
  108405. if( iCol>=0 && iCol!=pTab->iPKey ){
  108406. pCol = &pTab->aCol[iCol];
  108407. pExpr->iTable = regBase + iCol + 1;
  108408. pExpr->affinity = pCol->affinity;
  108409. zColl = pCol->zColl;
  108410. if( zColl==0 ) zColl = db->pDfltColl->zName;
  108411. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  108412. }else{
  108413. pExpr->iTable = regBase;
  108414. pExpr->affinity = SQLITE_AFF_INTEGER;
  108415. }
  108416. }
  108417. return pExpr;
  108418. }
  108419. /*
  108420. ** Return an Expr object that refers to column iCol of table pTab which
  108421. ** has cursor iCur.
  108422. */
  108423. static Expr *exprTableColumn(
  108424. sqlite3 *db, /* The database connection */
  108425. Table *pTab, /* The table whose column is desired */
  108426. int iCursor, /* The open cursor on the table */
  108427. i16 iCol /* The column that is wanted */
  108428. ){
  108429. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  108430. if( pExpr ){
  108431. pExpr->y.pTab = pTab;
  108432. pExpr->iTable = iCursor;
  108433. pExpr->iColumn = iCol;
  108434. }
  108435. return pExpr;
  108436. }
  108437. /*
  108438. ** This function is called to generate code executed when a row is deleted
  108439. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  108440. ** deferred, when a row is inserted into the same table. When generating
  108441. ** code for an SQL UPDATE operation, this function may be called twice -
  108442. ** once to "delete" the old row and once to "insert" the new row.
  108443. **
  108444. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  108445. ** the number of FK violations in the db) or +1 when deleting one (as this
  108446. ** may increase the number of FK constraint problems).
  108447. **
  108448. ** The code generated by this function scans through the rows in the child
  108449. ** table that correspond to the parent table row being deleted or inserted.
  108450. ** For each child row found, one of the following actions is taken:
  108451. **
  108452. ** Operation | FK type | Action taken
  108453. ** --------------------------------------------------------------------------
  108454. ** DELETE immediate Increment the "immediate constraint counter".
  108455. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  108456. ** throw a "FOREIGN KEY constraint failed" exception.
  108457. **
  108458. ** INSERT immediate Decrement the "immediate constraint counter".
  108459. **
  108460. ** DELETE deferred Increment the "deferred constraint counter".
  108461. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  108462. ** throw a "FOREIGN KEY constraint failed" exception.
  108463. **
  108464. ** INSERT deferred Decrement the "deferred constraint counter".
  108465. **
  108466. ** These operations are identified in the comment at the top of this file
  108467. ** (fkey.c) as "I.2" and "D.2".
  108468. */
  108469. static void fkScanChildren(
  108470. Parse *pParse, /* Parse context */
  108471. SrcList *pSrc, /* The child table to be scanned */
  108472. Table *pTab, /* The parent table */
  108473. Index *pIdx, /* Index on parent covering the foreign key */
  108474. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  108475. int *aiCol, /* Map from pIdx cols to child table cols */
  108476. int regData, /* Parent row data starts here */
  108477. int nIncr /* Amount to increment deferred counter by */
  108478. ){
  108479. sqlite3 *db = pParse->db; /* Database handle */
  108480. int i; /* Iterator variable */
  108481. Expr *pWhere = 0; /* WHERE clause to scan with */
  108482. NameContext sNameContext; /* Context used to resolve WHERE clause */
  108483. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  108484. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  108485. Vdbe *v = sqlite3GetVdbe(pParse);
  108486. assert( pIdx==0 || pIdx->pTable==pTab );
  108487. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  108488. assert( pIdx!=0 || pFKey->nCol==1 );
  108489. assert( pIdx!=0 || HasRowid(pTab) );
  108490. if( nIncr<0 ){
  108491. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  108492. VdbeCoverage(v);
  108493. }
  108494. /* Create an Expr object representing an SQL expression like:
  108495. **
  108496. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  108497. **
  108498. ** The collation sequence used for the comparison should be that of
  108499. ** the parent key columns. The affinity of the parent key column should
  108500. ** be applied to each child key value before the comparison takes place.
  108501. */
  108502. for(i=0; i<pFKey->nCol; i++){
  108503. Expr *pLeft; /* Value from parent table row */
  108504. Expr *pRight; /* Column ref to child table */
  108505. Expr *pEq; /* Expression (pLeft = pRight) */
  108506. i16 iCol; /* Index of column in child table */
  108507. const char *zCol; /* Name of column in child table */
  108508. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  108509. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  108510. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  108511. assert( iCol>=0 );
  108512. zCol = pFKey->pFrom->aCol[iCol].zName;
  108513. pRight = sqlite3Expr(db, TK_ID, zCol);
  108514. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  108515. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  108516. }
  108517. /* If the child table is the same as the parent table, then add terms
  108518. ** to the WHERE clause that prevent this entry from being scanned.
  108519. ** The added WHERE clause terms are like this:
  108520. **
  108521. ** $current_rowid!=rowid
  108522. ** NOT( $current_a==a AND $current_b==b AND ... )
  108523. **
  108524. ** The first form is used for rowid tables. The second form is used
  108525. ** for WITHOUT ROWID tables. In the second form, the *parent* key is
  108526. ** (a,b,...). Either the parent or primary key could be used to
  108527. ** uniquely identify the current row, but the parent key is more convenient
  108528. ** as the required values have already been loaded into registers
  108529. ** by the caller.
  108530. */
  108531. if( pTab==pFKey->pFrom && nIncr>0 ){
  108532. Expr *pNe; /* Expression (pLeft != pRight) */
  108533. Expr *pLeft; /* Value from parent table row */
  108534. Expr *pRight; /* Column ref to child table */
  108535. if( HasRowid(pTab) ){
  108536. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  108537. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  108538. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
  108539. }else{
  108540. Expr *pEq, *pAll = 0;
  108541. assert( pIdx!=0 );
  108542. for(i=0; i<pIdx->nKeyCol; i++){
  108543. i16 iCol = pIdx->aiColumn[i];
  108544. assert( iCol>=0 );
  108545. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  108546. pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zName);
  108547. pEq = sqlite3PExpr(pParse, TK_IS, pLeft, pRight);
  108548. pAll = sqlite3ExprAnd(db, pAll, pEq);
  108549. }
  108550. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
  108551. }
  108552. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  108553. }
  108554. /* Resolve the references in the WHERE clause. */
  108555. memset(&sNameContext, 0, sizeof(NameContext));
  108556. sNameContext.pSrcList = pSrc;
  108557. sNameContext.pParse = pParse;
  108558. sqlite3ResolveExprNames(&sNameContext, pWhere);
  108559. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  108560. ** clause. For each row found, increment either the deferred or immediate
  108561. ** foreign key constraint counter. */
  108562. if( pParse->nErr==0 ){
  108563. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  108564. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  108565. if( pWInfo ){
  108566. sqlite3WhereEnd(pWInfo);
  108567. }
  108568. }
  108569. /* Clean up the WHERE clause constructed above. */
  108570. sqlite3ExprDelete(db, pWhere);
  108571. if( iFkIfZero ){
  108572. sqlite3VdbeJumpHere(v, iFkIfZero);
  108573. }
  108574. }
  108575. /*
  108576. ** This function returns a linked list of FKey objects (connected by
  108577. ** FKey.pNextTo) holding all children of table pTab. For example,
  108578. ** given the following schema:
  108579. **
  108580. ** CREATE TABLE t1(a PRIMARY KEY);
  108581. ** CREATE TABLE t2(b REFERENCES t1(a);
  108582. **
  108583. ** Calling this function with table "t1" as an argument returns a pointer
  108584. ** to the FKey structure representing the foreign key constraint on table
  108585. ** "t2". Calling this function with "t2" as the argument would return a
  108586. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  108587. ** table).
  108588. */
  108589. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  108590. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  108591. }
  108592. /*
  108593. ** The second argument is a Trigger structure allocated by the
  108594. ** fkActionTrigger() routine. This function deletes the Trigger structure
  108595. ** and all of its sub-components.
  108596. **
  108597. ** The Trigger structure or any of its sub-components may be allocated from
  108598. ** the lookaside buffer belonging to database handle dbMem.
  108599. */
  108600. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  108601. if( p ){
  108602. TriggerStep *pStep = p->step_list;
  108603. sqlite3ExprDelete(dbMem, pStep->pWhere);
  108604. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  108605. sqlite3SelectDelete(dbMem, pStep->pSelect);
  108606. sqlite3ExprDelete(dbMem, p->pWhen);
  108607. sqlite3DbFree(dbMem, p);
  108608. }
  108609. }
  108610. /*
  108611. ** This function is called to generate code that runs when table pTab is
  108612. ** being dropped from the database. The SrcList passed as the second argument
  108613. ** to this function contains a single entry guaranteed to resolve to
  108614. ** table pTab.
  108615. **
  108616. ** Normally, no code is required. However, if either
  108617. **
  108618. ** (a) The table is the parent table of a FK constraint, or
  108619. ** (b) The table is the child table of a deferred FK constraint and it is
  108620. ** determined at runtime that there are outstanding deferred FK
  108621. ** constraint violations in the database,
  108622. **
  108623. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  108624. ** the table from the database. Triggers are disabled while running this
  108625. ** DELETE, but foreign key actions are not.
  108626. */
  108627. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  108628. sqlite3 *db = pParse->db;
  108629. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) ){
  108630. int iSkip = 0;
  108631. Vdbe *v = sqlite3GetVdbe(pParse);
  108632. assert( v ); /* VDBE has already been allocated */
  108633. assert( pTab->pSelect==0 ); /* Not a view */
  108634. if( sqlite3FkReferences(pTab)==0 ){
  108635. /* Search for a deferred foreign key constraint for which this table
  108636. ** is the child table. If one cannot be found, return without
  108637. ** generating any VDBE code. If one can be found, then jump over
  108638. ** the entire DELETE if there are no outstanding deferred constraints
  108639. ** when this statement is run. */
  108640. FKey *p;
  108641. for(p=pTab->pFKey; p; p=p->pNextFrom){
  108642. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  108643. }
  108644. if( !p ) return;
  108645. iSkip = sqlite3VdbeMakeLabel(pParse);
  108646. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  108647. }
  108648. pParse->disableTriggers = 1;
  108649. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
  108650. pParse->disableTriggers = 0;
  108651. /* If the DELETE has generated immediate foreign key constraint
  108652. ** violations, halt the VDBE and return an error at this point, before
  108653. ** any modifications to the schema are made. This is because statement
  108654. ** transactions are not able to rollback schema changes.
  108655. **
  108656. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  108657. ** the statement transaction will not be rolled back even if FK
  108658. ** constraints are violated.
  108659. */
  108660. if( (db->flags & SQLITE_DeferFKs)==0 ){
  108661. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  108662. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  108663. VdbeCoverage(v);
  108664. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  108665. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  108666. }
  108667. if( iSkip ){
  108668. sqlite3VdbeResolveLabel(v, iSkip);
  108669. }
  108670. }
  108671. }
  108672. /*
  108673. ** The second argument points to an FKey object representing a foreign key
  108674. ** for which pTab is the child table. An UPDATE statement against pTab
  108675. ** is currently being processed. For each column of the table that is
  108676. ** actually updated, the corresponding element in the aChange[] array
  108677. ** is zero or greater (if a column is unmodified the corresponding element
  108678. ** is set to -1). If the rowid column is modified by the UPDATE statement
  108679. ** the bChngRowid argument is non-zero.
  108680. **
  108681. ** This function returns true if any of the columns that are part of the
  108682. ** child key for FK constraint *p are modified.
  108683. */
  108684. static int fkChildIsModified(
  108685. Table *pTab, /* Table being updated */
  108686. FKey *p, /* Foreign key for which pTab is the child */
  108687. int *aChange, /* Array indicating modified columns */
  108688. int bChngRowid /* True if rowid is modified by this update */
  108689. ){
  108690. int i;
  108691. for(i=0; i<p->nCol; i++){
  108692. int iChildKey = p->aCol[i].iFrom;
  108693. if( aChange[iChildKey]>=0 ) return 1;
  108694. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  108695. }
  108696. return 0;
  108697. }
  108698. /*
  108699. ** The second argument points to an FKey object representing a foreign key
  108700. ** for which pTab is the parent table. An UPDATE statement against pTab
  108701. ** is currently being processed. For each column of the table that is
  108702. ** actually updated, the corresponding element in the aChange[] array
  108703. ** is zero or greater (if a column is unmodified the corresponding element
  108704. ** is set to -1). If the rowid column is modified by the UPDATE statement
  108705. ** the bChngRowid argument is non-zero.
  108706. **
  108707. ** This function returns true if any of the columns that are part of the
  108708. ** parent key for FK constraint *p are modified.
  108709. */
  108710. static int fkParentIsModified(
  108711. Table *pTab,
  108712. FKey *p,
  108713. int *aChange,
  108714. int bChngRowid
  108715. ){
  108716. int i;
  108717. for(i=0; i<p->nCol; i++){
  108718. char *zKey = p->aCol[i].zCol;
  108719. int iKey;
  108720. for(iKey=0; iKey<pTab->nCol; iKey++){
  108721. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  108722. Column *pCol = &pTab->aCol[iKey];
  108723. if( zKey ){
  108724. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  108725. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  108726. return 1;
  108727. }
  108728. }
  108729. }
  108730. }
  108731. return 0;
  108732. }
  108733. /*
  108734. ** Return true if the parser passed as the first argument is being
  108735. ** used to code a trigger that is really a "SET NULL" action belonging
  108736. ** to trigger pFKey.
  108737. */
  108738. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  108739. Parse *pTop = sqlite3ParseToplevel(pParse);
  108740. if( pTop->pTriggerPrg ){
  108741. Trigger *p = pTop->pTriggerPrg->pTrigger;
  108742. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  108743. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  108744. ){
  108745. return 1;
  108746. }
  108747. }
  108748. return 0;
  108749. }
  108750. /*
  108751. ** This function is called when inserting, deleting or updating a row of
  108752. ** table pTab to generate VDBE code to perform foreign key constraint
  108753. ** processing for the operation.
  108754. **
  108755. ** For a DELETE operation, parameter regOld is passed the index of the
  108756. ** first register in an array of (pTab->nCol+1) registers containing the
  108757. ** rowid of the row being deleted, followed by each of the column values
  108758. ** of the row being deleted, from left to right. Parameter regNew is passed
  108759. ** zero in this case.
  108760. **
  108761. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  108762. ** first register of an array of (pTab->nCol+1) registers containing the new
  108763. ** row data.
  108764. **
  108765. ** For an UPDATE operation, this function is called twice. Once before
  108766. ** the original record is deleted from the table using the calling convention
  108767. ** described for DELETE. Then again after the original record is deleted
  108768. ** but before the new record is inserted using the INSERT convention.
  108769. */
  108770. SQLITE_PRIVATE void sqlite3FkCheck(
  108771. Parse *pParse, /* Parse context */
  108772. Table *pTab, /* Row is being deleted from this table */
  108773. int regOld, /* Previous row data is stored here */
  108774. int regNew, /* New row data is stored here */
  108775. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  108776. int bChngRowid /* True if rowid is UPDATEd */
  108777. ){
  108778. sqlite3 *db = pParse->db; /* Database handle */
  108779. FKey *pFKey; /* Used to iterate through FKs */
  108780. int iDb; /* Index of database containing pTab */
  108781. const char *zDb; /* Name of database containing pTab */
  108782. int isIgnoreErrors = pParse->disableTriggers;
  108783. /* Exactly one of regOld and regNew should be non-zero. */
  108784. assert( (regOld==0)!=(regNew==0) );
  108785. /* If foreign-keys are disabled, this function is a no-op. */
  108786. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  108787. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  108788. zDb = db->aDb[iDb].zDbSName;
  108789. /* Loop through all the foreign key constraints for which pTab is the
  108790. ** child table (the table that the foreign key definition is part of). */
  108791. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  108792. Table *pTo; /* Parent table of foreign key pFKey */
  108793. Index *pIdx = 0; /* Index on key columns in pTo */
  108794. int *aiFree = 0;
  108795. int *aiCol;
  108796. int iCol;
  108797. int i;
  108798. int bIgnore = 0;
  108799. if( aChange
  108800. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  108801. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  108802. ){
  108803. continue;
  108804. }
  108805. /* Find the parent table of this foreign key. Also find a unique index
  108806. ** on the parent key columns in the parent table. If either of these
  108807. ** schema items cannot be located, set an error in pParse and return
  108808. ** early. */
  108809. if( pParse->disableTriggers ){
  108810. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  108811. }else{
  108812. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  108813. }
  108814. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  108815. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  108816. if( !isIgnoreErrors || db->mallocFailed ) return;
  108817. if( pTo==0 ){
  108818. /* If isIgnoreErrors is true, then a table is being dropped. In this
  108819. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  108820. ** before actually dropping it in order to check FK constraints.
  108821. ** If the parent table of an FK constraint on the current table is
  108822. ** missing, behave as if it is empty. i.e. decrement the relevant
  108823. ** FK counter for each row of the current table with non-NULL keys.
  108824. */
  108825. Vdbe *v = sqlite3GetVdbe(pParse);
  108826. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  108827. for(i=0; i<pFKey->nCol; i++){
  108828. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  108829. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  108830. }
  108831. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  108832. }
  108833. continue;
  108834. }
  108835. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  108836. if( aiFree ){
  108837. aiCol = aiFree;
  108838. }else{
  108839. iCol = pFKey->aCol[0].iFrom;
  108840. aiCol = &iCol;
  108841. }
  108842. for(i=0; i<pFKey->nCol; i++){
  108843. if( aiCol[i]==pTab->iPKey ){
  108844. aiCol[i] = -1;
  108845. }
  108846. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  108847. #ifndef SQLITE_OMIT_AUTHORIZATION
  108848. /* Request permission to read the parent key columns. If the
  108849. ** authorization callback returns SQLITE_IGNORE, behave as if any
  108850. ** values read from the parent table are NULL. */
  108851. if( db->xAuth ){
  108852. int rcauth;
  108853. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  108854. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  108855. bIgnore = (rcauth==SQLITE_IGNORE);
  108856. }
  108857. #endif
  108858. }
  108859. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  108860. ** a cursor to use to search the unique index on the parent key columns
  108861. ** in the parent table. */
  108862. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  108863. pParse->nTab++;
  108864. if( regOld!=0 ){
  108865. /* A row is being removed from the child table. Search for the parent.
  108866. ** If the parent does not exist, removing the child row resolves an
  108867. ** outstanding foreign key constraint violation. */
  108868. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  108869. }
  108870. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  108871. /* A row is being added to the child table. If a parent row cannot
  108872. ** be found, adding the child row has violated the FK constraint.
  108873. **
  108874. ** If this operation is being performed as part of a trigger program
  108875. ** that is actually a "SET NULL" action belonging to this very
  108876. ** foreign key, then omit this scan altogether. As all child key
  108877. ** values are guaranteed to be NULL, it is not possible for adding
  108878. ** this row to cause an FK violation. */
  108879. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  108880. }
  108881. sqlite3DbFree(db, aiFree);
  108882. }
  108883. /* Loop through all the foreign key constraints that refer to this table.
  108884. ** (the "child" constraints) */
  108885. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  108886. Index *pIdx = 0; /* Foreign key index for pFKey */
  108887. SrcList *pSrc;
  108888. int *aiCol = 0;
  108889. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  108890. continue;
  108891. }
  108892. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  108893. && !pParse->pToplevel && !pParse->isMultiWrite
  108894. ){
  108895. assert( regOld==0 && regNew!=0 );
  108896. /* Inserting a single row into a parent table cannot cause (or fix)
  108897. ** an immediate foreign key violation. So do nothing in this case. */
  108898. continue;
  108899. }
  108900. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  108901. if( !isIgnoreErrors || db->mallocFailed ) return;
  108902. continue;
  108903. }
  108904. assert( aiCol || pFKey->nCol==1 );
  108905. /* Create a SrcList structure containing the child table. We need the
  108906. ** child table as a SrcList for sqlite3WhereBegin() */
  108907. pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  108908. if( pSrc ){
  108909. struct SrcList_item *pItem = pSrc->a;
  108910. pItem->pTab = pFKey->pFrom;
  108911. pItem->zName = pFKey->pFrom->zName;
  108912. pItem->pTab->nTabRef++;
  108913. pItem->iCursor = pParse->nTab++;
  108914. if( regNew!=0 ){
  108915. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  108916. }
  108917. if( regOld!=0 ){
  108918. int eAction = pFKey->aAction[aChange!=0];
  108919. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  108920. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  108921. ** action applies, then any foreign key violations caused by
  108922. ** removing the parent key will be rectified by the action trigger.
  108923. ** So do not set the "may-abort" flag in this case.
  108924. **
  108925. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  108926. ** may-abort flag will eventually be set on this statement anyway
  108927. ** (when this function is called as part of processing the UPDATE
  108928. ** within the action trigger).
  108929. **
  108930. ** Note 2: At first glance it may seem like SQLite could simply omit
  108931. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  108932. ** applies. The trouble starts if the CASCADE or SET NULL action
  108933. ** trigger causes other triggers or action rules attached to the
  108934. ** child table to fire. In these cases the fk constraint counters
  108935. ** might be set incorrectly if any OP_FkCounter related scans are
  108936. ** omitted. */
  108937. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  108938. sqlite3MayAbort(pParse);
  108939. }
  108940. }
  108941. pItem->zName = 0;
  108942. sqlite3SrcListDelete(db, pSrc);
  108943. }
  108944. sqlite3DbFree(db, aiCol);
  108945. }
  108946. }
  108947. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  108948. /*
  108949. ** This function is called before generating code to update or delete a
  108950. ** row contained in table pTab.
  108951. */
  108952. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  108953. Parse *pParse, /* Parse context */
  108954. Table *pTab /* Table being modified */
  108955. ){
  108956. u32 mask = 0;
  108957. if( pParse->db->flags&SQLITE_ForeignKeys ){
  108958. FKey *p;
  108959. int i;
  108960. for(p=pTab->pFKey; p; p=p->pNextFrom){
  108961. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  108962. }
  108963. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  108964. Index *pIdx = 0;
  108965. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  108966. if( pIdx ){
  108967. for(i=0; i<pIdx->nKeyCol; i++){
  108968. assert( pIdx->aiColumn[i]>=0 );
  108969. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  108970. }
  108971. }
  108972. }
  108973. }
  108974. return mask;
  108975. }
  108976. /*
  108977. ** This function is called before generating code to update or delete a
  108978. ** row contained in table pTab. If the operation is a DELETE, then
  108979. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  108980. ** to an array of size N, where N is the number of columns in table pTab.
  108981. ** If the i'th column is not modified by the UPDATE, then the corresponding
  108982. ** entry in the aChange[] array is set to -1. If the column is modified,
  108983. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  108984. ** UPDATE statement modifies the rowid fields of the table.
  108985. **
  108986. ** If any foreign key processing will be required, this function returns
  108987. ** non-zero. If there is no foreign key related processing, this function
  108988. ** returns zero.
  108989. **
  108990. ** For an UPDATE, this function returns 2 if:
  108991. **
  108992. ** * There are any FKs for which pTab is the child and the parent table, or
  108993. ** * the UPDATE modifies one or more parent keys for which the action is
  108994. ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
  108995. **
  108996. ** Or, assuming some other foreign key processing is required, 1.
  108997. */
  108998. SQLITE_PRIVATE int sqlite3FkRequired(
  108999. Parse *pParse, /* Parse context */
  109000. Table *pTab, /* Table being modified */
  109001. int *aChange, /* Non-NULL for UPDATE operations */
  109002. int chngRowid /* True for UPDATE that affects rowid */
  109003. ){
  109004. int eRet = 0;
  109005. if( pParse->db->flags&SQLITE_ForeignKeys ){
  109006. if( !aChange ){
  109007. /* A DELETE operation. Foreign key processing is required if the
  109008. ** table in question is either the child or parent table for any
  109009. ** foreign key constraint. */
  109010. eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
  109011. }else{
  109012. /* This is an UPDATE. Foreign key processing is only required if the
  109013. ** operation modifies one or more child or parent key columns. */
  109014. FKey *p;
  109015. /* Check if any child key columns are being modified. */
  109016. for(p=pTab->pFKey; p; p=p->pNextFrom){
  109017. if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
  109018. if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
  109019. eRet = 1;
  109020. }
  109021. }
  109022. /* Check if any parent key columns are being modified. */
  109023. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  109024. if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
  109025. if( p->aAction[1]!=OE_None ) return 2;
  109026. eRet = 1;
  109027. }
  109028. }
  109029. }
  109030. }
  109031. return eRet;
  109032. }
  109033. /*
  109034. ** This function is called when an UPDATE or DELETE operation is being
  109035. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  109036. ** If the current operation is an UPDATE, then the pChanges parameter is
  109037. ** passed a pointer to the list of columns being modified. If it is a
  109038. ** DELETE, pChanges is passed a NULL pointer.
  109039. **
  109040. ** It returns a pointer to a Trigger structure containing a trigger
  109041. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  109042. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  109043. ** returned (these actions require no special handling by the triggers
  109044. ** sub-system, code for them is created by fkScanChildren()).
  109045. **
  109046. ** For example, if pFKey is the foreign key and pTab is table "p" in
  109047. ** the following schema:
  109048. **
  109049. ** CREATE TABLE p(pk PRIMARY KEY);
  109050. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  109051. **
  109052. ** then the returned trigger structure is equivalent to:
  109053. **
  109054. ** CREATE TRIGGER ... DELETE ON p BEGIN
  109055. ** DELETE FROM c WHERE ck = old.pk;
  109056. ** END;
  109057. **
  109058. ** The returned pointer is cached as part of the foreign key object. It
  109059. ** is eventually freed along with the rest of the foreign key object by
  109060. ** sqlite3FkDelete().
  109061. */
  109062. static Trigger *fkActionTrigger(
  109063. Parse *pParse, /* Parse context */
  109064. Table *pTab, /* Table being updated or deleted from */
  109065. FKey *pFKey, /* Foreign key to get action for */
  109066. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  109067. ){
  109068. sqlite3 *db = pParse->db; /* Database handle */
  109069. int action; /* One of OE_None, OE_Cascade etc. */
  109070. Trigger *pTrigger; /* Trigger definition to return */
  109071. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  109072. action = pFKey->aAction[iAction];
  109073. if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
  109074. return 0;
  109075. }
  109076. pTrigger = pFKey->apTrigger[iAction];
  109077. if( action!=OE_None && !pTrigger ){
  109078. char const *zFrom; /* Name of child table */
  109079. int nFrom; /* Length in bytes of zFrom */
  109080. Index *pIdx = 0; /* Parent key index for this FK */
  109081. int *aiCol = 0; /* child table cols -> parent key cols */
  109082. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  109083. Expr *pWhere = 0; /* WHERE clause of trigger step */
  109084. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  109085. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  109086. int i; /* Iterator variable */
  109087. Expr *pWhen = 0; /* WHEN clause for the trigger */
  109088. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  109089. assert( aiCol || pFKey->nCol==1 );
  109090. for(i=0; i<pFKey->nCol; i++){
  109091. Token tOld = { "old", 3 }; /* Literal "old" token */
  109092. Token tNew = { "new", 3 }; /* Literal "new" token */
  109093. Token tFromCol; /* Name of column in child table */
  109094. Token tToCol; /* Name of column in parent table */
  109095. int iFromCol; /* Idx of column in child table */
  109096. Expr *pEq; /* tFromCol = OLD.tToCol */
  109097. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  109098. assert( iFromCol>=0 );
  109099. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  109100. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  109101. sqlite3TokenInit(&tToCol,
  109102. pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
  109103. sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
  109104. /* Create the expression "OLD.zToCol = zFromCol". It is important
  109105. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  109106. ** that the affinity and collation sequence associated with the
  109107. ** parent table are used for the comparison. */
  109108. pEq = sqlite3PExpr(pParse, TK_EQ,
  109109. sqlite3PExpr(pParse, TK_DOT,
  109110. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  109111. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  109112. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  109113. );
  109114. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  109115. /* For ON UPDATE, construct the next term of the WHEN clause.
  109116. ** The final WHEN clause will be like this:
  109117. **
  109118. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  109119. */
  109120. if( pChanges ){
  109121. pEq = sqlite3PExpr(pParse, TK_IS,
  109122. sqlite3PExpr(pParse, TK_DOT,
  109123. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  109124. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  109125. sqlite3PExpr(pParse, TK_DOT,
  109126. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  109127. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
  109128. );
  109129. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  109130. }
  109131. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  109132. Expr *pNew;
  109133. if( action==OE_Cascade ){
  109134. pNew = sqlite3PExpr(pParse, TK_DOT,
  109135. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  109136. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
  109137. }else if( action==OE_SetDflt ){
  109138. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  109139. if( pDflt ){
  109140. pNew = sqlite3ExprDup(db, pDflt, 0);
  109141. }else{
  109142. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  109143. }
  109144. }else{
  109145. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  109146. }
  109147. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  109148. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  109149. }
  109150. }
  109151. sqlite3DbFree(db, aiCol);
  109152. zFrom = pFKey->pFrom->zName;
  109153. nFrom = sqlite3Strlen30(zFrom);
  109154. if( action==OE_Restrict ){
  109155. Token tFrom;
  109156. Expr *pRaise;
  109157. tFrom.z = zFrom;
  109158. tFrom.n = nFrom;
  109159. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  109160. if( pRaise ){
  109161. pRaise->affinity = OE_Abort;
  109162. }
  109163. pSelect = sqlite3SelectNew(pParse,
  109164. sqlite3ExprListAppend(pParse, 0, pRaise),
  109165. sqlite3SrcListAppend(pParse, 0, &tFrom, 0),
  109166. pWhere,
  109167. 0, 0, 0, 0, 0
  109168. );
  109169. pWhere = 0;
  109170. }
  109171. /* Disable lookaside memory allocation */
  109172. db->lookaside.bDisable++;
  109173. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  109174. sizeof(Trigger) + /* struct Trigger */
  109175. sizeof(TriggerStep) + /* Single step in trigger program */
  109176. nFrom + 1 /* Space for pStep->zTarget */
  109177. );
  109178. if( pTrigger ){
  109179. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  109180. pStep->zTarget = (char *)&pStep[1];
  109181. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  109182. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  109183. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  109184. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  109185. if( pWhen ){
  109186. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
  109187. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  109188. }
  109189. }
  109190. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  109191. db->lookaside.bDisable--;
  109192. sqlite3ExprDelete(db, pWhere);
  109193. sqlite3ExprDelete(db, pWhen);
  109194. sqlite3ExprListDelete(db, pList);
  109195. sqlite3SelectDelete(db, pSelect);
  109196. if( db->mallocFailed==1 ){
  109197. fkTriggerDelete(db, pTrigger);
  109198. return 0;
  109199. }
  109200. assert( pStep!=0 );
  109201. switch( action ){
  109202. case OE_Restrict:
  109203. pStep->op = TK_SELECT;
  109204. break;
  109205. case OE_Cascade:
  109206. if( !pChanges ){
  109207. pStep->op = TK_DELETE;
  109208. break;
  109209. }
  109210. default:
  109211. pStep->op = TK_UPDATE;
  109212. }
  109213. pStep->pTrig = pTrigger;
  109214. pTrigger->pSchema = pTab->pSchema;
  109215. pTrigger->pTabSchema = pTab->pSchema;
  109216. pFKey->apTrigger[iAction] = pTrigger;
  109217. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  109218. }
  109219. return pTrigger;
  109220. }
  109221. /*
  109222. ** This function is called when deleting or updating a row to implement
  109223. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  109224. */
  109225. SQLITE_PRIVATE void sqlite3FkActions(
  109226. Parse *pParse, /* Parse context */
  109227. Table *pTab, /* Table being updated or deleted from */
  109228. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  109229. int regOld, /* Address of array containing old row */
  109230. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  109231. int bChngRowid /* True if rowid is UPDATEd */
  109232. ){
  109233. /* If foreign-key support is enabled, iterate through all FKs that
  109234. ** refer to table pTab. If there is an action associated with the FK
  109235. ** for this operation (either update or delete), invoke the associated
  109236. ** trigger sub-program. */
  109237. if( pParse->db->flags&SQLITE_ForeignKeys ){
  109238. FKey *pFKey; /* Iterator variable */
  109239. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  109240. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  109241. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  109242. if( pAct ){
  109243. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  109244. }
  109245. }
  109246. }
  109247. }
  109248. }
  109249. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  109250. /*
  109251. ** Free all memory associated with foreign key definitions attached to
  109252. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  109253. ** hash table.
  109254. */
  109255. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  109256. FKey *pFKey; /* Iterator variable */
  109257. FKey *pNext; /* Copy of pFKey->pNextFrom */
  109258. assert( db==0 || IsVirtual(pTab)
  109259. || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  109260. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  109261. /* Remove the FK from the fkeyHash hash table. */
  109262. if( !db || db->pnBytesFreed==0 ){
  109263. if( pFKey->pPrevTo ){
  109264. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  109265. }else{
  109266. void *p = (void *)pFKey->pNextTo;
  109267. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  109268. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  109269. }
  109270. if( pFKey->pNextTo ){
  109271. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  109272. }
  109273. }
  109274. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  109275. ** classified as either immediate or deferred.
  109276. */
  109277. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  109278. /* Delete any triggers created to implement actions for this FK. */
  109279. #ifndef SQLITE_OMIT_TRIGGER
  109280. fkTriggerDelete(db, pFKey->apTrigger[0]);
  109281. fkTriggerDelete(db, pFKey->apTrigger[1]);
  109282. #endif
  109283. pNext = pFKey->pNextFrom;
  109284. sqlite3DbFree(db, pFKey);
  109285. }
  109286. }
  109287. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  109288. /************** End of fkey.c ************************************************/
  109289. /************** Begin file insert.c ******************************************/
  109290. /*
  109291. ** 2001 September 15
  109292. **
  109293. ** The author disclaims copyright to this source code. In place of
  109294. ** a legal notice, here is a blessing:
  109295. **
  109296. ** May you do good and not evil.
  109297. ** May you find forgiveness for yourself and forgive others.
  109298. ** May you share freely, never taking more than you give.
  109299. **
  109300. *************************************************************************
  109301. ** This file contains C code routines that are called by the parser
  109302. ** to handle INSERT statements in SQLite.
  109303. */
  109304. /* #include "sqliteInt.h" */
  109305. /*
  109306. ** Generate code that will
  109307. **
  109308. ** (1) acquire a lock for table pTab then
  109309. ** (2) open pTab as cursor iCur.
  109310. **
  109311. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  109312. ** for that table that is actually opened.
  109313. */
  109314. SQLITE_PRIVATE void sqlite3OpenTable(
  109315. Parse *pParse, /* Generate code into this VDBE */
  109316. int iCur, /* The cursor number of the table */
  109317. int iDb, /* The database index in sqlite3.aDb[] */
  109318. Table *pTab, /* The table to be opened */
  109319. int opcode /* OP_OpenRead or OP_OpenWrite */
  109320. ){
  109321. Vdbe *v;
  109322. assert( !IsVirtual(pTab) );
  109323. v = sqlite3GetVdbe(pParse);
  109324. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  109325. sqlite3TableLock(pParse, iDb, pTab->tnum,
  109326. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  109327. if( HasRowid(pTab) ){
  109328. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  109329. VdbeComment((v, "%s", pTab->zName));
  109330. }else{
  109331. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  109332. assert( pPk!=0 );
  109333. assert( pPk->tnum==pTab->tnum );
  109334. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  109335. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  109336. VdbeComment((v, "%s", pTab->zName));
  109337. }
  109338. }
  109339. /*
  109340. ** Return a pointer to the column affinity string associated with index
  109341. ** pIdx. A column affinity string has one character for each column in
  109342. ** the table, according to the affinity of the column:
  109343. **
  109344. ** Character Column affinity
  109345. ** ------------------------------
  109346. ** 'A' BLOB
  109347. ** 'B' TEXT
  109348. ** 'C' NUMERIC
  109349. ** 'D' INTEGER
  109350. ** 'F' REAL
  109351. **
  109352. ** An extra 'D' is appended to the end of the string to cover the
  109353. ** rowid that appears as the last column in every index.
  109354. **
  109355. ** Memory for the buffer containing the column index affinity string
  109356. ** is managed along with the rest of the Index structure. It will be
  109357. ** released when sqlite3DeleteIndex() is called.
  109358. */
  109359. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  109360. if( !pIdx->zColAff ){
  109361. /* The first time a column affinity string for a particular index is
  109362. ** required, it is allocated and populated here. It is then stored as
  109363. ** a member of the Index structure for subsequent use.
  109364. **
  109365. ** The column affinity string will eventually be deleted by
  109366. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  109367. ** up.
  109368. */
  109369. int n;
  109370. Table *pTab = pIdx->pTable;
  109371. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  109372. if( !pIdx->zColAff ){
  109373. sqlite3OomFault(db);
  109374. return 0;
  109375. }
  109376. for(n=0; n<pIdx->nColumn; n++){
  109377. i16 x = pIdx->aiColumn[n];
  109378. if( x>=0 ){
  109379. pIdx->zColAff[n] = pTab->aCol[x].affinity;
  109380. }else if( x==XN_ROWID ){
  109381. pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
  109382. }else{
  109383. char aff;
  109384. assert( x==XN_EXPR );
  109385. assert( pIdx->aColExpr!=0 );
  109386. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  109387. if( aff==0 ) aff = SQLITE_AFF_BLOB;
  109388. pIdx->zColAff[n] = aff;
  109389. }
  109390. }
  109391. pIdx->zColAff[n] = 0;
  109392. }
  109393. return pIdx->zColAff;
  109394. }
  109395. /*
  109396. ** Compute the affinity string for table pTab, if it has not already been
  109397. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  109398. **
  109399. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  109400. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  109401. ** for register iReg and following. Or if affinities exists and iReg==0,
  109402. ** then just set the P4 operand of the previous opcode (which should be
  109403. ** an OP_MakeRecord) to the affinity string.
  109404. **
  109405. ** A column affinity string has one character per column:
  109406. **
  109407. ** Character Column affinity
  109408. ** ------------------------------
  109409. ** 'A' BLOB
  109410. ** 'B' TEXT
  109411. ** 'C' NUMERIC
  109412. ** 'D' INTEGER
  109413. ** 'E' REAL
  109414. */
  109415. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  109416. int i;
  109417. char *zColAff = pTab->zColAff;
  109418. if( zColAff==0 ){
  109419. sqlite3 *db = sqlite3VdbeDb(v);
  109420. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  109421. if( !zColAff ){
  109422. sqlite3OomFault(db);
  109423. return;
  109424. }
  109425. for(i=0; i<pTab->nCol; i++){
  109426. zColAff[i] = pTab->aCol[i].affinity;
  109427. }
  109428. do{
  109429. zColAff[i--] = 0;
  109430. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  109431. pTab->zColAff = zColAff;
  109432. }
  109433. assert( zColAff!=0 );
  109434. i = sqlite3Strlen30NN(zColAff);
  109435. if( i ){
  109436. if( iReg ){
  109437. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  109438. }else{
  109439. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  109440. }
  109441. }
  109442. }
  109443. /*
  109444. ** Return non-zero if the table pTab in database iDb or any of its indices
  109445. ** have been opened at any point in the VDBE program. This is used to see if
  109446. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  109447. ** run without using a temporary table for the results of the SELECT.
  109448. */
  109449. static int readsTable(Parse *p, int iDb, Table *pTab){
  109450. Vdbe *v = sqlite3GetVdbe(p);
  109451. int i;
  109452. int iEnd = sqlite3VdbeCurrentAddr(v);
  109453. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109454. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  109455. #endif
  109456. for(i=1; i<iEnd; i++){
  109457. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  109458. assert( pOp!=0 );
  109459. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  109460. Index *pIndex;
  109461. int tnum = pOp->p2;
  109462. if( tnum==pTab->tnum ){
  109463. return 1;
  109464. }
  109465. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  109466. if( tnum==pIndex->tnum ){
  109467. return 1;
  109468. }
  109469. }
  109470. }
  109471. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109472. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  109473. assert( pOp->p4.pVtab!=0 );
  109474. assert( pOp->p4type==P4_VTAB );
  109475. return 1;
  109476. }
  109477. #endif
  109478. }
  109479. return 0;
  109480. }
  109481. #ifndef SQLITE_OMIT_AUTOINCREMENT
  109482. /*
  109483. ** Locate or create an AutoincInfo structure associated with table pTab
  109484. ** which is in database iDb. Return the register number for the register
  109485. ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
  109486. ** table. (Also return zero when doing a VACUUM since we do not want to
  109487. ** update the AUTOINCREMENT counters during a VACUUM.)
  109488. **
  109489. ** There is at most one AutoincInfo structure per table even if the
  109490. ** same table is autoincremented multiple times due to inserts within
  109491. ** triggers. A new AutoincInfo structure is created if this is the
  109492. ** first use of table pTab. On 2nd and subsequent uses, the original
  109493. ** AutoincInfo structure is used.
  109494. **
  109495. ** Four consecutive registers are allocated:
  109496. **
  109497. ** (1) The name of the pTab table.
  109498. ** (2) The maximum ROWID of pTab.
  109499. ** (3) The rowid in sqlite_sequence of pTab
  109500. ** (4) The original value of the max ROWID in pTab, or NULL if none
  109501. **
  109502. ** The 2nd register is the one that is returned. That is all the
  109503. ** insert routine needs to know about.
  109504. */
  109505. static int autoIncBegin(
  109506. Parse *pParse, /* Parsing context */
  109507. int iDb, /* Index of the database holding pTab */
  109508. Table *pTab /* The table we are writing to */
  109509. ){
  109510. int memId = 0; /* Register holding maximum rowid */
  109511. assert( pParse->db->aDb[iDb].pSchema!=0 );
  109512. if( (pTab->tabFlags & TF_Autoincrement)!=0
  109513. && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
  109514. ){
  109515. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  109516. AutoincInfo *pInfo;
  109517. Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
  109518. /* Verify that the sqlite_sequence table exists and is an ordinary
  109519. ** rowid table with exactly two columns.
  109520. ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
  109521. if( pSeqTab==0
  109522. || !HasRowid(pSeqTab)
  109523. || IsVirtual(pSeqTab)
  109524. || pSeqTab->nCol!=2
  109525. ){
  109526. pParse->nErr++;
  109527. pParse->rc = SQLITE_CORRUPT_SEQUENCE;
  109528. return 0;
  109529. }
  109530. pInfo = pToplevel->pAinc;
  109531. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  109532. if( pInfo==0 ){
  109533. pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
  109534. if( pInfo==0 ) return 0;
  109535. pInfo->pNext = pToplevel->pAinc;
  109536. pToplevel->pAinc = pInfo;
  109537. pInfo->pTab = pTab;
  109538. pInfo->iDb = iDb;
  109539. pToplevel->nMem++; /* Register to hold name of table */
  109540. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  109541. pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
  109542. }
  109543. memId = pInfo->regCtr;
  109544. }
  109545. return memId;
  109546. }
  109547. /*
  109548. ** This routine generates code that will initialize all of the
  109549. ** register used by the autoincrement tracker.
  109550. */
  109551. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  109552. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  109553. sqlite3 *db = pParse->db; /* The database connection */
  109554. Db *pDb; /* Database only autoinc table */
  109555. int memId; /* Register holding max rowid */
  109556. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  109557. /* This routine is never called during trigger-generation. It is
  109558. ** only called from the top-level */
  109559. assert( pParse->pTriggerTab==0 );
  109560. assert( sqlite3IsToplevel(pParse) );
  109561. assert( v ); /* We failed long ago if this is not so */
  109562. for(p = pParse->pAinc; p; p = p->pNext){
  109563. static const int iLn = VDBE_OFFSET_LINENO(2);
  109564. static const VdbeOpList autoInc[] = {
  109565. /* 0 */ {OP_Null, 0, 0, 0},
  109566. /* 1 */ {OP_Rewind, 0, 10, 0},
  109567. /* 2 */ {OP_Column, 0, 0, 0},
  109568. /* 3 */ {OP_Ne, 0, 9, 0},
  109569. /* 4 */ {OP_Rowid, 0, 0, 0},
  109570. /* 5 */ {OP_Column, 0, 1, 0},
  109571. /* 6 */ {OP_AddImm, 0, 0, 0},
  109572. /* 7 */ {OP_Copy, 0, 0, 0},
  109573. /* 8 */ {OP_Goto, 0, 11, 0},
  109574. /* 9 */ {OP_Next, 0, 2, 0},
  109575. /* 10 */ {OP_Integer, 0, 0, 0},
  109576. /* 11 */ {OP_Close, 0, 0, 0}
  109577. };
  109578. VdbeOp *aOp;
  109579. pDb = &db->aDb[p->iDb];
  109580. memId = p->regCtr;
  109581. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  109582. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  109583. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  109584. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
  109585. if( aOp==0 ) break;
  109586. aOp[0].p2 = memId;
  109587. aOp[0].p3 = memId+2;
  109588. aOp[2].p3 = memId;
  109589. aOp[3].p1 = memId-1;
  109590. aOp[3].p3 = memId;
  109591. aOp[3].p5 = SQLITE_JUMPIFNULL;
  109592. aOp[4].p2 = memId+1;
  109593. aOp[5].p3 = memId;
  109594. aOp[6].p1 = memId;
  109595. aOp[7].p2 = memId+2;
  109596. aOp[7].p1 = memId;
  109597. aOp[10].p2 = memId;
  109598. if( pParse->nTab==0 ) pParse->nTab = 1;
  109599. }
  109600. }
  109601. /*
  109602. ** Update the maximum rowid for an autoincrement calculation.
  109603. **
  109604. ** This routine should be called when the regRowid register holds a
  109605. ** new rowid that is about to be inserted. If that new rowid is
  109606. ** larger than the maximum rowid in the memId memory cell, then the
  109607. ** memory cell is updated.
  109608. */
  109609. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  109610. if( memId>0 ){
  109611. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  109612. }
  109613. }
  109614. /*
  109615. ** This routine generates the code needed to write autoincrement
  109616. ** maximum rowid values back into the sqlite_sequence register.
  109617. ** Every statement that might do an INSERT into an autoincrement
  109618. ** table (either directly or through triggers) needs to call this
  109619. ** routine just before the "exit" code.
  109620. */
  109621. static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
  109622. AutoincInfo *p;
  109623. Vdbe *v = pParse->pVdbe;
  109624. sqlite3 *db = pParse->db;
  109625. assert( v );
  109626. for(p = pParse->pAinc; p; p = p->pNext){
  109627. static const int iLn = VDBE_OFFSET_LINENO(2);
  109628. static const VdbeOpList autoIncEnd[] = {
  109629. /* 0 */ {OP_NotNull, 0, 2, 0},
  109630. /* 1 */ {OP_NewRowid, 0, 0, 0},
  109631. /* 2 */ {OP_MakeRecord, 0, 2, 0},
  109632. /* 3 */ {OP_Insert, 0, 0, 0},
  109633. /* 4 */ {OP_Close, 0, 0, 0}
  109634. };
  109635. VdbeOp *aOp;
  109636. Db *pDb = &db->aDb[p->iDb];
  109637. int iRec;
  109638. int memId = p->regCtr;
  109639. iRec = sqlite3GetTempReg(pParse);
  109640. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  109641. sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
  109642. VdbeCoverage(v);
  109643. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  109644. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
  109645. if( aOp==0 ) break;
  109646. aOp[0].p1 = memId+1;
  109647. aOp[1].p2 = memId+1;
  109648. aOp[2].p1 = memId-1;
  109649. aOp[2].p3 = iRec;
  109650. aOp[3].p2 = iRec;
  109651. aOp[3].p3 = memId+1;
  109652. aOp[3].p5 = OPFLAG_APPEND;
  109653. sqlite3ReleaseTempReg(pParse, iRec);
  109654. }
  109655. }
  109656. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  109657. if( pParse->pAinc ) autoIncrementEnd(pParse);
  109658. }
  109659. #else
  109660. /*
  109661. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  109662. ** above are all no-ops
  109663. */
  109664. # define autoIncBegin(A,B,C) (0)
  109665. # define autoIncStep(A,B,C)
  109666. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  109667. /* Forward declaration */
  109668. static int xferOptimization(
  109669. Parse *pParse, /* Parser context */
  109670. Table *pDest, /* The table we are inserting into */
  109671. Select *pSelect, /* A SELECT statement to use as the data source */
  109672. int onError, /* How to handle constraint errors */
  109673. int iDbDest /* The database of pDest */
  109674. );
  109675. /*
  109676. ** This routine is called to handle SQL of the following forms:
  109677. **
  109678. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  109679. ** insert into TABLE (IDLIST) select
  109680. ** insert into TABLE (IDLIST) default values
  109681. **
  109682. ** The IDLIST following the table name is always optional. If omitted,
  109683. ** then a list of all (non-hidden) columns for the table is substituted.
  109684. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  109685. ** is omitted.
  109686. **
  109687. ** For the pSelect parameter holds the values to be inserted for the
  109688. ** first two forms shown above. A VALUES clause is really just short-hand
  109689. ** for a SELECT statement that omits the FROM clause and everything else
  109690. ** that follows. If the pSelect parameter is NULL, that means that the
  109691. ** DEFAULT VALUES form of the INSERT statement is intended.
  109692. **
  109693. ** The code generated follows one of four templates. For a simple
  109694. ** insert with data coming from a single-row VALUES clause, the code executes
  109695. ** once straight down through. Pseudo-code follows (we call this
  109696. ** the "1st template"):
  109697. **
  109698. ** open write cursor to <table> and its indices
  109699. ** put VALUES clause expressions into registers
  109700. ** write the resulting record into <table>
  109701. ** cleanup
  109702. **
  109703. ** The three remaining templates assume the statement is of the form
  109704. **
  109705. ** INSERT INTO <table> SELECT ...
  109706. **
  109707. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  109708. ** in other words if the SELECT pulls all columns from a single table
  109709. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  109710. ** if <table2> and <table1> are distinct tables but have identical
  109711. ** schemas, including all the same indices, then a special optimization
  109712. ** is invoked that copies raw records from <table2> over to <table1>.
  109713. ** See the xferOptimization() function for the implementation of this
  109714. ** template. This is the 2nd template.
  109715. **
  109716. ** open a write cursor to <table>
  109717. ** open read cursor on <table2>
  109718. ** transfer all records in <table2> over to <table>
  109719. ** close cursors
  109720. ** foreach index on <table>
  109721. ** open a write cursor on the <table> index
  109722. ** open a read cursor on the corresponding <table2> index
  109723. ** transfer all records from the read to the write cursors
  109724. ** close cursors
  109725. ** end foreach
  109726. **
  109727. ** The 3rd template is for when the second template does not apply
  109728. ** and the SELECT clause does not read from <table> at any time.
  109729. ** The generated code follows this template:
  109730. **
  109731. ** X <- A
  109732. ** goto B
  109733. ** A: setup for the SELECT
  109734. ** loop over the rows in the SELECT
  109735. ** load values into registers R..R+n
  109736. ** yield X
  109737. ** end loop
  109738. ** cleanup after the SELECT
  109739. ** end-coroutine X
  109740. ** B: open write cursor to <table> and its indices
  109741. ** C: yield X, at EOF goto D
  109742. ** insert the select result into <table> from R..R+n
  109743. ** goto C
  109744. ** D: cleanup
  109745. **
  109746. ** The 4th template is used if the insert statement takes its
  109747. ** values from a SELECT but the data is being inserted into a table
  109748. ** that is also read as part of the SELECT. In the third form,
  109749. ** we have to use an intermediate table to store the results of
  109750. ** the select. The template is like this:
  109751. **
  109752. ** X <- A
  109753. ** goto B
  109754. ** A: setup for the SELECT
  109755. ** loop over the tables in the SELECT
  109756. ** load value into register R..R+n
  109757. ** yield X
  109758. ** end loop
  109759. ** cleanup after the SELECT
  109760. ** end co-routine R
  109761. ** B: open temp table
  109762. ** L: yield X, at EOF goto M
  109763. ** insert row from R..R+n into temp table
  109764. ** goto L
  109765. ** M: open write cursor to <table> and its indices
  109766. ** rewind temp table
  109767. ** C: loop over rows of intermediate table
  109768. ** transfer values form intermediate table into <table>
  109769. ** end loop
  109770. ** D: cleanup
  109771. */
  109772. SQLITE_PRIVATE void sqlite3Insert(
  109773. Parse *pParse, /* Parser context */
  109774. SrcList *pTabList, /* Name of table into which we are inserting */
  109775. Select *pSelect, /* A SELECT statement to use as the data source */
  109776. IdList *pColumn, /* Column names corresponding to IDLIST. */
  109777. int onError, /* How to handle constraint errors */
  109778. Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
  109779. ){
  109780. sqlite3 *db; /* The main database structure */
  109781. Table *pTab; /* The table to insert into. aka TABLE */
  109782. int i, j; /* Loop counters */
  109783. Vdbe *v; /* Generate code into this virtual machine */
  109784. Index *pIdx; /* For looping over indices of the table */
  109785. int nColumn; /* Number of columns in the data */
  109786. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  109787. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  109788. int iIdxCur = 0; /* First index cursor */
  109789. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  109790. int endOfLoop; /* Label for the end of the insertion loop */
  109791. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  109792. int addrInsTop = 0; /* Jump to label "D" */
  109793. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  109794. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  109795. int iDb; /* Index of database holding TABLE */
  109796. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  109797. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  109798. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  109799. u8 bIdListInOrder; /* True if IDLIST is in table order */
  109800. ExprList *pList = 0; /* List of VALUES() to be inserted */
  109801. /* Register allocations */
  109802. int regFromSelect = 0;/* Base register for data coming from SELECT */
  109803. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  109804. int regRowCount = 0; /* Memory cell used for the row counter */
  109805. int regIns; /* Block of regs holding rowid+data being inserted */
  109806. int regRowid; /* registers holding insert rowid */
  109807. int regData; /* register holding first column to insert */
  109808. int *aRegIdx = 0; /* One register allocated to each index */
  109809. #ifndef SQLITE_OMIT_TRIGGER
  109810. int isView; /* True if attempting to insert into a view */
  109811. Trigger *pTrigger; /* List of triggers on pTab, if required */
  109812. int tmask; /* Mask of trigger times */
  109813. #endif
  109814. db = pParse->db;
  109815. if( pParse->nErr || db->mallocFailed ){
  109816. goto insert_cleanup;
  109817. }
  109818. dest.iSDParm = 0; /* Suppress a harmless compiler warning */
  109819. /* If the Select object is really just a simple VALUES() list with a
  109820. ** single row (the common case) then keep that one row of values
  109821. ** and discard the other (unused) parts of the pSelect object
  109822. */
  109823. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  109824. pList = pSelect->pEList;
  109825. pSelect->pEList = 0;
  109826. sqlite3SelectDelete(db, pSelect);
  109827. pSelect = 0;
  109828. }
  109829. /* Locate the table into which we will be inserting new information.
  109830. */
  109831. assert( pTabList->nSrc==1 );
  109832. pTab = sqlite3SrcListLookup(pParse, pTabList);
  109833. if( pTab==0 ){
  109834. goto insert_cleanup;
  109835. }
  109836. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  109837. assert( iDb<db->nDb );
  109838. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
  109839. db->aDb[iDb].zDbSName) ){
  109840. goto insert_cleanup;
  109841. }
  109842. withoutRowid = !HasRowid(pTab);
  109843. /* Figure out if we have any triggers and if the table being
  109844. ** inserted into is a view
  109845. */
  109846. #ifndef SQLITE_OMIT_TRIGGER
  109847. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  109848. isView = pTab->pSelect!=0;
  109849. #else
  109850. # define pTrigger 0
  109851. # define tmask 0
  109852. # define isView 0
  109853. #endif
  109854. #ifdef SQLITE_OMIT_VIEW
  109855. # undef isView
  109856. # define isView 0
  109857. #endif
  109858. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  109859. /* If pTab is really a view, make sure it has been initialized.
  109860. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  109861. */
  109862. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  109863. goto insert_cleanup;
  109864. }
  109865. /* Cannot insert into a read-only table.
  109866. */
  109867. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  109868. goto insert_cleanup;
  109869. }
  109870. /* Allocate a VDBE
  109871. */
  109872. v = sqlite3GetVdbe(pParse);
  109873. if( v==0 ) goto insert_cleanup;
  109874. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  109875. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  109876. #ifndef SQLITE_OMIT_XFER_OPT
  109877. /* If the statement is of the form
  109878. **
  109879. ** INSERT INTO <table1> SELECT * FROM <table2>;
  109880. **
  109881. ** Then special optimizations can be applied that make the transfer
  109882. ** very fast and which reduce fragmentation of indices.
  109883. **
  109884. ** This is the 2nd template.
  109885. */
  109886. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  109887. assert( !pTrigger );
  109888. assert( pList==0 );
  109889. goto insert_end;
  109890. }
  109891. #endif /* SQLITE_OMIT_XFER_OPT */
  109892. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  109893. ** sqlite_sequence table and store it in memory cell regAutoinc.
  109894. */
  109895. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  109896. /* Allocate registers for holding the rowid of the new row,
  109897. ** the content of the new row, and the assembled row record.
  109898. */
  109899. regRowid = regIns = pParse->nMem+1;
  109900. pParse->nMem += pTab->nCol + 1;
  109901. if( IsVirtual(pTab) ){
  109902. regRowid++;
  109903. pParse->nMem++;
  109904. }
  109905. regData = regRowid+1;
  109906. /* If the INSERT statement included an IDLIST term, then make sure
  109907. ** all elements of the IDLIST really are columns of the table and
  109908. ** remember the column indices.
  109909. **
  109910. ** If the table has an INTEGER PRIMARY KEY column and that column
  109911. ** is named in the IDLIST, then record in the ipkColumn variable
  109912. ** the index into IDLIST of the primary key column. ipkColumn is
  109913. ** the index of the primary key as it appears in IDLIST, not as
  109914. ** is appears in the original table. (The index of the INTEGER
  109915. ** PRIMARY KEY in the original table is pTab->iPKey.)
  109916. */
  109917. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  109918. if( pColumn ){
  109919. for(i=0; i<pColumn->nId; i++){
  109920. pColumn->a[i].idx = -1;
  109921. }
  109922. for(i=0; i<pColumn->nId; i++){
  109923. for(j=0; j<pTab->nCol; j++){
  109924. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  109925. pColumn->a[i].idx = j;
  109926. if( i!=j ) bIdListInOrder = 0;
  109927. if( j==pTab->iPKey ){
  109928. ipkColumn = i; assert( !withoutRowid );
  109929. }
  109930. break;
  109931. }
  109932. }
  109933. if( j>=pTab->nCol ){
  109934. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  109935. ipkColumn = i;
  109936. bIdListInOrder = 0;
  109937. }else{
  109938. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  109939. pTabList, 0, pColumn->a[i].zName);
  109940. pParse->checkSchema = 1;
  109941. goto insert_cleanup;
  109942. }
  109943. }
  109944. }
  109945. }
  109946. /* Figure out how many columns of data are supplied. If the data
  109947. ** is coming from a SELECT statement, then generate a co-routine that
  109948. ** produces a single row of the SELECT on each invocation. The
  109949. ** co-routine is the common header to the 3rd and 4th templates.
  109950. */
  109951. if( pSelect ){
  109952. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  109953. ** Generate a co-routine to run the SELECT. */
  109954. int regYield; /* Register holding co-routine entry-point */
  109955. int addrTop; /* Top of the co-routine */
  109956. int rc; /* Result code */
  109957. regYield = ++pParse->nMem;
  109958. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  109959. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  109960. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  109961. dest.iSdst = bIdListInOrder ? regData : 0;
  109962. dest.nSdst = pTab->nCol;
  109963. rc = sqlite3Select(pParse, pSelect, &dest);
  109964. regFromSelect = dest.iSdst;
  109965. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  109966. sqlite3VdbeEndCoroutine(v, regYield);
  109967. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  109968. assert( pSelect->pEList );
  109969. nColumn = pSelect->pEList->nExpr;
  109970. /* Set useTempTable to TRUE if the result of the SELECT statement
  109971. ** should be written into a temporary table (template 4). Set to
  109972. ** FALSE if each output row of the SELECT can be written directly into
  109973. ** the destination table (template 3).
  109974. **
  109975. ** A temp table must be used if the table being updated is also one
  109976. ** of the tables being read by the SELECT statement. Also use a
  109977. ** temp table in the case of row triggers.
  109978. */
  109979. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  109980. useTempTable = 1;
  109981. }
  109982. if( useTempTable ){
  109983. /* Invoke the coroutine to extract information from the SELECT
  109984. ** and add it to a transient table srcTab. The code generated
  109985. ** here is from the 4th template:
  109986. **
  109987. ** B: open temp table
  109988. ** L: yield X, goto M at EOF
  109989. ** insert row from R..R+n into temp table
  109990. ** goto L
  109991. ** M: ...
  109992. */
  109993. int regRec; /* Register to hold packed record */
  109994. int regTempRowid; /* Register to hold temp table ROWID */
  109995. int addrL; /* Label "L" */
  109996. srcTab = pParse->nTab++;
  109997. regRec = sqlite3GetTempReg(pParse);
  109998. regTempRowid = sqlite3GetTempReg(pParse);
  109999. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  110000. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  110001. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  110002. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  110003. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  110004. sqlite3VdbeGoto(v, addrL);
  110005. sqlite3VdbeJumpHere(v, addrL);
  110006. sqlite3ReleaseTempReg(pParse, regRec);
  110007. sqlite3ReleaseTempReg(pParse, regTempRowid);
  110008. }
  110009. }else{
  110010. /* This is the case if the data for the INSERT is coming from a
  110011. ** single-row VALUES clause
  110012. */
  110013. NameContext sNC;
  110014. memset(&sNC, 0, sizeof(sNC));
  110015. sNC.pParse = pParse;
  110016. srcTab = -1;
  110017. assert( useTempTable==0 );
  110018. if( pList ){
  110019. nColumn = pList->nExpr;
  110020. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  110021. goto insert_cleanup;
  110022. }
  110023. }else{
  110024. nColumn = 0;
  110025. }
  110026. }
  110027. /* If there is no IDLIST term but the table has an integer primary
  110028. ** key, the set the ipkColumn variable to the integer primary key
  110029. ** column index in the original table definition.
  110030. */
  110031. if( pColumn==0 && nColumn>0 ){
  110032. ipkColumn = pTab->iPKey;
  110033. }
  110034. /* Make sure the number of columns in the source data matches the number
  110035. ** of columns to be inserted into the table.
  110036. */
  110037. for(i=0; i<pTab->nCol; i++){
  110038. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  110039. }
  110040. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  110041. sqlite3ErrorMsg(pParse,
  110042. "table %S has %d columns but %d values were supplied",
  110043. pTabList, 0, pTab->nCol-nHidden, nColumn);
  110044. goto insert_cleanup;
  110045. }
  110046. if( pColumn!=0 && nColumn!=pColumn->nId ){
  110047. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  110048. goto insert_cleanup;
  110049. }
  110050. /* Initialize the count of rows to be inserted
  110051. */
  110052. if( (db->flags & SQLITE_CountRows)!=0
  110053. && !pParse->nested
  110054. && !pParse->pTriggerTab
  110055. ){
  110056. regRowCount = ++pParse->nMem;
  110057. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  110058. }
  110059. /* If this is not a view, open the table and and all indices */
  110060. if( !isView ){
  110061. int nIdx;
  110062. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
  110063. &iDataCur, &iIdxCur);
  110064. aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
  110065. if( aRegIdx==0 ){
  110066. goto insert_cleanup;
  110067. }
  110068. for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
  110069. assert( pIdx );
  110070. aRegIdx[i] = ++pParse->nMem;
  110071. pParse->nMem += pIdx->nColumn;
  110072. }
  110073. }
  110074. #ifndef SQLITE_OMIT_UPSERT
  110075. if( pUpsert ){
  110076. if( IsVirtual(pTab) ){
  110077. sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
  110078. pTab->zName);
  110079. goto insert_cleanup;
  110080. }
  110081. pTabList->a[0].iCursor = iDataCur;
  110082. pUpsert->pUpsertSrc = pTabList;
  110083. pUpsert->regData = regData;
  110084. pUpsert->iDataCur = iDataCur;
  110085. pUpsert->iIdxCur = iIdxCur;
  110086. if( pUpsert->pUpsertTarget ){
  110087. sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
  110088. }
  110089. }
  110090. #endif
  110091. /* This is the top of the main insertion loop */
  110092. if( useTempTable ){
  110093. /* This block codes the top of loop only. The complete loop is the
  110094. ** following pseudocode (template 4):
  110095. **
  110096. ** rewind temp table, if empty goto D
  110097. ** C: loop over rows of intermediate table
  110098. ** transfer values form intermediate table into <table>
  110099. ** end loop
  110100. ** D: ...
  110101. */
  110102. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  110103. addrCont = sqlite3VdbeCurrentAddr(v);
  110104. }else if( pSelect ){
  110105. /* This block codes the top of loop only. The complete loop is the
  110106. ** following pseudocode (template 3):
  110107. **
  110108. ** C: yield X, at EOF goto D
  110109. ** insert the select result into <table> from R..R+n
  110110. ** goto C
  110111. ** D: ...
  110112. */
  110113. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  110114. VdbeCoverage(v);
  110115. }
  110116. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  110117. */
  110118. endOfLoop = sqlite3VdbeMakeLabel(pParse);
  110119. if( tmask & TRIGGER_BEFORE ){
  110120. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  110121. /* build the NEW.* reference row. Note that if there is an INTEGER
  110122. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  110123. ** translated into a unique ID for the row. But on a BEFORE trigger,
  110124. ** we do not know what the unique ID will be (because the insert has
  110125. ** not happened yet) so we substitute a rowid of -1
  110126. */
  110127. if( ipkColumn<0 ){
  110128. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  110129. }else{
  110130. int addr1;
  110131. assert( !withoutRowid );
  110132. if( useTempTable ){
  110133. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  110134. }else{
  110135. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  110136. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  110137. }
  110138. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  110139. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  110140. sqlite3VdbeJumpHere(v, addr1);
  110141. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  110142. }
  110143. /* Cannot have triggers on a virtual table. If it were possible,
  110144. ** this block would have to account for hidden column.
  110145. */
  110146. assert( !IsVirtual(pTab) );
  110147. /* Create the new column data
  110148. */
  110149. for(i=j=0; i<pTab->nCol; i++){
  110150. if( pColumn ){
  110151. for(j=0; j<pColumn->nId; j++){
  110152. if( pColumn->a[j].idx==i ) break;
  110153. }
  110154. }
  110155. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
  110156. || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
  110157. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  110158. }else if( useTempTable ){
  110159. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  110160. }else{
  110161. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  110162. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  110163. }
  110164. if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
  110165. }
  110166. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  110167. ** do not attempt any conversions before assembling the record.
  110168. ** If this is a real table, attempt conversions as required by the
  110169. ** table column affinities.
  110170. */
  110171. if( !isView ){
  110172. sqlite3TableAffinity(v, pTab, regCols+1);
  110173. }
  110174. /* Fire BEFORE or INSTEAD OF triggers */
  110175. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  110176. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  110177. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  110178. }
  110179. /* Compute the content of the next row to insert into a range of
  110180. ** registers beginning at regIns.
  110181. */
  110182. if( !isView ){
  110183. if( IsVirtual(pTab) ){
  110184. /* The row that the VUpdate opcode will delete: none */
  110185. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  110186. }
  110187. if( ipkColumn>=0 ){
  110188. if( useTempTable ){
  110189. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  110190. }else if( pSelect ){
  110191. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  110192. }else{
  110193. Expr *pIpk = pList->a[ipkColumn].pExpr;
  110194. if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
  110195. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  110196. appendFlag = 1;
  110197. }else{
  110198. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  110199. }
  110200. }
  110201. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  110202. ** to generate a unique primary key value.
  110203. */
  110204. if( !appendFlag ){
  110205. int addr1;
  110206. if( !IsVirtual(pTab) ){
  110207. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  110208. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  110209. sqlite3VdbeJumpHere(v, addr1);
  110210. }else{
  110211. addr1 = sqlite3VdbeCurrentAddr(v);
  110212. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  110213. }
  110214. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  110215. }
  110216. }else if( IsVirtual(pTab) || withoutRowid ){
  110217. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  110218. }else{
  110219. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  110220. appendFlag = 1;
  110221. }
  110222. autoIncStep(pParse, regAutoinc, regRowid);
  110223. /* Compute data for all columns of the new entry, beginning
  110224. ** with the first column.
  110225. */
  110226. nHidden = 0;
  110227. for(i=0; i<pTab->nCol; i++){
  110228. int iRegStore = regRowid+1+i;
  110229. if( i==pTab->iPKey ){
  110230. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  110231. ** Whenever this column is read, the rowid will be substituted
  110232. ** in its place. Hence, fill this column with a NULL to avoid
  110233. ** taking up data space with information that will never be used.
  110234. ** As there may be shallow copies of this value, make it a soft-NULL */
  110235. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  110236. continue;
  110237. }
  110238. if( pColumn==0 ){
  110239. if( IsHiddenColumn(&pTab->aCol[i]) ){
  110240. j = -1;
  110241. nHidden++;
  110242. }else{
  110243. j = i - nHidden;
  110244. }
  110245. }else{
  110246. for(j=0; j<pColumn->nId; j++){
  110247. if( pColumn->a[j].idx==i ) break;
  110248. }
  110249. }
  110250. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  110251. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  110252. }else if( useTempTable ){
  110253. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  110254. }else if( pSelect ){
  110255. if( regFromSelect!=regData ){
  110256. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  110257. }
  110258. }else{
  110259. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  110260. }
  110261. }
  110262. /* Generate code to check constraints and generate index keys and
  110263. ** do the insertion.
  110264. */
  110265. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110266. if( IsVirtual(pTab) ){
  110267. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  110268. sqlite3VtabMakeWritable(pParse, pTab);
  110269. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  110270. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  110271. sqlite3MayAbort(pParse);
  110272. }else
  110273. #endif
  110274. {
  110275. int isReplace; /* Set to true if constraints may cause a replace */
  110276. int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
  110277. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  110278. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
  110279. );
  110280. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  110281. /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
  110282. ** constraints or (b) there are no triggers and this table is not a
  110283. ** parent table in a foreign key constraint. It is safe to set the
  110284. ** flag in the second case as if any REPLACE constraint is hit, an
  110285. ** OP_Delete or OP_IdxDelete instruction will be executed on each
  110286. ** cursor that is disturbed. And these instructions both clear the
  110287. ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
  110288. ** functionality. */
  110289. bUseSeek = (isReplace==0 || (pTrigger==0 &&
  110290. ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
  110291. ));
  110292. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  110293. regIns, aRegIdx, 0, appendFlag, bUseSeek
  110294. );
  110295. }
  110296. }
  110297. /* Update the count of rows that are inserted
  110298. */
  110299. if( regRowCount ){
  110300. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  110301. }
  110302. if( pTrigger ){
  110303. /* Code AFTER triggers */
  110304. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  110305. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  110306. }
  110307. /* The bottom of the main insertion loop, if the data source
  110308. ** is a SELECT statement.
  110309. */
  110310. sqlite3VdbeResolveLabel(v, endOfLoop);
  110311. if( useTempTable ){
  110312. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  110313. sqlite3VdbeJumpHere(v, addrInsTop);
  110314. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  110315. }else if( pSelect ){
  110316. sqlite3VdbeGoto(v, addrCont);
  110317. sqlite3VdbeJumpHere(v, addrInsTop);
  110318. }
  110319. insert_end:
  110320. /* Update the sqlite_sequence table by storing the content of the
  110321. ** maximum rowid counter values recorded while inserting into
  110322. ** autoincrement tables.
  110323. */
  110324. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  110325. sqlite3AutoincrementEnd(pParse);
  110326. }
  110327. /*
  110328. ** Return the number of rows inserted. If this routine is
  110329. ** generating code because of a call to sqlite3NestedParse(), do not
  110330. ** invoke the callback function.
  110331. */
  110332. if( regRowCount ){
  110333. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  110334. sqlite3VdbeSetNumCols(v, 1);
  110335. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  110336. }
  110337. insert_cleanup:
  110338. sqlite3SrcListDelete(db, pTabList);
  110339. sqlite3ExprListDelete(db, pList);
  110340. sqlite3UpsertDelete(db, pUpsert);
  110341. sqlite3SelectDelete(db, pSelect);
  110342. sqlite3IdListDelete(db, pColumn);
  110343. sqlite3DbFree(db, aRegIdx);
  110344. }
  110345. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  110346. ** they may interfere with compilation of other functions in this file
  110347. ** (or in another file, if this file becomes part of the amalgamation). */
  110348. #ifdef isView
  110349. #undef isView
  110350. #endif
  110351. #ifdef pTrigger
  110352. #undef pTrigger
  110353. #endif
  110354. #ifdef tmask
  110355. #undef tmask
  110356. #endif
  110357. /*
  110358. ** Meanings of bits in of pWalker->eCode for
  110359. ** sqlite3ExprReferencesUpdatedColumn()
  110360. */
  110361. #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
  110362. #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
  110363. /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
  110364. * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
  110365. ** expression node references any of the
  110366. ** columns that are being modifed by an UPDATE statement.
  110367. */
  110368. static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
  110369. if( pExpr->op==TK_COLUMN ){
  110370. assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
  110371. if( pExpr->iColumn>=0 ){
  110372. if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
  110373. pWalker->eCode |= CKCNSTRNT_COLUMN;
  110374. }
  110375. }else{
  110376. pWalker->eCode |= CKCNSTRNT_ROWID;
  110377. }
  110378. }
  110379. return WRC_Continue;
  110380. }
  110381. /*
  110382. ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
  110383. ** only columns that are modified by the UPDATE are those for which
  110384. ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
  110385. **
  110386. ** Return true if CHECK constraint pExpr uses any of the
  110387. ** changing columns (or the rowid if it is changing). In other words,
  110388. ** return true if this CHECK constraint must be validated for
  110389. ** the new row in the UPDATE statement.
  110390. **
  110391. ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
  110392. ** The operation of this routine is the same - return true if an only if
  110393. ** the expression uses one or more of columns identified by the second and
  110394. ** third arguments.
  110395. */
  110396. SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(
  110397. Expr *pExpr, /* The expression to be checked */
  110398. int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
  110399. int chngRowid /* True if UPDATE changes the rowid */
  110400. ){
  110401. Walker w;
  110402. memset(&w, 0, sizeof(w));
  110403. w.eCode = 0;
  110404. w.xExprCallback = checkConstraintExprNode;
  110405. w.u.aiCol = aiChng;
  110406. sqlite3WalkExpr(&w, pExpr);
  110407. if( !chngRowid ){
  110408. testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
  110409. w.eCode &= ~CKCNSTRNT_ROWID;
  110410. }
  110411. testcase( w.eCode==0 );
  110412. testcase( w.eCode==CKCNSTRNT_COLUMN );
  110413. testcase( w.eCode==CKCNSTRNT_ROWID );
  110414. testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
  110415. return w.eCode!=0;
  110416. }
  110417. /*
  110418. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  110419. ** on table pTab.
  110420. **
  110421. ** The regNewData parameter is the first register in a range that contains
  110422. ** the data to be inserted or the data after the update. There will be
  110423. ** pTab->nCol+1 registers in this range. The first register (the one
  110424. ** that regNewData points to) will contain the new rowid, or NULL in the
  110425. ** case of a WITHOUT ROWID table. The second register in the range will
  110426. ** contain the content of the first table column. The third register will
  110427. ** contain the content of the second table column. And so forth.
  110428. **
  110429. ** The regOldData parameter is similar to regNewData except that it contains
  110430. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  110431. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  110432. ** checking regOldData for zero.
  110433. **
  110434. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  110435. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  110436. ** might be modified by the UPDATE. If pkChng is false, then the key of
  110437. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  110438. **
  110439. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  110440. ** was explicitly specified as part of the INSERT statement. If pkChng
  110441. ** is zero, it means that the either rowid is computed automatically or
  110442. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  110443. ** pkChng will only be true if the INSERT statement provides an integer
  110444. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  110445. **
  110446. ** The code generated by this routine will store new index entries into
  110447. ** registers identified by aRegIdx[]. No index entry is created for
  110448. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  110449. ** the same as the order of indices on the linked list of indices
  110450. ** at pTab->pIndex.
  110451. **
  110452. ** The caller must have already opened writeable cursors on the main
  110453. ** table and all applicable indices (that is to say, all indices for which
  110454. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  110455. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  110456. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  110457. ** for the first index in the pTab->pIndex list. Cursors for other indices
  110458. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  110459. **
  110460. ** This routine also generates code to check constraints. NOT NULL,
  110461. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  110462. ** then the appropriate action is performed. There are five possible
  110463. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  110464. **
  110465. ** Constraint type Action What Happens
  110466. ** --------------- ---------- ----------------------------------------
  110467. ** any ROLLBACK The current transaction is rolled back and
  110468. ** sqlite3_step() returns immediately with a
  110469. ** return code of SQLITE_CONSTRAINT.
  110470. **
  110471. ** any ABORT Back out changes from the current command
  110472. ** only (do not do a complete rollback) then
  110473. ** cause sqlite3_step() to return immediately
  110474. ** with SQLITE_CONSTRAINT.
  110475. **
  110476. ** any FAIL Sqlite3_step() returns immediately with a
  110477. ** return code of SQLITE_CONSTRAINT. The
  110478. ** transaction is not rolled back and any
  110479. ** changes to prior rows are retained.
  110480. **
  110481. ** any IGNORE The attempt in insert or update the current
  110482. ** row is skipped, without throwing an error.
  110483. ** Processing continues with the next row.
  110484. ** (There is an immediate jump to ignoreDest.)
  110485. **
  110486. ** NOT NULL REPLACE The NULL value is replace by the default
  110487. ** value for that column. If the default value
  110488. ** is NULL, the action is the same as ABORT.
  110489. **
  110490. ** UNIQUE REPLACE The other row that conflicts with the row
  110491. ** being inserted is removed.
  110492. **
  110493. ** CHECK REPLACE Illegal. The results in an exception.
  110494. **
  110495. ** Which action to take is determined by the overrideError parameter.
  110496. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  110497. ** is used. Or if pParse->onError==OE_Default then the onError value
  110498. ** for the constraint is used.
  110499. */
  110500. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  110501. Parse *pParse, /* The parser context */
  110502. Table *pTab, /* The table being inserted or updated */
  110503. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  110504. int iDataCur, /* Canonical data cursor (main table or PK index) */
  110505. int iIdxCur, /* First index cursor */
  110506. int regNewData, /* First register in a range holding values to insert */
  110507. int regOldData, /* Previous content. 0 for INSERTs */
  110508. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  110509. u8 overrideError, /* Override onError to this if not OE_Default */
  110510. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  110511. int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
  110512. int *aiChng, /* column i is unchanged if aiChng[i]<0 */
  110513. Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
  110514. ){
  110515. Vdbe *v; /* VDBE under constrution */
  110516. Index *pIdx; /* Pointer to one of the indices */
  110517. Index *pPk = 0; /* The PRIMARY KEY index */
  110518. sqlite3 *db; /* Database connection */
  110519. int i; /* loop counter */
  110520. int ix; /* Index loop counter */
  110521. int nCol; /* Number of columns */
  110522. int onError; /* Conflict resolution strategy */
  110523. int addr1; /* Address of jump instruction */
  110524. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  110525. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  110526. Index *pUpIdx = 0; /* Index to which to apply the upsert */
  110527. u8 isUpdate; /* True if this is an UPDATE operation */
  110528. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  110529. int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */
  110530. int upsertJump = 0; /* Address of Goto that jumps into upsert subroutine */
  110531. int ipkTop = 0; /* Top of the IPK uniqueness check */
  110532. int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
  110533. isUpdate = regOldData!=0;
  110534. db = pParse->db;
  110535. v = sqlite3GetVdbe(pParse);
  110536. assert( v!=0 );
  110537. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  110538. nCol = pTab->nCol;
  110539. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  110540. ** normal rowid tables. nPkField is the number of key fields in the
  110541. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  110542. ** number of fields in the true primary key of the table. */
  110543. if( HasRowid(pTab) ){
  110544. pPk = 0;
  110545. nPkField = 1;
  110546. }else{
  110547. pPk = sqlite3PrimaryKeyIndex(pTab);
  110548. nPkField = pPk->nKeyCol;
  110549. }
  110550. /* Record that this module has started */
  110551. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  110552. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  110553. /* Test all NOT NULL constraints.
  110554. */
  110555. for(i=0; i<nCol; i++){
  110556. if( i==pTab->iPKey ){
  110557. continue; /* ROWID is never NULL */
  110558. }
  110559. if( aiChng && aiChng[i]<0 ){
  110560. /* Don't bother checking for NOT NULL on columns that do not change */
  110561. continue;
  110562. }
  110563. onError = pTab->aCol[i].notNull;
  110564. if( onError==OE_None ) continue; /* This column is allowed to be NULL */
  110565. if( overrideError!=OE_Default ){
  110566. onError = overrideError;
  110567. }else if( onError==OE_Default ){
  110568. onError = OE_Abort;
  110569. }
  110570. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  110571. onError = OE_Abort;
  110572. }
  110573. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  110574. || onError==OE_Ignore || onError==OE_Replace );
  110575. addr1 = 0;
  110576. switch( onError ){
  110577. case OE_Replace: {
  110578. assert( onError==OE_Replace );
  110579. addr1 = sqlite3VdbeMakeLabel(pParse);
  110580. sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
  110581. VdbeCoverage(v);
  110582. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  110583. sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
  110584. VdbeCoverage(v);
  110585. onError = OE_Abort;
  110586. /* Fall through into the OE_Abort case to generate code that runs
  110587. ** if both the input and the default value are NULL */
  110588. }
  110589. case OE_Abort:
  110590. sqlite3MayAbort(pParse);
  110591. /* Fall through */
  110592. case OE_Rollback:
  110593. case OE_Fail: {
  110594. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  110595. pTab->aCol[i].zName);
  110596. sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  110597. regNewData+1+i);
  110598. sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
  110599. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  110600. VdbeCoverage(v);
  110601. if( addr1 ) sqlite3VdbeResolveLabel(v, addr1);
  110602. break;
  110603. }
  110604. default: {
  110605. assert( onError==OE_Ignore );
  110606. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  110607. VdbeCoverage(v);
  110608. break;
  110609. }
  110610. }
  110611. }
  110612. /* Test all CHECK constraints
  110613. */
  110614. #ifndef SQLITE_OMIT_CHECK
  110615. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  110616. ExprList *pCheck = pTab->pCheck;
  110617. pParse->iSelfTab = -(regNewData+1);
  110618. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  110619. for(i=0; i<pCheck->nExpr; i++){
  110620. int allOk;
  110621. Expr *pExpr = pCheck->a[i].pExpr;
  110622. if( aiChng
  110623. && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
  110624. ){
  110625. /* The check constraints do not reference any of the columns being
  110626. ** updated so there is no point it verifying the check constraint */
  110627. continue;
  110628. }
  110629. allOk = sqlite3VdbeMakeLabel(pParse);
  110630. sqlite3VdbeVerifyAbortable(v, onError);
  110631. sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
  110632. if( onError==OE_Ignore ){
  110633. sqlite3VdbeGoto(v, ignoreDest);
  110634. }else{
  110635. char *zName = pCheck->a[i].zName;
  110636. if( zName==0 ) zName = pTab->zName;
  110637. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  110638. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  110639. onError, zName, P4_TRANSIENT,
  110640. P5_ConstraintCheck);
  110641. }
  110642. sqlite3VdbeResolveLabel(v, allOk);
  110643. }
  110644. pParse->iSelfTab = 0;
  110645. }
  110646. #endif /* !defined(SQLITE_OMIT_CHECK) */
  110647. /* UNIQUE and PRIMARY KEY constraints should be handled in the following
  110648. ** order:
  110649. **
  110650. ** (1) OE_Update
  110651. ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
  110652. ** (3) OE_Replace
  110653. **
  110654. ** OE_Fail and OE_Ignore must happen before any changes are made.
  110655. ** OE_Update guarantees that only a single row will change, so it
  110656. ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
  110657. ** could happen in any order, but they are grouped up front for
  110658. ** convenience.
  110659. **
  110660. ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
  110661. ** The order of constraints used to have OE_Update as (2) and OE_Abort
  110662. ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
  110663. ** constraint before any others, so it had to be moved.
  110664. **
  110665. ** Constraint checking code is generated in this order:
  110666. ** (A) The rowid constraint
  110667. ** (B) Unique index constraints that do not have OE_Replace as their
  110668. ** default conflict resolution strategy
  110669. ** (C) Unique index that do use OE_Replace by default.
  110670. **
  110671. ** The ordering of (2) and (3) is accomplished by making sure the linked
  110672. ** list of indexes attached to a table puts all OE_Replace indexes last
  110673. ** in the list. See sqlite3CreateIndex() for where that happens.
  110674. */
  110675. if( pUpsert ){
  110676. if( pUpsert->pUpsertTarget==0 ){
  110677. /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
  110678. ** Make all unique constraint resolution be OE_Ignore */
  110679. assert( pUpsert->pUpsertSet==0 );
  110680. overrideError = OE_Ignore;
  110681. pUpsert = 0;
  110682. }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
  110683. /* If the constraint-target uniqueness check must be run first.
  110684. ** Jump to that uniqueness check now */
  110685. upsertJump = sqlite3VdbeAddOp0(v, OP_Goto);
  110686. VdbeComment((v, "UPSERT constraint goes first"));
  110687. }
  110688. }
  110689. /* If rowid is changing, make sure the new rowid does not previously
  110690. ** exist in the table.
  110691. */
  110692. if( pkChng && pPk==0 ){
  110693. int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
  110694. /* Figure out what action to take in case of a rowid collision */
  110695. onError = pTab->keyConf;
  110696. if( overrideError!=OE_Default ){
  110697. onError = overrideError;
  110698. }else if( onError==OE_Default ){
  110699. onError = OE_Abort;
  110700. }
  110701. /* figure out whether or not upsert applies in this case */
  110702. if( pUpsert && pUpsert->pUpsertIdx==0 ){
  110703. if( pUpsert->pUpsertSet==0 ){
  110704. onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
  110705. }else{
  110706. onError = OE_Update; /* DO UPDATE */
  110707. }
  110708. }
  110709. /* If the response to a rowid conflict is REPLACE but the response
  110710. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  110711. ** to defer the running of the rowid conflict checking until after
  110712. ** the UNIQUE constraints have run.
  110713. */
  110714. if( onError==OE_Replace /* IPK rule is REPLACE */
  110715. && onError!=overrideError /* Rules for other contraints are different */
  110716. && pTab->pIndex /* There exist other constraints */
  110717. ){
  110718. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
  110719. VdbeComment((v, "defer IPK REPLACE until last"));
  110720. }
  110721. if( isUpdate ){
  110722. /* pkChng!=0 does not mean that the rowid has changed, only that
  110723. ** it might have changed. Skip the conflict logic below if the rowid
  110724. ** is unchanged. */
  110725. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  110726. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  110727. VdbeCoverage(v);
  110728. }
  110729. /* Check to see if the new rowid already exists in the table. Skip
  110730. ** the following conflict logic if it does not. */
  110731. VdbeNoopComment((v, "uniqueness check for ROWID"));
  110732. sqlite3VdbeVerifyAbortable(v, onError);
  110733. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  110734. VdbeCoverage(v);
  110735. switch( onError ){
  110736. default: {
  110737. onError = OE_Abort;
  110738. /* Fall thru into the next case */
  110739. }
  110740. case OE_Rollback:
  110741. case OE_Abort:
  110742. case OE_Fail: {
  110743. testcase( onError==OE_Rollback );
  110744. testcase( onError==OE_Abort );
  110745. testcase( onError==OE_Fail );
  110746. sqlite3RowidConstraint(pParse, onError, pTab);
  110747. break;
  110748. }
  110749. case OE_Replace: {
  110750. /* If there are DELETE triggers on this table and the
  110751. ** recursive-triggers flag is set, call GenerateRowDelete() to
  110752. ** remove the conflicting row from the table. This will fire
  110753. ** the triggers and remove both the table and index b-tree entries.
  110754. **
  110755. ** Otherwise, if there are no triggers or the recursive-triggers
  110756. ** flag is not set, but the table has one or more indexes, call
  110757. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  110758. ** only. The table b-tree entry will be replaced by the new entry
  110759. ** when it is inserted.
  110760. **
  110761. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  110762. ** also invoke MultiWrite() to indicate that this VDBE may require
  110763. ** statement rollback (if the statement is aborted after the delete
  110764. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  110765. ** but being more selective here allows statements like:
  110766. **
  110767. ** REPLACE INTO t(rowid) VALUES($newrowid)
  110768. **
  110769. ** to run without a statement journal if there are no indexes on the
  110770. ** table.
  110771. */
  110772. Trigger *pTrigger = 0;
  110773. if( db->flags&SQLITE_RecTriggers ){
  110774. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  110775. }
  110776. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  110777. sqlite3MultiWrite(pParse);
  110778. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  110779. regNewData, 1, 0, OE_Replace, 1, -1);
  110780. }else{
  110781. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  110782. assert( HasRowid(pTab) );
  110783. /* This OP_Delete opcode fires the pre-update-hook only. It does
  110784. ** not modify the b-tree. It is more efficient to let the coming
  110785. ** OP_Insert replace the existing entry than it is to delete the
  110786. ** existing entry and then insert a new one. */
  110787. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
  110788. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  110789. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  110790. if( pTab->pIndex ){
  110791. sqlite3MultiWrite(pParse);
  110792. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  110793. }
  110794. }
  110795. seenReplace = 1;
  110796. break;
  110797. }
  110798. #ifndef SQLITE_OMIT_UPSERT
  110799. case OE_Update: {
  110800. sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
  110801. /* Fall through */
  110802. }
  110803. #endif
  110804. case OE_Ignore: {
  110805. testcase( onError==OE_Ignore );
  110806. sqlite3VdbeGoto(v, ignoreDest);
  110807. break;
  110808. }
  110809. }
  110810. sqlite3VdbeResolveLabel(v, addrRowidOk);
  110811. if( ipkTop ){
  110812. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  110813. sqlite3VdbeJumpHere(v, ipkTop-1);
  110814. }
  110815. }
  110816. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  110817. ** index and making sure that duplicate entries do not already exist.
  110818. ** Compute the revised record entries for indices as we go.
  110819. **
  110820. ** This loop also handles the case of the PRIMARY KEY index for a
  110821. ** WITHOUT ROWID table.
  110822. */
  110823. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  110824. int regIdx; /* Range of registers hold conent for pIdx */
  110825. int regR; /* Range of registers holding conflicting PK */
  110826. int iThisCur; /* Cursor for this UNIQUE index */
  110827. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  110828. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  110829. if( pUpIdx==pIdx ){
  110830. addrUniqueOk = upsertJump+1;
  110831. upsertBypass = sqlite3VdbeGoto(v, 0);
  110832. VdbeComment((v, "Skip upsert subroutine"));
  110833. sqlite3VdbeJumpHere(v, upsertJump);
  110834. }else{
  110835. addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
  110836. }
  110837. if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){
  110838. sqlite3TableAffinity(v, pTab, regNewData+1);
  110839. bAffinityDone = 1;
  110840. }
  110841. VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName));
  110842. iThisCur = iIdxCur+ix;
  110843. /* Skip partial indices for which the WHERE clause is not true */
  110844. if( pIdx->pPartIdxWhere ){
  110845. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  110846. pParse->iSelfTab = -(regNewData+1);
  110847. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  110848. SQLITE_JUMPIFNULL);
  110849. pParse->iSelfTab = 0;
  110850. }
  110851. /* Create a record for this index entry as it should appear after
  110852. ** the insert or update. Store that record in the aRegIdx[ix] register
  110853. */
  110854. regIdx = aRegIdx[ix]+1;
  110855. for(i=0; i<pIdx->nColumn; i++){
  110856. int iField = pIdx->aiColumn[i];
  110857. int x;
  110858. if( iField==XN_EXPR ){
  110859. pParse->iSelfTab = -(regNewData+1);
  110860. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  110861. pParse->iSelfTab = 0;
  110862. VdbeComment((v, "%s column %d", pIdx->zName, i));
  110863. }else{
  110864. if( iField==XN_ROWID || iField==pTab->iPKey ){
  110865. x = regNewData;
  110866. }else{
  110867. x = iField + regNewData + 1;
  110868. }
  110869. sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
  110870. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  110871. }
  110872. }
  110873. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  110874. VdbeComment((v, "for %s", pIdx->zName));
  110875. #ifdef SQLITE_ENABLE_NULL_TRIM
  110876. if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
  110877. sqlite3SetMakeRecordP5(v, pIdx->pTable);
  110878. }
  110879. #endif
  110880. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  110881. ** of a WITHOUT ROWID table and there has been no change the
  110882. ** primary key, then no collision is possible. The collision detection
  110883. ** logic below can all be skipped. */
  110884. if( isUpdate && pPk==pIdx && pkChng==0 ){
  110885. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  110886. continue;
  110887. }
  110888. /* Find out what action to take in case there is a uniqueness conflict */
  110889. onError = pIdx->onError;
  110890. if( onError==OE_None ){
  110891. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  110892. continue; /* pIdx is not a UNIQUE index */
  110893. }
  110894. if( overrideError!=OE_Default ){
  110895. onError = overrideError;
  110896. }else if( onError==OE_Default ){
  110897. onError = OE_Abort;
  110898. }
  110899. /* Figure out if the upsert clause applies to this index */
  110900. if( pUpIdx==pIdx ){
  110901. if( pUpsert->pUpsertSet==0 ){
  110902. onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
  110903. }else{
  110904. onError = OE_Update; /* DO UPDATE */
  110905. }
  110906. }
  110907. /* Collision detection may be omitted if all of the following are true:
  110908. ** (1) The conflict resolution algorithm is REPLACE
  110909. ** (2) The table is a WITHOUT ROWID table
  110910. ** (3) There are no secondary indexes on the table
  110911. ** (4) No delete triggers need to be fired if there is a conflict
  110912. ** (5) No FK constraint counters need to be updated if a conflict occurs.
  110913. **
  110914. ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
  110915. ** must be explicitly deleted in order to ensure any pre-update hook
  110916. ** is invoked. */
  110917. #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
  110918. if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
  110919. && pPk==pIdx /* Condition 2 */
  110920. && onError==OE_Replace /* Condition 1 */
  110921. && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
  110922. 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
  110923. && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
  110924. (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
  110925. ){
  110926. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  110927. continue;
  110928. }
  110929. #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
  110930. /* Check to see if the new index entry will be unique */
  110931. sqlite3VdbeVerifyAbortable(v, onError);
  110932. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  110933. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  110934. /* Generate code to handle collisions */
  110935. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  110936. if( isUpdate || onError==OE_Replace ){
  110937. if( HasRowid(pTab) ){
  110938. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  110939. /* Conflict only if the rowid of the existing index entry
  110940. ** is different from old-rowid */
  110941. if( isUpdate ){
  110942. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  110943. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  110944. VdbeCoverage(v);
  110945. }
  110946. }else{
  110947. int x;
  110948. /* Extract the PRIMARY KEY from the end of the index entry and
  110949. ** store it in registers regR..regR+nPk-1 */
  110950. if( pIdx!=pPk ){
  110951. for(i=0; i<pPk->nKeyCol; i++){
  110952. assert( pPk->aiColumn[i]>=0 );
  110953. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  110954. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  110955. VdbeComment((v, "%s.%s", pTab->zName,
  110956. pTab->aCol[pPk->aiColumn[i]].zName));
  110957. }
  110958. }
  110959. if( isUpdate ){
  110960. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  110961. ** table, only conflict if the new PRIMARY KEY values are actually
  110962. ** different from the old.
  110963. **
  110964. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  110965. ** of the matched index row are different from the original PRIMARY
  110966. ** KEY values of this row before the update. */
  110967. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  110968. int op = OP_Ne;
  110969. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  110970. for(i=0; i<pPk->nKeyCol; i++){
  110971. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  110972. x = pPk->aiColumn[i];
  110973. assert( x>=0 );
  110974. if( i==(pPk->nKeyCol-1) ){
  110975. addrJump = addrUniqueOk;
  110976. op = OP_Eq;
  110977. }
  110978. sqlite3VdbeAddOp4(v, op,
  110979. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  110980. );
  110981. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  110982. VdbeCoverageIf(v, op==OP_Eq);
  110983. VdbeCoverageIf(v, op==OP_Ne);
  110984. }
  110985. }
  110986. }
  110987. }
  110988. /* Generate code that executes if the new index entry is not unique */
  110989. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  110990. || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
  110991. switch( onError ){
  110992. case OE_Rollback:
  110993. case OE_Abort:
  110994. case OE_Fail: {
  110995. testcase( onError==OE_Rollback );
  110996. testcase( onError==OE_Abort );
  110997. testcase( onError==OE_Fail );
  110998. sqlite3UniqueConstraint(pParse, onError, pIdx);
  110999. break;
  111000. }
  111001. #ifndef SQLITE_OMIT_UPSERT
  111002. case OE_Update: {
  111003. sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
  111004. /* Fall through */
  111005. }
  111006. #endif
  111007. case OE_Ignore: {
  111008. testcase( onError==OE_Ignore );
  111009. sqlite3VdbeGoto(v, ignoreDest);
  111010. break;
  111011. }
  111012. default: {
  111013. Trigger *pTrigger = 0;
  111014. assert( onError==OE_Replace );
  111015. if( db->flags&SQLITE_RecTriggers ){
  111016. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  111017. }
  111018. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  111019. sqlite3MultiWrite(pParse);
  111020. }
  111021. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  111022. regR, nPkField, 0, OE_Replace,
  111023. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
  111024. seenReplace = 1;
  111025. break;
  111026. }
  111027. }
  111028. if( pUpIdx==pIdx ){
  111029. sqlite3VdbeGoto(v, upsertJump+1);
  111030. sqlite3VdbeJumpHere(v, upsertBypass);
  111031. }else{
  111032. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  111033. }
  111034. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  111035. }
  111036. /* If the IPK constraint is a REPLACE, run it last */
  111037. if( ipkTop ){
  111038. sqlite3VdbeGoto(v, ipkTop);
  111039. VdbeComment((v, "Do IPK REPLACE"));
  111040. sqlite3VdbeJumpHere(v, ipkBottom);
  111041. }
  111042. *pbMayReplace = seenReplace;
  111043. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  111044. }
  111045. #ifdef SQLITE_ENABLE_NULL_TRIM
  111046. /*
  111047. ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
  111048. ** to be the number of columns in table pTab that must not be NULL-trimmed.
  111049. **
  111050. ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
  111051. */
  111052. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
  111053. u16 i;
  111054. /* Records with omitted columns are only allowed for schema format
  111055. ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
  111056. if( pTab->pSchema->file_format<2 ) return;
  111057. for(i=pTab->nCol-1; i>0; i--){
  111058. if( pTab->aCol[i].pDflt!=0 ) break;
  111059. if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
  111060. }
  111061. sqlite3VdbeChangeP5(v, i+1);
  111062. }
  111063. #endif
  111064. /*
  111065. ** This routine generates code to finish the INSERT or UPDATE operation
  111066. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  111067. ** A consecutive range of registers starting at regNewData contains the
  111068. ** rowid and the content to be inserted.
  111069. **
  111070. ** The arguments to this routine should be the same as the first six
  111071. ** arguments to sqlite3GenerateConstraintChecks.
  111072. */
  111073. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  111074. Parse *pParse, /* The parser context */
  111075. Table *pTab, /* the table into which we are inserting */
  111076. int iDataCur, /* Cursor of the canonical data source */
  111077. int iIdxCur, /* First index cursor */
  111078. int regNewData, /* Range of content */
  111079. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  111080. int update_flags, /* True for UPDATE, False for INSERT */
  111081. int appendBias, /* True if this is likely to be an append */
  111082. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  111083. ){
  111084. Vdbe *v; /* Prepared statements under construction */
  111085. Index *pIdx; /* An index being inserted or updated */
  111086. u8 pik_flags; /* flag values passed to the btree insert */
  111087. int regData; /* Content registers (after the rowid) */
  111088. int regRec; /* Register holding assembled record for the table */
  111089. int i; /* Loop counter */
  111090. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  111091. assert( update_flags==0
  111092. || update_flags==OPFLAG_ISUPDATE
  111093. || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
  111094. );
  111095. v = sqlite3GetVdbe(pParse);
  111096. assert( v!=0 );
  111097. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  111098. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  111099. if( aRegIdx[i]==0 ) continue;
  111100. bAffinityDone = 1;
  111101. if( pIdx->pPartIdxWhere ){
  111102. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  111103. VdbeCoverage(v);
  111104. }
  111105. pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
  111106. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  111107. assert( pParse->nested==0 );
  111108. pik_flags |= OPFLAG_NCHANGE;
  111109. pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
  111110. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  111111. if( update_flags==0 ){
  111112. int r = sqlite3GetTempReg(pParse);
  111113. sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
  111114. sqlite3VdbeAddOp4(v, OP_Insert,
  111115. iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE
  111116. );
  111117. sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
  111118. sqlite3ReleaseTempReg(pParse, r);
  111119. }
  111120. #endif
  111121. }
  111122. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
  111123. aRegIdx[i]+1,
  111124. pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
  111125. sqlite3VdbeChangeP5(v, pik_flags);
  111126. }
  111127. if( !HasRowid(pTab) ) return;
  111128. regData = regNewData + 1;
  111129. regRec = sqlite3GetTempReg(pParse);
  111130. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  111131. sqlite3SetMakeRecordP5(v, pTab);
  111132. if( !bAffinityDone ){
  111133. sqlite3TableAffinity(v, pTab, 0);
  111134. }
  111135. if( pParse->nested ){
  111136. pik_flags = 0;
  111137. }else{
  111138. pik_flags = OPFLAG_NCHANGE;
  111139. pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
  111140. }
  111141. if( appendBias ){
  111142. pik_flags |= OPFLAG_APPEND;
  111143. }
  111144. if( useSeekResult ){
  111145. pik_flags |= OPFLAG_USESEEKRESULT;
  111146. }
  111147. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  111148. if( !pParse->nested ){
  111149. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  111150. }
  111151. sqlite3VdbeChangeP5(v, pik_flags);
  111152. }
  111153. /*
  111154. ** Allocate cursors for the pTab table and all its indices and generate
  111155. ** code to open and initialized those cursors.
  111156. **
  111157. ** The cursor for the object that contains the complete data (normally
  111158. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  111159. ** ROWID table) is returned in *piDataCur. The first index cursor is
  111160. ** returned in *piIdxCur. The number of indices is returned.
  111161. **
  111162. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  111163. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  111164. ** If iBase is negative, then allocate the next available cursor.
  111165. **
  111166. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  111167. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  111168. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  111169. ** pTab->pIndex list.
  111170. **
  111171. ** If pTab is a virtual table, then this routine is a no-op and the
  111172. ** *piDataCur and *piIdxCur values are left uninitialized.
  111173. */
  111174. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  111175. Parse *pParse, /* Parsing context */
  111176. Table *pTab, /* Table to be opened */
  111177. int op, /* OP_OpenRead or OP_OpenWrite */
  111178. u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
  111179. int iBase, /* Use this for the table cursor, if there is one */
  111180. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  111181. int *piDataCur, /* Write the database source cursor number here */
  111182. int *piIdxCur /* Write the first index cursor number here */
  111183. ){
  111184. int i;
  111185. int iDb;
  111186. int iDataCur;
  111187. Index *pIdx;
  111188. Vdbe *v;
  111189. assert( op==OP_OpenRead || op==OP_OpenWrite );
  111190. assert( op==OP_OpenWrite || p5==0 );
  111191. if( IsVirtual(pTab) ){
  111192. /* This routine is a no-op for virtual tables. Leave the output
  111193. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  111194. ** can detect if they are used by mistake in the caller. */
  111195. return 0;
  111196. }
  111197. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  111198. v = sqlite3GetVdbe(pParse);
  111199. assert( v!=0 );
  111200. if( iBase<0 ) iBase = pParse->nTab;
  111201. iDataCur = iBase++;
  111202. if( piDataCur ) *piDataCur = iDataCur;
  111203. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  111204. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  111205. }else{
  111206. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  111207. }
  111208. if( piIdxCur ) *piIdxCur = iBase;
  111209. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  111210. int iIdxCur = iBase++;
  111211. assert( pIdx->pSchema==pTab->pSchema );
  111212. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  111213. if( piDataCur ) *piDataCur = iIdxCur;
  111214. p5 = 0;
  111215. }
  111216. if( aToOpen==0 || aToOpen[i+1] ){
  111217. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  111218. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  111219. sqlite3VdbeChangeP5(v, p5);
  111220. VdbeComment((v, "%s", pIdx->zName));
  111221. }
  111222. }
  111223. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  111224. return i;
  111225. }
  111226. #ifdef SQLITE_TEST
  111227. /*
  111228. ** The following global variable is incremented whenever the
  111229. ** transfer optimization is used. This is used for testing
  111230. ** purposes only - to make sure the transfer optimization really
  111231. ** is happening when it is supposed to.
  111232. */
  111233. SQLITE_API int sqlite3_xferopt_count;
  111234. #endif /* SQLITE_TEST */
  111235. #ifndef SQLITE_OMIT_XFER_OPT
  111236. /*
  111237. ** Check to see if index pSrc is compatible as a source of data
  111238. ** for index pDest in an insert transfer optimization. The rules
  111239. ** for a compatible index:
  111240. **
  111241. ** * The index is over the same set of columns
  111242. ** * The same DESC and ASC markings occurs on all columns
  111243. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  111244. ** * The same collating sequence on each column
  111245. ** * The index has the exact same WHERE clause
  111246. */
  111247. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  111248. int i;
  111249. assert( pDest && pSrc );
  111250. assert( pDest->pTable!=pSrc->pTable );
  111251. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  111252. return 0; /* Different number of columns */
  111253. }
  111254. if( pDest->onError!=pSrc->onError ){
  111255. return 0; /* Different conflict resolution strategies */
  111256. }
  111257. for(i=0; i<pSrc->nKeyCol; i++){
  111258. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  111259. return 0; /* Different columns indexed */
  111260. }
  111261. if( pSrc->aiColumn[i]==XN_EXPR ){
  111262. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  111263. if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
  111264. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  111265. return 0; /* Different expressions in the index */
  111266. }
  111267. }
  111268. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  111269. return 0; /* Different sort orders */
  111270. }
  111271. if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
  111272. return 0; /* Different collating sequences */
  111273. }
  111274. }
  111275. if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  111276. return 0; /* Different WHERE clauses */
  111277. }
  111278. /* If no test above fails then the indices must be compatible */
  111279. return 1;
  111280. }
  111281. /*
  111282. ** Attempt the transfer optimization on INSERTs of the form
  111283. **
  111284. ** INSERT INTO tab1 SELECT * FROM tab2;
  111285. **
  111286. ** The xfer optimization transfers raw records from tab2 over to tab1.
  111287. ** Columns are not decoded and reassembled, which greatly improves
  111288. ** performance. Raw index records are transferred in the same way.
  111289. **
  111290. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  111291. ** There are lots of rules for determining compatibility - see comments
  111292. ** embedded in the code for details.
  111293. **
  111294. ** This routine returns TRUE if the optimization is guaranteed to be used.
  111295. ** Sometimes the xfer optimization will only work if the destination table
  111296. ** is empty - a factor that can only be determined at run-time. In that
  111297. ** case, this routine generates code for the xfer optimization but also
  111298. ** does a test to see if the destination table is empty and jumps over the
  111299. ** xfer optimization code if the test fails. In that case, this routine
  111300. ** returns FALSE so that the caller will know to go ahead and generate
  111301. ** an unoptimized transfer. This routine also returns FALSE if there
  111302. ** is no chance that the xfer optimization can be applied.
  111303. **
  111304. ** This optimization is particularly useful at making VACUUM run faster.
  111305. */
  111306. static int xferOptimization(
  111307. Parse *pParse, /* Parser context */
  111308. Table *pDest, /* The table we are inserting into */
  111309. Select *pSelect, /* A SELECT statement to use as the data source */
  111310. int onError, /* How to handle constraint errors */
  111311. int iDbDest /* The database of pDest */
  111312. ){
  111313. sqlite3 *db = pParse->db;
  111314. ExprList *pEList; /* The result set of the SELECT */
  111315. Table *pSrc; /* The table in the FROM clause of SELECT */
  111316. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  111317. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  111318. int i; /* Loop counter */
  111319. int iDbSrc; /* The database of pSrc */
  111320. int iSrc, iDest; /* Cursors from source and destination */
  111321. int addr1, addr2; /* Loop addresses */
  111322. int emptyDestTest = 0; /* Address of test for empty pDest */
  111323. int emptySrcTest = 0; /* Address of test for empty pSrc */
  111324. Vdbe *v; /* The VDBE we are building */
  111325. int regAutoinc; /* Memory register used by AUTOINC */
  111326. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  111327. int regData, regRowid; /* Registers holding data and rowid */
  111328. if( pSelect==0 ){
  111329. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  111330. }
  111331. if( pParse->pWith || pSelect->pWith ){
  111332. /* Do not attempt to process this query if there are an WITH clauses
  111333. ** attached to it. Proceeding may generate a false "no such table: xxx"
  111334. ** error if pSelect reads from a CTE named "xxx". */
  111335. return 0;
  111336. }
  111337. if( sqlite3TriggerList(pParse, pDest) ){
  111338. return 0; /* tab1 must not have triggers */
  111339. }
  111340. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111341. if( IsVirtual(pDest) ){
  111342. return 0; /* tab1 must not be a virtual table */
  111343. }
  111344. #endif
  111345. if( onError==OE_Default ){
  111346. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  111347. if( onError==OE_Default ) onError = OE_Abort;
  111348. }
  111349. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  111350. if( pSelect->pSrc->nSrc!=1 ){
  111351. return 0; /* FROM clause must have exactly one term */
  111352. }
  111353. if( pSelect->pSrc->a[0].pSelect ){
  111354. return 0; /* FROM clause cannot contain a subquery */
  111355. }
  111356. if( pSelect->pWhere ){
  111357. return 0; /* SELECT may not have a WHERE clause */
  111358. }
  111359. if( pSelect->pOrderBy ){
  111360. return 0; /* SELECT may not have an ORDER BY clause */
  111361. }
  111362. /* Do not need to test for a HAVING clause. If HAVING is present but
  111363. ** there is no ORDER BY, we will get an error. */
  111364. if( pSelect->pGroupBy ){
  111365. return 0; /* SELECT may not have a GROUP BY clause */
  111366. }
  111367. if( pSelect->pLimit ){
  111368. return 0; /* SELECT may not have a LIMIT clause */
  111369. }
  111370. if( pSelect->pPrior ){
  111371. return 0; /* SELECT may not be a compound query */
  111372. }
  111373. if( pSelect->selFlags & SF_Distinct ){
  111374. return 0; /* SELECT may not be DISTINCT */
  111375. }
  111376. pEList = pSelect->pEList;
  111377. assert( pEList!=0 );
  111378. if( pEList->nExpr!=1 ){
  111379. return 0; /* The result set must have exactly one column */
  111380. }
  111381. assert( pEList->a[0].pExpr );
  111382. if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
  111383. return 0; /* The result set must be the special operator "*" */
  111384. }
  111385. /* At this point we have established that the statement is of the
  111386. ** correct syntactic form to participate in this optimization. Now
  111387. ** we have to check the semantics.
  111388. */
  111389. pItem = pSelect->pSrc->a;
  111390. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  111391. if( pSrc==0 ){
  111392. return 0; /* FROM clause does not contain a real table */
  111393. }
  111394. if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
  111395. testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */
  111396. return 0; /* tab1 and tab2 may not be the same table */
  111397. }
  111398. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  111399. return 0; /* source and destination must both be WITHOUT ROWID or not */
  111400. }
  111401. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111402. if( IsVirtual(pSrc) ){
  111403. return 0; /* tab2 must not be a virtual table */
  111404. }
  111405. #endif
  111406. if( pSrc->pSelect ){
  111407. return 0; /* tab2 may not be a view */
  111408. }
  111409. if( pDest->nCol!=pSrc->nCol ){
  111410. return 0; /* Number of columns must be the same in tab1 and tab2 */
  111411. }
  111412. if( pDest->iPKey!=pSrc->iPKey ){
  111413. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  111414. }
  111415. for(i=0; i<pDest->nCol; i++){
  111416. Column *pDestCol = &pDest->aCol[i];
  111417. Column *pSrcCol = &pSrc->aCol[i];
  111418. #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
  111419. if( (db->mDbFlags & DBFLAG_Vacuum)==0
  111420. && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
  111421. ){
  111422. return 0; /* Neither table may have __hidden__ columns */
  111423. }
  111424. #endif
  111425. if( pDestCol->affinity!=pSrcCol->affinity ){
  111426. return 0; /* Affinity must be the same on all columns */
  111427. }
  111428. if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
  111429. return 0; /* Collating sequence must be the same on all columns */
  111430. }
  111431. if( pDestCol->notNull && !pSrcCol->notNull ){
  111432. return 0; /* tab2 must be NOT NULL if tab1 is */
  111433. }
  111434. /* Default values for second and subsequent columns need to match. */
  111435. if( i>0 ){
  111436. assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
  111437. assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
  111438. if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
  111439. || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
  111440. pSrcCol->pDflt->u.zToken)!=0)
  111441. ){
  111442. return 0; /* Default values must be the same for all columns */
  111443. }
  111444. }
  111445. }
  111446. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  111447. if( IsUniqueIndex(pDestIdx) ){
  111448. destHasUniqueIdx = 1;
  111449. }
  111450. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  111451. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  111452. }
  111453. if( pSrcIdx==0 ){
  111454. return 0; /* pDestIdx has no corresponding index in pSrc */
  111455. }
  111456. if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
  111457. && sqlite3FaultSim(411)==SQLITE_OK ){
  111458. /* The sqlite3FaultSim() call allows this corruption test to be
  111459. ** bypassed during testing, in order to exercise other corruption tests
  111460. ** further downstream. */
  111461. return 0; /* Corrupt schema - two indexes on the same btree */
  111462. }
  111463. }
  111464. #ifndef SQLITE_OMIT_CHECK
  111465. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  111466. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  111467. }
  111468. #endif
  111469. #ifndef SQLITE_OMIT_FOREIGN_KEY
  111470. /* Disallow the transfer optimization if the destination table constains
  111471. ** any foreign key constraints. This is more restrictive than necessary.
  111472. ** But the main beneficiary of the transfer optimization is the VACUUM
  111473. ** command, and the VACUUM command disables foreign key constraints. So
  111474. ** the extra complication to make this rule less restrictive is probably
  111475. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  111476. */
  111477. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  111478. return 0;
  111479. }
  111480. #endif
  111481. if( (db->flags & SQLITE_CountRows)!=0 ){
  111482. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  111483. }
  111484. /* If we get this far, it means that the xfer optimization is at
  111485. ** least a possibility, though it might only work if the destination
  111486. ** table (tab1) is initially empty.
  111487. */
  111488. #ifdef SQLITE_TEST
  111489. sqlite3_xferopt_count++;
  111490. #endif
  111491. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  111492. v = sqlite3GetVdbe(pParse);
  111493. sqlite3CodeVerifySchema(pParse, iDbSrc);
  111494. iSrc = pParse->nTab++;
  111495. iDest = pParse->nTab++;
  111496. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  111497. regData = sqlite3GetTempReg(pParse);
  111498. regRowid = sqlite3GetTempReg(pParse);
  111499. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  111500. assert( HasRowid(pDest) || destHasUniqueIdx );
  111501. if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
  111502. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  111503. || destHasUniqueIdx /* (2) */
  111504. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  111505. )){
  111506. /* In some circumstances, we are able to run the xfer optimization
  111507. ** only if the destination table is initially empty. Unless the
  111508. ** DBFLAG_Vacuum flag is set, this block generates code to make
  111509. ** that determination. If DBFLAG_Vacuum is set, then the destination
  111510. ** table is always empty.
  111511. **
  111512. ** Conditions under which the destination must be empty:
  111513. **
  111514. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  111515. ** (If the destination is not initially empty, the rowid fields
  111516. ** of index entries might need to change.)
  111517. **
  111518. ** (2) The destination has a unique index. (The xfer optimization
  111519. ** is unable to test uniqueness.)
  111520. **
  111521. ** (3) onError is something other than OE_Abort and OE_Rollback.
  111522. */
  111523. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  111524. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  111525. sqlite3VdbeJumpHere(v, addr1);
  111526. }
  111527. if( HasRowid(pSrc) ){
  111528. u8 insFlags;
  111529. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  111530. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  111531. if( pDest->iPKey>=0 ){
  111532. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  111533. sqlite3VdbeVerifyAbortable(v, onError);
  111534. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  111535. VdbeCoverage(v);
  111536. sqlite3RowidConstraint(pParse, onError, pDest);
  111537. sqlite3VdbeJumpHere(v, addr2);
  111538. autoIncStep(pParse, regAutoinc, regRowid);
  111539. }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
  111540. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  111541. }else{
  111542. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  111543. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  111544. }
  111545. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  111546. if( db->mDbFlags & DBFLAG_Vacuum ){
  111547. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  111548. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
  111549. OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
  111550. }else{
  111551. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
  111552. }
  111553. sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
  111554. (char*)pDest, P4_TABLE);
  111555. sqlite3VdbeChangeP5(v, insFlags);
  111556. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  111557. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  111558. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  111559. }else{
  111560. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  111561. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  111562. }
  111563. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  111564. u8 idxInsFlags = 0;
  111565. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  111566. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  111567. }
  111568. assert( pSrcIdx );
  111569. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  111570. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  111571. VdbeComment((v, "%s", pSrcIdx->zName));
  111572. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  111573. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  111574. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  111575. VdbeComment((v, "%s", pDestIdx->zName));
  111576. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  111577. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  111578. if( db->mDbFlags & DBFLAG_Vacuum ){
  111579. /* This INSERT command is part of a VACUUM operation, which guarantees
  111580. ** that the destination table is empty. If all indexed columns use
  111581. ** collation sequence BINARY, then it can also be assumed that the
  111582. ** index will be populated by inserting keys in strictly sorted
  111583. ** order. In this case, instead of seeking within the b-tree as part
  111584. ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
  111585. ** OP_IdxInsert to seek to the point within the b-tree where each key
  111586. ** should be inserted. This is faster.
  111587. **
  111588. ** If any of the indexed columns use a collation sequence other than
  111589. ** BINARY, this optimization is disabled. This is because the user
  111590. ** might change the definition of a collation sequence and then run
  111591. ** a VACUUM command. In that case keys may not be written in strictly
  111592. ** sorted order. */
  111593. for(i=0; i<pSrcIdx->nColumn; i++){
  111594. const char *zColl = pSrcIdx->azColl[i];
  111595. if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
  111596. }
  111597. if( i==pSrcIdx->nColumn ){
  111598. idxInsFlags = OPFLAG_USESEEKRESULT;
  111599. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  111600. }
  111601. }
  111602. if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
  111603. idxInsFlags |= OPFLAG_NCHANGE;
  111604. }
  111605. sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
  111606. sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
  111607. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  111608. sqlite3VdbeJumpHere(v, addr1);
  111609. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  111610. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  111611. }
  111612. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  111613. sqlite3ReleaseTempReg(pParse, regRowid);
  111614. sqlite3ReleaseTempReg(pParse, regData);
  111615. if( emptyDestTest ){
  111616. sqlite3AutoincrementEnd(pParse);
  111617. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  111618. sqlite3VdbeJumpHere(v, emptyDestTest);
  111619. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  111620. return 0;
  111621. }else{
  111622. return 1;
  111623. }
  111624. }
  111625. #endif /* SQLITE_OMIT_XFER_OPT */
  111626. /************** End of insert.c **********************************************/
  111627. /************** Begin file legacy.c ******************************************/
  111628. /*
  111629. ** 2001 September 15
  111630. **
  111631. ** The author disclaims copyright to this source code. In place of
  111632. ** a legal notice, here is a blessing:
  111633. **
  111634. ** May you do good and not evil.
  111635. ** May you find forgiveness for yourself and forgive others.
  111636. ** May you share freely, never taking more than you give.
  111637. **
  111638. *************************************************************************
  111639. ** Main file for the SQLite library. The routines in this file
  111640. ** implement the programmer interface to the library. Routines in
  111641. ** other files are for internal use by SQLite and should not be
  111642. ** accessed by users of the library.
  111643. */
  111644. /* #include "sqliteInt.h" */
  111645. /*
  111646. ** Execute SQL code. Return one of the SQLITE_ success/failure
  111647. ** codes. Also write an error message into memory obtained from
  111648. ** malloc() and make *pzErrMsg point to that message.
  111649. **
  111650. ** If the SQL is a query, then for each row in the query result
  111651. ** the xCallback() function is called. pArg becomes the first
  111652. ** argument to xCallback(). If xCallback=NULL then no callback
  111653. ** is invoked, even for queries.
  111654. */
  111655. SQLITE_API int sqlite3_exec(
  111656. sqlite3 *db, /* The database on which the SQL executes */
  111657. const char *zSql, /* The SQL to be executed */
  111658. sqlite3_callback xCallback, /* Invoke this callback routine */
  111659. void *pArg, /* First argument to xCallback() */
  111660. char **pzErrMsg /* Write error messages here */
  111661. ){
  111662. int rc = SQLITE_OK; /* Return code */
  111663. const char *zLeftover; /* Tail of unprocessed SQL */
  111664. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  111665. char **azCols = 0; /* Names of result columns */
  111666. int callbackIsInit; /* True if callback data is initialized */
  111667. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  111668. if( zSql==0 ) zSql = "";
  111669. sqlite3_mutex_enter(db->mutex);
  111670. sqlite3Error(db, SQLITE_OK);
  111671. while( rc==SQLITE_OK && zSql[0] ){
  111672. int nCol = 0;
  111673. char **azVals = 0;
  111674. pStmt = 0;
  111675. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  111676. assert( rc==SQLITE_OK || pStmt==0 );
  111677. if( rc!=SQLITE_OK ){
  111678. continue;
  111679. }
  111680. if( !pStmt ){
  111681. /* this happens for a comment or white-space */
  111682. zSql = zLeftover;
  111683. continue;
  111684. }
  111685. callbackIsInit = 0;
  111686. while( 1 ){
  111687. int i;
  111688. rc = sqlite3_step(pStmt);
  111689. /* Invoke the callback function if required */
  111690. if( xCallback && (SQLITE_ROW==rc ||
  111691. (SQLITE_DONE==rc && !callbackIsInit
  111692. && db->flags&SQLITE_NullCallback)) ){
  111693. if( !callbackIsInit ){
  111694. nCol = sqlite3_column_count(pStmt);
  111695. azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
  111696. if( azCols==0 ){
  111697. goto exec_out;
  111698. }
  111699. for(i=0; i<nCol; i++){
  111700. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  111701. /* sqlite3VdbeSetColName() installs column names as UTF8
  111702. ** strings so there is no way for sqlite3_column_name() to fail. */
  111703. assert( azCols[i]!=0 );
  111704. }
  111705. callbackIsInit = 1;
  111706. }
  111707. if( rc==SQLITE_ROW ){
  111708. azVals = &azCols[nCol];
  111709. for(i=0; i<nCol; i++){
  111710. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  111711. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  111712. sqlite3OomFault(db);
  111713. goto exec_out;
  111714. }
  111715. }
  111716. azVals[i] = 0;
  111717. }
  111718. if( xCallback(pArg, nCol, azVals, azCols) ){
  111719. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  111720. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  111721. ** return SQLITE_ABORT. */
  111722. rc = SQLITE_ABORT;
  111723. sqlite3VdbeFinalize((Vdbe *)pStmt);
  111724. pStmt = 0;
  111725. sqlite3Error(db, SQLITE_ABORT);
  111726. goto exec_out;
  111727. }
  111728. }
  111729. if( rc!=SQLITE_ROW ){
  111730. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  111731. pStmt = 0;
  111732. zSql = zLeftover;
  111733. while( sqlite3Isspace(zSql[0]) ) zSql++;
  111734. break;
  111735. }
  111736. }
  111737. sqlite3DbFree(db, azCols);
  111738. azCols = 0;
  111739. }
  111740. exec_out:
  111741. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  111742. sqlite3DbFree(db, azCols);
  111743. rc = sqlite3ApiExit(db, rc);
  111744. if( rc!=SQLITE_OK && pzErrMsg ){
  111745. *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
  111746. if( *pzErrMsg==0 ){
  111747. rc = SQLITE_NOMEM_BKPT;
  111748. sqlite3Error(db, SQLITE_NOMEM);
  111749. }
  111750. }else if( pzErrMsg ){
  111751. *pzErrMsg = 0;
  111752. }
  111753. assert( (rc&db->errMask)==rc );
  111754. sqlite3_mutex_leave(db->mutex);
  111755. return rc;
  111756. }
  111757. /************** End of legacy.c **********************************************/
  111758. /************** Begin file loadext.c *****************************************/
  111759. /*
  111760. ** 2006 June 7
  111761. **
  111762. ** The author disclaims copyright to this source code. In place of
  111763. ** a legal notice, here is a blessing:
  111764. **
  111765. ** May you do good and not evil.
  111766. ** May you find forgiveness for yourself and forgive others.
  111767. ** May you share freely, never taking more than you give.
  111768. **
  111769. *************************************************************************
  111770. ** This file contains code used to dynamically load extensions into
  111771. ** the SQLite library.
  111772. */
  111773. #ifndef SQLITE_CORE
  111774. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  111775. #endif
  111776. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  111777. /************** Begin file sqlite3ext.h **************************************/
  111778. /*
  111779. ** 2006 June 7
  111780. **
  111781. ** The author disclaims copyright to this source code. In place of
  111782. ** a legal notice, here is a blessing:
  111783. **
  111784. ** May you do good and not evil.
  111785. ** May you find forgiveness for yourself and forgive others.
  111786. ** May you share freely, never taking more than you give.
  111787. **
  111788. *************************************************************************
  111789. ** This header file defines the SQLite interface for use by
  111790. ** shared libraries that want to be imported as extensions into
  111791. ** an SQLite instance. Shared libraries that intend to be loaded
  111792. ** as extensions by SQLite should #include this file instead of
  111793. ** sqlite3.h.
  111794. */
  111795. #ifndef SQLITE3EXT_H
  111796. #define SQLITE3EXT_H
  111797. /* #include "sqlite3.h" */
  111798. /*
  111799. ** The following structure holds pointers to all of the SQLite API
  111800. ** routines.
  111801. **
  111802. ** WARNING: In order to maintain backwards compatibility, add new
  111803. ** interfaces to the end of this structure only. If you insert new
  111804. ** interfaces in the middle of this structure, then older different
  111805. ** versions of SQLite will not be able to load each other's shared
  111806. ** libraries!
  111807. */
  111808. struct sqlite3_api_routines {
  111809. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  111810. int (*aggregate_count)(sqlite3_context*);
  111811. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  111812. int (*bind_double)(sqlite3_stmt*,int,double);
  111813. int (*bind_int)(sqlite3_stmt*,int,int);
  111814. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  111815. int (*bind_null)(sqlite3_stmt*,int);
  111816. int (*bind_parameter_count)(sqlite3_stmt*);
  111817. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  111818. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  111819. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  111820. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  111821. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  111822. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  111823. int (*busy_timeout)(sqlite3*,int ms);
  111824. int (*changes)(sqlite3*);
  111825. int (*close)(sqlite3*);
  111826. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  111827. int eTextRep,const char*));
  111828. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  111829. int eTextRep,const void*));
  111830. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  111831. int (*column_bytes)(sqlite3_stmt*,int iCol);
  111832. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  111833. int (*column_count)(sqlite3_stmt*pStmt);
  111834. const char * (*column_database_name)(sqlite3_stmt*,int);
  111835. const void * (*column_database_name16)(sqlite3_stmt*,int);
  111836. const char * (*column_decltype)(sqlite3_stmt*,int i);
  111837. const void * (*column_decltype16)(sqlite3_stmt*,int);
  111838. double (*column_double)(sqlite3_stmt*,int iCol);
  111839. int (*column_int)(sqlite3_stmt*,int iCol);
  111840. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  111841. const char * (*column_name)(sqlite3_stmt*,int);
  111842. const void * (*column_name16)(sqlite3_stmt*,int);
  111843. const char * (*column_origin_name)(sqlite3_stmt*,int);
  111844. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  111845. const char * (*column_table_name)(sqlite3_stmt*,int);
  111846. const void * (*column_table_name16)(sqlite3_stmt*,int);
  111847. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  111848. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  111849. int (*column_type)(sqlite3_stmt*,int iCol);
  111850. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  111851. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  111852. int (*complete)(const char*sql);
  111853. int (*complete16)(const void*sql);
  111854. int (*create_collation)(sqlite3*,const char*,int,void*,
  111855. int(*)(void*,int,const void*,int,const void*));
  111856. int (*create_collation16)(sqlite3*,const void*,int,void*,
  111857. int(*)(void*,int,const void*,int,const void*));
  111858. int (*create_function)(sqlite3*,const char*,int,int,void*,
  111859. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  111860. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  111861. void (*xFinal)(sqlite3_context*));
  111862. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  111863. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  111864. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  111865. void (*xFinal)(sqlite3_context*));
  111866. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  111867. int (*data_count)(sqlite3_stmt*pStmt);
  111868. sqlite3 * (*db_handle)(sqlite3_stmt*);
  111869. int (*declare_vtab)(sqlite3*,const char*);
  111870. int (*enable_shared_cache)(int);
  111871. int (*errcode)(sqlite3*db);
  111872. const char * (*errmsg)(sqlite3*);
  111873. const void * (*errmsg16)(sqlite3*);
  111874. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  111875. int (*expired)(sqlite3_stmt*);
  111876. int (*finalize)(sqlite3_stmt*pStmt);
  111877. void (*free)(void*);
  111878. void (*free_table)(char**result);
  111879. int (*get_autocommit)(sqlite3*);
  111880. void * (*get_auxdata)(sqlite3_context*,int);
  111881. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  111882. int (*global_recover)(void);
  111883. void (*interruptx)(sqlite3*);
  111884. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  111885. const char * (*libversion)(void);
  111886. int (*libversion_number)(void);
  111887. void *(*malloc)(int);
  111888. char * (*mprintf)(const char*,...);
  111889. int (*open)(const char*,sqlite3**);
  111890. int (*open16)(const void*,sqlite3**);
  111891. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  111892. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  111893. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  111894. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  111895. void *(*realloc)(void*,int);
  111896. int (*reset)(sqlite3_stmt*pStmt);
  111897. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  111898. void (*result_double)(sqlite3_context*,double);
  111899. void (*result_error)(sqlite3_context*,const char*,int);
  111900. void (*result_error16)(sqlite3_context*,const void*,int);
  111901. void (*result_int)(sqlite3_context*,int);
  111902. void (*result_int64)(sqlite3_context*,sqlite_int64);
  111903. void (*result_null)(sqlite3_context*);
  111904. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  111905. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  111906. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  111907. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  111908. void (*result_value)(sqlite3_context*,sqlite3_value*);
  111909. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  111910. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  111911. const char*,const char*),void*);
  111912. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  111913. char * (*xsnprintf)(int,char*,const char*,...);
  111914. int (*step)(sqlite3_stmt*);
  111915. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  111916. char const**,char const**,int*,int*,int*);
  111917. void (*thread_cleanup)(void);
  111918. int (*total_changes)(sqlite3*);
  111919. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  111920. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  111921. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  111922. sqlite_int64),void*);
  111923. void * (*user_data)(sqlite3_context*);
  111924. const void * (*value_blob)(sqlite3_value*);
  111925. int (*value_bytes)(sqlite3_value*);
  111926. int (*value_bytes16)(sqlite3_value*);
  111927. double (*value_double)(sqlite3_value*);
  111928. int (*value_int)(sqlite3_value*);
  111929. sqlite_int64 (*value_int64)(sqlite3_value*);
  111930. int (*value_numeric_type)(sqlite3_value*);
  111931. const unsigned char * (*value_text)(sqlite3_value*);
  111932. const void * (*value_text16)(sqlite3_value*);
  111933. const void * (*value_text16be)(sqlite3_value*);
  111934. const void * (*value_text16le)(sqlite3_value*);
  111935. int (*value_type)(sqlite3_value*);
  111936. char *(*vmprintf)(const char*,va_list);
  111937. /* Added ??? */
  111938. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  111939. /* Added by 3.3.13 */
  111940. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  111941. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  111942. int (*clear_bindings)(sqlite3_stmt*);
  111943. /* Added by 3.4.1 */
  111944. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  111945. void (*xDestroy)(void *));
  111946. /* Added by 3.5.0 */
  111947. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  111948. int (*blob_bytes)(sqlite3_blob*);
  111949. int (*blob_close)(sqlite3_blob*);
  111950. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  111951. int,sqlite3_blob**);
  111952. int (*blob_read)(sqlite3_blob*,void*,int,int);
  111953. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  111954. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  111955. int(*)(void*,int,const void*,int,const void*),
  111956. void(*)(void*));
  111957. int (*file_control)(sqlite3*,const char*,int,void*);
  111958. sqlite3_int64 (*memory_highwater)(int);
  111959. sqlite3_int64 (*memory_used)(void);
  111960. sqlite3_mutex *(*mutex_alloc)(int);
  111961. void (*mutex_enter)(sqlite3_mutex*);
  111962. void (*mutex_free)(sqlite3_mutex*);
  111963. void (*mutex_leave)(sqlite3_mutex*);
  111964. int (*mutex_try)(sqlite3_mutex*);
  111965. int (*open_v2)(const char*,sqlite3**,int,const char*);
  111966. int (*release_memory)(int);
  111967. void (*result_error_nomem)(sqlite3_context*);
  111968. void (*result_error_toobig)(sqlite3_context*);
  111969. int (*sleep)(int);
  111970. void (*soft_heap_limit)(int);
  111971. sqlite3_vfs *(*vfs_find)(const char*);
  111972. int (*vfs_register)(sqlite3_vfs*,int);
  111973. int (*vfs_unregister)(sqlite3_vfs*);
  111974. int (*xthreadsafe)(void);
  111975. void (*result_zeroblob)(sqlite3_context*,int);
  111976. void (*result_error_code)(sqlite3_context*,int);
  111977. int (*test_control)(int, ...);
  111978. void (*randomness)(int,void*);
  111979. sqlite3 *(*context_db_handle)(sqlite3_context*);
  111980. int (*extended_result_codes)(sqlite3*,int);
  111981. int (*limit)(sqlite3*,int,int);
  111982. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  111983. const char *(*sql)(sqlite3_stmt*);
  111984. int (*status)(int,int*,int*,int);
  111985. int (*backup_finish)(sqlite3_backup*);
  111986. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  111987. int (*backup_pagecount)(sqlite3_backup*);
  111988. int (*backup_remaining)(sqlite3_backup*);
  111989. int (*backup_step)(sqlite3_backup*,int);
  111990. const char *(*compileoption_get)(int);
  111991. int (*compileoption_used)(const char*);
  111992. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  111993. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  111994. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  111995. void (*xFinal)(sqlite3_context*),
  111996. void(*xDestroy)(void*));
  111997. int (*db_config)(sqlite3*,int,...);
  111998. sqlite3_mutex *(*db_mutex)(sqlite3*);
  111999. int (*db_status)(sqlite3*,int,int*,int*,int);
  112000. int (*extended_errcode)(sqlite3*);
  112001. void (*log)(int,const char*,...);
  112002. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  112003. const char *(*sourceid)(void);
  112004. int (*stmt_status)(sqlite3_stmt*,int,int);
  112005. int (*strnicmp)(const char*,const char*,int);
  112006. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  112007. int (*wal_autocheckpoint)(sqlite3*,int);
  112008. int (*wal_checkpoint)(sqlite3*,const char*);
  112009. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  112010. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  112011. int (*vtab_config)(sqlite3*,int op,...);
  112012. int (*vtab_on_conflict)(sqlite3*);
  112013. /* Version 3.7.16 and later */
  112014. int (*close_v2)(sqlite3*);
  112015. const char *(*db_filename)(sqlite3*,const char*);
  112016. int (*db_readonly)(sqlite3*,const char*);
  112017. int (*db_release_memory)(sqlite3*);
  112018. const char *(*errstr)(int);
  112019. int (*stmt_busy)(sqlite3_stmt*);
  112020. int (*stmt_readonly)(sqlite3_stmt*);
  112021. int (*stricmp)(const char*,const char*);
  112022. int (*uri_boolean)(const char*,const char*,int);
  112023. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  112024. const char *(*uri_parameter)(const char*,const char*);
  112025. char *(*xvsnprintf)(int,char*,const char*,va_list);
  112026. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  112027. /* Version 3.8.7 and later */
  112028. int (*auto_extension)(void(*)(void));
  112029. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  112030. void(*)(void*));
  112031. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  112032. void(*)(void*),unsigned char);
  112033. int (*cancel_auto_extension)(void(*)(void));
  112034. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  112035. void *(*malloc64)(sqlite3_uint64);
  112036. sqlite3_uint64 (*msize)(void*);
  112037. void *(*realloc64)(void*,sqlite3_uint64);
  112038. void (*reset_auto_extension)(void);
  112039. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  112040. void(*)(void*));
  112041. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  112042. void(*)(void*), unsigned char);
  112043. int (*strglob)(const char*,const char*);
  112044. /* Version 3.8.11 and later */
  112045. sqlite3_value *(*value_dup)(const sqlite3_value*);
  112046. void (*value_free)(sqlite3_value*);
  112047. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  112048. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  112049. /* Version 3.9.0 and later */
  112050. unsigned int (*value_subtype)(sqlite3_value*);
  112051. void (*result_subtype)(sqlite3_context*,unsigned int);
  112052. /* Version 3.10.0 and later */
  112053. int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  112054. int (*strlike)(const char*,const char*,unsigned int);
  112055. int (*db_cacheflush)(sqlite3*);
  112056. /* Version 3.12.0 and later */
  112057. int (*system_errno)(sqlite3*);
  112058. /* Version 3.14.0 and later */
  112059. int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
  112060. char *(*expanded_sql)(sqlite3_stmt*);
  112061. /* Version 3.18.0 and later */
  112062. void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
  112063. /* Version 3.20.0 and later */
  112064. int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
  112065. sqlite3_stmt**,const char**);
  112066. int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
  112067. sqlite3_stmt**,const void**);
  112068. int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
  112069. void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
  112070. void *(*value_pointer)(sqlite3_value*,const char*);
  112071. int (*vtab_nochange)(sqlite3_context*);
  112072. int (*value_nochange)(sqlite3_value*);
  112073. const char *(*vtab_collation)(sqlite3_index_info*,int);
  112074. /* Version 3.24.0 and later */
  112075. int (*keyword_count)(void);
  112076. int (*keyword_name)(int,const char**,int*);
  112077. int (*keyword_check)(const char*,int);
  112078. sqlite3_str *(*str_new)(sqlite3*);
  112079. char *(*str_finish)(sqlite3_str*);
  112080. void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
  112081. void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
  112082. void (*str_append)(sqlite3_str*, const char *zIn, int N);
  112083. void (*str_appendall)(sqlite3_str*, const char *zIn);
  112084. void (*str_appendchar)(sqlite3_str*, int N, char C);
  112085. void (*str_reset)(sqlite3_str*);
  112086. int (*str_errcode)(sqlite3_str*);
  112087. int (*str_length)(sqlite3_str*);
  112088. char *(*str_value)(sqlite3_str*);
  112089. /* Version 3.25.0 and later */
  112090. int (*create_window_function)(sqlite3*,const char*,int,int,void*,
  112091. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  112092. void (*xFinal)(sqlite3_context*),
  112093. void (*xValue)(sqlite3_context*),
  112094. void (*xInv)(sqlite3_context*,int,sqlite3_value**),
  112095. void(*xDestroy)(void*));
  112096. /* Version 3.26.0 and later */
  112097. const char *(*normalized_sql)(sqlite3_stmt*);
  112098. /* Version 3.28.0 and later */
  112099. int (*stmt_isexplain)(sqlite3_stmt*);
  112100. int (*value_frombind)(sqlite3_value*);
  112101. };
  112102. /*
  112103. ** This is the function signature used for all extension entry points. It
  112104. ** is also defined in the file "loadext.c".
  112105. */
  112106. typedef int (*sqlite3_loadext_entry)(
  112107. sqlite3 *db, /* Handle to the database. */
  112108. char **pzErrMsg, /* Used to set error string on failure. */
  112109. const sqlite3_api_routines *pThunk /* Extension API function pointers. */
  112110. );
  112111. /*
  112112. ** The following macros redefine the API routines so that they are
  112113. ** redirected through the global sqlite3_api structure.
  112114. **
  112115. ** This header file is also used by the loadext.c source file
  112116. ** (part of the main SQLite library - not an extension) so that
  112117. ** it can get access to the sqlite3_api_routines structure
  112118. ** definition. But the main library does not want to redefine
  112119. ** the API. So the redefinition macros are only valid if the
  112120. ** SQLITE_CORE macros is undefined.
  112121. */
  112122. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  112123. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  112124. #ifndef SQLITE_OMIT_DEPRECATED
  112125. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  112126. #endif
  112127. #define sqlite3_bind_blob sqlite3_api->bind_blob
  112128. #define sqlite3_bind_double sqlite3_api->bind_double
  112129. #define sqlite3_bind_int sqlite3_api->bind_int
  112130. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  112131. #define sqlite3_bind_null sqlite3_api->bind_null
  112132. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  112133. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  112134. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  112135. #define sqlite3_bind_text sqlite3_api->bind_text
  112136. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  112137. #define sqlite3_bind_value sqlite3_api->bind_value
  112138. #define sqlite3_busy_handler sqlite3_api->busy_handler
  112139. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  112140. #define sqlite3_changes sqlite3_api->changes
  112141. #define sqlite3_close sqlite3_api->close
  112142. #define sqlite3_collation_needed sqlite3_api->collation_needed
  112143. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  112144. #define sqlite3_column_blob sqlite3_api->column_blob
  112145. #define sqlite3_column_bytes sqlite3_api->column_bytes
  112146. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  112147. #define sqlite3_column_count sqlite3_api->column_count
  112148. #define sqlite3_column_database_name sqlite3_api->column_database_name
  112149. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  112150. #define sqlite3_column_decltype sqlite3_api->column_decltype
  112151. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  112152. #define sqlite3_column_double sqlite3_api->column_double
  112153. #define sqlite3_column_int sqlite3_api->column_int
  112154. #define sqlite3_column_int64 sqlite3_api->column_int64
  112155. #define sqlite3_column_name sqlite3_api->column_name
  112156. #define sqlite3_column_name16 sqlite3_api->column_name16
  112157. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  112158. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  112159. #define sqlite3_column_table_name sqlite3_api->column_table_name
  112160. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  112161. #define sqlite3_column_text sqlite3_api->column_text
  112162. #define sqlite3_column_text16 sqlite3_api->column_text16
  112163. #define sqlite3_column_type sqlite3_api->column_type
  112164. #define sqlite3_column_value sqlite3_api->column_value
  112165. #define sqlite3_commit_hook sqlite3_api->commit_hook
  112166. #define sqlite3_complete sqlite3_api->complete
  112167. #define sqlite3_complete16 sqlite3_api->complete16
  112168. #define sqlite3_create_collation sqlite3_api->create_collation
  112169. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  112170. #define sqlite3_create_function sqlite3_api->create_function
  112171. #define sqlite3_create_function16 sqlite3_api->create_function16
  112172. #define sqlite3_create_module sqlite3_api->create_module
  112173. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  112174. #define sqlite3_data_count sqlite3_api->data_count
  112175. #define sqlite3_db_handle sqlite3_api->db_handle
  112176. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  112177. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  112178. #define sqlite3_errcode sqlite3_api->errcode
  112179. #define sqlite3_errmsg sqlite3_api->errmsg
  112180. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  112181. #define sqlite3_exec sqlite3_api->exec
  112182. #ifndef SQLITE_OMIT_DEPRECATED
  112183. #define sqlite3_expired sqlite3_api->expired
  112184. #endif
  112185. #define sqlite3_finalize sqlite3_api->finalize
  112186. #define sqlite3_free sqlite3_api->free
  112187. #define sqlite3_free_table sqlite3_api->free_table
  112188. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  112189. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  112190. #define sqlite3_get_table sqlite3_api->get_table
  112191. #ifndef SQLITE_OMIT_DEPRECATED
  112192. #define sqlite3_global_recover sqlite3_api->global_recover
  112193. #endif
  112194. #define sqlite3_interrupt sqlite3_api->interruptx
  112195. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  112196. #define sqlite3_libversion sqlite3_api->libversion
  112197. #define sqlite3_libversion_number sqlite3_api->libversion_number
  112198. #define sqlite3_malloc sqlite3_api->malloc
  112199. #define sqlite3_mprintf sqlite3_api->mprintf
  112200. #define sqlite3_open sqlite3_api->open
  112201. #define sqlite3_open16 sqlite3_api->open16
  112202. #define sqlite3_prepare sqlite3_api->prepare
  112203. #define sqlite3_prepare16 sqlite3_api->prepare16
  112204. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  112205. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  112206. #define sqlite3_profile sqlite3_api->profile
  112207. #define sqlite3_progress_handler sqlite3_api->progress_handler
  112208. #define sqlite3_realloc sqlite3_api->realloc
  112209. #define sqlite3_reset sqlite3_api->reset
  112210. #define sqlite3_result_blob sqlite3_api->result_blob
  112211. #define sqlite3_result_double sqlite3_api->result_double
  112212. #define sqlite3_result_error sqlite3_api->result_error
  112213. #define sqlite3_result_error16 sqlite3_api->result_error16
  112214. #define sqlite3_result_int sqlite3_api->result_int
  112215. #define sqlite3_result_int64 sqlite3_api->result_int64
  112216. #define sqlite3_result_null sqlite3_api->result_null
  112217. #define sqlite3_result_text sqlite3_api->result_text
  112218. #define sqlite3_result_text16 sqlite3_api->result_text16
  112219. #define sqlite3_result_text16be sqlite3_api->result_text16be
  112220. #define sqlite3_result_text16le sqlite3_api->result_text16le
  112221. #define sqlite3_result_value sqlite3_api->result_value
  112222. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  112223. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  112224. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  112225. #define sqlite3_snprintf sqlite3_api->xsnprintf
  112226. #define sqlite3_step sqlite3_api->step
  112227. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  112228. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  112229. #define sqlite3_total_changes sqlite3_api->total_changes
  112230. #define sqlite3_trace sqlite3_api->trace
  112231. #ifndef SQLITE_OMIT_DEPRECATED
  112232. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  112233. #endif
  112234. #define sqlite3_update_hook sqlite3_api->update_hook
  112235. #define sqlite3_user_data sqlite3_api->user_data
  112236. #define sqlite3_value_blob sqlite3_api->value_blob
  112237. #define sqlite3_value_bytes sqlite3_api->value_bytes
  112238. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  112239. #define sqlite3_value_double sqlite3_api->value_double
  112240. #define sqlite3_value_int sqlite3_api->value_int
  112241. #define sqlite3_value_int64 sqlite3_api->value_int64
  112242. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  112243. #define sqlite3_value_text sqlite3_api->value_text
  112244. #define sqlite3_value_text16 sqlite3_api->value_text16
  112245. #define sqlite3_value_text16be sqlite3_api->value_text16be
  112246. #define sqlite3_value_text16le sqlite3_api->value_text16le
  112247. #define sqlite3_value_type sqlite3_api->value_type
  112248. #define sqlite3_vmprintf sqlite3_api->vmprintf
  112249. #define sqlite3_vsnprintf sqlite3_api->xvsnprintf
  112250. #define sqlite3_overload_function sqlite3_api->overload_function
  112251. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  112252. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  112253. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  112254. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  112255. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  112256. #define sqlite3_blob_close sqlite3_api->blob_close
  112257. #define sqlite3_blob_open sqlite3_api->blob_open
  112258. #define sqlite3_blob_read sqlite3_api->blob_read
  112259. #define sqlite3_blob_write sqlite3_api->blob_write
  112260. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  112261. #define sqlite3_file_control sqlite3_api->file_control
  112262. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  112263. #define sqlite3_memory_used sqlite3_api->memory_used
  112264. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  112265. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  112266. #define sqlite3_mutex_free sqlite3_api->mutex_free
  112267. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  112268. #define sqlite3_mutex_try sqlite3_api->mutex_try
  112269. #define sqlite3_open_v2 sqlite3_api->open_v2
  112270. #define sqlite3_release_memory sqlite3_api->release_memory
  112271. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  112272. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  112273. #define sqlite3_sleep sqlite3_api->sleep
  112274. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  112275. #define sqlite3_vfs_find sqlite3_api->vfs_find
  112276. #define sqlite3_vfs_register sqlite3_api->vfs_register
  112277. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  112278. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  112279. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  112280. #define sqlite3_result_error_code sqlite3_api->result_error_code
  112281. #define sqlite3_test_control sqlite3_api->test_control
  112282. #define sqlite3_randomness sqlite3_api->randomness
  112283. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  112284. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  112285. #define sqlite3_limit sqlite3_api->limit
  112286. #define sqlite3_next_stmt sqlite3_api->next_stmt
  112287. #define sqlite3_sql sqlite3_api->sql
  112288. #define sqlite3_status sqlite3_api->status
  112289. #define sqlite3_backup_finish sqlite3_api->backup_finish
  112290. #define sqlite3_backup_init sqlite3_api->backup_init
  112291. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  112292. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  112293. #define sqlite3_backup_step sqlite3_api->backup_step
  112294. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  112295. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  112296. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  112297. #define sqlite3_db_config sqlite3_api->db_config
  112298. #define sqlite3_db_mutex sqlite3_api->db_mutex
  112299. #define sqlite3_db_status sqlite3_api->db_status
  112300. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  112301. #define sqlite3_log sqlite3_api->log
  112302. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  112303. #define sqlite3_sourceid sqlite3_api->sourceid
  112304. #define sqlite3_stmt_status sqlite3_api->stmt_status
  112305. #define sqlite3_strnicmp sqlite3_api->strnicmp
  112306. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  112307. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  112308. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  112309. #define sqlite3_wal_hook sqlite3_api->wal_hook
  112310. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  112311. #define sqlite3_vtab_config sqlite3_api->vtab_config
  112312. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  112313. /* Version 3.7.16 and later */
  112314. #define sqlite3_close_v2 sqlite3_api->close_v2
  112315. #define sqlite3_db_filename sqlite3_api->db_filename
  112316. #define sqlite3_db_readonly sqlite3_api->db_readonly
  112317. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  112318. #define sqlite3_errstr sqlite3_api->errstr
  112319. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  112320. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  112321. #define sqlite3_stricmp sqlite3_api->stricmp
  112322. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  112323. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  112324. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  112325. #define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
  112326. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  112327. /* Version 3.8.7 and later */
  112328. #define sqlite3_auto_extension sqlite3_api->auto_extension
  112329. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  112330. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  112331. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  112332. #define sqlite3_load_extension sqlite3_api->load_extension
  112333. #define sqlite3_malloc64 sqlite3_api->malloc64
  112334. #define sqlite3_msize sqlite3_api->msize
  112335. #define sqlite3_realloc64 sqlite3_api->realloc64
  112336. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  112337. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  112338. #define sqlite3_result_text64 sqlite3_api->result_text64
  112339. #define sqlite3_strglob sqlite3_api->strglob
  112340. /* Version 3.8.11 and later */
  112341. #define sqlite3_value_dup sqlite3_api->value_dup
  112342. #define sqlite3_value_free sqlite3_api->value_free
  112343. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  112344. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  112345. /* Version 3.9.0 and later */
  112346. #define sqlite3_value_subtype sqlite3_api->value_subtype
  112347. #define sqlite3_result_subtype sqlite3_api->result_subtype
  112348. /* Version 3.10.0 and later */
  112349. #define sqlite3_status64 sqlite3_api->status64
  112350. #define sqlite3_strlike sqlite3_api->strlike
  112351. #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
  112352. /* Version 3.12.0 and later */
  112353. #define sqlite3_system_errno sqlite3_api->system_errno
  112354. /* Version 3.14.0 and later */
  112355. #define sqlite3_trace_v2 sqlite3_api->trace_v2
  112356. #define sqlite3_expanded_sql sqlite3_api->expanded_sql
  112357. /* Version 3.18.0 and later */
  112358. #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
  112359. /* Version 3.20.0 and later */
  112360. #define sqlite3_prepare_v3 sqlite3_api->prepare_v3
  112361. #define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
  112362. #define sqlite3_bind_pointer sqlite3_api->bind_pointer
  112363. #define sqlite3_result_pointer sqlite3_api->result_pointer
  112364. #define sqlite3_value_pointer sqlite3_api->value_pointer
  112365. /* Version 3.22.0 and later */
  112366. #define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
  112367. #define sqlite3_value_nochange sqlite3_api->value_nochange
  112368. #define sqlite3_vtab_collation sqlite3_api->vtab_collation
  112369. /* Version 3.24.0 and later */
  112370. #define sqlite3_keyword_count sqlite3_api->keyword_count
  112371. #define sqlite3_keyword_name sqlite3_api->keyword_name
  112372. #define sqlite3_keyword_check sqlite3_api->keyword_check
  112373. #define sqlite3_str_new sqlite3_api->str_new
  112374. #define sqlite3_str_finish sqlite3_api->str_finish
  112375. #define sqlite3_str_appendf sqlite3_api->str_appendf
  112376. #define sqlite3_str_vappendf sqlite3_api->str_vappendf
  112377. #define sqlite3_str_append sqlite3_api->str_append
  112378. #define sqlite3_str_appendall sqlite3_api->str_appendall
  112379. #define sqlite3_str_appendchar sqlite3_api->str_appendchar
  112380. #define sqlite3_str_reset sqlite3_api->str_reset
  112381. #define sqlite3_str_errcode sqlite3_api->str_errcode
  112382. #define sqlite3_str_length sqlite3_api->str_length
  112383. #define sqlite3_str_value sqlite3_api->str_value
  112384. /* Version 3.25.0 and later */
  112385. #define sqlite3_create_window_function sqlite3_api->create_window_function
  112386. /* Version 3.26.0 and later */
  112387. #define sqlite3_normalized_sql sqlite3_api->normalized_sql
  112388. /* Version 3.28.0 and later */
  112389. #define sqlite3_stmt_isexplain sqlite3_api->isexplain
  112390. #define sqlite3_value_frombind sqlite3_api->frombind
  112391. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  112392. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  112393. /* This case when the file really is being compiled as a loadable
  112394. ** extension */
  112395. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  112396. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  112397. # define SQLITE_EXTENSION_INIT3 \
  112398. extern const sqlite3_api_routines *sqlite3_api;
  112399. #else
  112400. /* This case when the file is being statically linked into the
  112401. ** application */
  112402. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  112403. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  112404. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  112405. #endif
  112406. #endif /* SQLITE3EXT_H */
  112407. /************** End of sqlite3ext.h ******************************************/
  112408. /************** Continuing where we left off in loadext.c ********************/
  112409. /* #include "sqliteInt.h" */
  112410. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  112411. /*
  112412. ** Some API routines are omitted when various features are
  112413. ** excluded from a build of SQLite. Substitute a NULL pointer
  112414. ** for any missing APIs.
  112415. */
  112416. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  112417. # define sqlite3_column_database_name 0
  112418. # define sqlite3_column_database_name16 0
  112419. # define sqlite3_column_table_name 0
  112420. # define sqlite3_column_table_name16 0
  112421. # define sqlite3_column_origin_name 0
  112422. # define sqlite3_column_origin_name16 0
  112423. #endif
  112424. #ifdef SQLITE_OMIT_AUTHORIZATION
  112425. # define sqlite3_set_authorizer 0
  112426. #endif
  112427. #ifdef SQLITE_OMIT_UTF16
  112428. # define sqlite3_bind_text16 0
  112429. # define sqlite3_collation_needed16 0
  112430. # define sqlite3_column_decltype16 0
  112431. # define sqlite3_column_name16 0
  112432. # define sqlite3_column_text16 0
  112433. # define sqlite3_complete16 0
  112434. # define sqlite3_create_collation16 0
  112435. # define sqlite3_create_function16 0
  112436. # define sqlite3_errmsg16 0
  112437. # define sqlite3_open16 0
  112438. # define sqlite3_prepare16 0
  112439. # define sqlite3_prepare16_v2 0
  112440. # define sqlite3_prepare16_v3 0
  112441. # define sqlite3_result_error16 0
  112442. # define sqlite3_result_text16 0
  112443. # define sqlite3_result_text16be 0
  112444. # define sqlite3_result_text16le 0
  112445. # define sqlite3_value_text16 0
  112446. # define sqlite3_value_text16be 0
  112447. # define sqlite3_value_text16le 0
  112448. # define sqlite3_column_database_name16 0
  112449. # define sqlite3_column_table_name16 0
  112450. # define sqlite3_column_origin_name16 0
  112451. #endif
  112452. #ifdef SQLITE_OMIT_COMPLETE
  112453. # define sqlite3_complete 0
  112454. # define sqlite3_complete16 0
  112455. #endif
  112456. #ifdef SQLITE_OMIT_DECLTYPE
  112457. # define sqlite3_column_decltype16 0
  112458. # define sqlite3_column_decltype 0
  112459. #endif
  112460. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  112461. # define sqlite3_progress_handler 0
  112462. #endif
  112463. #ifdef SQLITE_OMIT_VIRTUALTABLE
  112464. # define sqlite3_create_module 0
  112465. # define sqlite3_create_module_v2 0
  112466. # define sqlite3_declare_vtab 0
  112467. # define sqlite3_vtab_config 0
  112468. # define sqlite3_vtab_on_conflict 0
  112469. # define sqlite3_vtab_collation 0
  112470. #endif
  112471. #ifdef SQLITE_OMIT_SHARED_CACHE
  112472. # define sqlite3_enable_shared_cache 0
  112473. #endif
  112474. #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
  112475. # define sqlite3_profile 0
  112476. # define sqlite3_trace 0
  112477. #endif
  112478. #ifdef SQLITE_OMIT_GET_TABLE
  112479. # define sqlite3_free_table 0
  112480. # define sqlite3_get_table 0
  112481. #endif
  112482. #ifdef SQLITE_OMIT_INCRBLOB
  112483. #define sqlite3_bind_zeroblob 0
  112484. #define sqlite3_blob_bytes 0
  112485. #define sqlite3_blob_close 0
  112486. #define sqlite3_blob_open 0
  112487. #define sqlite3_blob_read 0
  112488. #define sqlite3_blob_write 0
  112489. #define sqlite3_blob_reopen 0
  112490. #endif
  112491. #if defined(SQLITE_OMIT_TRACE)
  112492. # define sqlite3_trace_v2 0
  112493. #endif
  112494. /*
  112495. ** The following structure contains pointers to all SQLite API routines.
  112496. ** A pointer to this structure is passed into extensions when they are
  112497. ** loaded so that the extension can make calls back into the SQLite
  112498. ** library.
  112499. **
  112500. ** When adding new APIs, add them to the bottom of this structure
  112501. ** in order to preserve backwards compatibility.
  112502. **
  112503. ** Extensions that use newer APIs should first call the
  112504. ** sqlite3_libversion_number() to make sure that the API they
  112505. ** intend to use is supported by the library. Extensions should
  112506. ** also check to make sure that the pointer to the function is
  112507. ** not NULL before calling it.
  112508. */
  112509. static const sqlite3_api_routines sqlite3Apis = {
  112510. sqlite3_aggregate_context,
  112511. #ifndef SQLITE_OMIT_DEPRECATED
  112512. sqlite3_aggregate_count,
  112513. #else
  112514. 0,
  112515. #endif
  112516. sqlite3_bind_blob,
  112517. sqlite3_bind_double,
  112518. sqlite3_bind_int,
  112519. sqlite3_bind_int64,
  112520. sqlite3_bind_null,
  112521. sqlite3_bind_parameter_count,
  112522. sqlite3_bind_parameter_index,
  112523. sqlite3_bind_parameter_name,
  112524. sqlite3_bind_text,
  112525. sqlite3_bind_text16,
  112526. sqlite3_bind_value,
  112527. sqlite3_busy_handler,
  112528. sqlite3_busy_timeout,
  112529. sqlite3_changes,
  112530. sqlite3_close,
  112531. sqlite3_collation_needed,
  112532. sqlite3_collation_needed16,
  112533. sqlite3_column_blob,
  112534. sqlite3_column_bytes,
  112535. sqlite3_column_bytes16,
  112536. sqlite3_column_count,
  112537. sqlite3_column_database_name,
  112538. sqlite3_column_database_name16,
  112539. sqlite3_column_decltype,
  112540. sqlite3_column_decltype16,
  112541. sqlite3_column_double,
  112542. sqlite3_column_int,
  112543. sqlite3_column_int64,
  112544. sqlite3_column_name,
  112545. sqlite3_column_name16,
  112546. sqlite3_column_origin_name,
  112547. sqlite3_column_origin_name16,
  112548. sqlite3_column_table_name,
  112549. sqlite3_column_table_name16,
  112550. sqlite3_column_text,
  112551. sqlite3_column_text16,
  112552. sqlite3_column_type,
  112553. sqlite3_column_value,
  112554. sqlite3_commit_hook,
  112555. sqlite3_complete,
  112556. sqlite3_complete16,
  112557. sqlite3_create_collation,
  112558. sqlite3_create_collation16,
  112559. sqlite3_create_function,
  112560. sqlite3_create_function16,
  112561. sqlite3_create_module,
  112562. sqlite3_data_count,
  112563. sqlite3_db_handle,
  112564. sqlite3_declare_vtab,
  112565. sqlite3_enable_shared_cache,
  112566. sqlite3_errcode,
  112567. sqlite3_errmsg,
  112568. sqlite3_errmsg16,
  112569. sqlite3_exec,
  112570. #ifndef SQLITE_OMIT_DEPRECATED
  112571. sqlite3_expired,
  112572. #else
  112573. 0,
  112574. #endif
  112575. sqlite3_finalize,
  112576. sqlite3_free,
  112577. sqlite3_free_table,
  112578. sqlite3_get_autocommit,
  112579. sqlite3_get_auxdata,
  112580. sqlite3_get_table,
  112581. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  112582. sqlite3_interrupt,
  112583. sqlite3_last_insert_rowid,
  112584. sqlite3_libversion,
  112585. sqlite3_libversion_number,
  112586. sqlite3_malloc,
  112587. sqlite3_mprintf,
  112588. sqlite3_open,
  112589. sqlite3_open16,
  112590. sqlite3_prepare,
  112591. sqlite3_prepare16,
  112592. sqlite3_profile,
  112593. sqlite3_progress_handler,
  112594. sqlite3_realloc,
  112595. sqlite3_reset,
  112596. sqlite3_result_blob,
  112597. sqlite3_result_double,
  112598. sqlite3_result_error,
  112599. sqlite3_result_error16,
  112600. sqlite3_result_int,
  112601. sqlite3_result_int64,
  112602. sqlite3_result_null,
  112603. sqlite3_result_text,
  112604. sqlite3_result_text16,
  112605. sqlite3_result_text16be,
  112606. sqlite3_result_text16le,
  112607. sqlite3_result_value,
  112608. sqlite3_rollback_hook,
  112609. sqlite3_set_authorizer,
  112610. sqlite3_set_auxdata,
  112611. sqlite3_snprintf,
  112612. sqlite3_step,
  112613. sqlite3_table_column_metadata,
  112614. #ifndef SQLITE_OMIT_DEPRECATED
  112615. sqlite3_thread_cleanup,
  112616. #else
  112617. 0,
  112618. #endif
  112619. sqlite3_total_changes,
  112620. sqlite3_trace,
  112621. #ifndef SQLITE_OMIT_DEPRECATED
  112622. sqlite3_transfer_bindings,
  112623. #else
  112624. 0,
  112625. #endif
  112626. sqlite3_update_hook,
  112627. sqlite3_user_data,
  112628. sqlite3_value_blob,
  112629. sqlite3_value_bytes,
  112630. sqlite3_value_bytes16,
  112631. sqlite3_value_double,
  112632. sqlite3_value_int,
  112633. sqlite3_value_int64,
  112634. sqlite3_value_numeric_type,
  112635. sqlite3_value_text,
  112636. sqlite3_value_text16,
  112637. sqlite3_value_text16be,
  112638. sqlite3_value_text16le,
  112639. sqlite3_value_type,
  112640. sqlite3_vmprintf,
  112641. /*
  112642. ** The original API set ends here. All extensions can call any
  112643. ** of the APIs above provided that the pointer is not NULL. But
  112644. ** before calling APIs that follow, extension should check the
  112645. ** sqlite3_libversion_number() to make sure they are dealing with
  112646. ** a library that is new enough to support that API.
  112647. *************************************************************************
  112648. */
  112649. sqlite3_overload_function,
  112650. /*
  112651. ** Added after 3.3.13
  112652. */
  112653. sqlite3_prepare_v2,
  112654. sqlite3_prepare16_v2,
  112655. sqlite3_clear_bindings,
  112656. /*
  112657. ** Added for 3.4.1
  112658. */
  112659. sqlite3_create_module_v2,
  112660. /*
  112661. ** Added for 3.5.0
  112662. */
  112663. sqlite3_bind_zeroblob,
  112664. sqlite3_blob_bytes,
  112665. sqlite3_blob_close,
  112666. sqlite3_blob_open,
  112667. sqlite3_blob_read,
  112668. sqlite3_blob_write,
  112669. sqlite3_create_collation_v2,
  112670. sqlite3_file_control,
  112671. sqlite3_memory_highwater,
  112672. sqlite3_memory_used,
  112673. #ifdef SQLITE_MUTEX_OMIT
  112674. 0,
  112675. 0,
  112676. 0,
  112677. 0,
  112678. 0,
  112679. #else
  112680. sqlite3_mutex_alloc,
  112681. sqlite3_mutex_enter,
  112682. sqlite3_mutex_free,
  112683. sqlite3_mutex_leave,
  112684. sqlite3_mutex_try,
  112685. #endif
  112686. sqlite3_open_v2,
  112687. sqlite3_release_memory,
  112688. sqlite3_result_error_nomem,
  112689. sqlite3_result_error_toobig,
  112690. sqlite3_sleep,
  112691. sqlite3_soft_heap_limit,
  112692. sqlite3_vfs_find,
  112693. sqlite3_vfs_register,
  112694. sqlite3_vfs_unregister,
  112695. /*
  112696. ** Added for 3.5.8
  112697. */
  112698. sqlite3_threadsafe,
  112699. sqlite3_result_zeroblob,
  112700. sqlite3_result_error_code,
  112701. sqlite3_test_control,
  112702. sqlite3_randomness,
  112703. sqlite3_context_db_handle,
  112704. /*
  112705. ** Added for 3.6.0
  112706. */
  112707. sqlite3_extended_result_codes,
  112708. sqlite3_limit,
  112709. sqlite3_next_stmt,
  112710. sqlite3_sql,
  112711. sqlite3_status,
  112712. /*
  112713. ** Added for 3.7.4
  112714. */
  112715. sqlite3_backup_finish,
  112716. sqlite3_backup_init,
  112717. sqlite3_backup_pagecount,
  112718. sqlite3_backup_remaining,
  112719. sqlite3_backup_step,
  112720. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  112721. sqlite3_compileoption_get,
  112722. sqlite3_compileoption_used,
  112723. #else
  112724. 0,
  112725. 0,
  112726. #endif
  112727. sqlite3_create_function_v2,
  112728. sqlite3_db_config,
  112729. sqlite3_db_mutex,
  112730. sqlite3_db_status,
  112731. sqlite3_extended_errcode,
  112732. sqlite3_log,
  112733. sqlite3_soft_heap_limit64,
  112734. sqlite3_sourceid,
  112735. sqlite3_stmt_status,
  112736. sqlite3_strnicmp,
  112737. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  112738. sqlite3_unlock_notify,
  112739. #else
  112740. 0,
  112741. #endif
  112742. #ifndef SQLITE_OMIT_WAL
  112743. sqlite3_wal_autocheckpoint,
  112744. sqlite3_wal_checkpoint,
  112745. sqlite3_wal_hook,
  112746. #else
  112747. 0,
  112748. 0,
  112749. 0,
  112750. #endif
  112751. sqlite3_blob_reopen,
  112752. sqlite3_vtab_config,
  112753. sqlite3_vtab_on_conflict,
  112754. sqlite3_close_v2,
  112755. sqlite3_db_filename,
  112756. sqlite3_db_readonly,
  112757. sqlite3_db_release_memory,
  112758. sqlite3_errstr,
  112759. sqlite3_stmt_busy,
  112760. sqlite3_stmt_readonly,
  112761. sqlite3_stricmp,
  112762. sqlite3_uri_boolean,
  112763. sqlite3_uri_int64,
  112764. sqlite3_uri_parameter,
  112765. sqlite3_vsnprintf,
  112766. sqlite3_wal_checkpoint_v2,
  112767. /* Version 3.8.7 and later */
  112768. sqlite3_auto_extension,
  112769. sqlite3_bind_blob64,
  112770. sqlite3_bind_text64,
  112771. sqlite3_cancel_auto_extension,
  112772. sqlite3_load_extension,
  112773. sqlite3_malloc64,
  112774. sqlite3_msize,
  112775. sqlite3_realloc64,
  112776. sqlite3_reset_auto_extension,
  112777. sqlite3_result_blob64,
  112778. sqlite3_result_text64,
  112779. sqlite3_strglob,
  112780. /* Version 3.8.11 and later */
  112781. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  112782. sqlite3_value_free,
  112783. sqlite3_result_zeroblob64,
  112784. sqlite3_bind_zeroblob64,
  112785. /* Version 3.9.0 and later */
  112786. sqlite3_value_subtype,
  112787. sqlite3_result_subtype,
  112788. /* Version 3.10.0 and later */
  112789. sqlite3_status64,
  112790. sqlite3_strlike,
  112791. sqlite3_db_cacheflush,
  112792. /* Version 3.12.0 and later */
  112793. sqlite3_system_errno,
  112794. /* Version 3.14.0 and later */
  112795. sqlite3_trace_v2,
  112796. sqlite3_expanded_sql,
  112797. /* Version 3.18.0 and later */
  112798. sqlite3_set_last_insert_rowid,
  112799. /* Version 3.20.0 and later */
  112800. sqlite3_prepare_v3,
  112801. sqlite3_prepare16_v3,
  112802. sqlite3_bind_pointer,
  112803. sqlite3_result_pointer,
  112804. sqlite3_value_pointer,
  112805. /* Version 3.22.0 and later */
  112806. sqlite3_vtab_nochange,
  112807. sqlite3_value_nochange,
  112808. sqlite3_vtab_collation,
  112809. /* Version 3.24.0 and later */
  112810. sqlite3_keyword_count,
  112811. sqlite3_keyword_name,
  112812. sqlite3_keyword_check,
  112813. sqlite3_str_new,
  112814. sqlite3_str_finish,
  112815. sqlite3_str_appendf,
  112816. sqlite3_str_vappendf,
  112817. sqlite3_str_append,
  112818. sqlite3_str_appendall,
  112819. sqlite3_str_appendchar,
  112820. sqlite3_str_reset,
  112821. sqlite3_str_errcode,
  112822. sqlite3_str_length,
  112823. sqlite3_str_value,
  112824. /* Version 3.25.0 and later */
  112825. sqlite3_create_window_function,
  112826. /* Version 3.26.0 and later */
  112827. #ifdef SQLITE_ENABLE_NORMALIZE
  112828. sqlite3_normalized_sql,
  112829. #else
  112830. 0,
  112831. #endif
  112832. /* Version 3.28.0 and later */
  112833. sqlite3_stmt_isexplain,
  112834. sqlite3_value_frombind
  112835. };
  112836. /*
  112837. ** Attempt to load an SQLite extension library contained in the file
  112838. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  112839. ** default entry point name (sqlite3_extension_init) is used. Use
  112840. ** of the default name is recommended.
  112841. **
  112842. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  112843. **
  112844. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  112845. ** error message text. The calling function should free this memory
  112846. ** by calling sqlite3DbFree(db, ).
  112847. */
  112848. static int sqlite3LoadExtension(
  112849. sqlite3 *db, /* Load the extension into this database connection */
  112850. const char *zFile, /* Name of the shared library containing extension */
  112851. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  112852. char **pzErrMsg /* Put error message here if not 0 */
  112853. ){
  112854. sqlite3_vfs *pVfs = db->pVfs;
  112855. void *handle;
  112856. sqlite3_loadext_entry xInit;
  112857. char *zErrmsg = 0;
  112858. const char *zEntry;
  112859. char *zAltEntry = 0;
  112860. void **aHandle;
  112861. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  112862. int ii;
  112863. int rc;
  112864. /* Shared library endings to try if zFile cannot be loaded as written */
  112865. static const char *azEndings[] = {
  112866. #if SQLITE_OS_WIN
  112867. "dll"
  112868. #elif defined(__APPLE__)
  112869. "dylib"
  112870. #else
  112871. "so"
  112872. #endif
  112873. };
  112874. if( pzErrMsg ) *pzErrMsg = 0;
  112875. /* Ticket #1863. To avoid a creating security problems for older
  112876. ** applications that relink against newer versions of SQLite, the
  112877. ** ability to run load_extension is turned off by default. One
  112878. ** must call either sqlite3_enable_load_extension(db) or
  112879. ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
  112880. ** to turn on extension loading.
  112881. */
  112882. if( (db->flags & SQLITE_LoadExtension)==0 ){
  112883. if( pzErrMsg ){
  112884. *pzErrMsg = sqlite3_mprintf("not authorized");
  112885. }
  112886. return SQLITE_ERROR;
  112887. }
  112888. zEntry = zProc ? zProc : "sqlite3_extension_init";
  112889. handle = sqlite3OsDlOpen(pVfs, zFile);
  112890. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  112891. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  112892. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  112893. if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
  112894. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  112895. sqlite3_free(zAltFile);
  112896. }
  112897. #endif
  112898. if( handle==0 ){
  112899. if( pzErrMsg ){
  112900. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  112901. if( zErrmsg ){
  112902. sqlite3_snprintf(nMsg, zErrmsg,
  112903. "unable to open shared library [%s]", zFile);
  112904. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  112905. }
  112906. }
  112907. return SQLITE_ERROR;
  112908. }
  112909. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  112910. /* If no entry point was specified and the default legacy
  112911. ** entry point name "sqlite3_extension_init" was not found, then
  112912. ** construct an entry point name "sqlite3_X_init" where the X is
  112913. ** replaced by the lowercase value of every ASCII alphabetic
  112914. ** character in the filename after the last "/" upto the first ".",
  112915. ** and eliding the first three characters if they are "lib".
  112916. ** Examples:
  112917. **
  112918. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  112919. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  112920. */
  112921. if( xInit==0 && zProc==0 ){
  112922. int iFile, iEntry, c;
  112923. int ncFile = sqlite3Strlen30(zFile);
  112924. zAltEntry = sqlite3_malloc64(ncFile+30);
  112925. if( zAltEntry==0 ){
  112926. sqlite3OsDlClose(pVfs, handle);
  112927. return SQLITE_NOMEM_BKPT;
  112928. }
  112929. memcpy(zAltEntry, "sqlite3_", 8);
  112930. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  112931. iFile++;
  112932. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  112933. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  112934. if( sqlite3Isalpha(c) ){
  112935. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  112936. }
  112937. }
  112938. memcpy(zAltEntry+iEntry, "_init", 6);
  112939. zEntry = zAltEntry;
  112940. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  112941. }
  112942. if( xInit==0 ){
  112943. if( pzErrMsg ){
  112944. nMsg += sqlite3Strlen30(zEntry);
  112945. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  112946. if( zErrmsg ){
  112947. sqlite3_snprintf(nMsg, zErrmsg,
  112948. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  112949. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  112950. }
  112951. }
  112952. sqlite3OsDlClose(pVfs, handle);
  112953. sqlite3_free(zAltEntry);
  112954. return SQLITE_ERROR;
  112955. }
  112956. sqlite3_free(zAltEntry);
  112957. rc = xInit(db, &zErrmsg, &sqlite3Apis);
  112958. if( rc ){
  112959. if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
  112960. if( pzErrMsg ){
  112961. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  112962. }
  112963. sqlite3_free(zErrmsg);
  112964. sqlite3OsDlClose(pVfs, handle);
  112965. return SQLITE_ERROR;
  112966. }
  112967. /* Append the new shared library handle to the db->aExtension array. */
  112968. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  112969. if( aHandle==0 ){
  112970. return SQLITE_NOMEM_BKPT;
  112971. }
  112972. if( db->nExtension>0 ){
  112973. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  112974. }
  112975. sqlite3DbFree(db, db->aExtension);
  112976. db->aExtension = aHandle;
  112977. db->aExtension[db->nExtension++] = handle;
  112978. return SQLITE_OK;
  112979. }
  112980. SQLITE_API int sqlite3_load_extension(
  112981. sqlite3 *db, /* Load the extension into this database connection */
  112982. const char *zFile, /* Name of the shared library containing extension */
  112983. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  112984. char **pzErrMsg /* Put error message here if not 0 */
  112985. ){
  112986. int rc;
  112987. sqlite3_mutex_enter(db->mutex);
  112988. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  112989. rc = sqlite3ApiExit(db, rc);
  112990. sqlite3_mutex_leave(db->mutex);
  112991. return rc;
  112992. }
  112993. /*
  112994. ** Call this routine when the database connection is closing in order
  112995. ** to clean up loaded extensions
  112996. */
  112997. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  112998. int i;
  112999. assert( sqlite3_mutex_held(db->mutex) );
  113000. for(i=0; i<db->nExtension; i++){
  113001. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  113002. }
  113003. sqlite3DbFree(db, db->aExtension);
  113004. }
  113005. /*
  113006. ** Enable or disable extension loading. Extension loading is disabled by
  113007. ** default so as not to open security holes in older applications.
  113008. */
  113009. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  113010. sqlite3_mutex_enter(db->mutex);
  113011. if( onoff ){
  113012. db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
  113013. }else{
  113014. db->flags &= ~(u64)(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
  113015. }
  113016. sqlite3_mutex_leave(db->mutex);
  113017. return SQLITE_OK;
  113018. }
  113019. #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  113020. /*
  113021. ** The following object holds the list of automatically loaded
  113022. ** extensions.
  113023. **
  113024. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  113025. ** mutex must be held while accessing this list.
  113026. */
  113027. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  113028. static SQLITE_WSD struct sqlite3AutoExtList {
  113029. u32 nExt; /* Number of entries in aExt[] */
  113030. void (**aExt)(void); /* Pointers to the extension init functions */
  113031. } sqlite3Autoext = { 0, 0 };
  113032. /* The "wsdAutoext" macro will resolve to the autoextension
  113033. ** state vector. If writable static data is unsupported on the target,
  113034. ** we have to locate the state vector at run-time. In the more common
  113035. ** case where writable static data is supported, wsdStat can refer directly
  113036. ** to the "sqlite3Autoext" state vector declared above.
  113037. */
  113038. #ifdef SQLITE_OMIT_WSD
  113039. # define wsdAutoextInit \
  113040. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  113041. # define wsdAutoext x[0]
  113042. #else
  113043. # define wsdAutoextInit
  113044. # define wsdAutoext sqlite3Autoext
  113045. #endif
  113046. /*
  113047. ** Register a statically linked extension that is automatically
  113048. ** loaded by every new database connection.
  113049. */
  113050. SQLITE_API int sqlite3_auto_extension(
  113051. void (*xInit)(void)
  113052. ){
  113053. int rc = SQLITE_OK;
  113054. #ifndef SQLITE_OMIT_AUTOINIT
  113055. rc = sqlite3_initialize();
  113056. if( rc ){
  113057. return rc;
  113058. }else
  113059. #endif
  113060. {
  113061. u32 i;
  113062. #if SQLITE_THREADSAFE
  113063. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  113064. #endif
  113065. wsdAutoextInit;
  113066. sqlite3_mutex_enter(mutex);
  113067. for(i=0; i<wsdAutoext.nExt; i++){
  113068. if( wsdAutoext.aExt[i]==xInit ) break;
  113069. }
  113070. if( i==wsdAutoext.nExt ){
  113071. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  113072. void (**aNew)(void);
  113073. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  113074. if( aNew==0 ){
  113075. rc = SQLITE_NOMEM_BKPT;
  113076. }else{
  113077. wsdAutoext.aExt = aNew;
  113078. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  113079. wsdAutoext.nExt++;
  113080. }
  113081. }
  113082. sqlite3_mutex_leave(mutex);
  113083. assert( (rc&0xff)==rc );
  113084. return rc;
  113085. }
  113086. }
  113087. /*
  113088. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  113089. ** set of routines that is invoked for each new database connection, if it
  113090. ** is currently on the list. If xInit is not on the list, then this
  113091. ** routine is a no-op.
  113092. **
  113093. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  113094. ** was not on the list.
  113095. */
  113096. SQLITE_API int sqlite3_cancel_auto_extension(
  113097. void (*xInit)(void)
  113098. ){
  113099. #if SQLITE_THREADSAFE
  113100. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  113101. #endif
  113102. int i;
  113103. int n = 0;
  113104. wsdAutoextInit;
  113105. sqlite3_mutex_enter(mutex);
  113106. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  113107. if( wsdAutoext.aExt[i]==xInit ){
  113108. wsdAutoext.nExt--;
  113109. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  113110. n++;
  113111. break;
  113112. }
  113113. }
  113114. sqlite3_mutex_leave(mutex);
  113115. return n;
  113116. }
  113117. /*
  113118. ** Reset the automatic extension loading mechanism.
  113119. */
  113120. SQLITE_API void sqlite3_reset_auto_extension(void){
  113121. #ifndef SQLITE_OMIT_AUTOINIT
  113122. if( sqlite3_initialize()==SQLITE_OK )
  113123. #endif
  113124. {
  113125. #if SQLITE_THREADSAFE
  113126. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  113127. #endif
  113128. wsdAutoextInit;
  113129. sqlite3_mutex_enter(mutex);
  113130. sqlite3_free(wsdAutoext.aExt);
  113131. wsdAutoext.aExt = 0;
  113132. wsdAutoext.nExt = 0;
  113133. sqlite3_mutex_leave(mutex);
  113134. }
  113135. }
  113136. /*
  113137. ** Load all automatic extensions.
  113138. **
  113139. ** If anything goes wrong, set an error in the database connection.
  113140. */
  113141. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  113142. u32 i;
  113143. int go = 1;
  113144. int rc;
  113145. sqlite3_loadext_entry xInit;
  113146. wsdAutoextInit;
  113147. if( wsdAutoext.nExt==0 ){
  113148. /* Common case: early out without every having to acquire a mutex */
  113149. return;
  113150. }
  113151. for(i=0; go; i++){
  113152. char *zErrmsg;
  113153. #if SQLITE_THREADSAFE
  113154. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  113155. #endif
  113156. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  113157. const sqlite3_api_routines *pThunk = 0;
  113158. #else
  113159. const sqlite3_api_routines *pThunk = &sqlite3Apis;
  113160. #endif
  113161. sqlite3_mutex_enter(mutex);
  113162. if( i>=wsdAutoext.nExt ){
  113163. xInit = 0;
  113164. go = 0;
  113165. }else{
  113166. xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
  113167. }
  113168. sqlite3_mutex_leave(mutex);
  113169. zErrmsg = 0;
  113170. if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
  113171. sqlite3ErrorWithMsg(db, rc,
  113172. "automatic extension loading failed: %s", zErrmsg);
  113173. go = 0;
  113174. }
  113175. sqlite3_free(zErrmsg);
  113176. }
  113177. }
  113178. /************** End of loadext.c *********************************************/
  113179. /************** Begin file pragma.c ******************************************/
  113180. /*
  113181. ** 2003 April 6
  113182. **
  113183. ** The author disclaims copyright to this source code. In place of
  113184. ** a legal notice, here is a blessing:
  113185. **
  113186. ** May you do good and not evil.
  113187. ** May you find forgiveness for yourself and forgive others.
  113188. ** May you share freely, never taking more than you give.
  113189. **
  113190. *************************************************************************
  113191. ** This file contains code used to implement the PRAGMA command.
  113192. */
  113193. /* #include "sqliteInt.h" */
  113194. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  113195. # if defined(__APPLE__)
  113196. # define SQLITE_ENABLE_LOCKING_STYLE 1
  113197. # else
  113198. # define SQLITE_ENABLE_LOCKING_STYLE 0
  113199. # endif
  113200. #endif
  113201. /***************************************************************************
  113202. ** The "pragma.h" include file is an automatically generated file that
  113203. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  113204. ** object. This ensures that the aPragmaName[] table is arranged in
  113205. ** lexicographical order to facility a binary search of the pragma name.
  113206. ** Do not edit pragma.h directly. Edit and rerun the script in at
  113207. ** ../tool/mkpragmatab.tcl. */
  113208. /************** Include pragma.h in the middle of pragma.c *******************/
  113209. /************** Begin file pragma.h ******************************************/
  113210. /* DO NOT EDIT!
  113211. ** This file is automatically generated by the script at
  113212. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  113213. ** that script and rerun it.
  113214. */
  113215. /* The various pragma types */
  113216. #define PragTyp_HEADER_VALUE 0
  113217. #define PragTyp_AUTO_VACUUM 1
  113218. #define PragTyp_FLAG 2
  113219. #define PragTyp_BUSY_TIMEOUT 3
  113220. #define PragTyp_CACHE_SIZE 4
  113221. #define PragTyp_CACHE_SPILL 5
  113222. #define PragTyp_CASE_SENSITIVE_LIKE 6
  113223. #define PragTyp_COLLATION_LIST 7
  113224. #define PragTyp_COMPILE_OPTIONS 8
  113225. #define PragTyp_DATA_STORE_DIRECTORY 9
  113226. #define PragTyp_DATABASE_LIST 10
  113227. #define PragTyp_DEFAULT_CACHE_SIZE 11
  113228. #define PragTyp_ENCODING 12
  113229. #define PragTyp_FOREIGN_KEY_CHECK 13
  113230. #define PragTyp_FOREIGN_KEY_LIST 14
  113231. #define PragTyp_FUNCTION_LIST 15
  113232. #define PragTyp_INCREMENTAL_VACUUM 16
  113233. #define PragTyp_INDEX_INFO 17
  113234. #define PragTyp_INDEX_LIST 18
  113235. #define PragTyp_INTEGRITY_CHECK 19
  113236. #define PragTyp_JOURNAL_MODE 20
  113237. #define PragTyp_JOURNAL_SIZE_LIMIT 21
  113238. #define PragTyp_LOCK_PROXY_FILE 22
  113239. #define PragTyp_LOCKING_MODE 23
  113240. #define PragTyp_PAGE_COUNT 24
  113241. #define PragTyp_MMAP_SIZE 25
  113242. #define PragTyp_MODULE_LIST 26
  113243. #define PragTyp_OPTIMIZE 27
  113244. #define PragTyp_PAGE_SIZE 28
  113245. #define PragTyp_PRAGMA_LIST 29
  113246. #define PragTyp_SECURE_DELETE 30
  113247. #define PragTyp_SHRINK_MEMORY 31
  113248. #define PragTyp_SOFT_HEAP_LIMIT 32
  113249. #define PragTyp_SYNCHRONOUS 33
  113250. #define PragTyp_TABLE_INFO 34
  113251. #define PragTyp_TEMP_STORE 35
  113252. #define PragTyp_TEMP_STORE_DIRECTORY 36
  113253. #define PragTyp_THREADS 37
  113254. #define PragTyp_WAL_AUTOCHECKPOINT 38
  113255. #define PragTyp_WAL_CHECKPOINT 39
  113256. #define PragTyp_ACTIVATE_EXTENSIONS 40
  113257. #define PragTyp_HEXKEY 41
  113258. #define PragTyp_KEY 42
  113259. #define PragTyp_LOCK_STATUS 43
  113260. #define PragTyp_STATS 44
  113261. /* Property flags associated with various pragma. */
  113262. #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
  113263. #define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */
  113264. #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
  113265. #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
  113266. #define PragFlg_Result0 0x10 /* Acts as query when no argument */
  113267. #define PragFlg_Result1 0x20 /* Acts as query when has one argument */
  113268. #define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */
  113269. #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
  113270. /* Names of columns for pragmas that return multi-column result
  113271. ** or that return single-column results where the name of the
  113272. ** result column is different from the name of the pragma
  113273. */
  113274. static const char *const pragCName[] = {
  113275. /* 0 */ "id", /* Used by: foreign_key_list */
  113276. /* 1 */ "seq",
  113277. /* 2 */ "table",
  113278. /* 3 */ "from",
  113279. /* 4 */ "to",
  113280. /* 5 */ "on_update",
  113281. /* 6 */ "on_delete",
  113282. /* 7 */ "match",
  113283. /* 8 */ "cid", /* Used by: table_xinfo */
  113284. /* 9 */ "name",
  113285. /* 10 */ "type",
  113286. /* 11 */ "notnull",
  113287. /* 12 */ "dflt_value",
  113288. /* 13 */ "pk",
  113289. /* 14 */ "hidden",
  113290. /* table_info reuses 8 */
  113291. /* 15 */ "seqno", /* Used by: index_xinfo */
  113292. /* 16 */ "cid",
  113293. /* 17 */ "name",
  113294. /* 18 */ "desc",
  113295. /* 19 */ "coll",
  113296. /* 20 */ "key",
  113297. /* 21 */ "tbl", /* Used by: stats */
  113298. /* 22 */ "idx",
  113299. /* 23 */ "wdth",
  113300. /* 24 */ "hght",
  113301. /* 25 */ "flgs",
  113302. /* 26 */ "seq", /* Used by: index_list */
  113303. /* 27 */ "name",
  113304. /* 28 */ "unique",
  113305. /* 29 */ "origin",
  113306. /* 30 */ "partial",
  113307. /* 31 */ "table", /* Used by: foreign_key_check */
  113308. /* 32 */ "rowid",
  113309. /* 33 */ "parent",
  113310. /* 34 */ "fkid",
  113311. /* index_info reuses 15 */
  113312. /* 35 */ "seq", /* Used by: database_list */
  113313. /* 36 */ "name",
  113314. /* 37 */ "file",
  113315. /* 38 */ "busy", /* Used by: wal_checkpoint */
  113316. /* 39 */ "log",
  113317. /* 40 */ "checkpointed",
  113318. /* 41 */ "name", /* Used by: function_list */
  113319. /* 42 */ "builtin",
  113320. /* collation_list reuses 26 */
  113321. /* 43 */ "database", /* Used by: lock_status */
  113322. /* 44 */ "status",
  113323. /* 45 */ "cache_size", /* Used by: default_cache_size */
  113324. /* module_list pragma_list reuses 9 */
  113325. /* 46 */ "timeout", /* Used by: busy_timeout */
  113326. };
  113327. /* Definitions of all built-in pragmas */
  113328. typedef struct PragmaName {
  113329. const char *const zName; /* Name of pragma */
  113330. u8 ePragTyp; /* PragTyp_XXX value */
  113331. u8 mPragFlg; /* Zero or more PragFlg_XXX values */
  113332. u8 iPragCName; /* Start of column names in pragCName[] */
  113333. u8 nPragCName; /* Num of col names. 0 means use pragma name */
  113334. u64 iArg; /* Extra argument */
  113335. } PragmaName;
  113336. static const PragmaName aPragmaName[] = {
  113337. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  113338. {/* zName: */ "activate_extensions",
  113339. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  113340. /* ePragFlg: */ 0,
  113341. /* ColNames: */ 0, 0,
  113342. /* iArg: */ 0 },
  113343. #endif
  113344. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  113345. {/* zName: */ "application_id",
  113346. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  113347. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  113348. /* ColNames: */ 0, 0,
  113349. /* iArg: */ BTREE_APPLICATION_ID },
  113350. #endif
  113351. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  113352. {/* zName: */ "auto_vacuum",
  113353. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  113354. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  113355. /* ColNames: */ 0, 0,
  113356. /* iArg: */ 0 },
  113357. #endif
  113358. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113359. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  113360. {/* zName: */ "automatic_index",
  113361. /* ePragTyp: */ PragTyp_FLAG,
  113362. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113363. /* ColNames: */ 0, 0,
  113364. /* iArg: */ SQLITE_AutoIndex },
  113365. #endif
  113366. #endif
  113367. {/* zName: */ "busy_timeout",
  113368. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  113369. /* ePragFlg: */ PragFlg_Result0,
  113370. /* ColNames: */ 46, 1,
  113371. /* iArg: */ 0 },
  113372. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  113373. {/* zName: */ "cache_size",
  113374. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  113375. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  113376. /* ColNames: */ 0, 0,
  113377. /* iArg: */ 0 },
  113378. #endif
  113379. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113380. {/* zName: */ "cache_spill",
  113381. /* ePragTyp: */ PragTyp_CACHE_SPILL,
  113382. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  113383. /* ColNames: */ 0, 0,
  113384. /* iArg: */ 0 },
  113385. #endif
  113386. {/* zName: */ "case_sensitive_like",
  113387. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  113388. /* ePragFlg: */ PragFlg_NoColumns,
  113389. /* ColNames: */ 0, 0,
  113390. /* iArg: */ 0 },
  113391. {/* zName: */ "cell_size_check",
  113392. /* ePragTyp: */ PragTyp_FLAG,
  113393. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113394. /* ColNames: */ 0, 0,
  113395. /* iArg: */ SQLITE_CellSizeCk },
  113396. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113397. {/* zName: */ "checkpoint_fullfsync",
  113398. /* ePragTyp: */ PragTyp_FLAG,
  113399. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113400. /* ColNames: */ 0, 0,
  113401. /* iArg: */ SQLITE_CkptFullFSync },
  113402. #endif
  113403. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  113404. {/* zName: */ "collation_list",
  113405. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  113406. /* ePragFlg: */ PragFlg_Result0,
  113407. /* ColNames: */ 26, 2,
  113408. /* iArg: */ 0 },
  113409. #endif
  113410. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  113411. {/* zName: */ "compile_options",
  113412. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  113413. /* ePragFlg: */ PragFlg_Result0,
  113414. /* ColNames: */ 0, 0,
  113415. /* iArg: */ 0 },
  113416. #endif
  113417. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113418. {/* zName: */ "count_changes",
  113419. /* ePragTyp: */ PragTyp_FLAG,
  113420. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113421. /* ColNames: */ 0, 0,
  113422. /* iArg: */ SQLITE_CountRows },
  113423. #endif
  113424. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  113425. {/* zName: */ "data_store_directory",
  113426. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  113427. /* ePragFlg: */ PragFlg_NoColumns1,
  113428. /* ColNames: */ 0, 0,
  113429. /* iArg: */ 0 },
  113430. #endif
  113431. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  113432. {/* zName: */ "data_version",
  113433. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  113434. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  113435. /* ColNames: */ 0, 0,
  113436. /* iArg: */ BTREE_DATA_VERSION },
  113437. #endif
  113438. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  113439. {/* zName: */ "database_list",
  113440. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  113441. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  113442. /* ColNames: */ 35, 3,
  113443. /* iArg: */ 0 },
  113444. #endif
  113445. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  113446. {/* zName: */ "default_cache_size",
  113447. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  113448. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  113449. /* ColNames: */ 45, 1,
  113450. /* iArg: */ 0 },
  113451. #endif
  113452. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113453. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  113454. {/* zName: */ "defer_foreign_keys",
  113455. /* ePragTyp: */ PragTyp_FLAG,
  113456. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113457. /* ColNames: */ 0, 0,
  113458. /* iArg: */ SQLITE_DeferFKs },
  113459. #endif
  113460. #endif
  113461. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113462. {/* zName: */ "empty_result_callbacks",
  113463. /* ePragTyp: */ PragTyp_FLAG,
  113464. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113465. /* ColNames: */ 0, 0,
  113466. /* iArg: */ SQLITE_NullCallback },
  113467. #endif
  113468. #if !defined(SQLITE_OMIT_UTF16)
  113469. {/* zName: */ "encoding",
  113470. /* ePragTyp: */ PragTyp_ENCODING,
  113471. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113472. /* ColNames: */ 0, 0,
  113473. /* iArg: */ 0 },
  113474. #endif
  113475. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  113476. {/* zName: */ "foreign_key_check",
  113477. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  113478. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  113479. /* ColNames: */ 31, 4,
  113480. /* iArg: */ 0 },
  113481. #endif
  113482. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  113483. {/* zName: */ "foreign_key_list",
  113484. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  113485. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  113486. /* ColNames: */ 0, 8,
  113487. /* iArg: */ 0 },
  113488. #endif
  113489. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113490. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  113491. {/* zName: */ "foreign_keys",
  113492. /* ePragTyp: */ PragTyp_FLAG,
  113493. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113494. /* ColNames: */ 0, 0,
  113495. /* iArg: */ SQLITE_ForeignKeys },
  113496. #endif
  113497. #endif
  113498. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  113499. {/* zName: */ "freelist_count",
  113500. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  113501. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  113502. /* ColNames: */ 0, 0,
  113503. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  113504. #endif
  113505. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113506. {/* zName: */ "full_column_names",
  113507. /* ePragTyp: */ PragTyp_FLAG,
  113508. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113509. /* ColNames: */ 0, 0,
  113510. /* iArg: */ SQLITE_FullColNames },
  113511. {/* zName: */ "fullfsync",
  113512. /* ePragTyp: */ PragTyp_FLAG,
  113513. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113514. /* ColNames: */ 0, 0,
  113515. /* iArg: */ SQLITE_FullFSync },
  113516. #endif
  113517. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  113518. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  113519. {/* zName: */ "function_list",
  113520. /* ePragTyp: */ PragTyp_FUNCTION_LIST,
  113521. /* ePragFlg: */ PragFlg_Result0,
  113522. /* ColNames: */ 41, 2,
  113523. /* iArg: */ 0 },
  113524. #endif
  113525. #endif
  113526. #if defined(SQLITE_HAS_CODEC)
  113527. {/* zName: */ "hexkey",
  113528. /* ePragTyp: */ PragTyp_HEXKEY,
  113529. /* ePragFlg: */ 0,
  113530. /* ColNames: */ 0, 0,
  113531. /* iArg: */ 2 },
  113532. {/* zName: */ "hexrekey",
  113533. /* ePragTyp: */ PragTyp_HEXKEY,
  113534. /* ePragFlg: */ 0,
  113535. /* ColNames: */ 0, 0,
  113536. /* iArg: */ 3 },
  113537. #endif
  113538. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113539. #if !defined(SQLITE_OMIT_CHECK)
  113540. {/* zName: */ "ignore_check_constraints",
  113541. /* ePragTyp: */ PragTyp_FLAG,
  113542. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113543. /* ColNames: */ 0, 0,
  113544. /* iArg: */ SQLITE_IgnoreChecks },
  113545. #endif
  113546. #endif
  113547. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  113548. {/* zName: */ "incremental_vacuum",
  113549. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  113550. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns,
  113551. /* ColNames: */ 0, 0,
  113552. /* iArg: */ 0 },
  113553. #endif
  113554. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  113555. {/* zName: */ "index_info",
  113556. /* ePragTyp: */ PragTyp_INDEX_INFO,
  113557. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  113558. /* ColNames: */ 15, 3,
  113559. /* iArg: */ 0 },
  113560. {/* zName: */ "index_list",
  113561. /* ePragTyp: */ PragTyp_INDEX_LIST,
  113562. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  113563. /* ColNames: */ 26, 5,
  113564. /* iArg: */ 0 },
  113565. {/* zName: */ "index_xinfo",
  113566. /* ePragTyp: */ PragTyp_INDEX_INFO,
  113567. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  113568. /* ColNames: */ 15, 6,
  113569. /* iArg: */ 1 },
  113570. #endif
  113571. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  113572. {/* zName: */ "integrity_check",
  113573. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  113574. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  113575. /* ColNames: */ 0, 0,
  113576. /* iArg: */ 0 },
  113577. #endif
  113578. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  113579. {/* zName: */ "journal_mode",
  113580. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  113581. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  113582. /* ColNames: */ 0, 0,
  113583. /* iArg: */ 0 },
  113584. {/* zName: */ "journal_size_limit",
  113585. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  113586. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  113587. /* ColNames: */ 0, 0,
  113588. /* iArg: */ 0 },
  113589. #endif
  113590. #if defined(SQLITE_HAS_CODEC)
  113591. {/* zName: */ "key",
  113592. /* ePragTyp: */ PragTyp_KEY,
  113593. /* ePragFlg: */ 0,
  113594. /* ColNames: */ 0, 0,
  113595. /* iArg: */ 0 },
  113596. #endif
  113597. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113598. {/* zName: */ "legacy_alter_table",
  113599. /* ePragTyp: */ PragTyp_FLAG,
  113600. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113601. /* ColNames: */ 0, 0,
  113602. /* iArg: */ SQLITE_LegacyAlter },
  113603. {/* zName: */ "legacy_file_format",
  113604. /* ePragTyp: */ PragTyp_FLAG,
  113605. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113606. /* ColNames: */ 0, 0,
  113607. /* iArg: */ SQLITE_LegacyFileFmt },
  113608. #endif
  113609. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  113610. {/* zName: */ "lock_proxy_file",
  113611. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  113612. /* ePragFlg: */ PragFlg_NoColumns1,
  113613. /* ColNames: */ 0, 0,
  113614. /* iArg: */ 0 },
  113615. #endif
  113616. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  113617. {/* zName: */ "lock_status",
  113618. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  113619. /* ePragFlg: */ PragFlg_Result0,
  113620. /* ColNames: */ 43, 2,
  113621. /* iArg: */ 0 },
  113622. #endif
  113623. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  113624. {/* zName: */ "locking_mode",
  113625. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  113626. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  113627. /* ColNames: */ 0, 0,
  113628. /* iArg: */ 0 },
  113629. {/* zName: */ "max_page_count",
  113630. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  113631. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  113632. /* ColNames: */ 0, 0,
  113633. /* iArg: */ 0 },
  113634. {/* zName: */ "mmap_size",
  113635. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  113636. /* ePragFlg: */ 0,
  113637. /* ColNames: */ 0, 0,
  113638. /* iArg: */ 0 },
  113639. #endif
  113640. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  113641. #if !defined(SQLITE_OMIT_VIRTUALTABLE)
  113642. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  113643. {/* zName: */ "module_list",
  113644. /* ePragTyp: */ PragTyp_MODULE_LIST,
  113645. /* ePragFlg: */ PragFlg_Result0,
  113646. /* ColNames: */ 9, 1,
  113647. /* iArg: */ 0 },
  113648. #endif
  113649. #endif
  113650. #endif
  113651. {/* zName: */ "optimize",
  113652. /* ePragTyp: */ PragTyp_OPTIMIZE,
  113653. /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema,
  113654. /* ColNames: */ 0, 0,
  113655. /* iArg: */ 0 },
  113656. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  113657. {/* zName: */ "page_count",
  113658. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  113659. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  113660. /* ColNames: */ 0, 0,
  113661. /* iArg: */ 0 },
  113662. {/* zName: */ "page_size",
  113663. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  113664. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  113665. /* ColNames: */ 0, 0,
  113666. /* iArg: */ 0 },
  113667. #endif
  113668. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113669. #if defined(SQLITE_DEBUG)
  113670. {/* zName: */ "parser_trace",
  113671. /* ePragTyp: */ PragTyp_FLAG,
  113672. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113673. /* ColNames: */ 0, 0,
  113674. /* iArg: */ SQLITE_ParserTrace },
  113675. #endif
  113676. #endif
  113677. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  113678. {/* zName: */ "pragma_list",
  113679. /* ePragTyp: */ PragTyp_PRAGMA_LIST,
  113680. /* ePragFlg: */ PragFlg_Result0,
  113681. /* ColNames: */ 9, 1,
  113682. /* iArg: */ 0 },
  113683. #endif
  113684. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113685. {/* zName: */ "query_only",
  113686. /* ePragTyp: */ PragTyp_FLAG,
  113687. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113688. /* ColNames: */ 0, 0,
  113689. /* iArg: */ SQLITE_QueryOnly },
  113690. #endif
  113691. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  113692. {/* zName: */ "quick_check",
  113693. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  113694. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  113695. /* ColNames: */ 0, 0,
  113696. /* iArg: */ 0 },
  113697. #endif
  113698. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113699. {/* zName: */ "read_uncommitted",
  113700. /* ePragTyp: */ PragTyp_FLAG,
  113701. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113702. /* ColNames: */ 0, 0,
  113703. /* iArg: */ SQLITE_ReadUncommit },
  113704. {/* zName: */ "recursive_triggers",
  113705. /* ePragTyp: */ PragTyp_FLAG,
  113706. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113707. /* ColNames: */ 0, 0,
  113708. /* iArg: */ SQLITE_RecTriggers },
  113709. #endif
  113710. #if defined(SQLITE_HAS_CODEC)
  113711. {/* zName: */ "rekey",
  113712. /* ePragTyp: */ PragTyp_KEY,
  113713. /* ePragFlg: */ 0,
  113714. /* ColNames: */ 0, 0,
  113715. /* iArg: */ 1 },
  113716. #endif
  113717. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113718. {/* zName: */ "reverse_unordered_selects",
  113719. /* ePragTyp: */ PragTyp_FLAG,
  113720. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113721. /* ColNames: */ 0, 0,
  113722. /* iArg: */ SQLITE_ReverseOrder },
  113723. #endif
  113724. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  113725. {/* zName: */ "schema_version",
  113726. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  113727. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  113728. /* ColNames: */ 0, 0,
  113729. /* iArg: */ BTREE_SCHEMA_VERSION },
  113730. #endif
  113731. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  113732. {/* zName: */ "secure_delete",
  113733. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  113734. /* ePragFlg: */ PragFlg_Result0,
  113735. /* ColNames: */ 0, 0,
  113736. /* iArg: */ 0 },
  113737. #endif
  113738. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113739. {/* zName: */ "short_column_names",
  113740. /* ePragTyp: */ PragTyp_FLAG,
  113741. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113742. /* ColNames: */ 0, 0,
  113743. /* iArg: */ SQLITE_ShortColNames },
  113744. #endif
  113745. {/* zName: */ "shrink_memory",
  113746. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  113747. /* ePragFlg: */ PragFlg_NoColumns,
  113748. /* ColNames: */ 0, 0,
  113749. /* iArg: */ 0 },
  113750. {/* zName: */ "soft_heap_limit",
  113751. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  113752. /* ePragFlg: */ PragFlg_Result0,
  113753. /* ColNames: */ 0, 0,
  113754. /* iArg: */ 0 },
  113755. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113756. #if defined(SQLITE_DEBUG)
  113757. {/* zName: */ "sql_trace",
  113758. /* ePragTyp: */ PragTyp_FLAG,
  113759. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113760. /* ColNames: */ 0, 0,
  113761. /* iArg: */ SQLITE_SqlTrace },
  113762. #endif
  113763. #endif
  113764. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
  113765. {/* zName: */ "stats",
  113766. /* ePragTyp: */ PragTyp_STATS,
  113767. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  113768. /* ColNames: */ 21, 5,
  113769. /* iArg: */ 0 },
  113770. #endif
  113771. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  113772. {/* zName: */ "synchronous",
  113773. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  113774. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  113775. /* ColNames: */ 0, 0,
  113776. /* iArg: */ 0 },
  113777. #endif
  113778. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  113779. {/* zName: */ "table_info",
  113780. /* ePragTyp: */ PragTyp_TABLE_INFO,
  113781. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  113782. /* ColNames: */ 8, 6,
  113783. /* iArg: */ 0 },
  113784. {/* zName: */ "table_xinfo",
  113785. /* ePragTyp: */ PragTyp_TABLE_INFO,
  113786. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  113787. /* ColNames: */ 8, 7,
  113788. /* iArg: */ 1 },
  113789. #endif
  113790. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  113791. {/* zName: */ "temp_store",
  113792. /* ePragTyp: */ PragTyp_TEMP_STORE,
  113793. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113794. /* ColNames: */ 0, 0,
  113795. /* iArg: */ 0 },
  113796. {/* zName: */ "temp_store_directory",
  113797. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  113798. /* ePragFlg: */ PragFlg_NoColumns1,
  113799. /* ColNames: */ 0, 0,
  113800. /* iArg: */ 0 },
  113801. #endif
  113802. #if defined(SQLITE_HAS_CODEC)
  113803. {/* zName: */ "textkey",
  113804. /* ePragTyp: */ PragTyp_KEY,
  113805. /* ePragFlg: */ 0,
  113806. /* ColNames: */ 0, 0,
  113807. /* iArg: */ 4 },
  113808. {/* zName: */ "textrekey",
  113809. /* ePragTyp: */ PragTyp_KEY,
  113810. /* ePragFlg: */ 0,
  113811. /* ColNames: */ 0, 0,
  113812. /* iArg: */ 5 },
  113813. #endif
  113814. {/* zName: */ "threads",
  113815. /* ePragTyp: */ PragTyp_THREADS,
  113816. /* ePragFlg: */ PragFlg_Result0,
  113817. /* ColNames: */ 0, 0,
  113818. /* iArg: */ 0 },
  113819. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  113820. {/* zName: */ "user_version",
  113821. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  113822. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  113823. /* ColNames: */ 0, 0,
  113824. /* iArg: */ BTREE_USER_VERSION },
  113825. #endif
  113826. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113827. #if defined(SQLITE_DEBUG)
  113828. {/* zName: */ "vdbe_addoptrace",
  113829. /* ePragTyp: */ PragTyp_FLAG,
  113830. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113831. /* ColNames: */ 0, 0,
  113832. /* iArg: */ SQLITE_VdbeAddopTrace },
  113833. {/* zName: */ "vdbe_debug",
  113834. /* ePragTyp: */ PragTyp_FLAG,
  113835. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113836. /* ColNames: */ 0, 0,
  113837. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  113838. {/* zName: */ "vdbe_eqp",
  113839. /* ePragTyp: */ PragTyp_FLAG,
  113840. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113841. /* ColNames: */ 0, 0,
  113842. /* iArg: */ SQLITE_VdbeEQP },
  113843. {/* zName: */ "vdbe_listing",
  113844. /* ePragTyp: */ PragTyp_FLAG,
  113845. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113846. /* ColNames: */ 0, 0,
  113847. /* iArg: */ SQLITE_VdbeListing },
  113848. {/* zName: */ "vdbe_trace",
  113849. /* ePragTyp: */ PragTyp_FLAG,
  113850. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113851. /* ColNames: */ 0, 0,
  113852. /* iArg: */ SQLITE_VdbeTrace },
  113853. #endif
  113854. #endif
  113855. #if !defined(SQLITE_OMIT_WAL)
  113856. {/* zName: */ "wal_autocheckpoint",
  113857. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  113858. /* ePragFlg: */ 0,
  113859. /* ColNames: */ 0, 0,
  113860. /* iArg: */ 0 },
  113861. {/* zName: */ "wal_checkpoint",
  113862. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  113863. /* ePragFlg: */ PragFlg_NeedSchema,
  113864. /* ColNames: */ 38, 3,
  113865. /* iArg: */ 0 },
  113866. #endif
  113867. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  113868. {/* zName: */ "writable_schema",
  113869. /* ePragTyp: */ PragTyp_FLAG,
  113870. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  113871. /* ColNames: */ 0, 0,
  113872. /* iArg: */ SQLITE_WriteSchema|SQLITE_NoSchemaError },
  113873. #endif
  113874. };
  113875. /* Number of pragmas: 62 on by default, 81 total. */
  113876. /************** End of pragma.h **********************************************/
  113877. /************** Continuing where we left off in pragma.c *********************/
  113878. /*
  113879. ** Interpret the given string as a safety level. Return 0 for OFF,
  113880. ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
  113881. ** unrecognized string argument. The FULL and EXTRA option is disallowed
  113882. ** if the omitFull parameter it 1.
  113883. **
  113884. ** Note that the values returned are one less that the values that
  113885. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  113886. ** to support legacy SQL code. The safety level used to be boolean
  113887. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  113888. */
  113889. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  113890. /* 123456789 123456789 123 */
  113891. static const char zText[] = "onoffalseyestruextrafull";
  113892. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
  113893. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
  113894. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
  113895. /* on no off false yes true extra full */
  113896. int i, n;
  113897. if( sqlite3Isdigit(*z) ){
  113898. return (u8)sqlite3Atoi(z);
  113899. }
  113900. n = sqlite3Strlen30(z);
  113901. for(i=0; i<ArraySize(iLength); i++){
  113902. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
  113903. && (!omitFull || iValue[i]<=1)
  113904. ){
  113905. return iValue[i];
  113906. }
  113907. }
  113908. return dflt;
  113909. }
  113910. /*
  113911. ** Interpret the given string as a boolean value.
  113912. */
  113913. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  113914. return getSafetyLevel(z,1,dflt)!=0;
  113915. }
  113916. /* The sqlite3GetBoolean() function is used by other modules but the
  113917. ** remainder of this file is specific to PRAGMA processing. So omit
  113918. ** the rest of the file if PRAGMAs are omitted from the build.
  113919. */
  113920. #if !defined(SQLITE_OMIT_PRAGMA)
  113921. /*
  113922. ** Interpret the given string as a locking mode value.
  113923. */
  113924. static int getLockingMode(const char *z){
  113925. if( z ){
  113926. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  113927. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  113928. }
  113929. return PAGER_LOCKINGMODE_QUERY;
  113930. }
  113931. #ifndef SQLITE_OMIT_AUTOVACUUM
  113932. /*
  113933. ** Interpret the given string as an auto-vacuum mode value.
  113934. **
  113935. ** The following strings, "none", "full" and "incremental" are
  113936. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  113937. */
  113938. static int getAutoVacuum(const char *z){
  113939. int i;
  113940. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  113941. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  113942. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  113943. i = sqlite3Atoi(z);
  113944. return (u8)((i>=0&&i<=2)?i:0);
  113945. }
  113946. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  113947. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  113948. /*
  113949. ** Interpret the given string as a temp db location. Return 1 for file
  113950. ** backed temporary databases, 2 for the Red-Black tree in memory database
  113951. ** and 0 to use the compile-time default.
  113952. */
  113953. static int getTempStore(const char *z){
  113954. if( z[0]>='0' && z[0]<='2' ){
  113955. return z[0] - '0';
  113956. }else if( sqlite3StrICmp(z, "file")==0 ){
  113957. return 1;
  113958. }else if( sqlite3StrICmp(z, "memory")==0 ){
  113959. return 2;
  113960. }else{
  113961. return 0;
  113962. }
  113963. }
  113964. #endif /* SQLITE_PAGER_PRAGMAS */
  113965. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  113966. /*
  113967. ** Invalidate temp storage, either when the temp storage is changed
  113968. ** from default, or when 'file' and the temp_store_directory has changed
  113969. */
  113970. static int invalidateTempStorage(Parse *pParse){
  113971. sqlite3 *db = pParse->db;
  113972. if( db->aDb[1].pBt!=0 ){
  113973. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  113974. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  113975. "from within a transaction");
  113976. return SQLITE_ERROR;
  113977. }
  113978. sqlite3BtreeClose(db->aDb[1].pBt);
  113979. db->aDb[1].pBt = 0;
  113980. sqlite3ResetAllSchemasOfConnection(db);
  113981. }
  113982. return SQLITE_OK;
  113983. }
  113984. #endif /* SQLITE_PAGER_PRAGMAS */
  113985. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  113986. /*
  113987. ** If the TEMP database is open, close it and mark the database schema
  113988. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  113989. ** or DEFAULT_TEMP_STORE pragmas.
  113990. */
  113991. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  113992. int ts = getTempStore(zStorageType);
  113993. sqlite3 *db = pParse->db;
  113994. if( db->temp_store==ts ) return SQLITE_OK;
  113995. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  113996. return SQLITE_ERROR;
  113997. }
  113998. db->temp_store = (u8)ts;
  113999. return SQLITE_OK;
  114000. }
  114001. #endif /* SQLITE_PAGER_PRAGMAS */
  114002. /*
  114003. ** Set result column names for a pragma.
  114004. */
  114005. static void setPragmaResultColumnNames(
  114006. Vdbe *v, /* The query under construction */
  114007. const PragmaName *pPragma /* The pragma */
  114008. ){
  114009. u8 n = pPragma->nPragCName;
  114010. sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
  114011. if( n==0 ){
  114012. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
  114013. }else{
  114014. int i, j;
  114015. for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
  114016. sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
  114017. }
  114018. }
  114019. }
  114020. /*
  114021. ** Generate code to return a single integer value.
  114022. */
  114023. static void returnSingleInt(Vdbe *v, i64 value){
  114024. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  114025. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  114026. }
  114027. /*
  114028. ** Generate code to return a single text value.
  114029. */
  114030. static void returnSingleText(
  114031. Vdbe *v, /* Prepared statement under construction */
  114032. const char *zValue /* Value to be returned */
  114033. ){
  114034. if( zValue ){
  114035. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  114036. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  114037. }
  114038. }
  114039. /*
  114040. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  114041. ** set these values for all pagers.
  114042. */
  114043. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  114044. static void setAllPagerFlags(sqlite3 *db){
  114045. if( db->autoCommit ){
  114046. Db *pDb = db->aDb;
  114047. int n = db->nDb;
  114048. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  114049. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  114050. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  114051. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  114052. == PAGER_FLAGS_MASK );
  114053. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  114054. while( (n--) > 0 ){
  114055. if( pDb->pBt ){
  114056. sqlite3BtreeSetPagerFlags(pDb->pBt,
  114057. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  114058. }
  114059. pDb++;
  114060. }
  114061. }
  114062. }
  114063. #else
  114064. # define setAllPagerFlags(X) /* no-op */
  114065. #endif
  114066. /*
  114067. ** Return a human-readable name for a constraint resolution action.
  114068. */
  114069. #ifndef SQLITE_OMIT_FOREIGN_KEY
  114070. static const char *actionName(u8 action){
  114071. const char *zName;
  114072. switch( action ){
  114073. case OE_SetNull: zName = "SET NULL"; break;
  114074. case OE_SetDflt: zName = "SET DEFAULT"; break;
  114075. case OE_Cascade: zName = "CASCADE"; break;
  114076. case OE_Restrict: zName = "RESTRICT"; break;
  114077. default: zName = "NO ACTION";
  114078. assert( action==OE_None ); break;
  114079. }
  114080. return zName;
  114081. }
  114082. #endif
  114083. /*
  114084. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  114085. ** defined in pager.h. This function returns the associated lowercase
  114086. ** journal-mode name.
  114087. */
  114088. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  114089. static char * const azModeName[] = {
  114090. "delete", "persist", "off", "truncate", "memory"
  114091. #ifndef SQLITE_OMIT_WAL
  114092. , "wal"
  114093. #endif
  114094. };
  114095. assert( PAGER_JOURNALMODE_DELETE==0 );
  114096. assert( PAGER_JOURNALMODE_PERSIST==1 );
  114097. assert( PAGER_JOURNALMODE_OFF==2 );
  114098. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  114099. assert( PAGER_JOURNALMODE_MEMORY==4 );
  114100. assert( PAGER_JOURNALMODE_WAL==5 );
  114101. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  114102. if( eMode==ArraySize(azModeName) ) return 0;
  114103. return azModeName[eMode];
  114104. }
  114105. /*
  114106. ** Locate a pragma in the aPragmaName[] array.
  114107. */
  114108. static const PragmaName *pragmaLocate(const char *zName){
  114109. int upr, lwr, mid = 0, rc;
  114110. lwr = 0;
  114111. upr = ArraySize(aPragmaName)-1;
  114112. while( lwr<=upr ){
  114113. mid = (lwr+upr)/2;
  114114. rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
  114115. if( rc==0 ) break;
  114116. if( rc<0 ){
  114117. upr = mid - 1;
  114118. }else{
  114119. lwr = mid + 1;
  114120. }
  114121. }
  114122. return lwr>upr ? 0 : &aPragmaName[mid];
  114123. }
  114124. /*
  114125. ** Helper subroutine for PRAGMA integrity_check:
  114126. **
  114127. ** Generate code to output a single-column result row with a value of the
  114128. ** string held in register 3. Decrement the result count in register 1
  114129. ** and halt if the maximum number of result rows have been issued.
  114130. */
  114131. static int integrityCheckResultRow(Vdbe *v){
  114132. int addr;
  114133. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  114134. addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
  114135. VdbeCoverage(v);
  114136. sqlite3VdbeAddOp0(v, OP_Halt);
  114137. return addr;
  114138. }
  114139. /*
  114140. ** Process a pragma statement.
  114141. **
  114142. ** Pragmas are of this form:
  114143. **
  114144. ** PRAGMA [schema.]id [= value]
  114145. **
  114146. ** The identifier might also be a string. The value is a string, and
  114147. ** identifier, or a number. If minusFlag is true, then the value is
  114148. ** a number that was preceded by a minus sign.
  114149. **
  114150. ** If the left side is "database.id" then pId1 is the database name
  114151. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  114152. ** id and pId2 is any empty string.
  114153. */
  114154. SQLITE_PRIVATE void sqlite3Pragma(
  114155. Parse *pParse,
  114156. Token *pId1, /* First part of [schema.]id field */
  114157. Token *pId2, /* Second part of [schema.]id field, or NULL */
  114158. Token *pValue, /* Token for <value>, or NULL */
  114159. int minusFlag /* True if a '-' sign preceded <value> */
  114160. ){
  114161. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  114162. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  114163. const char *zDb = 0; /* The database name */
  114164. Token *pId; /* Pointer to <id> token */
  114165. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  114166. int iDb; /* Database index for <database> */
  114167. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  114168. sqlite3 *db = pParse->db; /* The database connection */
  114169. Db *pDb; /* The specific database being pragmaed */
  114170. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  114171. const PragmaName *pPragma; /* The pragma */
  114172. if( v==0 ) return;
  114173. sqlite3VdbeRunOnlyOnce(v);
  114174. pParse->nMem = 2;
  114175. /* Interpret the [schema.] part of the pragma statement. iDb is the
  114176. ** index of the database this pragma is being applied to in db.aDb[]. */
  114177. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  114178. if( iDb<0 ) return;
  114179. pDb = &db->aDb[iDb];
  114180. /* If the temp database has been explicitly named as part of the
  114181. ** pragma, make sure it is open.
  114182. */
  114183. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  114184. return;
  114185. }
  114186. zLeft = sqlite3NameFromToken(db, pId);
  114187. if( !zLeft ) return;
  114188. if( minusFlag ){
  114189. zRight = sqlite3MPrintf(db, "-%T", pValue);
  114190. }else{
  114191. zRight = sqlite3NameFromToken(db, pValue);
  114192. }
  114193. assert( pId2 );
  114194. zDb = pId2->n>0 ? pDb->zDbSName : 0;
  114195. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  114196. goto pragma_out;
  114197. }
  114198. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  114199. ** connection. If it returns SQLITE_OK, then assume that the VFS
  114200. ** handled the pragma and generate a no-op prepared statement.
  114201. **
  114202. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  114203. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  114204. ** object corresponding to the database file to which the pragma
  114205. ** statement refers.
  114206. **
  114207. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  114208. ** file control is an array of pointers to strings (char**) in which the
  114209. ** second element of the array is the name of the pragma and the third
  114210. ** element is the argument to the pragma or NULL if the pragma has no
  114211. ** argument.
  114212. */
  114213. aFcntl[0] = 0;
  114214. aFcntl[1] = zLeft;
  114215. aFcntl[2] = zRight;
  114216. aFcntl[3] = 0;
  114217. db->busyHandler.nBusy = 0;
  114218. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  114219. if( rc==SQLITE_OK ){
  114220. sqlite3VdbeSetNumCols(v, 1);
  114221. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
  114222. returnSingleText(v, aFcntl[0]);
  114223. sqlite3_free(aFcntl[0]);
  114224. goto pragma_out;
  114225. }
  114226. if( rc!=SQLITE_NOTFOUND ){
  114227. if( aFcntl[0] ){
  114228. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  114229. sqlite3_free(aFcntl[0]);
  114230. }
  114231. pParse->nErr++;
  114232. pParse->rc = rc;
  114233. goto pragma_out;
  114234. }
  114235. /* Locate the pragma in the lookup table */
  114236. pPragma = pragmaLocate(zLeft);
  114237. if( pPragma==0 ) goto pragma_out;
  114238. /* Make sure the database schema is loaded if the pragma requires that */
  114239. if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
  114240. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  114241. }
  114242. /* Register the result column names for pragmas that return results */
  114243. if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
  114244. && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
  114245. ){
  114246. setPragmaResultColumnNames(v, pPragma);
  114247. }
  114248. /* Jump to the appropriate pragma handler */
  114249. switch( pPragma->ePragTyp ){
  114250. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  114251. /*
  114252. ** PRAGMA [schema.]default_cache_size
  114253. ** PRAGMA [schema.]default_cache_size=N
  114254. **
  114255. ** The first form reports the current persistent setting for the
  114256. ** page cache size. The value returned is the maximum number of
  114257. ** pages in the page cache. The second form sets both the current
  114258. ** page cache size value and the persistent page cache size value
  114259. ** stored in the database file.
  114260. **
  114261. ** Older versions of SQLite would set the default cache size to a
  114262. ** negative number to indicate synchronous=OFF. These days, synchronous
  114263. ** is always on by default regardless of the sign of the default cache
  114264. ** size. But continue to take the absolute value of the default cache
  114265. ** size of historical compatibility.
  114266. */
  114267. case PragTyp_DEFAULT_CACHE_SIZE: {
  114268. static const int iLn = VDBE_OFFSET_LINENO(2);
  114269. static const VdbeOpList getCacheSize[] = {
  114270. { OP_Transaction, 0, 0, 0}, /* 0 */
  114271. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  114272. { OP_IfPos, 1, 8, 0},
  114273. { OP_Integer, 0, 2, 0},
  114274. { OP_Subtract, 1, 2, 1},
  114275. { OP_IfPos, 1, 8, 0},
  114276. { OP_Integer, 0, 1, 0}, /* 6 */
  114277. { OP_Noop, 0, 0, 0},
  114278. { OP_ResultRow, 1, 1, 0},
  114279. };
  114280. VdbeOp *aOp;
  114281. sqlite3VdbeUsesBtree(v, iDb);
  114282. if( !zRight ){
  114283. pParse->nMem += 2;
  114284. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
  114285. aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
  114286. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  114287. aOp[0].p1 = iDb;
  114288. aOp[1].p1 = iDb;
  114289. aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
  114290. }else{
  114291. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  114292. sqlite3BeginWriteOperation(pParse, 0, iDb);
  114293. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
  114294. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  114295. pDb->pSchema->cache_size = size;
  114296. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  114297. }
  114298. break;
  114299. }
  114300. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  114301. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  114302. /*
  114303. ** PRAGMA [schema.]page_size
  114304. ** PRAGMA [schema.]page_size=N
  114305. **
  114306. ** The first form reports the current setting for the
  114307. ** database page size in bytes. The second form sets the
  114308. ** database page size value. The value can only be set if
  114309. ** the database has not yet been created.
  114310. */
  114311. case PragTyp_PAGE_SIZE: {
  114312. Btree *pBt = pDb->pBt;
  114313. assert( pBt!=0 );
  114314. if( !zRight ){
  114315. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  114316. returnSingleInt(v, size);
  114317. }else{
  114318. /* Malloc may fail when setting the page-size, as there is an internal
  114319. ** buffer that the pager module resizes using sqlite3_realloc().
  114320. */
  114321. db->nextPagesize = sqlite3Atoi(zRight);
  114322. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  114323. sqlite3OomFault(db);
  114324. }
  114325. }
  114326. break;
  114327. }
  114328. /*
  114329. ** PRAGMA [schema.]secure_delete
  114330. ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
  114331. **
  114332. ** The first form reports the current setting for the
  114333. ** secure_delete flag. The second form changes the secure_delete
  114334. ** flag setting and reports the new value.
  114335. */
  114336. case PragTyp_SECURE_DELETE: {
  114337. Btree *pBt = pDb->pBt;
  114338. int b = -1;
  114339. assert( pBt!=0 );
  114340. if( zRight ){
  114341. if( sqlite3_stricmp(zRight, "fast")==0 ){
  114342. b = 2;
  114343. }else{
  114344. b = sqlite3GetBoolean(zRight, 0);
  114345. }
  114346. }
  114347. if( pId2->n==0 && b>=0 ){
  114348. int ii;
  114349. for(ii=0; ii<db->nDb; ii++){
  114350. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  114351. }
  114352. }
  114353. b = sqlite3BtreeSecureDelete(pBt, b);
  114354. returnSingleInt(v, b);
  114355. break;
  114356. }
  114357. /*
  114358. ** PRAGMA [schema.]max_page_count
  114359. ** PRAGMA [schema.]max_page_count=N
  114360. **
  114361. ** The first form reports the current setting for the
  114362. ** maximum number of pages in the database file. The
  114363. ** second form attempts to change this setting. Both
  114364. ** forms return the current setting.
  114365. **
  114366. ** The absolute value of N is used. This is undocumented and might
  114367. ** change. The only purpose is to provide an easy way to test
  114368. ** the sqlite3AbsInt32() function.
  114369. **
  114370. ** PRAGMA [schema.]page_count
  114371. **
  114372. ** Return the number of pages in the specified database.
  114373. */
  114374. case PragTyp_PAGE_COUNT: {
  114375. int iReg;
  114376. sqlite3CodeVerifySchema(pParse, iDb);
  114377. iReg = ++pParse->nMem;
  114378. if( sqlite3Tolower(zLeft[0])=='p' ){
  114379. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  114380. }else{
  114381. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  114382. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  114383. }
  114384. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  114385. break;
  114386. }
  114387. /*
  114388. ** PRAGMA [schema.]locking_mode
  114389. ** PRAGMA [schema.]locking_mode = (normal|exclusive)
  114390. */
  114391. case PragTyp_LOCKING_MODE: {
  114392. const char *zRet = "normal";
  114393. int eMode = getLockingMode(zRight);
  114394. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  114395. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  114396. ** the current default locking mode (which may be different to
  114397. ** the locking-mode of the main database).
  114398. */
  114399. eMode = db->dfltLockMode;
  114400. }else{
  114401. Pager *pPager;
  114402. if( pId2->n==0 ){
  114403. /* This indicates that no database name was specified as part
  114404. ** of the PRAGMA command. In this case the locking-mode must be
  114405. ** set on all attached databases, as well as the main db file.
  114406. **
  114407. ** Also, the sqlite3.dfltLockMode variable is set so that
  114408. ** any subsequently attached databases also use the specified
  114409. ** locking mode.
  114410. */
  114411. int ii;
  114412. assert(pDb==&db->aDb[0]);
  114413. for(ii=2; ii<db->nDb; ii++){
  114414. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  114415. sqlite3PagerLockingMode(pPager, eMode);
  114416. }
  114417. db->dfltLockMode = (u8)eMode;
  114418. }
  114419. pPager = sqlite3BtreePager(pDb->pBt);
  114420. eMode = sqlite3PagerLockingMode(pPager, eMode);
  114421. }
  114422. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  114423. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  114424. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  114425. zRet = "exclusive";
  114426. }
  114427. returnSingleText(v, zRet);
  114428. break;
  114429. }
  114430. /*
  114431. ** PRAGMA [schema.]journal_mode
  114432. ** PRAGMA [schema.]journal_mode =
  114433. ** (delete|persist|off|truncate|memory|wal|off)
  114434. */
  114435. case PragTyp_JOURNAL_MODE: {
  114436. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  114437. int ii; /* Loop counter */
  114438. if( zRight==0 ){
  114439. /* If there is no "=MODE" part of the pragma, do a query for the
  114440. ** current mode */
  114441. eMode = PAGER_JOURNALMODE_QUERY;
  114442. }else{
  114443. const char *zMode;
  114444. int n = sqlite3Strlen30(zRight);
  114445. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  114446. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  114447. }
  114448. if( !zMode ){
  114449. /* If the "=MODE" part does not match any known journal mode,
  114450. ** then do a query */
  114451. eMode = PAGER_JOURNALMODE_QUERY;
  114452. }
  114453. }
  114454. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  114455. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  114456. iDb = 0;
  114457. pId2->n = 1;
  114458. }
  114459. for(ii=db->nDb-1; ii>=0; ii--){
  114460. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  114461. sqlite3VdbeUsesBtree(v, ii);
  114462. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  114463. }
  114464. }
  114465. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  114466. break;
  114467. }
  114468. /*
  114469. ** PRAGMA [schema.]journal_size_limit
  114470. ** PRAGMA [schema.]journal_size_limit=N
  114471. **
  114472. ** Get or set the size limit on rollback journal files.
  114473. */
  114474. case PragTyp_JOURNAL_SIZE_LIMIT: {
  114475. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  114476. i64 iLimit = -2;
  114477. if( zRight ){
  114478. sqlite3DecOrHexToI64(zRight, &iLimit);
  114479. if( iLimit<-1 ) iLimit = -1;
  114480. }
  114481. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  114482. returnSingleInt(v, iLimit);
  114483. break;
  114484. }
  114485. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  114486. /*
  114487. ** PRAGMA [schema.]auto_vacuum
  114488. ** PRAGMA [schema.]auto_vacuum=N
  114489. **
  114490. ** Get or set the value of the database 'auto-vacuum' parameter.
  114491. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  114492. */
  114493. #ifndef SQLITE_OMIT_AUTOVACUUM
  114494. case PragTyp_AUTO_VACUUM: {
  114495. Btree *pBt = pDb->pBt;
  114496. assert( pBt!=0 );
  114497. if( !zRight ){
  114498. returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
  114499. }else{
  114500. int eAuto = getAutoVacuum(zRight);
  114501. assert( eAuto>=0 && eAuto<=2 );
  114502. db->nextAutovac = (u8)eAuto;
  114503. /* Call SetAutoVacuum() to set initialize the internal auto and
  114504. ** incr-vacuum flags. This is required in case this connection
  114505. ** creates the database file. It is important that it is created
  114506. ** as an auto-vacuum capable db.
  114507. */
  114508. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  114509. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  114510. /* When setting the auto_vacuum mode to either "full" or
  114511. ** "incremental", write the value of meta[6] in the database
  114512. ** file. Before writing to meta[6], check that meta[3] indicates
  114513. ** that this really is an auto-vacuum capable database.
  114514. */
  114515. static const int iLn = VDBE_OFFSET_LINENO(2);
  114516. static const VdbeOpList setMeta6[] = {
  114517. { OP_Transaction, 0, 1, 0}, /* 0 */
  114518. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  114519. { OP_If, 1, 0, 0}, /* 2 */
  114520. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  114521. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
  114522. };
  114523. VdbeOp *aOp;
  114524. int iAddr = sqlite3VdbeCurrentAddr(v);
  114525. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
  114526. aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  114527. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  114528. aOp[0].p1 = iDb;
  114529. aOp[1].p1 = iDb;
  114530. aOp[2].p2 = iAddr+4;
  114531. aOp[4].p1 = iDb;
  114532. aOp[4].p3 = eAuto - 1;
  114533. sqlite3VdbeUsesBtree(v, iDb);
  114534. }
  114535. }
  114536. break;
  114537. }
  114538. #endif
  114539. /*
  114540. ** PRAGMA [schema.]incremental_vacuum(N)
  114541. **
  114542. ** Do N steps of incremental vacuuming on a database.
  114543. */
  114544. #ifndef SQLITE_OMIT_AUTOVACUUM
  114545. case PragTyp_INCREMENTAL_VACUUM: {
  114546. int iLimit, addr;
  114547. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  114548. iLimit = 0x7fffffff;
  114549. }
  114550. sqlite3BeginWriteOperation(pParse, 0, iDb);
  114551. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  114552. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  114553. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  114554. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  114555. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  114556. sqlite3VdbeJumpHere(v, addr);
  114557. break;
  114558. }
  114559. #endif
  114560. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  114561. /*
  114562. ** PRAGMA [schema.]cache_size
  114563. ** PRAGMA [schema.]cache_size=N
  114564. **
  114565. ** The first form reports the current local setting for the
  114566. ** page cache size. The second form sets the local
  114567. ** page cache size value. If N is positive then that is the
  114568. ** number of pages in the cache. If N is negative, then the
  114569. ** number of pages is adjusted so that the cache uses -N kibibytes
  114570. ** of memory.
  114571. */
  114572. case PragTyp_CACHE_SIZE: {
  114573. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  114574. if( !zRight ){
  114575. returnSingleInt(v, pDb->pSchema->cache_size);
  114576. }else{
  114577. int size = sqlite3Atoi(zRight);
  114578. pDb->pSchema->cache_size = size;
  114579. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  114580. }
  114581. break;
  114582. }
  114583. /*
  114584. ** PRAGMA [schema.]cache_spill
  114585. ** PRAGMA cache_spill=BOOLEAN
  114586. ** PRAGMA [schema.]cache_spill=N
  114587. **
  114588. ** The first form reports the current local setting for the
  114589. ** page cache spill size. The second form turns cache spill on
  114590. ** or off. When turnning cache spill on, the size is set to the
  114591. ** current cache_size. The third form sets a spill size that
  114592. ** may be different form the cache size.
  114593. ** If N is positive then that is the
  114594. ** number of pages in the cache. If N is negative, then the
  114595. ** number of pages is adjusted so that the cache uses -N kibibytes
  114596. ** of memory.
  114597. **
  114598. ** If the number of cache_spill pages is less then the number of
  114599. ** cache_size pages, no spilling occurs until the page count exceeds
  114600. ** the number of cache_size pages.
  114601. **
  114602. ** The cache_spill=BOOLEAN setting applies to all attached schemas,
  114603. ** not just the schema specified.
  114604. */
  114605. case PragTyp_CACHE_SPILL: {
  114606. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  114607. if( !zRight ){
  114608. returnSingleInt(v,
  114609. (db->flags & SQLITE_CacheSpill)==0 ? 0 :
  114610. sqlite3BtreeSetSpillSize(pDb->pBt,0));
  114611. }else{
  114612. int size = 1;
  114613. if( sqlite3GetInt32(zRight, &size) ){
  114614. sqlite3BtreeSetSpillSize(pDb->pBt, size);
  114615. }
  114616. if( sqlite3GetBoolean(zRight, size!=0) ){
  114617. db->flags |= SQLITE_CacheSpill;
  114618. }else{
  114619. db->flags &= ~(u64)SQLITE_CacheSpill;
  114620. }
  114621. setAllPagerFlags(db);
  114622. }
  114623. break;
  114624. }
  114625. /*
  114626. ** PRAGMA [schema.]mmap_size(N)
  114627. **
  114628. ** Used to set mapping size limit. The mapping size limit is
  114629. ** used to limit the aggregate size of all memory mapped regions of the
  114630. ** database file. If this parameter is set to zero, then memory mapping
  114631. ** is not used at all. If N is negative, then the default memory map
  114632. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  114633. ** The parameter N is measured in bytes.
  114634. **
  114635. ** This value is advisory. The underlying VFS is free to memory map
  114636. ** as little or as much as it wants. Except, if N is set to 0 then the
  114637. ** upper layers will never invoke the xFetch interfaces to the VFS.
  114638. */
  114639. case PragTyp_MMAP_SIZE: {
  114640. sqlite3_int64 sz;
  114641. #if SQLITE_MAX_MMAP_SIZE>0
  114642. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  114643. if( zRight ){
  114644. int ii;
  114645. sqlite3DecOrHexToI64(zRight, &sz);
  114646. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  114647. if( pId2->n==0 ) db->szMmap = sz;
  114648. for(ii=db->nDb-1; ii>=0; ii--){
  114649. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  114650. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  114651. }
  114652. }
  114653. }
  114654. sz = -1;
  114655. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  114656. #else
  114657. sz = 0;
  114658. rc = SQLITE_OK;
  114659. #endif
  114660. if( rc==SQLITE_OK ){
  114661. returnSingleInt(v, sz);
  114662. }else if( rc!=SQLITE_NOTFOUND ){
  114663. pParse->nErr++;
  114664. pParse->rc = rc;
  114665. }
  114666. break;
  114667. }
  114668. /*
  114669. ** PRAGMA temp_store
  114670. ** PRAGMA temp_store = "default"|"memory"|"file"
  114671. **
  114672. ** Return or set the local value of the temp_store flag. Changing
  114673. ** the local value does not make changes to the disk file and the default
  114674. ** value will be restored the next time the database is opened.
  114675. **
  114676. ** Note that it is possible for the library compile-time options to
  114677. ** override this setting
  114678. */
  114679. case PragTyp_TEMP_STORE: {
  114680. if( !zRight ){
  114681. returnSingleInt(v, db->temp_store);
  114682. }else{
  114683. changeTempStorage(pParse, zRight);
  114684. }
  114685. break;
  114686. }
  114687. /*
  114688. ** PRAGMA temp_store_directory
  114689. ** PRAGMA temp_store_directory = ""|"directory_name"
  114690. **
  114691. ** Return or set the local value of the temp_store_directory flag. Changing
  114692. ** the value sets a specific directory to be used for temporary files.
  114693. ** Setting to a null string reverts to the default temporary directory search.
  114694. ** If temporary directory is changed, then invalidateTempStorage.
  114695. **
  114696. */
  114697. case PragTyp_TEMP_STORE_DIRECTORY: {
  114698. if( !zRight ){
  114699. returnSingleText(v, sqlite3_temp_directory);
  114700. }else{
  114701. #ifndef SQLITE_OMIT_WSD
  114702. if( zRight[0] ){
  114703. int res;
  114704. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  114705. if( rc!=SQLITE_OK || res==0 ){
  114706. sqlite3ErrorMsg(pParse, "not a writable directory");
  114707. goto pragma_out;
  114708. }
  114709. }
  114710. if( SQLITE_TEMP_STORE==0
  114711. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  114712. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  114713. ){
  114714. invalidateTempStorage(pParse);
  114715. }
  114716. sqlite3_free(sqlite3_temp_directory);
  114717. if( zRight[0] ){
  114718. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  114719. }else{
  114720. sqlite3_temp_directory = 0;
  114721. }
  114722. #endif /* SQLITE_OMIT_WSD */
  114723. }
  114724. break;
  114725. }
  114726. #if SQLITE_OS_WIN
  114727. /*
  114728. ** PRAGMA data_store_directory
  114729. ** PRAGMA data_store_directory = ""|"directory_name"
  114730. **
  114731. ** Return or set the local value of the data_store_directory flag. Changing
  114732. ** the value sets a specific directory to be used for database files that
  114733. ** were specified with a relative pathname. Setting to a null string reverts
  114734. ** to the default database directory, which for database files specified with
  114735. ** a relative path will probably be based on the current directory for the
  114736. ** process. Database file specified with an absolute path are not impacted
  114737. ** by this setting, regardless of its value.
  114738. **
  114739. */
  114740. case PragTyp_DATA_STORE_DIRECTORY: {
  114741. if( !zRight ){
  114742. returnSingleText(v, sqlite3_data_directory);
  114743. }else{
  114744. #ifndef SQLITE_OMIT_WSD
  114745. if( zRight[0] ){
  114746. int res;
  114747. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  114748. if( rc!=SQLITE_OK || res==0 ){
  114749. sqlite3ErrorMsg(pParse, "not a writable directory");
  114750. goto pragma_out;
  114751. }
  114752. }
  114753. sqlite3_free(sqlite3_data_directory);
  114754. if( zRight[0] ){
  114755. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  114756. }else{
  114757. sqlite3_data_directory = 0;
  114758. }
  114759. #endif /* SQLITE_OMIT_WSD */
  114760. }
  114761. break;
  114762. }
  114763. #endif
  114764. #if SQLITE_ENABLE_LOCKING_STYLE
  114765. /*
  114766. ** PRAGMA [schema.]lock_proxy_file
  114767. ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
  114768. **
  114769. ** Return or set the value of the lock_proxy_file flag. Changing
  114770. ** the value sets a specific file to be used for database access locks.
  114771. **
  114772. */
  114773. case PragTyp_LOCK_PROXY_FILE: {
  114774. if( !zRight ){
  114775. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  114776. char *proxy_file_path = NULL;
  114777. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  114778. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  114779. &proxy_file_path);
  114780. returnSingleText(v, proxy_file_path);
  114781. }else{
  114782. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  114783. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  114784. int res;
  114785. if( zRight[0] ){
  114786. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  114787. zRight);
  114788. } else {
  114789. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  114790. NULL);
  114791. }
  114792. if( res!=SQLITE_OK ){
  114793. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  114794. goto pragma_out;
  114795. }
  114796. }
  114797. break;
  114798. }
  114799. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  114800. /*
  114801. ** PRAGMA [schema.]synchronous
  114802. ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
  114803. **
  114804. ** Return or set the local value of the synchronous flag. Changing
  114805. ** the local value does not make changes to the disk file and the
  114806. ** default value will be restored the next time the database is
  114807. ** opened.
  114808. */
  114809. case PragTyp_SYNCHRONOUS: {
  114810. if( !zRight ){
  114811. returnSingleInt(v, pDb->safety_level-1);
  114812. }else{
  114813. if( !db->autoCommit ){
  114814. sqlite3ErrorMsg(pParse,
  114815. "Safety level may not be changed inside a transaction");
  114816. }else if( iDb!=1 ){
  114817. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  114818. if( iLevel==0 ) iLevel = 1;
  114819. pDb->safety_level = iLevel;
  114820. pDb->bSyncSet = 1;
  114821. setAllPagerFlags(db);
  114822. }
  114823. }
  114824. break;
  114825. }
  114826. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  114827. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  114828. case PragTyp_FLAG: {
  114829. if( zRight==0 ){
  114830. setPragmaResultColumnNames(v, pPragma);
  114831. returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
  114832. }else{
  114833. u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */
  114834. if( db->autoCommit==0 ){
  114835. /* Foreign key support may not be enabled or disabled while not
  114836. ** in auto-commit mode. */
  114837. mask &= ~(SQLITE_ForeignKeys);
  114838. }
  114839. #if SQLITE_USER_AUTHENTICATION
  114840. if( db->auth.authLevel==UAUTH_User ){
  114841. /* Do not allow non-admin users to modify the schema arbitrarily */
  114842. mask &= ~(SQLITE_WriteSchema);
  114843. }
  114844. #endif
  114845. if( sqlite3GetBoolean(zRight, 0) ){
  114846. db->flags |= mask;
  114847. }else{
  114848. db->flags &= ~mask;
  114849. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  114850. }
  114851. /* Many of the flag-pragmas modify the code generated by the SQL
  114852. ** compiler (eg. count_changes). So add an opcode to expire all
  114853. ** compiled SQL statements after modifying a pragma value.
  114854. */
  114855. sqlite3VdbeAddOp0(v, OP_Expire);
  114856. setAllPagerFlags(db);
  114857. }
  114858. break;
  114859. }
  114860. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  114861. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  114862. /*
  114863. ** PRAGMA table_info(<table>)
  114864. **
  114865. ** Return a single row for each column of the named table. The columns of
  114866. ** the returned data set are:
  114867. **
  114868. ** cid: Column id (numbered from left to right, starting at 0)
  114869. ** name: Column name
  114870. ** type: Column declaration type.
  114871. ** notnull: True if 'NOT NULL' is part of column declaration
  114872. ** dflt_value: The default value for the column, if any.
  114873. ** pk: Non-zero for PK fields.
  114874. */
  114875. case PragTyp_TABLE_INFO: if( zRight ){
  114876. Table *pTab;
  114877. pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
  114878. if( pTab ){
  114879. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  114880. int i, k;
  114881. int nHidden = 0;
  114882. Column *pCol;
  114883. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  114884. pParse->nMem = 7;
  114885. sqlite3CodeVerifySchema(pParse, iTabDb);
  114886. sqlite3ViewGetColumnNames(pParse, pTab);
  114887. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  114888. int isHidden = IsHiddenColumn(pCol);
  114889. if( isHidden && pPragma->iArg==0 ){
  114890. nHidden++;
  114891. continue;
  114892. }
  114893. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  114894. k = 0;
  114895. }else if( pPk==0 ){
  114896. k = 1;
  114897. }else{
  114898. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  114899. }
  114900. assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
  114901. sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
  114902. i-nHidden,
  114903. pCol->zName,
  114904. sqlite3ColumnType(pCol,""),
  114905. pCol->notNull ? 1 : 0,
  114906. pCol->pDflt ? pCol->pDflt->u.zToken : 0,
  114907. k,
  114908. isHidden);
  114909. }
  114910. }
  114911. }
  114912. break;
  114913. #ifdef SQLITE_DEBUG
  114914. case PragTyp_STATS: {
  114915. Index *pIdx;
  114916. HashElem *i;
  114917. pParse->nMem = 5;
  114918. sqlite3CodeVerifySchema(pParse, iDb);
  114919. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  114920. Table *pTab = sqliteHashData(i);
  114921. sqlite3VdbeMultiLoad(v, 1, "ssiii",
  114922. pTab->zName,
  114923. 0,
  114924. pTab->szTabRow,
  114925. pTab->nRowLogEst,
  114926. pTab->tabFlags);
  114927. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  114928. sqlite3VdbeMultiLoad(v, 2, "siiiX",
  114929. pIdx->zName,
  114930. pIdx->szIdxRow,
  114931. pIdx->aiRowLogEst[0],
  114932. pIdx->hasStat1);
  114933. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  114934. }
  114935. }
  114936. }
  114937. break;
  114938. #endif
  114939. case PragTyp_INDEX_INFO: if( zRight ){
  114940. Index *pIdx;
  114941. Table *pTab;
  114942. pIdx = sqlite3FindIndex(db, zRight, zDb);
  114943. if( pIdx ){
  114944. int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
  114945. int i;
  114946. int mx;
  114947. if( pPragma->iArg ){
  114948. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  114949. mx = pIdx->nColumn;
  114950. pParse->nMem = 6;
  114951. }else{
  114952. /* PRAGMA index_info (legacy version) */
  114953. mx = pIdx->nKeyCol;
  114954. pParse->nMem = 3;
  114955. }
  114956. pTab = pIdx->pTable;
  114957. sqlite3CodeVerifySchema(pParse, iIdxDb);
  114958. assert( pParse->nMem<=pPragma->nPragCName );
  114959. for(i=0; i<mx; i++){
  114960. i16 cnum = pIdx->aiColumn[i];
  114961. sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
  114962. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  114963. if( pPragma->iArg ){
  114964. sqlite3VdbeMultiLoad(v, 4, "isiX",
  114965. pIdx->aSortOrder[i],
  114966. pIdx->azColl[i],
  114967. i<pIdx->nKeyCol);
  114968. }
  114969. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  114970. }
  114971. }
  114972. }
  114973. break;
  114974. case PragTyp_INDEX_LIST: if( zRight ){
  114975. Index *pIdx;
  114976. Table *pTab;
  114977. int i;
  114978. pTab = sqlite3FindTable(db, zRight, zDb);
  114979. if( pTab ){
  114980. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  114981. pParse->nMem = 5;
  114982. sqlite3CodeVerifySchema(pParse, iTabDb);
  114983. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  114984. const char *azOrigin[] = { "c", "u", "pk" };
  114985. sqlite3VdbeMultiLoad(v, 1, "isisi",
  114986. i,
  114987. pIdx->zName,
  114988. IsUniqueIndex(pIdx),
  114989. azOrigin[pIdx->idxType],
  114990. pIdx->pPartIdxWhere!=0);
  114991. }
  114992. }
  114993. }
  114994. break;
  114995. case PragTyp_DATABASE_LIST: {
  114996. int i;
  114997. pParse->nMem = 3;
  114998. for(i=0; i<db->nDb; i++){
  114999. if( db->aDb[i].pBt==0 ) continue;
  115000. assert( db->aDb[i].zDbSName!=0 );
  115001. sqlite3VdbeMultiLoad(v, 1, "iss",
  115002. i,
  115003. db->aDb[i].zDbSName,
  115004. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  115005. }
  115006. }
  115007. break;
  115008. case PragTyp_COLLATION_LIST: {
  115009. int i = 0;
  115010. HashElem *p;
  115011. pParse->nMem = 2;
  115012. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  115013. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  115014. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  115015. }
  115016. }
  115017. break;
  115018. #ifdef SQLITE_INTROSPECTION_PRAGMAS
  115019. case PragTyp_FUNCTION_LIST: {
  115020. int i;
  115021. HashElem *j;
  115022. FuncDef *p;
  115023. pParse->nMem = 2;
  115024. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  115025. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
  115026. if( p->funcFlags & SQLITE_FUNC_INTERNAL ) continue;
  115027. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
  115028. }
  115029. }
  115030. for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
  115031. p = (FuncDef*)sqliteHashData(j);
  115032. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
  115033. }
  115034. }
  115035. break;
  115036. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115037. case PragTyp_MODULE_LIST: {
  115038. HashElem *j;
  115039. pParse->nMem = 1;
  115040. for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
  115041. Module *pMod = (Module*)sqliteHashData(j);
  115042. sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
  115043. }
  115044. }
  115045. break;
  115046. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  115047. case PragTyp_PRAGMA_LIST: {
  115048. int i;
  115049. for(i=0; i<ArraySize(aPragmaName); i++){
  115050. sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
  115051. }
  115052. }
  115053. break;
  115054. #endif /* SQLITE_INTROSPECTION_PRAGMAS */
  115055. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  115056. #ifndef SQLITE_OMIT_FOREIGN_KEY
  115057. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  115058. FKey *pFK;
  115059. Table *pTab;
  115060. pTab = sqlite3FindTable(db, zRight, zDb);
  115061. if( pTab ){
  115062. pFK = pTab->pFKey;
  115063. if( pFK ){
  115064. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  115065. int i = 0;
  115066. pParse->nMem = 8;
  115067. sqlite3CodeVerifySchema(pParse, iTabDb);
  115068. while(pFK){
  115069. int j;
  115070. for(j=0; j<pFK->nCol; j++){
  115071. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  115072. i,
  115073. j,
  115074. pFK->zTo,
  115075. pTab->aCol[pFK->aCol[j].iFrom].zName,
  115076. pFK->aCol[j].zCol,
  115077. actionName(pFK->aAction[1]), /* ON UPDATE */
  115078. actionName(pFK->aAction[0]), /* ON DELETE */
  115079. "NONE");
  115080. }
  115081. ++i;
  115082. pFK = pFK->pNextFrom;
  115083. }
  115084. }
  115085. }
  115086. }
  115087. break;
  115088. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  115089. #ifndef SQLITE_OMIT_FOREIGN_KEY
  115090. #ifndef SQLITE_OMIT_TRIGGER
  115091. case PragTyp_FOREIGN_KEY_CHECK: {
  115092. FKey *pFK; /* A foreign key constraint */
  115093. Table *pTab; /* Child table contain "REFERENCES" keyword */
  115094. Table *pParent; /* Parent table that child points to */
  115095. Index *pIdx; /* Index in the parent table */
  115096. int i; /* Loop counter: Foreign key number for pTab */
  115097. int j; /* Loop counter: Field of the foreign key */
  115098. HashElem *k; /* Loop counter: Next table in schema */
  115099. int x; /* result variable */
  115100. int regResult; /* 3 registers to hold a result row */
  115101. int regKey; /* Register to hold key for checking the FK */
  115102. int regRow; /* Registers to hold a row from pTab */
  115103. int addrTop; /* Top of a loop checking foreign keys */
  115104. int addrOk; /* Jump here if the key is OK */
  115105. int *aiCols; /* child to parent column mapping */
  115106. regResult = pParse->nMem+1;
  115107. pParse->nMem += 4;
  115108. regKey = ++pParse->nMem;
  115109. regRow = ++pParse->nMem;
  115110. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  115111. while( k ){
  115112. int iTabDb;
  115113. if( zRight ){
  115114. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  115115. k = 0;
  115116. }else{
  115117. pTab = (Table*)sqliteHashData(k);
  115118. k = sqliteHashNext(k);
  115119. }
  115120. if( pTab==0 || pTab->pFKey==0 ) continue;
  115121. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  115122. sqlite3CodeVerifySchema(pParse, iTabDb);
  115123. sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName);
  115124. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  115125. sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead);
  115126. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  115127. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  115128. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  115129. if( pParent==0 ) continue;
  115130. pIdx = 0;
  115131. sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName);
  115132. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  115133. if( x==0 ){
  115134. if( pIdx==0 ){
  115135. sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead);
  115136. }else{
  115137. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb);
  115138. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  115139. }
  115140. }else{
  115141. k = 0;
  115142. break;
  115143. }
  115144. }
  115145. assert( pParse->nErr>0 || pFK==0 );
  115146. if( pFK ) break;
  115147. if( pParse->nTab<i ) pParse->nTab = i;
  115148. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  115149. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  115150. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  115151. pIdx = 0;
  115152. aiCols = 0;
  115153. if( pParent ){
  115154. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  115155. assert( x==0 );
  115156. }
  115157. addrOk = sqlite3VdbeMakeLabel(pParse);
  115158. /* Generate code to read the child key values into registers
  115159. ** regRow..regRow+n. If any of the child key values are NULL, this
  115160. ** row cannot cause an FK violation. Jump directly to addrOk in
  115161. ** this case. */
  115162. for(j=0; j<pFK->nCol; j++){
  115163. int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
  115164. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
  115165. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  115166. }
  115167. /* Generate code to query the parent index for a matching parent
  115168. ** key. If a match is found, jump to addrOk. */
  115169. if( pIdx ){
  115170. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  115171. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  115172. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  115173. VdbeCoverage(v);
  115174. }else if( pParent ){
  115175. int jmp = sqlite3VdbeCurrentAddr(v)+2;
  115176. sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
  115177. sqlite3VdbeGoto(v, addrOk);
  115178. assert( pFK->nCol==1 );
  115179. }
  115180. /* Generate code to report an FK violation to the caller. */
  115181. if( HasRowid(pTab) ){
  115182. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  115183. }else{
  115184. sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
  115185. }
  115186. sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
  115187. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  115188. sqlite3VdbeResolveLabel(v, addrOk);
  115189. sqlite3DbFree(db, aiCols);
  115190. }
  115191. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  115192. sqlite3VdbeJumpHere(v, addrTop);
  115193. }
  115194. }
  115195. break;
  115196. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  115197. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  115198. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  115199. ** used will be case sensitive or not depending on the RHS.
  115200. */
  115201. case PragTyp_CASE_SENSITIVE_LIKE: {
  115202. if( zRight ){
  115203. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  115204. }
  115205. }
  115206. break;
  115207. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  115208. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  115209. #endif
  115210. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  115211. /* PRAGMA integrity_check
  115212. ** PRAGMA integrity_check(N)
  115213. ** PRAGMA quick_check
  115214. ** PRAGMA quick_check(N)
  115215. **
  115216. ** Verify the integrity of the database.
  115217. **
  115218. ** The "quick_check" is reduced version of
  115219. ** integrity_check designed to detect most database corruption
  115220. ** without the overhead of cross-checking indexes. Quick_check
  115221. ** is linear time wherease integrity_check is O(NlogN).
  115222. */
  115223. case PragTyp_INTEGRITY_CHECK: {
  115224. int i, j, addr, mxErr;
  115225. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  115226. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  115227. ** then iDb is set to the index of the database identified by <db>.
  115228. ** In this case, the integrity of database iDb only is verified by
  115229. ** the VDBE created below.
  115230. **
  115231. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  115232. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  115233. ** to -1 here, to indicate that the VDBE should verify the integrity
  115234. ** of all attached databases. */
  115235. assert( iDb>=0 );
  115236. assert( iDb==0 || pId2->z );
  115237. if( pId2->z==0 ) iDb = -1;
  115238. /* Initialize the VDBE program */
  115239. pParse->nMem = 6;
  115240. /* Set the maximum error count */
  115241. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  115242. if( zRight ){
  115243. sqlite3GetInt32(zRight, &mxErr);
  115244. if( mxErr<=0 ){
  115245. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  115246. }
  115247. }
  115248. sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
  115249. /* Do an integrity check on each database file */
  115250. for(i=0; i<db->nDb; i++){
  115251. HashElem *x; /* For looping over tables in the schema */
  115252. Hash *pTbls; /* Set of all tables in the schema */
  115253. int *aRoot; /* Array of root page numbers of all btrees */
  115254. int cnt = 0; /* Number of entries in aRoot[] */
  115255. int mxIdx = 0; /* Maximum number of indexes for any table */
  115256. if( OMIT_TEMPDB && i==1 ) continue;
  115257. if( iDb>=0 && i!=iDb ) continue;
  115258. sqlite3CodeVerifySchema(pParse, i);
  115259. /* Do an integrity check of the B-Tree
  115260. **
  115261. ** Begin by finding the root pages numbers
  115262. ** for all tables and indices in the database.
  115263. */
  115264. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  115265. pTbls = &db->aDb[i].pSchema->tblHash;
  115266. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  115267. Table *pTab = sqliteHashData(x); /* Current table */
  115268. Index *pIdx; /* An index on pTab */
  115269. int nIdx; /* Number of indexes on pTab */
  115270. if( HasRowid(pTab) ) cnt++;
  115271. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
  115272. if( nIdx>mxIdx ) mxIdx = nIdx;
  115273. }
  115274. aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
  115275. if( aRoot==0 ) break;
  115276. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  115277. Table *pTab = sqliteHashData(x);
  115278. Index *pIdx;
  115279. if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
  115280. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  115281. aRoot[++cnt] = pIdx->tnum;
  115282. }
  115283. }
  115284. aRoot[0] = cnt;
  115285. /* Make sure sufficient number of registers have been allocated */
  115286. pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
  115287. sqlite3ClearTempRegCache(pParse);
  115288. /* Do the b-tree integrity checks */
  115289. sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
  115290. sqlite3VdbeChangeP5(v, (u8)i);
  115291. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  115292. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  115293. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
  115294. P4_DYNAMIC);
  115295. sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
  115296. integrityCheckResultRow(v);
  115297. sqlite3VdbeJumpHere(v, addr);
  115298. /* Make sure all the indices are constructed correctly.
  115299. */
  115300. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  115301. Table *pTab = sqliteHashData(x);
  115302. Index *pIdx, *pPk;
  115303. Index *pPrior = 0;
  115304. int loopTop;
  115305. int iDataCur, iIdxCur;
  115306. int r1 = -1;
  115307. if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
  115308. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  115309. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
  115310. 1, 0, &iDataCur, &iIdxCur);
  115311. /* reg[7] counts the number of entries in the table.
  115312. ** reg[8+i] counts the number of entries in the i-th index
  115313. */
  115314. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  115315. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  115316. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  115317. }
  115318. assert( pParse->nMem>=8+j );
  115319. assert( sqlite3NoTempsInRange(pParse,1,7+j) );
  115320. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  115321. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  115322. if( !isQuick ){
  115323. /* Sanity check on record header decoding */
  115324. sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
  115325. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  115326. }
  115327. /* Verify that all NOT NULL columns really are NOT NULL */
  115328. for(j=0; j<pTab->nCol; j++){
  115329. char *zErr;
  115330. int jmp2;
  115331. if( j==pTab->iPKey ) continue;
  115332. if( pTab->aCol[j].notNull==0 ) continue;
  115333. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  115334. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  115335. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  115336. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  115337. pTab->aCol[j].zName);
  115338. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  115339. integrityCheckResultRow(v);
  115340. sqlite3VdbeJumpHere(v, jmp2);
  115341. }
  115342. /* Verify CHECK constraints */
  115343. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  115344. ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
  115345. if( db->mallocFailed==0 ){
  115346. int addrCkFault = sqlite3VdbeMakeLabel(pParse);
  115347. int addrCkOk = sqlite3VdbeMakeLabel(pParse);
  115348. char *zErr;
  115349. int k;
  115350. pParse->iSelfTab = iDataCur + 1;
  115351. for(k=pCheck->nExpr-1; k>0; k--){
  115352. sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
  115353. }
  115354. sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
  115355. SQLITE_JUMPIFNULL);
  115356. sqlite3VdbeResolveLabel(v, addrCkFault);
  115357. pParse->iSelfTab = 0;
  115358. zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
  115359. pTab->zName);
  115360. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  115361. integrityCheckResultRow(v);
  115362. sqlite3VdbeResolveLabel(v, addrCkOk);
  115363. }
  115364. sqlite3ExprListDelete(db, pCheck);
  115365. }
  115366. if( !isQuick ){ /* Omit the remaining tests for quick_check */
  115367. /* Validate index entries for the current row */
  115368. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  115369. int jmp2, jmp3, jmp4, jmp5;
  115370. int ckUniq = sqlite3VdbeMakeLabel(pParse);
  115371. if( pPk==pIdx ) continue;
  115372. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  115373. pPrior, r1);
  115374. pPrior = pIdx;
  115375. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
  115376. /* Verify that an index entry exists for the current table row */
  115377. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  115378. pIdx->nColumn); VdbeCoverage(v);
  115379. sqlite3VdbeLoadString(v, 3, "row ");
  115380. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  115381. sqlite3VdbeLoadString(v, 4, " missing from index ");
  115382. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  115383. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  115384. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  115385. jmp4 = integrityCheckResultRow(v);
  115386. sqlite3VdbeJumpHere(v, jmp2);
  115387. /* For UNIQUE indexes, verify that only one entry exists with the
  115388. ** current key. The entry is unique if (1) any column is NULL
  115389. ** or (2) the next entry has a different key */
  115390. if( IsUniqueIndex(pIdx) ){
  115391. int uniqOk = sqlite3VdbeMakeLabel(pParse);
  115392. int jmp6;
  115393. int kk;
  115394. for(kk=0; kk<pIdx->nKeyCol; kk++){
  115395. int iCol = pIdx->aiColumn[kk];
  115396. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  115397. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  115398. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  115399. VdbeCoverage(v);
  115400. }
  115401. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  115402. sqlite3VdbeGoto(v, uniqOk);
  115403. sqlite3VdbeJumpHere(v, jmp6);
  115404. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  115405. pIdx->nKeyCol); VdbeCoverage(v);
  115406. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  115407. sqlite3VdbeGoto(v, jmp5);
  115408. sqlite3VdbeResolveLabel(v, uniqOk);
  115409. }
  115410. sqlite3VdbeJumpHere(v, jmp4);
  115411. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  115412. }
  115413. }
  115414. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  115415. sqlite3VdbeJumpHere(v, loopTop-1);
  115416. #ifndef SQLITE_OMIT_BTREECOUNT
  115417. if( !isQuick ){
  115418. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  115419. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  115420. if( pPk==pIdx ) continue;
  115421. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  115422. addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
  115423. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  115424. sqlite3VdbeLoadString(v, 4, pIdx->zName);
  115425. sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
  115426. integrityCheckResultRow(v);
  115427. sqlite3VdbeJumpHere(v, addr);
  115428. }
  115429. }
  115430. #endif /* SQLITE_OMIT_BTREECOUNT */
  115431. }
  115432. }
  115433. {
  115434. static const int iLn = VDBE_OFFSET_LINENO(2);
  115435. static const VdbeOpList endCode[] = {
  115436. { OP_AddImm, 1, 0, 0}, /* 0 */
  115437. { OP_IfNotZero, 1, 4, 0}, /* 1 */
  115438. { OP_String8, 0, 3, 0}, /* 2 */
  115439. { OP_ResultRow, 3, 1, 0}, /* 3 */
  115440. { OP_Halt, 0, 0, 0}, /* 4 */
  115441. { OP_String8, 0, 3, 0}, /* 5 */
  115442. { OP_Goto, 0, 3, 0}, /* 6 */
  115443. };
  115444. VdbeOp *aOp;
  115445. aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  115446. if( aOp ){
  115447. aOp[0].p2 = 1-mxErr;
  115448. aOp[2].p4type = P4_STATIC;
  115449. aOp[2].p4.z = "ok";
  115450. aOp[5].p4type = P4_STATIC;
  115451. aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
  115452. }
  115453. sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
  115454. }
  115455. }
  115456. break;
  115457. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  115458. #ifndef SQLITE_OMIT_UTF16
  115459. /*
  115460. ** PRAGMA encoding
  115461. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  115462. **
  115463. ** In its first form, this pragma returns the encoding of the main
  115464. ** database. If the database is not initialized, it is initialized now.
  115465. **
  115466. ** The second form of this pragma is a no-op if the main database file
  115467. ** has not already been initialized. In this case it sets the default
  115468. ** encoding that will be used for the main database file if a new file
  115469. ** is created. If an existing main database file is opened, then the
  115470. ** default text encoding for the existing database is used.
  115471. **
  115472. ** In all cases new databases created using the ATTACH command are
  115473. ** created to use the same default text encoding as the main database. If
  115474. ** the main database has not been initialized and/or created when ATTACH
  115475. ** is executed, this is done before the ATTACH operation.
  115476. **
  115477. ** In the second form this pragma sets the text encoding to be used in
  115478. ** new database files created using this database handle. It is only
  115479. ** useful if invoked immediately after the main database i
  115480. */
  115481. case PragTyp_ENCODING: {
  115482. static const struct EncName {
  115483. char *zName;
  115484. u8 enc;
  115485. } encnames[] = {
  115486. { "UTF8", SQLITE_UTF8 },
  115487. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  115488. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  115489. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  115490. { "UTF16le", SQLITE_UTF16LE },
  115491. { "UTF16be", SQLITE_UTF16BE },
  115492. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  115493. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  115494. { 0, 0 }
  115495. };
  115496. const struct EncName *pEnc;
  115497. if( !zRight ){ /* "PRAGMA encoding" */
  115498. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  115499. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  115500. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  115501. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  115502. returnSingleText(v, encnames[ENC(pParse->db)].zName);
  115503. }else{ /* "PRAGMA encoding = XXX" */
  115504. /* Only change the value of sqlite.enc if the database handle is not
  115505. ** initialized. If the main database exists, the new sqlite.enc value
  115506. ** will be overwritten when the schema is next loaded. If it does not
  115507. ** already exists, it will be created to use the new encoding value.
  115508. */
  115509. if(
  115510. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  115511. DbHasProperty(db, 0, DB_Empty)
  115512. ){
  115513. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  115514. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  115515. SCHEMA_ENC(db) = ENC(db) =
  115516. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  115517. break;
  115518. }
  115519. }
  115520. if( !pEnc->zName ){
  115521. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  115522. }
  115523. }
  115524. }
  115525. }
  115526. break;
  115527. #endif /* SQLITE_OMIT_UTF16 */
  115528. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  115529. /*
  115530. ** PRAGMA [schema.]schema_version
  115531. ** PRAGMA [schema.]schema_version = <integer>
  115532. **
  115533. ** PRAGMA [schema.]user_version
  115534. ** PRAGMA [schema.]user_version = <integer>
  115535. **
  115536. ** PRAGMA [schema.]freelist_count
  115537. **
  115538. ** PRAGMA [schema.]data_version
  115539. **
  115540. ** PRAGMA [schema.]application_id
  115541. ** PRAGMA [schema.]application_id = <integer>
  115542. **
  115543. ** The pragma's schema_version and user_version are used to set or get
  115544. ** the value of the schema-version and user-version, respectively. Both
  115545. ** the schema-version and the user-version are 32-bit signed integers
  115546. ** stored in the database header.
  115547. **
  115548. ** The schema-cookie is usually only manipulated internally by SQLite. It
  115549. ** is incremented by SQLite whenever the database schema is modified (by
  115550. ** creating or dropping a table or index). The schema version is used by
  115551. ** SQLite each time a query is executed to ensure that the internal cache
  115552. ** of the schema used when compiling the SQL query matches the schema of
  115553. ** the database against which the compiled query is actually executed.
  115554. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  115555. ** the schema-version is potentially dangerous and may lead to program
  115556. ** crashes or database corruption. Use with caution!
  115557. **
  115558. ** The user-version is not used internally by SQLite. It may be used by
  115559. ** applications for any purpose.
  115560. */
  115561. case PragTyp_HEADER_VALUE: {
  115562. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  115563. sqlite3VdbeUsesBtree(v, iDb);
  115564. if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
  115565. /* Write the specified cookie value */
  115566. static const VdbeOpList setCookie[] = {
  115567. { OP_Transaction, 0, 1, 0}, /* 0 */
  115568. { OP_SetCookie, 0, 0, 0}, /* 1 */
  115569. };
  115570. VdbeOp *aOp;
  115571. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
  115572. aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  115573. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  115574. aOp[0].p1 = iDb;
  115575. aOp[1].p1 = iDb;
  115576. aOp[1].p2 = iCookie;
  115577. aOp[1].p3 = sqlite3Atoi(zRight);
  115578. }else{
  115579. /* Read the specified cookie value */
  115580. static const VdbeOpList readCookie[] = {
  115581. { OP_Transaction, 0, 0, 0}, /* 0 */
  115582. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  115583. { OP_ResultRow, 1, 1, 0}
  115584. };
  115585. VdbeOp *aOp;
  115586. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
  115587. aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
  115588. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  115589. aOp[0].p1 = iDb;
  115590. aOp[1].p1 = iDb;
  115591. aOp[1].p3 = iCookie;
  115592. sqlite3VdbeReusable(v);
  115593. }
  115594. }
  115595. break;
  115596. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  115597. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  115598. /*
  115599. ** PRAGMA compile_options
  115600. **
  115601. ** Return the names of all compile-time options used in this build,
  115602. ** one option per row.
  115603. */
  115604. case PragTyp_COMPILE_OPTIONS: {
  115605. int i = 0;
  115606. const char *zOpt;
  115607. pParse->nMem = 1;
  115608. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  115609. sqlite3VdbeLoadString(v, 1, zOpt);
  115610. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  115611. }
  115612. sqlite3VdbeReusable(v);
  115613. }
  115614. break;
  115615. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  115616. #ifndef SQLITE_OMIT_WAL
  115617. /*
  115618. ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
  115619. **
  115620. ** Checkpoint the database.
  115621. */
  115622. case PragTyp_WAL_CHECKPOINT: {
  115623. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  115624. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  115625. if( zRight ){
  115626. if( sqlite3StrICmp(zRight, "full")==0 ){
  115627. eMode = SQLITE_CHECKPOINT_FULL;
  115628. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  115629. eMode = SQLITE_CHECKPOINT_RESTART;
  115630. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  115631. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  115632. }
  115633. }
  115634. pParse->nMem = 3;
  115635. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  115636. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  115637. }
  115638. break;
  115639. /*
  115640. ** PRAGMA wal_autocheckpoint
  115641. ** PRAGMA wal_autocheckpoint = N
  115642. **
  115643. ** Configure a database connection to automatically checkpoint a database
  115644. ** after accumulating N frames in the log. Or query for the current value
  115645. ** of N.
  115646. */
  115647. case PragTyp_WAL_AUTOCHECKPOINT: {
  115648. if( zRight ){
  115649. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  115650. }
  115651. returnSingleInt(v,
  115652. db->xWalCallback==sqlite3WalDefaultHook ?
  115653. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  115654. }
  115655. break;
  115656. #endif
  115657. /*
  115658. ** PRAGMA shrink_memory
  115659. **
  115660. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  115661. ** connection on which it is invoked to free up as much memory as it
  115662. ** can, by calling sqlite3_db_release_memory().
  115663. */
  115664. case PragTyp_SHRINK_MEMORY: {
  115665. sqlite3_db_release_memory(db);
  115666. break;
  115667. }
  115668. /*
  115669. ** PRAGMA optimize
  115670. ** PRAGMA optimize(MASK)
  115671. ** PRAGMA schema.optimize
  115672. ** PRAGMA schema.optimize(MASK)
  115673. **
  115674. ** Attempt to optimize the database. All schemas are optimized in the first
  115675. ** two forms, and only the specified schema is optimized in the latter two.
  115676. **
  115677. ** The details of optimizations performed by this pragma are expected
  115678. ** to change and improve over time. Applications should anticipate that
  115679. ** this pragma will perform new optimizations in future releases.
  115680. **
  115681. ** The optional argument is a bitmask of optimizations to perform:
  115682. **
  115683. ** 0x0001 Debugging mode. Do not actually perform any optimizations
  115684. ** but instead return one line of text for each optimization
  115685. ** that would have been done. Off by default.
  115686. **
  115687. ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
  115688. ** See below for additional information.
  115689. **
  115690. ** 0x0004 (Not yet implemented) Record usage and performance
  115691. ** information from the current session in the
  115692. ** database file so that it will be available to "optimize"
  115693. ** pragmas run by future database connections.
  115694. **
  115695. ** 0x0008 (Not yet implemented) Create indexes that might have
  115696. ** been helpful to recent queries
  115697. **
  115698. ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
  115699. ** of the optimizations listed above except Debug Mode, including new
  115700. ** optimizations that have not yet been invented. If new optimizations are
  115701. ** ever added that should be off by default, those off-by-default
  115702. ** optimizations will have bitmasks of 0x10000 or larger.
  115703. **
  115704. ** DETERMINATION OF WHEN TO RUN ANALYZE
  115705. **
  115706. ** In the current implementation, a table is analyzed if only if all of
  115707. ** the following are true:
  115708. **
  115709. ** (1) MASK bit 0x02 is set.
  115710. **
  115711. ** (2) The query planner used sqlite_stat1-style statistics for one or
  115712. ** more indexes of the table at some point during the lifetime of
  115713. ** the current connection.
  115714. **
  115715. ** (3) One or more indexes of the table are currently unanalyzed OR
  115716. ** the number of rows in the table has increased by 25 times or more
  115717. ** since the last time ANALYZE was run.
  115718. **
  115719. ** The rules for when tables are analyzed are likely to change in
  115720. ** future releases.
  115721. */
  115722. case PragTyp_OPTIMIZE: {
  115723. int iDbLast; /* Loop termination point for the schema loop */
  115724. int iTabCur; /* Cursor for a table whose size needs checking */
  115725. HashElem *k; /* Loop over tables of a schema */
  115726. Schema *pSchema; /* The current schema */
  115727. Table *pTab; /* A table in the schema */
  115728. Index *pIdx; /* An index of the table */
  115729. LogEst szThreshold; /* Size threshold above which reanalysis is needd */
  115730. char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
  115731. u32 opMask; /* Mask of operations to perform */
  115732. if( zRight ){
  115733. opMask = (u32)sqlite3Atoi(zRight);
  115734. if( (opMask & 0x02)==0 ) break;
  115735. }else{
  115736. opMask = 0xfffe;
  115737. }
  115738. iTabCur = pParse->nTab++;
  115739. for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
  115740. if( iDb==1 ) continue;
  115741. sqlite3CodeVerifySchema(pParse, iDb);
  115742. pSchema = db->aDb[iDb].pSchema;
  115743. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  115744. pTab = (Table*)sqliteHashData(k);
  115745. /* If table pTab has not been used in a way that would benefit from
  115746. ** having analysis statistics during the current session, then skip it.
  115747. ** This also has the effect of skipping virtual tables and views */
  115748. if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
  115749. /* Reanalyze if the table is 25 times larger than the last analysis */
  115750. szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
  115751. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  115752. if( !pIdx->hasStat1 ){
  115753. szThreshold = 0; /* Always analyze if any index lacks statistics */
  115754. break;
  115755. }
  115756. }
  115757. if( szThreshold ){
  115758. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  115759. sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
  115760. sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
  115761. VdbeCoverage(v);
  115762. }
  115763. zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
  115764. db->aDb[iDb].zDbSName, pTab->zName);
  115765. if( opMask & 0x01 ){
  115766. int r1 = sqlite3GetTempReg(pParse);
  115767. sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
  115768. sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
  115769. }else{
  115770. sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
  115771. }
  115772. }
  115773. }
  115774. sqlite3VdbeAddOp0(v, OP_Expire);
  115775. break;
  115776. }
  115777. /*
  115778. ** PRAGMA busy_timeout
  115779. ** PRAGMA busy_timeout = N
  115780. **
  115781. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  115782. ** if one is set. If no busy handler or a different busy handler is set
  115783. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  115784. ** disables the timeout.
  115785. */
  115786. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  115787. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  115788. if( zRight ){
  115789. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  115790. }
  115791. returnSingleInt(v, db->busyTimeout);
  115792. break;
  115793. }
  115794. /*
  115795. ** PRAGMA soft_heap_limit
  115796. ** PRAGMA soft_heap_limit = N
  115797. **
  115798. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  115799. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  115800. ** specified and is a non-negative integer.
  115801. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  115802. ** returns the same integer that would be returned by the
  115803. ** sqlite3_soft_heap_limit64(-1) C-language function.
  115804. */
  115805. case PragTyp_SOFT_HEAP_LIMIT: {
  115806. sqlite3_int64 N;
  115807. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  115808. sqlite3_soft_heap_limit64(N);
  115809. }
  115810. returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
  115811. break;
  115812. }
  115813. /*
  115814. ** PRAGMA threads
  115815. ** PRAGMA threads = N
  115816. **
  115817. ** Configure the maximum number of worker threads. Return the new
  115818. ** maximum, which might be less than requested.
  115819. */
  115820. case PragTyp_THREADS: {
  115821. sqlite3_int64 N;
  115822. if( zRight
  115823. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  115824. && N>=0
  115825. ){
  115826. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  115827. }
  115828. returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  115829. break;
  115830. }
  115831. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  115832. /*
  115833. ** Report the current state of file logs for all databases
  115834. */
  115835. case PragTyp_LOCK_STATUS: {
  115836. static const char *const azLockName[] = {
  115837. "unlocked", "shared", "reserved", "pending", "exclusive"
  115838. };
  115839. int i;
  115840. pParse->nMem = 2;
  115841. for(i=0; i<db->nDb; i++){
  115842. Btree *pBt;
  115843. const char *zState = "unknown";
  115844. int j;
  115845. if( db->aDb[i].zDbSName==0 ) continue;
  115846. pBt = db->aDb[i].pBt;
  115847. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  115848. zState = "closed";
  115849. }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
  115850. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  115851. zState = azLockName[j];
  115852. }
  115853. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
  115854. }
  115855. break;
  115856. }
  115857. #endif
  115858. #ifdef SQLITE_HAS_CODEC
  115859. /* Pragma iArg
  115860. ** ---------- ------
  115861. ** key 0
  115862. ** rekey 1
  115863. ** hexkey 2
  115864. ** hexrekey 3
  115865. ** textkey 4
  115866. ** textrekey 5
  115867. */
  115868. case PragTyp_KEY: {
  115869. if( zRight ){
  115870. int n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1;
  115871. if( (pPragma->iArg & 1)==0 ){
  115872. sqlite3_key_v2(db, zDb, zRight, n);
  115873. }else{
  115874. sqlite3_rekey_v2(db, zDb, zRight, n);
  115875. }
  115876. }
  115877. break;
  115878. }
  115879. case PragTyp_HEXKEY: {
  115880. if( zRight ){
  115881. u8 iByte;
  115882. int i;
  115883. char zKey[40];
  115884. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  115885. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  115886. if( (i&1)!=0 ) zKey[i/2] = iByte;
  115887. }
  115888. if( (pPragma->iArg & 1)==0 ){
  115889. sqlite3_key_v2(db, zDb, zKey, i/2);
  115890. }else{
  115891. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  115892. }
  115893. }
  115894. break;
  115895. }
  115896. #endif
  115897. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  115898. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  115899. #ifdef SQLITE_HAS_CODEC
  115900. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  115901. sqlite3_activate_see(&zRight[4]);
  115902. }
  115903. #endif
  115904. #ifdef SQLITE_ENABLE_CEROD
  115905. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  115906. sqlite3_activate_cerod(&zRight[6]);
  115907. }
  115908. #endif
  115909. }
  115910. break;
  115911. #endif
  115912. } /* End of the PRAGMA switch */
  115913. /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
  115914. ** purpose is to execute assert() statements to verify that if the
  115915. ** PragFlg_NoColumns1 flag is set and the caller specified an argument
  115916. ** to the PRAGMA, the implementation has not added any OP_ResultRow
  115917. ** instructions to the VM. */
  115918. if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
  115919. sqlite3VdbeVerifyNoResultRow(v);
  115920. }
  115921. pragma_out:
  115922. sqlite3DbFree(db, zLeft);
  115923. sqlite3DbFree(db, zRight);
  115924. }
  115925. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115926. /*****************************************************************************
  115927. ** Implementation of an eponymous virtual table that runs a pragma.
  115928. **
  115929. */
  115930. typedef struct PragmaVtab PragmaVtab;
  115931. typedef struct PragmaVtabCursor PragmaVtabCursor;
  115932. struct PragmaVtab {
  115933. sqlite3_vtab base; /* Base class. Must be first */
  115934. sqlite3 *db; /* The database connection to which it belongs */
  115935. const PragmaName *pName; /* Name of the pragma */
  115936. u8 nHidden; /* Number of hidden columns */
  115937. u8 iHidden; /* Index of the first hidden column */
  115938. };
  115939. struct PragmaVtabCursor {
  115940. sqlite3_vtab_cursor base; /* Base class. Must be first */
  115941. sqlite3_stmt *pPragma; /* The pragma statement to run */
  115942. sqlite_int64 iRowid; /* Current rowid */
  115943. char *azArg[2]; /* Value of the argument and schema */
  115944. };
  115945. /*
  115946. ** Pragma virtual table module xConnect method.
  115947. */
  115948. static int pragmaVtabConnect(
  115949. sqlite3 *db,
  115950. void *pAux,
  115951. int argc, const char *const*argv,
  115952. sqlite3_vtab **ppVtab,
  115953. char **pzErr
  115954. ){
  115955. const PragmaName *pPragma = (const PragmaName*)pAux;
  115956. PragmaVtab *pTab = 0;
  115957. int rc;
  115958. int i, j;
  115959. char cSep = '(';
  115960. StrAccum acc;
  115961. char zBuf[200];
  115962. UNUSED_PARAMETER(argc);
  115963. UNUSED_PARAMETER(argv);
  115964. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  115965. sqlite3_str_appendall(&acc, "CREATE TABLE x");
  115966. for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
  115967. sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
  115968. cSep = ',';
  115969. }
  115970. if( i==0 ){
  115971. sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
  115972. i++;
  115973. }
  115974. j = 0;
  115975. if( pPragma->mPragFlg & PragFlg_Result1 ){
  115976. sqlite3_str_appendall(&acc, ",arg HIDDEN");
  115977. j++;
  115978. }
  115979. if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
  115980. sqlite3_str_appendall(&acc, ",schema HIDDEN");
  115981. j++;
  115982. }
  115983. sqlite3_str_append(&acc, ")", 1);
  115984. sqlite3StrAccumFinish(&acc);
  115985. assert( strlen(zBuf) < sizeof(zBuf)-1 );
  115986. rc = sqlite3_declare_vtab(db, zBuf);
  115987. if( rc==SQLITE_OK ){
  115988. pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
  115989. if( pTab==0 ){
  115990. rc = SQLITE_NOMEM;
  115991. }else{
  115992. memset(pTab, 0, sizeof(PragmaVtab));
  115993. pTab->pName = pPragma;
  115994. pTab->db = db;
  115995. pTab->iHidden = i;
  115996. pTab->nHidden = j;
  115997. }
  115998. }else{
  115999. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  116000. }
  116001. *ppVtab = (sqlite3_vtab*)pTab;
  116002. return rc;
  116003. }
  116004. /*
  116005. ** Pragma virtual table module xDisconnect method.
  116006. */
  116007. static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
  116008. PragmaVtab *pTab = (PragmaVtab*)pVtab;
  116009. sqlite3_free(pTab);
  116010. return SQLITE_OK;
  116011. }
  116012. /* Figure out the best index to use to search a pragma virtual table.
  116013. **
  116014. ** There are not really any index choices. But we want to encourage the
  116015. ** query planner to give == constraints on as many hidden parameters as
  116016. ** possible, and especially on the first hidden parameter. So return a
  116017. ** high cost if hidden parameters are unconstrained.
  116018. */
  116019. static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  116020. PragmaVtab *pTab = (PragmaVtab*)tab;
  116021. const struct sqlite3_index_constraint *pConstraint;
  116022. int i, j;
  116023. int seen[2];
  116024. pIdxInfo->estimatedCost = (double)1;
  116025. if( pTab->nHidden==0 ){ return SQLITE_OK; }
  116026. pConstraint = pIdxInfo->aConstraint;
  116027. seen[0] = 0;
  116028. seen[1] = 0;
  116029. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  116030. if( pConstraint->usable==0 ) continue;
  116031. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  116032. if( pConstraint->iColumn < pTab->iHidden ) continue;
  116033. j = pConstraint->iColumn - pTab->iHidden;
  116034. assert( j < 2 );
  116035. seen[j] = i+1;
  116036. }
  116037. if( seen[0]==0 ){
  116038. pIdxInfo->estimatedCost = (double)2147483647;
  116039. pIdxInfo->estimatedRows = 2147483647;
  116040. return SQLITE_OK;
  116041. }
  116042. j = seen[0]-1;
  116043. pIdxInfo->aConstraintUsage[j].argvIndex = 1;
  116044. pIdxInfo->aConstraintUsage[j].omit = 1;
  116045. if( seen[1]==0 ) return SQLITE_OK;
  116046. pIdxInfo->estimatedCost = (double)20;
  116047. pIdxInfo->estimatedRows = 20;
  116048. j = seen[1]-1;
  116049. pIdxInfo->aConstraintUsage[j].argvIndex = 2;
  116050. pIdxInfo->aConstraintUsage[j].omit = 1;
  116051. return SQLITE_OK;
  116052. }
  116053. /* Create a new cursor for the pragma virtual table */
  116054. static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
  116055. PragmaVtabCursor *pCsr;
  116056. pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
  116057. if( pCsr==0 ) return SQLITE_NOMEM;
  116058. memset(pCsr, 0, sizeof(PragmaVtabCursor));
  116059. pCsr->base.pVtab = pVtab;
  116060. *ppCursor = &pCsr->base;
  116061. return SQLITE_OK;
  116062. }
  116063. /* Clear all content from pragma virtual table cursor. */
  116064. static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
  116065. int i;
  116066. sqlite3_finalize(pCsr->pPragma);
  116067. pCsr->pPragma = 0;
  116068. for(i=0; i<ArraySize(pCsr->azArg); i++){
  116069. sqlite3_free(pCsr->azArg[i]);
  116070. pCsr->azArg[i] = 0;
  116071. }
  116072. }
  116073. /* Close a pragma virtual table cursor */
  116074. static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
  116075. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
  116076. pragmaVtabCursorClear(pCsr);
  116077. sqlite3_free(pCsr);
  116078. return SQLITE_OK;
  116079. }
  116080. /* Advance the pragma virtual table cursor to the next row */
  116081. static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
  116082. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  116083. int rc = SQLITE_OK;
  116084. /* Increment the xRowid value */
  116085. pCsr->iRowid++;
  116086. assert( pCsr->pPragma );
  116087. if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
  116088. rc = sqlite3_finalize(pCsr->pPragma);
  116089. pCsr->pPragma = 0;
  116090. pragmaVtabCursorClear(pCsr);
  116091. }
  116092. return rc;
  116093. }
  116094. /*
  116095. ** Pragma virtual table module xFilter method.
  116096. */
  116097. static int pragmaVtabFilter(
  116098. sqlite3_vtab_cursor *pVtabCursor,
  116099. int idxNum, const char *idxStr,
  116100. int argc, sqlite3_value **argv
  116101. ){
  116102. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  116103. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  116104. int rc;
  116105. int i, j;
  116106. StrAccum acc;
  116107. char *zSql;
  116108. UNUSED_PARAMETER(idxNum);
  116109. UNUSED_PARAMETER(idxStr);
  116110. pragmaVtabCursorClear(pCsr);
  116111. j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
  116112. for(i=0; i<argc; i++, j++){
  116113. const char *zText = (const char*)sqlite3_value_text(argv[i]);
  116114. assert( j<ArraySize(pCsr->azArg) );
  116115. assert( pCsr->azArg[j]==0 );
  116116. if( zText ){
  116117. pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
  116118. if( pCsr->azArg[j]==0 ){
  116119. return SQLITE_NOMEM;
  116120. }
  116121. }
  116122. }
  116123. sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
  116124. sqlite3_str_appendall(&acc, "PRAGMA ");
  116125. if( pCsr->azArg[1] ){
  116126. sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
  116127. }
  116128. sqlite3_str_appendall(&acc, pTab->pName->zName);
  116129. if( pCsr->azArg[0] ){
  116130. sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
  116131. }
  116132. zSql = sqlite3StrAccumFinish(&acc);
  116133. if( zSql==0 ) return SQLITE_NOMEM;
  116134. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
  116135. sqlite3_free(zSql);
  116136. if( rc!=SQLITE_OK ){
  116137. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  116138. return rc;
  116139. }
  116140. return pragmaVtabNext(pVtabCursor);
  116141. }
  116142. /*
  116143. ** Pragma virtual table module xEof method.
  116144. */
  116145. static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
  116146. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  116147. return (pCsr->pPragma==0);
  116148. }
  116149. /* The xColumn method simply returns the corresponding column from
  116150. ** the PRAGMA.
  116151. */
  116152. static int pragmaVtabColumn(
  116153. sqlite3_vtab_cursor *pVtabCursor,
  116154. sqlite3_context *ctx,
  116155. int i
  116156. ){
  116157. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  116158. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  116159. if( i<pTab->iHidden ){
  116160. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
  116161. }else{
  116162. sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
  116163. }
  116164. return SQLITE_OK;
  116165. }
  116166. /*
  116167. ** Pragma virtual table module xRowid method.
  116168. */
  116169. static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
  116170. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  116171. *p = pCsr->iRowid;
  116172. return SQLITE_OK;
  116173. }
  116174. /* The pragma virtual table object */
  116175. static const sqlite3_module pragmaVtabModule = {
  116176. 0, /* iVersion */
  116177. 0, /* xCreate - create a table */
  116178. pragmaVtabConnect, /* xConnect - connect to an existing table */
  116179. pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
  116180. pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
  116181. 0, /* xDestroy - Drop a table */
  116182. pragmaVtabOpen, /* xOpen - open a cursor */
  116183. pragmaVtabClose, /* xClose - close a cursor */
  116184. pragmaVtabFilter, /* xFilter - configure scan constraints */
  116185. pragmaVtabNext, /* xNext - advance a cursor */
  116186. pragmaVtabEof, /* xEof */
  116187. pragmaVtabColumn, /* xColumn - read data */
  116188. pragmaVtabRowid, /* xRowid - read data */
  116189. 0, /* xUpdate - write data */
  116190. 0, /* xBegin - begin transaction */
  116191. 0, /* xSync - sync transaction */
  116192. 0, /* xCommit - commit transaction */
  116193. 0, /* xRollback - rollback transaction */
  116194. 0, /* xFindFunction - function overloading */
  116195. 0, /* xRename - rename the table */
  116196. 0, /* xSavepoint */
  116197. 0, /* xRelease */
  116198. 0, /* xRollbackTo */
  116199. 0 /* xShadowName */
  116200. };
  116201. /*
  116202. ** Check to see if zTabName is really the name of a pragma. If it is,
  116203. ** then register an eponymous virtual table for that pragma and return
  116204. ** a pointer to the Module object for the new virtual table.
  116205. */
  116206. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
  116207. const PragmaName *pName;
  116208. assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
  116209. pName = pragmaLocate(zName+7);
  116210. if( pName==0 ) return 0;
  116211. if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
  116212. assert( sqlite3HashFind(&db->aModule, zName)==0 );
  116213. return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
  116214. }
  116215. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  116216. #endif /* SQLITE_OMIT_PRAGMA */
  116217. /************** End of pragma.c **********************************************/
  116218. /************** Begin file prepare.c *****************************************/
  116219. /*
  116220. ** 2005 May 25
  116221. **
  116222. ** The author disclaims copyright to this source code. In place of
  116223. ** a legal notice, here is a blessing:
  116224. **
  116225. ** May you do good and not evil.
  116226. ** May you find forgiveness for yourself and forgive others.
  116227. ** May you share freely, never taking more than you give.
  116228. **
  116229. *************************************************************************
  116230. ** This file contains the implementation of the sqlite3_prepare()
  116231. ** interface, and routines that contribute to loading the database schema
  116232. ** from disk.
  116233. */
  116234. /* #include "sqliteInt.h" */
  116235. /*
  116236. ** Fill the InitData structure with an error message that indicates
  116237. ** that the database is corrupt.
  116238. */
  116239. static void corruptSchema(
  116240. InitData *pData, /* Initialization context */
  116241. const char *zObj, /* Object being parsed at the point of error */
  116242. const char *zExtra /* Error information */
  116243. ){
  116244. sqlite3 *db = pData->db;
  116245. if( db->mallocFailed ){
  116246. pData->rc = SQLITE_NOMEM_BKPT;
  116247. }else if( pData->pzErrMsg[0]!=0 ){
  116248. /* A error message has already been generated. Do not overwrite it */
  116249. }else if( pData->mInitFlags & INITFLAG_AlterTable ){
  116250. *pData->pzErrMsg = sqlite3DbStrDup(db, zExtra);
  116251. pData->rc = SQLITE_ERROR;
  116252. }else if( db->flags & SQLITE_WriteSchema ){
  116253. pData->rc = SQLITE_CORRUPT_BKPT;
  116254. }else{
  116255. char *z;
  116256. if( zObj==0 ) zObj = "?";
  116257. z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
  116258. if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
  116259. *pData->pzErrMsg = z;
  116260. pData->rc = SQLITE_CORRUPT_BKPT;
  116261. }
  116262. }
  116263. /*
  116264. ** Check to see if any sibling index (another index on the same table)
  116265. ** of pIndex has the same root page number, and if it does, return true.
  116266. ** This would indicate a corrupt schema.
  116267. */
  116268. SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index *pIndex){
  116269. Index *p;
  116270. for(p=pIndex->pTable->pIndex; p; p=p->pNext){
  116271. if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;
  116272. }
  116273. return 0;
  116274. }
  116275. /*
  116276. ** This is the callback routine for the code that initializes the
  116277. ** database. See sqlite3Init() below for additional information.
  116278. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  116279. **
  116280. ** Each callback contains the following information:
  116281. **
  116282. ** argv[0] = name of thing being created
  116283. ** argv[1] = root page number for table or index. 0 for trigger or view.
  116284. ** argv[2] = SQL text for the CREATE statement.
  116285. **
  116286. */
  116287. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  116288. InitData *pData = (InitData*)pInit;
  116289. sqlite3 *db = pData->db;
  116290. int iDb = pData->iDb;
  116291. assert( argc==3 );
  116292. UNUSED_PARAMETER2(NotUsed, argc);
  116293. assert( sqlite3_mutex_held(db->mutex) );
  116294. DbClearProperty(db, iDb, DB_Empty);
  116295. pData->nInitRow++;
  116296. if( db->mallocFailed ){
  116297. corruptSchema(pData, argv[0], 0);
  116298. return 1;
  116299. }
  116300. assert( iDb>=0 && iDb<db->nDb );
  116301. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  116302. if( argv[1]==0 ){
  116303. corruptSchema(pData, argv[0], 0);
  116304. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  116305. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  116306. ** But because db->init.busy is set to 1, no VDBE code is generated
  116307. ** or executed. All the parser does is build the internal data
  116308. ** structures that describe the table, index, or view.
  116309. */
  116310. int rc;
  116311. u8 saved_iDb = db->init.iDb;
  116312. sqlite3_stmt *pStmt;
  116313. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  116314. assert( db->init.busy );
  116315. db->init.iDb = iDb;
  116316. db->init.newTnum = sqlite3Atoi(argv[1]);
  116317. db->init.orphanTrigger = 0;
  116318. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  116319. rc = db->errCode;
  116320. assert( (rc&0xFF)==(rcp&0xFF) );
  116321. db->init.iDb = saved_iDb;
  116322. /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
  116323. if( SQLITE_OK!=rc ){
  116324. if( db->init.orphanTrigger ){
  116325. assert( iDb==1 );
  116326. }else{
  116327. pData->rc = rc;
  116328. if( rc==SQLITE_NOMEM ){
  116329. sqlite3OomFault(db);
  116330. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  116331. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  116332. }
  116333. }
  116334. }
  116335. sqlite3_finalize(pStmt);
  116336. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  116337. corruptSchema(pData, argv[0], 0);
  116338. }else{
  116339. /* If the SQL column is blank it means this is an index that
  116340. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  116341. ** constraint for a CREATE TABLE. The index should have already
  116342. ** been created when we processed the CREATE TABLE. All we have
  116343. ** to do here is record the root page number for that index.
  116344. */
  116345. Index *pIndex;
  116346. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
  116347. if( pIndex==0
  116348. || sqlite3GetInt32(argv[1],&pIndex->tnum)==0
  116349. || pIndex->tnum<2
  116350. || sqlite3IndexHasDuplicateRootPage(pIndex)
  116351. ){
  116352. corruptSchema(pData, argv[0], pIndex?"invalid rootpage":"orphan index");
  116353. }
  116354. }
  116355. return 0;
  116356. }
  116357. /*
  116358. ** Attempt to read the database schema and initialize internal
  116359. ** data structures for a single database file. The index of the
  116360. ** database file is given by iDb. iDb==0 is used for the main
  116361. ** database. iDb==1 should never be used. iDb>=2 is used for
  116362. ** auxiliary databases. Return one of the SQLITE_ error codes to
  116363. ** indicate success or failure.
  116364. */
  116365. SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){
  116366. int rc;
  116367. int i;
  116368. #ifndef SQLITE_OMIT_DEPRECATED
  116369. int size;
  116370. #endif
  116371. Db *pDb;
  116372. char const *azArg[4];
  116373. int meta[5];
  116374. InitData initData;
  116375. const char *zMasterName;
  116376. int openedTransaction = 0;
  116377. assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
  116378. assert( iDb>=0 && iDb<db->nDb );
  116379. assert( db->aDb[iDb].pSchema );
  116380. assert( sqlite3_mutex_held(db->mutex) );
  116381. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  116382. db->init.busy = 1;
  116383. /* Construct the in-memory representation schema tables (sqlite_master or
  116384. ** sqlite_temp_master) by invoking the parser directly. The appropriate
  116385. ** table name will be inserted automatically by the parser so we can just
  116386. ** use the abbreviation "x" here. The parser will also automatically tag
  116387. ** the schema table as read-only. */
  116388. azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
  116389. azArg[1] = "1";
  116390. azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
  116391. "rootpage int,sql text)";
  116392. azArg[3] = 0;
  116393. initData.db = db;
  116394. initData.iDb = iDb;
  116395. initData.rc = SQLITE_OK;
  116396. initData.pzErrMsg = pzErrMsg;
  116397. initData.mInitFlags = mFlags;
  116398. initData.nInitRow = 0;
  116399. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  116400. if( initData.rc ){
  116401. rc = initData.rc;
  116402. goto error_out;
  116403. }
  116404. /* Create a cursor to hold the database open
  116405. */
  116406. pDb = &db->aDb[iDb];
  116407. if( pDb->pBt==0 ){
  116408. assert( iDb==1 );
  116409. DbSetProperty(db, 1, DB_SchemaLoaded);
  116410. rc = SQLITE_OK;
  116411. goto error_out;
  116412. }
  116413. /* If there is not already a read-only (or read-write) transaction opened
  116414. ** on the b-tree database, open one now. If a transaction is opened, it
  116415. ** will be closed before this function returns. */
  116416. sqlite3BtreeEnter(pDb->pBt);
  116417. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  116418. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
  116419. if( rc!=SQLITE_OK ){
  116420. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  116421. goto initone_error_out;
  116422. }
  116423. openedTransaction = 1;
  116424. }
  116425. /* Get the database meta information.
  116426. **
  116427. ** Meta values are as follows:
  116428. ** meta[0] Schema cookie. Changes with each schema change.
  116429. ** meta[1] File format of schema layer.
  116430. ** meta[2] Size of the page cache.
  116431. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  116432. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  116433. ** meta[5] User version
  116434. ** meta[6] Incremental vacuum mode
  116435. ** meta[7] unused
  116436. ** meta[8] unused
  116437. ** meta[9] unused
  116438. **
  116439. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  116440. ** the possible values of meta[4].
  116441. */
  116442. for(i=0; i<ArraySize(meta); i++){
  116443. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  116444. }
  116445. if( (db->flags & SQLITE_ResetDatabase)!=0 ){
  116446. memset(meta, 0, sizeof(meta));
  116447. }
  116448. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  116449. /* If opening a non-empty database, check the text encoding. For the
  116450. ** main database, set sqlite3.enc to the encoding of the main database.
  116451. ** For an attached db, it is an error if the encoding is not the same
  116452. ** as sqlite3.enc.
  116453. */
  116454. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  116455. if( iDb==0 ){
  116456. #ifndef SQLITE_OMIT_UTF16
  116457. u8 encoding;
  116458. /* If opening the main database, set ENC(db). */
  116459. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  116460. if( encoding==0 ) encoding = SQLITE_UTF8;
  116461. ENC(db) = encoding;
  116462. #else
  116463. ENC(db) = SQLITE_UTF8;
  116464. #endif
  116465. }else{
  116466. /* If opening an attached database, the encoding much match ENC(db) */
  116467. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  116468. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  116469. " text encoding as main database");
  116470. rc = SQLITE_ERROR;
  116471. goto initone_error_out;
  116472. }
  116473. }
  116474. }else{
  116475. DbSetProperty(db, iDb, DB_Empty);
  116476. }
  116477. pDb->pSchema->enc = ENC(db);
  116478. if( pDb->pSchema->cache_size==0 ){
  116479. #ifndef SQLITE_OMIT_DEPRECATED
  116480. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  116481. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  116482. pDb->pSchema->cache_size = size;
  116483. #else
  116484. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  116485. #endif
  116486. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  116487. }
  116488. /*
  116489. ** file_format==1 Version 3.0.0.
  116490. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  116491. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  116492. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  116493. */
  116494. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  116495. if( pDb->pSchema->file_format==0 ){
  116496. pDb->pSchema->file_format = 1;
  116497. }
  116498. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  116499. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  116500. rc = SQLITE_ERROR;
  116501. goto initone_error_out;
  116502. }
  116503. /* Ticket #2804: When we open a database in the newer file format,
  116504. ** clear the legacy_file_format pragma flag so that a VACUUM will
  116505. ** not downgrade the database and thus invalidate any descending
  116506. ** indices that the user might have created.
  116507. */
  116508. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  116509. db->flags &= ~(u64)SQLITE_LegacyFileFmt;
  116510. }
  116511. /* Read the schema information out of the schema tables
  116512. */
  116513. assert( db->init.busy );
  116514. {
  116515. char *zSql;
  116516. zSql = sqlite3MPrintf(db,
  116517. "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
  116518. db->aDb[iDb].zDbSName, zMasterName);
  116519. #ifndef SQLITE_OMIT_AUTHORIZATION
  116520. {
  116521. sqlite3_xauth xAuth;
  116522. xAuth = db->xAuth;
  116523. db->xAuth = 0;
  116524. #endif
  116525. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  116526. #ifndef SQLITE_OMIT_AUTHORIZATION
  116527. db->xAuth = xAuth;
  116528. }
  116529. #endif
  116530. if( rc==SQLITE_OK ) rc = initData.rc;
  116531. sqlite3DbFree(db, zSql);
  116532. #ifndef SQLITE_OMIT_ANALYZE
  116533. if( rc==SQLITE_OK ){
  116534. sqlite3AnalysisLoad(db, iDb);
  116535. }
  116536. #endif
  116537. }
  116538. if( db->mallocFailed ){
  116539. rc = SQLITE_NOMEM_BKPT;
  116540. sqlite3ResetAllSchemasOfConnection(db);
  116541. }
  116542. if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){
  116543. /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider
  116544. ** the schema loaded, even if errors occurred. In this situation the
  116545. ** current sqlite3_prepare() operation will fail, but the following one
  116546. ** will attempt to compile the supplied statement against whatever subset
  116547. ** of the schema was loaded before the error occurred. The primary
  116548. ** purpose of this is to allow access to the sqlite_master table
  116549. ** even when its contents have been corrupted.
  116550. */
  116551. DbSetProperty(db, iDb, DB_SchemaLoaded);
  116552. rc = SQLITE_OK;
  116553. }
  116554. /* Jump here for an error that occurs after successfully allocating
  116555. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  116556. ** before that point, jump to error_out.
  116557. */
  116558. initone_error_out:
  116559. if( openedTransaction ){
  116560. sqlite3BtreeCommit(pDb->pBt);
  116561. }
  116562. sqlite3BtreeLeave(pDb->pBt);
  116563. error_out:
  116564. if( rc ){
  116565. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  116566. sqlite3OomFault(db);
  116567. }
  116568. sqlite3ResetOneSchema(db, iDb);
  116569. }
  116570. db->init.busy = 0;
  116571. return rc;
  116572. }
  116573. /*
  116574. ** Initialize all database files - the main database file, the file
  116575. ** used to store temporary tables, and any additional database files
  116576. ** created using ATTACH statements. Return a success code. If an
  116577. ** error occurs, write an error message into *pzErrMsg.
  116578. **
  116579. ** After a database is initialized, the DB_SchemaLoaded bit is set
  116580. ** bit is set in the flags field of the Db structure. If the database
  116581. ** file was of zero-length, then the DB_Empty flag is also set.
  116582. */
  116583. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  116584. int i, rc;
  116585. int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
  116586. assert( sqlite3_mutex_held(db->mutex) );
  116587. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  116588. assert( db->init.busy==0 );
  116589. ENC(db) = SCHEMA_ENC(db);
  116590. assert( db->nDb>0 );
  116591. /* Do the main schema first */
  116592. if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
  116593. rc = sqlite3InitOne(db, 0, pzErrMsg, 0);
  116594. if( rc ) return rc;
  116595. }
  116596. /* All other schemas after the main schema. The "temp" schema must be last */
  116597. for(i=db->nDb-1; i>0; i--){
  116598. assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
  116599. if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
  116600. rc = sqlite3InitOne(db, i, pzErrMsg, 0);
  116601. if( rc ) return rc;
  116602. }
  116603. }
  116604. if( commit_internal ){
  116605. sqlite3CommitInternalChanges(db);
  116606. }
  116607. return SQLITE_OK;
  116608. }
  116609. /*
  116610. ** This routine is a no-op if the database schema is already initialized.
  116611. ** Otherwise, the schema is loaded. An error code is returned.
  116612. */
  116613. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  116614. int rc = SQLITE_OK;
  116615. sqlite3 *db = pParse->db;
  116616. assert( sqlite3_mutex_held(db->mutex) );
  116617. if( !db->init.busy ){
  116618. rc = sqlite3Init(db, &pParse->zErrMsg);
  116619. if( rc!=SQLITE_OK ){
  116620. pParse->rc = rc;
  116621. pParse->nErr++;
  116622. }else if( db->noSharedCache ){
  116623. db->mDbFlags |= DBFLAG_SchemaKnownOk;
  116624. }
  116625. }
  116626. return rc;
  116627. }
  116628. /*
  116629. ** Check schema cookies in all databases. If any cookie is out
  116630. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  116631. ** make no changes to pParse->rc.
  116632. */
  116633. static void schemaIsValid(Parse *pParse){
  116634. sqlite3 *db = pParse->db;
  116635. int iDb;
  116636. int rc;
  116637. int cookie;
  116638. assert( pParse->checkSchema );
  116639. assert( sqlite3_mutex_held(db->mutex) );
  116640. for(iDb=0; iDb<db->nDb; iDb++){
  116641. int openedTransaction = 0; /* True if a transaction is opened */
  116642. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  116643. if( pBt==0 ) continue;
  116644. /* If there is not already a read-only (or read-write) transaction opened
  116645. ** on the b-tree database, open one now. If a transaction is opened, it
  116646. ** will be closed immediately after reading the meta-value. */
  116647. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  116648. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  116649. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  116650. sqlite3OomFault(db);
  116651. }
  116652. if( rc!=SQLITE_OK ) return;
  116653. openedTransaction = 1;
  116654. }
  116655. /* Read the schema cookie from the database. If it does not match the
  116656. ** value stored as part of the in-memory schema representation,
  116657. ** set Parse.rc to SQLITE_SCHEMA. */
  116658. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  116659. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  116660. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  116661. sqlite3ResetOneSchema(db, iDb);
  116662. pParse->rc = SQLITE_SCHEMA;
  116663. }
  116664. /* Close the transaction, if one was opened. */
  116665. if( openedTransaction ){
  116666. sqlite3BtreeCommit(pBt);
  116667. }
  116668. }
  116669. }
  116670. /*
  116671. ** Convert a schema pointer into the iDb index that indicates
  116672. ** which database file in db->aDb[] the schema refers to.
  116673. **
  116674. ** If the same database is attached more than once, the first
  116675. ** attached database is returned.
  116676. */
  116677. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  116678. int i = -1000000;
  116679. /* If pSchema is NULL, then return -1000000. This happens when code in
  116680. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  116681. ** created by a sub-select). In this case the return value of this
  116682. ** function should never be used.
  116683. **
  116684. ** We return -1000000 instead of the more usual -1 simply because using
  116685. ** -1000000 as the incorrect index into db->aDb[] is much
  116686. ** more likely to cause a segfault than -1 (of course there are assert()
  116687. ** statements too, but it never hurts to play the odds).
  116688. */
  116689. assert( sqlite3_mutex_held(db->mutex) );
  116690. if( pSchema ){
  116691. for(i=0; 1; i++){
  116692. assert( i<db->nDb );
  116693. if( db->aDb[i].pSchema==pSchema ){
  116694. break;
  116695. }
  116696. }
  116697. assert( i>=0 && i<db->nDb );
  116698. }
  116699. return i;
  116700. }
  116701. /*
  116702. ** Free all memory allocations in the pParse object
  116703. */
  116704. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  116705. sqlite3 *db = pParse->db;
  116706. sqlite3DbFree(db, pParse->aLabel);
  116707. sqlite3ExprListDelete(db, pParse->pConstExpr);
  116708. if( db ){
  116709. assert( db->lookaside.bDisable >= pParse->disableLookaside );
  116710. db->lookaside.bDisable -= pParse->disableLookaside;
  116711. }
  116712. pParse->disableLookaside = 0;
  116713. }
  116714. /*
  116715. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  116716. */
  116717. static int sqlite3Prepare(
  116718. sqlite3 *db, /* Database handle. */
  116719. const char *zSql, /* UTF-8 encoded SQL statement. */
  116720. int nBytes, /* Length of zSql in bytes. */
  116721. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  116722. Vdbe *pReprepare, /* VM being reprepared */
  116723. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116724. const char **pzTail /* OUT: End of parsed string */
  116725. ){
  116726. char *zErrMsg = 0; /* Error message */
  116727. int rc = SQLITE_OK; /* Result code */
  116728. int i; /* Loop counter */
  116729. Parse sParse; /* Parsing context */
  116730. memset(&sParse, 0, PARSE_HDR_SZ);
  116731. memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
  116732. sParse.pReprepare = pReprepare;
  116733. assert( ppStmt && *ppStmt==0 );
  116734. /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
  116735. assert( sqlite3_mutex_held(db->mutex) );
  116736. /* For a long-term use prepared statement avoid the use of
  116737. ** lookaside memory.
  116738. */
  116739. if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
  116740. sParse.disableLookaside++;
  116741. db->lookaside.bDisable++;
  116742. }
  116743. sParse.disableVtab = (prepFlags & SQLITE_PREPARE_NO_VTAB)!=0;
  116744. /* Check to verify that it is possible to get a read lock on all
  116745. ** database schemas. The inability to get a read lock indicates that
  116746. ** some other database connection is holding a write-lock, which in
  116747. ** turn means that the other connection has made uncommitted changes
  116748. ** to the schema.
  116749. **
  116750. ** Were we to proceed and prepare the statement against the uncommitted
  116751. ** schema changes and if those schema changes are subsequently rolled
  116752. ** back and different changes are made in their place, then when this
  116753. ** prepared statement goes to run the schema cookie would fail to detect
  116754. ** the schema change. Disaster would follow.
  116755. **
  116756. ** This thread is currently holding mutexes on all Btrees (because
  116757. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  116758. ** is not possible for another thread to start a new schema change
  116759. ** while this routine is running. Hence, we do not need to hold
  116760. ** locks on the schema, we just need to make sure nobody else is
  116761. ** holding them.
  116762. **
  116763. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  116764. ** but it does *not* override schema lock detection, so this all still
  116765. ** works even if READ_UNCOMMITTED is set.
  116766. */
  116767. for(i=0; i<db->nDb; i++) {
  116768. Btree *pBt = db->aDb[i].pBt;
  116769. if( pBt ){
  116770. assert( sqlite3BtreeHoldsMutex(pBt) );
  116771. rc = sqlite3BtreeSchemaLocked(pBt);
  116772. if( rc ){
  116773. const char *zDb = db->aDb[i].zDbSName;
  116774. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  116775. testcase( db->flags & SQLITE_ReadUncommit );
  116776. goto end_prepare;
  116777. }
  116778. }
  116779. }
  116780. sqlite3VtabUnlockList(db);
  116781. sParse.db = db;
  116782. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  116783. char *zSqlCopy;
  116784. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  116785. testcase( nBytes==mxLen );
  116786. testcase( nBytes==mxLen+1 );
  116787. if( nBytes>mxLen ){
  116788. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  116789. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  116790. goto end_prepare;
  116791. }
  116792. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  116793. if( zSqlCopy ){
  116794. sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
  116795. sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
  116796. sqlite3DbFree(db, zSqlCopy);
  116797. }else{
  116798. sParse.zTail = &zSql[nBytes];
  116799. }
  116800. }else{
  116801. sqlite3RunParser(&sParse, zSql, &zErrMsg);
  116802. }
  116803. assert( 0==sParse.nQueryLoop );
  116804. if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  116805. if( sParse.checkSchema ){
  116806. schemaIsValid(&sParse);
  116807. }
  116808. if( db->mallocFailed ){
  116809. sParse.rc = SQLITE_NOMEM_BKPT;
  116810. }
  116811. if( pzTail ){
  116812. *pzTail = sParse.zTail;
  116813. }
  116814. rc = sParse.rc;
  116815. #ifndef SQLITE_OMIT_EXPLAIN
  116816. if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
  116817. static const char * const azColName[] = {
  116818. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  116819. "id", "parent", "notused", "detail"
  116820. };
  116821. int iFirst, mx;
  116822. if( sParse.explain==2 ){
  116823. sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
  116824. iFirst = 8;
  116825. mx = 12;
  116826. }else{
  116827. sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
  116828. iFirst = 0;
  116829. mx = 8;
  116830. }
  116831. for(i=iFirst; i<mx; i++){
  116832. sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
  116833. azColName[i], SQLITE_STATIC);
  116834. }
  116835. }
  116836. #endif
  116837. if( db->init.busy==0 ){
  116838. sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
  116839. }
  116840. if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  116841. sqlite3VdbeFinalize(sParse.pVdbe);
  116842. assert(!(*ppStmt));
  116843. }else{
  116844. *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
  116845. }
  116846. if( zErrMsg ){
  116847. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  116848. sqlite3DbFree(db, zErrMsg);
  116849. }else{
  116850. sqlite3Error(db, rc);
  116851. }
  116852. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  116853. while( sParse.pTriggerPrg ){
  116854. TriggerPrg *pT = sParse.pTriggerPrg;
  116855. sParse.pTriggerPrg = pT->pNext;
  116856. sqlite3DbFree(db, pT);
  116857. }
  116858. end_prepare:
  116859. sqlite3ParserReset(&sParse);
  116860. return rc;
  116861. }
  116862. static int sqlite3LockAndPrepare(
  116863. sqlite3 *db, /* Database handle. */
  116864. const char *zSql, /* UTF-8 encoded SQL statement. */
  116865. int nBytes, /* Length of zSql in bytes. */
  116866. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  116867. Vdbe *pOld, /* VM being reprepared */
  116868. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116869. const char **pzTail /* OUT: End of parsed string */
  116870. ){
  116871. int rc;
  116872. int cnt = 0;
  116873. #ifdef SQLITE_ENABLE_API_ARMOR
  116874. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  116875. #endif
  116876. *ppStmt = 0;
  116877. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  116878. return SQLITE_MISUSE_BKPT;
  116879. }
  116880. sqlite3_mutex_enter(db->mutex);
  116881. sqlite3BtreeEnterAll(db);
  116882. do{
  116883. /* Make multiple attempts to compile the SQL, until it either succeeds
  116884. ** or encounters a permanent error. A schema problem after one schema
  116885. ** reset is considered a permanent error. */
  116886. rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
  116887. assert( rc==SQLITE_OK || *ppStmt==0 );
  116888. }while( rc==SQLITE_ERROR_RETRY
  116889. || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
  116890. sqlite3BtreeLeaveAll(db);
  116891. rc = sqlite3ApiExit(db, rc);
  116892. assert( (rc&db->errMask)==rc );
  116893. sqlite3_mutex_leave(db->mutex);
  116894. return rc;
  116895. }
  116896. /*
  116897. ** Rerun the compilation of a statement after a schema change.
  116898. **
  116899. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  116900. ** if the statement cannot be recompiled because another connection has
  116901. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  116902. ** occurs, return SQLITE_SCHEMA.
  116903. */
  116904. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  116905. int rc;
  116906. sqlite3_stmt *pNew;
  116907. const char *zSql;
  116908. sqlite3 *db;
  116909. u8 prepFlags;
  116910. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  116911. zSql = sqlite3_sql((sqlite3_stmt *)p);
  116912. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  116913. db = sqlite3VdbeDb(p);
  116914. assert( sqlite3_mutex_held(db->mutex) );
  116915. prepFlags = sqlite3VdbePrepareFlags(p);
  116916. rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
  116917. if( rc ){
  116918. if( rc==SQLITE_NOMEM ){
  116919. sqlite3OomFault(db);
  116920. }
  116921. assert( pNew==0 );
  116922. return rc;
  116923. }else{
  116924. assert( pNew!=0 );
  116925. }
  116926. sqlite3VdbeSwap((Vdbe*)pNew, p);
  116927. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  116928. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  116929. sqlite3VdbeFinalize((Vdbe*)pNew);
  116930. return SQLITE_OK;
  116931. }
  116932. /*
  116933. ** Two versions of the official API. Legacy and new use. In the legacy
  116934. ** version, the original SQL text is not saved in the prepared statement
  116935. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  116936. ** sqlite3_step(). In the new version, the original SQL text is retained
  116937. ** and the statement is automatically recompiled if an schema change
  116938. ** occurs.
  116939. */
  116940. SQLITE_API int sqlite3_prepare(
  116941. sqlite3 *db, /* Database handle. */
  116942. const char *zSql, /* UTF-8 encoded SQL statement. */
  116943. int nBytes, /* Length of zSql in bytes. */
  116944. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116945. const char **pzTail /* OUT: End of parsed string */
  116946. ){
  116947. int rc;
  116948. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  116949. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  116950. return rc;
  116951. }
  116952. SQLITE_API int sqlite3_prepare_v2(
  116953. sqlite3 *db, /* Database handle. */
  116954. const char *zSql, /* UTF-8 encoded SQL statement. */
  116955. int nBytes, /* Length of zSql in bytes. */
  116956. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116957. const char **pzTail /* OUT: End of parsed string */
  116958. ){
  116959. int rc;
  116960. /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
  116961. ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
  116962. ** parameter.
  116963. **
  116964. ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
  116965. rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
  116966. ppStmt,pzTail);
  116967. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  116968. return rc;
  116969. }
  116970. SQLITE_API int sqlite3_prepare_v3(
  116971. sqlite3 *db, /* Database handle. */
  116972. const char *zSql, /* UTF-8 encoded SQL statement. */
  116973. int nBytes, /* Length of zSql in bytes. */
  116974. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  116975. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  116976. const char **pzTail /* OUT: End of parsed string */
  116977. ){
  116978. int rc;
  116979. /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
  116980. ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
  116981. ** which is a bit array consisting of zero or more of the
  116982. ** SQLITE_PREPARE_* flags.
  116983. **
  116984. ** Proof by comparison to the implementation of sqlite3_prepare_v2()
  116985. ** directly above. */
  116986. rc = sqlite3LockAndPrepare(db,zSql,nBytes,
  116987. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  116988. 0,ppStmt,pzTail);
  116989. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  116990. return rc;
  116991. }
  116992. #ifndef SQLITE_OMIT_UTF16
  116993. /*
  116994. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  116995. */
  116996. static int sqlite3Prepare16(
  116997. sqlite3 *db, /* Database handle. */
  116998. const void *zSql, /* UTF-16 encoded SQL statement. */
  116999. int nBytes, /* Length of zSql in bytes. */
  117000. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  117001. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117002. const void **pzTail /* OUT: End of parsed string */
  117003. ){
  117004. /* This function currently works by first transforming the UTF-16
  117005. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  117006. ** tricky bit is figuring out the pointer to return in *pzTail.
  117007. */
  117008. char *zSql8;
  117009. const char *zTail8 = 0;
  117010. int rc = SQLITE_OK;
  117011. #ifdef SQLITE_ENABLE_API_ARMOR
  117012. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  117013. #endif
  117014. *ppStmt = 0;
  117015. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  117016. return SQLITE_MISUSE_BKPT;
  117017. }
  117018. if( nBytes>=0 ){
  117019. int sz;
  117020. const char *z = (const char*)zSql;
  117021. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  117022. nBytes = sz;
  117023. }
  117024. sqlite3_mutex_enter(db->mutex);
  117025. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  117026. if( zSql8 ){
  117027. rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
  117028. }
  117029. if( zTail8 && pzTail ){
  117030. /* If sqlite3_prepare returns a tail pointer, we calculate the
  117031. ** equivalent pointer into the UTF-16 string by counting the unicode
  117032. ** characters between zSql8 and zTail8, and then returning a pointer
  117033. ** the same number of characters into the UTF-16 string.
  117034. */
  117035. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  117036. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  117037. }
  117038. sqlite3DbFree(db, zSql8);
  117039. rc = sqlite3ApiExit(db, rc);
  117040. sqlite3_mutex_leave(db->mutex);
  117041. return rc;
  117042. }
  117043. /*
  117044. ** Two versions of the official API. Legacy and new use. In the legacy
  117045. ** version, the original SQL text is not saved in the prepared statement
  117046. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  117047. ** sqlite3_step(). In the new version, the original SQL text is retained
  117048. ** and the statement is automatically recompiled if an schema change
  117049. ** occurs.
  117050. */
  117051. SQLITE_API int sqlite3_prepare16(
  117052. sqlite3 *db, /* Database handle. */
  117053. const void *zSql, /* UTF-16 encoded SQL statement. */
  117054. int nBytes, /* Length of zSql in bytes. */
  117055. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117056. const void **pzTail /* OUT: End of parsed string */
  117057. ){
  117058. int rc;
  117059. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  117060. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  117061. return rc;
  117062. }
  117063. SQLITE_API int sqlite3_prepare16_v2(
  117064. sqlite3 *db, /* Database handle. */
  117065. const void *zSql, /* UTF-16 encoded SQL statement. */
  117066. int nBytes, /* Length of zSql in bytes. */
  117067. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117068. const void **pzTail /* OUT: End of parsed string */
  117069. ){
  117070. int rc;
  117071. rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
  117072. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  117073. return rc;
  117074. }
  117075. SQLITE_API int sqlite3_prepare16_v3(
  117076. sqlite3 *db, /* Database handle. */
  117077. const void *zSql, /* UTF-16 encoded SQL statement. */
  117078. int nBytes, /* Length of zSql in bytes. */
  117079. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  117080. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  117081. const void **pzTail /* OUT: End of parsed string */
  117082. ){
  117083. int rc;
  117084. rc = sqlite3Prepare16(db,zSql,nBytes,
  117085. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  117086. ppStmt,pzTail);
  117087. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  117088. return rc;
  117089. }
  117090. #endif /* SQLITE_OMIT_UTF16 */
  117091. /************** End of prepare.c *********************************************/
  117092. /************** Begin file select.c ******************************************/
  117093. /*
  117094. ** 2001 September 15
  117095. **
  117096. ** The author disclaims copyright to this source code. In place of
  117097. ** a legal notice, here is a blessing:
  117098. **
  117099. ** May you do good and not evil.
  117100. ** May you find forgiveness for yourself and forgive others.
  117101. ** May you share freely, never taking more than you give.
  117102. **
  117103. *************************************************************************
  117104. ** This file contains C code routines that are called by the parser
  117105. ** to handle SELECT statements in SQLite.
  117106. */
  117107. /* #include "sqliteInt.h" */
  117108. /*
  117109. ** Trace output macros
  117110. */
  117111. #if SELECTTRACE_ENABLED
  117112. /***/ int sqlite3SelectTrace = 0;
  117113. # define SELECTTRACE(K,P,S,X) \
  117114. if(sqlite3SelectTrace&(K)) \
  117115. sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
  117116. sqlite3DebugPrintf X
  117117. #else
  117118. # define SELECTTRACE(K,P,S,X)
  117119. #endif
  117120. /*
  117121. ** An instance of the following object is used to record information about
  117122. ** how to process the DISTINCT keyword, to simplify passing that information
  117123. ** into the selectInnerLoop() routine.
  117124. */
  117125. typedef struct DistinctCtx DistinctCtx;
  117126. struct DistinctCtx {
  117127. u8 isTnct; /* True if the DISTINCT keyword is present */
  117128. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  117129. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  117130. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  117131. };
  117132. /*
  117133. ** An instance of the following object is used to record information about
  117134. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  117135. **
  117136. ** The aDefer[] array is used by the sorter-references optimization. For
  117137. ** example, assuming there is no index that can be used for the ORDER BY,
  117138. ** for the query:
  117139. **
  117140. ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
  117141. **
  117142. ** it may be more efficient to add just the "a" values to the sorter, and
  117143. ** retrieve the associated "bigblob" values directly from table t1 as the
  117144. ** 10 smallest "a" values are extracted from the sorter.
  117145. **
  117146. ** When the sorter-reference optimization is used, there is one entry in the
  117147. ** aDefer[] array for each database table that may be read as values are
  117148. ** extracted from the sorter.
  117149. */
  117150. typedef struct SortCtx SortCtx;
  117151. struct SortCtx {
  117152. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  117153. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  117154. int iECursor; /* Cursor number for the sorter */
  117155. int regReturn; /* Register holding block-output return address */
  117156. int labelBkOut; /* Start label for the block-output subroutine */
  117157. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  117158. int labelDone; /* Jump here when done, ex: LIMIT reached */
  117159. int labelOBLopt; /* Jump here when sorter is full */
  117160. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  117161. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117162. u8 nDefer; /* Number of valid entries in aDefer[] */
  117163. struct DeferredCsr {
  117164. Table *pTab; /* Table definition */
  117165. int iCsr; /* Cursor number for table */
  117166. int nKey; /* Number of PK columns for table pTab (>=1) */
  117167. } aDefer[4];
  117168. #endif
  117169. struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */
  117170. };
  117171. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  117172. /*
  117173. ** Delete all the content of a Select structure. Deallocate the structure
  117174. ** itself only if bFree is true.
  117175. */
  117176. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  117177. while( p ){
  117178. Select *pPrior = p->pPrior;
  117179. sqlite3ExprListDelete(db, p->pEList);
  117180. sqlite3SrcListDelete(db, p->pSrc);
  117181. sqlite3ExprDelete(db, p->pWhere);
  117182. sqlite3ExprListDelete(db, p->pGroupBy);
  117183. sqlite3ExprDelete(db, p->pHaving);
  117184. sqlite3ExprListDelete(db, p->pOrderBy);
  117185. sqlite3ExprDelete(db, p->pLimit);
  117186. #ifndef SQLITE_OMIT_WINDOWFUNC
  117187. if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
  117188. sqlite3WindowListDelete(db, p->pWinDefn);
  117189. }
  117190. #endif
  117191. if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
  117192. if( bFree ) sqlite3DbFreeNN(db, p);
  117193. p = pPrior;
  117194. bFree = 1;
  117195. }
  117196. }
  117197. /*
  117198. ** Initialize a SelectDest structure.
  117199. */
  117200. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  117201. pDest->eDest = (u8)eDest;
  117202. pDest->iSDParm = iParm;
  117203. pDest->zAffSdst = 0;
  117204. pDest->iSdst = 0;
  117205. pDest->nSdst = 0;
  117206. }
  117207. /*
  117208. ** Allocate a new Select structure and return a pointer to that
  117209. ** structure.
  117210. */
  117211. SQLITE_PRIVATE Select *sqlite3SelectNew(
  117212. Parse *pParse, /* Parsing context */
  117213. ExprList *pEList, /* which columns to include in the result */
  117214. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  117215. Expr *pWhere, /* the WHERE clause */
  117216. ExprList *pGroupBy, /* the GROUP BY clause */
  117217. Expr *pHaving, /* the HAVING clause */
  117218. ExprList *pOrderBy, /* the ORDER BY clause */
  117219. u32 selFlags, /* Flag parameters, such as SF_Distinct */
  117220. Expr *pLimit /* LIMIT value. NULL means not used */
  117221. ){
  117222. Select *pNew;
  117223. Select standin;
  117224. pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
  117225. if( pNew==0 ){
  117226. assert( pParse->db->mallocFailed );
  117227. pNew = &standin;
  117228. }
  117229. if( pEList==0 ){
  117230. pEList = sqlite3ExprListAppend(pParse, 0,
  117231. sqlite3Expr(pParse->db,TK_ASTERISK,0));
  117232. }
  117233. pNew->pEList = pEList;
  117234. pNew->op = TK_SELECT;
  117235. pNew->selFlags = selFlags;
  117236. pNew->iLimit = 0;
  117237. pNew->iOffset = 0;
  117238. pNew->selId = ++pParse->nSelect;
  117239. pNew->addrOpenEphm[0] = -1;
  117240. pNew->addrOpenEphm[1] = -1;
  117241. pNew->nSelectRow = 0;
  117242. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
  117243. pNew->pSrc = pSrc;
  117244. pNew->pWhere = pWhere;
  117245. pNew->pGroupBy = pGroupBy;
  117246. pNew->pHaving = pHaving;
  117247. pNew->pOrderBy = pOrderBy;
  117248. pNew->pPrior = 0;
  117249. pNew->pNext = 0;
  117250. pNew->pLimit = pLimit;
  117251. pNew->pWith = 0;
  117252. #ifndef SQLITE_OMIT_WINDOWFUNC
  117253. pNew->pWin = 0;
  117254. pNew->pWinDefn = 0;
  117255. #endif
  117256. if( pParse->db->mallocFailed ) {
  117257. clearSelect(pParse->db, pNew, pNew!=&standin);
  117258. pNew = 0;
  117259. }else{
  117260. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  117261. }
  117262. assert( pNew!=&standin );
  117263. return pNew;
  117264. }
  117265. /*
  117266. ** Delete the given Select structure and all of its substructures.
  117267. */
  117268. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  117269. if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
  117270. }
  117271. /*
  117272. ** Return a pointer to the right-most SELECT statement in a compound.
  117273. */
  117274. static Select *findRightmost(Select *p){
  117275. while( p->pNext ) p = p->pNext;
  117276. return p;
  117277. }
  117278. /*
  117279. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  117280. ** type of join. Return an integer constant that expresses that type
  117281. ** in terms of the following bit values:
  117282. **
  117283. ** JT_INNER
  117284. ** JT_CROSS
  117285. ** JT_OUTER
  117286. ** JT_NATURAL
  117287. ** JT_LEFT
  117288. ** JT_RIGHT
  117289. **
  117290. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  117291. **
  117292. ** If an illegal or unsupported join type is seen, then still return
  117293. ** a join type, but put an error in the pParse structure.
  117294. */
  117295. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  117296. int jointype = 0;
  117297. Token *apAll[3];
  117298. Token *p;
  117299. /* 0123456789 123456789 123456789 123 */
  117300. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  117301. static const struct {
  117302. u8 i; /* Beginning of keyword text in zKeyText[] */
  117303. u8 nChar; /* Length of the keyword in characters */
  117304. u8 code; /* Join type mask */
  117305. } aKeyword[] = {
  117306. /* natural */ { 0, 7, JT_NATURAL },
  117307. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  117308. /* outer */ { 10, 5, JT_OUTER },
  117309. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  117310. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  117311. /* inner */ { 23, 5, JT_INNER },
  117312. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  117313. };
  117314. int i, j;
  117315. apAll[0] = pA;
  117316. apAll[1] = pB;
  117317. apAll[2] = pC;
  117318. for(i=0; i<3 && apAll[i]; i++){
  117319. p = apAll[i];
  117320. for(j=0; j<ArraySize(aKeyword); j++){
  117321. if( p->n==aKeyword[j].nChar
  117322. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  117323. jointype |= aKeyword[j].code;
  117324. break;
  117325. }
  117326. }
  117327. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  117328. if( j>=ArraySize(aKeyword) ){
  117329. jointype |= JT_ERROR;
  117330. break;
  117331. }
  117332. }
  117333. if(
  117334. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  117335. (jointype & JT_ERROR)!=0
  117336. ){
  117337. const char *zSp = " ";
  117338. assert( pB!=0 );
  117339. if( pC==0 ){ zSp++; }
  117340. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  117341. "%T %T%s%T", pA, pB, zSp, pC);
  117342. jointype = JT_INNER;
  117343. }else if( (jointype & JT_OUTER)!=0
  117344. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  117345. sqlite3ErrorMsg(pParse,
  117346. "RIGHT and FULL OUTER JOINs are not currently supported");
  117347. jointype = JT_INNER;
  117348. }
  117349. return jointype;
  117350. }
  117351. /*
  117352. ** Return the index of a column in a table. Return -1 if the column
  117353. ** is not contained in the table.
  117354. */
  117355. static int columnIndex(Table *pTab, const char *zCol){
  117356. int i;
  117357. for(i=0; i<pTab->nCol; i++){
  117358. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  117359. }
  117360. return -1;
  117361. }
  117362. /*
  117363. ** Search the first N tables in pSrc, from left to right, looking for a
  117364. ** table that has a column named zCol.
  117365. **
  117366. ** When found, set *piTab and *piCol to the table index and column index
  117367. ** of the matching column and return TRUE.
  117368. **
  117369. ** If not found, return FALSE.
  117370. */
  117371. static int tableAndColumnIndex(
  117372. SrcList *pSrc, /* Array of tables to search */
  117373. int N, /* Number of tables in pSrc->a[] to search */
  117374. const char *zCol, /* Name of the column we are looking for */
  117375. int *piTab, /* Write index of pSrc->a[] here */
  117376. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  117377. ){
  117378. int i; /* For looping over tables in pSrc */
  117379. int iCol; /* Index of column matching zCol */
  117380. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  117381. for(i=0; i<N; i++){
  117382. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  117383. if( iCol>=0 ){
  117384. if( piTab ){
  117385. *piTab = i;
  117386. *piCol = iCol;
  117387. }
  117388. return 1;
  117389. }
  117390. }
  117391. return 0;
  117392. }
  117393. /*
  117394. ** This function is used to add terms implied by JOIN syntax to the
  117395. ** WHERE clause expression of a SELECT statement. The new term, which
  117396. ** is ANDed with the existing WHERE clause, is of the form:
  117397. **
  117398. ** (tab1.col1 = tab2.col2)
  117399. **
  117400. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  117401. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  117402. ** column iColRight of tab2.
  117403. */
  117404. static void addWhereTerm(
  117405. Parse *pParse, /* Parsing context */
  117406. SrcList *pSrc, /* List of tables in FROM clause */
  117407. int iLeft, /* Index of first table to join in pSrc */
  117408. int iColLeft, /* Index of column in first table */
  117409. int iRight, /* Index of second table in pSrc */
  117410. int iColRight, /* Index of column in second table */
  117411. int isOuterJoin, /* True if this is an OUTER join */
  117412. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  117413. ){
  117414. sqlite3 *db = pParse->db;
  117415. Expr *pE1;
  117416. Expr *pE2;
  117417. Expr *pEq;
  117418. assert( iLeft<iRight );
  117419. assert( pSrc->nSrc>iRight );
  117420. assert( pSrc->a[iLeft].pTab );
  117421. assert( pSrc->a[iRight].pTab );
  117422. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  117423. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  117424. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
  117425. if( pEq && isOuterJoin ){
  117426. ExprSetProperty(pEq, EP_FromJoin);
  117427. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  117428. ExprSetVVAProperty(pEq, EP_NoReduce);
  117429. pEq->iRightJoinTable = (i16)pE2->iTable;
  117430. }
  117431. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  117432. }
  117433. /*
  117434. ** Set the EP_FromJoin property on all terms of the given expression.
  117435. ** And set the Expr.iRightJoinTable to iTable for every term in the
  117436. ** expression.
  117437. **
  117438. ** The EP_FromJoin property is used on terms of an expression to tell
  117439. ** the LEFT OUTER JOIN processing logic that this term is part of the
  117440. ** join restriction specified in the ON or USING clause and not a part
  117441. ** of the more general WHERE clause. These terms are moved over to the
  117442. ** WHERE clause during join processing but we need to remember that they
  117443. ** originated in the ON or USING clause.
  117444. **
  117445. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  117446. ** expression depends on table iRightJoinTable even if that table is not
  117447. ** explicitly mentioned in the expression. That information is needed
  117448. ** for cases like this:
  117449. **
  117450. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  117451. **
  117452. ** The where clause needs to defer the handling of the t1.x=5
  117453. ** term until after the t2 loop of the join. In that way, a
  117454. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  117455. ** defer the handling of t1.x=5, it will be processed immediately
  117456. ** after the t1 loop and rows with t1.x!=5 will never appear in
  117457. ** the output, which is incorrect.
  117458. */
  117459. static void setJoinExpr(Expr *p, int iTable){
  117460. while( p ){
  117461. ExprSetProperty(p, EP_FromJoin);
  117462. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  117463. ExprSetVVAProperty(p, EP_NoReduce);
  117464. p->iRightJoinTable = (i16)iTable;
  117465. if( p->op==TK_FUNCTION && p->x.pList ){
  117466. int i;
  117467. for(i=0; i<p->x.pList->nExpr; i++){
  117468. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  117469. }
  117470. }
  117471. setJoinExpr(p->pLeft, iTable);
  117472. p = p->pRight;
  117473. }
  117474. }
  117475. /* Undo the work of setJoinExpr(). In the expression tree p, convert every
  117476. ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
  117477. ** an ordinary term that omits the EP_FromJoin mark.
  117478. **
  117479. ** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
  117480. */
  117481. static void unsetJoinExpr(Expr *p, int iTable){
  117482. while( p ){
  117483. if( ExprHasProperty(p, EP_FromJoin)
  117484. && (iTable<0 || p->iRightJoinTable==iTable) ){
  117485. ExprClearProperty(p, EP_FromJoin);
  117486. }
  117487. if( p->op==TK_FUNCTION && p->x.pList ){
  117488. int i;
  117489. for(i=0; i<p->x.pList->nExpr; i++){
  117490. unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
  117491. }
  117492. }
  117493. unsetJoinExpr(p->pLeft, iTable);
  117494. p = p->pRight;
  117495. }
  117496. }
  117497. /*
  117498. ** This routine processes the join information for a SELECT statement.
  117499. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  117500. ** NATURAL joins also create extra WHERE clause terms.
  117501. **
  117502. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  117503. ** The left most table is the first entry in Select.pSrc. The right-most
  117504. ** table is the last entry. The join operator is held in the entry to
  117505. ** the left. Thus entry 0 contains the join operator for the join between
  117506. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  117507. ** also attached to the left entry.
  117508. **
  117509. ** This routine returns the number of errors encountered.
  117510. */
  117511. static int sqliteProcessJoin(Parse *pParse, Select *p){
  117512. SrcList *pSrc; /* All tables in the FROM clause */
  117513. int i, j; /* Loop counters */
  117514. struct SrcList_item *pLeft; /* Left table being joined */
  117515. struct SrcList_item *pRight; /* Right table being joined */
  117516. pSrc = p->pSrc;
  117517. pLeft = &pSrc->a[0];
  117518. pRight = &pLeft[1];
  117519. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  117520. Table *pRightTab = pRight->pTab;
  117521. int isOuter;
  117522. if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
  117523. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  117524. /* When the NATURAL keyword is present, add WHERE clause terms for
  117525. ** every column that the two tables have in common.
  117526. */
  117527. if( pRight->fg.jointype & JT_NATURAL ){
  117528. if( pRight->pOn || pRight->pUsing ){
  117529. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  117530. "an ON or USING clause", 0);
  117531. return 1;
  117532. }
  117533. for(j=0; j<pRightTab->nCol; j++){
  117534. char *zName; /* Name of column in the right table */
  117535. int iLeft; /* Matching left table */
  117536. int iLeftCol; /* Matching column in the left table */
  117537. zName = pRightTab->aCol[j].zName;
  117538. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  117539. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  117540. isOuter, &p->pWhere);
  117541. }
  117542. }
  117543. }
  117544. /* Disallow both ON and USING clauses in the same join
  117545. */
  117546. if( pRight->pOn && pRight->pUsing ){
  117547. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  117548. "clauses in the same join");
  117549. return 1;
  117550. }
  117551. /* Add the ON clause to the end of the WHERE clause, connected by
  117552. ** an AND operator.
  117553. */
  117554. if( pRight->pOn ){
  117555. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  117556. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  117557. pRight->pOn = 0;
  117558. }
  117559. /* Create extra terms on the WHERE clause for each column named
  117560. ** in the USING clause. Example: If the two tables to be joined are
  117561. ** A and B and the USING clause names X, Y, and Z, then add this
  117562. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  117563. ** Report an error if any column mentioned in the USING clause is
  117564. ** not contained in both tables to be joined.
  117565. */
  117566. if( pRight->pUsing ){
  117567. IdList *pList = pRight->pUsing;
  117568. for(j=0; j<pList->nId; j++){
  117569. char *zName; /* Name of the term in the USING clause */
  117570. int iLeft; /* Table on the left with matching column name */
  117571. int iLeftCol; /* Column number of matching column on the left */
  117572. int iRightCol; /* Column number of matching column on the right */
  117573. zName = pList->a[j].zName;
  117574. iRightCol = columnIndex(pRightTab, zName);
  117575. if( iRightCol<0
  117576. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  117577. ){
  117578. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  117579. "not present in both tables", zName);
  117580. return 1;
  117581. }
  117582. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  117583. isOuter, &p->pWhere);
  117584. }
  117585. }
  117586. }
  117587. return 0;
  117588. }
  117589. /*
  117590. ** An instance of this object holds information (beyond pParse and pSelect)
  117591. ** needed to load the next result row that is to be added to the sorter.
  117592. */
  117593. typedef struct RowLoadInfo RowLoadInfo;
  117594. struct RowLoadInfo {
  117595. int regResult; /* Store results in array of registers here */
  117596. u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
  117597. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117598. ExprList *pExtra; /* Extra columns needed by sorter refs */
  117599. int regExtraResult; /* Where to load the extra columns */
  117600. #endif
  117601. };
  117602. /*
  117603. ** This routine does the work of loading query data into an array of
  117604. ** registers so that it can be added to the sorter.
  117605. */
  117606. static void innerLoopLoadRow(
  117607. Parse *pParse, /* Statement under construction */
  117608. Select *pSelect, /* The query being coded */
  117609. RowLoadInfo *pInfo /* Info needed to complete the row load */
  117610. ){
  117611. sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
  117612. 0, pInfo->ecelFlags);
  117613. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117614. if( pInfo->pExtra ){
  117615. sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
  117616. sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
  117617. }
  117618. #endif
  117619. }
  117620. /*
  117621. ** Code the OP_MakeRecord instruction that generates the entry to be
  117622. ** added into the sorter.
  117623. **
  117624. ** Return the register in which the result is stored.
  117625. */
  117626. static int makeSorterRecord(
  117627. Parse *pParse,
  117628. SortCtx *pSort,
  117629. Select *pSelect,
  117630. int regBase,
  117631. int nBase
  117632. ){
  117633. int nOBSat = pSort->nOBSat;
  117634. Vdbe *v = pParse->pVdbe;
  117635. int regOut = ++pParse->nMem;
  117636. if( pSort->pDeferredRowLoad ){
  117637. innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
  117638. }
  117639. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
  117640. return regOut;
  117641. }
  117642. /*
  117643. ** Generate code that will push the record in registers regData
  117644. ** through regData+nData-1 onto the sorter.
  117645. */
  117646. static void pushOntoSorter(
  117647. Parse *pParse, /* Parser context */
  117648. SortCtx *pSort, /* Information about the ORDER BY clause */
  117649. Select *pSelect, /* The whole SELECT statement */
  117650. int regData, /* First register holding data to be sorted */
  117651. int regOrigData, /* First register holding data before packing */
  117652. int nData, /* Number of elements in the regData data array */
  117653. int nPrefixReg /* No. of reg prior to regData available for use */
  117654. ){
  117655. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  117656. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  117657. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  117658. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  117659. int regBase; /* Regs for sorter record */
  117660. int regRecord = 0; /* Assembled sorter record */
  117661. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  117662. int op; /* Opcode to add sorter record to sorter */
  117663. int iLimit; /* LIMIT counter */
  117664. int iSkip = 0; /* End of the sorter insert loop */
  117665. assert( bSeq==0 || bSeq==1 );
  117666. /* Three cases:
  117667. ** (1) The data to be sorted has already been packed into a Record
  117668. ** by a prior OP_MakeRecord. In this case nData==1 and regData
  117669. ** will be completely unrelated to regOrigData.
  117670. ** (2) All output columns are included in the sort record. In that
  117671. ** case regData==regOrigData.
  117672. ** (3) Some output columns are omitted from the sort record due to
  117673. ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
  117674. ** SQLITE_ECEL_OMITREF optimization, or due to the
  117675. ** SortCtx.pDeferredRowLoad optimiation. In any of these cases
  117676. ** regOrigData is 0 to prevent this routine from trying to copy
  117677. ** values that might not yet exist.
  117678. */
  117679. assert( nData==1 || regData==regOrigData || regOrigData==0 );
  117680. if( nPrefixReg ){
  117681. assert( nPrefixReg==nExpr+bSeq );
  117682. regBase = regData - nPrefixReg;
  117683. }else{
  117684. regBase = pParse->nMem + 1;
  117685. pParse->nMem += nBase;
  117686. }
  117687. assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
  117688. iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
  117689. pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
  117690. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  117691. SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
  117692. if( bSeq ){
  117693. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  117694. }
  117695. if( nPrefixReg==0 && nData>0 ){
  117696. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  117697. }
  117698. if( nOBSat>0 ){
  117699. int regPrevKey; /* The first nOBSat columns of the previous row */
  117700. int addrFirst; /* Address of the OP_IfNot opcode */
  117701. int addrJmp; /* Address of the OP_Jump opcode */
  117702. VdbeOp *pOp; /* Opcode that opens the sorter */
  117703. int nKey; /* Number of sorting key columns, including OP_Sequence */
  117704. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  117705. regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
  117706. regPrevKey = pParse->nMem+1;
  117707. pParse->nMem += pSort->nOBSat;
  117708. nKey = nExpr - pSort->nOBSat + bSeq;
  117709. if( bSeq ){
  117710. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  117711. }else{
  117712. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  117713. }
  117714. VdbeCoverage(v);
  117715. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  117716. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  117717. if( pParse->db->mallocFailed ) return;
  117718. pOp->p2 = nKey + nData;
  117719. pKI = pOp->p4.pKeyInfo;
  117720. memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */
  117721. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  117722. testcase( pKI->nAllField > pKI->nKeyField+2 );
  117723. pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
  117724. pKI->nAllField-pKI->nKeyField-1);
  117725. addrJmp = sqlite3VdbeCurrentAddr(v);
  117726. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  117727. pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
  117728. pSort->regReturn = ++pParse->nMem;
  117729. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  117730. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  117731. if( iLimit ){
  117732. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
  117733. VdbeCoverage(v);
  117734. }
  117735. sqlite3VdbeJumpHere(v, addrFirst);
  117736. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  117737. sqlite3VdbeJumpHere(v, addrJmp);
  117738. }
  117739. if( iLimit ){
  117740. /* At this point the values for the new sorter entry are stored
  117741. ** in an array of registers. They need to be composed into a record
  117742. ** and inserted into the sorter if either (a) there are currently
  117743. ** less than LIMIT+OFFSET items or (b) the new record is smaller than
  117744. ** the largest record currently in the sorter. If (b) is true and there
  117745. ** are already LIMIT+OFFSET items in the sorter, delete the largest
  117746. ** entry before inserting the new one. This way there are never more
  117747. ** than LIMIT+OFFSET items in the sorter.
  117748. **
  117749. ** If the new record does not need to be inserted into the sorter,
  117750. ** jump to the next iteration of the loop. If the pSort->labelOBLopt
  117751. ** value is not zero, then it is a label of where to jump. Otherwise,
  117752. ** just bypass the row insert logic. See the header comment on the
  117753. ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
  117754. */
  117755. int iCsr = pSort->iECursor;
  117756. sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
  117757. VdbeCoverage(v);
  117758. sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
  117759. iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
  117760. iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
  117761. VdbeCoverage(v);
  117762. sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
  117763. }
  117764. if( regRecord==0 ){
  117765. regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
  117766. }
  117767. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  117768. op = OP_SorterInsert;
  117769. }else{
  117770. op = OP_IdxInsert;
  117771. }
  117772. sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
  117773. regBase+nOBSat, nBase-nOBSat);
  117774. if( iSkip ){
  117775. sqlite3VdbeChangeP2(v, iSkip,
  117776. pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
  117777. }
  117778. }
  117779. /*
  117780. ** Add code to implement the OFFSET
  117781. */
  117782. static void codeOffset(
  117783. Vdbe *v, /* Generate code into this VM */
  117784. int iOffset, /* Register holding the offset counter */
  117785. int iContinue /* Jump here to skip the current record */
  117786. ){
  117787. if( iOffset>0 ){
  117788. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  117789. VdbeComment((v, "OFFSET"));
  117790. }
  117791. }
  117792. /*
  117793. ** Add code that will check to make sure the N registers starting at iMem
  117794. ** form a distinct entry. iTab is a sorting index that holds previously
  117795. ** seen combinations of the N values. A new entry is made in iTab
  117796. ** if the current N values are new.
  117797. **
  117798. ** A jump to addrRepeat is made and the N+1 values are popped from the
  117799. ** stack if the top N elements are not distinct.
  117800. */
  117801. static void codeDistinct(
  117802. Parse *pParse, /* Parsing and code generating context */
  117803. int iTab, /* A sorting index used to test for distinctness */
  117804. int addrRepeat, /* Jump to here if not distinct */
  117805. int N, /* Number of elements */
  117806. int iMem /* First element */
  117807. ){
  117808. Vdbe *v;
  117809. int r1;
  117810. v = pParse->pVdbe;
  117811. r1 = sqlite3GetTempReg(pParse);
  117812. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  117813. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  117814. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
  117815. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  117816. sqlite3ReleaseTempReg(pParse, r1);
  117817. }
  117818. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117819. /*
  117820. ** This function is called as part of inner-loop generation for a SELECT
  117821. ** statement with an ORDER BY that is not optimized by an index. It
  117822. ** determines the expressions, if any, that the sorter-reference
  117823. ** optimization should be used for. The sorter-reference optimization
  117824. ** is used for SELECT queries like:
  117825. **
  117826. ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
  117827. **
  117828. ** If the optimization is used for expression "bigblob", then instead of
  117829. ** storing values read from that column in the sorter records, the PK of
  117830. ** the row from table t1 is stored instead. Then, as records are extracted from
  117831. ** the sorter to return to the user, the required value of bigblob is
  117832. ** retrieved directly from table t1. If the values are very large, this
  117833. ** can be more efficient than storing them directly in the sorter records.
  117834. **
  117835. ** The ExprList_item.bSorterRef flag is set for each expression in pEList
  117836. ** for which the sorter-reference optimization should be enabled.
  117837. ** Additionally, the pSort->aDefer[] array is populated with entries
  117838. ** for all cursors required to evaluate all selected expressions. Finally.
  117839. ** output variable (*ppExtra) is set to an expression list containing
  117840. ** expressions for all extra PK values that should be stored in the
  117841. ** sorter records.
  117842. */
  117843. static void selectExprDefer(
  117844. Parse *pParse, /* Leave any error here */
  117845. SortCtx *pSort, /* Sorter context */
  117846. ExprList *pEList, /* Expressions destined for sorter */
  117847. ExprList **ppExtra /* Expressions to append to sorter record */
  117848. ){
  117849. int i;
  117850. int nDefer = 0;
  117851. ExprList *pExtra = 0;
  117852. for(i=0; i<pEList->nExpr; i++){
  117853. struct ExprList_item *pItem = &pEList->a[i];
  117854. if( pItem->u.x.iOrderByCol==0 ){
  117855. Expr *pExpr = pItem->pExpr;
  117856. Table *pTab = pExpr->y.pTab;
  117857. if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
  117858. && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
  117859. ){
  117860. int j;
  117861. for(j=0; j<nDefer; j++){
  117862. if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
  117863. }
  117864. if( j==nDefer ){
  117865. if( nDefer==ArraySize(pSort->aDefer) ){
  117866. continue;
  117867. }else{
  117868. int nKey = 1;
  117869. int k;
  117870. Index *pPk = 0;
  117871. if( !HasRowid(pTab) ){
  117872. pPk = sqlite3PrimaryKeyIndex(pTab);
  117873. nKey = pPk->nKeyCol;
  117874. }
  117875. for(k=0; k<nKey; k++){
  117876. Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
  117877. if( pNew ){
  117878. pNew->iTable = pExpr->iTable;
  117879. pNew->y.pTab = pExpr->y.pTab;
  117880. pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
  117881. pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
  117882. }
  117883. }
  117884. pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
  117885. pSort->aDefer[nDefer].iCsr = pExpr->iTable;
  117886. pSort->aDefer[nDefer].nKey = nKey;
  117887. nDefer++;
  117888. }
  117889. }
  117890. pItem->bSorterRef = 1;
  117891. }
  117892. }
  117893. }
  117894. pSort->nDefer = (u8)nDefer;
  117895. *ppExtra = pExtra;
  117896. }
  117897. #endif
  117898. /*
  117899. ** This routine generates the code for the inside of the inner loop
  117900. ** of a SELECT.
  117901. **
  117902. ** If srcTab is negative, then the p->pEList expressions
  117903. ** are evaluated in order to get the data for this row. If srcTab is
  117904. ** zero or more, then data is pulled from srcTab and p->pEList is used only
  117905. ** to get the number of columns and the collation sequence for each column.
  117906. */
  117907. static void selectInnerLoop(
  117908. Parse *pParse, /* The parser context */
  117909. Select *p, /* The complete select statement being coded */
  117910. int srcTab, /* Pull data from this table if non-negative */
  117911. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  117912. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  117913. SelectDest *pDest, /* How to dispose of the results */
  117914. int iContinue, /* Jump here to continue with next row */
  117915. int iBreak /* Jump here to break out of the inner loop */
  117916. ){
  117917. Vdbe *v = pParse->pVdbe;
  117918. int i;
  117919. int hasDistinct; /* True if the DISTINCT keyword is present */
  117920. int eDest = pDest->eDest; /* How to dispose of results */
  117921. int iParm = pDest->iSDParm; /* First argument to disposal method */
  117922. int nResultCol; /* Number of result columns */
  117923. int nPrefixReg = 0; /* Number of extra registers before regResult */
  117924. RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
  117925. /* Usually, regResult is the first cell in an array of memory cells
  117926. ** containing the current result row. In this case regOrig is set to the
  117927. ** same value. However, if the results are being sent to the sorter, the
  117928. ** values for any expressions that are also part of the sort-key are omitted
  117929. ** from this array. In this case regOrig is set to zero. */
  117930. int regResult; /* Start of memory holding current results */
  117931. int regOrig; /* Start of memory holding full result (or 0) */
  117932. assert( v );
  117933. assert( p->pEList!=0 );
  117934. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  117935. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  117936. if( pSort==0 && !hasDistinct ){
  117937. assert( iContinue!=0 );
  117938. codeOffset(v, p->iOffset, iContinue);
  117939. }
  117940. /* Pull the requested columns.
  117941. */
  117942. nResultCol = p->pEList->nExpr;
  117943. if( pDest->iSdst==0 ){
  117944. if( pSort ){
  117945. nPrefixReg = pSort->pOrderBy->nExpr;
  117946. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  117947. pParse->nMem += nPrefixReg;
  117948. }
  117949. pDest->iSdst = pParse->nMem+1;
  117950. pParse->nMem += nResultCol;
  117951. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  117952. /* This is an error condition that can result, for example, when a SELECT
  117953. ** on the right-hand side of an INSERT contains more result columns than
  117954. ** there are columns in the table on the left. The error will be caught
  117955. ** and reported later. But we need to make sure enough memory is allocated
  117956. ** to avoid other spurious errors in the meantime. */
  117957. pParse->nMem += nResultCol;
  117958. }
  117959. pDest->nSdst = nResultCol;
  117960. regOrig = regResult = pDest->iSdst;
  117961. if( srcTab>=0 ){
  117962. for(i=0; i<nResultCol; i++){
  117963. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  117964. VdbeComment((v, "%s", p->pEList->a[i].zName));
  117965. }
  117966. }else if( eDest!=SRT_Exists ){
  117967. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117968. ExprList *pExtra = 0;
  117969. #endif
  117970. /* If the destination is an EXISTS(...) expression, the actual
  117971. ** values returned by the SELECT are not required.
  117972. */
  117973. u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
  117974. ExprList *pEList;
  117975. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  117976. ecelFlags = SQLITE_ECEL_DUP;
  117977. }else{
  117978. ecelFlags = 0;
  117979. }
  117980. if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
  117981. /* For each expression in p->pEList that is a copy of an expression in
  117982. ** the ORDER BY clause (pSort->pOrderBy), set the associated
  117983. ** iOrderByCol value to one more than the index of the ORDER BY
  117984. ** expression within the sort-key that pushOntoSorter() will generate.
  117985. ** This allows the p->pEList field to be omitted from the sorted record,
  117986. ** saving space and CPU cycles. */
  117987. ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
  117988. for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
  117989. int j;
  117990. if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
  117991. p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
  117992. }
  117993. }
  117994. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  117995. selectExprDefer(pParse, pSort, p->pEList, &pExtra);
  117996. if( pExtra && pParse->db->mallocFailed==0 ){
  117997. /* If there are any extra PK columns to add to the sorter records,
  117998. ** allocate extra memory cells and adjust the OpenEphemeral
  117999. ** instruction to account for the larger records. This is only
  118000. ** required if there are one or more WITHOUT ROWID tables with
  118001. ** composite primary keys in the SortCtx.aDefer[] array. */
  118002. VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  118003. pOp->p2 += (pExtra->nExpr - pSort->nDefer);
  118004. pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
  118005. pParse->nMem += pExtra->nExpr;
  118006. }
  118007. #endif
  118008. /* Adjust nResultCol to account for columns that are omitted
  118009. ** from the sorter by the optimizations in this branch */
  118010. pEList = p->pEList;
  118011. for(i=0; i<pEList->nExpr; i++){
  118012. if( pEList->a[i].u.x.iOrderByCol>0
  118013. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118014. || pEList->a[i].bSorterRef
  118015. #endif
  118016. ){
  118017. nResultCol--;
  118018. regOrig = 0;
  118019. }
  118020. }
  118021. testcase( regOrig );
  118022. testcase( eDest==SRT_Set );
  118023. testcase( eDest==SRT_Mem );
  118024. testcase( eDest==SRT_Coroutine );
  118025. testcase( eDest==SRT_Output );
  118026. assert( eDest==SRT_Set || eDest==SRT_Mem
  118027. || eDest==SRT_Coroutine || eDest==SRT_Output );
  118028. }
  118029. sRowLoadInfo.regResult = regResult;
  118030. sRowLoadInfo.ecelFlags = ecelFlags;
  118031. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118032. sRowLoadInfo.pExtra = pExtra;
  118033. sRowLoadInfo.regExtraResult = regResult + nResultCol;
  118034. if( pExtra ) nResultCol += pExtra->nExpr;
  118035. #endif
  118036. if( p->iLimit
  118037. && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
  118038. && nPrefixReg>0
  118039. ){
  118040. assert( pSort!=0 );
  118041. assert( hasDistinct==0 );
  118042. pSort->pDeferredRowLoad = &sRowLoadInfo;
  118043. regOrig = 0;
  118044. }else{
  118045. innerLoopLoadRow(pParse, p, &sRowLoadInfo);
  118046. }
  118047. }
  118048. /* If the DISTINCT keyword was present on the SELECT statement
  118049. ** and this row has been seen before, then do not make this row
  118050. ** part of the result.
  118051. */
  118052. if( hasDistinct ){
  118053. switch( pDistinct->eTnctType ){
  118054. case WHERE_DISTINCT_ORDERED: {
  118055. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  118056. int iJump; /* Jump destination */
  118057. int regPrev; /* Previous row content */
  118058. /* Allocate space for the previous row */
  118059. regPrev = pParse->nMem+1;
  118060. pParse->nMem += nResultCol;
  118061. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  118062. ** sets the MEM_Cleared bit on the first register of the
  118063. ** previous value. This will cause the OP_Ne below to always
  118064. ** fail on the first iteration of the loop even if the first
  118065. ** row is all NULLs.
  118066. */
  118067. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  118068. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  118069. pOp->opcode = OP_Null;
  118070. pOp->p1 = 1;
  118071. pOp->p2 = regPrev;
  118072. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  118073. for(i=0; i<nResultCol; i++){
  118074. CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
  118075. if( i<nResultCol-1 ){
  118076. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  118077. VdbeCoverage(v);
  118078. }else{
  118079. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  118080. VdbeCoverage(v);
  118081. }
  118082. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  118083. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  118084. }
  118085. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  118086. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  118087. break;
  118088. }
  118089. case WHERE_DISTINCT_UNIQUE: {
  118090. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  118091. break;
  118092. }
  118093. default: {
  118094. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  118095. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  118096. regResult);
  118097. break;
  118098. }
  118099. }
  118100. if( pSort==0 ){
  118101. codeOffset(v, p->iOffset, iContinue);
  118102. }
  118103. }
  118104. switch( eDest ){
  118105. /* In this mode, write each query result to the key of the temporary
  118106. ** table iParm.
  118107. */
  118108. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  118109. case SRT_Union: {
  118110. int r1;
  118111. r1 = sqlite3GetTempReg(pParse);
  118112. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  118113. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  118114. sqlite3ReleaseTempReg(pParse, r1);
  118115. break;
  118116. }
  118117. /* Construct a record from the query result, but instead of
  118118. ** saving that record, use it as a key to delete elements from
  118119. ** the temporary table iParm.
  118120. */
  118121. case SRT_Except: {
  118122. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  118123. break;
  118124. }
  118125. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  118126. /* Store the result as data using a unique key.
  118127. */
  118128. case SRT_Fifo:
  118129. case SRT_DistFifo:
  118130. case SRT_Table:
  118131. case SRT_EphemTab: {
  118132. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  118133. testcase( eDest==SRT_Table );
  118134. testcase( eDest==SRT_EphemTab );
  118135. testcase( eDest==SRT_Fifo );
  118136. testcase( eDest==SRT_DistFifo );
  118137. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  118138. #ifndef SQLITE_OMIT_CTE
  118139. if( eDest==SRT_DistFifo ){
  118140. /* If the destination is DistFifo, then cursor (iParm+1) is open
  118141. ** on an ephemeral index. If the current row is already present
  118142. ** in the index, do not write it to the output. If not, add the
  118143. ** current row to the index and proceed with writing it to the
  118144. ** output table as well. */
  118145. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  118146. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  118147. VdbeCoverage(v);
  118148. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
  118149. assert( pSort==0 );
  118150. }
  118151. #endif
  118152. if( pSort ){
  118153. assert( regResult==regOrig );
  118154. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
  118155. }else{
  118156. int r2 = sqlite3GetTempReg(pParse);
  118157. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  118158. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  118159. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  118160. sqlite3ReleaseTempReg(pParse, r2);
  118161. }
  118162. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  118163. break;
  118164. }
  118165. #ifndef SQLITE_OMIT_SUBQUERY
  118166. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  118167. ** then there should be a single item on the stack. Write this
  118168. ** item into the set table with bogus data.
  118169. */
  118170. case SRT_Set: {
  118171. if( pSort ){
  118172. /* At first glance you would think we could optimize out the
  118173. ** ORDER BY in this case since the order of entries in the set
  118174. ** does not matter. But there might be a LIMIT clause, in which
  118175. ** case the order does matter */
  118176. pushOntoSorter(
  118177. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  118178. }else{
  118179. int r1 = sqlite3GetTempReg(pParse);
  118180. assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
  118181. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
  118182. r1, pDest->zAffSdst, nResultCol);
  118183. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  118184. sqlite3ReleaseTempReg(pParse, r1);
  118185. }
  118186. break;
  118187. }
  118188. /* If any row exist in the result set, record that fact and abort.
  118189. */
  118190. case SRT_Exists: {
  118191. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  118192. /* The LIMIT clause will terminate the loop for us */
  118193. break;
  118194. }
  118195. /* If this is a scalar select that is part of an expression, then
  118196. ** store the results in the appropriate memory cell or array of
  118197. ** memory cells and break out of the scan loop.
  118198. */
  118199. case SRT_Mem: {
  118200. if( pSort ){
  118201. assert( nResultCol<=pDest->nSdst );
  118202. pushOntoSorter(
  118203. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  118204. }else{
  118205. assert( nResultCol==pDest->nSdst );
  118206. assert( regResult==iParm );
  118207. /* The LIMIT clause will jump out of the loop for us */
  118208. }
  118209. break;
  118210. }
  118211. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  118212. case SRT_Coroutine: /* Send data to a co-routine */
  118213. case SRT_Output: { /* Return the results */
  118214. testcase( eDest==SRT_Coroutine );
  118215. testcase( eDest==SRT_Output );
  118216. if( pSort ){
  118217. pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
  118218. nPrefixReg);
  118219. }else if( eDest==SRT_Coroutine ){
  118220. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  118221. }else{
  118222. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  118223. }
  118224. break;
  118225. }
  118226. #ifndef SQLITE_OMIT_CTE
  118227. /* Write the results into a priority queue that is order according to
  118228. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  118229. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  118230. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  118231. ** final OP_Sequence column. The last column is the record as a blob.
  118232. */
  118233. case SRT_DistQueue:
  118234. case SRT_Queue: {
  118235. int nKey;
  118236. int r1, r2, r3;
  118237. int addrTest = 0;
  118238. ExprList *pSO;
  118239. pSO = pDest->pOrderBy;
  118240. assert( pSO );
  118241. nKey = pSO->nExpr;
  118242. r1 = sqlite3GetTempReg(pParse);
  118243. r2 = sqlite3GetTempRange(pParse, nKey+2);
  118244. r3 = r2+nKey+1;
  118245. if( eDest==SRT_DistQueue ){
  118246. /* If the destination is DistQueue, then cursor (iParm+1) is open
  118247. ** on a second ephemeral index that holds all values every previously
  118248. ** added to the queue. */
  118249. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  118250. regResult, nResultCol);
  118251. VdbeCoverage(v);
  118252. }
  118253. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  118254. if( eDest==SRT_DistQueue ){
  118255. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  118256. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  118257. }
  118258. for(i=0; i<nKey; i++){
  118259. sqlite3VdbeAddOp2(v, OP_SCopy,
  118260. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  118261. r2+i);
  118262. }
  118263. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  118264. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  118265. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
  118266. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  118267. sqlite3ReleaseTempReg(pParse, r1);
  118268. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  118269. break;
  118270. }
  118271. #endif /* SQLITE_OMIT_CTE */
  118272. #if !defined(SQLITE_OMIT_TRIGGER)
  118273. /* Discard the results. This is used for SELECT statements inside
  118274. ** the body of a TRIGGER. The purpose of such selects is to call
  118275. ** user-defined functions that have side effects. We do not care
  118276. ** about the actual results of the select.
  118277. */
  118278. default: {
  118279. assert( eDest==SRT_Discard );
  118280. break;
  118281. }
  118282. #endif
  118283. }
  118284. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  118285. ** there is a sorter, in which case the sorter has already limited
  118286. ** the output for us.
  118287. */
  118288. if( pSort==0 && p->iLimit ){
  118289. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  118290. }
  118291. }
  118292. /*
  118293. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  118294. ** X extra columns.
  118295. */
  118296. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  118297. int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
  118298. KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
  118299. if( p ){
  118300. p->aSortOrder = (u8*)&p->aColl[N+X];
  118301. p->nKeyField = (u16)N;
  118302. p->nAllField = (u16)(N+X);
  118303. p->enc = ENC(db);
  118304. p->db = db;
  118305. p->nRef = 1;
  118306. memset(&p[1], 0, nExtra);
  118307. }else{
  118308. sqlite3OomFault(db);
  118309. }
  118310. return p;
  118311. }
  118312. /*
  118313. ** Deallocate a KeyInfo object
  118314. */
  118315. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  118316. if( p ){
  118317. assert( p->nRef>0 );
  118318. p->nRef--;
  118319. if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
  118320. }
  118321. }
  118322. /*
  118323. ** Make a new pointer to a KeyInfo object
  118324. */
  118325. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  118326. if( p ){
  118327. assert( p->nRef>0 );
  118328. p->nRef++;
  118329. }
  118330. return p;
  118331. }
  118332. #ifdef SQLITE_DEBUG
  118333. /*
  118334. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  118335. ** can only be changed if this is just a single reference to the object.
  118336. **
  118337. ** This routine is used only inside of assert() statements.
  118338. */
  118339. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  118340. #endif /* SQLITE_DEBUG */
  118341. /*
  118342. ** Given an expression list, generate a KeyInfo structure that records
  118343. ** the collating sequence for each expression in that expression list.
  118344. **
  118345. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  118346. ** KeyInfo structure is appropriate for initializing a virtual index to
  118347. ** implement that clause. If the ExprList is the result set of a SELECT
  118348. ** then the KeyInfo structure is appropriate for initializing a virtual
  118349. ** index to implement a DISTINCT test.
  118350. **
  118351. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  118352. ** function is responsible for seeing that this structure is eventually
  118353. ** freed.
  118354. */
  118355. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(
  118356. Parse *pParse, /* Parsing context */
  118357. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  118358. int iStart, /* Begin with this column of pList */
  118359. int nExtra /* Add this many extra columns to the end */
  118360. ){
  118361. int nExpr;
  118362. KeyInfo *pInfo;
  118363. struct ExprList_item *pItem;
  118364. sqlite3 *db = pParse->db;
  118365. int i;
  118366. nExpr = pList->nExpr;
  118367. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  118368. if( pInfo ){
  118369. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  118370. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  118371. pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
  118372. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  118373. }
  118374. }
  118375. return pInfo;
  118376. }
  118377. /*
  118378. ** Name of the connection operator, used for error messages.
  118379. */
  118380. static const char *selectOpName(int id){
  118381. char *z;
  118382. switch( id ){
  118383. case TK_ALL: z = "UNION ALL"; break;
  118384. case TK_INTERSECT: z = "INTERSECT"; break;
  118385. case TK_EXCEPT: z = "EXCEPT"; break;
  118386. default: z = "UNION"; break;
  118387. }
  118388. return z;
  118389. }
  118390. #ifndef SQLITE_OMIT_EXPLAIN
  118391. /*
  118392. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  118393. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  118394. ** where the caption is of the form:
  118395. **
  118396. ** "USE TEMP B-TREE FOR xxx"
  118397. **
  118398. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  118399. ** is determined by the zUsage argument.
  118400. */
  118401. static void explainTempTable(Parse *pParse, const char *zUsage){
  118402. ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
  118403. }
  118404. /*
  118405. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  118406. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  118407. ** in sqlite3Select() to assign values to structure member variables that
  118408. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  118409. ** code with #ifndef directives.
  118410. */
  118411. # define explainSetInteger(a, b) a = b
  118412. #else
  118413. /* No-op versions of the explainXXX() functions and macros. */
  118414. # define explainTempTable(y,z)
  118415. # define explainSetInteger(y,z)
  118416. #endif
  118417. /*
  118418. ** If the inner loop was generated using a non-null pOrderBy argument,
  118419. ** then the results were placed in a sorter. After the loop is terminated
  118420. ** we need to run the sorter and output the results. The following
  118421. ** routine generates the code needed to do that.
  118422. */
  118423. static void generateSortTail(
  118424. Parse *pParse, /* Parsing context */
  118425. Select *p, /* The SELECT statement */
  118426. SortCtx *pSort, /* Information on the ORDER BY clause */
  118427. int nColumn, /* Number of columns of data */
  118428. SelectDest *pDest /* Write the sorted results here */
  118429. ){
  118430. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  118431. int addrBreak = pSort->labelDone; /* Jump here to exit loop */
  118432. int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
  118433. int addr; /* Top of output loop. Jump for Next. */
  118434. int addrOnce = 0;
  118435. int iTab;
  118436. ExprList *pOrderBy = pSort->pOrderBy;
  118437. int eDest = pDest->eDest;
  118438. int iParm = pDest->iSDParm;
  118439. int regRow;
  118440. int regRowid;
  118441. int iCol;
  118442. int nKey; /* Number of key columns in sorter record */
  118443. int iSortTab; /* Sorter cursor to read from */
  118444. int i;
  118445. int bSeq; /* True if sorter record includes seq. no. */
  118446. int nRefKey = 0;
  118447. struct ExprList_item *aOutEx = p->pEList->a;
  118448. assert( addrBreak<0 );
  118449. if( pSort->labelBkOut ){
  118450. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  118451. sqlite3VdbeGoto(v, addrBreak);
  118452. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  118453. }
  118454. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118455. /* Open any cursors needed for sorter-reference expressions */
  118456. for(i=0; i<pSort->nDefer; i++){
  118457. Table *pTab = pSort->aDefer[i].pTab;
  118458. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  118459. sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
  118460. nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
  118461. }
  118462. #endif
  118463. iTab = pSort->iECursor;
  118464. if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
  118465. regRowid = 0;
  118466. regRow = pDest->iSdst;
  118467. }else{
  118468. regRowid = sqlite3GetTempReg(pParse);
  118469. if( eDest==SRT_EphemTab || eDest==SRT_Table ){
  118470. regRow = sqlite3GetTempReg(pParse);
  118471. nColumn = 0;
  118472. }else{
  118473. regRow = sqlite3GetTempRange(pParse, nColumn);
  118474. }
  118475. }
  118476. nKey = pOrderBy->nExpr - pSort->nOBSat;
  118477. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  118478. int regSortOut = ++pParse->nMem;
  118479. iSortTab = pParse->nTab++;
  118480. if( pSort->labelBkOut ){
  118481. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  118482. }
  118483. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
  118484. nKey+1+nColumn+nRefKey);
  118485. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  118486. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  118487. VdbeCoverage(v);
  118488. codeOffset(v, p->iOffset, addrContinue);
  118489. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  118490. bSeq = 0;
  118491. }else{
  118492. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  118493. codeOffset(v, p->iOffset, addrContinue);
  118494. iSortTab = iTab;
  118495. bSeq = 1;
  118496. }
  118497. for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
  118498. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118499. if( aOutEx[i].bSorterRef ) continue;
  118500. #endif
  118501. if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
  118502. }
  118503. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118504. if( pSort->nDefer ){
  118505. int iKey = iCol+1;
  118506. int regKey = sqlite3GetTempRange(pParse, nRefKey);
  118507. for(i=0; i<pSort->nDefer; i++){
  118508. int iCsr = pSort->aDefer[i].iCsr;
  118509. Table *pTab = pSort->aDefer[i].pTab;
  118510. int nKey = pSort->aDefer[i].nKey;
  118511. sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
  118512. if( HasRowid(pTab) ){
  118513. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
  118514. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
  118515. sqlite3VdbeCurrentAddr(v)+1, regKey);
  118516. }else{
  118517. int k;
  118518. int iJmp;
  118519. assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
  118520. for(k=0; k<nKey; k++){
  118521. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
  118522. }
  118523. iJmp = sqlite3VdbeCurrentAddr(v);
  118524. sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
  118525. sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
  118526. sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
  118527. }
  118528. }
  118529. sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
  118530. }
  118531. #endif
  118532. for(i=nColumn-1; i>=0; i--){
  118533. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  118534. if( aOutEx[i].bSorterRef ){
  118535. sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
  118536. }else
  118537. #endif
  118538. {
  118539. int iRead;
  118540. if( aOutEx[i].u.x.iOrderByCol ){
  118541. iRead = aOutEx[i].u.x.iOrderByCol-1;
  118542. }else{
  118543. iRead = iCol--;
  118544. }
  118545. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
  118546. VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan));
  118547. }
  118548. }
  118549. switch( eDest ){
  118550. case SRT_Table:
  118551. case SRT_EphemTab: {
  118552. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
  118553. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  118554. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  118555. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  118556. break;
  118557. }
  118558. #ifndef SQLITE_OMIT_SUBQUERY
  118559. case SRT_Set: {
  118560. assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
  118561. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
  118562. pDest->zAffSdst, nColumn);
  118563. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
  118564. break;
  118565. }
  118566. case SRT_Mem: {
  118567. /* The LIMIT clause will terminate the loop for us */
  118568. break;
  118569. }
  118570. #endif
  118571. default: {
  118572. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  118573. testcase( eDest==SRT_Output );
  118574. testcase( eDest==SRT_Coroutine );
  118575. if( eDest==SRT_Output ){
  118576. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  118577. }else{
  118578. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  118579. }
  118580. break;
  118581. }
  118582. }
  118583. if( regRowid ){
  118584. if( eDest==SRT_Set ){
  118585. sqlite3ReleaseTempRange(pParse, regRow, nColumn);
  118586. }else{
  118587. sqlite3ReleaseTempReg(pParse, regRow);
  118588. }
  118589. sqlite3ReleaseTempReg(pParse, regRowid);
  118590. }
  118591. /* The bottom of the loop
  118592. */
  118593. sqlite3VdbeResolveLabel(v, addrContinue);
  118594. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  118595. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  118596. }else{
  118597. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  118598. }
  118599. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  118600. sqlite3VdbeResolveLabel(v, addrBreak);
  118601. }
  118602. /*
  118603. ** Return a pointer to a string containing the 'declaration type' of the
  118604. ** expression pExpr. The string may be treated as static by the caller.
  118605. **
  118606. ** Also try to estimate the size of the returned value and return that
  118607. ** result in *pEstWidth.
  118608. **
  118609. ** The declaration type is the exact datatype definition extracted from the
  118610. ** original CREATE TABLE statement if the expression is a column. The
  118611. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  118612. ** is considered a column can be complex in the presence of subqueries. The
  118613. ** result-set expression in all of the following SELECT statements is
  118614. ** considered a column by this function.
  118615. **
  118616. ** SELECT col FROM tbl;
  118617. ** SELECT (SELECT col FROM tbl;
  118618. ** SELECT (SELECT col FROM tbl);
  118619. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  118620. **
  118621. ** The declaration type for any expression other than a column is NULL.
  118622. **
  118623. ** This routine has either 3 or 6 parameters depending on whether or not
  118624. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  118625. */
  118626. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  118627. # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
  118628. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  118629. # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
  118630. #endif
  118631. static const char *columnTypeImpl(
  118632. NameContext *pNC,
  118633. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  118634. Expr *pExpr
  118635. #else
  118636. Expr *pExpr,
  118637. const char **pzOrigDb,
  118638. const char **pzOrigTab,
  118639. const char **pzOrigCol
  118640. #endif
  118641. ){
  118642. char const *zType = 0;
  118643. int j;
  118644. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  118645. char const *zOrigDb = 0;
  118646. char const *zOrigTab = 0;
  118647. char const *zOrigCol = 0;
  118648. #endif
  118649. assert( pExpr!=0 );
  118650. assert( pNC->pSrcList!=0 );
  118651. assert( pExpr->op!=TK_AGG_COLUMN ); /* This routine runes before aggregates
  118652. ** are processed */
  118653. switch( pExpr->op ){
  118654. case TK_COLUMN: {
  118655. /* The expression is a column. Locate the table the column is being
  118656. ** extracted from in NameContext.pSrcList. This table may be real
  118657. ** database table or a subquery.
  118658. */
  118659. Table *pTab = 0; /* Table structure column is extracted from */
  118660. Select *pS = 0; /* Select the column is extracted from */
  118661. int iCol = pExpr->iColumn; /* Index of column in pTab */
  118662. while( pNC && !pTab ){
  118663. SrcList *pTabList = pNC->pSrcList;
  118664. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  118665. if( j<pTabList->nSrc ){
  118666. pTab = pTabList->a[j].pTab;
  118667. pS = pTabList->a[j].pSelect;
  118668. }else{
  118669. pNC = pNC->pNext;
  118670. }
  118671. }
  118672. if( pTab==0 ){
  118673. /* At one time, code such as "SELECT new.x" within a trigger would
  118674. ** cause this condition to run. Since then, we have restructured how
  118675. ** trigger code is generated and so this condition is no longer
  118676. ** possible. However, it can still be true for statements like
  118677. ** the following:
  118678. **
  118679. ** CREATE TABLE t1(col INTEGER);
  118680. ** SELECT (SELECT t1.col) FROM FROM t1;
  118681. **
  118682. ** when columnType() is called on the expression "t1.col" in the
  118683. ** sub-select. In this case, set the column type to NULL, even
  118684. ** though it should really be "INTEGER".
  118685. **
  118686. ** This is not a problem, as the column type of "t1.col" is never
  118687. ** used. When columnType() is called on the expression
  118688. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  118689. ** branch below. */
  118690. break;
  118691. }
  118692. assert( pTab && pExpr->y.pTab==pTab );
  118693. if( pS ){
  118694. /* The "table" is actually a sub-select or a view in the FROM clause
  118695. ** of the SELECT statement. Return the declaration type and origin
  118696. ** data for the result-set column of the sub-select.
  118697. */
  118698. if( iCol>=0 && iCol<pS->pEList->nExpr ){
  118699. /* If iCol is less than zero, then the expression requests the
  118700. ** rowid of the sub-select or view. This expression is legal (see
  118701. ** test case misc2.2.2) - it always evaluates to NULL.
  118702. */
  118703. NameContext sNC;
  118704. Expr *p = pS->pEList->a[iCol].pExpr;
  118705. sNC.pSrcList = pS->pSrc;
  118706. sNC.pNext = pNC;
  118707. sNC.pParse = pNC->pParse;
  118708. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
  118709. }
  118710. }else{
  118711. /* A real table or a CTE table */
  118712. assert( !pS );
  118713. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  118714. if( iCol<0 ) iCol = pTab->iPKey;
  118715. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  118716. if( iCol<0 ){
  118717. zType = "INTEGER";
  118718. zOrigCol = "rowid";
  118719. }else{
  118720. zOrigCol = pTab->aCol[iCol].zName;
  118721. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  118722. }
  118723. zOrigTab = pTab->zName;
  118724. if( pNC->pParse && pTab->pSchema ){
  118725. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  118726. zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
  118727. }
  118728. #else
  118729. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  118730. if( iCol<0 ){
  118731. zType = "INTEGER";
  118732. }else{
  118733. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  118734. }
  118735. #endif
  118736. }
  118737. break;
  118738. }
  118739. #ifndef SQLITE_OMIT_SUBQUERY
  118740. case TK_SELECT: {
  118741. /* The expression is a sub-select. Return the declaration type and
  118742. ** origin info for the single column in the result set of the SELECT
  118743. ** statement.
  118744. */
  118745. NameContext sNC;
  118746. Select *pS = pExpr->x.pSelect;
  118747. Expr *p = pS->pEList->a[0].pExpr;
  118748. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  118749. sNC.pSrcList = pS->pSrc;
  118750. sNC.pNext = pNC;
  118751. sNC.pParse = pNC->pParse;
  118752. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  118753. break;
  118754. }
  118755. #endif
  118756. }
  118757. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  118758. if( pzOrigDb ){
  118759. assert( pzOrigTab && pzOrigCol );
  118760. *pzOrigDb = zOrigDb;
  118761. *pzOrigTab = zOrigTab;
  118762. *pzOrigCol = zOrigCol;
  118763. }
  118764. #endif
  118765. return zType;
  118766. }
  118767. /*
  118768. ** Generate code that will tell the VDBE the declaration types of columns
  118769. ** in the result set.
  118770. */
  118771. static void generateColumnTypes(
  118772. Parse *pParse, /* Parser context */
  118773. SrcList *pTabList, /* List of tables */
  118774. ExprList *pEList /* Expressions defining the result set */
  118775. ){
  118776. #ifndef SQLITE_OMIT_DECLTYPE
  118777. Vdbe *v = pParse->pVdbe;
  118778. int i;
  118779. NameContext sNC;
  118780. sNC.pSrcList = pTabList;
  118781. sNC.pParse = pParse;
  118782. sNC.pNext = 0;
  118783. for(i=0; i<pEList->nExpr; i++){
  118784. Expr *p = pEList->a[i].pExpr;
  118785. const char *zType;
  118786. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  118787. const char *zOrigDb = 0;
  118788. const char *zOrigTab = 0;
  118789. const char *zOrigCol = 0;
  118790. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  118791. /* The vdbe must make its own copy of the column-type and other
  118792. ** column specific strings, in case the schema is reset before this
  118793. ** virtual machine is deleted.
  118794. */
  118795. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  118796. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  118797. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  118798. #else
  118799. zType = columnType(&sNC, p, 0, 0, 0);
  118800. #endif
  118801. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  118802. }
  118803. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  118804. }
  118805. /*
  118806. ** Compute the column names for a SELECT statement.
  118807. **
  118808. ** The only guarantee that SQLite makes about column names is that if the
  118809. ** column has an AS clause assigning it a name, that will be the name used.
  118810. ** That is the only documented guarantee. However, countless applications
  118811. ** developed over the years have made baseless assumptions about column names
  118812. ** and will break if those assumptions changes. Hence, use extreme caution
  118813. ** when modifying this routine to avoid breaking legacy.
  118814. **
  118815. ** See Also: sqlite3ColumnsFromExprList()
  118816. **
  118817. ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
  118818. ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
  118819. ** applications should operate this way. Nevertheless, we need to support the
  118820. ** other modes for legacy:
  118821. **
  118822. ** short=OFF, full=OFF: Column name is the text of the expression has it
  118823. ** originally appears in the SELECT statement. In
  118824. ** other words, the zSpan of the result expression.
  118825. **
  118826. ** short=ON, full=OFF: (This is the default setting). If the result
  118827. ** refers directly to a table column, then the
  118828. ** result column name is just the table column
  118829. ** name: COLUMN. Otherwise use zSpan.
  118830. **
  118831. ** full=ON, short=ANY: If the result refers directly to a table column,
  118832. ** then the result column name with the table name
  118833. ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
  118834. */
  118835. static void generateColumnNames(
  118836. Parse *pParse, /* Parser context */
  118837. Select *pSelect /* Generate column names for this SELECT statement */
  118838. ){
  118839. Vdbe *v = pParse->pVdbe;
  118840. int i;
  118841. Table *pTab;
  118842. SrcList *pTabList;
  118843. ExprList *pEList;
  118844. sqlite3 *db = pParse->db;
  118845. int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
  118846. int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
  118847. #ifndef SQLITE_OMIT_EXPLAIN
  118848. /* If this is an EXPLAIN, skip this step */
  118849. if( pParse->explain ){
  118850. return;
  118851. }
  118852. #endif
  118853. if( pParse->colNamesSet ) return;
  118854. /* Column names are determined by the left-most term of a compound select */
  118855. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  118856. SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
  118857. pTabList = pSelect->pSrc;
  118858. pEList = pSelect->pEList;
  118859. assert( v!=0 );
  118860. assert( pTabList!=0 );
  118861. pParse->colNamesSet = 1;
  118862. fullName = (db->flags & SQLITE_FullColNames)!=0;
  118863. srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
  118864. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  118865. for(i=0; i<pEList->nExpr; i++){
  118866. Expr *p = pEList->a[i].pExpr;
  118867. assert( p!=0 );
  118868. assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
  118869. assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
  118870. if( pEList->a[i].zName ){
  118871. /* An AS clause always takes first priority */
  118872. char *zName = pEList->a[i].zName;
  118873. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  118874. }else if( srcName && p->op==TK_COLUMN ){
  118875. char *zCol;
  118876. int iCol = p->iColumn;
  118877. pTab = p->y.pTab;
  118878. assert( pTab!=0 );
  118879. if( iCol<0 ) iCol = pTab->iPKey;
  118880. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  118881. if( iCol<0 ){
  118882. zCol = "rowid";
  118883. }else{
  118884. zCol = pTab->aCol[iCol].zName;
  118885. }
  118886. if( fullName ){
  118887. char *zName = 0;
  118888. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  118889. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  118890. }else{
  118891. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  118892. }
  118893. }else{
  118894. const char *z = pEList->a[i].zSpan;
  118895. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  118896. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  118897. }
  118898. }
  118899. generateColumnTypes(pParse, pTabList, pEList);
  118900. }
  118901. /*
  118902. ** Given an expression list (which is really the list of expressions
  118903. ** that form the result set of a SELECT statement) compute appropriate
  118904. ** column names for a table that would hold the expression list.
  118905. **
  118906. ** All column names will be unique.
  118907. **
  118908. ** Only the column names are computed. Column.zType, Column.zColl,
  118909. ** and other fields of Column are zeroed.
  118910. **
  118911. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  118912. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  118913. **
  118914. ** The only guarantee that SQLite makes about column names is that if the
  118915. ** column has an AS clause assigning it a name, that will be the name used.
  118916. ** That is the only documented guarantee. However, countless applications
  118917. ** developed over the years have made baseless assumptions about column names
  118918. ** and will break if those assumptions changes. Hence, use extreme caution
  118919. ** when modifying this routine to avoid breaking legacy.
  118920. **
  118921. ** See Also: generateColumnNames()
  118922. */
  118923. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  118924. Parse *pParse, /* Parsing context */
  118925. ExprList *pEList, /* Expr list from which to derive column names */
  118926. i16 *pnCol, /* Write the number of columns here */
  118927. Column **paCol /* Write the new column list here */
  118928. ){
  118929. sqlite3 *db = pParse->db; /* Database connection */
  118930. int i, j; /* Loop counters */
  118931. u32 cnt; /* Index added to make the name unique */
  118932. Column *aCol, *pCol; /* For looping over result columns */
  118933. int nCol; /* Number of columns in the result set */
  118934. char *zName; /* Column name */
  118935. int nName; /* Size of name in zName[] */
  118936. Hash ht; /* Hash table of column names */
  118937. sqlite3HashInit(&ht);
  118938. if( pEList ){
  118939. nCol = pEList->nExpr;
  118940. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  118941. testcase( aCol==0 );
  118942. if( nCol>32767 ) nCol = 32767;
  118943. }else{
  118944. nCol = 0;
  118945. aCol = 0;
  118946. }
  118947. assert( nCol==(i16)nCol );
  118948. *pnCol = nCol;
  118949. *paCol = aCol;
  118950. for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
  118951. /* Get an appropriate name for the column
  118952. */
  118953. if( (zName = pEList->a[i].zName)!=0 ){
  118954. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  118955. }else{
  118956. Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  118957. while( pColExpr->op==TK_DOT ){
  118958. pColExpr = pColExpr->pRight;
  118959. assert( pColExpr!=0 );
  118960. }
  118961. assert( pColExpr->op!=TK_AGG_COLUMN );
  118962. if( pColExpr->op==TK_COLUMN ){
  118963. /* For columns use the column name name */
  118964. int iCol = pColExpr->iColumn;
  118965. Table *pTab = pColExpr->y.pTab;
  118966. assert( pTab!=0 );
  118967. if( iCol<0 ) iCol = pTab->iPKey;
  118968. zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
  118969. }else if( pColExpr->op==TK_ID ){
  118970. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  118971. zName = pColExpr->u.zToken;
  118972. }else{
  118973. /* Use the original text of the column expression as its name */
  118974. zName = pEList->a[i].zSpan;
  118975. }
  118976. }
  118977. if( zName ){
  118978. zName = sqlite3DbStrDup(db, zName);
  118979. }else{
  118980. zName = sqlite3MPrintf(db,"column%d",i+1);
  118981. }
  118982. /* Make sure the column name is unique. If the name is not unique,
  118983. ** append an integer to the name so that it becomes unique.
  118984. */
  118985. cnt = 0;
  118986. while( zName && sqlite3HashFind(&ht, zName)!=0 ){
  118987. nName = sqlite3Strlen30(zName);
  118988. if( nName>0 ){
  118989. for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
  118990. if( zName[j]==':' ) nName = j;
  118991. }
  118992. zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  118993. if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  118994. }
  118995. pCol->zName = zName;
  118996. sqlite3ColumnPropertiesFromName(0, pCol);
  118997. if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  118998. sqlite3OomFault(db);
  118999. }
  119000. }
  119001. sqlite3HashClear(&ht);
  119002. if( db->mallocFailed ){
  119003. for(j=0; j<i; j++){
  119004. sqlite3DbFree(db, aCol[j].zName);
  119005. }
  119006. sqlite3DbFree(db, aCol);
  119007. *paCol = 0;
  119008. *pnCol = 0;
  119009. return SQLITE_NOMEM_BKPT;
  119010. }
  119011. return SQLITE_OK;
  119012. }
  119013. /*
  119014. ** Add type and collation information to a column list based on
  119015. ** a SELECT statement.
  119016. **
  119017. ** The column list presumably came from selectColumnNamesFromExprList().
  119018. ** The column list has only names, not types or collations. This
  119019. ** routine goes through and adds the types and collations.
  119020. **
  119021. ** This routine requires that all identifiers in the SELECT
  119022. ** statement be resolved.
  119023. */
  119024. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
  119025. Parse *pParse, /* Parsing contexts */
  119026. Table *pTab, /* Add column type information to this table */
  119027. Select *pSelect /* SELECT used to determine types and collations */
  119028. ){
  119029. sqlite3 *db = pParse->db;
  119030. NameContext sNC;
  119031. Column *pCol;
  119032. CollSeq *pColl;
  119033. int i;
  119034. Expr *p;
  119035. struct ExprList_item *a;
  119036. assert( pSelect!=0 );
  119037. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  119038. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  119039. if( db->mallocFailed ) return;
  119040. memset(&sNC, 0, sizeof(sNC));
  119041. sNC.pSrcList = pSelect->pSrc;
  119042. a = pSelect->pEList->a;
  119043. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  119044. const char *zType;
  119045. int n, m;
  119046. p = a[i].pExpr;
  119047. zType = columnType(&sNC, p, 0, 0, 0);
  119048. /* pCol->szEst = ... // Column size est for SELECT tables never used */
  119049. pCol->affinity = sqlite3ExprAffinity(p);
  119050. if( zType ){
  119051. m = sqlite3Strlen30(zType);
  119052. n = sqlite3Strlen30(pCol->zName);
  119053. pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
  119054. if( pCol->zName ){
  119055. memcpy(&pCol->zName[n+1], zType, m+1);
  119056. pCol->colFlags |= COLFLAG_HASTYPE;
  119057. }
  119058. }
  119059. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  119060. pColl = sqlite3ExprCollSeq(pParse, p);
  119061. if( pColl && pCol->zColl==0 ){
  119062. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  119063. }
  119064. }
  119065. pTab->szTabRow = 1; /* Any non-zero value works */
  119066. }
  119067. /*
  119068. ** Given a SELECT statement, generate a Table structure that describes
  119069. ** the result set of that SELECT.
  119070. */
  119071. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  119072. Table *pTab;
  119073. sqlite3 *db = pParse->db;
  119074. u64 savedFlags;
  119075. savedFlags = db->flags;
  119076. db->flags &= ~(u64)SQLITE_FullColNames;
  119077. db->flags |= SQLITE_ShortColNames;
  119078. sqlite3SelectPrep(pParse, pSelect, 0);
  119079. db->flags = savedFlags;
  119080. if( pParse->nErr ) return 0;
  119081. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  119082. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  119083. if( pTab==0 ){
  119084. return 0;
  119085. }
  119086. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  119087. ** is disabled */
  119088. assert( db->lookaside.bDisable );
  119089. pTab->nTabRef = 1;
  119090. pTab->zName = 0;
  119091. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  119092. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  119093. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  119094. pTab->iPKey = -1;
  119095. if( db->mallocFailed ){
  119096. sqlite3DeleteTable(db, pTab);
  119097. return 0;
  119098. }
  119099. return pTab;
  119100. }
  119101. /*
  119102. ** Get a VDBE for the given parser context. Create a new one if necessary.
  119103. ** If an error occurs, return NULL and leave a message in pParse.
  119104. */
  119105. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  119106. if( pParse->pVdbe ){
  119107. return pParse->pVdbe;
  119108. }
  119109. if( pParse->pToplevel==0
  119110. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  119111. ){
  119112. pParse->okConstFactor = 1;
  119113. }
  119114. return sqlite3VdbeCreate(pParse);
  119115. }
  119116. /*
  119117. ** Compute the iLimit and iOffset fields of the SELECT based on the
  119118. ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
  119119. ** that appear in the original SQL statement after the LIMIT and OFFSET
  119120. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  119121. ** are the integer memory register numbers for counters used to compute
  119122. ** the limit and offset. If there is no limit and/or offset, then
  119123. ** iLimit and iOffset are negative.
  119124. **
  119125. ** This routine changes the values of iLimit and iOffset only if
  119126. ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
  119127. ** and iOffset should have been preset to appropriate default values (zero)
  119128. ** prior to calling this routine.
  119129. **
  119130. ** The iOffset register (if it exists) is initialized to the value
  119131. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  119132. ** iOffset+1 is initialized to LIMIT+OFFSET.
  119133. **
  119134. ** Only if pLimit->pLeft!=0 do the limit registers get
  119135. ** redefined. The UNION ALL operator uses this property to force
  119136. ** the reuse of the same limit and offset registers across multiple
  119137. ** SELECT statements.
  119138. */
  119139. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  119140. Vdbe *v = 0;
  119141. int iLimit = 0;
  119142. int iOffset;
  119143. int n;
  119144. Expr *pLimit = p->pLimit;
  119145. if( p->iLimit ) return;
  119146. /*
  119147. ** "LIMIT -1" always shows all rows. There is some
  119148. ** controversy about what the correct behavior should be.
  119149. ** The current implementation interprets "LIMIT 0" to mean
  119150. ** no rows.
  119151. */
  119152. if( pLimit ){
  119153. assert( pLimit->op==TK_LIMIT );
  119154. assert( pLimit->pLeft!=0 );
  119155. p->iLimit = iLimit = ++pParse->nMem;
  119156. v = sqlite3GetVdbe(pParse);
  119157. assert( v!=0 );
  119158. if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
  119159. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  119160. VdbeComment((v, "LIMIT counter"));
  119161. if( n==0 ){
  119162. sqlite3VdbeGoto(v, iBreak);
  119163. }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
  119164. p->nSelectRow = sqlite3LogEst((u64)n);
  119165. p->selFlags |= SF_FixedLimit;
  119166. }
  119167. }else{
  119168. sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
  119169. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  119170. VdbeComment((v, "LIMIT counter"));
  119171. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  119172. }
  119173. if( pLimit->pRight ){
  119174. p->iOffset = iOffset = ++pParse->nMem;
  119175. pParse->nMem++; /* Allocate an extra register for limit+offset */
  119176. sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
  119177. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  119178. VdbeComment((v, "OFFSET counter"));
  119179. sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
  119180. VdbeComment((v, "LIMIT+OFFSET"));
  119181. }
  119182. }
  119183. }
  119184. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  119185. /*
  119186. ** Return the appropriate collating sequence for the iCol-th column of
  119187. ** the result set for the compound-select statement "p". Return NULL if
  119188. ** the column has no default collating sequence.
  119189. **
  119190. ** The collating sequence for the compound select is taken from the
  119191. ** left-most term of the select that has a collating sequence.
  119192. */
  119193. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  119194. CollSeq *pRet;
  119195. if( p->pPrior ){
  119196. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  119197. }else{
  119198. pRet = 0;
  119199. }
  119200. assert( iCol>=0 );
  119201. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  119202. ** have been thrown during name resolution and we would not have gotten
  119203. ** this far */
  119204. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  119205. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  119206. }
  119207. return pRet;
  119208. }
  119209. /*
  119210. ** The select statement passed as the second parameter is a compound SELECT
  119211. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  119212. ** structure suitable for implementing the ORDER BY.
  119213. **
  119214. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  119215. ** function is responsible for ensuring that this structure is eventually
  119216. ** freed.
  119217. */
  119218. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  119219. ExprList *pOrderBy = p->pOrderBy;
  119220. int nOrderBy = p->pOrderBy->nExpr;
  119221. sqlite3 *db = pParse->db;
  119222. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  119223. if( pRet ){
  119224. int i;
  119225. for(i=0; i<nOrderBy; i++){
  119226. struct ExprList_item *pItem = &pOrderBy->a[i];
  119227. Expr *pTerm = pItem->pExpr;
  119228. CollSeq *pColl;
  119229. if( pTerm->flags & EP_Collate ){
  119230. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  119231. }else{
  119232. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  119233. if( pColl==0 ) pColl = db->pDfltColl;
  119234. pOrderBy->a[i].pExpr =
  119235. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  119236. }
  119237. assert( sqlite3KeyInfoIsWriteable(pRet) );
  119238. pRet->aColl[i] = pColl;
  119239. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  119240. }
  119241. }
  119242. return pRet;
  119243. }
  119244. #ifndef SQLITE_OMIT_CTE
  119245. /*
  119246. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  119247. ** query of the form:
  119248. **
  119249. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  119250. ** \___________/ \_______________/
  119251. ** p->pPrior p
  119252. **
  119253. **
  119254. ** There is exactly one reference to the recursive-table in the FROM clause
  119255. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  119256. **
  119257. ** The setup-query runs once to generate an initial set of rows that go
  119258. ** into a Queue table. Rows are extracted from the Queue table one by
  119259. ** one. Each row extracted from Queue is output to pDest. Then the single
  119260. ** extracted row (now in the iCurrent table) becomes the content of the
  119261. ** recursive-table for a recursive-query run. The output of the recursive-query
  119262. ** is added back into the Queue table. Then another row is extracted from Queue
  119263. ** and the iteration continues until the Queue table is empty.
  119264. **
  119265. ** If the compound query operator is UNION then no duplicate rows are ever
  119266. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  119267. ** that have ever been inserted into Queue and causes duplicates to be
  119268. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  119269. **
  119270. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  119271. ** ORDER BY order and the first entry is extracted for each cycle. Without
  119272. ** an ORDER BY, the Queue table is just a FIFO.
  119273. **
  119274. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  119275. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  119276. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  119277. ** with a positive value, then the first OFFSET outputs are discarded rather
  119278. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  119279. ** rows have been skipped.
  119280. */
  119281. static void generateWithRecursiveQuery(
  119282. Parse *pParse, /* Parsing context */
  119283. Select *p, /* The recursive SELECT to be coded */
  119284. SelectDest *pDest /* What to do with query results */
  119285. ){
  119286. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  119287. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  119288. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  119289. Select *pSetup = p->pPrior; /* The setup query */
  119290. int addrTop; /* Top of the loop */
  119291. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  119292. int iCurrent = 0; /* The Current table */
  119293. int regCurrent; /* Register holding Current table */
  119294. int iQueue; /* The Queue table */
  119295. int iDistinct = 0; /* To ensure unique results if UNION */
  119296. int eDest = SRT_Fifo; /* How to write to Queue */
  119297. SelectDest destQueue; /* SelectDest targetting the Queue table */
  119298. int i; /* Loop counter */
  119299. int rc; /* Result code */
  119300. ExprList *pOrderBy; /* The ORDER BY clause */
  119301. Expr *pLimit; /* Saved LIMIT and OFFSET */
  119302. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  119303. #ifndef SQLITE_OMIT_WINDOWFUNC
  119304. if( p->pWin ){
  119305. sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
  119306. return;
  119307. }
  119308. #endif
  119309. /* Obtain authorization to do a recursive query */
  119310. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  119311. /* Process the LIMIT and OFFSET clauses, if they exist */
  119312. addrBreak = sqlite3VdbeMakeLabel(pParse);
  119313. p->nSelectRow = 320; /* 4 billion rows */
  119314. computeLimitRegisters(pParse, p, addrBreak);
  119315. pLimit = p->pLimit;
  119316. regLimit = p->iLimit;
  119317. regOffset = p->iOffset;
  119318. p->pLimit = 0;
  119319. p->iLimit = p->iOffset = 0;
  119320. pOrderBy = p->pOrderBy;
  119321. /* Locate the cursor number of the Current table */
  119322. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  119323. if( pSrc->a[i].fg.isRecursive ){
  119324. iCurrent = pSrc->a[i].iCursor;
  119325. break;
  119326. }
  119327. }
  119328. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  119329. ** the Distinct table must be exactly one greater than Queue in order
  119330. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  119331. iQueue = pParse->nTab++;
  119332. if( p->op==TK_UNION ){
  119333. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  119334. iDistinct = pParse->nTab++;
  119335. }else{
  119336. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  119337. }
  119338. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  119339. /* Allocate cursors for Current, Queue, and Distinct. */
  119340. regCurrent = ++pParse->nMem;
  119341. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  119342. if( pOrderBy ){
  119343. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  119344. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  119345. (char*)pKeyInfo, P4_KEYINFO);
  119346. destQueue.pOrderBy = pOrderBy;
  119347. }else{
  119348. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  119349. }
  119350. VdbeComment((v, "Queue table"));
  119351. if( iDistinct ){
  119352. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  119353. p->selFlags |= SF_UsesEphemeral;
  119354. }
  119355. /* Detach the ORDER BY clause from the compound SELECT */
  119356. p->pOrderBy = 0;
  119357. /* Store the results of the setup-query in Queue. */
  119358. pSetup->pNext = 0;
  119359. ExplainQueryPlan((pParse, 1, "SETUP"));
  119360. rc = sqlite3Select(pParse, pSetup, &destQueue);
  119361. pSetup->pNext = p;
  119362. if( rc ) goto end_of_recursive_query;
  119363. /* Find the next row in the Queue and output that row */
  119364. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  119365. /* Transfer the next row in Queue over to Current */
  119366. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  119367. if( pOrderBy ){
  119368. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  119369. }else{
  119370. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  119371. }
  119372. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  119373. /* Output the single row in Current */
  119374. addrCont = sqlite3VdbeMakeLabel(pParse);
  119375. codeOffset(v, regOffset, addrCont);
  119376. selectInnerLoop(pParse, p, iCurrent,
  119377. 0, 0, pDest, addrCont, addrBreak);
  119378. if( regLimit ){
  119379. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  119380. VdbeCoverage(v);
  119381. }
  119382. sqlite3VdbeResolveLabel(v, addrCont);
  119383. /* Execute the recursive SELECT taking the single row in Current as
  119384. ** the value for the recursive-table. Store the results in the Queue.
  119385. */
  119386. if( p->selFlags & SF_Aggregate ){
  119387. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  119388. }else{
  119389. p->pPrior = 0;
  119390. ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
  119391. sqlite3Select(pParse, p, &destQueue);
  119392. assert( p->pPrior==0 );
  119393. p->pPrior = pSetup;
  119394. }
  119395. /* Keep running the loop until the Queue is empty */
  119396. sqlite3VdbeGoto(v, addrTop);
  119397. sqlite3VdbeResolveLabel(v, addrBreak);
  119398. end_of_recursive_query:
  119399. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  119400. p->pOrderBy = pOrderBy;
  119401. p->pLimit = pLimit;
  119402. return;
  119403. }
  119404. #endif /* SQLITE_OMIT_CTE */
  119405. /* Forward references */
  119406. static int multiSelectOrderBy(
  119407. Parse *pParse, /* Parsing context */
  119408. Select *p, /* The right-most of SELECTs to be coded */
  119409. SelectDest *pDest /* What to do with query results */
  119410. );
  119411. /*
  119412. ** Handle the special case of a compound-select that originates from a
  119413. ** VALUES clause. By handling this as a special case, we avoid deep
  119414. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  119415. ** on a VALUES clause.
  119416. **
  119417. ** Because the Select object originates from a VALUES clause:
  119418. ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
  119419. ** (2) All terms are UNION ALL
  119420. ** (3) There is no ORDER BY clause
  119421. **
  119422. ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
  119423. ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
  119424. ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
  119425. ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
  119426. */
  119427. static int multiSelectValues(
  119428. Parse *pParse, /* Parsing context */
  119429. Select *p, /* The right-most of SELECTs to be coded */
  119430. SelectDest *pDest /* What to do with query results */
  119431. ){
  119432. int nRow = 1;
  119433. int rc = 0;
  119434. int bShowAll = p->pLimit==0;
  119435. assert( p->selFlags & SF_MultiValue );
  119436. do{
  119437. assert( p->selFlags & SF_Values );
  119438. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  119439. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  119440. if( p->pPrior==0 ) break;
  119441. assert( p->pPrior->pNext==p );
  119442. p = p->pPrior;
  119443. nRow += bShowAll;
  119444. }while(1);
  119445. ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
  119446. nRow==1 ? "" : "S"));
  119447. while( p ){
  119448. selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
  119449. if( !bShowAll ) break;
  119450. p->nSelectRow = nRow;
  119451. p = p->pNext;
  119452. }
  119453. return rc;
  119454. }
  119455. /*
  119456. ** This routine is called to process a compound query form from
  119457. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  119458. ** INTERSECT
  119459. **
  119460. ** "p" points to the right-most of the two queries. the query on the
  119461. ** left is p->pPrior. The left query could also be a compound query
  119462. ** in which case this routine will be called recursively.
  119463. **
  119464. ** The results of the total query are to be written into a destination
  119465. ** of type eDest with parameter iParm.
  119466. **
  119467. ** Example 1: Consider a three-way compound SQL statement.
  119468. **
  119469. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  119470. **
  119471. ** This statement is parsed up as follows:
  119472. **
  119473. ** SELECT c FROM t3
  119474. ** |
  119475. ** `-----> SELECT b FROM t2
  119476. ** |
  119477. ** `------> SELECT a FROM t1
  119478. **
  119479. ** The arrows in the diagram above represent the Select.pPrior pointer.
  119480. ** So if this routine is called with p equal to the t3 query, then
  119481. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  119482. **
  119483. ** Notice that because of the way SQLite parses compound SELECTs, the
  119484. ** individual selects always group from left to right.
  119485. */
  119486. static int multiSelect(
  119487. Parse *pParse, /* Parsing context */
  119488. Select *p, /* The right-most of SELECTs to be coded */
  119489. SelectDest *pDest /* What to do with query results */
  119490. ){
  119491. int rc = SQLITE_OK; /* Success code from a subroutine */
  119492. Select *pPrior; /* Another SELECT immediately to our left */
  119493. Vdbe *v; /* Generate code to this VDBE */
  119494. SelectDest dest; /* Alternative data destination */
  119495. Select *pDelete = 0; /* Chain of simple selects to delete */
  119496. sqlite3 *db; /* Database connection */
  119497. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  119498. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  119499. */
  119500. assert( p && p->pPrior ); /* Calling function guarantees this much */
  119501. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  119502. db = pParse->db;
  119503. pPrior = p->pPrior;
  119504. dest = *pDest;
  119505. if( pPrior->pOrderBy || pPrior->pLimit ){
  119506. sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
  119507. pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
  119508. rc = 1;
  119509. goto multi_select_end;
  119510. }
  119511. v = sqlite3GetVdbe(pParse);
  119512. assert( v!=0 ); /* The VDBE already created by calling function */
  119513. /* Create the destination temporary table if necessary
  119514. */
  119515. if( dest.eDest==SRT_EphemTab ){
  119516. assert( p->pEList );
  119517. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  119518. dest.eDest = SRT_Table;
  119519. }
  119520. /* Special handling for a compound-select that originates as a VALUES clause.
  119521. */
  119522. if( p->selFlags & SF_MultiValue ){
  119523. rc = multiSelectValues(pParse, p, &dest);
  119524. goto multi_select_end;
  119525. }
  119526. /* Make sure all SELECTs in the statement have the same number of elements
  119527. ** in their result sets.
  119528. */
  119529. assert( p->pEList && pPrior->pEList );
  119530. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  119531. #ifndef SQLITE_OMIT_CTE
  119532. if( p->selFlags & SF_Recursive ){
  119533. generateWithRecursiveQuery(pParse, p, &dest);
  119534. }else
  119535. #endif
  119536. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  119537. */
  119538. if( p->pOrderBy ){
  119539. return multiSelectOrderBy(pParse, p, pDest);
  119540. }else{
  119541. #ifndef SQLITE_OMIT_EXPLAIN
  119542. if( pPrior->pPrior==0 ){
  119543. ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
  119544. ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
  119545. }
  119546. #endif
  119547. /* Generate code for the left and right SELECT statements.
  119548. */
  119549. switch( p->op ){
  119550. case TK_ALL: {
  119551. int addr = 0;
  119552. int nLimit;
  119553. assert( !pPrior->pLimit );
  119554. pPrior->iLimit = p->iLimit;
  119555. pPrior->iOffset = p->iOffset;
  119556. pPrior->pLimit = p->pLimit;
  119557. rc = sqlite3Select(pParse, pPrior, &dest);
  119558. p->pLimit = 0;
  119559. if( rc ){
  119560. goto multi_select_end;
  119561. }
  119562. p->pPrior = 0;
  119563. p->iLimit = pPrior->iLimit;
  119564. p->iOffset = pPrior->iOffset;
  119565. if( p->iLimit ){
  119566. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  119567. VdbeComment((v, "Jump ahead if LIMIT reached"));
  119568. if( p->iOffset ){
  119569. sqlite3VdbeAddOp3(v, OP_OffsetLimit,
  119570. p->iLimit, p->iOffset+1, p->iOffset);
  119571. }
  119572. }
  119573. ExplainQueryPlan((pParse, 1, "UNION ALL"));
  119574. rc = sqlite3Select(pParse, p, &dest);
  119575. testcase( rc!=SQLITE_OK );
  119576. pDelete = p->pPrior;
  119577. p->pPrior = pPrior;
  119578. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  119579. if( pPrior->pLimit
  119580. && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
  119581. && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
  119582. ){
  119583. p->nSelectRow = sqlite3LogEst((u64)nLimit);
  119584. }
  119585. if( addr ){
  119586. sqlite3VdbeJumpHere(v, addr);
  119587. }
  119588. break;
  119589. }
  119590. case TK_EXCEPT:
  119591. case TK_UNION: {
  119592. int unionTab; /* Cursor number of the temp table holding result */
  119593. u8 op = 0; /* One of the SRT_ operations to apply to self */
  119594. int priorOp; /* The SRT_ operation to apply to prior selects */
  119595. Expr *pLimit; /* Saved values of p->nLimit */
  119596. int addr;
  119597. SelectDest uniondest;
  119598. testcase( p->op==TK_EXCEPT );
  119599. testcase( p->op==TK_UNION );
  119600. priorOp = SRT_Union;
  119601. if( dest.eDest==priorOp ){
  119602. /* We can reuse a temporary table generated by a SELECT to our
  119603. ** right.
  119604. */
  119605. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  119606. unionTab = dest.iSDParm;
  119607. }else{
  119608. /* We will need to create our own temporary table to hold the
  119609. ** intermediate results.
  119610. */
  119611. unionTab = pParse->nTab++;
  119612. assert( p->pOrderBy==0 );
  119613. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  119614. assert( p->addrOpenEphm[0] == -1 );
  119615. p->addrOpenEphm[0] = addr;
  119616. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  119617. assert( p->pEList );
  119618. }
  119619. /* Code the SELECT statements to our left
  119620. */
  119621. assert( !pPrior->pOrderBy );
  119622. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  119623. rc = sqlite3Select(pParse, pPrior, &uniondest);
  119624. if( rc ){
  119625. goto multi_select_end;
  119626. }
  119627. /* Code the current SELECT statement
  119628. */
  119629. if( p->op==TK_EXCEPT ){
  119630. op = SRT_Except;
  119631. }else{
  119632. assert( p->op==TK_UNION );
  119633. op = SRT_Union;
  119634. }
  119635. p->pPrior = 0;
  119636. pLimit = p->pLimit;
  119637. p->pLimit = 0;
  119638. uniondest.eDest = op;
  119639. ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
  119640. selectOpName(p->op)));
  119641. rc = sqlite3Select(pParse, p, &uniondest);
  119642. testcase( rc!=SQLITE_OK );
  119643. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  119644. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  119645. sqlite3ExprListDelete(db, p->pOrderBy);
  119646. pDelete = p->pPrior;
  119647. p->pPrior = pPrior;
  119648. p->pOrderBy = 0;
  119649. if( p->op==TK_UNION ){
  119650. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  119651. }
  119652. sqlite3ExprDelete(db, p->pLimit);
  119653. p->pLimit = pLimit;
  119654. p->iLimit = 0;
  119655. p->iOffset = 0;
  119656. /* Convert the data in the temporary table into whatever form
  119657. ** it is that we currently need.
  119658. */
  119659. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  119660. if( dest.eDest!=priorOp ){
  119661. int iCont, iBreak, iStart;
  119662. assert( p->pEList );
  119663. iBreak = sqlite3VdbeMakeLabel(pParse);
  119664. iCont = sqlite3VdbeMakeLabel(pParse);
  119665. computeLimitRegisters(pParse, p, iBreak);
  119666. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  119667. iStart = sqlite3VdbeCurrentAddr(v);
  119668. selectInnerLoop(pParse, p, unionTab,
  119669. 0, 0, &dest, iCont, iBreak);
  119670. sqlite3VdbeResolveLabel(v, iCont);
  119671. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  119672. sqlite3VdbeResolveLabel(v, iBreak);
  119673. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  119674. }
  119675. break;
  119676. }
  119677. default: assert( p->op==TK_INTERSECT ); {
  119678. int tab1, tab2;
  119679. int iCont, iBreak, iStart;
  119680. Expr *pLimit;
  119681. int addr;
  119682. SelectDest intersectdest;
  119683. int r1;
  119684. /* INTERSECT is different from the others since it requires
  119685. ** two temporary tables. Hence it has its own case. Begin
  119686. ** by allocating the tables we will need.
  119687. */
  119688. tab1 = pParse->nTab++;
  119689. tab2 = pParse->nTab++;
  119690. assert( p->pOrderBy==0 );
  119691. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  119692. assert( p->addrOpenEphm[0] == -1 );
  119693. p->addrOpenEphm[0] = addr;
  119694. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  119695. assert( p->pEList );
  119696. /* Code the SELECTs to our left into temporary table "tab1".
  119697. */
  119698. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  119699. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  119700. if( rc ){
  119701. goto multi_select_end;
  119702. }
  119703. /* Code the current SELECT into temporary table "tab2"
  119704. */
  119705. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  119706. assert( p->addrOpenEphm[1] == -1 );
  119707. p->addrOpenEphm[1] = addr;
  119708. p->pPrior = 0;
  119709. pLimit = p->pLimit;
  119710. p->pLimit = 0;
  119711. intersectdest.iSDParm = tab2;
  119712. ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
  119713. selectOpName(p->op)));
  119714. rc = sqlite3Select(pParse, p, &intersectdest);
  119715. testcase( rc!=SQLITE_OK );
  119716. pDelete = p->pPrior;
  119717. p->pPrior = pPrior;
  119718. if( p->nSelectRow>pPrior->nSelectRow ){
  119719. p->nSelectRow = pPrior->nSelectRow;
  119720. }
  119721. sqlite3ExprDelete(db, p->pLimit);
  119722. p->pLimit = pLimit;
  119723. /* Generate code to take the intersection of the two temporary
  119724. ** tables.
  119725. */
  119726. assert( p->pEList );
  119727. iBreak = sqlite3VdbeMakeLabel(pParse);
  119728. iCont = sqlite3VdbeMakeLabel(pParse);
  119729. computeLimitRegisters(pParse, p, iBreak);
  119730. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  119731. r1 = sqlite3GetTempReg(pParse);
  119732. iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
  119733. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  119734. VdbeCoverage(v);
  119735. sqlite3ReleaseTempReg(pParse, r1);
  119736. selectInnerLoop(pParse, p, tab1,
  119737. 0, 0, &dest, iCont, iBreak);
  119738. sqlite3VdbeResolveLabel(v, iCont);
  119739. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  119740. sqlite3VdbeResolveLabel(v, iBreak);
  119741. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  119742. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  119743. break;
  119744. }
  119745. }
  119746. #ifndef SQLITE_OMIT_EXPLAIN
  119747. if( p->pNext==0 ){
  119748. ExplainQueryPlanPop(pParse);
  119749. }
  119750. #endif
  119751. }
  119752. /* Compute collating sequences used by
  119753. ** temporary tables needed to implement the compound select.
  119754. ** Attach the KeyInfo structure to all temporary tables.
  119755. **
  119756. ** This section is run by the right-most SELECT statement only.
  119757. ** SELECT statements to the left always skip this part. The right-most
  119758. ** SELECT might also skip this part if it has no ORDER BY clause and
  119759. ** no temp tables are required.
  119760. */
  119761. if( p->selFlags & SF_UsesEphemeral ){
  119762. int i; /* Loop counter */
  119763. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  119764. Select *pLoop; /* For looping through SELECT statements */
  119765. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  119766. int nCol; /* Number of columns in result set */
  119767. assert( p->pNext==0 );
  119768. nCol = p->pEList->nExpr;
  119769. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  119770. if( !pKeyInfo ){
  119771. rc = SQLITE_NOMEM_BKPT;
  119772. goto multi_select_end;
  119773. }
  119774. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  119775. *apColl = multiSelectCollSeq(pParse, p, i);
  119776. if( 0==*apColl ){
  119777. *apColl = db->pDfltColl;
  119778. }
  119779. }
  119780. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  119781. for(i=0; i<2; i++){
  119782. int addr = pLoop->addrOpenEphm[i];
  119783. if( addr<0 ){
  119784. /* If [0] is unused then [1] is also unused. So we can
  119785. ** always safely abort as soon as the first unused slot is found */
  119786. assert( pLoop->addrOpenEphm[1]<0 );
  119787. break;
  119788. }
  119789. sqlite3VdbeChangeP2(v, addr, nCol);
  119790. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  119791. P4_KEYINFO);
  119792. pLoop->addrOpenEphm[i] = -1;
  119793. }
  119794. }
  119795. sqlite3KeyInfoUnref(pKeyInfo);
  119796. }
  119797. multi_select_end:
  119798. pDest->iSdst = dest.iSdst;
  119799. pDest->nSdst = dest.nSdst;
  119800. sqlite3SelectDelete(db, pDelete);
  119801. return rc;
  119802. }
  119803. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  119804. /*
  119805. ** Error message for when two or more terms of a compound select have different
  119806. ** size result sets.
  119807. */
  119808. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  119809. if( p->selFlags & SF_Values ){
  119810. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  119811. }else{
  119812. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  119813. " do not have the same number of result columns", selectOpName(p->op));
  119814. }
  119815. }
  119816. /*
  119817. ** Code an output subroutine for a coroutine implementation of a
  119818. ** SELECT statment.
  119819. **
  119820. ** The data to be output is contained in pIn->iSdst. There are
  119821. ** pIn->nSdst columns to be output. pDest is where the output should
  119822. ** be sent.
  119823. **
  119824. ** regReturn is the number of the register holding the subroutine
  119825. ** return address.
  119826. **
  119827. ** If regPrev>0 then it is the first register in a vector that
  119828. ** records the previous output. mem[regPrev] is a flag that is false
  119829. ** if there has been no previous output. If regPrev>0 then code is
  119830. ** generated to suppress duplicates. pKeyInfo is used for comparing
  119831. ** keys.
  119832. **
  119833. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  119834. ** iBreak.
  119835. */
  119836. static int generateOutputSubroutine(
  119837. Parse *pParse, /* Parsing context */
  119838. Select *p, /* The SELECT statement */
  119839. SelectDest *pIn, /* Coroutine supplying data */
  119840. SelectDest *pDest, /* Where to send the data */
  119841. int regReturn, /* The return address register */
  119842. int regPrev, /* Previous result register. No uniqueness if 0 */
  119843. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  119844. int iBreak /* Jump here if we hit the LIMIT */
  119845. ){
  119846. Vdbe *v = pParse->pVdbe;
  119847. int iContinue;
  119848. int addr;
  119849. addr = sqlite3VdbeCurrentAddr(v);
  119850. iContinue = sqlite3VdbeMakeLabel(pParse);
  119851. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  119852. */
  119853. if( regPrev ){
  119854. int addr1, addr2;
  119855. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  119856. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  119857. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  119858. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  119859. sqlite3VdbeJumpHere(v, addr1);
  119860. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  119861. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  119862. }
  119863. if( pParse->db->mallocFailed ) return 0;
  119864. /* Suppress the first OFFSET entries if there is an OFFSET clause
  119865. */
  119866. codeOffset(v, p->iOffset, iContinue);
  119867. assert( pDest->eDest!=SRT_Exists );
  119868. assert( pDest->eDest!=SRT_Table );
  119869. switch( pDest->eDest ){
  119870. /* Store the result as data using a unique key.
  119871. */
  119872. case SRT_EphemTab: {
  119873. int r1 = sqlite3GetTempReg(pParse);
  119874. int r2 = sqlite3GetTempReg(pParse);
  119875. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  119876. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  119877. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  119878. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  119879. sqlite3ReleaseTempReg(pParse, r2);
  119880. sqlite3ReleaseTempReg(pParse, r1);
  119881. break;
  119882. }
  119883. #ifndef SQLITE_OMIT_SUBQUERY
  119884. /* If we are creating a set for an "expr IN (SELECT ...)".
  119885. */
  119886. case SRT_Set: {
  119887. int r1;
  119888. testcase( pIn->nSdst>1 );
  119889. r1 = sqlite3GetTempReg(pParse);
  119890. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
  119891. r1, pDest->zAffSdst, pIn->nSdst);
  119892. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
  119893. pIn->iSdst, pIn->nSdst);
  119894. sqlite3ReleaseTempReg(pParse, r1);
  119895. break;
  119896. }
  119897. /* If this is a scalar select that is part of an expression, then
  119898. ** store the results in the appropriate memory cell and break out
  119899. ** of the scan loop.
  119900. */
  119901. case SRT_Mem: {
  119902. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  119903. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  119904. /* The LIMIT clause will jump out of the loop for us */
  119905. break;
  119906. }
  119907. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  119908. /* The results are stored in a sequence of registers
  119909. ** starting at pDest->iSdst. Then the co-routine yields.
  119910. */
  119911. case SRT_Coroutine: {
  119912. if( pDest->iSdst==0 ){
  119913. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  119914. pDest->nSdst = pIn->nSdst;
  119915. }
  119916. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  119917. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  119918. break;
  119919. }
  119920. /* If none of the above, then the result destination must be
  119921. ** SRT_Output. This routine is never called with any other
  119922. ** destination other than the ones handled above or SRT_Output.
  119923. **
  119924. ** For SRT_Output, results are stored in a sequence of registers.
  119925. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  119926. ** return the next row of result.
  119927. */
  119928. default: {
  119929. assert( pDest->eDest==SRT_Output );
  119930. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  119931. break;
  119932. }
  119933. }
  119934. /* Jump to the end of the loop if the LIMIT is reached.
  119935. */
  119936. if( p->iLimit ){
  119937. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  119938. }
  119939. /* Generate the subroutine return
  119940. */
  119941. sqlite3VdbeResolveLabel(v, iContinue);
  119942. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  119943. return addr;
  119944. }
  119945. /*
  119946. ** Alternative compound select code generator for cases when there
  119947. ** is an ORDER BY clause.
  119948. **
  119949. ** We assume a query of the following form:
  119950. **
  119951. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  119952. **
  119953. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  119954. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  119955. ** co-routines. Then run the co-routines in parallel and merge the results
  119956. ** into the output. In addition to the two coroutines (called selectA and
  119957. ** selectB) there are 7 subroutines:
  119958. **
  119959. ** outA: Move the output of the selectA coroutine into the output
  119960. ** of the compound query.
  119961. **
  119962. ** outB: Move the output of the selectB coroutine into the output
  119963. ** of the compound query. (Only generated for UNION and
  119964. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  119965. ** appears only in B.)
  119966. **
  119967. ** AltB: Called when there is data from both coroutines and A<B.
  119968. **
  119969. ** AeqB: Called when there is data from both coroutines and A==B.
  119970. **
  119971. ** AgtB: Called when there is data from both coroutines and A>B.
  119972. **
  119973. ** EofA: Called when data is exhausted from selectA.
  119974. **
  119975. ** EofB: Called when data is exhausted from selectB.
  119976. **
  119977. ** The implementation of the latter five subroutines depend on which
  119978. ** <operator> is used:
  119979. **
  119980. **
  119981. ** UNION ALL UNION EXCEPT INTERSECT
  119982. ** ------------- ----------------- -------------- -----------------
  119983. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  119984. **
  119985. ** AeqB: outA, nextA nextA nextA outA, nextA
  119986. **
  119987. ** AgtB: outB, nextB outB, nextB nextB nextB
  119988. **
  119989. ** EofA: outB, nextB outB, nextB halt halt
  119990. **
  119991. ** EofB: outA, nextA outA, nextA outA, nextA halt
  119992. **
  119993. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  119994. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  119995. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  119996. ** following nextX causes a jump to the end of the select processing.
  119997. **
  119998. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  119999. ** within the output subroutine. The regPrev register set holds the previously
  120000. ** output value. A comparison is made against this value and the output
  120001. ** is skipped if the next results would be the same as the previous.
  120002. **
  120003. ** The implementation plan is to implement the two coroutines and seven
  120004. ** subroutines first, then put the control logic at the bottom. Like this:
  120005. **
  120006. ** goto Init
  120007. ** coA: coroutine for left query (A)
  120008. ** coB: coroutine for right query (B)
  120009. ** outA: output one row of A
  120010. ** outB: output one row of B (UNION and UNION ALL only)
  120011. ** EofA: ...
  120012. ** EofB: ...
  120013. ** AltB: ...
  120014. ** AeqB: ...
  120015. ** AgtB: ...
  120016. ** Init: initialize coroutine registers
  120017. ** yield coA
  120018. ** if eof(A) goto EofA
  120019. ** yield coB
  120020. ** if eof(B) goto EofB
  120021. ** Cmpr: Compare A, B
  120022. ** Jump AltB, AeqB, AgtB
  120023. ** End: ...
  120024. **
  120025. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  120026. ** actually called using Gosub and they do not Return. EofA and EofB loop
  120027. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  120028. ** and AgtB jump to either L2 or to one of EofA or EofB.
  120029. */
  120030. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  120031. static int multiSelectOrderBy(
  120032. Parse *pParse, /* Parsing context */
  120033. Select *p, /* The right-most of SELECTs to be coded */
  120034. SelectDest *pDest /* What to do with query results */
  120035. ){
  120036. int i, j; /* Loop counters */
  120037. Select *pPrior; /* Another SELECT immediately to our left */
  120038. Vdbe *v; /* Generate code to this VDBE */
  120039. SelectDest destA; /* Destination for coroutine A */
  120040. SelectDest destB; /* Destination for coroutine B */
  120041. int regAddrA; /* Address register for select-A coroutine */
  120042. int regAddrB; /* Address register for select-B coroutine */
  120043. int addrSelectA; /* Address of the select-A coroutine */
  120044. int addrSelectB; /* Address of the select-B coroutine */
  120045. int regOutA; /* Address register for the output-A subroutine */
  120046. int regOutB; /* Address register for the output-B subroutine */
  120047. int addrOutA; /* Address of the output-A subroutine */
  120048. int addrOutB = 0; /* Address of the output-B subroutine */
  120049. int addrEofA; /* Address of the select-A-exhausted subroutine */
  120050. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  120051. int addrEofB; /* Address of the select-B-exhausted subroutine */
  120052. int addrAltB; /* Address of the A<B subroutine */
  120053. int addrAeqB; /* Address of the A==B subroutine */
  120054. int addrAgtB; /* Address of the A>B subroutine */
  120055. int regLimitA; /* Limit register for select-A */
  120056. int regLimitB; /* Limit register for select-A */
  120057. int regPrev; /* A range of registers to hold previous output */
  120058. int savedLimit; /* Saved value of p->iLimit */
  120059. int savedOffset; /* Saved value of p->iOffset */
  120060. int labelCmpr; /* Label for the start of the merge algorithm */
  120061. int labelEnd; /* Label for the end of the overall SELECT stmt */
  120062. int addr1; /* Jump instructions that get retargetted */
  120063. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  120064. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  120065. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  120066. sqlite3 *db; /* Database connection */
  120067. ExprList *pOrderBy; /* The ORDER BY clause */
  120068. int nOrderBy; /* Number of terms in the ORDER BY clause */
  120069. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  120070. assert( p->pOrderBy!=0 );
  120071. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  120072. db = pParse->db;
  120073. v = pParse->pVdbe;
  120074. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  120075. labelEnd = sqlite3VdbeMakeLabel(pParse);
  120076. labelCmpr = sqlite3VdbeMakeLabel(pParse);
  120077. /* Patch up the ORDER BY clause
  120078. */
  120079. op = p->op;
  120080. pPrior = p->pPrior;
  120081. assert( pPrior->pOrderBy==0 );
  120082. pOrderBy = p->pOrderBy;
  120083. assert( pOrderBy );
  120084. nOrderBy = pOrderBy->nExpr;
  120085. /* For operators other than UNION ALL we have to make sure that
  120086. ** the ORDER BY clause covers every term of the result set. Add
  120087. ** terms to the ORDER BY clause as necessary.
  120088. */
  120089. if( op!=TK_ALL ){
  120090. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  120091. struct ExprList_item *pItem;
  120092. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  120093. assert( pItem->u.x.iOrderByCol>0 );
  120094. if( pItem->u.x.iOrderByCol==i ) break;
  120095. }
  120096. if( j==nOrderBy ){
  120097. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  120098. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  120099. pNew->flags |= EP_IntValue;
  120100. pNew->u.iValue = i;
  120101. p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  120102. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  120103. }
  120104. }
  120105. }
  120106. /* Compute the comparison permutation and keyinfo that is used with
  120107. ** the permutation used to determine if the next
  120108. ** row of results comes from selectA or selectB. Also add explicit
  120109. ** collations to the ORDER BY clause terms so that when the subqueries
  120110. ** to the right and the left are evaluated, they use the correct
  120111. ** collation.
  120112. */
  120113. aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
  120114. if( aPermute ){
  120115. struct ExprList_item *pItem;
  120116. aPermute[0] = nOrderBy;
  120117. for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
  120118. assert( pItem->u.x.iOrderByCol>0 );
  120119. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  120120. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  120121. }
  120122. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  120123. }else{
  120124. pKeyMerge = 0;
  120125. }
  120126. /* Reattach the ORDER BY clause to the query.
  120127. */
  120128. p->pOrderBy = pOrderBy;
  120129. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  120130. /* Allocate a range of temporary registers and the KeyInfo needed
  120131. ** for the logic that removes duplicate result rows when the
  120132. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  120133. */
  120134. if( op==TK_ALL ){
  120135. regPrev = 0;
  120136. }else{
  120137. int nExpr = p->pEList->nExpr;
  120138. assert( nOrderBy>=nExpr || db->mallocFailed );
  120139. regPrev = pParse->nMem+1;
  120140. pParse->nMem += nExpr+1;
  120141. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  120142. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  120143. if( pKeyDup ){
  120144. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  120145. for(i=0; i<nExpr; i++){
  120146. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  120147. pKeyDup->aSortOrder[i] = 0;
  120148. }
  120149. }
  120150. }
  120151. /* Separate the left and the right query from one another
  120152. */
  120153. p->pPrior = 0;
  120154. pPrior->pNext = 0;
  120155. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  120156. if( pPrior->pPrior==0 ){
  120157. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  120158. }
  120159. /* Compute the limit registers */
  120160. computeLimitRegisters(pParse, p, labelEnd);
  120161. if( p->iLimit && op==TK_ALL ){
  120162. regLimitA = ++pParse->nMem;
  120163. regLimitB = ++pParse->nMem;
  120164. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  120165. regLimitA);
  120166. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  120167. }else{
  120168. regLimitA = regLimitB = 0;
  120169. }
  120170. sqlite3ExprDelete(db, p->pLimit);
  120171. p->pLimit = 0;
  120172. regAddrA = ++pParse->nMem;
  120173. regAddrB = ++pParse->nMem;
  120174. regOutA = ++pParse->nMem;
  120175. regOutB = ++pParse->nMem;
  120176. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  120177. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  120178. ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
  120179. /* Generate a coroutine to evaluate the SELECT statement to the
  120180. ** left of the compound operator - the "A" select.
  120181. */
  120182. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  120183. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  120184. VdbeComment((v, "left SELECT"));
  120185. pPrior->iLimit = regLimitA;
  120186. ExplainQueryPlan((pParse, 1, "LEFT"));
  120187. sqlite3Select(pParse, pPrior, &destA);
  120188. sqlite3VdbeEndCoroutine(v, regAddrA);
  120189. sqlite3VdbeJumpHere(v, addr1);
  120190. /* Generate a coroutine to evaluate the SELECT statement on
  120191. ** the right - the "B" select
  120192. */
  120193. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  120194. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  120195. VdbeComment((v, "right SELECT"));
  120196. savedLimit = p->iLimit;
  120197. savedOffset = p->iOffset;
  120198. p->iLimit = regLimitB;
  120199. p->iOffset = 0;
  120200. ExplainQueryPlan((pParse, 1, "RIGHT"));
  120201. sqlite3Select(pParse, p, &destB);
  120202. p->iLimit = savedLimit;
  120203. p->iOffset = savedOffset;
  120204. sqlite3VdbeEndCoroutine(v, regAddrB);
  120205. /* Generate a subroutine that outputs the current row of the A
  120206. ** select as the next output row of the compound select.
  120207. */
  120208. VdbeNoopComment((v, "Output routine for A"));
  120209. addrOutA = generateOutputSubroutine(pParse,
  120210. p, &destA, pDest, regOutA,
  120211. regPrev, pKeyDup, labelEnd);
  120212. /* Generate a subroutine that outputs the current row of the B
  120213. ** select as the next output row of the compound select.
  120214. */
  120215. if( op==TK_ALL || op==TK_UNION ){
  120216. VdbeNoopComment((v, "Output routine for B"));
  120217. addrOutB = generateOutputSubroutine(pParse,
  120218. p, &destB, pDest, regOutB,
  120219. regPrev, pKeyDup, labelEnd);
  120220. }
  120221. sqlite3KeyInfoUnref(pKeyDup);
  120222. /* Generate a subroutine to run when the results from select A
  120223. ** are exhausted and only data in select B remains.
  120224. */
  120225. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  120226. addrEofA_noB = addrEofA = labelEnd;
  120227. }else{
  120228. VdbeNoopComment((v, "eof-A subroutine"));
  120229. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  120230. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  120231. VdbeCoverage(v);
  120232. sqlite3VdbeGoto(v, addrEofA);
  120233. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  120234. }
  120235. /* Generate a subroutine to run when the results from select B
  120236. ** are exhausted and only data in select A remains.
  120237. */
  120238. if( op==TK_INTERSECT ){
  120239. addrEofB = addrEofA;
  120240. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  120241. }else{
  120242. VdbeNoopComment((v, "eof-B subroutine"));
  120243. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  120244. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  120245. sqlite3VdbeGoto(v, addrEofB);
  120246. }
  120247. /* Generate code to handle the case of A<B
  120248. */
  120249. VdbeNoopComment((v, "A-lt-B subroutine"));
  120250. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  120251. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  120252. sqlite3VdbeGoto(v, labelCmpr);
  120253. /* Generate code to handle the case of A==B
  120254. */
  120255. if( op==TK_ALL ){
  120256. addrAeqB = addrAltB;
  120257. }else if( op==TK_INTERSECT ){
  120258. addrAeqB = addrAltB;
  120259. addrAltB++;
  120260. }else{
  120261. VdbeNoopComment((v, "A-eq-B subroutine"));
  120262. addrAeqB =
  120263. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  120264. sqlite3VdbeGoto(v, labelCmpr);
  120265. }
  120266. /* Generate code to handle the case of A>B
  120267. */
  120268. VdbeNoopComment((v, "A-gt-B subroutine"));
  120269. addrAgtB = sqlite3VdbeCurrentAddr(v);
  120270. if( op==TK_ALL || op==TK_UNION ){
  120271. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  120272. }
  120273. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  120274. sqlite3VdbeGoto(v, labelCmpr);
  120275. /* This code runs once to initialize everything.
  120276. */
  120277. sqlite3VdbeJumpHere(v, addr1);
  120278. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  120279. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  120280. /* Implement the main merge loop
  120281. */
  120282. sqlite3VdbeResolveLabel(v, labelCmpr);
  120283. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  120284. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  120285. (char*)pKeyMerge, P4_KEYINFO);
  120286. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  120287. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  120288. /* Jump to the this point in order to terminate the query.
  120289. */
  120290. sqlite3VdbeResolveLabel(v, labelEnd);
  120291. /* Reassembly the compound query so that it will be freed correctly
  120292. ** by the calling function */
  120293. if( p->pPrior ){
  120294. sqlite3SelectDelete(db, p->pPrior);
  120295. }
  120296. p->pPrior = pPrior;
  120297. pPrior->pNext = p;
  120298. /*** TBD: Insert subroutine calls to close cursors on incomplete
  120299. **** subqueries ****/
  120300. ExplainQueryPlanPop(pParse);
  120301. return pParse->nErr!=0;
  120302. }
  120303. #endif
  120304. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  120305. /* An instance of the SubstContext object describes an substitution edit
  120306. ** to be performed on a parse tree.
  120307. **
  120308. ** All references to columns in table iTable are to be replaced by corresponding
  120309. ** expressions in pEList.
  120310. */
  120311. typedef struct SubstContext {
  120312. Parse *pParse; /* The parsing context */
  120313. int iTable; /* Replace references to this table */
  120314. int iNewTable; /* New table number */
  120315. int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
  120316. ExprList *pEList; /* Replacement expressions */
  120317. } SubstContext;
  120318. /* Forward Declarations */
  120319. static void substExprList(SubstContext*, ExprList*);
  120320. static void substSelect(SubstContext*, Select*, int);
  120321. /*
  120322. ** Scan through the expression pExpr. Replace every reference to
  120323. ** a column in table number iTable with a copy of the iColumn-th
  120324. ** entry in pEList. (But leave references to the ROWID column
  120325. ** unchanged.)
  120326. **
  120327. ** This routine is part of the flattening procedure. A subquery
  120328. ** whose result set is defined by pEList appears as entry in the
  120329. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  120330. ** FORM clause entry is iTable. This routine makes the necessary
  120331. ** changes to pExpr so that it refers directly to the source table
  120332. ** of the subquery rather the result set of the subquery.
  120333. */
  120334. static Expr *substExpr(
  120335. SubstContext *pSubst, /* Description of the substitution */
  120336. Expr *pExpr /* Expr in which substitution occurs */
  120337. ){
  120338. if( pExpr==0 ) return 0;
  120339. if( ExprHasProperty(pExpr, EP_FromJoin)
  120340. && pExpr->iRightJoinTable==pSubst->iTable
  120341. ){
  120342. pExpr->iRightJoinTable = pSubst->iNewTable;
  120343. }
  120344. if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
  120345. if( pExpr->iColumn<0 ){
  120346. pExpr->op = TK_NULL;
  120347. }else{
  120348. Expr *pNew;
  120349. Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
  120350. Expr ifNullRow;
  120351. assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
  120352. assert( pExpr->pRight==0 );
  120353. if( sqlite3ExprIsVector(pCopy) ){
  120354. sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
  120355. }else{
  120356. sqlite3 *db = pSubst->pParse->db;
  120357. if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
  120358. memset(&ifNullRow, 0, sizeof(ifNullRow));
  120359. ifNullRow.op = TK_IF_NULL_ROW;
  120360. ifNullRow.pLeft = pCopy;
  120361. ifNullRow.iTable = pSubst->iNewTable;
  120362. pCopy = &ifNullRow;
  120363. }
  120364. testcase( ExprHasProperty(pCopy, EP_Subquery) );
  120365. pNew = sqlite3ExprDup(db, pCopy, 0);
  120366. if( pNew && pSubst->isLeftJoin ){
  120367. ExprSetProperty(pNew, EP_CanBeNull);
  120368. }
  120369. if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
  120370. pNew->iRightJoinTable = pExpr->iRightJoinTable;
  120371. ExprSetProperty(pNew, EP_FromJoin);
  120372. }
  120373. sqlite3ExprDelete(db, pExpr);
  120374. pExpr = pNew;
  120375. }
  120376. }
  120377. }else{
  120378. if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
  120379. pExpr->iTable = pSubst->iNewTable;
  120380. }
  120381. pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
  120382. pExpr->pRight = substExpr(pSubst, pExpr->pRight);
  120383. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  120384. substSelect(pSubst, pExpr->x.pSelect, 1);
  120385. }else{
  120386. substExprList(pSubst, pExpr->x.pList);
  120387. }
  120388. }
  120389. return pExpr;
  120390. }
  120391. static void substExprList(
  120392. SubstContext *pSubst, /* Description of the substitution */
  120393. ExprList *pList /* List to scan and in which to make substitutes */
  120394. ){
  120395. int i;
  120396. if( pList==0 ) return;
  120397. for(i=0; i<pList->nExpr; i++){
  120398. pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
  120399. }
  120400. }
  120401. static void substSelect(
  120402. SubstContext *pSubst, /* Description of the substitution */
  120403. Select *p, /* SELECT statement in which to make substitutions */
  120404. int doPrior /* Do substitutes on p->pPrior too */
  120405. ){
  120406. SrcList *pSrc;
  120407. struct SrcList_item *pItem;
  120408. int i;
  120409. if( !p ) return;
  120410. do{
  120411. substExprList(pSubst, p->pEList);
  120412. substExprList(pSubst, p->pGroupBy);
  120413. substExprList(pSubst, p->pOrderBy);
  120414. p->pHaving = substExpr(pSubst, p->pHaving);
  120415. p->pWhere = substExpr(pSubst, p->pWhere);
  120416. pSrc = p->pSrc;
  120417. assert( pSrc!=0 );
  120418. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  120419. substSelect(pSubst, pItem->pSelect, 1);
  120420. if( pItem->fg.isTabFunc ){
  120421. substExprList(pSubst, pItem->u1.pFuncArg);
  120422. }
  120423. }
  120424. }while( doPrior && (p = p->pPrior)!=0 );
  120425. }
  120426. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  120427. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  120428. /*
  120429. ** This routine attempts to flatten subqueries as a performance optimization.
  120430. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  120431. **
  120432. ** To understand the concept of flattening, consider the following
  120433. ** query:
  120434. **
  120435. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  120436. **
  120437. ** The default way of implementing this query is to execute the
  120438. ** subquery first and store the results in a temporary table, then
  120439. ** run the outer query on that temporary table. This requires two
  120440. ** passes over the data. Furthermore, because the temporary table
  120441. ** has no indices, the WHERE clause on the outer query cannot be
  120442. ** optimized.
  120443. **
  120444. ** This routine attempts to rewrite queries such as the above into
  120445. ** a single flat select, like this:
  120446. **
  120447. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  120448. **
  120449. ** The code generated for this simplification gives the same result
  120450. ** but only has to scan the data once. And because indices might
  120451. ** exist on the table t1, a complete scan of the data might be
  120452. ** avoided.
  120453. **
  120454. ** Flattening is subject to the following constraints:
  120455. **
  120456. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  120457. ** The subquery and the outer query cannot both be aggregates.
  120458. **
  120459. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  120460. ** (2) If the subquery is an aggregate then
  120461. ** (2a) the outer query must not be a join and
  120462. ** (2b) the outer query must not use subqueries
  120463. ** other than the one FROM-clause subquery that is a candidate
  120464. ** for flattening. (This is due to ticket [2f7170d73bf9abf80]
  120465. ** from 2015-02-09.)
  120466. **
  120467. ** (3) If the subquery is the right operand of a LEFT JOIN then
  120468. ** (3a) the subquery may not be a join and
  120469. ** (3b) the FROM clause of the subquery may not contain a virtual
  120470. ** table and
  120471. ** (3c) the outer query may not be an aggregate.
  120472. **
  120473. ** (4) The subquery can not be DISTINCT.
  120474. **
  120475. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  120476. ** sub-queries that were excluded from this optimization. Restriction
  120477. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  120478. **
  120479. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  120480. ** If the subquery is aggregate, the outer query may not be DISTINCT.
  120481. **
  120482. ** (7) The subquery must have a FROM clause. TODO: For subqueries without
  120483. ** A FROM clause, consider adding a FROM clause with the special
  120484. ** table sqlite_once that consists of a single row containing a
  120485. ** single NULL.
  120486. **
  120487. ** (8) If the subquery uses LIMIT then the outer query may not be a join.
  120488. **
  120489. ** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
  120490. **
  120491. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  120492. ** accidently carried the comment forward until 2014-09-15. Original
  120493. ** constraint: "If the subquery is aggregate then the outer query
  120494. ** may not use LIMIT."
  120495. **
  120496. ** (11) The subquery and the outer query may not both have ORDER BY clauses.
  120497. **
  120498. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  120499. ** a separate restriction deriving from ticket #350.
  120500. **
  120501. ** (13) The subquery and outer query may not both use LIMIT.
  120502. **
  120503. ** (14) The subquery may not use OFFSET.
  120504. **
  120505. ** (15) If the outer query is part of a compound select, then the
  120506. ** subquery may not use LIMIT.
  120507. ** (See ticket #2339 and ticket [02a8e81d44]).
  120508. **
  120509. ** (16) If the outer query is aggregate, then the subquery may not
  120510. ** use ORDER BY. (Ticket #2942) This used to not matter
  120511. ** until we introduced the group_concat() function.
  120512. **
  120513. ** (17) If the subquery is a compound select, then
  120514. ** (17a) all compound operators must be a UNION ALL, and
  120515. ** (17b) no terms within the subquery compound may be aggregate
  120516. ** or DISTINCT, and
  120517. ** (17c) every term within the subquery compound must have a FROM clause
  120518. ** (17d) the outer query may not be
  120519. ** (17d1) aggregate, or
  120520. ** (17d2) DISTINCT, or
  120521. ** (17d3) a join.
  120522. **
  120523. ** The parent and sub-query may contain WHERE clauses. Subject to
  120524. ** rules (11), (13) and (14), they may also contain ORDER BY,
  120525. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  120526. ** operator other than UNION ALL because all the other compound
  120527. ** operators have an implied DISTINCT which is disallowed by
  120528. ** restriction (4).
  120529. **
  120530. ** Also, each component of the sub-query must return the same number
  120531. ** of result columns. This is actually a requirement for any compound
  120532. ** SELECT statement, but all the code here does is make sure that no
  120533. ** such (illegal) sub-query is flattened. The caller will detect the
  120534. ** syntax error and return a detailed message.
  120535. **
  120536. ** (18) If the sub-query is a compound select, then all terms of the
  120537. ** ORDER BY clause of the parent must be simple references to
  120538. ** columns of the sub-query.
  120539. **
  120540. ** (19) If the subquery uses LIMIT then the outer query may not
  120541. ** have a WHERE clause.
  120542. **
  120543. ** (20) If the sub-query is a compound select, then it must not use
  120544. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  120545. ** somewhat by saying that the terms of the ORDER BY clause must
  120546. ** appear as unmodified result columns in the outer query. But we
  120547. ** have other optimizations in mind to deal with that case.
  120548. **
  120549. ** (21) If the subquery uses LIMIT then the outer query may not be
  120550. ** DISTINCT. (See ticket [752e1646fc]).
  120551. **
  120552. ** (22) The subquery may not be a recursive CTE.
  120553. **
  120554. ** (**) Subsumed into restriction (17d3). Was: If the outer query is
  120555. ** a recursive CTE, then the sub-query may not be a compound query.
  120556. ** This restriction is because transforming the
  120557. ** parent to a compound query confuses the code that handles
  120558. ** recursive queries in multiSelect().
  120559. **
  120560. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  120561. ** The subquery may not be an aggregate that uses the built-in min() or
  120562. ** or max() functions. (Without this restriction, a query like:
  120563. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  120564. ** return the value X for which Y was maximal.)
  120565. **
  120566. ** (25) If either the subquery or the parent query contains a window
  120567. ** function in the select list or ORDER BY clause, flattening
  120568. ** is not attempted.
  120569. **
  120570. **
  120571. ** In this routine, the "p" parameter is a pointer to the outer query.
  120572. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  120573. ** uses aggregates.
  120574. **
  120575. ** If flattening is not attempted, this routine is a no-op and returns 0.
  120576. ** If flattening is attempted this routine returns 1.
  120577. **
  120578. ** All of the expression analysis must occur on both the outer query and
  120579. ** the subquery before this routine runs.
  120580. */
  120581. static int flattenSubquery(
  120582. Parse *pParse, /* Parsing context */
  120583. Select *p, /* The parent or outer SELECT statement */
  120584. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  120585. int isAgg /* True if outer SELECT uses aggregate functions */
  120586. ){
  120587. const char *zSavedAuthContext = pParse->zAuthContext;
  120588. Select *pParent; /* Current UNION ALL term of the other query */
  120589. Select *pSub; /* The inner query or "subquery" */
  120590. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  120591. SrcList *pSrc; /* The FROM clause of the outer query */
  120592. SrcList *pSubSrc; /* The FROM clause of the subquery */
  120593. int iParent; /* VDBE cursor number of the pSub result set temp table */
  120594. int iNewParent = -1;/* Replacement table for iParent */
  120595. int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
  120596. int i; /* Loop counter */
  120597. Expr *pWhere; /* The WHERE clause */
  120598. struct SrcList_item *pSubitem; /* The subquery */
  120599. sqlite3 *db = pParse->db;
  120600. /* Check to see if flattening is permitted. Return 0 if not.
  120601. */
  120602. assert( p!=0 );
  120603. assert( p->pPrior==0 );
  120604. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  120605. pSrc = p->pSrc;
  120606. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  120607. pSubitem = &pSrc->a[iFrom];
  120608. iParent = pSubitem->iCursor;
  120609. pSub = pSubitem->pSelect;
  120610. assert( pSub!=0 );
  120611. #ifndef SQLITE_OMIT_WINDOWFUNC
  120612. if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
  120613. #endif
  120614. pSubSrc = pSub->pSrc;
  120615. assert( pSubSrc );
  120616. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  120617. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  120618. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  120619. ** became arbitrary expressions, we were forced to add restrictions (13)
  120620. ** and (14). */
  120621. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  120622. if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
  120623. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  120624. return 0; /* Restriction (15) */
  120625. }
  120626. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  120627. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
  120628. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  120629. return 0; /* Restrictions (8)(9) */
  120630. }
  120631. if( p->pOrderBy && pSub->pOrderBy ){
  120632. return 0; /* Restriction (11) */
  120633. }
  120634. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  120635. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  120636. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  120637. return 0; /* Restriction (21) */
  120638. }
  120639. if( pSub->selFlags & (SF_Recursive) ){
  120640. return 0; /* Restrictions (22) */
  120641. }
  120642. /*
  120643. ** If the subquery is the right operand of a LEFT JOIN, then the
  120644. ** subquery may not be a join itself (3a). Example of why this is not
  120645. ** allowed:
  120646. **
  120647. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  120648. **
  120649. ** If we flatten the above, we would get
  120650. **
  120651. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  120652. **
  120653. ** which is not at all the same thing.
  120654. **
  120655. ** If the subquery is the right operand of a LEFT JOIN, then the outer
  120656. ** query cannot be an aggregate. (3c) This is an artifact of the way
  120657. ** aggregates are processed - there is no mechanism to determine if
  120658. ** the LEFT JOIN table should be all-NULL.
  120659. **
  120660. ** See also tickets #306, #350, and #3300.
  120661. */
  120662. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  120663. isLeftJoin = 1;
  120664. if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
  120665. /* (3a) (3c) (3b) */
  120666. return 0;
  120667. }
  120668. }
  120669. #ifdef SQLITE_EXTRA_IFNULLROW
  120670. else if( iFrom>0 && !isAgg ){
  120671. /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
  120672. ** every reference to any result column from subquery in a join, even
  120673. ** though they are not necessary. This will stress-test the OP_IfNullRow
  120674. ** opcode. */
  120675. isLeftJoin = -1;
  120676. }
  120677. #endif
  120678. /* Restriction (17): If the sub-query is a compound SELECT, then it must
  120679. ** use only the UNION ALL operator. And none of the simple select queries
  120680. ** that make up the compound SELECT are allowed to be aggregate or distinct
  120681. ** queries.
  120682. */
  120683. if( pSub->pPrior ){
  120684. if( pSub->pOrderBy ){
  120685. return 0; /* Restriction (20) */
  120686. }
  120687. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  120688. return 0; /* (17d1), (17d2), or (17d3) */
  120689. }
  120690. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  120691. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  120692. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  120693. assert( pSub->pSrc!=0 );
  120694. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  120695. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
  120696. || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
  120697. || pSub1->pSrc->nSrc<1 /* (17c) */
  120698. ){
  120699. return 0;
  120700. }
  120701. testcase( pSub1->pSrc->nSrc>1 );
  120702. }
  120703. /* Restriction (18). */
  120704. if( p->pOrderBy ){
  120705. int ii;
  120706. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  120707. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  120708. }
  120709. }
  120710. }
  120711. /* Ex-restriction (23):
  120712. ** The only way that the recursive part of a CTE can contain a compound
  120713. ** subquery is for the subquery to be one term of a join. But if the
  120714. ** subquery is a join, then the flattening has already been stopped by
  120715. ** restriction (17d3)
  120716. */
  120717. assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
  120718. /***** If we reach this point, flattening is permitted. *****/
  120719. SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
  120720. pSub->selId, pSub, iFrom));
  120721. /* Authorize the subquery */
  120722. pParse->zAuthContext = pSubitem->zName;
  120723. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  120724. testcase( i==SQLITE_DENY );
  120725. pParse->zAuthContext = zSavedAuthContext;
  120726. /* If the sub-query is a compound SELECT statement, then (by restrictions
  120727. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  120728. ** be of the form:
  120729. **
  120730. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  120731. **
  120732. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  120733. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  120734. ** OFFSET clauses and joins them to the left-hand-side of the original
  120735. ** using UNION ALL operators. In this case N is the number of simple
  120736. ** select statements in the compound sub-query.
  120737. **
  120738. ** Example:
  120739. **
  120740. ** SELECT a+1 FROM (
  120741. ** SELECT x FROM tab
  120742. ** UNION ALL
  120743. ** SELECT y FROM tab
  120744. ** UNION ALL
  120745. ** SELECT abs(z*2) FROM tab2
  120746. ** ) WHERE a!=5 ORDER BY 1
  120747. **
  120748. ** Transformed into:
  120749. **
  120750. ** SELECT x+1 FROM tab WHERE x+1!=5
  120751. ** UNION ALL
  120752. ** SELECT y+1 FROM tab WHERE y+1!=5
  120753. ** UNION ALL
  120754. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  120755. ** ORDER BY 1
  120756. **
  120757. ** We call this the "compound-subquery flattening".
  120758. */
  120759. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  120760. Select *pNew;
  120761. ExprList *pOrderBy = p->pOrderBy;
  120762. Expr *pLimit = p->pLimit;
  120763. Select *pPrior = p->pPrior;
  120764. p->pOrderBy = 0;
  120765. p->pSrc = 0;
  120766. p->pPrior = 0;
  120767. p->pLimit = 0;
  120768. pNew = sqlite3SelectDup(db, p, 0);
  120769. p->pLimit = pLimit;
  120770. p->pOrderBy = pOrderBy;
  120771. p->pSrc = pSrc;
  120772. p->op = TK_ALL;
  120773. if( pNew==0 ){
  120774. p->pPrior = pPrior;
  120775. }else{
  120776. pNew->pPrior = pPrior;
  120777. if( pPrior ) pPrior->pNext = pNew;
  120778. pNew->pNext = p;
  120779. p->pPrior = pNew;
  120780. SELECTTRACE(2,pParse,p,("compound-subquery flattener"
  120781. " creates %u as peer\n",pNew->selId));
  120782. }
  120783. if( db->mallocFailed ) return 1;
  120784. }
  120785. /* Begin flattening the iFrom-th entry of the FROM clause
  120786. ** in the outer query.
  120787. */
  120788. pSub = pSub1 = pSubitem->pSelect;
  120789. /* Delete the transient table structure associated with the
  120790. ** subquery
  120791. */
  120792. sqlite3DbFree(db, pSubitem->zDatabase);
  120793. sqlite3DbFree(db, pSubitem->zName);
  120794. sqlite3DbFree(db, pSubitem->zAlias);
  120795. pSubitem->zDatabase = 0;
  120796. pSubitem->zName = 0;
  120797. pSubitem->zAlias = 0;
  120798. pSubitem->pSelect = 0;
  120799. /* Defer deleting the Table object associated with the
  120800. ** subquery until code generation is
  120801. ** complete, since there may still exist Expr.pTab entries that
  120802. ** refer to the subquery even after flattening. Ticket #3346.
  120803. **
  120804. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  120805. */
  120806. if( ALWAYS(pSubitem->pTab!=0) ){
  120807. Table *pTabToDel = pSubitem->pTab;
  120808. if( pTabToDel->nTabRef==1 ){
  120809. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  120810. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  120811. pToplevel->pZombieTab = pTabToDel;
  120812. }else{
  120813. pTabToDel->nTabRef--;
  120814. }
  120815. pSubitem->pTab = 0;
  120816. }
  120817. /* The following loop runs once for each term in a compound-subquery
  120818. ** flattening (as described above). If we are doing a different kind
  120819. ** of flattening - a flattening other than a compound-subquery flattening -
  120820. ** then this loop only runs once.
  120821. **
  120822. ** This loop moves all of the FROM elements of the subquery into the
  120823. ** the FROM clause of the outer query. Before doing this, remember
  120824. ** the cursor number for the original outer query FROM element in
  120825. ** iParent. The iParent cursor will never be used. Subsequent code
  120826. ** will scan expressions looking for iParent references and replace
  120827. ** those references with expressions that resolve to the subquery FROM
  120828. ** elements we are now copying in.
  120829. */
  120830. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  120831. int nSubSrc;
  120832. u8 jointype = 0;
  120833. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  120834. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  120835. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  120836. if( pSrc ){
  120837. assert( pParent==p ); /* First time through the loop */
  120838. jointype = pSubitem->fg.jointype;
  120839. }else{
  120840. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  120841. pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  120842. if( pSrc==0 ) break;
  120843. pParent->pSrc = pSrc;
  120844. }
  120845. /* The subquery uses a single slot of the FROM clause of the outer
  120846. ** query. If the subquery has more than one element in its FROM clause,
  120847. ** then expand the outer query to make space for it to hold all elements
  120848. ** of the subquery.
  120849. **
  120850. ** Example:
  120851. **
  120852. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  120853. **
  120854. ** The outer query has 3 slots in its FROM clause. One slot of the
  120855. ** outer query (the middle slot) is used by the subquery. The next
  120856. ** block of code will expand the outer query FROM clause to 4 slots.
  120857. ** The middle slot is expanded to two slots in order to make space
  120858. ** for the two elements in the FROM clause of the subquery.
  120859. */
  120860. if( nSubSrc>1 ){
  120861. pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
  120862. if( pSrc==0 ) break;
  120863. pParent->pSrc = pSrc;
  120864. }
  120865. /* Transfer the FROM clause terms from the subquery into the
  120866. ** outer query.
  120867. */
  120868. for(i=0; i<nSubSrc; i++){
  120869. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  120870. assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
  120871. pSrc->a[i+iFrom] = pSubSrc->a[i];
  120872. iNewParent = pSubSrc->a[i].iCursor;
  120873. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  120874. }
  120875. pSrc->a[iFrom].fg.jointype = jointype;
  120876. /* Now begin substituting subquery result set expressions for
  120877. ** references to the iParent in the outer query.
  120878. **
  120879. ** Example:
  120880. **
  120881. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  120882. ** \ \_____________ subquery __________/ /
  120883. ** \_____________________ outer query ______________________________/
  120884. **
  120885. ** We look at every expression in the outer query and every place we see
  120886. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  120887. */
  120888. if( pSub->pOrderBy ){
  120889. /* At this point, any non-zero iOrderByCol values indicate that the
  120890. ** ORDER BY column expression is identical to the iOrderByCol'th
  120891. ** expression returned by SELECT statement pSub. Since these values
  120892. ** do not necessarily correspond to columns in SELECT statement pParent,
  120893. ** zero them before transfering the ORDER BY clause.
  120894. **
  120895. ** Not doing this may cause an error if a subsequent call to this
  120896. ** function attempts to flatten a compound sub-query into pParent
  120897. ** (the only way this can happen is if the compound sub-query is
  120898. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  120899. ExprList *pOrderBy = pSub->pOrderBy;
  120900. for(i=0; i<pOrderBy->nExpr; i++){
  120901. pOrderBy->a[i].u.x.iOrderByCol = 0;
  120902. }
  120903. assert( pParent->pOrderBy==0 );
  120904. pParent->pOrderBy = pOrderBy;
  120905. pSub->pOrderBy = 0;
  120906. }
  120907. pWhere = pSub->pWhere;
  120908. pSub->pWhere = 0;
  120909. if( isLeftJoin>0 ){
  120910. setJoinExpr(pWhere, iNewParent);
  120911. }
  120912. pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
  120913. if( db->mallocFailed==0 ){
  120914. SubstContext x;
  120915. x.pParse = pParse;
  120916. x.iTable = iParent;
  120917. x.iNewTable = iNewParent;
  120918. x.isLeftJoin = isLeftJoin;
  120919. x.pEList = pSub->pEList;
  120920. substSelect(&x, pParent, 0);
  120921. }
  120922. /* The flattened query is distinct if either the inner or the
  120923. ** outer query is distinct.
  120924. */
  120925. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  120926. /*
  120927. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  120928. **
  120929. ** One is tempted to try to add a and b to combine the limits. But this
  120930. ** does not work if either limit is negative.
  120931. */
  120932. if( pSub->pLimit ){
  120933. pParent->pLimit = pSub->pLimit;
  120934. pSub->pLimit = 0;
  120935. }
  120936. }
  120937. /* Finially, delete what is left of the subquery and return
  120938. ** success.
  120939. */
  120940. sqlite3SelectDelete(db, pSub1);
  120941. #if SELECTTRACE_ENABLED
  120942. if( sqlite3SelectTrace & 0x100 ){
  120943. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  120944. sqlite3TreeViewSelect(0, p, 0);
  120945. }
  120946. #endif
  120947. return 1;
  120948. }
  120949. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  120950. /*
  120951. ** A structure to keep track of all of the column values that are fixed to
  120952. ** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
  120953. */
  120954. typedef struct WhereConst WhereConst;
  120955. struct WhereConst {
  120956. Parse *pParse; /* Parsing context */
  120957. int nConst; /* Number for COLUMN=CONSTANT terms */
  120958. int nChng; /* Number of times a constant is propagated */
  120959. Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
  120960. };
  120961. /*
  120962. ** Add a new entry to the pConst object. Except, do not add duplicate
  120963. ** pColumn entires.
  120964. */
  120965. static void constInsert(
  120966. WhereConst *pConst, /* The WhereConst into which we are inserting */
  120967. Expr *pColumn, /* The COLUMN part of the constraint */
  120968. Expr *pValue /* The VALUE part of the constraint */
  120969. ){
  120970. int i;
  120971. assert( pColumn->op==TK_COLUMN );
  120972. /* 2018-10-25 ticket [cf5ed20f]
  120973. ** Make sure the same pColumn is not inserted more than once */
  120974. for(i=0; i<pConst->nConst; i++){
  120975. const Expr *pExpr = pConst->apExpr[i*2];
  120976. assert( pExpr->op==TK_COLUMN );
  120977. if( pExpr->iTable==pColumn->iTable
  120978. && pExpr->iColumn==pColumn->iColumn
  120979. ){
  120980. return; /* Already present. Return without doing anything. */
  120981. }
  120982. }
  120983. pConst->nConst++;
  120984. pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
  120985. pConst->nConst*2*sizeof(Expr*));
  120986. if( pConst->apExpr==0 ){
  120987. pConst->nConst = 0;
  120988. }else{
  120989. if( ExprHasProperty(pValue, EP_FixedCol) ) pValue = pValue->pLeft;
  120990. pConst->apExpr[pConst->nConst*2-2] = pColumn;
  120991. pConst->apExpr[pConst->nConst*2-1] = pValue;
  120992. }
  120993. }
  120994. /*
  120995. ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
  120996. ** is a constant expression and where the term must be true because it
  120997. ** is part of the AND-connected terms of the expression. For each term
  120998. ** found, add it to the pConst structure.
  120999. */
  121000. static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
  121001. Expr *pRight, *pLeft;
  121002. if( pExpr==0 ) return;
  121003. if( ExprHasProperty(pExpr, EP_FromJoin) ) return;
  121004. if( pExpr->op==TK_AND ){
  121005. findConstInWhere(pConst, pExpr->pRight);
  121006. findConstInWhere(pConst, pExpr->pLeft);
  121007. return;
  121008. }
  121009. if( pExpr->op!=TK_EQ ) return;
  121010. pRight = pExpr->pRight;
  121011. pLeft = pExpr->pLeft;
  121012. assert( pRight!=0 );
  121013. assert( pLeft!=0 );
  121014. if( pRight->op==TK_COLUMN
  121015. && !ExprHasProperty(pRight, EP_FixedCol)
  121016. && sqlite3ExprIsConstant(pLeft)
  121017. && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight))
  121018. ){
  121019. constInsert(pConst, pRight, pLeft);
  121020. }else
  121021. if( pLeft->op==TK_COLUMN
  121022. && !ExprHasProperty(pLeft, EP_FixedCol)
  121023. && sqlite3ExprIsConstant(pRight)
  121024. && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight))
  121025. ){
  121026. constInsert(pConst, pLeft, pRight);
  121027. }
  121028. }
  121029. /*
  121030. ** This is a Walker expression callback. pExpr is a candidate expression
  121031. ** to be replaced by a value. If pExpr is equivalent to one of the
  121032. ** columns named in pWalker->u.pConst, then overwrite it with its
  121033. ** corresponding value.
  121034. */
  121035. static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
  121036. int i;
  121037. WhereConst *pConst;
  121038. if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
  121039. if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue;
  121040. pConst = pWalker->u.pConst;
  121041. for(i=0; i<pConst->nConst; i++){
  121042. Expr *pColumn = pConst->apExpr[i*2];
  121043. if( pColumn==pExpr ) continue;
  121044. if( pColumn->iTable!=pExpr->iTable ) continue;
  121045. if( pColumn->iColumn!=pExpr->iColumn ) continue;
  121046. /* A match is found. Add the EP_FixedCol property */
  121047. pConst->nChng++;
  121048. ExprClearProperty(pExpr, EP_Leaf);
  121049. ExprSetProperty(pExpr, EP_FixedCol);
  121050. assert( pExpr->pLeft==0 );
  121051. pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
  121052. break;
  121053. }
  121054. return WRC_Prune;
  121055. }
  121056. /*
  121057. ** The WHERE-clause constant propagation optimization.
  121058. **
  121059. ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
  121060. ** CONSTANT=COLUMN that must be tree (in other words, if the terms top-level
  121061. ** AND-connected terms that are not part of a ON clause from a LEFT JOIN)
  121062. ** then throughout the query replace all other occurrences of COLUMN
  121063. ** with CONSTANT within the WHERE clause.
  121064. **
  121065. ** For example, the query:
  121066. **
  121067. ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
  121068. **
  121069. ** Is transformed into
  121070. **
  121071. ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
  121072. **
  121073. ** Return true if any transformations where made and false if not.
  121074. **
  121075. ** Implementation note: Constant propagation is tricky due to affinity
  121076. ** and collating sequence interactions. Consider this example:
  121077. **
  121078. ** CREATE TABLE t1(a INT,b TEXT);
  121079. ** INSERT INTO t1 VALUES(123,'0123');
  121080. ** SELECT * FROM t1 WHERE a=123 AND b=a;
  121081. ** SELECT * FROM t1 WHERE a=123 AND b=123;
  121082. **
  121083. ** The two SELECT statements above should return different answers. b=a
  121084. ** is alway true because the comparison uses numeric affinity, but b=123
  121085. ** is false because it uses text affinity and '0123' is not the same as '123'.
  121086. ** To work around this, the expression tree is not actually changed from
  121087. ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
  121088. ** and the "123" value is hung off of the pLeft pointer. Code generator
  121089. ** routines know to generate the constant "123" instead of looking up the
  121090. ** column value. Also, to avoid collation problems, this optimization is
  121091. ** only attempted if the "a=123" term uses the default BINARY collation.
  121092. */
  121093. static int propagateConstants(
  121094. Parse *pParse, /* The parsing context */
  121095. Select *p /* The query in which to propagate constants */
  121096. ){
  121097. WhereConst x;
  121098. Walker w;
  121099. int nChng = 0;
  121100. x.pParse = pParse;
  121101. do{
  121102. x.nConst = 0;
  121103. x.nChng = 0;
  121104. x.apExpr = 0;
  121105. findConstInWhere(&x, p->pWhere);
  121106. if( x.nConst ){
  121107. memset(&w, 0, sizeof(w));
  121108. w.pParse = pParse;
  121109. w.xExprCallback = propagateConstantExprRewrite;
  121110. w.xSelectCallback = sqlite3SelectWalkNoop;
  121111. w.xSelectCallback2 = 0;
  121112. w.walkerDepth = 0;
  121113. w.u.pConst = &x;
  121114. sqlite3WalkExpr(&w, p->pWhere);
  121115. sqlite3DbFree(x.pParse->db, x.apExpr);
  121116. nChng += x.nChng;
  121117. }
  121118. }while( x.nChng );
  121119. return nChng;
  121120. }
  121121. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  121122. /*
  121123. ** Make copies of relevant WHERE clause terms of the outer query into
  121124. ** the WHERE clause of subquery. Example:
  121125. **
  121126. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  121127. **
  121128. ** Transformed into:
  121129. **
  121130. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  121131. ** WHERE x=5 AND y=10;
  121132. **
  121133. ** The hope is that the terms added to the inner query will make it more
  121134. ** efficient.
  121135. **
  121136. ** Do not attempt this optimization if:
  121137. **
  121138. ** (1) (** This restriction was removed on 2017-09-29. We used to
  121139. ** disallow this optimization for aggregate subqueries, but now
  121140. ** it is allowed by putting the extra terms on the HAVING clause.
  121141. ** The added HAVING clause is pointless if the subquery lacks
  121142. ** a GROUP BY clause. But such a HAVING clause is also harmless
  121143. ** so there does not appear to be any reason to add extra logic
  121144. ** to suppress it. **)
  121145. **
  121146. ** (2) The inner query is the recursive part of a common table expression.
  121147. **
  121148. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  121149. ** clause would change the meaning of the LIMIT).
  121150. **
  121151. ** (4) The inner query is the right operand of a LEFT JOIN and the
  121152. ** expression to be pushed down does not come from the ON clause
  121153. ** on that LEFT JOIN.
  121154. **
  121155. ** (5) The WHERE clause expression originates in the ON or USING clause
  121156. ** of a LEFT JOIN where iCursor is not the right-hand table of that
  121157. ** left join. An example:
  121158. **
  121159. ** SELECT *
  121160. ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
  121161. ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
  121162. ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
  121163. **
  121164. ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
  121165. ** But if the (b2=2) term were to be pushed down into the bb subquery,
  121166. ** then the (1,1,NULL) row would be suppressed.
  121167. **
  121168. ** (6) The inner query features one or more window-functions (since
  121169. ** changes to the WHERE clause of the inner query could change the
  121170. ** window over which window functions are calculated).
  121171. **
  121172. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  121173. ** terms are duplicated into the subquery.
  121174. */
  121175. static int pushDownWhereTerms(
  121176. Parse *pParse, /* Parse context (for malloc() and error reporting) */
  121177. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  121178. Expr *pWhere, /* The WHERE clause of the outer query */
  121179. int iCursor, /* Cursor number of the subquery */
  121180. int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */
  121181. ){
  121182. Expr *pNew;
  121183. int nChng = 0;
  121184. if( pWhere==0 ) return 0;
  121185. if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
  121186. #ifndef SQLITE_OMIT_WINDOWFUNC
  121187. if( pSubq->pWin ) return 0; /* restriction (6) */
  121188. #endif
  121189. #ifdef SQLITE_DEBUG
  121190. /* Only the first term of a compound can have a WITH clause. But make
  121191. ** sure no other terms are marked SF_Recursive in case something changes
  121192. ** in the future.
  121193. */
  121194. {
  121195. Select *pX;
  121196. for(pX=pSubq; pX; pX=pX->pPrior){
  121197. assert( (pX->selFlags & (SF_Recursive))==0 );
  121198. }
  121199. }
  121200. #endif
  121201. if( pSubq->pLimit!=0 ){
  121202. return 0; /* restriction (3) */
  121203. }
  121204. while( pWhere->op==TK_AND ){
  121205. nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
  121206. iCursor, isLeftJoin);
  121207. pWhere = pWhere->pLeft;
  121208. }
  121209. if( isLeftJoin
  121210. && (ExprHasProperty(pWhere,EP_FromJoin)==0
  121211. || pWhere->iRightJoinTable!=iCursor)
  121212. ){
  121213. return 0; /* restriction (4) */
  121214. }
  121215. if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
  121216. return 0; /* restriction (5) */
  121217. }
  121218. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  121219. nChng++;
  121220. while( pSubq ){
  121221. SubstContext x;
  121222. pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
  121223. unsetJoinExpr(pNew, -1);
  121224. x.pParse = pParse;
  121225. x.iTable = iCursor;
  121226. x.iNewTable = iCursor;
  121227. x.isLeftJoin = 0;
  121228. x.pEList = pSubq->pEList;
  121229. pNew = substExpr(&x, pNew);
  121230. if( pSubq->selFlags & SF_Aggregate ){
  121231. pSubq->pHaving = sqlite3ExprAnd(pParse->db, pSubq->pHaving, pNew);
  121232. }else{
  121233. pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
  121234. }
  121235. pSubq = pSubq->pPrior;
  121236. }
  121237. }
  121238. return nChng;
  121239. }
  121240. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  121241. /*
  121242. ** The pFunc is the only aggregate function in the query. Check to see
  121243. ** if the query is a candidate for the min/max optimization.
  121244. **
  121245. ** If the query is a candidate for the min/max optimization, then set
  121246. ** *ppMinMax to be an ORDER BY clause to be used for the optimization
  121247. ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
  121248. ** whether pFunc is a min() or max() function.
  121249. **
  121250. ** If the query is not a candidate for the min/max optimization, return
  121251. ** WHERE_ORDERBY_NORMAL (which must be zero).
  121252. **
  121253. ** This routine must be called after aggregate functions have been
  121254. ** located but before their arguments have been subjected to aggregate
  121255. ** analysis.
  121256. */
  121257. static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
  121258. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  121259. ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */
  121260. const char *zFunc; /* Name of aggregate function pFunc */
  121261. ExprList *pOrderBy;
  121262. u8 sortOrder;
  121263. assert( *ppMinMax==0 );
  121264. assert( pFunc->op==TK_AGG_FUNCTION );
  121265. if( pEList==0 || pEList->nExpr!=1 ) return eRet;
  121266. zFunc = pFunc->u.zToken;
  121267. if( sqlite3StrICmp(zFunc, "min")==0 ){
  121268. eRet = WHERE_ORDERBY_MIN;
  121269. sortOrder = SQLITE_SO_ASC;
  121270. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  121271. eRet = WHERE_ORDERBY_MAX;
  121272. sortOrder = SQLITE_SO_DESC;
  121273. }else{
  121274. return eRet;
  121275. }
  121276. *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
  121277. assert( pOrderBy!=0 || db->mallocFailed );
  121278. if( pOrderBy ) pOrderBy->a[0].sortOrder = sortOrder;
  121279. return eRet;
  121280. }
  121281. /*
  121282. ** The select statement passed as the first argument is an aggregate query.
  121283. ** The second argument is the associated aggregate-info object. This
  121284. ** function tests if the SELECT is of the form:
  121285. **
  121286. ** SELECT count(*) FROM <tbl>
  121287. **
  121288. ** where table is a database table, not a sub-select or view. If the query
  121289. ** does match this pattern, then a pointer to the Table object representing
  121290. ** <tbl> is returned. Otherwise, 0 is returned.
  121291. */
  121292. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  121293. Table *pTab;
  121294. Expr *pExpr;
  121295. assert( !p->pGroupBy );
  121296. if( p->pWhere || p->pEList->nExpr!=1
  121297. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  121298. ){
  121299. return 0;
  121300. }
  121301. pTab = p->pSrc->a[0].pTab;
  121302. pExpr = p->pEList->a[0].pExpr;
  121303. assert( pTab && !pTab->pSelect && pExpr );
  121304. if( IsVirtual(pTab) ) return 0;
  121305. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  121306. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  121307. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  121308. if( pExpr->flags&EP_Distinct ) return 0;
  121309. return pTab;
  121310. }
  121311. /*
  121312. ** If the source-list item passed as an argument was augmented with an
  121313. ** INDEXED BY clause, then try to locate the specified index. If there
  121314. ** was such a clause and the named index cannot be found, return
  121315. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  121316. ** pFrom->pIndex and return SQLITE_OK.
  121317. */
  121318. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  121319. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  121320. Table *pTab = pFrom->pTab;
  121321. char *zIndexedBy = pFrom->u1.zIndexedBy;
  121322. Index *pIdx;
  121323. for(pIdx=pTab->pIndex;
  121324. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  121325. pIdx=pIdx->pNext
  121326. );
  121327. if( !pIdx ){
  121328. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  121329. pParse->checkSchema = 1;
  121330. return SQLITE_ERROR;
  121331. }
  121332. pFrom->pIBIndex = pIdx;
  121333. }
  121334. return SQLITE_OK;
  121335. }
  121336. /*
  121337. ** Detect compound SELECT statements that use an ORDER BY clause with
  121338. ** an alternative collating sequence.
  121339. **
  121340. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  121341. **
  121342. ** These are rewritten as a subquery:
  121343. **
  121344. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  121345. ** ORDER BY ... COLLATE ...
  121346. **
  121347. ** This transformation is necessary because the multiSelectOrderBy() routine
  121348. ** above that generates the code for a compound SELECT with an ORDER BY clause
  121349. ** uses a merge algorithm that requires the same collating sequence on the
  121350. ** result columns as on the ORDER BY clause. See ticket
  121351. ** http://www.sqlite.org/src/info/6709574d2a
  121352. **
  121353. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  121354. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  121355. ** there are COLLATE terms in the ORDER BY.
  121356. */
  121357. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  121358. int i;
  121359. Select *pNew;
  121360. Select *pX;
  121361. sqlite3 *db;
  121362. struct ExprList_item *a;
  121363. SrcList *pNewSrc;
  121364. Parse *pParse;
  121365. Token dummy;
  121366. if( p->pPrior==0 ) return WRC_Continue;
  121367. if( p->pOrderBy==0 ) return WRC_Continue;
  121368. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  121369. if( pX==0 ) return WRC_Continue;
  121370. a = p->pOrderBy->a;
  121371. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  121372. if( a[i].pExpr->flags & EP_Collate ) break;
  121373. }
  121374. if( i<0 ) return WRC_Continue;
  121375. /* If we reach this point, that means the transformation is required. */
  121376. pParse = pWalker->pParse;
  121377. db = pParse->db;
  121378. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  121379. if( pNew==0 ) return WRC_Abort;
  121380. memset(&dummy, 0, sizeof(dummy));
  121381. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  121382. if( pNewSrc==0 ) return WRC_Abort;
  121383. *pNew = *p;
  121384. p->pSrc = pNewSrc;
  121385. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
  121386. p->op = TK_SELECT;
  121387. p->pWhere = 0;
  121388. pNew->pGroupBy = 0;
  121389. pNew->pHaving = 0;
  121390. pNew->pOrderBy = 0;
  121391. p->pPrior = 0;
  121392. p->pNext = 0;
  121393. p->pWith = 0;
  121394. p->selFlags &= ~SF_Compound;
  121395. assert( (p->selFlags & SF_Converted)==0 );
  121396. p->selFlags |= SF_Converted;
  121397. assert( pNew->pPrior!=0 );
  121398. pNew->pPrior->pNext = pNew;
  121399. pNew->pLimit = 0;
  121400. return WRC_Continue;
  121401. }
  121402. /*
  121403. ** Check to see if the FROM clause term pFrom has table-valued function
  121404. ** arguments. If it does, leave an error message in pParse and return
  121405. ** non-zero, since pFrom is not allowed to be a table-valued function.
  121406. */
  121407. static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
  121408. if( pFrom->fg.isTabFunc ){
  121409. sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
  121410. return 1;
  121411. }
  121412. return 0;
  121413. }
  121414. #ifndef SQLITE_OMIT_CTE
  121415. /*
  121416. ** Argument pWith (which may be NULL) points to a linked list of nested
  121417. ** WITH contexts, from inner to outermost. If the table identified by
  121418. ** FROM clause element pItem is really a common-table-expression (CTE)
  121419. ** then return a pointer to the CTE definition for that table. Otherwise
  121420. ** return NULL.
  121421. **
  121422. ** If a non-NULL value is returned, set *ppContext to point to the With
  121423. ** object that the returned CTE belongs to.
  121424. */
  121425. static struct Cte *searchWith(
  121426. With *pWith, /* Current innermost WITH clause */
  121427. struct SrcList_item *pItem, /* FROM clause element to resolve */
  121428. With **ppContext /* OUT: WITH clause return value belongs to */
  121429. ){
  121430. const char *zName;
  121431. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  121432. With *p;
  121433. for(p=pWith; p; p=p->pOuter){
  121434. int i;
  121435. for(i=0; i<p->nCte; i++){
  121436. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  121437. *ppContext = p;
  121438. return &p->a[i];
  121439. }
  121440. }
  121441. }
  121442. }
  121443. return 0;
  121444. }
  121445. /* The code generator maintains a stack of active WITH clauses
  121446. ** with the inner-most WITH clause being at the top of the stack.
  121447. **
  121448. ** This routine pushes the WITH clause passed as the second argument
  121449. ** onto the top of the stack. If argument bFree is true, then this
  121450. ** WITH clause will never be popped from the stack. In this case it
  121451. ** should be freed along with the Parse object. In other cases, when
  121452. ** bFree==0, the With object will be freed along with the SELECT
  121453. ** statement with which it is associated.
  121454. */
  121455. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  121456. assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
  121457. if( pWith ){
  121458. assert( pParse->pWith!=pWith );
  121459. pWith->pOuter = pParse->pWith;
  121460. pParse->pWith = pWith;
  121461. if( bFree ) pParse->pWithToFree = pWith;
  121462. }
  121463. }
  121464. /*
  121465. ** This function checks if argument pFrom refers to a CTE declared by
  121466. ** a WITH clause on the stack currently maintained by the parser. And,
  121467. ** if currently processing a CTE expression, if it is a recursive
  121468. ** reference to the current CTE.
  121469. **
  121470. ** If pFrom falls into either of the two categories above, pFrom->pTab
  121471. ** and other fields are populated accordingly. The caller should check
  121472. ** (pFrom->pTab!=0) to determine whether or not a successful match
  121473. ** was found.
  121474. **
  121475. ** Whether or not a match is found, SQLITE_OK is returned if no error
  121476. ** occurs. If an error does occur, an error message is stored in the
  121477. ** parser and some error code other than SQLITE_OK returned.
  121478. */
  121479. static int withExpand(
  121480. Walker *pWalker,
  121481. struct SrcList_item *pFrom
  121482. ){
  121483. Parse *pParse = pWalker->pParse;
  121484. sqlite3 *db = pParse->db;
  121485. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  121486. With *pWith; /* WITH clause that pCte belongs to */
  121487. assert( pFrom->pTab==0 );
  121488. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  121489. if( pCte ){
  121490. Table *pTab;
  121491. ExprList *pEList;
  121492. Select *pSel;
  121493. Select *pLeft; /* Left-most SELECT statement */
  121494. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  121495. With *pSavedWith; /* Initial value of pParse->pWith */
  121496. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  121497. ** recursive reference to CTE pCte. Leave an error in pParse and return
  121498. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  121499. ** In this case, proceed. */
  121500. if( pCte->zCteErr ){
  121501. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  121502. return SQLITE_ERROR;
  121503. }
  121504. if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
  121505. assert( pFrom->pTab==0 );
  121506. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  121507. if( pTab==0 ) return WRC_Abort;
  121508. pTab->nTabRef = 1;
  121509. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  121510. pTab->iPKey = -1;
  121511. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  121512. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  121513. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  121514. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  121515. assert( pFrom->pSelect );
  121516. /* Check if this is a recursive CTE. */
  121517. pSel = pFrom->pSelect;
  121518. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  121519. if( bMayRecursive ){
  121520. int i;
  121521. SrcList *pSrc = pFrom->pSelect->pSrc;
  121522. for(i=0; i<pSrc->nSrc; i++){
  121523. struct SrcList_item *pItem = &pSrc->a[i];
  121524. if( pItem->zDatabase==0
  121525. && pItem->zName!=0
  121526. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  121527. ){
  121528. pItem->pTab = pTab;
  121529. pItem->fg.isRecursive = 1;
  121530. pTab->nTabRef++;
  121531. pSel->selFlags |= SF_Recursive;
  121532. }
  121533. }
  121534. }
  121535. /* Only one recursive reference is permitted. */
  121536. if( pTab->nTabRef>2 ){
  121537. sqlite3ErrorMsg(
  121538. pParse, "multiple references to recursive table: %s", pCte->zName
  121539. );
  121540. return SQLITE_ERROR;
  121541. }
  121542. assert( pTab->nTabRef==1 ||
  121543. ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
  121544. pCte->zCteErr = "circular reference: %s";
  121545. pSavedWith = pParse->pWith;
  121546. pParse->pWith = pWith;
  121547. if( bMayRecursive ){
  121548. Select *pPrior = pSel->pPrior;
  121549. assert( pPrior->pWith==0 );
  121550. pPrior->pWith = pSel->pWith;
  121551. sqlite3WalkSelect(pWalker, pPrior);
  121552. pPrior->pWith = 0;
  121553. }else{
  121554. sqlite3WalkSelect(pWalker, pSel);
  121555. }
  121556. pParse->pWith = pWith;
  121557. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  121558. pEList = pLeft->pEList;
  121559. if( pCte->pCols ){
  121560. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  121561. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  121562. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  121563. );
  121564. pParse->pWith = pSavedWith;
  121565. return SQLITE_ERROR;
  121566. }
  121567. pEList = pCte->pCols;
  121568. }
  121569. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  121570. if( bMayRecursive ){
  121571. if( pSel->selFlags & SF_Recursive ){
  121572. pCte->zCteErr = "multiple recursive references: %s";
  121573. }else{
  121574. pCte->zCteErr = "recursive reference in a subquery: %s";
  121575. }
  121576. sqlite3WalkSelect(pWalker, pSel);
  121577. }
  121578. pCte->zCteErr = 0;
  121579. pParse->pWith = pSavedWith;
  121580. }
  121581. return SQLITE_OK;
  121582. }
  121583. #endif
  121584. #ifndef SQLITE_OMIT_CTE
  121585. /*
  121586. ** If the SELECT passed as the second argument has an associated WITH
  121587. ** clause, pop it from the stack stored as part of the Parse object.
  121588. **
  121589. ** This function is used as the xSelectCallback2() callback by
  121590. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  121591. ** names and other FROM clause elements.
  121592. */
  121593. static void selectPopWith(Walker *pWalker, Select *p){
  121594. Parse *pParse = pWalker->pParse;
  121595. if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
  121596. With *pWith = findRightmost(p)->pWith;
  121597. if( pWith!=0 ){
  121598. assert( pParse->pWith==pWith );
  121599. pParse->pWith = pWith->pOuter;
  121600. }
  121601. }
  121602. }
  121603. #else
  121604. #define selectPopWith 0
  121605. #endif
  121606. /*
  121607. ** The SrcList_item structure passed as the second argument represents a
  121608. ** sub-query in the FROM clause of a SELECT statement. This function
  121609. ** allocates and populates the SrcList_item.pTab object. If successful,
  121610. ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
  121611. ** SQLITE_NOMEM.
  121612. */
  121613. SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){
  121614. Select *pSel = pFrom->pSelect;
  121615. Table *pTab;
  121616. assert( pSel );
  121617. pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
  121618. if( pTab==0 ) return SQLITE_NOMEM;
  121619. pTab->nTabRef = 1;
  121620. if( pFrom->zAlias ){
  121621. pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
  121622. }else{
  121623. pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId);
  121624. }
  121625. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  121626. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  121627. pTab->iPKey = -1;
  121628. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  121629. pTab->tabFlags |= TF_Ephemeral;
  121630. return SQLITE_OK;
  121631. }
  121632. /*
  121633. ** This routine is a Walker callback for "expanding" a SELECT statement.
  121634. ** "Expanding" means to do the following:
  121635. **
  121636. ** (1) Make sure VDBE cursor numbers have been assigned to every
  121637. ** element of the FROM clause.
  121638. **
  121639. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  121640. ** defines FROM clause. When views appear in the FROM clause,
  121641. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  121642. ** that implements the view. A copy is made of the view's SELECT
  121643. ** statement so that we can freely modify or delete that statement
  121644. ** without worrying about messing up the persistent representation
  121645. ** of the view.
  121646. **
  121647. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  121648. ** on joins and the ON and USING clause of joins.
  121649. **
  121650. ** (4) Scan the list of columns in the result set (pEList) looking
  121651. ** for instances of the "*" operator or the TABLE.* operator.
  121652. ** If found, expand each "*" to be every column in every table
  121653. ** and TABLE.* to be every column in TABLE.
  121654. **
  121655. */
  121656. static int selectExpander(Walker *pWalker, Select *p){
  121657. Parse *pParse = pWalker->pParse;
  121658. int i, j, k;
  121659. SrcList *pTabList;
  121660. ExprList *pEList;
  121661. struct SrcList_item *pFrom;
  121662. sqlite3 *db = pParse->db;
  121663. Expr *pE, *pRight, *pExpr;
  121664. u16 selFlags = p->selFlags;
  121665. u32 elistFlags = 0;
  121666. p->selFlags |= SF_Expanded;
  121667. if( db->mallocFailed ){
  121668. return WRC_Abort;
  121669. }
  121670. assert( p->pSrc!=0 );
  121671. if( (selFlags & SF_Expanded)!=0 ){
  121672. return WRC_Prune;
  121673. }
  121674. pTabList = p->pSrc;
  121675. pEList = p->pEList;
  121676. sqlite3WithPush(pParse, p->pWith, 0);
  121677. /* Make sure cursor numbers have been assigned to all entries in
  121678. ** the FROM clause of the SELECT statement.
  121679. */
  121680. sqlite3SrcListAssignCursors(pParse, pTabList);
  121681. /* Look up every table named in the FROM clause of the select. If
  121682. ** an entry of the FROM clause is a subquery instead of a table or view,
  121683. ** then create a transient table structure to describe the subquery.
  121684. */
  121685. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  121686. Table *pTab;
  121687. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  121688. if( pFrom->fg.isRecursive ) continue;
  121689. assert( pFrom->pTab==0 );
  121690. #ifndef SQLITE_OMIT_CTE
  121691. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  121692. if( pFrom->pTab ) {} else
  121693. #endif
  121694. if( pFrom->zName==0 ){
  121695. #ifndef SQLITE_OMIT_SUBQUERY
  121696. Select *pSel = pFrom->pSelect;
  121697. /* A sub-query in the FROM clause of a SELECT */
  121698. assert( pSel!=0 );
  121699. assert( pFrom->pTab==0 );
  121700. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  121701. if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
  121702. #endif
  121703. }else{
  121704. /* An ordinary table or view name in the FROM clause */
  121705. assert( pFrom->pTab==0 );
  121706. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  121707. if( pTab==0 ) return WRC_Abort;
  121708. if( pTab->nTabRef>=0xffff ){
  121709. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  121710. pTab->zName);
  121711. pFrom->pTab = 0;
  121712. return WRC_Abort;
  121713. }
  121714. pTab->nTabRef++;
  121715. if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
  121716. return WRC_Abort;
  121717. }
  121718. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  121719. if( IsVirtual(pTab) || pTab->pSelect ){
  121720. i16 nCol;
  121721. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  121722. assert( pFrom->pSelect==0 );
  121723. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  121724. nCol = pTab->nCol;
  121725. pTab->nCol = -1;
  121726. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  121727. pTab->nCol = nCol;
  121728. }
  121729. #endif
  121730. }
  121731. /* Locate the index named by the INDEXED BY clause, if any. */
  121732. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  121733. return WRC_Abort;
  121734. }
  121735. }
  121736. /* Process NATURAL keywords, and ON and USING clauses of joins.
  121737. */
  121738. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  121739. return WRC_Abort;
  121740. }
  121741. /* For every "*" that occurs in the column list, insert the names of
  121742. ** all columns in all tables. And for every TABLE.* insert the names
  121743. ** of all columns in TABLE. The parser inserted a special expression
  121744. ** with the TK_ASTERISK operator for each "*" that it found in the column
  121745. ** list. The following code just has to locate the TK_ASTERISK
  121746. ** expressions and expand each one to the list of all columns in
  121747. ** all tables.
  121748. **
  121749. ** The first loop just checks to see if there are any "*" operators
  121750. ** that need expanding.
  121751. */
  121752. for(k=0; k<pEList->nExpr; k++){
  121753. pE = pEList->a[k].pExpr;
  121754. if( pE->op==TK_ASTERISK ) break;
  121755. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  121756. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  121757. if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
  121758. elistFlags |= pE->flags;
  121759. }
  121760. if( k<pEList->nExpr ){
  121761. /*
  121762. ** If we get here it means the result set contains one or more "*"
  121763. ** operators that need to be expanded. Loop through each expression
  121764. ** in the result set and expand them one by one.
  121765. */
  121766. struct ExprList_item *a = pEList->a;
  121767. ExprList *pNew = 0;
  121768. int flags = pParse->db->flags;
  121769. int longNames = (flags & SQLITE_FullColNames)!=0
  121770. && (flags & SQLITE_ShortColNames)==0;
  121771. for(k=0; k<pEList->nExpr; k++){
  121772. pE = a[k].pExpr;
  121773. elistFlags |= pE->flags;
  121774. pRight = pE->pRight;
  121775. assert( pE->op!=TK_DOT || pRight!=0 );
  121776. if( pE->op!=TK_ASTERISK
  121777. && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
  121778. ){
  121779. /* This particular expression does not need to be expanded.
  121780. */
  121781. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  121782. if( pNew ){
  121783. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  121784. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  121785. a[k].zName = 0;
  121786. a[k].zSpan = 0;
  121787. }
  121788. a[k].pExpr = 0;
  121789. }else{
  121790. /* This expression is a "*" or a "TABLE.*" and needs to be
  121791. ** expanded. */
  121792. int tableSeen = 0; /* Set to 1 when TABLE matches */
  121793. char *zTName = 0; /* text of name of TABLE */
  121794. if( pE->op==TK_DOT ){
  121795. assert( pE->pLeft!=0 );
  121796. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  121797. zTName = pE->pLeft->u.zToken;
  121798. }
  121799. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  121800. Table *pTab = pFrom->pTab;
  121801. Select *pSub = pFrom->pSelect;
  121802. char *zTabName = pFrom->zAlias;
  121803. const char *zSchemaName = 0;
  121804. int iDb;
  121805. if( zTabName==0 ){
  121806. zTabName = pTab->zName;
  121807. }
  121808. if( db->mallocFailed ) break;
  121809. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  121810. pSub = 0;
  121811. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  121812. continue;
  121813. }
  121814. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  121815. zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
  121816. }
  121817. for(j=0; j<pTab->nCol; j++){
  121818. char *zName = pTab->aCol[j].zName;
  121819. char *zColname; /* The computed column name */
  121820. char *zToFree; /* Malloced string that needs to be freed */
  121821. Token sColname; /* Computed column name as a token */
  121822. assert( zName );
  121823. if( zTName && pSub
  121824. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  121825. ){
  121826. continue;
  121827. }
  121828. /* If a column is marked as 'hidden', omit it from the expanded
  121829. ** result-set list unless the SELECT has the SF_IncludeHidden
  121830. ** bit set.
  121831. */
  121832. if( (p->selFlags & SF_IncludeHidden)==0
  121833. && IsHiddenColumn(&pTab->aCol[j])
  121834. ){
  121835. continue;
  121836. }
  121837. tableSeen = 1;
  121838. if( i>0 && zTName==0 ){
  121839. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  121840. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  121841. ){
  121842. /* In a NATURAL join, omit the join columns from the
  121843. ** table to the right of the join */
  121844. continue;
  121845. }
  121846. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  121847. /* In a join with a USING clause, omit columns in the
  121848. ** using clause from the table on the right. */
  121849. continue;
  121850. }
  121851. }
  121852. pRight = sqlite3Expr(db, TK_ID, zName);
  121853. zColname = zName;
  121854. zToFree = 0;
  121855. if( longNames || pTabList->nSrc>1 ){
  121856. Expr *pLeft;
  121857. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  121858. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  121859. if( zSchemaName ){
  121860. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  121861. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
  121862. }
  121863. if( longNames ){
  121864. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  121865. zToFree = zColname;
  121866. }
  121867. }else{
  121868. pExpr = pRight;
  121869. }
  121870. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  121871. sqlite3TokenInit(&sColname, zColname);
  121872. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  121873. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  121874. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  121875. if( pSub ){
  121876. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  121877. testcase( pX->zSpan==0 );
  121878. }else{
  121879. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  121880. zSchemaName, zTabName, zColname);
  121881. testcase( pX->zSpan==0 );
  121882. }
  121883. pX->bSpanIsTab = 1;
  121884. }
  121885. sqlite3DbFree(db, zToFree);
  121886. }
  121887. }
  121888. if( !tableSeen ){
  121889. if( zTName ){
  121890. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  121891. }else{
  121892. sqlite3ErrorMsg(pParse, "no tables specified");
  121893. }
  121894. }
  121895. }
  121896. }
  121897. sqlite3ExprListDelete(db, pEList);
  121898. p->pEList = pNew;
  121899. }
  121900. if( p->pEList ){
  121901. if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  121902. sqlite3ErrorMsg(pParse, "too many columns in result set");
  121903. return WRC_Abort;
  121904. }
  121905. if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
  121906. p->selFlags |= SF_ComplexResult;
  121907. }
  121908. }
  121909. return WRC_Continue;
  121910. }
  121911. /*
  121912. ** No-op routine for the parse-tree walker.
  121913. **
  121914. ** When this routine is the Walker.xExprCallback then expression trees
  121915. ** are walked without any actions being taken at each node. Presumably,
  121916. ** when this routine is used for Walker.xExprCallback then
  121917. ** Walker.xSelectCallback is set to do something useful for every
  121918. ** subquery in the parser tree.
  121919. */
  121920. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  121921. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  121922. return WRC_Continue;
  121923. }
  121924. /*
  121925. ** No-op routine for the parse-tree walker for SELECT statements.
  121926. ** subquery in the parser tree.
  121927. */
  121928. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
  121929. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  121930. return WRC_Continue;
  121931. }
  121932. #if SQLITE_DEBUG
  121933. /*
  121934. ** Always assert. This xSelectCallback2 implementation proves that the
  121935. ** xSelectCallback2 is never invoked.
  121936. */
  121937. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
  121938. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  121939. assert( 0 );
  121940. }
  121941. #endif
  121942. /*
  121943. ** This routine "expands" a SELECT statement and all of its subqueries.
  121944. ** For additional information on what it means to "expand" a SELECT
  121945. ** statement, see the comment on the selectExpand worker callback above.
  121946. **
  121947. ** Expanding a SELECT statement is the first step in processing a
  121948. ** SELECT statement. The SELECT statement must be expanded before
  121949. ** name resolution is performed.
  121950. **
  121951. ** If anything goes wrong, an error message is written into pParse.
  121952. ** The calling function can detect the problem by looking at pParse->nErr
  121953. ** and/or pParse->db->mallocFailed.
  121954. */
  121955. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  121956. Walker w;
  121957. w.xExprCallback = sqlite3ExprWalkNoop;
  121958. w.pParse = pParse;
  121959. if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
  121960. w.xSelectCallback = convertCompoundSelectToSubquery;
  121961. w.xSelectCallback2 = 0;
  121962. sqlite3WalkSelect(&w, pSelect);
  121963. }
  121964. w.xSelectCallback = selectExpander;
  121965. w.xSelectCallback2 = selectPopWith;
  121966. sqlite3WalkSelect(&w, pSelect);
  121967. }
  121968. #ifndef SQLITE_OMIT_SUBQUERY
  121969. /*
  121970. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  121971. ** interface.
  121972. **
  121973. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  121974. ** information to the Table structure that represents the result set
  121975. ** of that subquery.
  121976. **
  121977. ** The Table structure that represents the result set was constructed
  121978. ** by selectExpander() but the type and collation information was omitted
  121979. ** at that point because identifiers had not yet been resolved. This
  121980. ** routine is called after identifier resolution.
  121981. */
  121982. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  121983. Parse *pParse;
  121984. int i;
  121985. SrcList *pTabList;
  121986. struct SrcList_item *pFrom;
  121987. assert( p->selFlags & SF_Resolved );
  121988. if( p->selFlags & SF_HasTypeInfo ) return;
  121989. p->selFlags |= SF_HasTypeInfo;
  121990. pParse = pWalker->pParse;
  121991. pTabList = p->pSrc;
  121992. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  121993. Table *pTab = pFrom->pTab;
  121994. assert( pTab!=0 );
  121995. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  121996. /* A sub-query in the FROM clause of a SELECT */
  121997. Select *pSel = pFrom->pSelect;
  121998. if( pSel ){
  121999. while( pSel->pPrior ) pSel = pSel->pPrior;
  122000. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
  122001. }
  122002. }
  122003. }
  122004. }
  122005. #endif
  122006. /*
  122007. ** This routine adds datatype and collating sequence information to
  122008. ** the Table structures of all FROM-clause subqueries in a
  122009. ** SELECT statement.
  122010. **
  122011. ** Use this routine after name resolution.
  122012. */
  122013. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  122014. #ifndef SQLITE_OMIT_SUBQUERY
  122015. Walker w;
  122016. w.xSelectCallback = sqlite3SelectWalkNoop;
  122017. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  122018. w.xExprCallback = sqlite3ExprWalkNoop;
  122019. w.pParse = pParse;
  122020. sqlite3WalkSelect(&w, pSelect);
  122021. #endif
  122022. }
  122023. /*
  122024. ** This routine sets up a SELECT statement for processing. The
  122025. ** following is accomplished:
  122026. **
  122027. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  122028. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  122029. ** * ON and USING clauses are shifted into WHERE statements
  122030. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  122031. ** * Identifiers in expression are matched to tables.
  122032. **
  122033. ** This routine acts recursively on all subqueries within the SELECT.
  122034. */
  122035. SQLITE_PRIVATE void sqlite3SelectPrep(
  122036. Parse *pParse, /* The parser context */
  122037. Select *p, /* The SELECT statement being coded. */
  122038. NameContext *pOuterNC /* Name context for container */
  122039. ){
  122040. assert( p!=0 || pParse->db->mallocFailed );
  122041. if( pParse->db->mallocFailed ) return;
  122042. if( p->selFlags & SF_HasTypeInfo ) return;
  122043. sqlite3SelectExpand(pParse, p);
  122044. if( pParse->nErr || pParse->db->mallocFailed ) return;
  122045. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  122046. if( pParse->nErr || pParse->db->mallocFailed ) return;
  122047. sqlite3SelectAddTypeInfo(pParse, p);
  122048. }
  122049. /*
  122050. ** Reset the aggregate accumulator.
  122051. **
  122052. ** The aggregate accumulator is a set of memory cells that hold
  122053. ** intermediate results while calculating an aggregate. This
  122054. ** routine generates code that stores NULLs in all of those memory
  122055. ** cells.
  122056. */
  122057. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  122058. Vdbe *v = pParse->pVdbe;
  122059. int i;
  122060. struct AggInfo_func *pFunc;
  122061. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  122062. if( nReg==0 ) return;
  122063. #ifdef SQLITE_DEBUG
  122064. /* Verify that all AggInfo registers are within the range specified by
  122065. ** AggInfo.mnReg..AggInfo.mxReg */
  122066. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  122067. for(i=0; i<pAggInfo->nColumn; i++){
  122068. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  122069. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  122070. }
  122071. for(i=0; i<pAggInfo->nFunc; i++){
  122072. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  122073. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  122074. }
  122075. #endif
  122076. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  122077. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  122078. if( pFunc->iDistinct>=0 ){
  122079. Expr *pE = pFunc->pExpr;
  122080. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  122081. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  122082. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  122083. "argument");
  122084. pFunc->iDistinct = -1;
  122085. }else{
  122086. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
  122087. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  122088. (char*)pKeyInfo, P4_KEYINFO);
  122089. }
  122090. }
  122091. }
  122092. }
  122093. /*
  122094. ** Invoke the OP_AggFinalize opcode for every aggregate function
  122095. ** in the AggInfo structure.
  122096. */
  122097. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  122098. Vdbe *v = pParse->pVdbe;
  122099. int i;
  122100. struct AggInfo_func *pF;
  122101. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  122102. ExprList *pList = pF->pExpr->x.pList;
  122103. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  122104. sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
  122105. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  122106. }
  122107. }
  122108. /*
  122109. ** Update the accumulator memory cells for an aggregate based on
  122110. ** the current cursor position.
  122111. **
  122112. ** If regAcc is non-zero and there are no min() or max() aggregates
  122113. ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
  122114. ** registers if register regAcc contains 0. The caller will take care
  122115. ** of setting and clearing regAcc.
  122116. */
  122117. static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
  122118. Vdbe *v = pParse->pVdbe;
  122119. int i;
  122120. int regHit = 0;
  122121. int addrHitTest = 0;
  122122. struct AggInfo_func *pF;
  122123. struct AggInfo_col *pC;
  122124. pAggInfo->directMode = 1;
  122125. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  122126. int nArg;
  122127. int addrNext = 0;
  122128. int regAgg;
  122129. ExprList *pList = pF->pExpr->x.pList;
  122130. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  122131. if( pList ){
  122132. nArg = pList->nExpr;
  122133. regAgg = sqlite3GetTempRange(pParse, nArg);
  122134. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  122135. }else{
  122136. nArg = 0;
  122137. regAgg = 0;
  122138. }
  122139. if( pF->iDistinct>=0 ){
  122140. addrNext = sqlite3VdbeMakeLabel(pParse);
  122141. testcase( nArg==0 ); /* Error condition */
  122142. testcase( nArg>1 ); /* Also an error */
  122143. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  122144. }
  122145. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  122146. CollSeq *pColl = 0;
  122147. struct ExprList_item *pItem;
  122148. int j;
  122149. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  122150. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  122151. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  122152. }
  122153. if( !pColl ){
  122154. pColl = pParse->db->pDfltColl;
  122155. }
  122156. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  122157. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  122158. }
  122159. sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
  122160. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  122161. sqlite3VdbeChangeP5(v, (u8)nArg);
  122162. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  122163. if( addrNext ){
  122164. sqlite3VdbeResolveLabel(v, addrNext);
  122165. }
  122166. }
  122167. if( regHit==0 && pAggInfo->nAccumulator ){
  122168. regHit = regAcc;
  122169. }
  122170. if( regHit ){
  122171. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  122172. }
  122173. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  122174. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  122175. }
  122176. pAggInfo->directMode = 0;
  122177. if( addrHitTest ){
  122178. sqlite3VdbeJumpHere(v, addrHitTest);
  122179. }
  122180. }
  122181. /*
  122182. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  122183. ** count(*) query ("SELECT count(*) FROM pTab").
  122184. */
  122185. #ifndef SQLITE_OMIT_EXPLAIN
  122186. static void explainSimpleCount(
  122187. Parse *pParse, /* Parse context */
  122188. Table *pTab, /* Table being queried */
  122189. Index *pIdx /* Index used to optimize scan, or NULL */
  122190. ){
  122191. if( pParse->explain==2 ){
  122192. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  122193. sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
  122194. pTab->zName,
  122195. bCover ? " USING COVERING INDEX " : "",
  122196. bCover ? pIdx->zName : ""
  122197. );
  122198. }
  122199. }
  122200. #else
  122201. # define explainSimpleCount(a,b,c)
  122202. #endif
  122203. /*
  122204. ** sqlite3WalkExpr() callback used by havingToWhere().
  122205. **
  122206. ** If the node passed to the callback is a TK_AND node, return
  122207. ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
  122208. **
  122209. ** Otherwise, return WRC_Prune. In this case, also check if the
  122210. ** sub-expression matches the criteria for being moved to the WHERE
  122211. ** clause. If so, add it to the WHERE clause and replace the sub-expression
  122212. ** within the HAVING expression with a constant "1".
  122213. */
  122214. static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
  122215. if( pExpr->op!=TK_AND ){
  122216. Select *pS = pWalker->u.pSelect;
  122217. if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
  122218. sqlite3 *db = pWalker->pParse->db;
  122219. Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
  122220. if( pNew ){
  122221. Expr *pWhere = pS->pWhere;
  122222. SWAP(Expr, *pNew, *pExpr);
  122223. pNew = sqlite3ExprAnd(db, pWhere, pNew);
  122224. pS->pWhere = pNew;
  122225. pWalker->eCode = 1;
  122226. }
  122227. }
  122228. return WRC_Prune;
  122229. }
  122230. return WRC_Continue;
  122231. }
  122232. /*
  122233. ** Transfer eligible terms from the HAVING clause of a query, which is
  122234. ** processed after grouping, to the WHERE clause, which is processed before
  122235. ** grouping. For example, the query:
  122236. **
  122237. ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
  122238. **
  122239. ** can be rewritten as:
  122240. **
  122241. ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
  122242. **
  122243. ** A term of the HAVING expression is eligible for transfer if it consists
  122244. ** entirely of constants and expressions that are also GROUP BY terms that
  122245. ** use the "BINARY" collation sequence.
  122246. */
  122247. static void havingToWhere(Parse *pParse, Select *p){
  122248. Walker sWalker;
  122249. memset(&sWalker, 0, sizeof(sWalker));
  122250. sWalker.pParse = pParse;
  122251. sWalker.xExprCallback = havingToWhereExprCb;
  122252. sWalker.u.pSelect = p;
  122253. sqlite3WalkExpr(&sWalker, p->pHaving);
  122254. #if SELECTTRACE_ENABLED
  122255. if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){
  122256. SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
  122257. sqlite3TreeViewSelect(0, p, 0);
  122258. }
  122259. #endif
  122260. }
  122261. /*
  122262. ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
  122263. ** If it is, then return the SrcList_item for the prior view. If it is not,
  122264. ** then return 0.
  122265. */
  122266. static struct SrcList_item *isSelfJoinView(
  122267. SrcList *pTabList, /* Search for self-joins in this FROM clause */
  122268. struct SrcList_item *pThis /* Search for prior reference to this subquery */
  122269. ){
  122270. struct SrcList_item *pItem;
  122271. for(pItem = pTabList->a; pItem<pThis; pItem++){
  122272. Select *pS1;
  122273. if( pItem->pSelect==0 ) continue;
  122274. if( pItem->fg.viaCoroutine ) continue;
  122275. if( pItem->zName==0 ) continue;
  122276. if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
  122277. if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
  122278. pS1 = pItem->pSelect;
  122279. if( pThis->pSelect->selId!=pS1->selId ){
  122280. /* The query flattener left two different CTE tables with identical
  122281. ** names in the same FROM clause. */
  122282. continue;
  122283. }
  122284. if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1) ){
  122285. /* The view was modified by some other optimization such as
  122286. ** pushDownWhereTerms() */
  122287. continue;
  122288. }
  122289. return pItem;
  122290. }
  122291. return 0;
  122292. }
  122293. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  122294. /*
  122295. ** Attempt to transform a query of the form
  122296. **
  122297. ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
  122298. **
  122299. ** Into this:
  122300. **
  122301. ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
  122302. **
  122303. ** The transformation only works if all of the following are true:
  122304. **
  122305. ** * The subquery is a UNION ALL of two or more terms
  122306. ** * The subquery does not have a LIMIT clause
  122307. ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
  122308. ** * The outer query is a simple count(*)
  122309. **
  122310. ** Return TRUE if the optimization is undertaken.
  122311. */
  122312. static int countOfViewOptimization(Parse *pParse, Select *p){
  122313. Select *pSub, *pPrior;
  122314. Expr *pExpr;
  122315. Expr *pCount;
  122316. sqlite3 *db;
  122317. if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
  122318. if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
  122319. pExpr = p->pEList->a[0].pExpr;
  122320. if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
  122321. if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
  122322. if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
  122323. if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
  122324. pSub = p->pSrc->a[0].pSelect;
  122325. if( pSub==0 ) return 0; /* The FROM is a subquery */
  122326. if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
  122327. do{
  122328. if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
  122329. if( pSub->pWhere ) return 0; /* No WHERE clause */
  122330. if( pSub->pLimit ) return 0; /* No LIMIT clause */
  122331. if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
  122332. pSub = pSub->pPrior; /* Repeat over compound */
  122333. }while( pSub );
  122334. /* If we reach this point then it is OK to perform the transformation */
  122335. db = pParse->db;
  122336. pCount = pExpr;
  122337. pExpr = 0;
  122338. pSub = p->pSrc->a[0].pSelect;
  122339. p->pSrc->a[0].pSelect = 0;
  122340. sqlite3SrcListDelete(db, p->pSrc);
  122341. p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
  122342. while( pSub ){
  122343. Expr *pTerm;
  122344. pPrior = pSub->pPrior;
  122345. pSub->pPrior = 0;
  122346. pSub->pNext = 0;
  122347. pSub->selFlags |= SF_Aggregate;
  122348. pSub->selFlags &= ~SF_Compound;
  122349. pSub->nSelectRow = 0;
  122350. sqlite3ExprListDelete(db, pSub->pEList);
  122351. pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
  122352. pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
  122353. pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  122354. sqlite3PExprAddSelect(pParse, pTerm, pSub);
  122355. if( pExpr==0 ){
  122356. pExpr = pTerm;
  122357. }else{
  122358. pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
  122359. }
  122360. pSub = pPrior;
  122361. }
  122362. p->pEList->a[0].pExpr = pExpr;
  122363. p->selFlags &= ~SF_Aggregate;
  122364. #if SELECTTRACE_ENABLED
  122365. if( sqlite3SelectTrace & 0x400 ){
  122366. SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
  122367. sqlite3TreeViewSelect(0, p, 0);
  122368. }
  122369. #endif
  122370. return 1;
  122371. }
  122372. #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
  122373. /*
  122374. ** Generate code for the SELECT statement given in the p argument.
  122375. **
  122376. ** The results are returned according to the SelectDest structure.
  122377. ** See comments in sqliteInt.h for further information.
  122378. **
  122379. ** This routine returns the number of errors. If any errors are
  122380. ** encountered, then an appropriate error message is left in
  122381. ** pParse->zErrMsg.
  122382. **
  122383. ** This routine does NOT free the Select structure passed in. The
  122384. ** calling function needs to do that.
  122385. */
  122386. SQLITE_PRIVATE int sqlite3Select(
  122387. Parse *pParse, /* The parser context */
  122388. Select *p, /* The SELECT statement being coded. */
  122389. SelectDest *pDest /* What to do with the query results */
  122390. ){
  122391. int i, j; /* Loop counters */
  122392. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  122393. Vdbe *v; /* The virtual machine under construction */
  122394. int isAgg; /* True for select lists like "count(*)" */
  122395. ExprList *pEList = 0; /* List of columns to extract. */
  122396. SrcList *pTabList; /* List of tables to select from */
  122397. Expr *pWhere; /* The WHERE clause. May be NULL */
  122398. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  122399. Expr *pHaving; /* The HAVING clause. May be NULL */
  122400. int rc = 1; /* Value to return from this function */
  122401. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  122402. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  122403. AggInfo sAggInfo; /* Information used by aggregate queries */
  122404. int iEnd; /* Address of the end of the query */
  122405. sqlite3 *db; /* The database connection */
  122406. ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
  122407. u8 minMaxFlag; /* Flag for min/max queries */
  122408. db = pParse->db;
  122409. v = sqlite3GetVdbe(pParse);
  122410. if( p==0 || db->mallocFailed || pParse->nErr ){
  122411. return 1;
  122412. }
  122413. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  122414. memset(&sAggInfo, 0, sizeof(sAggInfo));
  122415. #if SELECTTRACE_ENABLED
  122416. SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
  122417. if( sqlite3SelectTrace & 0x100 ){
  122418. sqlite3TreeViewSelect(0, p, 0);
  122419. }
  122420. #endif
  122421. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  122422. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  122423. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  122424. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  122425. if( IgnorableOrderby(pDest) ){
  122426. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  122427. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  122428. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  122429. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  122430. /* If ORDER BY makes no difference in the output then neither does
  122431. ** DISTINCT so it can be removed too. */
  122432. sqlite3ExprListDelete(db, p->pOrderBy);
  122433. p->pOrderBy = 0;
  122434. p->selFlags &= ~SF_Distinct;
  122435. }
  122436. sqlite3SelectPrep(pParse, p, 0);
  122437. if( pParse->nErr || db->mallocFailed ){
  122438. goto select_end;
  122439. }
  122440. assert( p->pEList!=0 );
  122441. #if SELECTTRACE_ENABLED
  122442. if( sqlite3SelectTrace & 0x104 ){
  122443. SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
  122444. sqlite3TreeViewSelect(0, p, 0);
  122445. }
  122446. #endif
  122447. if( pDest->eDest==SRT_Output ){
  122448. generateColumnNames(pParse, p);
  122449. }
  122450. #ifndef SQLITE_OMIT_WINDOWFUNC
  122451. if( sqlite3WindowRewrite(pParse, p) ){
  122452. goto select_end;
  122453. }
  122454. #if SELECTTRACE_ENABLED
  122455. if( sqlite3SelectTrace & 0x108 ){
  122456. SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
  122457. sqlite3TreeViewSelect(0, p, 0);
  122458. }
  122459. #endif
  122460. #endif /* SQLITE_OMIT_WINDOWFUNC */
  122461. pTabList = p->pSrc;
  122462. isAgg = (p->selFlags & SF_Aggregate)!=0;
  122463. memset(&sSort, 0, sizeof(sSort));
  122464. sSort.pOrderBy = p->pOrderBy;
  122465. /* Try to various optimizations (flattening subqueries, and strength
  122466. ** reduction of join operators) in the FROM clause up into the main query
  122467. */
  122468. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  122469. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  122470. struct SrcList_item *pItem = &pTabList->a[i];
  122471. Select *pSub = pItem->pSelect;
  122472. Table *pTab = pItem->pTab;
  122473. /* Convert LEFT JOIN into JOIN if there are terms of the right table
  122474. ** of the LEFT JOIN used in the WHERE clause.
  122475. */
  122476. if( (pItem->fg.jointype & JT_LEFT)!=0
  122477. && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
  122478. && OptimizationEnabled(db, SQLITE_SimplifyJoin)
  122479. ){
  122480. SELECTTRACE(0x100,pParse,p,
  122481. ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
  122482. pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
  122483. unsetJoinExpr(p->pWhere, pItem->iCursor);
  122484. }
  122485. /* No futher action if this term of the FROM clause is no a subquery */
  122486. if( pSub==0 ) continue;
  122487. /* Catch mismatch in the declared columns of a view and the number of
  122488. ** columns in the SELECT on the RHS */
  122489. if( pTab->nCol!=pSub->pEList->nExpr ){
  122490. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  122491. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  122492. goto select_end;
  122493. }
  122494. /* Do not try to flatten an aggregate subquery.
  122495. **
  122496. ** Flattening an aggregate subquery is only possible if the outer query
  122497. ** is not a join. But if the outer query is not a join, then the subquery
  122498. ** will be implemented as a co-routine and there is no advantage to
  122499. ** flattening in that case.
  122500. */
  122501. if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
  122502. assert( pSub->pGroupBy==0 );
  122503. /* If the outer query contains a "complex" result set (that is,
  122504. ** if the result set of the outer query uses functions or subqueries)
  122505. ** and if the subquery contains an ORDER BY clause and if
  122506. ** it will be implemented as a co-routine, then do not flatten. This
  122507. ** restriction allows SQL constructs like this:
  122508. **
  122509. ** SELECT expensive_function(x)
  122510. ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  122511. **
  122512. ** The expensive_function() is only computed on the 10 rows that
  122513. ** are output, rather than every row of the table.
  122514. **
  122515. ** The requirement that the outer query have a complex result set
  122516. ** means that flattening does occur on simpler SQL constraints without
  122517. ** the expensive_function() like:
  122518. **
  122519. ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  122520. */
  122521. if( pSub->pOrderBy!=0
  122522. && i==0
  122523. && (p->selFlags & SF_ComplexResult)!=0
  122524. && (pTabList->nSrc==1
  122525. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
  122526. ){
  122527. continue;
  122528. }
  122529. if( flattenSubquery(pParse, p, i, isAgg) ){
  122530. if( pParse->nErr ) goto select_end;
  122531. /* This subquery can be absorbed into its parent. */
  122532. i = -1;
  122533. }
  122534. pTabList = p->pSrc;
  122535. if( db->mallocFailed ) goto select_end;
  122536. if( !IgnorableOrderby(pDest) ){
  122537. sSort.pOrderBy = p->pOrderBy;
  122538. }
  122539. }
  122540. #endif
  122541. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  122542. /* Handle compound SELECT statements using the separate multiSelect()
  122543. ** procedure.
  122544. */
  122545. if( p->pPrior ){
  122546. rc = multiSelect(pParse, p, pDest);
  122547. #if SELECTTRACE_ENABLED
  122548. SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
  122549. if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
  122550. sqlite3TreeViewSelect(0, p, 0);
  122551. }
  122552. #endif
  122553. if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
  122554. return rc;
  122555. }
  122556. #endif
  122557. /* Do the WHERE-clause constant propagation optimization if this is
  122558. ** a join. No need to speed time on this operation for non-join queries
  122559. ** as the equivalent optimization will be handled by query planner in
  122560. ** sqlite3WhereBegin().
  122561. */
  122562. if( pTabList->nSrc>1
  122563. && OptimizationEnabled(db, SQLITE_PropagateConst)
  122564. && propagateConstants(pParse, p)
  122565. ){
  122566. #if SELECTTRACE_ENABLED
  122567. if( sqlite3SelectTrace & 0x100 ){
  122568. SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
  122569. sqlite3TreeViewSelect(0, p, 0);
  122570. }
  122571. #endif
  122572. }else{
  122573. SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n"));
  122574. }
  122575. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  122576. if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
  122577. && countOfViewOptimization(pParse, p)
  122578. ){
  122579. if( db->mallocFailed ) goto select_end;
  122580. pEList = p->pEList;
  122581. pTabList = p->pSrc;
  122582. }
  122583. #endif
  122584. /* For each term in the FROM clause, do two things:
  122585. ** (1) Authorized unreferenced tables
  122586. ** (2) Generate code for all sub-queries
  122587. */
  122588. for(i=0; i<pTabList->nSrc; i++){
  122589. struct SrcList_item *pItem = &pTabList->a[i];
  122590. SelectDest dest;
  122591. Select *pSub;
  122592. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  122593. const char *zSavedAuthContext;
  122594. #endif
  122595. /* Issue SQLITE_READ authorizations with a fake column name for any
  122596. ** tables that are referenced but from which no values are extracted.
  122597. ** Examples of where these kinds of null SQLITE_READ authorizations
  122598. ** would occur:
  122599. **
  122600. ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
  122601. ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
  122602. **
  122603. ** The fake column name is an empty string. It is possible for a table to
  122604. ** have a column named by the empty string, in which case there is no way to
  122605. ** distinguish between an unreferenced table and an actual reference to the
  122606. ** "" column. The original design was for the fake column name to be a NULL,
  122607. ** which would be unambiguous. But legacy authorization callbacks might
  122608. ** assume the column name is non-NULL and segfault. The use of an empty
  122609. ** string for the fake column name seems safer.
  122610. */
  122611. if( pItem->colUsed==0 ){
  122612. sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
  122613. }
  122614. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  122615. /* Generate code for all sub-queries in the FROM clause
  122616. */
  122617. pSub = pItem->pSelect;
  122618. if( pSub==0 ) continue;
  122619. /* The code for a subquery should only be generated once, though it is
  122620. ** technically harmless for it to be generated multiple times. The
  122621. ** following assert() will detect if something changes to cause
  122622. ** the same subquery to be coded multiple times, as a signal to the
  122623. ** developers to try to optimize the situation. */
  122624. assert( pItem->addrFillSub==0 );
  122625. /* Increment Parse.nHeight by the height of the largest expression
  122626. ** tree referred to by this, the parent select. The child select
  122627. ** may contain expression trees of at most
  122628. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  122629. ** more conservative than necessary, but much easier than enforcing
  122630. ** an exact limit.
  122631. */
  122632. pParse->nHeight += sqlite3SelectExprHeight(p);
  122633. /* Make copies of constant WHERE-clause terms in the outer query down
  122634. ** inside the subquery. This can help the subquery to run more efficiently.
  122635. */
  122636. if( OptimizationEnabled(db, SQLITE_PushDown)
  122637. && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
  122638. (pItem->fg.jointype & JT_OUTER)!=0)
  122639. ){
  122640. #if SELECTTRACE_ENABLED
  122641. if( sqlite3SelectTrace & 0x100 ){
  122642. SELECTTRACE(0x100,pParse,p,
  122643. ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
  122644. sqlite3TreeViewSelect(0, p, 0);
  122645. }
  122646. #endif
  122647. }else{
  122648. SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
  122649. }
  122650. zSavedAuthContext = pParse->zAuthContext;
  122651. pParse->zAuthContext = pItem->zName;
  122652. /* Generate code to implement the subquery
  122653. **
  122654. ** The subquery is implemented as a co-routine if the subquery is
  122655. ** guaranteed to be the outer loop (so that it does not need to be
  122656. ** computed more than once)
  122657. **
  122658. ** TODO: Are there other reasons beside (1) to use a co-routine
  122659. ** implementation?
  122660. */
  122661. if( i==0
  122662. && (pTabList->nSrc==1
  122663. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
  122664. ){
  122665. /* Implement a co-routine that will return a single row of the result
  122666. ** set on each invocation.
  122667. */
  122668. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  122669. pItem->regReturn = ++pParse->nMem;
  122670. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  122671. VdbeComment((v, "%s", pItem->pTab->zName));
  122672. pItem->addrFillSub = addrTop;
  122673. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  122674. ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId));
  122675. sqlite3Select(pParse, pSub, &dest);
  122676. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  122677. pItem->fg.viaCoroutine = 1;
  122678. pItem->regResult = dest.iSdst;
  122679. sqlite3VdbeEndCoroutine(v, pItem->regReturn);
  122680. sqlite3VdbeJumpHere(v, addrTop-1);
  122681. sqlite3ClearTempRegCache(pParse);
  122682. }else{
  122683. /* Generate a subroutine that will fill an ephemeral table with
  122684. ** the content of this subquery. pItem->addrFillSub will point
  122685. ** to the address of the generated subroutine. pItem->regReturn
  122686. ** is a register allocated to hold the subroutine return address
  122687. */
  122688. int topAddr;
  122689. int onceAddr = 0;
  122690. int retAddr;
  122691. struct SrcList_item *pPrior;
  122692. assert( pItem->addrFillSub==0 );
  122693. pItem->regReturn = ++pParse->nMem;
  122694. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  122695. pItem->addrFillSub = topAddr+1;
  122696. if( pItem->fg.isCorrelated==0 ){
  122697. /* If the subquery is not correlated and if we are not inside of
  122698. ** a trigger, then we only need to compute the value of the subquery
  122699. ** once. */
  122700. onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  122701. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  122702. }else{
  122703. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  122704. }
  122705. pPrior = isSelfJoinView(pTabList, pItem);
  122706. if( pPrior ){
  122707. sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
  122708. assert( pPrior->pSelect!=0 );
  122709. pSub->nSelectRow = pPrior->pSelect->nSelectRow;
  122710. }else{
  122711. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  122712. ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
  122713. sqlite3Select(pParse, pSub, &dest);
  122714. }
  122715. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  122716. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  122717. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  122718. VdbeComment((v, "end %s", pItem->pTab->zName));
  122719. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  122720. sqlite3ClearTempRegCache(pParse);
  122721. }
  122722. if( db->mallocFailed ) goto select_end;
  122723. pParse->nHeight -= sqlite3SelectExprHeight(p);
  122724. pParse->zAuthContext = zSavedAuthContext;
  122725. #endif
  122726. }
  122727. /* Various elements of the SELECT copied into local variables for
  122728. ** convenience */
  122729. pEList = p->pEList;
  122730. pWhere = p->pWhere;
  122731. pGroupBy = p->pGroupBy;
  122732. pHaving = p->pHaving;
  122733. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  122734. #if SELECTTRACE_ENABLED
  122735. if( sqlite3SelectTrace & 0x400 ){
  122736. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  122737. sqlite3TreeViewSelect(0, p, 0);
  122738. }
  122739. #endif
  122740. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  122741. ** if the select-list is the same as the ORDER BY list, then this query
  122742. ** can be rewritten as a GROUP BY. In other words, this:
  122743. **
  122744. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  122745. **
  122746. ** is transformed to:
  122747. **
  122748. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  122749. **
  122750. ** The second form is preferred as a single index (or temp-table) may be
  122751. ** used for both the ORDER BY and DISTINCT processing. As originally
  122752. ** written the query must use a temp-table for at least one of the ORDER
  122753. ** BY and DISTINCT, and an index or separate temp-table for the other.
  122754. */
  122755. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  122756. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  122757. ){
  122758. p->selFlags &= ~SF_Distinct;
  122759. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  122760. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  122761. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  122762. ** original setting of the SF_Distinct flag, not the current setting */
  122763. assert( sDistinct.isTnct );
  122764. #if SELECTTRACE_ENABLED
  122765. if( sqlite3SelectTrace & 0x400 ){
  122766. SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
  122767. sqlite3TreeViewSelect(0, p, 0);
  122768. }
  122769. #endif
  122770. }
  122771. /* If there is an ORDER BY clause, then create an ephemeral index to
  122772. ** do the sorting. But this sorting ephemeral index might end up
  122773. ** being unused if the data can be extracted in pre-sorted order.
  122774. ** If that is the case, then the OP_OpenEphemeral instruction will be
  122775. ** changed to an OP_Noop once we figure out that the sorting index is
  122776. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  122777. ** that change.
  122778. */
  122779. if( sSort.pOrderBy ){
  122780. KeyInfo *pKeyInfo;
  122781. pKeyInfo = sqlite3KeyInfoFromExprList(
  122782. pParse, sSort.pOrderBy, 0, pEList->nExpr);
  122783. sSort.iECursor = pParse->nTab++;
  122784. sSort.addrSortIndex =
  122785. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  122786. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  122787. (char*)pKeyInfo, P4_KEYINFO
  122788. );
  122789. }else{
  122790. sSort.addrSortIndex = -1;
  122791. }
  122792. /* If the output is destined for a temporary table, open that table.
  122793. */
  122794. if( pDest->eDest==SRT_EphemTab ){
  122795. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  122796. }
  122797. /* Set the limiter.
  122798. */
  122799. iEnd = sqlite3VdbeMakeLabel(pParse);
  122800. if( (p->selFlags & SF_FixedLimit)==0 ){
  122801. p->nSelectRow = 320; /* 4 billion rows */
  122802. }
  122803. computeLimitRegisters(pParse, p, iEnd);
  122804. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  122805. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  122806. sSort.sortFlags |= SORTFLAG_UseSorter;
  122807. }
  122808. /* Open an ephemeral index to use for the distinct set.
  122809. */
  122810. if( p->selFlags & SF_Distinct ){
  122811. sDistinct.tabTnct = pParse->nTab++;
  122812. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  122813. sDistinct.tabTnct, 0, 0,
  122814. (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
  122815. P4_KEYINFO);
  122816. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  122817. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  122818. }else{
  122819. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  122820. }
  122821. if( !isAgg && pGroupBy==0 ){
  122822. /* No aggregate functions and no GROUP BY clause */
  122823. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
  122824. | (p->selFlags & SF_FixedLimit);
  122825. #ifndef SQLITE_OMIT_WINDOWFUNC
  122826. Window *pWin = p->pWin; /* Master window object (or NULL) */
  122827. if( pWin ){
  122828. sqlite3WindowCodeInit(pParse, pWin);
  122829. }
  122830. #endif
  122831. assert( WHERE_USE_LIMIT==SF_FixedLimit );
  122832. /* Begin the database scan. */
  122833. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  122834. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  122835. p->pEList, wctrlFlags, p->nSelectRow);
  122836. if( pWInfo==0 ) goto select_end;
  122837. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  122838. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  122839. }
  122840. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  122841. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  122842. }
  122843. if( sSort.pOrderBy ){
  122844. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  122845. sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
  122846. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  122847. sSort.pOrderBy = 0;
  122848. }
  122849. }
  122850. /* If sorting index that was created by a prior OP_OpenEphemeral
  122851. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  122852. ** into an OP_Noop.
  122853. */
  122854. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  122855. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  122856. }
  122857. assert( p->pEList==pEList );
  122858. #ifndef SQLITE_OMIT_WINDOWFUNC
  122859. if( pWin ){
  122860. int addrGosub = sqlite3VdbeMakeLabel(pParse);
  122861. int iCont = sqlite3VdbeMakeLabel(pParse);
  122862. int iBreak = sqlite3VdbeMakeLabel(pParse);
  122863. int regGosub = ++pParse->nMem;
  122864. sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
  122865. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  122866. sqlite3VdbeResolveLabel(v, addrGosub);
  122867. VdbeNoopComment((v, "inner-loop subroutine"));
  122868. sSort.labelOBLopt = 0;
  122869. selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
  122870. sqlite3VdbeResolveLabel(v, iCont);
  122871. sqlite3VdbeAddOp1(v, OP_Return, regGosub);
  122872. VdbeComment((v, "end inner-loop subroutine"));
  122873. sqlite3VdbeResolveLabel(v, iBreak);
  122874. }else
  122875. #endif /* SQLITE_OMIT_WINDOWFUNC */
  122876. {
  122877. /* Use the standard inner loop. */
  122878. selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
  122879. sqlite3WhereContinueLabel(pWInfo),
  122880. sqlite3WhereBreakLabel(pWInfo));
  122881. /* End the database scan loop.
  122882. */
  122883. sqlite3WhereEnd(pWInfo);
  122884. }
  122885. }else{
  122886. /* This case when there exist aggregate functions or a GROUP BY clause
  122887. ** or both */
  122888. NameContext sNC; /* Name context for processing aggregate information */
  122889. int iAMem; /* First Mem address for storing current GROUP BY */
  122890. int iBMem; /* First Mem address for previous GROUP BY */
  122891. int iUseFlag; /* Mem address holding flag indicating that at least
  122892. ** one row of the input to the aggregator has been
  122893. ** processed */
  122894. int iAbortFlag; /* Mem address which causes query abort if positive */
  122895. int groupBySort; /* Rows come from source in GROUP BY order */
  122896. int addrEnd; /* End of processing for this SELECT */
  122897. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  122898. int sortOut = 0; /* Output register from the sorter */
  122899. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  122900. /* Remove any and all aliases between the result set and the
  122901. ** GROUP BY clause.
  122902. */
  122903. if( pGroupBy ){
  122904. int k; /* Loop counter */
  122905. struct ExprList_item *pItem; /* For looping over expression in a list */
  122906. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  122907. pItem->u.x.iAlias = 0;
  122908. }
  122909. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  122910. pItem->u.x.iAlias = 0;
  122911. }
  122912. assert( 66==sqlite3LogEst(100) );
  122913. if( p->nSelectRow>66 ) p->nSelectRow = 66;
  122914. }else{
  122915. assert( 0==sqlite3LogEst(1) );
  122916. p->nSelectRow = 0;
  122917. }
  122918. /* If there is both a GROUP BY and an ORDER BY clause and they are
  122919. ** identical, then it may be possible to disable the ORDER BY clause
  122920. ** on the grounds that the GROUP BY will cause elements to come out
  122921. ** in the correct order. It also may not - the GROUP BY might use a
  122922. ** database index that causes rows to be grouped together as required
  122923. ** but not actually sorted. Either way, record the fact that the
  122924. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  122925. ** variable. */
  122926. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  122927. orderByGrp = 1;
  122928. }
  122929. /* Create a label to jump to when we want to abort the query */
  122930. addrEnd = sqlite3VdbeMakeLabel(pParse);
  122931. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  122932. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  122933. ** SELECT statement.
  122934. */
  122935. memset(&sNC, 0, sizeof(sNC));
  122936. sNC.pParse = pParse;
  122937. sNC.pSrcList = pTabList;
  122938. sNC.uNC.pAggInfo = &sAggInfo;
  122939. VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
  122940. sAggInfo.mnReg = pParse->nMem+1;
  122941. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  122942. sAggInfo.pGroupBy = pGroupBy;
  122943. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  122944. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  122945. if( pHaving ){
  122946. if( pGroupBy ){
  122947. assert( pWhere==p->pWhere );
  122948. assert( pHaving==p->pHaving );
  122949. assert( pGroupBy==p->pGroupBy );
  122950. havingToWhere(pParse, p);
  122951. pWhere = p->pWhere;
  122952. }
  122953. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  122954. }
  122955. sAggInfo.nAccumulator = sAggInfo.nColumn;
  122956. if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
  122957. minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
  122958. }else{
  122959. minMaxFlag = WHERE_ORDERBY_NORMAL;
  122960. }
  122961. for(i=0; i<sAggInfo.nFunc; i++){
  122962. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  122963. sNC.ncFlags |= NC_InAggFunc;
  122964. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  122965. sNC.ncFlags &= ~NC_InAggFunc;
  122966. }
  122967. sAggInfo.mxReg = pParse->nMem;
  122968. if( db->mallocFailed ) goto select_end;
  122969. #if SELECTTRACE_ENABLED
  122970. if( sqlite3SelectTrace & 0x400 ){
  122971. int ii;
  122972. SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n"));
  122973. sqlite3TreeViewSelect(0, p, 0);
  122974. for(ii=0; ii<sAggInfo.nColumn; ii++){
  122975. sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
  122976. ii, sAggInfo.aCol[ii].iMem);
  122977. sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
  122978. }
  122979. for(ii=0; ii<sAggInfo.nFunc; ii++){
  122980. sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
  122981. ii, sAggInfo.aFunc[ii].iMem);
  122982. sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
  122983. }
  122984. }
  122985. #endif
  122986. /* Processing for aggregates with GROUP BY is very different and
  122987. ** much more complex than aggregates without a GROUP BY.
  122988. */
  122989. if( pGroupBy ){
  122990. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  122991. int addr1; /* A-vs-B comparision jump */
  122992. int addrOutputRow; /* Start of subroutine that outputs a result row */
  122993. int regOutputRow; /* Return address register for output subroutine */
  122994. int addrSetAbort; /* Set the abort flag and return */
  122995. int addrTopOfLoop; /* Top of the input loop */
  122996. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  122997. int addrReset; /* Subroutine for resetting the accumulator */
  122998. int regReset; /* Return address register for reset subroutine */
  122999. /* If there is a GROUP BY clause we might need a sorting index to
  123000. ** implement it. Allocate that sorting index now. If it turns out
  123001. ** that we do not need it after all, the OP_SorterOpen instruction
  123002. ** will be converted into a Noop.
  123003. */
  123004. sAggInfo.sortingIdx = pParse->nTab++;
  123005. pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn);
  123006. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  123007. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  123008. 0, (char*)pKeyInfo, P4_KEYINFO);
  123009. /* Initialize memory locations used by GROUP BY aggregate processing
  123010. */
  123011. iUseFlag = ++pParse->nMem;
  123012. iAbortFlag = ++pParse->nMem;
  123013. regOutputRow = ++pParse->nMem;
  123014. addrOutputRow = sqlite3VdbeMakeLabel(pParse);
  123015. regReset = ++pParse->nMem;
  123016. addrReset = sqlite3VdbeMakeLabel(pParse);
  123017. iAMem = pParse->nMem + 1;
  123018. pParse->nMem += pGroupBy->nExpr;
  123019. iBMem = pParse->nMem + 1;
  123020. pParse->nMem += pGroupBy->nExpr;
  123021. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  123022. VdbeComment((v, "clear abort flag"));
  123023. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  123024. /* Begin a loop that will extract all source rows in GROUP BY order.
  123025. ** This might involve two separate loops with an OP_Sort in between, or
  123026. ** it might be a single loop that uses an index to extract information
  123027. ** in the right order to begin with.
  123028. */
  123029. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  123030. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  123031. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  123032. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  123033. );
  123034. if( pWInfo==0 ) goto select_end;
  123035. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  123036. /* The optimizer is able to deliver rows in group by order so
  123037. ** we do not have to sort. The OP_OpenEphemeral table will be
  123038. ** cancelled later because we still need to use the pKeyInfo
  123039. */
  123040. groupBySort = 0;
  123041. }else{
  123042. /* Rows are coming out in undetermined order. We have to push
  123043. ** each row into a sorting index, terminate the first loop,
  123044. ** then loop over the sorting index in order to get the output
  123045. ** in sorted order
  123046. */
  123047. int regBase;
  123048. int regRecord;
  123049. int nCol;
  123050. int nGroupBy;
  123051. explainTempTable(pParse,
  123052. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  123053. "DISTINCT" : "GROUP BY");
  123054. groupBySort = 1;
  123055. nGroupBy = pGroupBy->nExpr;
  123056. nCol = nGroupBy;
  123057. j = nGroupBy;
  123058. for(i=0; i<sAggInfo.nColumn; i++){
  123059. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  123060. nCol++;
  123061. j++;
  123062. }
  123063. }
  123064. regBase = sqlite3GetTempRange(pParse, nCol);
  123065. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  123066. j = nGroupBy;
  123067. for(i=0; i<sAggInfo.nColumn; i++){
  123068. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  123069. if( pCol->iSorterColumn>=j ){
  123070. int r1 = j + regBase;
  123071. sqlite3ExprCodeGetColumnOfTable(v,
  123072. pCol->pTab, pCol->iTable, pCol->iColumn, r1);
  123073. j++;
  123074. }
  123075. }
  123076. regRecord = sqlite3GetTempReg(pParse);
  123077. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  123078. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  123079. sqlite3ReleaseTempReg(pParse, regRecord);
  123080. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  123081. sqlite3WhereEnd(pWInfo);
  123082. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  123083. sortOut = sqlite3GetTempReg(pParse);
  123084. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  123085. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  123086. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  123087. sAggInfo.useSortingIdx = 1;
  123088. }
  123089. /* If the index or temporary table used by the GROUP BY sort
  123090. ** will naturally deliver rows in the order required by the ORDER BY
  123091. ** clause, cancel the ephemeral table open coded earlier.
  123092. **
  123093. ** This is an optimization - the correct answer should result regardless.
  123094. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  123095. ** disable this optimization for testing purposes. */
  123096. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  123097. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  123098. ){
  123099. sSort.pOrderBy = 0;
  123100. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  123101. }
  123102. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  123103. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  123104. ** Then compare the current GROUP BY terms against the GROUP BY terms
  123105. ** from the previous row currently stored in a0, a1, a2...
  123106. */
  123107. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  123108. if( groupBySort ){
  123109. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  123110. sortOut, sortPTab);
  123111. }
  123112. for(j=0; j<pGroupBy->nExpr; j++){
  123113. if( groupBySort ){
  123114. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  123115. }else{
  123116. sAggInfo.directMode = 1;
  123117. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  123118. }
  123119. }
  123120. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  123121. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  123122. addr1 = sqlite3VdbeCurrentAddr(v);
  123123. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  123124. /* Generate code that runs whenever the GROUP BY changes.
  123125. ** Changes in the GROUP BY are detected by the previous code
  123126. ** block. If there were no changes, this block is skipped.
  123127. **
  123128. ** This code copies current group by terms in b0,b1,b2,...
  123129. ** over to a0,a1,a2. It then calls the output subroutine
  123130. ** and resets the aggregate accumulator registers in preparation
  123131. ** for the next GROUP BY batch.
  123132. */
  123133. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  123134. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  123135. VdbeComment((v, "output one row"));
  123136. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  123137. VdbeComment((v, "check abort flag"));
  123138. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  123139. VdbeComment((v, "reset accumulator"));
  123140. /* Update the aggregate accumulators based on the content of
  123141. ** the current row
  123142. */
  123143. sqlite3VdbeJumpHere(v, addr1);
  123144. updateAccumulator(pParse, iUseFlag, &sAggInfo);
  123145. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  123146. VdbeComment((v, "indicate data in accumulator"));
  123147. /* End of the loop
  123148. */
  123149. if( groupBySort ){
  123150. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  123151. VdbeCoverage(v);
  123152. }else{
  123153. sqlite3WhereEnd(pWInfo);
  123154. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  123155. }
  123156. /* Output the final row of result
  123157. */
  123158. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  123159. VdbeComment((v, "output final row"));
  123160. /* Jump over the subroutines
  123161. */
  123162. sqlite3VdbeGoto(v, addrEnd);
  123163. /* Generate a subroutine that outputs a single row of the result
  123164. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  123165. ** is less than or equal to zero, the subroutine is a no-op. If
  123166. ** the processing calls for the query to abort, this subroutine
  123167. ** increments the iAbortFlag memory location before returning in
  123168. ** order to signal the caller to abort.
  123169. */
  123170. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  123171. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  123172. VdbeComment((v, "set abort flag"));
  123173. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  123174. sqlite3VdbeResolveLabel(v, addrOutputRow);
  123175. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  123176. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  123177. VdbeCoverage(v);
  123178. VdbeComment((v, "Groupby result generator entry point"));
  123179. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  123180. finalizeAggFunctions(pParse, &sAggInfo);
  123181. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  123182. selectInnerLoop(pParse, p, -1, &sSort,
  123183. &sDistinct, pDest,
  123184. addrOutputRow+1, addrSetAbort);
  123185. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  123186. VdbeComment((v, "end groupby result generator"));
  123187. /* Generate a subroutine that will reset the group-by accumulator
  123188. */
  123189. sqlite3VdbeResolveLabel(v, addrReset);
  123190. resetAccumulator(pParse, &sAggInfo);
  123191. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  123192. VdbeComment((v, "indicate accumulator empty"));
  123193. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  123194. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  123195. else {
  123196. #ifndef SQLITE_OMIT_BTREECOUNT
  123197. Table *pTab;
  123198. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  123199. /* If isSimpleCount() returns a pointer to a Table structure, then
  123200. ** the SQL statement is of the form:
  123201. **
  123202. ** SELECT count(*) FROM <tbl>
  123203. **
  123204. ** where the Table structure returned represents table <tbl>.
  123205. **
  123206. ** This statement is so common that it is optimized specially. The
  123207. ** OP_Count instruction is executed either on the intkey table that
  123208. ** contains the data for table <tbl> or on one of its indexes. It
  123209. ** is better to execute the op on an index, as indexes are almost
  123210. ** always spread across less pages than their corresponding tables.
  123211. */
  123212. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  123213. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  123214. Index *pIdx; /* Iterator variable */
  123215. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  123216. Index *pBest = 0; /* Best index found so far */
  123217. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  123218. sqlite3CodeVerifySchema(pParse, iDb);
  123219. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  123220. /* Search for the index that has the lowest scan cost.
  123221. **
  123222. ** (2011-04-15) Do not do a full scan of an unordered index.
  123223. **
  123224. ** (2013-10-03) Do not count the entries in a partial index.
  123225. **
  123226. ** In practice the KeyInfo structure will not be used. It is only
  123227. ** passed to keep OP_OpenRead happy.
  123228. */
  123229. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  123230. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  123231. if( pIdx->bUnordered==0
  123232. && pIdx->szIdxRow<pTab->szTabRow
  123233. && pIdx->pPartIdxWhere==0
  123234. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  123235. ){
  123236. pBest = pIdx;
  123237. }
  123238. }
  123239. if( pBest ){
  123240. iRoot = pBest->tnum;
  123241. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  123242. }
  123243. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  123244. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  123245. if( pKeyInfo ){
  123246. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  123247. }
  123248. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  123249. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  123250. explainSimpleCount(pParse, pTab, pBest);
  123251. }else
  123252. #endif /* SQLITE_OMIT_BTREECOUNT */
  123253. {
  123254. int regAcc = 0; /* "populate accumulators" flag */
  123255. /* If there are accumulator registers but no min() or max() functions,
  123256. ** allocate register regAcc. Register regAcc will contain 0 the first
  123257. ** time the inner loop runs, and 1 thereafter. The code generated
  123258. ** by updateAccumulator() only updates the accumulator registers if
  123259. ** regAcc contains 0. */
  123260. if( sAggInfo.nAccumulator ){
  123261. for(i=0; i<sAggInfo.nFunc; i++){
  123262. if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break;
  123263. }
  123264. if( i==sAggInfo.nFunc ){
  123265. regAcc = ++pParse->nMem;
  123266. sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
  123267. }
  123268. }
  123269. /* This case runs if the aggregate has no GROUP BY clause. The
  123270. ** processing is much simpler since there is only a single row
  123271. ** of output.
  123272. */
  123273. assert( p->pGroupBy==0 );
  123274. resetAccumulator(pParse, &sAggInfo);
  123275. /* If this query is a candidate for the min/max optimization, then
  123276. ** minMaxFlag will have been previously set to either
  123277. ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
  123278. ** be an appropriate ORDER BY expression for the optimization.
  123279. */
  123280. assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
  123281. assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
  123282. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  123283. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
  123284. 0, minMaxFlag, 0);
  123285. if( pWInfo==0 ){
  123286. goto select_end;
  123287. }
  123288. updateAccumulator(pParse, regAcc, &sAggInfo);
  123289. if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
  123290. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  123291. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  123292. VdbeComment((v, "%s() by index",
  123293. (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
  123294. }
  123295. sqlite3WhereEnd(pWInfo);
  123296. finalizeAggFunctions(pParse, &sAggInfo);
  123297. }
  123298. sSort.pOrderBy = 0;
  123299. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  123300. selectInnerLoop(pParse, p, -1, 0, 0,
  123301. pDest, addrEnd, addrEnd);
  123302. }
  123303. sqlite3VdbeResolveLabel(v, addrEnd);
  123304. } /* endif aggregate query */
  123305. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  123306. explainTempTable(pParse, "DISTINCT");
  123307. }
  123308. /* If there is an ORDER BY clause, then we need to sort the results
  123309. ** and send them to the callback one by one.
  123310. */
  123311. if( sSort.pOrderBy ){
  123312. explainTempTable(pParse,
  123313. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  123314. assert( p->pEList==pEList );
  123315. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  123316. }
  123317. /* Jump here to skip this query
  123318. */
  123319. sqlite3VdbeResolveLabel(v, iEnd);
  123320. /* The SELECT has been coded. If there is an error in the Parse structure,
  123321. ** set the return code to 1. Otherwise 0. */
  123322. rc = (pParse->nErr>0);
  123323. /* Control jumps to here if an error is encountered above, or upon
  123324. ** successful coding of the SELECT.
  123325. */
  123326. select_end:
  123327. sqlite3ExprListDelete(db, pMinMaxOrderBy);
  123328. sqlite3DbFree(db, sAggInfo.aCol);
  123329. sqlite3DbFree(db, sAggInfo.aFunc);
  123330. #if SELECTTRACE_ENABLED
  123331. SELECTTRACE(0x1,pParse,p,("end processing\n"));
  123332. if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
  123333. sqlite3TreeViewSelect(0, p, 0);
  123334. }
  123335. #endif
  123336. ExplainQueryPlanPop(pParse);
  123337. return rc;
  123338. }
  123339. /************** End of select.c **********************************************/
  123340. /************** Begin file table.c *******************************************/
  123341. /*
  123342. ** 2001 September 15
  123343. **
  123344. ** The author disclaims copyright to this source code. In place of
  123345. ** a legal notice, here is a blessing:
  123346. **
  123347. ** May you do good and not evil.
  123348. ** May you find forgiveness for yourself and forgive others.
  123349. ** May you share freely, never taking more than you give.
  123350. **
  123351. *************************************************************************
  123352. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  123353. ** interface routines. These are just wrappers around the main
  123354. ** interface routine of sqlite3_exec().
  123355. **
  123356. ** These routines are in a separate files so that they will not be linked
  123357. ** if they are not used.
  123358. */
  123359. /* #include "sqliteInt.h" */
  123360. #ifndef SQLITE_OMIT_GET_TABLE
  123361. /*
  123362. ** This structure is used to pass data from sqlite3_get_table() through
  123363. ** to the callback function is uses to build the result.
  123364. */
  123365. typedef struct TabResult {
  123366. char **azResult; /* Accumulated output */
  123367. char *zErrMsg; /* Error message text, if an error occurs */
  123368. u32 nAlloc; /* Slots allocated for azResult[] */
  123369. u32 nRow; /* Number of rows in the result */
  123370. u32 nColumn; /* Number of columns in the result */
  123371. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  123372. int rc; /* Return code from sqlite3_exec() */
  123373. } TabResult;
  123374. /*
  123375. ** This routine is called once for each row in the result table. Its job
  123376. ** is to fill in the TabResult structure appropriately, allocating new
  123377. ** memory as necessary.
  123378. */
  123379. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  123380. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  123381. int need; /* Slots needed in p->azResult[] */
  123382. int i; /* Loop counter */
  123383. char *z; /* A single column of result */
  123384. /* Make sure there is enough space in p->azResult to hold everything
  123385. ** we need to remember from this invocation of the callback.
  123386. */
  123387. if( p->nRow==0 && argv!=0 ){
  123388. need = nCol*2;
  123389. }else{
  123390. need = nCol;
  123391. }
  123392. if( p->nData + need > p->nAlloc ){
  123393. char **azNew;
  123394. p->nAlloc = p->nAlloc*2 + need;
  123395. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  123396. if( azNew==0 ) goto malloc_failed;
  123397. p->azResult = azNew;
  123398. }
  123399. /* If this is the first row, then generate an extra row containing
  123400. ** the names of all columns.
  123401. */
  123402. if( p->nRow==0 ){
  123403. p->nColumn = nCol;
  123404. for(i=0; i<nCol; i++){
  123405. z = sqlite3_mprintf("%s", colv[i]);
  123406. if( z==0 ) goto malloc_failed;
  123407. p->azResult[p->nData++] = z;
  123408. }
  123409. }else if( (int)p->nColumn!=nCol ){
  123410. sqlite3_free(p->zErrMsg);
  123411. p->zErrMsg = sqlite3_mprintf(
  123412. "sqlite3_get_table() called with two or more incompatible queries"
  123413. );
  123414. p->rc = SQLITE_ERROR;
  123415. return 1;
  123416. }
  123417. /* Copy over the row data
  123418. */
  123419. if( argv!=0 ){
  123420. for(i=0; i<nCol; i++){
  123421. if( argv[i]==0 ){
  123422. z = 0;
  123423. }else{
  123424. int n = sqlite3Strlen30(argv[i])+1;
  123425. z = sqlite3_malloc64( n );
  123426. if( z==0 ) goto malloc_failed;
  123427. memcpy(z, argv[i], n);
  123428. }
  123429. p->azResult[p->nData++] = z;
  123430. }
  123431. p->nRow++;
  123432. }
  123433. return 0;
  123434. malloc_failed:
  123435. p->rc = SQLITE_NOMEM_BKPT;
  123436. return 1;
  123437. }
  123438. /*
  123439. ** Query the database. But instead of invoking a callback for each row,
  123440. ** malloc() for space to hold the result and return the entire results
  123441. ** at the conclusion of the call.
  123442. **
  123443. ** The result that is written to ***pazResult is held in memory obtained
  123444. ** from malloc(). But the caller cannot free this memory directly.
  123445. ** Instead, the entire table should be passed to sqlite3_free_table() when
  123446. ** the calling procedure is finished using it.
  123447. */
  123448. SQLITE_API int sqlite3_get_table(
  123449. sqlite3 *db, /* The database on which the SQL executes */
  123450. const char *zSql, /* The SQL to be executed */
  123451. char ***pazResult, /* Write the result table here */
  123452. int *pnRow, /* Write the number of rows in the result here */
  123453. int *pnColumn, /* Write the number of columns of result here */
  123454. char **pzErrMsg /* Write error messages here */
  123455. ){
  123456. int rc;
  123457. TabResult res;
  123458. #ifdef SQLITE_ENABLE_API_ARMOR
  123459. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  123460. #endif
  123461. *pazResult = 0;
  123462. if( pnColumn ) *pnColumn = 0;
  123463. if( pnRow ) *pnRow = 0;
  123464. if( pzErrMsg ) *pzErrMsg = 0;
  123465. res.zErrMsg = 0;
  123466. res.nRow = 0;
  123467. res.nColumn = 0;
  123468. res.nData = 1;
  123469. res.nAlloc = 20;
  123470. res.rc = SQLITE_OK;
  123471. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  123472. if( res.azResult==0 ){
  123473. db->errCode = SQLITE_NOMEM;
  123474. return SQLITE_NOMEM_BKPT;
  123475. }
  123476. res.azResult[0] = 0;
  123477. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  123478. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  123479. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  123480. if( (rc&0xff)==SQLITE_ABORT ){
  123481. sqlite3_free_table(&res.azResult[1]);
  123482. if( res.zErrMsg ){
  123483. if( pzErrMsg ){
  123484. sqlite3_free(*pzErrMsg);
  123485. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  123486. }
  123487. sqlite3_free(res.zErrMsg);
  123488. }
  123489. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  123490. return res.rc;
  123491. }
  123492. sqlite3_free(res.zErrMsg);
  123493. if( rc!=SQLITE_OK ){
  123494. sqlite3_free_table(&res.azResult[1]);
  123495. return rc;
  123496. }
  123497. if( res.nAlloc>res.nData ){
  123498. char **azNew;
  123499. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  123500. if( azNew==0 ){
  123501. sqlite3_free_table(&res.azResult[1]);
  123502. db->errCode = SQLITE_NOMEM;
  123503. return SQLITE_NOMEM_BKPT;
  123504. }
  123505. res.azResult = azNew;
  123506. }
  123507. *pazResult = &res.azResult[1];
  123508. if( pnColumn ) *pnColumn = res.nColumn;
  123509. if( pnRow ) *pnRow = res.nRow;
  123510. return rc;
  123511. }
  123512. /*
  123513. ** This routine frees the space the sqlite3_get_table() malloced.
  123514. */
  123515. SQLITE_API void sqlite3_free_table(
  123516. char **azResult /* Result returned from sqlite3_get_table() */
  123517. ){
  123518. if( azResult ){
  123519. int i, n;
  123520. azResult--;
  123521. assert( azResult!=0 );
  123522. n = SQLITE_PTR_TO_INT(azResult[0]);
  123523. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  123524. sqlite3_free(azResult);
  123525. }
  123526. }
  123527. #endif /* SQLITE_OMIT_GET_TABLE */
  123528. /************** End of table.c ***********************************************/
  123529. /************** Begin file trigger.c *****************************************/
  123530. /*
  123531. **
  123532. ** The author disclaims copyright to this source code. In place of
  123533. ** a legal notice, here is a blessing:
  123534. **
  123535. ** May you do good and not evil.
  123536. ** May you find forgiveness for yourself and forgive others.
  123537. ** May you share freely, never taking more than you give.
  123538. **
  123539. *************************************************************************
  123540. ** This file contains the implementation for TRIGGERs
  123541. */
  123542. /* #include "sqliteInt.h" */
  123543. #ifndef SQLITE_OMIT_TRIGGER
  123544. /*
  123545. ** Delete a linked list of TriggerStep structures.
  123546. */
  123547. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  123548. while( pTriggerStep ){
  123549. TriggerStep * pTmp = pTriggerStep;
  123550. pTriggerStep = pTriggerStep->pNext;
  123551. sqlite3ExprDelete(db, pTmp->pWhere);
  123552. sqlite3ExprListDelete(db, pTmp->pExprList);
  123553. sqlite3SelectDelete(db, pTmp->pSelect);
  123554. sqlite3IdListDelete(db, pTmp->pIdList);
  123555. sqlite3UpsertDelete(db, pTmp->pUpsert);
  123556. sqlite3DbFree(db, pTmp->zSpan);
  123557. sqlite3DbFree(db, pTmp);
  123558. }
  123559. }
  123560. /*
  123561. ** Given table pTab, return a list of all the triggers attached to
  123562. ** the table. The list is connected by Trigger.pNext pointers.
  123563. **
  123564. ** All of the triggers on pTab that are in the same database as pTab
  123565. ** are already attached to pTab->pTrigger. But there might be additional
  123566. ** triggers on pTab in the TEMP schema. This routine prepends all
  123567. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  123568. ** and returns the combined list.
  123569. **
  123570. ** To state it another way: This routine returns a list of all triggers
  123571. ** that fire off of pTab. The list will include any TEMP triggers on
  123572. ** pTab as well as the triggers lised in pTab->pTrigger.
  123573. */
  123574. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  123575. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  123576. Trigger *pList = 0; /* List of triggers to return */
  123577. if( pParse->disableTriggers ){
  123578. return 0;
  123579. }
  123580. if( pTmpSchema!=pTab->pSchema ){
  123581. HashElem *p;
  123582. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  123583. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  123584. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  123585. if( pTrig->pTabSchema==pTab->pSchema
  123586. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  123587. ){
  123588. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  123589. pList = pTrig;
  123590. }
  123591. }
  123592. }
  123593. return (pList ? pList : pTab->pTrigger);
  123594. }
  123595. /*
  123596. ** This is called by the parser when it sees a CREATE TRIGGER statement
  123597. ** up to the point of the BEGIN before the trigger actions. A Trigger
  123598. ** structure is generated based on the information available and stored
  123599. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  123600. ** sqlite3FinishTrigger() function is called to complete the trigger
  123601. ** construction process.
  123602. */
  123603. SQLITE_PRIVATE void sqlite3BeginTrigger(
  123604. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  123605. Token *pName1, /* The name of the trigger */
  123606. Token *pName2, /* The name of the trigger */
  123607. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  123608. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  123609. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  123610. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  123611. Expr *pWhen, /* WHEN clause */
  123612. int isTemp, /* True if the TEMPORARY keyword is present */
  123613. int noErr /* Suppress errors if the trigger already exists */
  123614. ){
  123615. Trigger *pTrigger = 0; /* The new trigger */
  123616. Table *pTab; /* Table that the trigger fires off of */
  123617. char *zName = 0; /* Name of the trigger */
  123618. sqlite3 *db = pParse->db; /* The database connection */
  123619. int iDb; /* The database to store the trigger in */
  123620. Token *pName; /* The unqualified db name */
  123621. DbFixer sFix; /* State vector for the DB fixer */
  123622. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  123623. assert( pName2!=0 );
  123624. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  123625. assert( op>0 && op<0xff );
  123626. if( isTemp ){
  123627. /* If TEMP was specified, then the trigger name may not be qualified. */
  123628. if( pName2->n>0 ){
  123629. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  123630. goto trigger_cleanup;
  123631. }
  123632. iDb = 1;
  123633. pName = pName1;
  123634. }else{
  123635. /* Figure out the db that the trigger will be created in */
  123636. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  123637. if( iDb<0 ){
  123638. goto trigger_cleanup;
  123639. }
  123640. }
  123641. if( !pTableName || db->mallocFailed ){
  123642. goto trigger_cleanup;
  123643. }
  123644. /* A long-standing parser bug is that this syntax was allowed:
  123645. **
  123646. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  123647. ** ^^^^^^^^
  123648. **
  123649. ** To maintain backwards compatibility, ignore the database
  123650. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  123651. */
  123652. if( db->init.busy && iDb!=1 ){
  123653. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  123654. pTableName->a[0].zDatabase = 0;
  123655. }
  123656. /* If the trigger name was unqualified, and the table is a temp table,
  123657. ** then set iDb to 1 to create the trigger in the temporary database.
  123658. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  123659. ** exist, the error is caught by the block below.
  123660. */
  123661. pTab = sqlite3SrcListLookup(pParse, pTableName);
  123662. if( db->init.busy==0 && pName2->n==0 && pTab
  123663. && pTab->pSchema==db->aDb[1].pSchema ){
  123664. iDb = 1;
  123665. }
  123666. /* Ensure the table name matches database name and that the table exists */
  123667. if( db->mallocFailed ) goto trigger_cleanup;
  123668. assert( pTableName->nSrc==1 );
  123669. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  123670. if( sqlite3FixSrcList(&sFix, pTableName) ){
  123671. goto trigger_cleanup;
  123672. }
  123673. pTab = sqlite3SrcListLookup(pParse, pTableName);
  123674. if( !pTab ){
  123675. /* The table does not exist. */
  123676. if( db->init.iDb==1 ){
  123677. /* Ticket #3810.
  123678. ** Normally, whenever a table is dropped, all associated triggers are
  123679. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  123680. ** and the table is dropped by a different database connection, the
  123681. ** trigger is not visible to the database connection that does the
  123682. ** drop so the trigger cannot be dropped. This results in an
  123683. ** "orphaned trigger" - a trigger whose associated table is missing.
  123684. */
  123685. db->init.orphanTrigger = 1;
  123686. }
  123687. goto trigger_cleanup;
  123688. }
  123689. if( IsVirtual(pTab) ){
  123690. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  123691. goto trigger_cleanup;
  123692. }
  123693. /* Check that the trigger name is not reserved and that no trigger of the
  123694. ** specified name exists */
  123695. zName = sqlite3NameFromToken(db, pName);
  123696. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  123697. goto trigger_cleanup;
  123698. }
  123699. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  123700. if( !IN_RENAME_OBJECT ){
  123701. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  123702. if( !noErr ){
  123703. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  123704. }else{
  123705. assert( !db->init.busy );
  123706. sqlite3CodeVerifySchema(pParse, iDb);
  123707. }
  123708. goto trigger_cleanup;
  123709. }
  123710. }
  123711. /* Do not create a trigger on a system table */
  123712. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  123713. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  123714. goto trigger_cleanup;
  123715. }
  123716. /* INSTEAD of triggers are only for views and views only support INSTEAD
  123717. ** of triggers.
  123718. */
  123719. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  123720. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  123721. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  123722. goto trigger_cleanup;
  123723. }
  123724. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  123725. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  123726. " trigger on table: %S", pTableName, 0);
  123727. goto trigger_cleanup;
  123728. }
  123729. #ifndef SQLITE_OMIT_AUTHORIZATION
  123730. if( !IN_RENAME_OBJECT ){
  123731. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  123732. int code = SQLITE_CREATE_TRIGGER;
  123733. const char *zDb = db->aDb[iTabDb].zDbSName;
  123734. const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
  123735. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  123736. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  123737. goto trigger_cleanup;
  123738. }
  123739. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  123740. goto trigger_cleanup;
  123741. }
  123742. }
  123743. #endif
  123744. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  123745. ** cannot appear on views. So we might as well translate every
  123746. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  123747. ** elsewhere.
  123748. */
  123749. if (tr_tm == TK_INSTEAD){
  123750. tr_tm = TK_BEFORE;
  123751. }
  123752. /* Build the Trigger object */
  123753. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  123754. if( pTrigger==0 ) goto trigger_cleanup;
  123755. pTrigger->zName = zName;
  123756. zName = 0;
  123757. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  123758. pTrigger->pSchema = db->aDb[iDb].pSchema;
  123759. pTrigger->pTabSchema = pTab->pSchema;
  123760. pTrigger->op = (u8)op;
  123761. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  123762. if( IN_RENAME_OBJECT ){
  123763. sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName);
  123764. pTrigger->pWhen = pWhen;
  123765. pWhen = 0;
  123766. }else{
  123767. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  123768. }
  123769. pTrigger->pColumns = pColumns;
  123770. pColumns = 0;
  123771. assert( pParse->pNewTrigger==0 );
  123772. pParse->pNewTrigger = pTrigger;
  123773. trigger_cleanup:
  123774. sqlite3DbFree(db, zName);
  123775. sqlite3SrcListDelete(db, pTableName);
  123776. sqlite3IdListDelete(db, pColumns);
  123777. sqlite3ExprDelete(db, pWhen);
  123778. if( !pParse->pNewTrigger ){
  123779. sqlite3DeleteTrigger(db, pTrigger);
  123780. }else{
  123781. assert( pParse->pNewTrigger==pTrigger );
  123782. }
  123783. }
  123784. /*
  123785. ** This routine is called after all of the trigger actions have been parsed
  123786. ** in order to complete the process of building the trigger.
  123787. */
  123788. SQLITE_PRIVATE void sqlite3FinishTrigger(
  123789. Parse *pParse, /* Parser context */
  123790. TriggerStep *pStepList, /* The triggered program */
  123791. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  123792. ){
  123793. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  123794. char *zName; /* Name of trigger */
  123795. sqlite3 *db = pParse->db; /* The database */
  123796. DbFixer sFix; /* Fixer object */
  123797. int iDb; /* Database containing the trigger */
  123798. Token nameToken; /* Trigger name for error reporting */
  123799. pParse->pNewTrigger = 0;
  123800. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  123801. zName = pTrig->zName;
  123802. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  123803. pTrig->step_list = pStepList;
  123804. while( pStepList ){
  123805. pStepList->pTrig = pTrig;
  123806. pStepList = pStepList->pNext;
  123807. }
  123808. sqlite3TokenInit(&nameToken, pTrig->zName);
  123809. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  123810. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  123811. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  123812. ){
  123813. goto triggerfinish_cleanup;
  123814. }
  123815. #ifndef SQLITE_OMIT_ALTERTABLE
  123816. if( IN_RENAME_OBJECT ){
  123817. assert( !db->init.busy );
  123818. pParse->pNewTrigger = pTrig;
  123819. pTrig = 0;
  123820. }else
  123821. #endif
  123822. /* if we are not initializing,
  123823. ** build the sqlite_master entry
  123824. */
  123825. if( !db->init.busy ){
  123826. Vdbe *v;
  123827. char *z;
  123828. /* Make an entry in the sqlite_master table */
  123829. v = sqlite3GetVdbe(pParse);
  123830. if( v==0 ) goto triggerfinish_cleanup;
  123831. sqlite3BeginWriteOperation(pParse, 0, iDb);
  123832. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  123833. testcase( z==0 );
  123834. sqlite3NestedParse(pParse,
  123835. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  123836. db->aDb[iDb].zDbSName, MASTER_NAME, zName,
  123837. pTrig->table, z);
  123838. sqlite3DbFree(db, z);
  123839. sqlite3ChangeCookie(pParse, iDb);
  123840. sqlite3VdbeAddParseSchemaOp(v, iDb,
  123841. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  123842. }
  123843. if( db->init.busy ){
  123844. Trigger *pLink = pTrig;
  123845. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  123846. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  123847. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  123848. if( pTrig ){
  123849. sqlite3OomFault(db);
  123850. }else if( pLink->pSchema==pLink->pTabSchema ){
  123851. Table *pTab;
  123852. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  123853. assert( pTab!=0 );
  123854. pLink->pNext = pTab->pTrigger;
  123855. pTab->pTrigger = pLink;
  123856. }
  123857. }
  123858. triggerfinish_cleanup:
  123859. sqlite3DeleteTrigger(db, pTrig);
  123860. assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );
  123861. sqlite3DeleteTriggerStep(db, pStepList);
  123862. }
  123863. /*
  123864. ** Duplicate a range of text from an SQL statement, then convert all
  123865. ** whitespace characters into ordinary space characters.
  123866. */
  123867. static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  123868. char *z = sqlite3DbSpanDup(db, zStart, zEnd);
  123869. int i;
  123870. if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
  123871. return z;
  123872. }
  123873. /*
  123874. ** Turn a SELECT statement (that the pSelect parameter points to) into
  123875. ** a trigger step. Return a pointer to a TriggerStep structure.
  123876. **
  123877. ** The parser calls this routine when it finds a SELECT statement in
  123878. ** body of a TRIGGER.
  123879. */
  123880. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(
  123881. sqlite3 *db, /* Database connection */
  123882. Select *pSelect, /* The SELECT statement */
  123883. const char *zStart, /* Start of SQL text */
  123884. const char *zEnd /* End of SQL text */
  123885. ){
  123886. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  123887. if( pTriggerStep==0 ) {
  123888. sqlite3SelectDelete(db, pSelect);
  123889. return 0;
  123890. }
  123891. pTriggerStep->op = TK_SELECT;
  123892. pTriggerStep->pSelect = pSelect;
  123893. pTriggerStep->orconf = OE_Default;
  123894. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  123895. return pTriggerStep;
  123896. }
  123897. /*
  123898. ** Allocate space to hold a new trigger step. The allocated space
  123899. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  123900. **
  123901. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  123902. */
  123903. static TriggerStep *triggerStepAllocate(
  123904. Parse *pParse, /* Parser context */
  123905. u8 op, /* Trigger opcode */
  123906. Token *pName, /* The target name */
  123907. const char *zStart, /* Start of SQL text */
  123908. const char *zEnd /* End of SQL text */
  123909. ){
  123910. sqlite3 *db = pParse->db;
  123911. TriggerStep *pTriggerStep;
  123912. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  123913. if( pTriggerStep ){
  123914. char *z = (char*)&pTriggerStep[1];
  123915. memcpy(z, pName->z, pName->n);
  123916. sqlite3Dequote(z);
  123917. pTriggerStep->zTarget = z;
  123918. pTriggerStep->op = op;
  123919. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  123920. if( IN_RENAME_OBJECT ){
  123921. sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);
  123922. }
  123923. }
  123924. return pTriggerStep;
  123925. }
  123926. /*
  123927. ** Build a trigger step out of an INSERT statement. Return a pointer
  123928. ** to the new trigger step.
  123929. **
  123930. ** The parser calls this routine when it sees an INSERT inside the
  123931. ** body of a trigger.
  123932. */
  123933. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  123934. Parse *pParse, /* Parser */
  123935. Token *pTableName, /* Name of the table into which we insert */
  123936. IdList *pColumn, /* List of columns in pTableName to insert into */
  123937. Select *pSelect, /* A SELECT statement that supplies values */
  123938. u8 orconf, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  123939. Upsert *pUpsert, /* ON CONFLICT clauses for upsert */
  123940. const char *zStart, /* Start of SQL text */
  123941. const char *zEnd /* End of SQL text */
  123942. ){
  123943. sqlite3 *db = pParse->db;
  123944. TriggerStep *pTriggerStep;
  123945. assert(pSelect != 0 || db->mallocFailed);
  123946. pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd);
  123947. if( pTriggerStep ){
  123948. if( IN_RENAME_OBJECT ){
  123949. pTriggerStep->pSelect = pSelect;
  123950. pSelect = 0;
  123951. }else{
  123952. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  123953. }
  123954. pTriggerStep->pIdList = pColumn;
  123955. pTriggerStep->pUpsert = pUpsert;
  123956. pTriggerStep->orconf = orconf;
  123957. }else{
  123958. testcase( pColumn );
  123959. sqlite3IdListDelete(db, pColumn);
  123960. testcase( pUpsert );
  123961. sqlite3UpsertDelete(db, pUpsert);
  123962. }
  123963. sqlite3SelectDelete(db, pSelect);
  123964. return pTriggerStep;
  123965. }
  123966. /*
  123967. ** Construct a trigger step that implements an UPDATE statement and return
  123968. ** a pointer to that trigger step. The parser calls this routine when it
  123969. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  123970. */
  123971. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  123972. Parse *pParse, /* Parser */
  123973. Token *pTableName, /* Name of the table to be updated */
  123974. ExprList *pEList, /* The SET clause: list of column and new values */
  123975. Expr *pWhere, /* The WHERE clause */
  123976. u8 orconf, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  123977. const char *zStart, /* Start of SQL text */
  123978. const char *zEnd /* End of SQL text */
  123979. ){
  123980. sqlite3 *db = pParse->db;
  123981. TriggerStep *pTriggerStep;
  123982. pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd);
  123983. if( pTriggerStep ){
  123984. if( IN_RENAME_OBJECT ){
  123985. pTriggerStep->pExprList = pEList;
  123986. pTriggerStep->pWhere = pWhere;
  123987. pEList = 0;
  123988. pWhere = 0;
  123989. }else{
  123990. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  123991. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  123992. }
  123993. pTriggerStep->orconf = orconf;
  123994. }
  123995. sqlite3ExprListDelete(db, pEList);
  123996. sqlite3ExprDelete(db, pWhere);
  123997. return pTriggerStep;
  123998. }
  123999. /*
  124000. ** Construct a trigger step that implements a DELETE statement and return
  124001. ** a pointer to that trigger step. The parser calls this routine when it
  124002. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  124003. */
  124004. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  124005. Parse *pParse, /* Parser */
  124006. Token *pTableName, /* The table from which rows are deleted */
  124007. Expr *pWhere, /* The WHERE clause */
  124008. const char *zStart, /* Start of SQL text */
  124009. const char *zEnd /* End of SQL text */
  124010. ){
  124011. sqlite3 *db = pParse->db;
  124012. TriggerStep *pTriggerStep;
  124013. pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd);
  124014. if( pTriggerStep ){
  124015. if( IN_RENAME_OBJECT ){
  124016. pTriggerStep->pWhere = pWhere;
  124017. pWhere = 0;
  124018. }else{
  124019. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  124020. }
  124021. pTriggerStep->orconf = OE_Default;
  124022. }
  124023. sqlite3ExprDelete(db, pWhere);
  124024. return pTriggerStep;
  124025. }
  124026. /*
  124027. ** Recursively delete a Trigger structure
  124028. */
  124029. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  124030. if( pTrigger==0 ) return;
  124031. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  124032. sqlite3DbFree(db, pTrigger->zName);
  124033. sqlite3DbFree(db, pTrigger->table);
  124034. sqlite3ExprDelete(db, pTrigger->pWhen);
  124035. sqlite3IdListDelete(db, pTrigger->pColumns);
  124036. sqlite3DbFree(db, pTrigger);
  124037. }
  124038. /*
  124039. ** This function is called to drop a trigger from the database schema.
  124040. **
  124041. ** This may be called directly from the parser and therefore identifies
  124042. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  124043. ** same job as this routine except it takes a pointer to the trigger
  124044. ** instead of the trigger name.
  124045. **/
  124046. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  124047. Trigger *pTrigger = 0;
  124048. int i;
  124049. const char *zDb;
  124050. const char *zName;
  124051. sqlite3 *db = pParse->db;
  124052. if( db->mallocFailed ) goto drop_trigger_cleanup;
  124053. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  124054. goto drop_trigger_cleanup;
  124055. }
  124056. assert( pName->nSrc==1 );
  124057. zDb = pName->a[0].zDatabase;
  124058. zName = pName->a[0].zName;
  124059. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  124060. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  124061. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  124062. if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
  124063. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  124064. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  124065. if( pTrigger ) break;
  124066. }
  124067. if( !pTrigger ){
  124068. if( !noErr ){
  124069. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  124070. }else{
  124071. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  124072. }
  124073. pParse->checkSchema = 1;
  124074. goto drop_trigger_cleanup;
  124075. }
  124076. sqlite3DropTriggerPtr(pParse, pTrigger);
  124077. drop_trigger_cleanup:
  124078. sqlite3SrcListDelete(db, pName);
  124079. }
  124080. /*
  124081. ** Return a pointer to the Table structure for the table that a trigger
  124082. ** is set on.
  124083. */
  124084. static Table *tableOfTrigger(Trigger *pTrigger){
  124085. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  124086. }
  124087. /*
  124088. ** Drop a trigger given a pointer to that trigger.
  124089. */
  124090. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  124091. Table *pTable;
  124092. Vdbe *v;
  124093. sqlite3 *db = pParse->db;
  124094. int iDb;
  124095. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  124096. assert( iDb>=0 && iDb<db->nDb );
  124097. pTable = tableOfTrigger(pTrigger);
  124098. assert( pTable );
  124099. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  124100. #ifndef SQLITE_OMIT_AUTHORIZATION
  124101. {
  124102. int code = SQLITE_DROP_TRIGGER;
  124103. const char *zDb = db->aDb[iDb].zDbSName;
  124104. const char *zTab = SCHEMA_TABLE(iDb);
  124105. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  124106. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  124107. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  124108. return;
  124109. }
  124110. }
  124111. #endif
  124112. /* Generate code to destroy the database record of the trigger.
  124113. */
  124114. assert( pTable!=0 );
  124115. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  124116. sqlite3NestedParse(pParse,
  124117. "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
  124118. db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
  124119. );
  124120. sqlite3ChangeCookie(pParse, iDb);
  124121. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  124122. }
  124123. }
  124124. /*
  124125. ** Remove a trigger from the hash tables of the sqlite* pointer.
  124126. */
  124127. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  124128. Trigger *pTrigger;
  124129. Hash *pHash;
  124130. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  124131. pHash = &(db->aDb[iDb].pSchema->trigHash);
  124132. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  124133. if( ALWAYS(pTrigger) ){
  124134. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  124135. Table *pTab = tableOfTrigger(pTrigger);
  124136. Trigger **pp;
  124137. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  124138. *pp = (*pp)->pNext;
  124139. }
  124140. sqlite3DeleteTrigger(db, pTrigger);
  124141. db->mDbFlags |= DBFLAG_SchemaChange;
  124142. }
  124143. }
  124144. /*
  124145. ** pEList is the SET clause of an UPDATE statement. Each entry
  124146. ** in pEList is of the format <id>=<expr>. If any of the entries
  124147. ** in pEList have an <id> which matches an identifier in pIdList,
  124148. ** then return TRUE. If pIdList==NULL, then it is considered a
  124149. ** wildcard that matches anything. Likewise if pEList==NULL then
  124150. ** it matches anything so always return true. Return false only
  124151. ** if there is no match.
  124152. */
  124153. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  124154. int e;
  124155. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  124156. for(e=0; e<pEList->nExpr; e++){
  124157. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  124158. }
  124159. return 0;
  124160. }
  124161. /*
  124162. ** Return a list of all triggers on table pTab if there exists at least
  124163. ** one trigger that must be fired when an operation of type 'op' is
  124164. ** performed on the table, and, if that operation is an UPDATE, if at
  124165. ** least one of the columns in pChanges is being modified.
  124166. */
  124167. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  124168. Parse *pParse, /* Parse context */
  124169. Table *pTab, /* The table the contains the triggers */
  124170. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  124171. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  124172. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  124173. ){
  124174. int mask = 0;
  124175. Trigger *pList = 0;
  124176. Trigger *p;
  124177. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  124178. pList = sqlite3TriggerList(pParse, pTab);
  124179. }
  124180. assert( pList==0 || IsVirtual(pTab)==0 );
  124181. for(p=pList; p; p=p->pNext){
  124182. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  124183. mask |= p->tr_tm;
  124184. }
  124185. }
  124186. if( pMask ){
  124187. *pMask = mask;
  124188. }
  124189. return (mask ? pList : 0);
  124190. }
  124191. /*
  124192. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  124193. ** to that SrcList.
  124194. **
  124195. ** This routine adds a specific database name, if needed, to the target when
  124196. ** forming the SrcList. This prevents a trigger in one database from
  124197. ** referring to a target in another database. An exception is when the
  124198. ** trigger is in TEMP in which case it can refer to any other database it
  124199. ** wants.
  124200. */
  124201. static SrcList *targetSrcList(
  124202. Parse *pParse, /* The parsing context */
  124203. TriggerStep *pStep /* The trigger containing the target token */
  124204. ){
  124205. sqlite3 *db = pParse->db;
  124206. int iDb; /* Index of the database to use */
  124207. SrcList *pSrc; /* SrcList to be returned */
  124208. pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  124209. if( pSrc ){
  124210. assert( pSrc->nSrc>0 );
  124211. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  124212. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  124213. if( iDb==0 || iDb>=2 ){
  124214. const char *zDb;
  124215. assert( iDb<db->nDb );
  124216. zDb = db->aDb[iDb].zDbSName;
  124217. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
  124218. }
  124219. }
  124220. return pSrc;
  124221. }
  124222. /*
  124223. ** Generate VDBE code for the statements inside the body of a single
  124224. ** trigger.
  124225. */
  124226. static int codeTriggerProgram(
  124227. Parse *pParse, /* The parser context */
  124228. TriggerStep *pStepList, /* List of statements inside the trigger body */
  124229. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  124230. ){
  124231. TriggerStep *pStep;
  124232. Vdbe *v = pParse->pVdbe;
  124233. sqlite3 *db = pParse->db;
  124234. assert( pParse->pTriggerTab && pParse->pToplevel );
  124235. assert( pStepList );
  124236. assert( v!=0 );
  124237. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  124238. /* Figure out the ON CONFLICT policy that will be used for this step
  124239. ** of the trigger program. If the statement that caused this trigger
  124240. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  124241. ** the ON CONFLICT policy that was specified as part of the trigger
  124242. ** step statement. Example:
  124243. **
  124244. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  124245. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  124246. ** END;
  124247. **
  124248. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  124249. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  124250. */
  124251. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  124252. assert( pParse->okConstFactor==0 );
  124253. #ifndef SQLITE_OMIT_TRACE
  124254. if( pStep->zSpan ){
  124255. sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
  124256. sqlite3MPrintf(db, "-- %s", pStep->zSpan),
  124257. P4_DYNAMIC);
  124258. }
  124259. #endif
  124260. switch( pStep->op ){
  124261. case TK_UPDATE: {
  124262. sqlite3Update(pParse,
  124263. targetSrcList(pParse, pStep),
  124264. sqlite3ExprListDup(db, pStep->pExprList, 0),
  124265. sqlite3ExprDup(db, pStep->pWhere, 0),
  124266. pParse->eOrconf, 0, 0, 0
  124267. );
  124268. break;
  124269. }
  124270. case TK_INSERT: {
  124271. sqlite3Insert(pParse,
  124272. targetSrcList(pParse, pStep),
  124273. sqlite3SelectDup(db, pStep->pSelect, 0),
  124274. sqlite3IdListDup(db, pStep->pIdList),
  124275. pParse->eOrconf,
  124276. sqlite3UpsertDup(db, pStep->pUpsert)
  124277. );
  124278. break;
  124279. }
  124280. case TK_DELETE: {
  124281. sqlite3DeleteFrom(pParse,
  124282. targetSrcList(pParse, pStep),
  124283. sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
  124284. );
  124285. break;
  124286. }
  124287. default: assert( pStep->op==TK_SELECT ); {
  124288. SelectDest sDest;
  124289. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  124290. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  124291. sqlite3Select(pParse, pSelect, &sDest);
  124292. sqlite3SelectDelete(db, pSelect);
  124293. break;
  124294. }
  124295. }
  124296. if( pStep->op!=TK_SELECT ){
  124297. sqlite3VdbeAddOp0(v, OP_ResetCount);
  124298. }
  124299. }
  124300. return 0;
  124301. }
  124302. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  124303. /*
  124304. ** This function is used to add VdbeComment() annotations to a VDBE
  124305. ** program. It is not used in production code, only for debugging.
  124306. */
  124307. static const char *onErrorText(int onError){
  124308. switch( onError ){
  124309. case OE_Abort: return "abort";
  124310. case OE_Rollback: return "rollback";
  124311. case OE_Fail: return "fail";
  124312. case OE_Replace: return "replace";
  124313. case OE_Ignore: return "ignore";
  124314. case OE_Default: return "default";
  124315. }
  124316. return "n/a";
  124317. }
  124318. #endif
  124319. /*
  124320. ** Parse context structure pFrom has just been used to create a sub-vdbe
  124321. ** (trigger program). If an error has occurred, transfer error information
  124322. ** from pFrom to pTo.
  124323. */
  124324. static void transferParseError(Parse *pTo, Parse *pFrom){
  124325. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  124326. assert( pTo->zErrMsg==0 || pTo->nErr );
  124327. if( pTo->nErr==0 ){
  124328. pTo->zErrMsg = pFrom->zErrMsg;
  124329. pTo->nErr = pFrom->nErr;
  124330. pTo->rc = pFrom->rc;
  124331. }else{
  124332. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  124333. }
  124334. }
  124335. /*
  124336. ** Create and populate a new TriggerPrg object with a sub-program
  124337. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  124338. */
  124339. static TriggerPrg *codeRowTrigger(
  124340. Parse *pParse, /* Current parse context */
  124341. Trigger *pTrigger, /* Trigger to code */
  124342. Table *pTab, /* The table pTrigger is attached to */
  124343. int orconf /* ON CONFLICT policy to code trigger program with */
  124344. ){
  124345. Parse *pTop = sqlite3ParseToplevel(pParse);
  124346. sqlite3 *db = pParse->db; /* Database handle */
  124347. TriggerPrg *pPrg; /* Value to return */
  124348. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  124349. Vdbe *v; /* Temporary VM */
  124350. NameContext sNC; /* Name context for sub-vdbe */
  124351. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  124352. Parse *pSubParse; /* Parse context for sub-vdbe */
  124353. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  124354. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  124355. assert( pTop->pVdbe );
  124356. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  124357. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  124358. ** list of the top-level Parse object sooner rather than later. */
  124359. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  124360. if( !pPrg ) return 0;
  124361. pPrg->pNext = pTop->pTriggerPrg;
  124362. pTop->pTriggerPrg = pPrg;
  124363. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  124364. if( !pProgram ) return 0;
  124365. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  124366. pPrg->pTrigger = pTrigger;
  124367. pPrg->orconf = orconf;
  124368. pPrg->aColmask[0] = 0xffffffff;
  124369. pPrg->aColmask[1] = 0xffffffff;
  124370. /* Allocate and populate a new Parse context to use for coding the
  124371. ** trigger sub-program. */
  124372. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  124373. if( !pSubParse ) return 0;
  124374. memset(&sNC, 0, sizeof(sNC));
  124375. sNC.pParse = pSubParse;
  124376. pSubParse->db = db;
  124377. pSubParse->pTriggerTab = pTab;
  124378. pSubParse->pToplevel = pTop;
  124379. pSubParse->zAuthContext = pTrigger->zName;
  124380. pSubParse->eTriggerOp = pTrigger->op;
  124381. pSubParse->nQueryLoop = pParse->nQueryLoop;
  124382. pSubParse->disableVtab = pParse->disableVtab;
  124383. v = sqlite3GetVdbe(pSubParse);
  124384. if( v ){
  124385. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  124386. pTrigger->zName, onErrorText(orconf),
  124387. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  124388. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  124389. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  124390. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  124391. pTab->zName
  124392. ));
  124393. #ifndef SQLITE_OMIT_TRACE
  124394. if( pTrigger->zName ){
  124395. sqlite3VdbeChangeP4(v, -1,
  124396. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  124397. );
  124398. }
  124399. #endif
  124400. /* If one was specified, code the WHEN clause. If it evaluates to false
  124401. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  124402. ** OP_Halt inserted at the end of the program. */
  124403. if( pTrigger->pWhen ){
  124404. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  124405. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  124406. && db->mallocFailed==0
  124407. ){
  124408. iEndTrigger = sqlite3VdbeMakeLabel(pSubParse);
  124409. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  124410. }
  124411. sqlite3ExprDelete(db, pWhen);
  124412. }
  124413. /* Code the trigger program into the sub-vdbe. */
  124414. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  124415. /* Insert an OP_Halt at the end of the sub-program. */
  124416. if( iEndTrigger ){
  124417. sqlite3VdbeResolveLabel(v, iEndTrigger);
  124418. }
  124419. sqlite3VdbeAddOp0(v, OP_Halt);
  124420. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  124421. transferParseError(pParse, pSubParse);
  124422. if( db->mallocFailed==0 && pParse->nErr==0 ){
  124423. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  124424. }
  124425. pProgram->nMem = pSubParse->nMem;
  124426. pProgram->nCsr = pSubParse->nTab;
  124427. pProgram->token = (void *)pTrigger;
  124428. pPrg->aColmask[0] = pSubParse->oldmask;
  124429. pPrg->aColmask[1] = pSubParse->newmask;
  124430. sqlite3VdbeDelete(v);
  124431. }
  124432. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  124433. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  124434. sqlite3ParserReset(pSubParse);
  124435. sqlite3StackFree(db, pSubParse);
  124436. return pPrg;
  124437. }
  124438. /*
  124439. ** Return a pointer to a TriggerPrg object containing the sub-program for
  124440. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  124441. ** TriggerPrg object exists, a new object is allocated and populated before
  124442. ** being returned.
  124443. */
  124444. static TriggerPrg *getRowTrigger(
  124445. Parse *pParse, /* Current parse context */
  124446. Trigger *pTrigger, /* Trigger to code */
  124447. Table *pTab, /* The table trigger pTrigger is attached to */
  124448. int orconf /* ON CONFLICT algorithm. */
  124449. ){
  124450. Parse *pRoot = sqlite3ParseToplevel(pParse);
  124451. TriggerPrg *pPrg;
  124452. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  124453. /* It may be that this trigger has already been coded (or is in the
  124454. ** process of being coded). If this is the case, then an entry with
  124455. ** a matching TriggerPrg.pTrigger field will be present somewhere
  124456. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  124457. for(pPrg=pRoot->pTriggerPrg;
  124458. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  124459. pPrg=pPrg->pNext
  124460. );
  124461. /* If an existing TriggerPrg could not be located, create a new one. */
  124462. if( !pPrg ){
  124463. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  124464. }
  124465. return pPrg;
  124466. }
  124467. /*
  124468. ** Generate code for the trigger program associated with trigger p on
  124469. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  124470. ** function are the same as those described in the header function for
  124471. ** sqlite3CodeRowTrigger()
  124472. */
  124473. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  124474. Parse *pParse, /* Parse context */
  124475. Trigger *p, /* Trigger to code */
  124476. Table *pTab, /* The table to code triggers from */
  124477. int reg, /* Reg array containing OLD.* and NEW.* values */
  124478. int orconf, /* ON CONFLICT policy */
  124479. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  124480. ){
  124481. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  124482. TriggerPrg *pPrg;
  124483. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  124484. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  124485. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  124486. ** is a pointer to the sub-vdbe containing the trigger program. */
  124487. if( pPrg ){
  124488. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  124489. sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
  124490. (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  124491. VdbeComment(
  124492. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  124493. /* Set the P5 operand of the OP_Program instruction to non-zero if
  124494. ** recursive invocation of this trigger program is disallowed. Recursive
  124495. ** invocation is disallowed if (a) the sub-program is really a trigger,
  124496. ** not a foreign key action, and (b) the flag to enable recursive triggers
  124497. ** is clear. */
  124498. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  124499. }
  124500. }
  124501. /*
  124502. ** This is called to code the required FOR EACH ROW triggers for an operation
  124503. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  124504. ** is given by the op parameter. The tr_tm parameter determines whether the
  124505. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  124506. ** parameter pChanges is passed the list of columns being modified.
  124507. **
  124508. ** If there are no triggers that fire at the specified time for the specified
  124509. ** operation on pTab, this function is a no-op.
  124510. **
  124511. ** The reg argument is the address of the first in an array of registers
  124512. ** that contain the values substituted for the new.* and old.* references
  124513. ** in the trigger program. If N is the number of columns in table pTab
  124514. ** (a copy of pTab->nCol), then registers are populated as follows:
  124515. **
  124516. ** Register Contains
  124517. ** ------------------------------------------------------
  124518. ** reg+0 OLD.rowid
  124519. ** reg+1 OLD.* value of left-most column of pTab
  124520. ** ... ...
  124521. ** reg+N OLD.* value of right-most column of pTab
  124522. ** reg+N+1 NEW.rowid
  124523. ** reg+N+2 OLD.* value of left-most column of pTab
  124524. ** ... ...
  124525. ** reg+N+N+1 NEW.* value of right-most column of pTab
  124526. **
  124527. ** For ON DELETE triggers, the registers containing the NEW.* values will
  124528. ** never be accessed by the trigger program, so they are not allocated or
  124529. ** populated by the caller (there is no data to populate them with anyway).
  124530. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  124531. ** are never accessed, and so are not allocated by the caller. So, for an
  124532. ** ON INSERT trigger, the value passed to this function as parameter reg
  124533. ** is not a readable register, although registers (reg+N) through
  124534. ** (reg+N+N+1) are.
  124535. **
  124536. ** Parameter orconf is the default conflict resolution algorithm for the
  124537. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  124538. ** is the instruction that control should jump to if a trigger program
  124539. ** raises an IGNORE exception.
  124540. */
  124541. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  124542. Parse *pParse, /* Parse context */
  124543. Trigger *pTrigger, /* List of triggers on table pTab */
  124544. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  124545. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  124546. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  124547. Table *pTab, /* The table to code triggers from */
  124548. int reg, /* The first in an array of registers (see above) */
  124549. int orconf, /* ON CONFLICT policy */
  124550. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  124551. ){
  124552. Trigger *p; /* Used to iterate through pTrigger list */
  124553. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  124554. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  124555. assert( (op==TK_UPDATE)==(pChanges!=0) );
  124556. for(p=pTrigger; p; p=p->pNext){
  124557. /* Sanity checking: The schema for the trigger and for the table are
  124558. ** always defined. The trigger must be in the same schema as the table
  124559. ** or else it must be a TEMP trigger. */
  124560. assert( p->pSchema!=0 );
  124561. assert( p->pTabSchema!=0 );
  124562. assert( p->pSchema==p->pTabSchema
  124563. || p->pSchema==pParse->db->aDb[1].pSchema );
  124564. /* Determine whether we should code this trigger */
  124565. if( p->op==op
  124566. && p->tr_tm==tr_tm
  124567. && checkColumnOverlap(p->pColumns, pChanges)
  124568. ){
  124569. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  124570. }
  124571. }
  124572. }
  124573. /*
  124574. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  124575. ** This function returns a 32-bit bitmask indicating which columns of the
  124576. ** old.* or new.* tables actually are used by triggers. This information
  124577. ** may be used by the caller, for example, to avoid having to load the entire
  124578. ** old.* record into memory when executing an UPDATE or DELETE command.
  124579. **
  124580. ** Bit 0 of the returned mask is set if the left-most column of the
  124581. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  124582. ** the second leftmost column value is required, and so on. If there
  124583. ** are more than 32 columns in the table, and at least one of the columns
  124584. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  124585. **
  124586. ** It is not possible to determine if the old.rowid or new.rowid column is
  124587. ** accessed by triggers. The caller must always assume that it is.
  124588. **
  124589. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  124590. ** applies to the old.* table. If 1, the new.* table.
  124591. **
  124592. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  124593. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  124594. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  124595. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  124596. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  124597. */
  124598. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  124599. Parse *pParse, /* Parse context */
  124600. Trigger *pTrigger, /* List of triggers on table pTab */
  124601. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  124602. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  124603. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  124604. Table *pTab, /* The table to code triggers from */
  124605. int orconf /* Default ON CONFLICT policy for trigger steps */
  124606. ){
  124607. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  124608. u32 mask = 0;
  124609. Trigger *p;
  124610. assert( isNew==1 || isNew==0 );
  124611. for(p=pTrigger; p; p=p->pNext){
  124612. if( p->op==op && (tr_tm&p->tr_tm)
  124613. && checkColumnOverlap(p->pColumns,pChanges)
  124614. ){
  124615. TriggerPrg *pPrg;
  124616. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  124617. if( pPrg ){
  124618. mask |= pPrg->aColmask[isNew];
  124619. }
  124620. }
  124621. }
  124622. return mask;
  124623. }
  124624. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  124625. /************** End of trigger.c *********************************************/
  124626. /************** Begin file update.c ******************************************/
  124627. /*
  124628. ** 2001 September 15
  124629. **
  124630. ** The author disclaims copyright to this source code. In place of
  124631. ** a legal notice, here is a blessing:
  124632. **
  124633. ** May you do good and not evil.
  124634. ** May you find forgiveness for yourself and forgive others.
  124635. ** May you share freely, never taking more than you give.
  124636. **
  124637. *************************************************************************
  124638. ** This file contains C code routines that are called by the parser
  124639. ** to handle UPDATE statements.
  124640. */
  124641. /* #include "sqliteInt.h" */
  124642. #ifndef SQLITE_OMIT_VIRTUALTABLE
  124643. /* Forward declaration */
  124644. static void updateVirtualTable(
  124645. Parse *pParse, /* The parsing context */
  124646. SrcList *pSrc, /* The virtual table to be modified */
  124647. Table *pTab, /* The virtual table */
  124648. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  124649. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  124650. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  124651. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  124652. int onError /* ON CONFLICT strategy */
  124653. );
  124654. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  124655. /*
  124656. ** The most recently coded instruction was an OP_Column to retrieve the
  124657. ** i-th column of table pTab. This routine sets the P4 parameter of the
  124658. ** OP_Column to the default value, if any.
  124659. **
  124660. ** The default value of a column is specified by a DEFAULT clause in the
  124661. ** column definition. This was either supplied by the user when the table
  124662. ** was created, or added later to the table definition by an ALTER TABLE
  124663. ** command. If the latter, then the row-records in the table btree on disk
  124664. ** may not contain a value for the column and the default value, taken
  124665. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  124666. ** If the former, then all row-records are guaranteed to include a value
  124667. ** for the column and the P4 value is not required.
  124668. **
  124669. ** Column definitions created by an ALTER TABLE command may only have
  124670. ** literal default values specified: a number, null or a string. (If a more
  124671. ** complicated default expression value was provided, it is evaluated
  124672. ** when the ALTER TABLE is executed and one of the literal values written
  124673. ** into the sqlite_master table.)
  124674. **
  124675. ** Therefore, the P4 parameter is only required if the default value for
  124676. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  124677. ** function is capable of transforming these types of expressions into
  124678. ** sqlite3_value objects.
  124679. **
  124680. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  124681. ** on register iReg. This is used when an equivalent integer value is
  124682. ** stored in place of an 8-byte floating point value in order to save
  124683. ** space.
  124684. */
  124685. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  124686. assert( pTab!=0 );
  124687. if( !pTab->pSelect ){
  124688. sqlite3_value *pValue = 0;
  124689. u8 enc = ENC(sqlite3VdbeDb(v));
  124690. Column *pCol = &pTab->aCol[i];
  124691. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  124692. assert( i<pTab->nCol );
  124693. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  124694. pCol->affinity, &pValue);
  124695. if( pValue ){
  124696. sqlite3VdbeAppendP4(v, pValue, P4_MEM);
  124697. }
  124698. }
  124699. #ifndef SQLITE_OMIT_FLOATING_POINT
  124700. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  124701. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  124702. }
  124703. #endif
  124704. }
  124705. /*
  124706. ** Check to see if column iCol of index pIdx references any of the
  124707. ** columns defined by aXRef and chngRowid. Return true if it does
  124708. ** and false if not. This is an optimization. False-positives are a
  124709. ** performance degradation, but false-negatives can result in a corrupt
  124710. ** index and incorrect answers.
  124711. **
  124712. ** aXRef[j] will be non-negative if column j of the original table is
  124713. ** being updated. chngRowid will be true if the rowid of the table is
  124714. ** being updated.
  124715. */
  124716. static int indexColumnIsBeingUpdated(
  124717. Index *pIdx, /* The index to check */
  124718. int iCol, /* Which column of the index to check */
  124719. int *aXRef, /* aXRef[j]>=0 if column j is being updated */
  124720. int chngRowid /* true if the rowid is being updated */
  124721. ){
  124722. i16 iIdxCol = pIdx->aiColumn[iCol];
  124723. assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */
  124724. if( iIdxCol>=0 ){
  124725. return aXRef[iIdxCol]>=0;
  124726. }
  124727. assert( iIdxCol==XN_EXPR );
  124728. assert( pIdx->aColExpr!=0 );
  124729. assert( pIdx->aColExpr->a[iCol].pExpr!=0 );
  124730. return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,
  124731. aXRef,chngRowid);
  124732. }
  124733. /*
  124734. ** Check to see if index pIdx is a partial index whose conditional
  124735. ** expression might change values due to an UPDATE. Return true if
  124736. ** the index is subject to change and false if the index is guaranteed
  124737. ** to be unchanged. This is an optimization. False-positives are a
  124738. ** performance degradation, but false-negatives can result in a corrupt
  124739. ** index and incorrect answers.
  124740. **
  124741. ** aXRef[j] will be non-negative if column j of the original table is
  124742. ** being updated. chngRowid will be true if the rowid of the table is
  124743. ** being updated.
  124744. */
  124745. static int indexWhereClauseMightChange(
  124746. Index *pIdx, /* The index to check */
  124747. int *aXRef, /* aXRef[j]>=0 if column j is being updated */
  124748. int chngRowid /* true if the rowid is being updated */
  124749. ){
  124750. if( pIdx->pPartIdxWhere==0 ) return 0;
  124751. return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,
  124752. aXRef, chngRowid);
  124753. }
  124754. /*
  124755. ** Process an UPDATE statement.
  124756. **
  124757. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  124758. ** \_______/ \________/ \______/ \________________/
  124759. * onError pTabList pChanges pWhere
  124760. */
  124761. SQLITE_PRIVATE void sqlite3Update(
  124762. Parse *pParse, /* The parser context */
  124763. SrcList *pTabList, /* The table in which we should change things */
  124764. ExprList *pChanges, /* Things to be changed */
  124765. Expr *pWhere, /* The WHERE clause. May be null */
  124766. int onError, /* How to handle constraint errors */
  124767. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  124768. Expr *pLimit, /* LIMIT clause. May be null */
  124769. Upsert *pUpsert /* ON CONFLICT clause, or null */
  124770. ){
  124771. int i, j; /* Loop counters */
  124772. Table *pTab; /* The table to be updated */
  124773. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  124774. WhereInfo *pWInfo; /* Information about the WHERE clause */
  124775. Vdbe *v; /* The virtual database engine */
  124776. Index *pIdx; /* For looping over indices */
  124777. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  124778. int nIdx; /* Number of indices that need updating */
  124779. int iBaseCur; /* Base cursor number */
  124780. int iDataCur; /* Cursor for the canonical data btree */
  124781. int iIdxCur; /* Cursor for the first index */
  124782. sqlite3 *db; /* The database structure */
  124783. int *aRegIdx = 0; /* First register in array assigned to each index */
  124784. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  124785. ** an expression for the i-th column of the table.
  124786. ** aXRef[i]==-1 if the i-th column is not changed. */
  124787. u8 *aToOpen; /* 1 for tables and indices to be opened */
  124788. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  124789. u8 chngRowid; /* Rowid changed in a normal table */
  124790. u8 chngKey; /* Either chngPk or chngRowid */
  124791. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  124792. AuthContext sContext; /* The authorization context */
  124793. NameContext sNC; /* The name-context to resolve expressions in */
  124794. int iDb; /* Database containing the table being updated */
  124795. int eOnePass; /* ONEPASS_XXX value from where.c */
  124796. int hasFK; /* True if foreign key processing is required */
  124797. int labelBreak; /* Jump here to break out of UPDATE loop */
  124798. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  124799. int flags; /* Flags for sqlite3WhereBegin() */
  124800. #ifndef SQLITE_OMIT_TRIGGER
  124801. int isView; /* True when updating a view (INSTEAD OF trigger) */
  124802. Trigger *pTrigger; /* List of triggers on pTab, if required */
  124803. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  124804. #endif
  124805. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  124806. int iEph = 0; /* Ephemeral table holding all primary key values */
  124807. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  124808. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  124809. int addrOpen = 0; /* Address of OP_OpenEphemeral */
  124810. int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
  124811. i16 nPk = 0; /* Number of components of the PRIMARY KEY */
  124812. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  124813. /* Register Allocations */
  124814. int regRowCount = 0; /* A count of rows changed */
  124815. int regOldRowid = 0; /* The old rowid */
  124816. int regNewRowid = 0; /* The new rowid */
  124817. int regNew = 0; /* Content of the NEW.* table in triggers */
  124818. int regOld = 0; /* Content of OLD.* table in triggers */
  124819. int regRowSet = 0; /* Rowset of rows to be updated */
  124820. int regKey = 0; /* composite PRIMARY KEY value */
  124821. memset(&sContext, 0, sizeof(sContext));
  124822. db = pParse->db;
  124823. if( pParse->nErr || db->mallocFailed ){
  124824. goto update_cleanup;
  124825. }
  124826. assert( pTabList->nSrc==1 );
  124827. /* Locate the table which we want to update.
  124828. */
  124829. pTab = sqlite3SrcListLookup(pParse, pTabList);
  124830. if( pTab==0 ) goto update_cleanup;
  124831. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  124832. /* Figure out if we have any triggers and if the table being
  124833. ** updated is a view.
  124834. */
  124835. #ifndef SQLITE_OMIT_TRIGGER
  124836. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  124837. isView = pTab->pSelect!=0;
  124838. assert( pTrigger || tmask==0 );
  124839. #else
  124840. # define pTrigger 0
  124841. # define isView 0
  124842. # define tmask 0
  124843. #endif
  124844. #ifdef SQLITE_OMIT_VIEW
  124845. # undef isView
  124846. # define isView 0
  124847. #endif
  124848. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  124849. if( !isView ){
  124850. pWhere = sqlite3LimitWhere(
  124851. pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
  124852. );
  124853. pOrderBy = 0;
  124854. pLimit = 0;
  124855. }
  124856. #endif
  124857. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  124858. goto update_cleanup;
  124859. }
  124860. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  124861. goto update_cleanup;
  124862. }
  124863. /* Allocate a cursors for the main database table and for all indices.
  124864. ** The index cursors might not be used, but if they are used they
  124865. ** need to occur right after the database cursor. So go ahead and
  124866. ** allocate enough space, just in case.
  124867. */
  124868. iBaseCur = iDataCur = pParse->nTab++;
  124869. iIdxCur = iDataCur+1;
  124870. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  124871. testcase( pPk!=0 && pPk!=pTab->pIndex );
  124872. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  124873. if( pPk==pIdx ){
  124874. iDataCur = pParse->nTab;
  124875. }
  124876. pParse->nTab++;
  124877. }
  124878. if( pUpsert ){
  124879. /* On an UPSERT, reuse the same cursors already opened by INSERT */
  124880. iDataCur = pUpsert->iDataCur;
  124881. iIdxCur = pUpsert->iIdxCur;
  124882. pParse->nTab = iBaseCur;
  124883. }
  124884. pTabList->a[0].iCursor = iDataCur;
  124885. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  124886. ** Initialize aXRef[] and aToOpen[] to their default values.
  124887. */
  124888. aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  124889. if( aXRef==0 ) goto update_cleanup;
  124890. aRegIdx = aXRef+pTab->nCol;
  124891. aToOpen = (u8*)(aRegIdx+nIdx);
  124892. memset(aToOpen, 1, nIdx+1);
  124893. aToOpen[nIdx+1] = 0;
  124894. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  124895. /* Initialize the name-context */
  124896. memset(&sNC, 0, sizeof(sNC));
  124897. sNC.pParse = pParse;
  124898. sNC.pSrcList = pTabList;
  124899. sNC.uNC.pUpsert = pUpsert;
  124900. sNC.ncFlags = NC_UUpsert;
  124901. /* Resolve the column names in all the expressions of the
  124902. ** of the UPDATE statement. Also find the column index
  124903. ** for each column to be updated in the pChanges array. For each
  124904. ** column to be updated, make sure we have authorization to change
  124905. ** that column.
  124906. */
  124907. chngRowid = chngPk = 0;
  124908. for(i=0; i<pChanges->nExpr; i++){
  124909. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  124910. goto update_cleanup;
  124911. }
  124912. for(j=0; j<pTab->nCol; j++){
  124913. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  124914. if( j==pTab->iPKey ){
  124915. chngRowid = 1;
  124916. pRowidExpr = pChanges->a[i].pExpr;
  124917. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  124918. chngPk = 1;
  124919. }
  124920. aXRef[j] = i;
  124921. break;
  124922. }
  124923. }
  124924. if( j>=pTab->nCol ){
  124925. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  124926. j = -1;
  124927. chngRowid = 1;
  124928. pRowidExpr = pChanges->a[i].pExpr;
  124929. }else{
  124930. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  124931. pParse->checkSchema = 1;
  124932. goto update_cleanup;
  124933. }
  124934. }
  124935. #ifndef SQLITE_OMIT_AUTHORIZATION
  124936. {
  124937. int rc;
  124938. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  124939. j<0 ? "ROWID" : pTab->aCol[j].zName,
  124940. db->aDb[iDb].zDbSName);
  124941. if( rc==SQLITE_DENY ){
  124942. goto update_cleanup;
  124943. }else if( rc==SQLITE_IGNORE ){
  124944. aXRef[j] = -1;
  124945. }
  124946. }
  124947. #endif
  124948. }
  124949. assert( (chngRowid & chngPk)==0 );
  124950. assert( chngRowid==0 || chngRowid==1 );
  124951. assert( chngPk==0 || chngPk==1 );
  124952. chngKey = chngRowid + chngPk;
  124953. /* The SET expressions are not actually used inside the WHERE loop.
  124954. ** So reset the colUsed mask. Unless this is a virtual table. In that
  124955. ** case, set all bits of the colUsed mask (to ensure that the virtual
  124956. ** table implementation makes all columns available).
  124957. */
  124958. pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
  124959. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  124960. /* There is one entry in the aRegIdx[] array for each index on the table
  124961. ** being updated. Fill in aRegIdx[] with a register number that will hold
  124962. ** the key for accessing each index.
  124963. */
  124964. if( onError==OE_Replace ) bReplace = 1;
  124965. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  124966. int reg;
  124967. if( chngKey || hasFK>1 || pIdx==pPk
  124968. || indexWhereClauseMightChange(pIdx,aXRef,chngRowid)
  124969. ){
  124970. reg = ++pParse->nMem;
  124971. pParse->nMem += pIdx->nColumn;
  124972. }else{
  124973. reg = 0;
  124974. for(i=0; i<pIdx->nKeyCol; i++){
  124975. if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){
  124976. reg = ++pParse->nMem;
  124977. pParse->nMem += pIdx->nColumn;
  124978. if( onError==OE_Default && pIdx->onError==OE_Replace ){
  124979. bReplace = 1;
  124980. }
  124981. break;
  124982. }
  124983. }
  124984. }
  124985. if( reg==0 ) aToOpen[j+1] = 0;
  124986. aRegIdx[j] = reg;
  124987. }
  124988. if( bReplace ){
  124989. /* If REPLACE conflict resolution might be invoked, open cursors on all
  124990. ** indexes in case they are needed to delete records. */
  124991. memset(aToOpen, 1, nIdx+1);
  124992. }
  124993. /* Begin generating code. */
  124994. v = sqlite3GetVdbe(pParse);
  124995. if( v==0 ) goto update_cleanup;
  124996. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  124997. sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
  124998. /* Allocate required registers. */
  124999. if( !IsVirtual(pTab) ){
  125000. regRowSet = ++pParse->nMem;
  125001. regOldRowid = regNewRowid = ++pParse->nMem;
  125002. if( chngPk || pTrigger || hasFK ){
  125003. regOld = pParse->nMem + 1;
  125004. pParse->nMem += pTab->nCol;
  125005. }
  125006. if( chngKey || pTrigger || hasFK ){
  125007. regNewRowid = ++pParse->nMem;
  125008. }
  125009. regNew = pParse->nMem + 1;
  125010. pParse->nMem += pTab->nCol;
  125011. }
  125012. /* Start the view context. */
  125013. if( isView ){
  125014. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  125015. }
  125016. /* If we are trying to update a view, realize that view into
  125017. ** an ephemeral table.
  125018. */
  125019. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  125020. if( isView ){
  125021. sqlite3MaterializeView(pParse, pTab,
  125022. pWhere, pOrderBy, pLimit, iDataCur
  125023. );
  125024. pOrderBy = 0;
  125025. pLimit = 0;
  125026. }
  125027. #endif
  125028. /* Resolve the column names in all the expressions in the
  125029. ** WHERE clause.
  125030. */
  125031. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  125032. goto update_cleanup;
  125033. }
  125034. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125035. /* Virtual tables must be handled separately */
  125036. if( IsVirtual(pTab) ){
  125037. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  125038. pWhere, onError);
  125039. goto update_cleanup;
  125040. }
  125041. #endif
  125042. /* Jump to labelBreak to abandon further processing of this UPDATE */
  125043. labelContinue = labelBreak = sqlite3VdbeMakeLabel(pParse);
  125044. /* Not an UPSERT. Normal processing. Begin by
  125045. ** initialize the count of updated rows */
  125046. if( (db->flags&SQLITE_CountRows)!=0
  125047. && !pParse->pTriggerTab
  125048. && !pParse->nested
  125049. && pUpsert==0
  125050. ){
  125051. regRowCount = ++pParse->nMem;
  125052. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  125053. }
  125054. if( HasRowid(pTab) ){
  125055. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  125056. }else{
  125057. assert( pPk!=0 );
  125058. nPk = pPk->nKeyCol;
  125059. iPk = pParse->nMem+1;
  125060. pParse->nMem += nPk;
  125061. regKey = ++pParse->nMem;
  125062. if( pUpsert==0 ){
  125063. iEph = pParse->nTab++;
  125064. sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
  125065. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  125066. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  125067. }
  125068. }
  125069. if( pUpsert ){
  125070. /* If this is an UPSERT, then all cursors have already been opened by
  125071. ** the outer INSERT and the data cursor should be pointing at the row
  125072. ** that is to be updated. So bypass the code that searches for the
  125073. ** row(s) to be updated.
  125074. */
  125075. pWInfo = 0;
  125076. eOnePass = ONEPASS_SINGLE;
  125077. sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
  125078. }else{
  125079. /* Begin the database scan.
  125080. **
  125081. ** Do not consider a single-pass strategy for a multi-row update if
  125082. ** there are any triggers or foreign keys to process, or rows may
  125083. ** be deleted as a result of REPLACE conflict handling. Any of these
  125084. ** things might disturb a cursor being used to scan through the table
  125085. ** or index, causing a single-pass approach to malfunction. */
  125086. flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
  125087. if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
  125088. flags |= WHERE_ONEPASS_MULTIROW;
  125089. }
  125090. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
  125091. if( pWInfo==0 ) goto update_cleanup;
  125092. /* A one-pass strategy that might update more than one row may not
  125093. ** be used if any column of the index used for the scan is being
  125094. ** updated. Otherwise, if there is an index on "b", statements like
  125095. ** the following could create an infinite loop:
  125096. **
  125097. ** UPDATE t1 SET b=b+1 WHERE b>?
  125098. **
  125099. ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
  125100. ** strategy that uses an index for which one or more columns are being
  125101. ** updated. */
  125102. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  125103. if( eOnePass!=ONEPASS_SINGLE ){
  125104. sqlite3MultiWrite(pParse);
  125105. if( eOnePass==ONEPASS_MULTI ){
  125106. int iCur = aiCurOnePass[1];
  125107. if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
  125108. eOnePass = ONEPASS_OFF;
  125109. }
  125110. assert( iCur!=iDataCur || !HasRowid(pTab) );
  125111. }
  125112. }
  125113. }
  125114. if( HasRowid(pTab) ){
  125115. /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
  125116. ** mode, write the rowid into the FIFO. In either of the one-pass modes,
  125117. ** leave it in register regOldRowid. */
  125118. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  125119. if( eOnePass==ONEPASS_OFF ){
  125120. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  125121. }
  125122. }else{
  125123. /* Read the PK of the current row into an array of registers. In
  125124. ** ONEPASS_OFF mode, serialize the array into a record and store it in
  125125. ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
  125126. ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
  125127. ** is not required) and leave the PK fields in the array of registers. */
  125128. for(i=0; i<nPk; i++){
  125129. assert( pPk->aiColumn[i]>=0 );
  125130. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
  125131. }
  125132. if( eOnePass ){
  125133. if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
  125134. nKey = nPk;
  125135. regKey = iPk;
  125136. }else{
  125137. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  125138. sqlite3IndexAffinityStr(db, pPk), nPk);
  125139. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
  125140. }
  125141. }
  125142. if( pUpsert==0 ){
  125143. if( eOnePass!=ONEPASS_MULTI ){
  125144. sqlite3WhereEnd(pWInfo);
  125145. }
  125146. if( !isView ){
  125147. int addrOnce = 0;
  125148. /* Open every index that needs updating. */
  125149. if( eOnePass!=ONEPASS_OFF ){
  125150. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  125151. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  125152. }
  125153. if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
  125154. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  125155. }
  125156. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
  125157. aToOpen, 0, 0);
  125158. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  125159. }
  125160. /* Top of the update loop */
  125161. if( eOnePass!=ONEPASS_OFF ){
  125162. if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
  125163. assert( pPk );
  125164. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
  125165. VdbeCoverage(v);
  125166. }
  125167. if( eOnePass!=ONEPASS_SINGLE ){
  125168. labelContinue = sqlite3VdbeMakeLabel(pParse);
  125169. }
  125170. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  125171. VdbeCoverageIf(v, pPk==0);
  125172. VdbeCoverageIf(v, pPk!=0);
  125173. }else if( pPk ){
  125174. labelContinue = sqlite3VdbeMakeLabel(pParse);
  125175. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  125176. addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
  125177. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  125178. VdbeCoverage(v);
  125179. }else{
  125180. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet,labelBreak,
  125181. regOldRowid);
  125182. VdbeCoverage(v);
  125183. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  125184. VdbeCoverage(v);
  125185. }
  125186. }
  125187. /* If the rowid value will change, set register regNewRowid to
  125188. ** contain the new value. If the rowid is not being modified,
  125189. ** then regNewRowid is the same register as regOldRowid, which is
  125190. ** already populated. */
  125191. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  125192. if( chngRowid ){
  125193. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  125194. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  125195. }
  125196. /* Compute the old pre-UPDATE content of the row being changed, if that
  125197. ** information is needed */
  125198. if( chngPk || hasFK || pTrigger ){
  125199. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  125200. oldmask |= sqlite3TriggerColmask(pParse,
  125201. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  125202. );
  125203. for(i=0; i<pTab->nCol; i++){
  125204. if( oldmask==0xffffffff
  125205. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  125206. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  125207. ){
  125208. testcase( oldmask!=0xffffffff && i==31 );
  125209. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  125210. }else{
  125211. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  125212. }
  125213. }
  125214. if( chngRowid==0 && pPk==0 ){
  125215. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  125216. }
  125217. }
  125218. /* Populate the array of registers beginning at regNew with the new
  125219. ** row data. This array is used to check constants, create the new
  125220. ** table and index records, and as the values for any new.* references
  125221. ** made by triggers.
  125222. **
  125223. ** If there are one or more BEFORE triggers, then do not populate the
  125224. ** registers associated with columns that are (a) not modified by
  125225. ** this UPDATE statement and (b) not accessed by new.* references. The
  125226. ** values for registers not modified by the UPDATE must be reloaded from
  125227. ** the database after the BEFORE triggers are fired anyway (as the trigger
  125228. ** may have modified them). So not loading those that are not going to
  125229. ** be used eliminates some redundant opcodes.
  125230. */
  125231. newmask = sqlite3TriggerColmask(
  125232. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  125233. );
  125234. for(i=0; i<pTab->nCol; i++){
  125235. if( i==pTab->iPKey ){
  125236. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  125237. }else{
  125238. j = aXRef[i];
  125239. if( j>=0 ){
  125240. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  125241. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  125242. /* This branch loads the value of a column that will not be changed
  125243. ** into a register. This is done if there are no BEFORE triggers, or
  125244. ** if there are one or more BEFORE triggers that use this value via
  125245. ** a new.* reference in a trigger program.
  125246. */
  125247. testcase( i==31 );
  125248. testcase( i==32 );
  125249. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  125250. }else{
  125251. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  125252. }
  125253. }
  125254. }
  125255. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  125256. ** verified. One could argue that this is wrong.
  125257. */
  125258. if( tmask&TRIGGER_BEFORE ){
  125259. sqlite3TableAffinity(v, pTab, regNew);
  125260. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  125261. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  125262. /* The row-trigger may have deleted the row being updated. In this
  125263. ** case, jump to the next row. No updates or AFTER triggers are
  125264. ** required. This behavior - what happens when the row being updated
  125265. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  125266. ** documentation.
  125267. */
  125268. if( pPk ){
  125269. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  125270. VdbeCoverage(v);
  125271. }else{
  125272. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  125273. VdbeCoverage(v);
  125274. }
  125275. /* After-BEFORE-trigger-reload-loop:
  125276. ** If it did not delete it, the BEFORE trigger may still have modified
  125277. ** some of the columns of the row being updated. Load the values for
  125278. ** all columns not modified by the update statement into their registers
  125279. ** in case this has happened. Only unmodified columns are reloaded.
  125280. ** The values computed for modified columns use the values before the
  125281. ** BEFORE trigger runs. See test case trigger1-18.0 (added 2018-04-26)
  125282. ** for an example.
  125283. */
  125284. for(i=0; i<pTab->nCol; i++){
  125285. if( aXRef[i]<0 && i!=pTab->iPKey ){
  125286. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  125287. }
  125288. }
  125289. }
  125290. if( !isView ){
  125291. int addr1 = 0; /* Address of jump instruction */
  125292. /* Do constraint checks. */
  125293. assert( regOldRowid>0 );
  125294. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  125295. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
  125296. aXRef, 0);
  125297. /* Do FK constraint checks. */
  125298. if( hasFK ){
  125299. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  125300. }
  125301. /* Delete the index entries associated with the current record. */
  125302. if( bReplace || chngKey ){
  125303. if( pPk ){
  125304. addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  125305. }else{
  125306. addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  125307. }
  125308. VdbeCoverageNeverTaken(v);
  125309. }
  125310. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  125311. /* If changing the rowid value, or if there are foreign key constraints
  125312. ** to process, delete the old record. Otherwise, add a noop OP_Delete
  125313. ** to invoke the pre-update hook.
  125314. **
  125315. ** That (regNew==regnewRowid+1) is true is also important for the
  125316. ** pre-update hook. If the caller invokes preupdate_new(), the returned
  125317. ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
  125318. ** is the column index supplied by the user.
  125319. */
  125320. assert( regNew==regNewRowid+1 );
  125321. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  125322. sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
  125323. OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
  125324. regNewRowid
  125325. );
  125326. if( eOnePass==ONEPASS_MULTI ){
  125327. assert( hasFK==0 && chngKey==0 );
  125328. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  125329. }
  125330. if( !pParse->nested ){
  125331. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  125332. }
  125333. #else
  125334. if( hasFK>1 || chngKey ){
  125335. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  125336. }
  125337. #endif
  125338. if( bReplace || chngKey ){
  125339. sqlite3VdbeJumpHere(v, addr1);
  125340. }
  125341. if( hasFK ){
  125342. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  125343. }
  125344. /* Insert the new index entries and the new record. */
  125345. sqlite3CompleteInsertion(
  125346. pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
  125347. OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
  125348. 0, 0
  125349. );
  125350. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  125351. ** handle rows (possibly in other tables) that refer via a foreign key
  125352. ** to the row just updated. */
  125353. if( hasFK ){
  125354. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  125355. }
  125356. }
  125357. /* Increment the row counter
  125358. */
  125359. if( regRowCount ){
  125360. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  125361. }
  125362. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  125363. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  125364. /* Repeat the above with the next record to be updated, until
  125365. ** all record selected by the WHERE clause have been updated.
  125366. */
  125367. if( eOnePass==ONEPASS_SINGLE ){
  125368. /* Nothing to do at end-of-loop for a single-pass */
  125369. }else if( eOnePass==ONEPASS_MULTI ){
  125370. sqlite3VdbeResolveLabel(v, labelContinue);
  125371. sqlite3WhereEnd(pWInfo);
  125372. }else if( pPk ){
  125373. sqlite3VdbeResolveLabel(v, labelContinue);
  125374. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  125375. }else{
  125376. sqlite3VdbeGoto(v, labelContinue);
  125377. }
  125378. sqlite3VdbeResolveLabel(v, labelBreak);
  125379. /* Update the sqlite_sequence table by storing the content of the
  125380. ** maximum rowid counter values recorded while inserting into
  125381. ** autoincrement tables.
  125382. */
  125383. if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
  125384. sqlite3AutoincrementEnd(pParse);
  125385. }
  125386. /*
  125387. ** Return the number of rows that were changed, if we are tracking
  125388. ** that information.
  125389. */
  125390. if( regRowCount ){
  125391. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  125392. sqlite3VdbeSetNumCols(v, 1);
  125393. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  125394. }
  125395. update_cleanup:
  125396. sqlite3AuthContextPop(&sContext);
  125397. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  125398. sqlite3SrcListDelete(db, pTabList);
  125399. sqlite3ExprListDelete(db, pChanges);
  125400. sqlite3ExprDelete(db, pWhere);
  125401. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  125402. sqlite3ExprListDelete(db, pOrderBy);
  125403. sqlite3ExprDelete(db, pLimit);
  125404. #endif
  125405. return;
  125406. }
  125407. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  125408. ** they may interfere with compilation of other functions in this file
  125409. ** (or in another file, if this file becomes part of the amalgamation). */
  125410. #ifdef isView
  125411. #undef isView
  125412. #endif
  125413. #ifdef pTrigger
  125414. #undef pTrigger
  125415. #endif
  125416. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125417. /*
  125418. ** Generate code for an UPDATE of a virtual table.
  125419. **
  125420. ** There are two possible strategies - the default and the special
  125421. ** "onepass" strategy. Onepass is only used if the virtual table
  125422. ** implementation indicates that pWhere may match at most one row.
  125423. **
  125424. ** The default strategy is to create an ephemeral table that contains
  125425. ** for each row to be changed:
  125426. **
  125427. ** (A) The original rowid of that row.
  125428. ** (B) The revised rowid for the row.
  125429. ** (C) The content of every column in the row.
  125430. **
  125431. ** Then loop through the contents of this ephemeral table executing a
  125432. ** VUpdate for each row. When finished, drop the ephemeral table.
  125433. **
  125434. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  125435. ** stores the same values (A, B and C above) in a register array and
  125436. ** makes a single invocation of VUpdate.
  125437. */
  125438. static void updateVirtualTable(
  125439. Parse *pParse, /* The parsing context */
  125440. SrcList *pSrc, /* The virtual table to be modified */
  125441. Table *pTab, /* The virtual table */
  125442. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  125443. Expr *pRowid, /* Expression used to recompute the rowid */
  125444. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  125445. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  125446. int onError /* ON CONFLICT strategy */
  125447. ){
  125448. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  125449. int ephemTab; /* Table holding the result of the SELECT */
  125450. int i; /* Loop counter */
  125451. sqlite3 *db = pParse->db; /* Database connection */
  125452. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  125453. WhereInfo *pWInfo;
  125454. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  125455. int regArg; /* First register in VUpdate arg array */
  125456. int regRec; /* Register in which to assemble record */
  125457. int regRowid; /* Register for ephem table rowid */
  125458. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  125459. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  125460. int eOnePass; /* True to use onepass strategy */
  125461. int addr; /* Address of OP_OpenEphemeral */
  125462. /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
  125463. ** create and open the ephemeral table in which the records created from
  125464. ** these arguments will be temporarily stored. */
  125465. assert( v );
  125466. ephemTab = pParse->nTab++;
  125467. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  125468. regArg = pParse->nMem + 1;
  125469. pParse->nMem += nArg;
  125470. regRec = ++pParse->nMem;
  125471. regRowid = ++pParse->nMem;
  125472. /* Start scanning the virtual table */
  125473. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  125474. if( pWInfo==0 ) return;
  125475. /* Populate the argument registers. */
  125476. for(i=0; i<pTab->nCol; i++){
  125477. if( aXRef[i]>=0 ){
  125478. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  125479. }else{
  125480. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  125481. sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* Enable sqlite3_vtab_nochange() */
  125482. }
  125483. }
  125484. if( HasRowid(pTab) ){
  125485. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  125486. if( pRowid ){
  125487. sqlite3ExprCode(pParse, pRowid, regArg+1);
  125488. }else{
  125489. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  125490. }
  125491. }else{
  125492. Index *pPk; /* PRIMARY KEY index */
  125493. i16 iPk; /* PRIMARY KEY column */
  125494. pPk = sqlite3PrimaryKeyIndex(pTab);
  125495. assert( pPk!=0 );
  125496. assert( pPk->nKeyCol==1 );
  125497. iPk = pPk->aiColumn[0];
  125498. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
  125499. sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
  125500. }
  125501. eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  125502. /* There is no ONEPASS_MULTI on virtual tables */
  125503. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  125504. if( eOnePass ){
  125505. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  125506. ** above. */
  125507. sqlite3VdbeChangeToNoop(v, addr);
  125508. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  125509. }else{
  125510. /* Create a record from the argument register contents and insert it into
  125511. ** the ephemeral table. */
  125512. sqlite3MultiWrite(pParse);
  125513. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  125514. #ifdef SQLITE_DEBUG
  125515. /* Signal an assert() within OP_MakeRecord that it is allowed to
  125516. ** accept no-change records with serial_type 10 */
  125517. sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
  125518. #endif
  125519. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  125520. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  125521. }
  125522. if( eOnePass==ONEPASS_OFF ){
  125523. /* End the virtual table scan */
  125524. sqlite3WhereEnd(pWInfo);
  125525. /* Begin scannning through the ephemeral table. */
  125526. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  125527. /* Extract arguments from the current row of the ephemeral table and
  125528. ** invoke the VUpdate method. */
  125529. for(i=0; i<nArg; i++){
  125530. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  125531. }
  125532. }
  125533. sqlite3VtabMakeWritable(pParse, pTab);
  125534. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  125535. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  125536. sqlite3MayAbort(pParse);
  125537. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  125538. ** jump to here if the scan visited zero rows. */
  125539. if( eOnePass==ONEPASS_OFF ){
  125540. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  125541. sqlite3VdbeJumpHere(v, addr);
  125542. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  125543. }else{
  125544. sqlite3WhereEnd(pWInfo);
  125545. }
  125546. }
  125547. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  125548. /************** End of update.c **********************************************/
  125549. /************** Begin file upsert.c ******************************************/
  125550. /*
  125551. ** 2018-04-12
  125552. **
  125553. ** The author disclaims copyright to this source code. In place of
  125554. ** a legal notice, here is a blessing:
  125555. **
  125556. ** May you do good and not evil.
  125557. ** May you find forgiveness for yourself and forgive others.
  125558. ** May you share freely, never taking more than you give.
  125559. **
  125560. *************************************************************************
  125561. ** This file contains code to implement various aspects of UPSERT
  125562. ** processing and handling of the Upsert object.
  125563. */
  125564. /* #include "sqliteInt.h" */
  125565. #ifndef SQLITE_OMIT_UPSERT
  125566. /*
  125567. ** Free a list of Upsert objects
  125568. */
  125569. SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3 *db, Upsert *p){
  125570. if( p ){
  125571. sqlite3ExprListDelete(db, p->pUpsertTarget);
  125572. sqlite3ExprDelete(db, p->pUpsertTargetWhere);
  125573. sqlite3ExprListDelete(db, p->pUpsertSet);
  125574. sqlite3ExprDelete(db, p->pUpsertWhere);
  125575. sqlite3DbFree(db, p);
  125576. }
  125577. }
  125578. /*
  125579. ** Duplicate an Upsert object.
  125580. */
  125581. SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3 *db, Upsert *p){
  125582. if( p==0 ) return 0;
  125583. return sqlite3UpsertNew(db,
  125584. sqlite3ExprListDup(db, p->pUpsertTarget, 0),
  125585. sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),
  125586. sqlite3ExprListDup(db, p->pUpsertSet, 0),
  125587. sqlite3ExprDup(db, p->pUpsertWhere, 0)
  125588. );
  125589. }
  125590. /*
  125591. ** Create a new Upsert object.
  125592. */
  125593. SQLITE_PRIVATE Upsert *sqlite3UpsertNew(
  125594. sqlite3 *db, /* Determines which memory allocator to use */
  125595. ExprList *pTarget, /* Target argument to ON CONFLICT, or NULL */
  125596. Expr *pTargetWhere, /* Optional WHERE clause on the target */
  125597. ExprList *pSet, /* UPDATE columns, or NULL for a DO NOTHING */
  125598. Expr *pWhere /* WHERE clause for the ON CONFLICT UPDATE */
  125599. ){
  125600. Upsert *pNew;
  125601. pNew = sqlite3DbMallocRaw(db, sizeof(Upsert));
  125602. if( pNew==0 ){
  125603. sqlite3ExprListDelete(db, pTarget);
  125604. sqlite3ExprDelete(db, pTargetWhere);
  125605. sqlite3ExprListDelete(db, pSet);
  125606. sqlite3ExprDelete(db, pWhere);
  125607. return 0;
  125608. }else{
  125609. pNew->pUpsertTarget = pTarget;
  125610. pNew->pUpsertTargetWhere = pTargetWhere;
  125611. pNew->pUpsertSet = pSet;
  125612. pNew->pUpsertWhere = pWhere;
  125613. pNew->pUpsertIdx = 0;
  125614. }
  125615. return pNew;
  125616. }
  125617. /*
  125618. ** Analyze the ON CONFLICT clause described by pUpsert. Resolve all
  125619. ** symbols in the conflict-target.
  125620. **
  125621. ** Return SQLITE_OK if everything works, or an error code is something
  125622. ** is wrong.
  125623. */
  125624. SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(
  125625. Parse *pParse, /* The parsing context */
  125626. SrcList *pTabList, /* Table into which we are inserting */
  125627. Upsert *pUpsert /* The ON CONFLICT clauses */
  125628. ){
  125629. Table *pTab; /* That table into which we are inserting */
  125630. int rc; /* Result code */
  125631. int iCursor; /* Cursor used by pTab */
  125632. Index *pIdx; /* One of the indexes of pTab */
  125633. ExprList *pTarget; /* The conflict-target clause */
  125634. Expr *pTerm; /* One term of the conflict-target clause */
  125635. NameContext sNC; /* Context for resolving symbolic names */
  125636. Expr sCol[2]; /* Index column converted into an Expr */
  125637. assert( pTabList->nSrc==1 );
  125638. assert( pTabList->a[0].pTab!=0 );
  125639. assert( pUpsert!=0 );
  125640. assert( pUpsert->pUpsertTarget!=0 );
  125641. /* Resolve all symbolic names in the conflict-target clause, which
  125642. ** includes both the list of columns and the optional partial-index
  125643. ** WHERE clause.
  125644. */
  125645. memset(&sNC, 0, sizeof(sNC));
  125646. sNC.pParse = pParse;
  125647. sNC.pSrcList = pTabList;
  125648. rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
  125649. if( rc ) return rc;
  125650. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
  125651. if( rc ) return rc;
  125652. /* Check to see if the conflict target matches the rowid. */
  125653. pTab = pTabList->a[0].pTab;
  125654. pTarget = pUpsert->pUpsertTarget;
  125655. iCursor = pTabList->a[0].iCursor;
  125656. if( HasRowid(pTab)
  125657. && pTarget->nExpr==1
  125658. && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
  125659. && pTerm->iColumn==XN_ROWID
  125660. ){
  125661. /* The conflict-target is the rowid of the primary table */
  125662. assert( pUpsert->pUpsertIdx==0 );
  125663. return SQLITE_OK;
  125664. }
  125665. /* Initialize sCol[0..1] to be an expression parse tree for a
  125666. ** single column of an index. The sCol[0] node will be the TK_COLLATE
  125667. ** operator and sCol[1] will be the TK_COLUMN operator. Code below
  125668. ** will populate the specific collation and column number values
  125669. ** prior to comparing against the conflict-target expression.
  125670. */
  125671. memset(sCol, 0, sizeof(sCol));
  125672. sCol[0].op = TK_COLLATE;
  125673. sCol[0].pLeft = &sCol[1];
  125674. sCol[1].op = TK_COLUMN;
  125675. sCol[1].iTable = pTabList->a[0].iCursor;
  125676. /* Check for matches against other indexes */
  125677. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  125678. int ii, jj, nn;
  125679. if( !IsUniqueIndex(pIdx) ) continue;
  125680. if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
  125681. if( pIdx->pPartIdxWhere ){
  125682. if( pUpsert->pUpsertTargetWhere==0 ) continue;
  125683. if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
  125684. pIdx->pPartIdxWhere, iCursor)!=0 ){
  125685. continue;
  125686. }
  125687. }
  125688. nn = pIdx->nKeyCol;
  125689. for(ii=0; ii<nn; ii++){
  125690. Expr *pExpr;
  125691. sCol[0].u.zToken = (char*)pIdx->azColl[ii];
  125692. if( pIdx->aiColumn[ii]==XN_EXPR ){
  125693. assert( pIdx->aColExpr!=0 );
  125694. assert( pIdx->aColExpr->nExpr>ii );
  125695. pExpr = pIdx->aColExpr->a[ii].pExpr;
  125696. if( pExpr->op!=TK_COLLATE ){
  125697. sCol[0].pLeft = pExpr;
  125698. pExpr = &sCol[0];
  125699. }
  125700. }else{
  125701. sCol[0].pLeft = &sCol[1];
  125702. sCol[1].iColumn = pIdx->aiColumn[ii];
  125703. pExpr = &sCol[0];
  125704. }
  125705. for(jj=0; jj<nn; jj++){
  125706. if( sqlite3ExprCompare(pParse, pTarget->a[jj].pExpr, pExpr,iCursor)<2 ){
  125707. break; /* Column ii of the index matches column jj of target */
  125708. }
  125709. }
  125710. if( jj>=nn ){
  125711. /* The target contains no match for column jj of the index */
  125712. break;
  125713. }
  125714. }
  125715. if( ii<nn ){
  125716. /* Column ii of the index did not match any term of the conflict target.
  125717. ** Continue the search with the next index. */
  125718. continue;
  125719. }
  125720. pUpsert->pUpsertIdx = pIdx;
  125721. return SQLITE_OK;
  125722. }
  125723. sqlite3ErrorMsg(pParse, "ON CONFLICT clause does not match any "
  125724. "PRIMARY KEY or UNIQUE constraint");
  125725. return SQLITE_ERROR;
  125726. }
  125727. /*
  125728. ** Generate bytecode that does an UPDATE as part of an upsert.
  125729. **
  125730. ** If pIdx is NULL, then the UNIQUE constraint that failed was the IPK.
  125731. ** In this case parameter iCur is a cursor open on the table b-tree that
  125732. ** currently points to the conflicting table row. Otherwise, if pIdx
  125733. ** is not NULL, then pIdx is the constraint that failed and iCur is a
  125734. ** cursor points to the conflicting row.
  125735. */
  125736. SQLITE_PRIVATE void sqlite3UpsertDoUpdate(
  125737. Parse *pParse, /* The parsing and code-generating context */
  125738. Upsert *pUpsert, /* The ON CONFLICT clause for the upsert */
  125739. Table *pTab, /* The table being updated */
  125740. Index *pIdx, /* The UNIQUE constraint that failed */
  125741. int iCur /* Cursor for pIdx (or pTab if pIdx==NULL) */
  125742. ){
  125743. Vdbe *v = pParse->pVdbe;
  125744. sqlite3 *db = pParse->db;
  125745. SrcList *pSrc; /* FROM clause for the UPDATE */
  125746. int iDataCur;
  125747. assert( v!=0 );
  125748. assert( pUpsert!=0 );
  125749. VdbeNoopComment((v, "Begin DO UPDATE of UPSERT"));
  125750. iDataCur = pUpsert->iDataCur;
  125751. if( pIdx && iCur!=iDataCur ){
  125752. if( HasRowid(pTab) ){
  125753. int regRowid = sqlite3GetTempReg(pParse);
  125754. sqlite3VdbeAddOp2(v, OP_IdxRowid, iCur, regRowid);
  125755. sqlite3VdbeAddOp3(v, OP_SeekRowid, iDataCur, 0, regRowid);
  125756. VdbeCoverage(v);
  125757. sqlite3ReleaseTempReg(pParse, regRowid);
  125758. }else{
  125759. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  125760. int nPk = pPk->nKeyCol;
  125761. int iPk = pParse->nMem+1;
  125762. int i;
  125763. pParse->nMem += nPk;
  125764. for(i=0; i<nPk; i++){
  125765. int k;
  125766. assert( pPk->aiColumn[i]>=0 );
  125767. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  125768. sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);
  125769. VdbeComment((v, "%s.%s", pIdx->zName,
  125770. pTab->aCol[pPk->aiColumn[i]].zName));
  125771. }
  125772. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  125773. i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);
  125774. VdbeCoverage(v);
  125775. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0,
  125776. "corrupt database", P4_STATIC);
  125777. sqlite3VdbeJumpHere(v, i);
  125778. }
  125779. }
  125780. /* pUpsert does not own pUpsertSrc - the outer INSERT statement does. So
  125781. ** we have to make a copy before passing it down into sqlite3Update() */
  125782. pSrc = sqlite3SrcListDup(db, pUpsert->pUpsertSrc, 0);
  125783. sqlite3Update(pParse, pSrc, pUpsert->pUpsertSet,
  125784. pUpsert->pUpsertWhere, OE_Abort, 0, 0, pUpsert);
  125785. pUpsert->pUpsertSet = 0; /* Will have been deleted by sqlite3Update() */
  125786. pUpsert->pUpsertWhere = 0; /* Will have been deleted by sqlite3Update() */
  125787. VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
  125788. }
  125789. #endif /* SQLITE_OMIT_UPSERT */
  125790. /************** End of upsert.c **********************************************/
  125791. /************** Begin file vacuum.c ******************************************/
  125792. /*
  125793. ** 2003 April 6
  125794. **
  125795. ** The author disclaims copyright to this source code. In place of
  125796. ** a legal notice, here is a blessing:
  125797. **
  125798. ** May you do good and not evil.
  125799. ** May you find forgiveness for yourself and forgive others.
  125800. ** May you share freely, never taking more than you give.
  125801. **
  125802. *************************************************************************
  125803. ** This file contains code used to implement the VACUUM command.
  125804. **
  125805. ** Most of the code in this file may be omitted by defining the
  125806. ** SQLITE_OMIT_VACUUM macro.
  125807. */
  125808. /* #include "sqliteInt.h" */
  125809. /* #include "vdbeInt.h" */
  125810. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  125811. /*
  125812. ** Execute zSql on database db.
  125813. **
  125814. ** If zSql returns rows, then each row will have exactly one
  125815. ** column. (This will only happen if zSql begins with "SELECT".)
  125816. ** Take each row of result and call execSql() again recursively.
  125817. **
  125818. ** The execSqlF() routine does the same thing, except it accepts
  125819. ** a format string as its third argument
  125820. */
  125821. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  125822. sqlite3_stmt *pStmt;
  125823. int rc;
  125824. /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
  125825. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  125826. if( rc!=SQLITE_OK ) return rc;
  125827. while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  125828. const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
  125829. assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
  125830. /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX,
  125831. ** or INSERT. Historically there have been attacks that first
  125832. ** corrupt the sqlite_master.sql field with other kinds of statements
  125833. ** then run VACUUM to get those statements to execute at inappropriate
  125834. ** times. */
  125835. if( zSubSql
  125836. && (strncmp(zSubSql,"CRE",3)==0 || strncmp(zSubSql,"INS",3)==0)
  125837. ){
  125838. rc = execSql(db, pzErrMsg, zSubSql);
  125839. if( rc!=SQLITE_OK ) break;
  125840. }
  125841. }
  125842. assert( rc!=SQLITE_ROW );
  125843. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  125844. if( rc ){
  125845. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  125846. }
  125847. (void)sqlite3_finalize(pStmt);
  125848. return rc;
  125849. }
  125850. static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
  125851. char *z;
  125852. va_list ap;
  125853. int rc;
  125854. va_start(ap, zSql);
  125855. z = sqlite3VMPrintf(db, zSql, ap);
  125856. va_end(ap);
  125857. if( z==0 ) return SQLITE_NOMEM;
  125858. rc = execSql(db, pzErrMsg, z);
  125859. sqlite3DbFree(db, z);
  125860. return rc;
  125861. }
  125862. /*
  125863. ** The VACUUM command is used to clean up the database,
  125864. ** collapse free space, etc. It is modelled after the VACUUM command
  125865. ** in PostgreSQL. The VACUUM command works as follows:
  125866. **
  125867. ** (1) Create a new transient database file
  125868. ** (2) Copy all content from the database being vacuumed into
  125869. ** the new transient database file
  125870. ** (3) Copy content from the transient database back into the
  125871. ** original database.
  125872. **
  125873. ** The transient database requires temporary disk space approximately
  125874. ** equal to the size of the original database. The copy operation of
  125875. ** step (3) requires additional temporary disk space approximately equal
  125876. ** to the size of the original database for the rollback journal.
  125877. ** Hence, temporary disk space that is approximately 2x the size of the
  125878. ** original database is required. Every page of the database is written
  125879. ** approximately 3 times: Once for step (2) and twice for step (3).
  125880. ** Two writes per page are required in step (3) because the original
  125881. ** database content must be written into the rollback journal prior to
  125882. ** overwriting the database with the vacuumed content.
  125883. **
  125884. ** Only 1x temporary space and only 1x writes would be required if
  125885. ** the copy of step (3) were replaced by deleting the original database
  125886. ** and renaming the transient database as the original. But that will
  125887. ** not work if other processes are attached to the original database.
  125888. ** And a power loss in between deleting the original and renaming the
  125889. ** transient would cause the database file to appear to be deleted
  125890. ** following reboot.
  125891. */
  125892. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm, Expr *pInto){
  125893. Vdbe *v = sqlite3GetVdbe(pParse);
  125894. int iDb = 0;
  125895. if( v==0 ) goto build_vacuum_end;
  125896. if( pNm ){
  125897. #ifndef SQLITE_BUG_COMPATIBLE_20160819
  125898. /* Default behavior: Report an error if the argument to VACUUM is
  125899. ** not recognized */
  125900. iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
  125901. if( iDb<0 ) goto build_vacuum_end;
  125902. #else
  125903. /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
  125904. ** to VACUUM are silently ignored. This is a back-out of a bug fix that
  125905. ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
  125906. ** The buggy behavior is required for binary compatibility with some
  125907. ** legacy applications. */
  125908. iDb = sqlite3FindDb(pParse->db, pNm);
  125909. if( iDb<0 ) iDb = 0;
  125910. #endif
  125911. }
  125912. if( iDb!=1 ){
  125913. int iIntoReg = 0;
  125914. if( pInto && sqlite3ResolveSelfReference(pParse,0,0,pInto,0)==0 ){
  125915. iIntoReg = ++pParse->nMem;
  125916. sqlite3ExprCode(pParse, pInto, iIntoReg);
  125917. }
  125918. sqlite3VdbeAddOp2(v, OP_Vacuum, iDb, iIntoReg);
  125919. sqlite3VdbeUsesBtree(v, iDb);
  125920. }
  125921. build_vacuum_end:
  125922. sqlite3ExprDelete(pParse->db, pInto);
  125923. return;
  125924. }
  125925. /*
  125926. ** This routine implements the OP_Vacuum opcode of the VDBE.
  125927. */
  125928. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
  125929. char **pzErrMsg, /* Write error message here */
  125930. sqlite3 *db, /* Database connection */
  125931. int iDb, /* Which attached DB to vacuum */
  125932. sqlite3_value *pOut /* Write results here, if not NULL. VACUUM INTO */
  125933. ){
  125934. int rc = SQLITE_OK; /* Return code from service routines */
  125935. Btree *pMain; /* The database being vacuumed */
  125936. Btree *pTemp; /* The temporary database we vacuum into */
  125937. u32 saved_mDbFlags; /* Saved value of db->mDbFlags */
  125938. u64 saved_flags; /* Saved value of db->flags */
  125939. int saved_nChange; /* Saved value of db->nChange */
  125940. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  125941. u32 saved_openFlags; /* Saved value of db->openFlags */
  125942. u8 saved_mTrace; /* Saved trace settings */
  125943. Db *pDb = 0; /* Database to detach at end of vacuum */
  125944. int isMemDb; /* True if vacuuming a :memory: database */
  125945. int nRes; /* Bytes of reserved space at the end of each page */
  125946. int nDb; /* Number of attached databases */
  125947. const char *zDbMain; /* Schema name of database to vacuum */
  125948. const char *zOut; /* Name of output file */
  125949. if( !db->autoCommit ){
  125950. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  125951. return SQLITE_ERROR; /* IMP: R-12218-18073 */
  125952. }
  125953. if( db->nVdbeActive>1 ){
  125954. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  125955. return SQLITE_ERROR; /* IMP: R-15610-35227 */
  125956. }
  125957. saved_openFlags = db->openFlags;
  125958. if( pOut ){
  125959. if( sqlite3_value_type(pOut)!=SQLITE_TEXT ){
  125960. sqlite3SetString(pzErrMsg, db, "non-text filename");
  125961. return SQLITE_ERROR;
  125962. }
  125963. zOut = (const char*)sqlite3_value_text(pOut);
  125964. db->openFlags &= ~SQLITE_OPEN_READONLY;
  125965. db->openFlags |= SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
  125966. }else{
  125967. zOut = "";
  125968. }
  125969. /* Save the current value of the database flags so that it can be
  125970. ** restored before returning. Then set the writable-schema flag, and
  125971. ** disable CHECK and foreign key constraints. */
  125972. saved_flags = db->flags;
  125973. saved_mDbFlags = db->mDbFlags;
  125974. saved_nChange = db->nChange;
  125975. saved_nTotalChange = db->nTotalChange;
  125976. saved_mTrace = db->mTrace;
  125977. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
  125978. db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
  125979. db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder
  125980. | SQLITE_Defensive | SQLITE_CountRows);
  125981. db->mTrace = 0;
  125982. zDbMain = db->aDb[iDb].zDbSName;
  125983. pMain = db->aDb[iDb].pBt;
  125984. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  125985. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  125986. ** can be set to 'off' for this file, as it is not recovered if a crash
  125987. ** occurs anyway. The integrity of the database is maintained by a
  125988. ** (possibly synchronous) transaction opened on the main database before
  125989. ** sqlite3BtreeCopyFile() is called.
  125990. **
  125991. ** An optimisation would be to use a non-journaled pager.
  125992. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  125993. ** that actually made the VACUUM run slower. Very little journalling
  125994. ** actually occurs when doing a vacuum since the vacuum_db is initially
  125995. ** empty. Only the journal header is written. Apparently it takes more
  125996. ** time to parse and run the PRAGMA to turn journalling off than it does
  125997. ** to write the journal header file.
  125998. */
  125999. nDb = db->nDb;
  126000. rc = execSqlF(db, pzErrMsg, "ATTACH %Q AS vacuum_db", zOut);
  126001. db->openFlags = saved_openFlags;
  126002. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126003. assert( (db->nDb-1)==nDb );
  126004. pDb = &db->aDb[nDb];
  126005. assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
  126006. pTemp = pDb->pBt;
  126007. if( pOut ){
  126008. sqlite3_file *id = sqlite3PagerFile(sqlite3BtreePager(pTemp));
  126009. i64 sz = 0;
  126010. if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){
  126011. rc = SQLITE_ERROR;
  126012. sqlite3SetString(pzErrMsg, db, "output file already exists");
  126013. goto end_of_vacuum;
  126014. }
  126015. db->mDbFlags |= DBFLAG_VacuumInto;
  126016. }
  126017. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  126018. /* A VACUUM cannot change the pagesize of an encrypted database. */
  126019. #ifdef SQLITE_HAS_CODEC
  126020. if( db->nextPagesize ){
  126021. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  126022. int nKey;
  126023. char *zKey;
  126024. sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
  126025. if( nKey ) db->nextPagesize = 0;
  126026. }
  126027. #endif
  126028. sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
  126029. sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
  126030. sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
  126031. /* Begin a transaction and take an exclusive lock on the main database
  126032. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  126033. ** to ensure that we do not try to change the page-size on a WAL database.
  126034. */
  126035. rc = execSql(db, pzErrMsg, "BEGIN");
  126036. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126037. rc = sqlite3BtreeBeginTrans(pMain, pOut==0 ? 2 : 0, 0);
  126038. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126039. /* Do not attempt to change the page size for a WAL database */
  126040. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  126041. ==PAGER_JOURNALMODE_WAL ){
  126042. db->nextPagesize = 0;
  126043. }
  126044. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  126045. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  126046. || NEVER(db->mallocFailed)
  126047. ){
  126048. rc = SQLITE_NOMEM_BKPT;
  126049. goto end_of_vacuum;
  126050. }
  126051. #ifndef SQLITE_OMIT_AUTOVACUUM
  126052. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  126053. sqlite3BtreeGetAutoVacuum(pMain));
  126054. #endif
  126055. /* Query the schema of the main database. Create a mirror schema
  126056. ** in the temporary database.
  126057. */
  126058. db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
  126059. rc = execSqlF(db, pzErrMsg,
  126060. "SELECT sql FROM \"%w\".sqlite_master"
  126061. " WHERE type='table'AND name<>'sqlite_sequence'"
  126062. " AND coalesce(rootpage,1)>0",
  126063. zDbMain
  126064. );
  126065. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126066. rc = execSqlF(db, pzErrMsg,
  126067. "SELECT sql FROM \"%w\".sqlite_master"
  126068. " WHERE type='index'",
  126069. zDbMain
  126070. );
  126071. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126072. db->init.iDb = 0;
  126073. /* Loop through the tables in the main database. For each, do
  126074. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  126075. ** the contents to the temporary database.
  126076. */
  126077. rc = execSqlF(db, pzErrMsg,
  126078. "SELECT'INSERT INTO vacuum_db.'||quote(name)"
  126079. "||' SELECT*FROM\"%w\".'||quote(name)"
  126080. "FROM vacuum_db.sqlite_master "
  126081. "WHERE type='table'AND coalesce(rootpage,1)>0",
  126082. zDbMain
  126083. );
  126084. assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
  126085. db->mDbFlags &= ~DBFLAG_Vacuum;
  126086. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126087. /* Copy the triggers, views, and virtual tables from the main database
  126088. ** over to the temporary database. None of these objects has any
  126089. ** associated storage, so all we have to do is copy their entries
  126090. ** from the SQLITE_MASTER table.
  126091. */
  126092. rc = execSqlF(db, pzErrMsg,
  126093. "INSERT INTO vacuum_db.sqlite_master"
  126094. " SELECT*FROM \"%w\".sqlite_master"
  126095. " WHERE type IN('view','trigger')"
  126096. " OR(type='table'AND rootpage=0)",
  126097. zDbMain
  126098. );
  126099. if( rc ) goto end_of_vacuum;
  126100. /* At this point, there is a write transaction open on both the
  126101. ** vacuum database and the main database. Assuming no error occurs,
  126102. ** both transactions are closed by this block - the main database
  126103. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  126104. ** call to sqlite3BtreeCommit().
  126105. */
  126106. {
  126107. u32 meta;
  126108. int i;
  126109. /* This array determines which meta meta values are preserved in the
  126110. ** vacuum. Even entries are the meta value number and odd entries
  126111. ** are an increment to apply to the meta value after the vacuum.
  126112. ** The increment is used to increase the schema cookie so that other
  126113. ** connections to the same database will know to reread the schema.
  126114. */
  126115. static const unsigned char aCopy[] = {
  126116. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  126117. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  126118. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  126119. BTREE_USER_VERSION, 0, /* Preserve the user version */
  126120. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  126121. };
  126122. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  126123. assert( pOut!=0 || 1==sqlite3BtreeIsInTrans(pMain) );
  126124. /* Copy Btree meta values */
  126125. for(i=0; i<ArraySize(aCopy); i+=2){
  126126. /* GetMeta() and UpdateMeta() cannot fail in this context because
  126127. ** we already have page 1 loaded into cache and marked dirty. */
  126128. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  126129. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  126130. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  126131. }
  126132. if( pOut==0 ){
  126133. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  126134. }
  126135. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126136. rc = sqlite3BtreeCommit(pTemp);
  126137. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  126138. #ifndef SQLITE_OMIT_AUTOVACUUM
  126139. if( pOut==0 ){
  126140. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  126141. }
  126142. #endif
  126143. }
  126144. assert( rc==SQLITE_OK );
  126145. if( pOut==0 ){
  126146. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  126147. }
  126148. end_of_vacuum:
  126149. /* Restore the original value of db->flags */
  126150. db->init.iDb = 0;
  126151. db->mDbFlags = saved_mDbFlags;
  126152. db->flags = saved_flags;
  126153. db->nChange = saved_nChange;
  126154. db->nTotalChange = saved_nTotalChange;
  126155. db->mTrace = saved_mTrace;
  126156. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  126157. /* Currently there is an SQL level transaction open on the vacuum
  126158. ** database. No locks are held on any other files (since the main file
  126159. ** was committed at the btree level). So it safe to end the transaction
  126160. ** by manually setting the autoCommit flag to true and detaching the
  126161. ** vacuum database. The vacuum_db journal file is deleted when the pager
  126162. ** is closed by the DETACH.
  126163. */
  126164. db->autoCommit = 1;
  126165. if( pDb ){
  126166. sqlite3BtreeClose(pDb->pBt);
  126167. pDb->pBt = 0;
  126168. pDb->pSchema = 0;
  126169. }
  126170. /* This both clears the schemas and reduces the size of the db->aDb[]
  126171. ** array. */
  126172. sqlite3ResetAllSchemasOfConnection(db);
  126173. return rc;
  126174. }
  126175. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  126176. /************** End of vacuum.c **********************************************/
  126177. /************** Begin file vtab.c ********************************************/
  126178. /*
  126179. ** 2006 June 10
  126180. **
  126181. ** The author disclaims copyright to this source code. In place of
  126182. ** a legal notice, here is a blessing:
  126183. **
  126184. ** May you do good and not evil.
  126185. ** May you find forgiveness for yourself and forgive others.
  126186. ** May you share freely, never taking more than you give.
  126187. **
  126188. *************************************************************************
  126189. ** This file contains code used to help implement virtual tables.
  126190. */
  126191. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126192. /* #include "sqliteInt.h" */
  126193. /*
  126194. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  126195. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  126196. ** this struct allocated on the stack. It is used by the implementation of
  126197. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  126198. ** are invoked only from within xCreate and xConnect methods.
  126199. */
  126200. struct VtabCtx {
  126201. VTable *pVTable; /* The virtual table being constructed */
  126202. Table *pTab; /* The Table object to which the virtual table belongs */
  126203. VtabCtx *pPrior; /* Parent context (if any) */
  126204. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  126205. };
  126206. /*
  126207. ** Construct and install a Module object for a virtual table. When this
  126208. ** routine is called, it is guaranteed that all appropriate locks are held
  126209. ** and the module is not already part of the connection.
  126210. */
  126211. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  126212. sqlite3 *db, /* Database in which module is registered */
  126213. const char *zName, /* Name assigned to this module */
  126214. const sqlite3_module *pModule, /* The definition of the module */
  126215. void *pAux, /* Context pointer for xCreate/xConnect */
  126216. void (*xDestroy)(void *) /* Module destructor function */
  126217. ){
  126218. Module *pMod;
  126219. int nName = sqlite3Strlen30(zName);
  126220. pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
  126221. if( pMod==0 ){
  126222. sqlite3OomFault(db);
  126223. }else{
  126224. Module *pDel;
  126225. char *zCopy = (char *)(&pMod[1]);
  126226. memcpy(zCopy, zName, nName+1);
  126227. pMod->zName = zCopy;
  126228. pMod->pModule = pModule;
  126229. pMod->pAux = pAux;
  126230. pMod->xDestroy = xDestroy;
  126231. pMod->pEpoTab = 0;
  126232. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  126233. assert( pDel==0 || pDel==pMod );
  126234. if( pDel ){
  126235. sqlite3OomFault(db);
  126236. sqlite3DbFree(db, pDel);
  126237. pMod = 0;
  126238. }
  126239. }
  126240. return pMod;
  126241. }
  126242. /*
  126243. ** The actual function that does the work of creating a new module.
  126244. ** This function implements the sqlite3_create_module() and
  126245. ** sqlite3_create_module_v2() interfaces.
  126246. */
  126247. static int createModule(
  126248. sqlite3 *db, /* Database in which module is registered */
  126249. const char *zName, /* Name assigned to this module */
  126250. const sqlite3_module *pModule, /* The definition of the module */
  126251. void *pAux, /* Context pointer for xCreate/xConnect */
  126252. void (*xDestroy)(void *) /* Module destructor function */
  126253. ){
  126254. int rc = SQLITE_OK;
  126255. sqlite3_mutex_enter(db->mutex);
  126256. if( sqlite3HashFind(&db->aModule, zName) ){
  126257. rc = SQLITE_MISUSE_BKPT;
  126258. }else{
  126259. (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
  126260. }
  126261. rc = sqlite3ApiExit(db, rc);
  126262. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  126263. sqlite3_mutex_leave(db->mutex);
  126264. return rc;
  126265. }
  126266. /*
  126267. ** External API function used to create a new virtual-table module.
  126268. */
  126269. SQLITE_API int sqlite3_create_module(
  126270. sqlite3 *db, /* Database in which module is registered */
  126271. const char *zName, /* Name assigned to this module */
  126272. const sqlite3_module *pModule, /* The definition of the module */
  126273. void *pAux /* Context pointer for xCreate/xConnect */
  126274. ){
  126275. #ifdef SQLITE_ENABLE_API_ARMOR
  126276. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  126277. #endif
  126278. return createModule(db, zName, pModule, pAux, 0);
  126279. }
  126280. /*
  126281. ** External API function used to create a new virtual-table module.
  126282. */
  126283. SQLITE_API int sqlite3_create_module_v2(
  126284. sqlite3 *db, /* Database in which module is registered */
  126285. const char *zName, /* Name assigned to this module */
  126286. const sqlite3_module *pModule, /* The definition of the module */
  126287. void *pAux, /* Context pointer for xCreate/xConnect */
  126288. void (*xDestroy)(void *) /* Module destructor function */
  126289. ){
  126290. #ifdef SQLITE_ENABLE_API_ARMOR
  126291. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  126292. #endif
  126293. return createModule(db, zName, pModule, pAux, xDestroy);
  126294. }
  126295. /*
  126296. ** Lock the virtual table so that it cannot be disconnected.
  126297. ** Locks nest. Every lock should have a corresponding unlock.
  126298. ** If an unlock is omitted, resources leaks will occur.
  126299. **
  126300. ** If a disconnect is attempted while a virtual table is locked,
  126301. ** the disconnect is deferred until all locks have been removed.
  126302. */
  126303. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  126304. pVTab->nRef++;
  126305. }
  126306. /*
  126307. ** pTab is a pointer to a Table structure representing a virtual-table.
  126308. ** Return a pointer to the VTable object used by connection db to access
  126309. ** this virtual-table, if one has been created, or NULL otherwise.
  126310. */
  126311. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  126312. VTable *pVtab;
  126313. assert( IsVirtual(pTab) );
  126314. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  126315. return pVtab;
  126316. }
  126317. /*
  126318. ** Decrement the ref-count on a virtual table object. When the ref-count
  126319. ** reaches zero, call the xDisconnect() method to delete the object.
  126320. */
  126321. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  126322. sqlite3 *db = pVTab->db;
  126323. assert( db );
  126324. assert( pVTab->nRef>0 );
  126325. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  126326. pVTab->nRef--;
  126327. if( pVTab->nRef==0 ){
  126328. sqlite3_vtab *p = pVTab->pVtab;
  126329. if( p ){
  126330. p->pModule->xDisconnect(p);
  126331. }
  126332. sqlite3DbFree(db, pVTab);
  126333. }
  126334. }
  126335. /*
  126336. ** Table p is a virtual table. This function moves all elements in the
  126337. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  126338. ** database connections to be disconnected at the next opportunity.
  126339. ** Except, if argument db is not NULL, then the entry associated with
  126340. ** connection db is left in the p->pVTable list.
  126341. */
  126342. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  126343. VTable *pRet = 0;
  126344. VTable *pVTable = p->pVTable;
  126345. p->pVTable = 0;
  126346. /* Assert that the mutex (if any) associated with the BtShared database
  126347. ** that contains table p is held by the caller. See header comments
  126348. ** above function sqlite3VtabUnlockList() for an explanation of why
  126349. ** this makes it safe to access the sqlite3.pDisconnect list of any
  126350. ** database connection that may have an entry in the p->pVTable list.
  126351. */
  126352. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  126353. while( pVTable ){
  126354. sqlite3 *db2 = pVTable->db;
  126355. VTable *pNext = pVTable->pNext;
  126356. assert( db2 );
  126357. if( db2==db ){
  126358. pRet = pVTable;
  126359. p->pVTable = pRet;
  126360. pRet->pNext = 0;
  126361. }else{
  126362. pVTable->pNext = db2->pDisconnect;
  126363. db2->pDisconnect = pVTable;
  126364. }
  126365. pVTable = pNext;
  126366. }
  126367. assert( !db || pRet );
  126368. return pRet;
  126369. }
  126370. /*
  126371. ** Table *p is a virtual table. This function removes the VTable object
  126372. ** for table *p associated with database connection db from the linked
  126373. ** list in p->pVTab. It also decrements the VTable ref count. This is
  126374. ** used when closing database connection db to free all of its VTable
  126375. ** objects without disturbing the rest of the Schema object (which may
  126376. ** be being used by other shared-cache connections).
  126377. */
  126378. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  126379. VTable **ppVTab;
  126380. assert( IsVirtual(p) );
  126381. assert( sqlite3BtreeHoldsAllMutexes(db) );
  126382. assert( sqlite3_mutex_held(db->mutex) );
  126383. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  126384. if( (*ppVTab)->db==db ){
  126385. VTable *pVTab = *ppVTab;
  126386. *ppVTab = pVTab->pNext;
  126387. sqlite3VtabUnlock(pVTab);
  126388. break;
  126389. }
  126390. }
  126391. }
  126392. /*
  126393. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  126394. **
  126395. ** This function may only be called when the mutexes associated with all
  126396. ** shared b-tree databases opened using connection db are held by the
  126397. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  126398. ** sqlite3.pDisconnect list is accessed only as follows:
  126399. **
  126400. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  126401. ** associated with the database handle itself must be held.
  126402. **
  126403. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  126404. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  126405. ** associated with the database the virtual table is stored in is held
  126406. ** or, if the virtual table is stored in a non-sharable database, then
  126407. ** the database handle mutex is held.
  126408. **
  126409. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  126410. ** by multiple threads. It is thread-safe.
  126411. */
  126412. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  126413. VTable *p = db->pDisconnect;
  126414. db->pDisconnect = 0;
  126415. assert( sqlite3BtreeHoldsAllMutexes(db) );
  126416. assert( sqlite3_mutex_held(db->mutex) );
  126417. if( p ){
  126418. sqlite3ExpirePreparedStatements(db, 0);
  126419. do {
  126420. VTable *pNext = p->pNext;
  126421. sqlite3VtabUnlock(p);
  126422. p = pNext;
  126423. }while( p );
  126424. }
  126425. }
  126426. /*
  126427. ** Clear any and all virtual-table information from the Table record.
  126428. ** This routine is called, for example, just before deleting the Table
  126429. ** record.
  126430. **
  126431. ** Since it is a virtual-table, the Table structure contains a pointer
  126432. ** to the head of a linked list of VTable structures. Each VTable
  126433. ** structure is associated with a single sqlite3* user of the schema.
  126434. ** The reference count of the VTable structure associated with database
  126435. ** connection db is decremented immediately (which may lead to the
  126436. ** structure being xDisconnected and free). Any other VTable structures
  126437. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  126438. ** database connection.
  126439. */
  126440. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  126441. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  126442. if( p->azModuleArg ){
  126443. int i;
  126444. for(i=0; i<p->nModuleArg; i++){
  126445. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  126446. }
  126447. sqlite3DbFree(db, p->azModuleArg);
  126448. }
  126449. }
  126450. /*
  126451. ** Add a new module argument to pTable->azModuleArg[].
  126452. ** The string is not copied - the pointer is stored. The
  126453. ** string will be freed automatically when the table is
  126454. ** deleted.
  126455. */
  126456. static void addModuleArgument(Parse *pParse, Table *pTable, char *zArg){
  126457. sqlite3_int64 nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  126458. char **azModuleArg;
  126459. sqlite3 *db = pParse->db;
  126460. if( pTable->nModuleArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){
  126461. sqlite3ErrorMsg(pParse, "too many columns on %s", pTable->zName);
  126462. }
  126463. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  126464. if( azModuleArg==0 ){
  126465. sqlite3DbFree(db, zArg);
  126466. }else{
  126467. int i = pTable->nModuleArg++;
  126468. azModuleArg[i] = zArg;
  126469. azModuleArg[i+1] = 0;
  126470. pTable->azModuleArg = azModuleArg;
  126471. }
  126472. }
  126473. /*
  126474. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  126475. ** statement. The module name has been parsed, but the optional list
  126476. ** of parameters that follow the module name are still pending.
  126477. */
  126478. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  126479. Parse *pParse, /* Parsing context */
  126480. Token *pName1, /* Name of new table, or database name */
  126481. Token *pName2, /* Name of new table or NULL */
  126482. Token *pModuleName, /* Name of the module for the virtual table */
  126483. int ifNotExists /* No error if the table already exists */
  126484. ){
  126485. Table *pTable; /* The new virtual table */
  126486. sqlite3 *db; /* Database connection */
  126487. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  126488. pTable = pParse->pNewTable;
  126489. if( pTable==0 ) return;
  126490. assert( 0==pTable->pIndex );
  126491. db = pParse->db;
  126492. assert( pTable->nModuleArg==0 );
  126493. addModuleArgument(pParse, pTable, sqlite3NameFromToken(db, pModuleName));
  126494. addModuleArgument(pParse, pTable, 0);
  126495. addModuleArgument(pParse, pTable, sqlite3DbStrDup(db, pTable->zName));
  126496. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  126497. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  126498. );
  126499. pParse->sNameToken.n = (int)(
  126500. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  126501. );
  126502. #ifndef SQLITE_OMIT_AUTHORIZATION
  126503. /* Creating a virtual table invokes the authorization callback twice.
  126504. ** The first invocation, to obtain permission to INSERT a row into the
  126505. ** sqlite_master table, has already been made by sqlite3StartTable().
  126506. ** The second call, to obtain permission to create the table, is made now.
  126507. */
  126508. if( pTable->azModuleArg ){
  126509. int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  126510. assert( iDb>=0 ); /* The database the table is being created in */
  126511. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  126512. pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
  126513. }
  126514. #endif
  126515. }
  126516. /*
  126517. ** This routine takes the module argument that has been accumulating
  126518. ** in pParse->zArg[] and appends it to the list of arguments on the
  126519. ** virtual table currently under construction in pParse->pTable.
  126520. */
  126521. static void addArgumentToVtab(Parse *pParse){
  126522. if( pParse->sArg.z && pParse->pNewTable ){
  126523. const char *z = (const char*)pParse->sArg.z;
  126524. int n = pParse->sArg.n;
  126525. sqlite3 *db = pParse->db;
  126526. addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  126527. }
  126528. }
  126529. /*
  126530. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  126531. ** has been completely parsed.
  126532. */
  126533. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  126534. Table *pTab = pParse->pNewTable; /* The table being constructed */
  126535. sqlite3 *db = pParse->db; /* The database connection */
  126536. if( pTab==0 ) return;
  126537. addArgumentToVtab(pParse);
  126538. pParse->sArg.z = 0;
  126539. if( pTab->nModuleArg<1 ) return;
  126540. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  126541. ** first time (in other words if the virtual table is actually being
  126542. ** created now instead of just being read out of sqlite_master) then
  126543. ** do additional initialization work and store the statement text
  126544. ** in the sqlite_master table.
  126545. */
  126546. if( !db->init.busy ){
  126547. char *zStmt;
  126548. char *zWhere;
  126549. int iDb;
  126550. int iReg;
  126551. Vdbe *v;
  126552. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  126553. if( pEnd ){
  126554. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  126555. }
  126556. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  126557. /* A slot for the record has already been allocated in the
  126558. ** SQLITE_MASTER table. We just need to update that slot with all
  126559. ** the information we've collected.
  126560. **
  126561. ** The VM register number pParse->regRowid holds the rowid of an
  126562. ** entry in the sqlite_master table tht was created for this vtab
  126563. ** by sqlite3StartTable().
  126564. */
  126565. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  126566. sqlite3NestedParse(pParse,
  126567. "UPDATE %Q.%s "
  126568. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  126569. "WHERE rowid=#%d",
  126570. db->aDb[iDb].zDbSName, MASTER_NAME,
  126571. pTab->zName,
  126572. pTab->zName,
  126573. zStmt,
  126574. pParse->regRowid
  126575. );
  126576. sqlite3DbFree(db, zStmt);
  126577. v = sqlite3GetVdbe(pParse);
  126578. sqlite3ChangeCookie(pParse, iDb);
  126579. sqlite3VdbeAddOp0(v, OP_Expire);
  126580. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  126581. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  126582. iReg = ++pParse->nMem;
  126583. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  126584. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  126585. }
  126586. /* If we are rereading the sqlite_master table create the in-memory
  126587. ** record of the table. The xConnect() method is not called until
  126588. ** the first time the virtual table is used in an SQL statement. This
  126589. ** allows a schema that contains virtual tables to be loaded before
  126590. ** the required virtual table implementations are registered. */
  126591. else {
  126592. Table *pOld;
  126593. Schema *pSchema = pTab->pSchema;
  126594. const char *zName = pTab->zName;
  126595. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  126596. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  126597. if( pOld ){
  126598. sqlite3OomFault(db);
  126599. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  126600. return;
  126601. }
  126602. pParse->pNewTable = 0;
  126603. }
  126604. }
  126605. /*
  126606. ** The parser calls this routine when it sees the first token
  126607. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  126608. */
  126609. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  126610. addArgumentToVtab(pParse);
  126611. pParse->sArg.z = 0;
  126612. pParse->sArg.n = 0;
  126613. }
  126614. /*
  126615. ** The parser calls this routine for each token after the first token
  126616. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  126617. */
  126618. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  126619. Token *pArg = &pParse->sArg;
  126620. if( pArg->z==0 ){
  126621. pArg->z = p->z;
  126622. pArg->n = p->n;
  126623. }else{
  126624. assert(pArg->z <= p->z);
  126625. pArg->n = (int)(&p->z[p->n] - pArg->z);
  126626. }
  126627. }
  126628. /*
  126629. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  126630. ** pointer to the function to invoke is passed as the fourth parameter
  126631. ** to this procedure.
  126632. */
  126633. static int vtabCallConstructor(
  126634. sqlite3 *db,
  126635. Table *pTab,
  126636. Module *pMod,
  126637. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  126638. char **pzErr
  126639. ){
  126640. VtabCtx sCtx;
  126641. VTable *pVTable;
  126642. int rc;
  126643. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  126644. int nArg = pTab->nModuleArg;
  126645. char *zErr = 0;
  126646. char *zModuleName;
  126647. int iDb;
  126648. VtabCtx *pCtx;
  126649. /* Check that the virtual-table is not already being initialized */
  126650. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  126651. if( pCtx->pTab==pTab ){
  126652. *pzErr = sqlite3MPrintf(db,
  126653. "vtable constructor called recursively: %s", pTab->zName
  126654. );
  126655. return SQLITE_LOCKED;
  126656. }
  126657. }
  126658. zModuleName = sqlite3DbStrDup(db, pTab->zName);
  126659. if( !zModuleName ){
  126660. return SQLITE_NOMEM_BKPT;
  126661. }
  126662. pVTable = sqlite3MallocZero(sizeof(VTable));
  126663. if( !pVTable ){
  126664. sqlite3OomFault(db);
  126665. sqlite3DbFree(db, zModuleName);
  126666. return SQLITE_NOMEM_BKPT;
  126667. }
  126668. pVTable->db = db;
  126669. pVTable->pMod = pMod;
  126670. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  126671. pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
  126672. /* Invoke the virtual table constructor */
  126673. assert( &db->pVtabCtx );
  126674. assert( xConstruct );
  126675. sCtx.pTab = pTab;
  126676. sCtx.pVTable = pVTable;
  126677. sCtx.pPrior = db->pVtabCtx;
  126678. sCtx.bDeclared = 0;
  126679. db->pVtabCtx = &sCtx;
  126680. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  126681. db->pVtabCtx = sCtx.pPrior;
  126682. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  126683. assert( sCtx.pTab==pTab );
  126684. if( SQLITE_OK!=rc ){
  126685. if( zErr==0 ){
  126686. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  126687. }else {
  126688. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  126689. sqlite3_free(zErr);
  126690. }
  126691. sqlite3DbFree(db, pVTable);
  126692. }else if( ALWAYS(pVTable->pVtab) ){
  126693. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  126694. ** the sqlite3_vtab object if successful. */
  126695. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  126696. pVTable->pVtab->pModule = pMod->pModule;
  126697. pVTable->nRef = 1;
  126698. if( sCtx.bDeclared==0 ){
  126699. const char *zFormat = "vtable constructor did not declare schema: %s";
  126700. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  126701. sqlite3VtabUnlock(pVTable);
  126702. rc = SQLITE_ERROR;
  126703. }else{
  126704. int iCol;
  126705. u8 oooHidden = 0;
  126706. /* If everything went according to plan, link the new VTable structure
  126707. ** into the linked list headed by pTab->pVTable. Then loop through the
  126708. ** columns of the table to see if any of them contain the token "hidden".
  126709. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  126710. ** the type string. */
  126711. pVTable->pNext = pTab->pVTable;
  126712. pTab->pVTable = pVTable;
  126713. for(iCol=0; iCol<pTab->nCol; iCol++){
  126714. char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
  126715. int nType;
  126716. int i = 0;
  126717. nType = sqlite3Strlen30(zType);
  126718. for(i=0; i<nType; i++){
  126719. if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
  126720. && (i==0 || zType[i-1]==' ')
  126721. && (zType[i+6]=='\0' || zType[i+6]==' ')
  126722. ){
  126723. break;
  126724. }
  126725. }
  126726. if( i<nType ){
  126727. int j;
  126728. int nDel = 6 + (zType[i+6] ? 1 : 0);
  126729. for(j=i; (j+nDel)<=nType; j++){
  126730. zType[j] = zType[j+nDel];
  126731. }
  126732. if( zType[i]=='\0' && i>0 ){
  126733. assert(zType[i-1]==' ');
  126734. zType[i-1] = '\0';
  126735. }
  126736. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  126737. oooHidden = TF_OOOHidden;
  126738. }else{
  126739. pTab->tabFlags |= oooHidden;
  126740. }
  126741. }
  126742. }
  126743. }
  126744. sqlite3DbFree(db, zModuleName);
  126745. return rc;
  126746. }
  126747. /*
  126748. ** This function is invoked by the parser to call the xConnect() method
  126749. ** of the virtual table pTab. If an error occurs, an error code is returned
  126750. ** and an error left in pParse.
  126751. **
  126752. ** This call is a no-op if table pTab is not a virtual table.
  126753. */
  126754. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  126755. sqlite3 *db = pParse->db;
  126756. const char *zMod;
  126757. Module *pMod;
  126758. int rc;
  126759. assert( pTab );
  126760. if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
  126761. return SQLITE_OK;
  126762. }
  126763. /* Locate the required virtual table module */
  126764. zMod = pTab->azModuleArg[0];
  126765. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  126766. if( !pMod ){
  126767. const char *zModule = pTab->azModuleArg[0];
  126768. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  126769. rc = SQLITE_ERROR;
  126770. }else{
  126771. char *zErr = 0;
  126772. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  126773. if( rc!=SQLITE_OK ){
  126774. sqlite3ErrorMsg(pParse, "%s", zErr);
  126775. pParse->rc = rc;
  126776. }
  126777. sqlite3DbFree(db, zErr);
  126778. }
  126779. return rc;
  126780. }
  126781. /*
  126782. ** Grow the db->aVTrans[] array so that there is room for at least one
  126783. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  126784. */
  126785. static int growVTrans(sqlite3 *db){
  126786. const int ARRAY_INCR = 5;
  126787. /* Grow the sqlite3.aVTrans array if required */
  126788. if( (db->nVTrans%ARRAY_INCR)==0 ){
  126789. VTable **aVTrans;
  126790. sqlite3_int64 nBytes = sizeof(sqlite3_vtab*)*
  126791. ((sqlite3_int64)db->nVTrans + ARRAY_INCR);
  126792. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  126793. if( !aVTrans ){
  126794. return SQLITE_NOMEM_BKPT;
  126795. }
  126796. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  126797. db->aVTrans = aVTrans;
  126798. }
  126799. return SQLITE_OK;
  126800. }
  126801. /*
  126802. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  126803. ** have already been reserved using growVTrans().
  126804. */
  126805. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  126806. /* Add pVtab to the end of sqlite3.aVTrans */
  126807. db->aVTrans[db->nVTrans++] = pVTab;
  126808. sqlite3VtabLock(pVTab);
  126809. }
  126810. /*
  126811. ** This function is invoked by the vdbe to call the xCreate method
  126812. ** of the virtual table named zTab in database iDb.
  126813. **
  126814. ** If an error occurs, *pzErr is set to point to an English language
  126815. ** description of the error and an SQLITE_XXX error code is returned.
  126816. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  126817. */
  126818. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  126819. int rc = SQLITE_OK;
  126820. Table *pTab;
  126821. Module *pMod;
  126822. const char *zMod;
  126823. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  126824. assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
  126825. /* Locate the required virtual table module */
  126826. zMod = pTab->azModuleArg[0];
  126827. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  126828. /* If the module has been registered and includes a Create method,
  126829. ** invoke it now. If the module has not been registered, return an
  126830. ** error. Otherwise, do nothing.
  126831. */
  126832. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  126833. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  126834. rc = SQLITE_ERROR;
  126835. }else{
  126836. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  126837. }
  126838. /* Justification of ALWAYS(): The xConstructor method is required to
  126839. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  126840. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  126841. rc = growVTrans(db);
  126842. if( rc==SQLITE_OK ){
  126843. addToVTrans(db, sqlite3GetVTable(db, pTab));
  126844. }
  126845. }
  126846. return rc;
  126847. }
  126848. /*
  126849. ** This function is used to set the schema of a virtual table. It is only
  126850. ** valid to call this function from within the xCreate() or xConnect() of a
  126851. ** virtual table module.
  126852. */
  126853. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  126854. VtabCtx *pCtx;
  126855. int rc = SQLITE_OK;
  126856. Table *pTab;
  126857. char *zErr = 0;
  126858. Parse sParse;
  126859. #ifdef SQLITE_ENABLE_API_ARMOR
  126860. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  126861. return SQLITE_MISUSE_BKPT;
  126862. }
  126863. #endif
  126864. sqlite3_mutex_enter(db->mutex);
  126865. pCtx = db->pVtabCtx;
  126866. if( !pCtx || pCtx->bDeclared ){
  126867. sqlite3Error(db, SQLITE_MISUSE);
  126868. sqlite3_mutex_leave(db->mutex);
  126869. return SQLITE_MISUSE_BKPT;
  126870. }
  126871. pTab = pCtx->pTab;
  126872. assert( IsVirtual(pTab) );
  126873. memset(&sParse, 0, sizeof(sParse));
  126874. sParse.eParseMode = PARSE_MODE_DECLARE_VTAB;
  126875. sParse.db = db;
  126876. sParse.nQueryLoop = 1;
  126877. if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
  126878. && sParse.pNewTable
  126879. && !db->mallocFailed
  126880. && !sParse.pNewTable->pSelect
  126881. && !IsVirtual(sParse.pNewTable)
  126882. ){
  126883. if( !pTab->aCol ){
  126884. Table *pNew = sParse.pNewTable;
  126885. Index *pIdx;
  126886. pTab->aCol = pNew->aCol;
  126887. pTab->nCol = pNew->nCol;
  126888. pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
  126889. pNew->nCol = 0;
  126890. pNew->aCol = 0;
  126891. assert( pTab->pIndex==0 );
  126892. assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
  126893. if( !HasRowid(pNew)
  126894. && pCtx->pVTable->pMod->pModule->xUpdate!=0
  126895. && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
  126896. ){
  126897. /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
  126898. ** or else must have a single-column PRIMARY KEY */
  126899. rc = SQLITE_ERROR;
  126900. }
  126901. pIdx = pNew->pIndex;
  126902. if( pIdx ){
  126903. assert( pIdx->pNext==0 );
  126904. pTab->pIndex = pIdx;
  126905. pNew->pIndex = 0;
  126906. pIdx->pTable = pTab;
  126907. }
  126908. }
  126909. pCtx->bDeclared = 1;
  126910. }else{
  126911. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  126912. sqlite3DbFree(db, zErr);
  126913. rc = SQLITE_ERROR;
  126914. }
  126915. sParse.eParseMode = PARSE_MODE_NORMAL;
  126916. if( sParse.pVdbe ){
  126917. sqlite3VdbeFinalize(sParse.pVdbe);
  126918. }
  126919. sqlite3DeleteTable(db, sParse.pNewTable);
  126920. sqlite3ParserReset(&sParse);
  126921. assert( (rc&0xff)==rc );
  126922. rc = sqlite3ApiExit(db, rc);
  126923. sqlite3_mutex_leave(db->mutex);
  126924. return rc;
  126925. }
  126926. /*
  126927. ** This function is invoked by the vdbe to call the xDestroy method
  126928. ** of the virtual table named zTab in database iDb. This occurs
  126929. ** when a DROP TABLE is mentioned.
  126930. **
  126931. ** This call is a no-op if zTab is not a virtual table.
  126932. */
  126933. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  126934. int rc = SQLITE_OK;
  126935. Table *pTab;
  126936. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  126937. if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
  126938. VTable *p;
  126939. int (*xDestroy)(sqlite3_vtab *);
  126940. for(p=pTab->pVTable; p; p=p->pNext){
  126941. assert( p->pVtab );
  126942. if( p->pVtab->nRef>0 ){
  126943. return SQLITE_LOCKED;
  126944. }
  126945. }
  126946. p = vtabDisconnectAll(db, pTab);
  126947. xDestroy = p->pMod->pModule->xDestroy;
  126948. assert( xDestroy!=0 ); /* Checked before the virtual table is created */
  126949. rc = xDestroy(p->pVtab);
  126950. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  126951. if( rc==SQLITE_OK ){
  126952. assert( pTab->pVTable==p && p->pNext==0 );
  126953. p->pVtab = 0;
  126954. pTab->pVTable = 0;
  126955. sqlite3VtabUnlock(p);
  126956. }
  126957. }
  126958. return rc;
  126959. }
  126960. /*
  126961. ** This function invokes either the xRollback or xCommit method
  126962. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  126963. ** called is identified by the second argument, "offset", which is
  126964. ** the offset of the method to call in the sqlite3_module structure.
  126965. **
  126966. ** The array is cleared after invoking the callbacks.
  126967. */
  126968. static void callFinaliser(sqlite3 *db, int offset){
  126969. int i;
  126970. if( db->aVTrans ){
  126971. VTable **aVTrans = db->aVTrans;
  126972. db->aVTrans = 0;
  126973. for(i=0; i<db->nVTrans; i++){
  126974. VTable *pVTab = aVTrans[i];
  126975. sqlite3_vtab *p = pVTab->pVtab;
  126976. if( p ){
  126977. int (*x)(sqlite3_vtab *);
  126978. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  126979. if( x ) x(p);
  126980. }
  126981. pVTab->iSavepoint = 0;
  126982. sqlite3VtabUnlock(pVTab);
  126983. }
  126984. sqlite3DbFree(db, aVTrans);
  126985. db->nVTrans = 0;
  126986. }
  126987. }
  126988. /*
  126989. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  126990. ** array. Return the error code for the first error that occurs, or
  126991. ** SQLITE_OK if all xSync operations are successful.
  126992. **
  126993. ** If an error message is available, leave it in p->zErrMsg.
  126994. */
  126995. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  126996. int i;
  126997. int rc = SQLITE_OK;
  126998. VTable **aVTrans = db->aVTrans;
  126999. db->aVTrans = 0;
  127000. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  127001. int (*x)(sqlite3_vtab *);
  127002. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  127003. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  127004. rc = x(pVtab);
  127005. sqlite3VtabImportErrmsg(p, pVtab);
  127006. }
  127007. }
  127008. db->aVTrans = aVTrans;
  127009. return rc;
  127010. }
  127011. /*
  127012. ** Invoke the xRollback method of all virtual tables in the
  127013. ** sqlite3.aVTrans array. Then clear the array itself.
  127014. */
  127015. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  127016. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  127017. return SQLITE_OK;
  127018. }
  127019. /*
  127020. ** Invoke the xCommit method of all virtual tables in the
  127021. ** sqlite3.aVTrans array. Then clear the array itself.
  127022. */
  127023. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  127024. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  127025. return SQLITE_OK;
  127026. }
  127027. /*
  127028. ** If the virtual table pVtab supports the transaction interface
  127029. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  127030. ** not currently open, invoke the xBegin method now.
  127031. **
  127032. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  127033. ** in the sqlite3.aVTrans array.
  127034. */
  127035. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  127036. int rc = SQLITE_OK;
  127037. const sqlite3_module *pModule;
  127038. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  127039. ** than zero, then this function is being called from within a
  127040. ** virtual module xSync() callback. It is illegal to write to
  127041. ** virtual module tables in this case, so return SQLITE_LOCKED.
  127042. */
  127043. if( sqlite3VtabInSync(db) ){
  127044. return SQLITE_LOCKED;
  127045. }
  127046. if( !pVTab ){
  127047. return SQLITE_OK;
  127048. }
  127049. pModule = pVTab->pVtab->pModule;
  127050. if( pModule->xBegin ){
  127051. int i;
  127052. /* If pVtab is already in the aVTrans array, return early */
  127053. for(i=0; i<db->nVTrans; i++){
  127054. if( db->aVTrans[i]==pVTab ){
  127055. return SQLITE_OK;
  127056. }
  127057. }
  127058. /* Invoke the xBegin method. If successful, add the vtab to the
  127059. ** sqlite3.aVTrans[] array. */
  127060. rc = growVTrans(db);
  127061. if( rc==SQLITE_OK ){
  127062. rc = pModule->xBegin(pVTab->pVtab);
  127063. if( rc==SQLITE_OK ){
  127064. int iSvpt = db->nStatement + db->nSavepoint;
  127065. addToVTrans(db, pVTab);
  127066. if( iSvpt && pModule->xSavepoint ){
  127067. pVTab->iSavepoint = iSvpt;
  127068. rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
  127069. }
  127070. }
  127071. }
  127072. }
  127073. return rc;
  127074. }
  127075. /*
  127076. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  127077. ** virtual tables that currently have an open transaction. Pass iSavepoint
  127078. ** as the second argument to the virtual table method invoked.
  127079. **
  127080. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  127081. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  127082. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  127083. ** an open transaction is invoked.
  127084. **
  127085. ** If any virtual table method returns an error code other than SQLITE_OK,
  127086. ** processing is abandoned and the error returned to the caller of this
  127087. ** function immediately. If all calls to virtual table methods are successful,
  127088. ** SQLITE_OK is returned.
  127089. */
  127090. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  127091. int rc = SQLITE_OK;
  127092. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  127093. assert( iSavepoint>=-1 );
  127094. if( db->aVTrans ){
  127095. int i;
  127096. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  127097. VTable *pVTab = db->aVTrans[i];
  127098. const sqlite3_module *pMod = pVTab->pMod->pModule;
  127099. if( pVTab->pVtab && pMod->iVersion>=2 ){
  127100. int (*xMethod)(sqlite3_vtab *, int);
  127101. sqlite3VtabLock(pVTab);
  127102. switch( op ){
  127103. case SAVEPOINT_BEGIN:
  127104. xMethod = pMod->xSavepoint;
  127105. pVTab->iSavepoint = iSavepoint+1;
  127106. break;
  127107. case SAVEPOINT_ROLLBACK:
  127108. xMethod = pMod->xRollbackTo;
  127109. break;
  127110. default:
  127111. xMethod = pMod->xRelease;
  127112. break;
  127113. }
  127114. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  127115. rc = xMethod(pVTab->pVtab, iSavepoint);
  127116. }
  127117. sqlite3VtabUnlock(pVTab);
  127118. }
  127119. }
  127120. }
  127121. return rc;
  127122. }
  127123. /*
  127124. ** The first parameter (pDef) is a function implementation. The
  127125. ** second parameter (pExpr) is the first argument to this function.
  127126. ** If pExpr is a column in a virtual table, then let the virtual
  127127. ** table implementation have an opportunity to overload the function.
  127128. **
  127129. ** This routine is used to allow virtual table implementations to
  127130. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  127131. **
  127132. ** Return either the pDef argument (indicating no change) or a
  127133. ** new FuncDef structure that is marked as ephemeral using the
  127134. ** SQLITE_FUNC_EPHEM flag.
  127135. */
  127136. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  127137. sqlite3 *db, /* Database connection for reporting malloc problems */
  127138. FuncDef *pDef, /* Function to possibly overload */
  127139. int nArg, /* Number of arguments to the function */
  127140. Expr *pExpr /* First argument to the function */
  127141. ){
  127142. Table *pTab;
  127143. sqlite3_vtab *pVtab;
  127144. sqlite3_module *pMod;
  127145. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  127146. void *pArg = 0;
  127147. FuncDef *pNew;
  127148. int rc = 0;
  127149. /* Check to see the left operand is a column in a virtual table */
  127150. if( NEVER(pExpr==0) ) return pDef;
  127151. if( pExpr->op!=TK_COLUMN ) return pDef;
  127152. pTab = pExpr->y.pTab;
  127153. if( pTab==0 ) return pDef;
  127154. if( !IsVirtual(pTab) ) return pDef;
  127155. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  127156. assert( pVtab!=0 );
  127157. assert( pVtab->pModule!=0 );
  127158. pMod = (sqlite3_module *)pVtab->pModule;
  127159. if( pMod->xFindFunction==0 ) return pDef;
  127160. /* Call the xFindFunction method on the virtual table implementation
  127161. ** to see if the implementation wants to overload this function.
  127162. **
  127163. ** Though undocumented, we have historically always invoked xFindFunction
  127164. ** with an all lower-case function name. Continue in this tradition to
  127165. ** avoid any chance of an incompatibility.
  127166. */
  127167. #ifdef SQLITE_DEBUG
  127168. {
  127169. int i;
  127170. for(i=0; pDef->zName[i]; i++){
  127171. unsigned char x = (unsigned char)pDef->zName[i];
  127172. assert( x==sqlite3UpperToLower[x] );
  127173. }
  127174. }
  127175. #endif
  127176. rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);
  127177. if( rc==0 ){
  127178. return pDef;
  127179. }
  127180. /* Create a new ephemeral function definition for the overloaded
  127181. ** function */
  127182. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  127183. + sqlite3Strlen30(pDef->zName) + 1);
  127184. if( pNew==0 ){
  127185. return pDef;
  127186. }
  127187. *pNew = *pDef;
  127188. pNew->zName = (const char*)&pNew[1];
  127189. memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  127190. pNew->xSFunc = xSFunc;
  127191. pNew->pUserData = pArg;
  127192. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  127193. return pNew;
  127194. }
  127195. /*
  127196. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  127197. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  127198. ** array if it is missing. If pTab is already in the array, this routine
  127199. ** is a no-op.
  127200. */
  127201. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  127202. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  127203. int i, n;
  127204. Table **apVtabLock;
  127205. assert( IsVirtual(pTab) );
  127206. for(i=0; i<pToplevel->nVtabLock; i++){
  127207. if( pTab==pToplevel->apVtabLock[i] ) return;
  127208. }
  127209. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  127210. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  127211. if( apVtabLock ){
  127212. pToplevel->apVtabLock = apVtabLock;
  127213. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  127214. }else{
  127215. sqlite3OomFault(pToplevel->db);
  127216. }
  127217. }
  127218. /*
  127219. ** Check to see if virtual table module pMod can be have an eponymous
  127220. ** virtual table instance. If it can, create one if one does not already
  127221. ** exist. Return non-zero if the eponymous virtual table instance exists
  127222. ** when this routine returns, and return zero if it does not exist.
  127223. **
  127224. ** An eponymous virtual table instance is one that is named after its
  127225. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  127226. ** statement in order to come into existance. Eponymous virtual table
  127227. ** instances always exist. They cannot be DROP-ed.
  127228. **
  127229. ** Any virtual table module for which xConnect and xCreate are the same
  127230. ** method can have an eponymous virtual table instance.
  127231. */
  127232. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  127233. const sqlite3_module *pModule = pMod->pModule;
  127234. Table *pTab;
  127235. char *zErr = 0;
  127236. int rc;
  127237. sqlite3 *db = pParse->db;
  127238. if( pMod->pEpoTab ) return 1;
  127239. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  127240. pTab = sqlite3DbMallocZero(db, sizeof(Table));
  127241. if( pTab==0 ) return 0;
  127242. pTab->zName = sqlite3DbStrDup(db, pMod->zName);
  127243. if( pTab->zName==0 ){
  127244. sqlite3DbFree(db, pTab);
  127245. return 0;
  127246. }
  127247. pMod->pEpoTab = pTab;
  127248. pTab->nTabRef = 1;
  127249. pTab->pSchema = db->aDb[0].pSchema;
  127250. assert( pTab->nModuleArg==0 );
  127251. pTab->iPKey = -1;
  127252. addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
  127253. addModuleArgument(pParse, pTab, 0);
  127254. addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
  127255. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  127256. if( rc ){
  127257. sqlite3ErrorMsg(pParse, "%s", zErr);
  127258. sqlite3DbFree(db, zErr);
  127259. sqlite3VtabEponymousTableClear(db, pMod);
  127260. return 0;
  127261. }
  127262. return 1;
  127263. }
  127264. /*
  127265. ** Erase the eponymous virtual table instance associated with
  127266. ** virtual table module pMod, if it exists.
  127267. */
  127268. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  127269. Table *pTab = pMod->pEpoTab;
  127270. if( pTab!=0 ){
  127271. /* Mark the table as Ephemeral prior to deleting it, so that the
  127272. ** sqlite3DeleteTable() routine will know that it is not stored in
  127273. ** the schema. */
  127274. pTab->tabFlags |= TF_Ephemeral;
  127275. sqlite3DeleteTable(db, pTab);
  127276. pMod->pEpoTab = 0;
  127277. }
  127278. }
  127279. /*
  127280. ** Return the ON CONFLICT resolution mode in effect for the virtual
  127281. ** table update operation currently in progress.
  127282. **
  127283. ** The results of this routine are undefined unless it is called from
  127284. ** within an xUpdate method.
  127285. */
  127286. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  127287. static const unsigned char aMap[] = {
  127288. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  127289. };
  127290. #ifdef SQLITE_ENABLE_API_ARMOR
  127291. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  127292. #endif
  127293. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  127294. assert( OE_Ignore==4 && OE_Replace==5 );
  127295. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  127296. return (int)aMap[db->vtabOnConflict-1];
  127297. }
  127298. /*
  127299. ** Call from within the xCreate() or xConnect() methods to provide
  127300. ** the SQLite core with additional information about the behavior
  127301. ** of the virtual table being implemented.
  127302. */
  127303. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  127304. va_list ap;
  127305. int rc = SQLITE_OK;
  127306. #ifdef SQLITE_ENABLE_API_ARMOR
  127307. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  127308. #endif
  127309. sqlite3_mutex_enter(db->mutex);
  127310. va_start(ap, op);
  127311. switch( op ){
  127312. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  127313. VtabCtx *p = db->pVtabCtx;
  127314. if( !p ){
  127315. rc = SQLITE_MISUSE_BKPT;
  127316. }else{
  127317. assert( p->pTab==0 || IsVirtual(p->pTab) );
  127318. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  127319. }
  127320. break;
  127321. }
  127322. default:
  127323. rc = SQLITE_MISUSE_BKPT;
  127324. break;
  127325. }
  127326. va_end(ap);
  127327. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  127328. sqlite3_mutex_leave(db->mutex);
  127329. return rc;
  127330. }
  127331. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  127332. /************** End of vtab.c ************************************************/
  127333. /************** Begin file wherecode.c ***************************************/
  127334. /*
  127335. ** 2015-06-06
  127336. **
  127337. ** The author disclaims copyright to this source code. In place of
  127338. ** a legal notice, here is a blessing:
  127339. **
  127340. ** May you do good and not evil.
  127341. ** May you find forgiveness for yourself and forgive others.
  127342. ** May you share freely, never taking more than you give.
  127343. **
  127344. *************************************************************************
  127345. ** This module contains C code that generates VDBE code used to process
  127346. ** the WHERE clause of SQL statements.
  127347. **
  127348. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  127349. ** size of where.c and make it easier to edit. This file contains the routines
  127350. ** that actually generate the bulk of the WHERE loop code. The original where.c
  127351. ** file retains the code that does query planning and analysis.
  127352. */
  127353. /* #include "sqliteInt.h" */
  127354. /************** Include whereInt.h in the middle of wherecode.c **************/
  127355. /************** Begin file whereInt.h ****************************************/
  127356. /*
  127357. ** 2013-11-12
  127358. **
  127359. ** The author disclaims copyright to this source code. In place of
  127360. ** a legal notice, here is a blessing:
  127361. **
  127362. ** May you do good and not evil.
  127363. ** May you find forgiveness for yourself and forgive others.
  127364. ** May you share freely, never taking more than you give.
  127365. **
  127366. *************************************************************************
  127367. **
  127368. ** This file contains structure and macro definitions for the query
  127369. ** planner logic in "where.c". These definitions are broken out into
  127370. ** a separate source file for easier editing.
  127371. */
  127372. /*
  127373. ** Trace output macros
  127374. */
  127375. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  127376. /***/ extern int sqlite3WhereTrace;
  127377. #endif
  127378. #if defined(SQLITE_DEBUG) \
  127379. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  127380. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  127381. # define WHERETRACE_ENABLED 1
  127382. #else
  127383. # define WHERETRACE(K,X)
  127384. #endif
  127385. /* Forward references
  127386. */
  127387. typedef struct WhereClause WhereClause;
  127388. typedef struct WhereMaskSet WhereMaskSet;
  127389. typedef struct WhereOrInfo WhereOrInfo;
  127390. typedef struct WhereAndInfo WhereAndInfo;
  127391. typedef struct WhereLevel WhereLevel;
  127392. typedef struct WhereLoop WhereLoop;
  127393. typedef struct WherePath WherePath;
  127394. typedef struct WhereTerm WhereTerm;
  127395. typedef struct WhereLoopBuilder WhereLoopBuilder;
  127396. typedef struct WhereScan WhereScan;
  127397. typedef struct WhereOrCost WhereOrCost;
  127398. typedef struct WhereOrSet WhereOrSet;
  127399. /*
  127400. ** This object contains information needed to implement a single nested
  127401. ** loop in WHERE clause.
  127402. **
  127403. ** Contrast this object with WhereLoop. This object describes the
  127404. ** implementation of the loop. WhereLoop describes the algorithm.
  127405. ** This object contains a pointer to the WhereLoop algorithm as one of
  127406. ** its elements.
  127407. **
  127408. ** The WhereInfo object contains a single instance of this object for
  127409. ** each term in the FROM clause (which is to say, for each of the
  127410. ** nested loops as implemented). The order of WhereLevel objects determines
  127411. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  127412. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  127413. */
  127414. struct WhereLevel {
  127415. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  127416. int iTabCur; /* The VDBE cursor used to access the table */
  127417. int iIdxCur; /* The VDBE cursor used to access pIdx */
  127418. int addrBrk; /* Jump here to break out of the loop */
  127419. int addrNxt; /* Jump here to start the next IN combination */
  127420. int addrSkip; /* Jump here for next iteration of skip-scan */
  127421. int addrCont; /* Jump here to continue with the next loop cycle */
  127422. int addrFirst; /* First instruction of interior of the loop */
  127423. int addrBody; /* Beginning of the body of this loop */
  127424. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  127425. u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
  127426. int addrLikeRep; /* LIKE range processing address */
  127427. #endif
  127428. u8 iFrom; /* Which entry in the FROM clause */
  127429. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  127430. int p1, p2; /* Operands of the opcode used to ends the loop */
  127431. union { /* Information that depends on pWLoop->wsFlags */
  127432. struct {
  127433. int nIn; /* Number of entries in aInLoop[] */
  127434. struct InLoop {
  127435. int iCur; /* The VDBE cursor used by this IN operator */
  127436. int addrInTop; /* Top of the IN loop */
  127437. int iBase; /* Base register of multi-key index record */
  127438. int nPrefix; /* Number of prior entires in the key */
  127439. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  127440. } *aInLoop; /* Information about each nested IN operator */
  127441. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  127442. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  127443. } u;
  127444. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  127445. Bitmask notReady; /* FROM entries not usable at this level */
  127446. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  127447. int addrVisit; /* Address at which row is visited */
  127448. #endif
  127449. };
  127450. /*
  127451. ** Each instance of this object represents an algorithm for evaluating one
  127452. ** term of a join. Every term of the FROM clause will have at least
  127453. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  127454. ** prevent a query solution - which is an error) and many terms of the
  127455. ** FROM clause will have multiple WhereLoop objects, each describing a
  127456. ** potential way of implementing that FROM-clause term, together with
  127457. ** dependencies and cost estimates for using the chosen algorithm.
  127458. **
  127459. ** Query planning consists of building up a collection of these WhereLoop
  127460. ** objects, then computing a particular sequence of WhereLoop objects, with
  127461. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  127462. ** and that minimize the overall cost.
  127463. */
  127464. struct WhereLoop {
  127465. Bitmask prereq; /* Bitmask of other loops that must run first */
  127466. Bitmask maskSelf; /* Bitmask identifying table iTab */
  127467. #ifdef SQLITE_DEBUG
  127468. char cId; /* Symbolic ID of this loop for debugging use */
  127469. #endif
  127470. u8 iTab; /* Position in FROM clause of table for this loop */
  127471. u8 iSortIdx; /* Sorting index number. 0==None */
  127472. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  127473. LogEst rRun; /* Cost of running each loop */
  127474. LogEst nOut; /* Estimated number of output rows */
  127475. union {
  127476. struct { /* Information for internal btree tables */
  127477. u16 nEq; /* Number of equality constraints */
  127478. u16 nBtm; /* Size of BTM vector */
  127479. u16 nTop; /* Size of TOP vector */
  127480. u16 nIdxCol; /* Index column used for ORDER BY */
  127481. Index *pIndex; /* Index used, or NULL */
  127482. } btree;
  127483. struct { /* Information for virtual tables */
  127484. int idxNum; /* Index number */
  127485. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  127486. i8 isOrdered; /* True if satisfies ORDER BY */
  127487. u16 omitMask; /* Terms that may be omitted */
  127488. char *idxStr; /* Index identifier string */
  127489. } vtab;
  127490. } u;
  127491. u32 wsFlags; /* WHERE_* flags describing the plan */
  127492. u16 nLTerm; /* Number of entries in aLTerm[] */
  127493. u16 nSkip; /* Number of NULL aLTerm[] entries */
  127494. /**** whereLoopXfer() copies fields above ***********************/
  127495. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  127496. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  127497. WhereTerm **aLTerm; /* WhereTerms used */
  127498. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  127499. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  127500. };
  127501. /* This object holds the prerequisites and the cost of running a
  127502. ** subquery on one operand of an OR operator in the WHERE clause.
  127503. ** See WhereOrSet for additional information
  127504. */
  127505. struct WhereOrCost {
  127506. Bitmask prereq; /* Prerequisites */
  127507. LogEst rRun; /* Cost of running this subquery */
  127508. LogEst nOut; /* Number of outputs for this subquery */
  127509. };
  127510. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  127511. ** correspond to the subquery(s) of OR-clause processing. Only the
  127512. ** best N_OR_COST elements are retained.
  127513. */
  127514. #define N_OR_COST 3
  127515. struct WhereOrSet {
  127516. u16 n; /* Number of valid a[] entries */
  127517. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  127518. };
  127519. /*
  127520. ** Each instance of this object holds a sequence of WhereLoop objects
  127521. ** that implement some or all of a query plan.
  127522. **
  127523. ** Think of each WhereLoop object as a node in a graph with arcs
  127524. ** showing dependencies and costs for travelling between nodes. (That is
  127525. ** not a completely accurate description because WhereLoop costs are a
  127526. ** vector, not a scalar, and because dependencies are many-to-one, not
  127527. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  127528. ** Then a WherePath object is a path through the graph that visits some
  127529. ** or all of the WhereLoop objects once.
  127530. **
  127531. ** The "solver" works by creating the N best WherePath objects of length
  127532. ** 1. Then using those as a basis to compute the N best WherePath objects
  127533. ** of length 2. And so forth until the length of WherePaths equals the
  127534. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  127535. ** at the end is the chosen query plan.
  127536. */
  127537. struct WherePath {
  127538. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  127539. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  127540. LogEst nRow; /* Estimated number of rows generated by this path */
  127541. LogEst rCost; /* Total cost of this path */
  127542. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  127543. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  127544. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  127545. };
  127546. /*
  127547. ** The query generator uses an array of instances of this structure to
  127548. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  127549. ** clause subexpression is separated from the others by AND operators,
  127550. ** usually, or sometimes subexpressions separated by OR.
  127551. **
  127552. ** All WhereTerms are collected into a single WhereClause structure.
  127553. ** The following identity holds:
  127554. **
  127555. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  127556. **
  127557. ** When a term is of the form:
  127558. **
  127559. ** X <op> <expr>
  127560. **
  127561. ** where X is a column name and <op> is one of certain operators,
  127562. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  127563. ** cursor number and column number for X. WhereTerm.eOperator records
  127564. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  127565. ** use of a bitmask encoding for the operator allows us to search
  127566. ** quickly for terms that match any of several different operators.
  127567. **
  127568. ** A WhereTerm might also be two or more subterms connected by OR:
  127569. **
  127570. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  127571. **
  127572. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  127573. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  127574. ** is collected about the OR clause.
  127575. **
  127576. ** If a term in the WHERE clause does not match either of the two previous
  127577. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  127578. ** to the original subexpression content and wtFlags is set up appropriately
  127579. ** but no other fields in the WhereTerm object are meaningful.
  127580. **
  127581. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  127582. ** but they do so indirectly. A single WhereMaskSet structure translates
  127583. ** cursor number into bits and the translated bit is stored in the prereq
  127584. ** fields. The translation is used in order to maximize the number of
  127585. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  127586. ** spread out over the non-negative integers. For example, the cursor
  127587. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  127588. ** translates these sparse cursor numbers into consecutive integers
  127589. ** beginning with 0 in order to make the best possible use of the available
  127590. ** bits in the Bitmask. So, in the example above, the cursor numbers
  127591. ** would be mapped into integers 0 through 7.
  127592. **
  127593. ** The number of terms in a join is limited by the number of bits
  127594. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  127595. ** is only able to process joins with 64 or fewer tables.
  127596. */
  127597. struct WhereTerm {
  127598. Expr *pExpr; /* Pointer to the subexpression that is this term */
  127599. WhereClause *pWC; /* The clause this term is part of */
  127600. LogEst truthProb; /* Probability of truth for this expression */
  127601. u16 wtFlags; /* TERM_xxx bit flags. See below */
  127602. u16 eOperator; /* A WO_xx value describing <op> */
  127603. u8 nChild; /* Number of children that must disable us */
  127604. u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
  127605. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  127606. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  127607. int iField; /* Field in (?,?,?) IN (SELECT...) vector */
  127608. union {
  127609. int leftColumn; /* Column number of X in "X <op> <expr>" */
  127610. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  127611. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  127612. } u;
  127613. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  127614. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  127615. };
  127616. /*
  127617. ** Allowed values of WhereTerm.wtFlags
  127618. */
  127619. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  127620. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  127621. #define TERM_CODED 0x04 /* This term is already coded */
  127622. #define TERM_COPIED 0x08 /* Has a child */
  127623. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  127624. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  127625. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  127626. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  127627. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  127628. #else
  127629. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  127630. #endif
  127631. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  127632. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  127633. #define TERM_LIKE 0x400 /* The original LIKE operator */
  127634. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  127635. #define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */
  127636. /*
  127637. ** An instance of the WhereScan object is used as an iterator for locating
  127638. ** terms in the WHERE clause that are useful to the query planner.
  127639. */
  127640. struct WhereScan {
  127641. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  127642. WhereClause *pWC; /* WhereClause currently being scanned */
  127643. const char *zCollName; /* Required collating sequence, if not NULL */
  127644. Expr *pIdxExpr; /* Search for this index expression */
  127645. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  127646. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  127647. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  127648. u32 opMask; /* Acceptable operators */
  127649. int k; /* Resume scanning at this->pWC->a[this->k] */
  127650. int aiCur[11]; /* Cursors in the equivalence class */
  127651. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  127652. };
  127653. /*
  127654. ** An instance of the following structure holds all information about a
  127655. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  127656. **
  127657. ** Explanation of pOuter: For a WHERE clause of the form
  127658. **
  127659. ** a AND ((b AND c) OR (d AND e)) AND f
  127660. **
  127661. ** There are separate WhereClause objects for the whole clause and for
  127662. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  127663. ** subclauses points to the WhereClause object for the whole clause.
  127664. */
  127665. struct WhereClause {
  127666. WhereInfo *pWInfo; /* WHERE clause processing context */
  127667. WhereClause *pOuter; /* Outer conjunction */
  127668. u8 op; /* Split operator. TK_AND or TK_OR */
  127669. u8 hasOr; /* True if any a[].eOperator is WO_OR */
  127670. int nTerm; /* Number of terms */
  127671. int nSlot; /* Number of entries in a[] */
  127672. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  127673. #if defined(SQLITE_SMALL_STACK)
  127674. WhereTerm aStatic[1]; /* Initial static space for a[] */
  127675. #else
  127676. WhereTerm aStatic[8]; /* Initial static space for a[] */
  127677. #endif
  127678. };
  127679. /*
  127680. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  127681. ** a dynamically allocated instance of the following structure.
  127682. */
  127683. struct WhereOrInfo {
  127684. WhereClause wc; /* Decomposition into subterms */
  127685. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  127686. };
  127687. /*
  127688. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  127689. ** a dynamically allocated instance of the following structure.
  127690. */
  127691. struct WhereAndInfo {
  127692. WhereClause wc; /* The subexpression broken out */
  127693. };
  127694. /*
  127695. ** An instance of the following structure keeps track of a mapping
  127696. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  127697. **
  127698. ** The VDBE cursor numbers are small integers contained in
  127699. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  127700. ** clause, the cursor numbers might not begin with 0 and they might
  127701. ** contain gaps in the numbering sequence. But we want to make maximum
  127702. ** use of the bits in our bitmasks. This structure provides a mapping
  127703. ** from the sparse cursor numbers into consecutive integers beginning
  127704. ** with 0.
  127705. **
  127706. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  127707. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  127708. **
  127709. ** For example, if the WHERE clause expression used these VDBE
  127710. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  127711. ** would map those cursor numbers into bits 0 through 5.
  127712. **
  127713. ** Note that the mapping is not necessarily ordered. In the example
  127714. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  127715. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  127716. ** does not really matter. What is important is that sparse cursor
  127717. ** numbers all get mapped into bit numbers that begin with 0 and contain
  127718. ** no gaps.
  127719. */
  127720. struct WhereMaskSet {
  127721. int bVarSelect; /* Used by sqlite3WhereExprUsage() */
  127722. int n; /* Number of assigned cursor values */
  127723. int ix[BMS]; /* Cursor assigned to each bit */
  127724. };
  127725. /*
  127726. ** Initialize a WhereMaskSet object
  127727. */
  127728. #define initMaskSet(P) (P)->n=0
  127729. /*
  127730. ** This object is a convenience wrapper holding all information needed
  127731. ** to construct WhereLoop objects for a particular query.
  127732. */
  127733. struct WhereLoopBuilder {
  127734. WhereInfo *pWInfo; /* Information about this WHERE */
  127735. WhereClause *pWC; /* WHERE clause terms */
  127736. ExprList *pOrderBy; /* ORDER BY clause */
  127737. WhereLoop *pNew; /* Template WhereLoop */
  127738. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  127739. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  127740. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  127741. int nRecValid; /* Number of valid fields currently in pRec */
  127742. #endif
  127743. unsigned int bldFlags; /* SQLITE_BLDF_* flags */
  127744. unsigned int iPlanLimit; /* Search limiter */
  127745. };
  127746. /* Allowed values for WhereLoopBuider.bldFlags */
  127747. #define SQLITE_BLDF_INDEXED 0x0001 /* An index is used */
  127748. #define SQLITE_BLDF_UNIQUE 0x0002 /* All keys of a UNIQUE index used */
  127749. /* The WhereLoopBuilder.iPlanLimit is used to limit the number of
  127750. ** index+constraint combinations the query planner will consider for a
  127751. ** particular query. If this parameter is unlimited, then certain
  127752. ** pathological queries can spend excess time in the sqlite3WhereBegin()
  127753. ** routine. The limit is high enough that is should not impact real-world
  127754. ** queries.
  127755. **
  127756. ** SQLITE_QUERY_PLANNER_LIMIT is the baseline limit. The limit is
  127757. ** increased by SQLITE_QUERY_PLANNER_LIMIT_INCR before each term of the FROM
  127758. ** clause is processed, so that every table in a join is guaranteed to be
  127759. ** able to propose a some index+constraint combinations even if the initial
  127760. ** baseline limit was exhausted by prior tables of the join.
  127761. */
  127762. #ifndef SQLITE_QUERY_PLANNER_LIMIT
  127763. # define SQLITE_QUERY_PLANNER_LIMIT 20000
  127764. #endif
  127765. #ifndef SQLITE_QUERY_PLANNER_LIMIT_INCR
  127766. # define SQLITE_QUERY_PLANNER_LIMIT_INCR 1000
  127767. #endif
  127768. /*
  127769. ** The WHERE clause processing routine has two halves. The
  127770. ** first part does the start of the WHERE loop and the second
  127771. ** half does the tail of the WHERE loop. An instance of
  127772. ** this structure is returned by the first half and passed
  127773. ** into the second half to give some continuity.
  127774. **
  127775. ** An instance of this object holds the complete state of the query
  127776. ** planner.
  127777. */
  127778. struct WhereInfo {
  127779. Parse *pParse; /* Parsing and code generating context */
  127780. SrcList *pTabList; /* List of tables in the join */
  127781. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  127782. ExprList *pResultSet; /* Result set of the query */
  127783. Expr *pWhere; /* The complete WHERE clause */
  127784. LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
  127785. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  127786. int iContinue; /* Jump here to continue with next record */
  127787. int iBreak; /* Jump here to break out of the loop */
  127788. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  127789. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  127790. u8 nLevel; /* Number of nested loop */
  127791. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  127792. u8 sorted; /* True if really sorted (not just grouped) */
  127793. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  127794. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  127795. u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
  127796. u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */
  127797. int iTop; /* The very beginning of the WHERE loop */
  127798. WhereLoop *pLoops; /* List of all WhereLoop objects */
  127799. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  127800. LogEst nRowOut; /* Estimated number of output rows */
  127801. WhereClause sWC; /* Decomposition of the WHERE clause */
  127802. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  127803. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  127804. };
  127805. /*
  127806. ** Private interfaces - callable only by other where.c routines.
  127807. **
  127808. ** where.c:
  127809. */
  127810. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  127811. #ifdef WHERETRACE_ENABLED
  127812. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
  127813. #endif
  127814. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  127815. WhereClause *pWC, /* The WHERE clause to be searched */
  127816. int iCur, /* Cursor number of LHS */
  127817. int iColumn, /* Column number of LHS */
  127818. Bitmask notReady, /* RHS must not overlap with this mask */
  127819. u32 op, /* Mask of WO_xx values describing operator */
  127820. Index *pIdx /* Must be compatible with this index, if not NULL */
  127821. );
  127822. /* wherecode.c: */
  127823. #ifndef SQLITE_OMIT_EXPLAIN
  127824. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  127825. Parse *pParse, /* Parse context */
  127826. SrcList *pTabList, /* Table list this loop refers to */
  127827. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  127828. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  127829. );
  127830. #else
  127831. # define sqlite3WhereExplainOneScan(u,v,w,x) 0
  127832. #endif /* SQLITE_OMIT_EXPLAIN */
  127833. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  127834. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  127835. Vdbe *v, /* Vdbe to add scanstatus entry to */
  127836. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  127837. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  127838. int addrExplain /* Address of OP_Explain (or 0) */
  127839. );
  127840. #else
  127841. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  127842. #endif
  127843. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  127844. Parse *pParse, /* Parsing context */
  127845. Vdbe *v, /* Prepared statement under construction */
  127846. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  127847. int iLevel, /* Which level of pWInfo->a[] should be coded */
  127848. WhereLevel *pLevel, /* The current level pointer */
  127849. Bitmask notReady /* Which tables are currently available */
  127850. );
  127851. /* whereexpr.c: */
  127852. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  127853. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  127854. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  127855. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  127856. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
  127857. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  127858. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  127859. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  127860. /*
  127861. ** Bitmasks for the operators on WhereTerm objects. These are all
  127862. ** operators that are of interest to the query planner. An
  127863. ** OR-ed combination of these values can be used when searching for
  127864. ** particular WhereTerms within a WhereClause.
  127865. **
  127866. ** Value constraints:
  127867. ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
  127868. ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
  127869. ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
  127870. ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
  127871. ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
  127872. */
  127873. #define WO_IN 0x0001
  127874. #define WO_EQ 0x0002
  127875. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  127876. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  127877. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  127878. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  127879. #define WO_AUX 0x0040 /* Op useful to virtual tables only */
  127880. #define WO_IS 0x0080
  127881. #define WO_ISNULL 0x0100
  127882. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  127883. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  127884. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  127885. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  127886. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  127887. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  127888. /*
  127889. ** These are definitions of bits in the WhereLoop.wsFlags field.
  127890. ** The particular combination of bits in each WhereLoop help to
  127891. ** determine the algorithm that WhereLoop represents.
  127892. */
  127893. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  127894. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  127895. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  127896. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  127897. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  127898. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  127899. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  127900. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  127901. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  127902. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  127903. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  127904. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  127905. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  127906. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  127907. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  127908. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  127909. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  127910. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  127911. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  127912. #define WHERE_IN_EARLYOUT 0x00040000 /* Perhaps quit IN loops early */
  127913. /************** End of whereInt.h ********************************************/
  127914. /************** Continuing where we left off in wherecode.c ******************/
  127915. #ifndef SQLITE_OMIT_EXPLAIN
  127916. /*
  127917. ** Return the name of the i-th column of the pIdx index.
  127918. */
  127919. static const char *explainIndexColumnName(Index *pIdx, int i){
  127920. i = pIdx->aiColumn[i];
  127921. if( i==XN_EXPR ) return "<expr>";
  127922. if( i==XN_ROWID ) return "rowid";
  127923. return pIdx->pTable->aCol[i].zName;
  127924. }
  127925. /*
  127926. ** This routine is a helper for explainIndexRange() below
  127927. **
  127928. ** pStr holds the text of an expression that we are building up one term
  127929. ** at a time. This routine adds a new term to the end of the expression.
  127930. ** Terms are separated by AND so add the "AND" text for second and subsequent
  127931. ** terms only.
  127932. */
  127933. static void explainAppendTerm(
  127934. StrAccum *pStr, /* The text expression being built */
  127935. Index *pIdx, /* Index to read column names from */
  127936. int nTerm, /* Number of terms */
  127937. int iTerm, /* Zero-based index of first term. */
  127938. int bAnd, /* Non-zero to append " AND " */
  127939. const char *zOp /* Name of the operator */
  127940. ){
  127941. int i;
  127942. assert( nTerm>=1 );
  127943. if( bAnd ) sqlite3_str_append(pStr, " AND ", 5);
  127944. if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
  127945. for(i=0; i<nTerm; i++){
  127946. if( i ) sqlite3_str_append(pStr, ",", 1);
  127947. sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i));
  127948. }
  127949. if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
  127950. sqlite3_str_append(pStr, zOp, 1);
  127951. if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
  127952. for(i=0; i<nTerm; i++){
  127953. if( i ) sqlite3_str_append(pStr, ",", 1);
  127954. sqlite3_str_append(pStr, "?", 1);
  127955. }
  127956. if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
  127957. }
  127958. /*
  127959. ** Argument pLevel describes a strategy for scanning table pTab. This
  127960. ** function appends text to pStr that describes the subset of table
  127961. ** rows scanned by the strategy in the form of an SQL expression.
  127962. **
  127963. ** For example, if the query:
  127964. **
  127965. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  127966. **
  127967. ** is run and there is an index on (a, b), then this function returns a
  127968. ** string similar to:
  127969. **
  127970. ** "a=? AND b>?"
  127971. */
  127972. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  127973. Index *pIndex = pLoop->u.btree.pIndex;
  127974. u16 nEq = pLoop->u.btree.nEq;
  127975. u16 nSkip = pLoop->nSkip;
  127976. int i, j;
  127977. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  127978. sqlite3_str_append(pStr, " (", 2);
  127979. for(i=0; i<nEq; i++){
  127980. const char *z = explainIndexColumnName(pIndex, i);
  127981. if( i ) sqlite3_str_append(pStr, " AND ", 5);
  127982. sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  127983. }
  127984. j = i;
  127985. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  127986. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
  127987. i = 1;
  127988. }
  127989. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  127990. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
  127991. }
  127992. sqlite3_str_append(pStr, ")", 1);
  127993. }
  127994. /*
  127995. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  127996. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  127997. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  127998. ** is added to the output to describe the table scan strategy in pLevel.
  127999. **
  128000. ** If an OP_Explain opcode is added to the VM, its address is returned.
  128001. ** Otherwise, if no OP_Explain is coded, zero is returned.
  128002. */
  128003. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  128004. Parse *pParse, /* Parse context */
  128005. SrcList *pTabList, /* Table list this loop refers to */
  128006. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  128007. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  128008. ){
  128009. int ret = 0;
  128010. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  128011. if( sqlite3ParseToplevel(pParse)->explain==2 )
  128012. #endif
  128013. {
  128014. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  128015. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  128016. sqlite3 *db = pParse->db; /* Database handle */
  128017. int isSearch; /* True for a SEARCH. False for SCAN. */
  128018. WhereLoop *pLoop; /* The controlling WhereLoop object */
  128019. u32 flags; /* Flags that describe this loop */
  128020. char *zMsg; /* Text to add to EQP output */
  128021. StrAccum str; /* EQP output string */
  128022. char zBuf[100]; /* Initial space for EQP output string */
  128023. pLoop = pLevel->pWLoop;
  128024. flags = pLoop->wsFlags;
  128025. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
  128026. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  128027. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  128028. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  128029. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  128030. sqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN");
  128031. if( pItem->pSelect ){
  128032. sqlite3_str_appendf(&str, " SUBQUERY %u", pItem->pSelect->selId);
  128033. }else{
  128034. sqlite3_str_appendf(&str, " TABLE %s", pItem->zName);
  128035. }
  128036. if( pItem->zAlias ){
  128037. sqlite3_str_appendf(&str, " AS %s", pItem->zAlias);
  128038. }
  128039. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  128040. const char *zFmt = 0;
  128041. Index *pIdx;
  128042. assert( pLoop->u.btree.pIndex!=0 );
  128043. pIdx = pLoop->u.btree.pIndex;
  128044. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  128045. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  128046. if( isSearch ){
  128047. zFmt = "PRIMARY KEY";
  128048. }
  128049. }else if( flags & WHERE_PARTIALIDX ){
  128050. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  128051. }else if( flags & WHERE_AUTO_INDEX ){
  128052. zFmt = "AUTOMATIC COVERING INDEX";
  128053. }else if( flags & WHERE_IDX_ONLY ){
  128054. zFmt = "COVERING INDEX %s";
  128055. }else{
  128056. zFmt = "INDEX %s";
  128057. }
  128058. if( zFmt ){
  128059. sqlite3_str_append(&str, " USING ", 7);
  128060. sqlite3_str_appendf(&str, zFmt, pIdx->zName);
  128061. explainIndexRange(&str, pLoop);
  128062. }
  128063. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  128064. const char *zRangeOp;
  128065. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  128066. zRangeOp = "=";
  128067. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  128068. zRangeOp = ">? AND rowid<";
  128069. }else if( flags&WHERE_BTM_LIMIT ){
  128070. zRangeOp = ">";
  128071. }else{
  128072. assert( flags&WHERE_TOP_LIMIT);
  128073. zRangeOp = "<";
  128074. }
  128075. sqlite3_str_appendf(&str,
  128076. " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  128077. }
  128078. #ifndef SQLITE_OMIT_VIRTUALTABLE
  128079. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  128080. sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s",
  128081. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  128082. }
  128083. #endif
  128084. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  128085. if( pLoop->nOut>=10 ){
  128086. sqlite3_str_appendf(&str, " (~%llu rows)",
  128087. sqlite3LogEstToInt(pLoop->nOut));
  128088. }else{
  128089. sqlite3_str_append(&str, " (~1 row)", 9);
  128090. }
  128091. #endif
  128092. zMsg = sqlite3StrAccumFinish(&str);
  128093. sqlite3ExplainBreakpoint("",zMsg);
  128094. ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
  128095. pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
  128096. }
  128097. return ret;
  128098. }
  128099. #endif /* SQLITE_OMIT_EXPLAIN */
  128100. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  128101. /*
  128102. ** Configure the VM passed as the first argument with an
  128103. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  128104. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  128105. ** clause that the scan reads data from.
  128106. **
  128107. ** If argument addrExplain is not 0, it must be the address of an
  128108. ** OP_Explain instruction that describes the same loop.
  128109. */
  128110. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  128111. Vdbe *v, /* Vdbe to add scanstatus entry to */
  128112. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  128113. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  128114. int addrExplain /* Address of OP_Explain (or 0) */
  128115. ){
  128116. const char *zObj = 0;
  128117. WhereLoop *pLoop = pLvl->pWLoop;
  128118. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  128119. zObj = pLoop->u.btree.pIndex->zName;
  128120. }else{
  128121. zObj = pSrclist->a[pLvl->iFrom].zName;
  128122. }
  128123. sqlite3VdbeScanStatus(
  128124. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  128125. );
  128126. }
  128127. #endif
  128128. /*
  128129. ** Disable a term in the WHERE clause. Except, do not disable the term
  128130. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  128131. ** or USING clause of that join.
  128132. **
  128133. ** Consider the term t2.z='ok' in the following queries:
  128134. **
  128135. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  128136. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  128137. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  128138. **
  128139. ** The t2.z='ok' is disabled in the in (2) because it originates
  128140. ** in the ON clause. The term is disabled in (3) because it is not part
  128141. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  128142. **
  128143. ** Disabling a term causes that term to not be tested in the inner loop
  128144. ** of the join. Disabling is an optimization. When terms are satisfied
  128145. ** by indices, we disable them to prevent redundant tests in the inner
  128146. ** loop. We would get the correct results if nothing were ever disabled,
  128147. ** but joins might run a little slower. The trick is to disable as much
  128148. ** as we can without disabling too much. If we disabled in (1), we'd get
  128149. ** the wrong answer. See ticket #813.
  128150. **
  128151. ** If all the children of a term are disabled, then that term is also
  128152. ** automatically disabled. In this way, terms get disabled if derived
  128153. ** virtual terms are tested first. For example:
  128154. **
  128155. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  128156. ** \___________/ \______/ \_____/
  128157. ** parent child1 child2
  128158. **
  128159. ** Only the parent term was in the original WHERE clause. The child1
  128160. ** and child2 terms were added by the LIKE optimization. If both of
  128161. ** the virtual child terms are valid, then testing of the parent can be
  128162. ** skipped.
  128163. **
  128164. ** Usually the parent term is marked as TERM_CODED. But if the parent
  128165. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  128166. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  128167. ** a conditional such that is only evaluated on the second pass of a
  128168. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  128169. */
  128170. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  128171. int nLoop = 0;
  128172. assert( pTerm!=0 );
  128173. while( (pTerm->wtFlags & TERM_CODED)==0
  128174. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  128175. && (pLevel->notReady & pTerm->prereqAll)==0
  128176. ){
  128177. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  128178. pTerm->wtFlags |= TERM_LIKECOND;
  128179. }else{
  128180. pTerm->wtFlags |= TERM_CODED;
  128181. }
  128182. if( pTerm->iParent<0 ) break;
  128183. pTerm = &pTerm->pWC->a[pTerm->iParent];
  128184. assert( pTerm!=0 );
  128185. pTerm->nChild--;
  128186. if( pTerm->nChild!=0 ) break;
  128187. nLoop++;
  128188. }
  128189. }
  128190. /*
  128191. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  128192. ** to the n registers starting at base.
  128193. **
  128194. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  128195. ** beginning and end of zAff are ignored. If all entries in zAff are
  128196. ** SQLITE_AFF_BLOB, then no code gets generated.
  128197. **
  128198. ** This routine makes its own copy of zAff so that the caller is free
  128199. ** to modify zAff after this routine returns.
  128200. */
  128201. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  128202. Vdbe *v = pParse->pVdbe;
  128203. if( zAff==0 ){
  128204. assert( pParse->db->mallocFailed );
  128205. return;
  128206. }
  128207. assert( v!=0 );
  128208. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  128209. ** and end of the affinity string.
  128210. */
  128211. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  128212. n--;
  128213. base++;
  128214. zAff++;
  128215. }
  128216. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  128217. n--;
  128218. }
  128219. /* Code the OP_Affinity opcode if there is anything left to do. */
  128220. if( n>0 ){
  128221. sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
  128222. }
  128223. }
  128224. /*
  128225. ** Expression pRight, which is the RHS of a comparison operation, is
  128226. ** either a vector of n elements or, if n==1, a scalar expression.
  128227. ** Before the comparison operation, affinity zAff is to be applied
  128228. ** to the pRight values. This function modifies characters within the
  128229. ** affinity string to SQLITE_AFF_BLOB if either:
  128230. **
  128231. ** * the comparison will be performed with no affinity, or
  128232. ** * the affinity change in zAff is guaranteed not to change the value.
  128233. */
  128234. static void updateRangeAffinityStr(
  128235. Expr *pRight, /* RHS of comparison */
  128236. int n, /* Number of vector elements in comparison */
  128237. char *zAff /* Affinity string to modify */
  128238. ){
  128239. int i;
  128240. for(i=0; i<n; i++){
  128241. Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
  128242. if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
  128243. || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
  128244. ){
  128245. zAff[i] = SQLITE_AFF_BLOB;
  128246. }
  128247. }
  128248. }
  128249. /*
  128250. ** pX is an expression of the form: (vector) IN (SELECT ...)
  128251. ** In other words, it is a vector IN operator with a SELECT clause on the
  128252. ** LHS. But not all terms in the vector are indexable and the terms might
  128253. ** not be in the correct order for indexing.
  128254. **
  128255. ** This routine makes a copy of the input pX expression and then adjusts
  128256. ** the vector on the LHS with corresponding changes to the SELECT so that
  128257. ** the vector contains only index terms and those terms are in the correct
  128258. ** order. The modified IN expression is returned. The caller is responsible
  128259. ** for deleting the returned expression.
  128260. **
  128261. ** Example:
  128262. **
  128263. ** CREATE TABLE t1(a,b,c,d,e,f);
  128264. ** CREATE INDEX t1x1 ON t1(e,c);
  128265. ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
  128266. ** \_______________________________________/
  128267. ** The pX expression
  128268. **
  128269. ** Since only columns e and c can be used with the index, in that order,
  128270. ** the modified IN expression that is returned will be:
  128271. **
  128272. ** (e,c) IN (SELECT z,x FROM t2)
  128273. **
  128274. ** The reduced pX is different from the original (obviously) and thus is
  128275. ** only used for indexing, to improve performance. The original unaltered
  128276. ** IN expression must also be run on each output row for correctness.
  128277. */
  128278. static Expr *removeUnindexableInClauseTerms(
  128279. Parse *pParse, /* The parsing context */
  128280. int iEq, /* Look at loop terms starting here */
  128281. WhereLoop *pLoop, /* The current loop */
  128282. Expr *pX /* The IN expression to be reduced */
  128283. ){
  128284. sqlite3 *db = pParse->db;
  128285. Expr *pNew = sqlite3ExprDup(db, pX, 0);
  128286. if( db->mallocFailed==0 ){
  128287. ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */
  128288. ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */
  128289. ExprList *pRhs = 0; /* New RHS after modifications */
  128290. ExprList *pLhs = 0; /* New LHS after mods */
  128291. int i; /* Loop counter */
  128292. Select *pSelect; /* Pointer to the SELECT on the RHS */
  128293. for(i=iEq; i<pLoop->nLTerm; i++){
  128294. if( pLoop->aLTerm[i]->pExpr==pX ){
  128295. int iField = pLoop->aLTerm[i]->iField - 1;
  128296. if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
  128297. pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
  128298. pOrigRhs->a[iField].pExpr = 0;
  128299. assert( pOrigLhs->a[iField].pExpr!=0 );
  128300. pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
  128301. pOrigLhs->a[iField].pExpr = 0;
  128302. }
  128303. }
  128304. sqlite3ExprListDelete(db, pOrigRhs);
  128305. sqlite3ExprListDelete(db, pOrigLhs);
  128306. pNew->pLeft->x.pList = pLhs;
  128307. pNew->x.pSelect->pEList = pRhs;
  128308. if( pLhs && pLhs->nExpr==1 ){
  128309. /* Take care here not to generate a TK_VECTOR containing only a
  128310. ** single value. Since the parser never creates such a vector, some
  128311. ** of the subroutines do not handle this case. */
  128312. Expr *p = pLhs->a[0].pExpr;
  128313. pLhs->a[0].pExpr = 0;
  128314. sqlite3ExprDelete(db, pNew->pLeft);
  128315. pNew->pLeft = p;
  128316. }
  128317. pSelect = pNew->x.pSelect;
  128318. if( pSelect->pOrderBy ){
  128319. /* If the SELECT statement has an ORDER BY clause, zero the
  128320. ** iOrderByCol variables. These are set to non-zero when an
  128321. ** ORDER BY term exactly matches one of the terms of the
  128322. ** result-set. Since the result-set of the SELECT statement may
  128323. ** have been modified or reordered, these variables are no longer
  128324. ** set correctly. Since setting them is just an optimization,
  128325. ** it's easiest just to zero them here. */
  128326. ExprList *pOrderBy = pSelect->pOrderBy;
  128327. for(i=0; i<pOrderBy->nExpr; i++){
  128328. pOrderBy->a[i].u.x.iOrderByCol = 0;
  128329. }
  128330. }
  128331. #if 0
  128332. printf("For indexing, change the IN expr:\n");
  128333. sqlite3TreeViewExpr(0, pX, 0);
  128334. printf("Into:\n");
  128335. sqlite3TreeViewExpr(0, pNew, 0);
  128336. #endif
  128337. }
  128338. return pNew;
  128339. }
  128340. /*
  128341. ** Generate code for a single equality term of the WHERE clause. An equality
  128342. ** term can be either X=expr or X IN (...). pTerm is the term to be
  128343. ** coded.
  128344. **
  128345. ** The current value for the constraint is left in a register, the index
  128346. ** of which is returned. An attempt is made store the result in iTarget but
  128347. ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
  128348. ** constraint is a TK_EQ or TK_IS, then the current value might be left in
  128349. ** some other register and it is the caller's responsibility to compensate.
  128350. **
  128351. ** For a constraint of the form X=expr, the expression is evaluated in
  128352. ** straight-line code. For constraints of the form X IN (...)
  128353. ** this routine sets up a loop that will iterate over all values of X.
  128354. */
  128355. static int codeEqualityTerm(
  128356. Parse *pParse, /* The parsing context */
  128357. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  128358. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  128359. int iEq, /* Index of the equality term within this level */
  128360. int bRev, /* True for reverse-order IN operations */
  128361. int iTarget /* Attempt to leave results in this register */
  128362. ){
  128363. Expr *pX = pTerm->pExpr;
  128364. Vdbe *v = pParse->pVdbe;
  128365. int iReg; /* Register holding results */
  128366. assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
  128367. assert( iTarget>0 );
  128368. if( pX->op==TK_EQ || pX->op==TK_IS ){
  128369. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  128370. }else if( pX->op==TK_ISNULL ){
  128371. iReg = iTarget;
  128372. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  128373. #ifndef SQLITE_OMIT_SUBQUERY
  128374. }else{
  128375. int eType = IN_INDEX_NOOP;
  128376. int iTab;
  128377. struct InLoop *pIn;
  128378. WhereLoop *pLoop = pLevel->pWLoop;
  128379. int i;
  128380. int nEq = 0;
  128381. int *aiMap = 0;
  128382. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  128383. && pLoop->u.btree.pIndex!=0
  128384. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  128385. ){
  128386. testcase( iEq==0 );
  128387. testcase( bRev );
  128388. bRev = !bRev;
  128389. }
  128390. assert( pX->op==TK_IN );
  128391. iReg = iTarget;
  128392. for(i=0; i<iEq; i++){
  128393. if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
  128394. disableTerm(pLevel, pTerm);
  128395. return iTarget;
  128396. }
  128397. }
  128398. for(i=iEq;i<pLoop->nLTerm; i++){
  128399. assert( pLoop->aLTerm[i]!=0 );
  128400. if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
  128401. }
  128402. iTab = 0;
  128403. if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
  128404. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);
  128405. }else{
  128406. sqlite3 *db = pParse->db;
  128407. pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
  128408. if( !db->mallocFailed ){
  128409. aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
  128410. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab);
  128411. pTerm->pExpr->iTable = iTab;
  128412. }
  128413. sqlite3ExprDelete(db, pX);
  128414. pX = pTerm->pExpr;
  128415. }
  128416. if( eType==IN_INDEX_INDEX_DESC ){
  128417. testcase( bRev );
  128418. bRev = !bRev;
  128419. }
  128420. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  128421. VdbeCoverageIf(v, bRev);
  128422. VdbeCoverageIf(v, !bRev);
  128423. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  128424. pLoop->wsFlags |= WHERE_IN_ABLE;
  128425. if( pLevel->u.in.nIn==0 ){
  128426. pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
  128427. }
  128428. i = pLevel->u.in.nIn;
  128429. pLevel->u.in.nIn += nEq;
  128430. pLevel->u.in.aInLoop =
  128431. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  128432. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  128433. pIn = pLevel->u.in.aInLoop;
  128434. if( pIn ){
  128435. int iMap = 0; /* Index in aiMap[] */
  128436. pIn += i;
  128437. for(i=iEq;i<pLoop->nLTerm; i++){
  128438. if( pLoop->aLTerm[i]->pExpr==pX ){
  128439. int iOut = iReg + i - iEq;
  128440. if( eType==IN_INDEX_ROWID ){
  128441. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
  128442. }else{
  128443. int iCol = aiMap ? aiMap[iMap++] : 0;
  128444. pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
  128445. }
  128446. sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
  128447. if( i==iEq ){
  128448. pIn->iCur = iTab;
  128449. pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
  128450. if( iEq>0 && (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  128451. pIn->iBase = iReg - i;
  128452. pIn->nPrefix = i;
  128453. pLoop->wsFlags |= WHERE_IN_EARLYOUT;
  128454. }else{
  128455. pIn->nPrefix = 0;
  128456. }
  128457. }else{
  128458. pIn->eEndLoopOp = OP_Noop;
  128459. }
  128460. pIn++;
  128461. }
  128462. }
  128463. }else{
  128464. pLevel->u.in.nIn = 0;
  128465. }
  128466. sqlite3DbFree(pParse->db, aiMap);
  128467. #endif
  128468. }
  128469. disableTerm(pLevel, pTerm);
  128470. return iReg;
  128471. }
  128472. /*
  128473. ** Generate code that will evaluate all == and IN constraints for an
  128474. ** index scan.
  128475. **
  128476. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  128477. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  128478. ** The index has as many as three equality constraints, but in this
  128479. ** example, the third "c" value is an inequality. So only two
  128480. ** constraints are coded. This routine will generate code to evaluate
  128481. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  128482. ** in consecutive registers and the index of the first register is returned.
  128483. **
  128484. ** In the example above nEq==2. But this subroutine works for any value
  128485. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  128486. ** The only thing it does is allocate the pLevel->iMem memory cell and
  128487. ** compute the affinity string.
  128488. **
  128489. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  128490. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  128491. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  128492. ** occurs after the nEq quality constraints.
  128493. **
  128494. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  128495. ** the index of the first memory cell in that range. The code that
  128496. ** calls this routine will use that memory range to store keys for
  128497. ** start and termination conditions of the loop.
  128498. ** key value of the loop. If one or more IN operators appear, then
  128499. ** this routine allocates an additional nEq memory cells for internal
  128500. ** use.
  128501. **
  128502. ** Before returning, *pzAff is set to point to a buffer containing a
  128503. ** copy of the column affinity string of the index allocated using
  128504. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  128505. ** with equality constraints that use BLOB or NONE affinity are set to
  128506. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  128507. **
  128508. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  128509. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  128510. **
  128511. ** In the example above, the index on t1(a) has TEXT affinity. But since
  128512. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  128513. ** no conversion should be attempted before using a t2.b value as part of
  128514. ** a key to search the index. Hence the first byte in the returned affinity
  128515. ** string in this example would be set to SQLITE_AFF_BLOB.
  128516. */
  128517. static int codeAllEqualityTerms(
  128518. Parse *pParse, /* Parsing context */
  128519. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  128520. int bRev, /* Reverse the order of IN operators */
  128521. int nExtraReg, /* Number of extra registers to allocate */
  128522. char **pzAff /* OUT: Set to point to affinity string */
  128523. ){
  128524. u16 nEq; /* The number of == or IN constraints to code */
  128525. u16 nSkip; /* Number of left-most columns to skip */
  128526. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  128527. Index *pIdx; /* The index being used for this loop */
  128528. WhereTerm *pTerm; /* A single constraint term */
  128529. WhereLoop *pLoop; /* The WhereLoop object */
  128530. int j; /* Loop counter */
  128531. int regBase; /* Base register */
  128532. int nReg; /* Number of registers to allocate */
  128533. char *zAff; /* Affinity string to return */
  128534. /* This module is only called on query plans that use an index. */
  128535. pLoop = pLevel->pWLoop;
  128536. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  128537. nEq = pLoop->u.btree.nEq;
  128538. nSkip = pLoop->nSkip;
  128539. pIdx = pLoop->u.btree.pIndex;
  128540. assert( pIdx!=0 );
  128541. /* Figure out how many memory cells we will need then allocate them.
  128542. */
  128543. regBase = pParse->nMem + 1;
  128544. nReg = pLoop->u.btree.nEq + nExtraReg;
  128545. pParse->nMem += nReg;
  128546. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  128547. assert( zAff!=0 || pParse->db->mallocFailed );
  128548. if( nSkip ){
  128549. int iIdxCur = pLevel->iIdxCur;
  128550. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  128551. VdbeCoverageIf(v, bRev==0);
  128552. VdbeCoverageIf(v, bRev!=0);
  128553. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  128554. j = sqlite3VdbeAddOp0(v, OP_Goto);
  128555. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  128556. iIdxCur, 0, regBase, nSkip);
  128557. VdbeCoverageIf(v, bRev==0);
  128558. VdbeCoverageIf(v, bRev!=0);
  128559. sqlite3VdbeJumpHere(v, j);
  128560. for(j=0; j<nSkip; j++){
  128561. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  128562. testcase( pIdx->aiColumn[j]==XN_EXPR );
  128563. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  128564. }
  128565. }
  128566. /* Evaluate the equality constraints
  128567. */
  128568. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  128569. for(j=nSkip; j<nEq; j++){
  128570. int r1;
  128571. pTerm = pLoop->aLTerm[j];
  128572. assert( pTerm!=0 );
  128573. /* The following testcase is true for indices with redundant columns.
  128574. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  128575. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  128576. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  128577. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  128578. if( r1!=regBase+j ){
  128579. if( nReg==1 ){
  128580. sqlite3ReleaseTempReg(pParse, regBase);
  128581. regBase = r1;
  128582. }else{
  128583. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  128584. }
  128585. }
  128586. if( pTerm->eOperator & WO_IN ){
  128587. if( pTerm->pExpr->flags & EP_xIsSelect ){
  128588. /* No affinity ever needs to be (or should be) applied to a value
  128589. ** from the RHS of an "? IN (SELECT ...)" expression. The
  128590. ** sqlite3FindInIndex() routine has already ensured that the
  128591. ** affinity of the comparison has been applied to the value. */
  128592. if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
  128593. }
  128594. }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
  128595. Expr *pRight = pTerm->pExpr->pRight;
  128596. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  128597. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  128598. VdbeCoverage(v);
  128599. }
  128600. if( zAff ){
  128601. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  128602. zAff[j] = SQLITE_AFF_BLOB;
  128603. }
  128604. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  128605. zAff[j] = SQLITE_AFF_BLOB;
  128606. }
  128607. }
  128608. }
  128609. }
  128610. *pzAff = zAff;
  128611. return regBase;
  128612. }
  128613. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  128614. /*
  128615. ** If the most recently coded instruction is a constant range constraint
  128616. ** (a string literal) that originated from the LIKE optimization, then
  128617. ** set P3 and P5 on the OP_String opcode so that the string will be cast
  128618. ** to a BLOB at appropriate times.
  128619. **
  128620. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  128621. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  128622. ** scan loop run twice, once for strings and a second time for BLOBs.
  128623. ** The OP_String opcodes on the second pass convert the upper and lower
  128624. ** bound string constants to blobs. This routine makes the necessary changes
  128625. ** to the OP_String opcodes for that to happen.
  128626. **
  128627. ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
  128628. ** only the one pass through the string space is required, so this routine
  128629. ** becomes a no-op.
  128630. */
  128631. static void whereLikeOptimizationStringFixup(
  128632. Vdbe *v, /* prepared statement under construction */
  128633. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  128634. WhereTerm *pTerm /* The upper or lower bound just coded */
  128635. ){
  128636. if( pTerm->wtFlags & TERM_LIKEOPT ){
  128637. VdbeOp *pOp;
  128638. assert( pLevel->iLikeRepCntr>0 );
  128639. pOp = sqlite3VdbeGetOp(v, -1);
  128640. assert( pOp!=0 );
  128641. assert( pOp->opcode==OP_String8
  128642. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  128643. pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
  128644. pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
  128645. }
  128646. }
  128647. #else
  128648. # define whereLikeOptimizationStringFixup(A,B,C)
  128649. #endif
  128650. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  128651. /*
  128652. ** Information is passed from codeCursorHint() down to individual nodes of
  128653. ** the expression tree (by sqlite3WalkExpr()) using an instance of this
  128654. ** structure.
  128655. */
  128656. struct CCurHint {
  128657. int iTabCur; /* Cursor for the main table */
  128658. int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
  128659. Index *pIdx; /* The index used to access the table */
  128660. };
  128661. /*
  128662. ** This function is called for every node of an expression that is a candidate
  128663. ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
  128664. ** the table CCurHint.iTabCur, verify that the same column can be
  128665. ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
  128666. */
  128667. static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
  128668. struct CCurHint *pHint = pWalker->u.pCCurHint;
  128669. assert( pHint->pIdx!=0 );
  128670. if( pExpr->op==TK_COLUMN
  128671. && pExpr->iTable==pHint->iTabCur
  128672. && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
  128673. ){
  128674. pWalker->eCode = 1;
  128675. }
  128676. return WRC_Continue;
  128677. }
  128678. /*
  128679. ** Test whether or not expression pExpr, which was part of a WHERE clause,
  128680. ** should be included in the cursor-hint for a table that is on the rhs
  128681. ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
  128682. ** expression is not suitable.
  128683. **
  128684. ** An expression is unsuitable if it might evaluate to non NULL even if
  128685. ** a TK_COLUMN node that does affect the value of the expression is set
  128686. ** to NULL. For example:
  128687. **
  128688. ** col IS NULL
  128689. ** col IS NOT NULL
  128690. ** coalesce(col, 1)
  128691. ** CASE WHEN col THEN 0 ELSE 1 END
  128692. */
  128693. static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
  128694. if( pExpr->op==TK_IS
  128695. || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
  128696. || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
  128697. ){
  128698. pWalker->eCode = 1;
  128699. }else if( pExpr->op==TK_FUNCTION ){
  128700. int d1;
  128701. char d2[4];
  128702. if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
  128703. pWalker->eCode = 1;
  128704. }
  128705. }
  128706. return WRC_Continue;
  128707. }
  128708. /*
  128709. ** This function is called on every node of an expression tree used as an
  128710. ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
  128711. ** that accesses any table other than the one identified by
  128712. ** CCurHint.iTabCur, then do the following:
  128713. **
  128714. ** 1) allocate a register and code an OP_Column instruction to read
  128715. ** the specified column into the new register, and
  128716. **
  128717. ** 2) transform the expression node to a TK_REGISTER node that reads
  128718. ** from the newly populated register.
  128719. **
  128720. ** Also, if the node is a TK_COLUMN that does access the table idenified
  128721. ** by pCCurHint.iTabCur, and an index is being used (which we will
  128722. ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
  128723. ** an access of the index rather than the original table.
  128724. */
  128725. static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  128726. int rc = WRC_Continue;
  128727. struct CCurHint *pHint = pWalker->u.pCCurHint;
  128728. if( pExpr->op==TK_COLUMN ){
  128729. if( pExpr->iTable!=pHint->iTabCur ){
  128730. int reg = ++pWalker->pParse->nMem; /* Register for column value */
  128731. sqlite3ExprCode(pWalker->pParse, pExpr, reg);
  128732. pExpr->op = TK_REGISTER;
  128733. pExpr->iTable = reg;
  128734. }else if( pHint->pIdx!=0 ){
  128735. pExpr->iTable = pHint->iIdxCur;
  128736. pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
  128737. assert( pExpr->iColumn>=0 );
  128738. }
  128739. }else if( pExpr->op==TK_AGG_FUNCTION ){
  128740. /* An aggregate function in the WHERE clause of a query means this must
  128741. ** be a correlated sub-query, and expression pExpr is an aggregate from
  128742. ** the parent context. Do not walk the function arguments in this case.
  128743. **
  128744. ** todo: It should be possible to replace this node with a TK_REGISTER
  128745. ** expression, as the result of the expression must be stored in a
  128746. ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
  128747. rc = WRC_Prune;
  128748. }
  128749. return rc;
  128750. }
  128751. /*
  128752. ** Insert an OP_CursorHint instruction if it is appropriate to do so.
  128753. */
  128754. static void codeCursorHint(
  128755. struct SrcList_item *pTabItem, /* FROM clause item */
  128756. WhereInfo *pWInfo, /* The where clause */
  128757. WhereLevel *pLevel, /* Which loop to provide hints for */
  128758. WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
  128759. ){
  128760. Parse *pParse = pWInfo->pParse;
  128761. sqlite3 *db = pParse->db;
  128762. Vdbe *v = pParse->pVdbe;
  128763. Expr *pExpr = 0;
  128764. WhereLoop *pLoop = pLevel->pWLoop;
  128765. int iCur;
  128766. WhereClause *pWC;
  128767. WhereTerm *pTerm;
  128768. int i, j;
  128769. struct CCurHint sHint;
  128770. Walker sWalker;
  128771. if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
  128772. iCur = pLevel->iTabCur;
  128773. assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
  128774. sHint.iTabCur = iCur;
  128775. sHint.iIdxCur = pLevel->iIdxCur;
  128776. sHint.pIdx = pLoop->u.btree.pIndex;
  128777. memset(&sWalker, 0, sizeof(sWalker));
  128778. sWalker.pParse = pParse;
  128779. sWalker.u.pCCurHint = &sHint;
  128780. pWC = &pWInfo->sWC;
  128781. for(i=0; i<pWC->nTerm; i++){
  128782. pTerm = &pWC->a[i];
  128783. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  128784. if( pTerm->prereqAll & pLevel->notReady ) continue;
  128785. /* Any terms specified as part of the ON(...) clause for any LEFT
  128786. ** JOIN for which the current table is not the rhs are omitted
  128787. ** from the cursor-hint.
  128788. **
  128789. ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
  128790. ** that were specified as part of the WHERE clause must be excluded.
  128791. ** This is to address the following:
  128792. **
  128793. ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
  128794. **
  128795. ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
  128796. ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
  128797. ** pushed down to the cursor, this row is filtered out, causing
  128798. ** SQLite to synthesize a row of NULL values. Which does match the
  128799. ** WHERE clause, and so the query returns a row. Which is incorrect.
  128800. **
  128801. ** For the same reason, WHERE terms such as:
  128802. **
  128803. ** WHERE 1 = (t2.c IS NULL)
  128804. **
  128805. ** are also excluded. See codeCursorHintIsOrFunction() for details.
  128806. */
  128807. if( pTabItem->fg.jointype & JT_LEFT ){
  128808. Expr *pExpr = pTerm->pExpr;
  128809. if( !ExprHasProperty(pExpr, EP_FromJoin)
  128810. || pExpr->iRightJoinTable!=pTabItem->iCursor
  128811. ){
  128812. sWalker.eCode = 0;
  128813. sWalker.xExprCallback = codeCursorHintIsOrFunction;
  128814. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  128815. if( sWalker.eCode ) continue;
  128816. }
  128817. }else{
  128818. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
  128819. }
  128820. /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
  128821. ** the cursor. These terms are not needed as hints for a pure range
  128822. ** scan (that has no == terms) so omit them. */
  128823. if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
  128824. for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
  128825. if( j<pLoop->nLTerm ) continue;
  128826. }
  128827. /* No subqueries or non-deterministic functions allowed */
  128828. if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
  128829. /* For an index scan, make sure referenced columns are actually in
  128830. ** the index. */
  128831. if( sHint.pIdx!=0 ){
  128832. sWalker.eCode = 0;
  128833. sWalker.xExprCallback = codeCursorHintCheckExpr;
  128834. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  128835. if( sWalker.eCode ) continue;
  128836. }
  128837. /* If we survive all prior tests, that means this term is worth hinting */
  128838. pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  128839. }
  128840. if( pExpr!=0 ){
  128841. sWalker.xExprCallback = codeCursorHintFixExpr;
  128842. sqlite3WalkExpr(&sWalker, pExpr);
  128843. sqlite3VdbeAddOp4(v, OP_CursorHint,
  128844. (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
  128845. (const char*)pExpr, P4_EXPR);
  128846. }
  128847. }
  128848. #else
  128849. # define codeCursorHint(A,B,C,D) /* No-op */
  128850. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  128851. /*
  128852. ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
  128853. ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
  128854. ** function generates code to do a deferred seek of cursor iCur to the
  128855. ** rowid stored in register iRowid.
  128856. **
  128857. ** Normally, this is just:
  128858. **
  128859. ** OP_DeferredSeek $iCur $iRowid
  128860. **
  128861. ** However, if the scan currently being coded is a branch of an OR-loop and
  128862. ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
  128863. ** is set to iIdxCur and P4 is set to point to an array of integers
  128864. ** containing one entry for each column of the table cursor iCur is open
  128865. ** on. For each table column, if the column is the i'th column of the
  128866. ** index, then the corresponding array entry is set to (i+1). If the column
  128867. ** does not appear in the index at all, the array entry is set to 0.
  128868. */
  128869. static void codeDeferredSeek(
  128870. WhereInfo *pWInfo, /* Where clause context */
  128871. Index *pIdx, /* Index scan is using */
  128872. int iCur, /* Cursor for IPK b-tree */
  128873. int iIdxCur /* Index cursor */
  128874. ){
  128875. Parse *pParse = pWInfo->pParse; /* Parse context */
  128876. Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
  128877. assert( iIdxCur>0 );
  128878. assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
  128879. sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
  128880. if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  128881. && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
  128882. ){
  128883. int i;
  128884. Table *pTab = pIdx->pTable;
  128885. int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
  128886. if( ai ){
  128887. ai[0] = pTab->nCol;
  128888. for(i=0; i<pIdx->nColumn-1; i++){
  128889. assert( pIdx->aiColumn[i]<pTab->nCol );
  128890. if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
  128891. }
  128892. sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
  128893. }
  128894. }
  128895. }
  128896. /*
  128897. ** If the expression passed as the second argument is a vector, generate
  128898. ** code to write the first nReg elements of the vector into an array
  128899. ** of registers starting with iReg.
  128900. **
  128901. ** If the expression is not a vector, then nReg must be passed 1. In
  128902. ** this case, generate code to evaluate the expression and leave the
  128903. ** result in register iReg.
  128904. */
  128905. static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
  128906. assert( nReg>0 );
  128907. if( p && sqlite3ExprIsVector(p) ){
  128908. #ifndef SQLITE_OMIT_SUBQUERY
  128909. if( (p->flags & EP_xIsSelect) ){
  128910. Vdbe *v = pParse->pVdbe;
  128911. int iSelect;
  128912. assert( p->op==TK_SELECT );
  128913. iSelect = sqlite3CodeSubselect(pParse, p);
  128914. sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
  128915. }else
  128916. #endif
  128917. {
  128918. int i;
  128919. ExprList *pList = p->x.pList;
  128920. assert( nReg<=pList->nExpr );
  128921. for(i=0; i<nReg; i++){
  128922. sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
  128923. }
  128924. }
  128925. }else{
  128926. assert( nReg==1 );
  128927. sqlite3ExprCode(pParse, p, iReg);
  128928. }
  128929. }
  128930. /* An instance of the IdxExprTrans object carries information about a
  128931. ** mapping from an expression on table columns into a column in an index
  128932. ** down through the Walker.
  128933. */
  128934. typedef struct IdxExprTrans {
  128935. Expr *pIdxExpr; /* The index expression */
  128936. int iTabCur; /* The cursor of the corresponding table */
  128937. int iIdxCur; /* The cursor for the index */
  128938. int iIdxCol; /* The column for the index */
  128939. } IdxExprTrans;
  128940. /* The walker node callback used to transform matching expressions into
  128941. ** a reference to an index column for an index on an expression.
  128942. **
  128943. ** If pExpr matches, then transform it into a reference to the index column
  128944. ** that contains the value of pExpr.
  128945. */
  128946. static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
  128947. IdxExprTrans *pX = p->u.pIdxTrans;
  128948. if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
  128949. pExpr->op = TK_COLUMN;
  128950. pExpr->iTable = pX->iIdxCur;
  128951. pExpr->iColumn = pX->iIdxCol;
  128952. pExpr->y.pTab = 0;
  128953. return WRC_Prune;
  128954. }else{
  128955. return WRC_Continue;
  128956. }
  128957. }
  128958. /*
  128959. ** For an indexes on expression X, locate every instance of expression X
  128960. ** in pExpr and change that subexpression into a reference to the appropriate
  128961. ** column of the index.
  128962. */
  128963. static void whereIndexExprTrans(
  128964. Index *pIdx, /* The Index */
  128965. int iTabCur, /* Cursor of the table that is being indexed */
  128966. int iIdxCur, /* Cursor of the index itself */
  128967. WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
  128968. ){
  128969. int iIdxCol; /* Column number of the index */
  128970. ExprList *aColExpr; /* Expressions that are indexed */
  128971. Walker w;
  128972. IdxExprTrans x;
  128973. aColExpr = pIdx->aColExpr;
  128974. if( aColExpr==0 ) return; /* Not an index on expressions */
  128975. memset(&w, 0, sizeof(w));
  128976. w.xExprCallback = whereIndexExprTransNode;
  128977. w.u.pIdxTrans = &x;
  128978. x.iTabCur = iTabCur;
  128979. x.iIdxCur = iIdxCur;
  128980. for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
  128981. if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
  128982. assert( aColExpr->a[iIdxCol].pExpr!=0 );
  128983. x.iIdxCol = iIdxCol;
  128984. x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
  128985. sqlite3WalkExpr(&w, pWInfo->pWhere);
  128986. sqlite3WalkExprList(&w, pWInfo->pOrderBy);
  128987. sqlite3WalkExprList(&w, pWInfo->pResultSet);
  128988. }
  128989. }
  128990. /*
  128991. ** The pTruth expression is always true because it is the WHERE clause
  128992. ** a partial index that is driving a query loop. Look through all of the
  128993. ** WHERE clause terms on the query, and if any of those terms must be
  128994. ** true because pTruth is true, then mark those WHERE clause terms as
  128995. ** coded.
  128996. */
  128997. static void whereApplyPartialIndexConstraints(
  128998. Expr *pTruth,
  128999. int iTabCur,
  129000. WhereClause *pWC
  129001. ){
  129002. int i;
  129003. WhereTerm *pTerm;
  129004. while( pTruth->op==TK_AND ){
  129005. whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC);
  129006. pTruth = pTruth->pRight;
  129007. }
  129008. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  129009. Expr *pExpr;
  129010. if( pTerm->wtFlags & TERM_CODED ) continue;
  129011. pExpr = pTerm->pExpr;
  129012. if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){
  129013. pTerm->wtFlags |= TERM_CODED;
  129014. }
  129015. }
  129016. }
  129017. /*
  129018. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  129019. ** implementation described by pWInfo.
  129020. */
  129021. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  129022. Parse *pParse, /* Parsing context */
  129023. Vdbe *v, /* Prepared statement under construction */
  129024. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  129025. int iLevel, /* Which level of pWInfo->a[] should be coded */
  129026. WhereLevel *pLevel, /* The current level pointer */
  129027. Bitmask notReady /* Which tables are currently available */
  129028. ){
  129029. int j, k; /* Loop counters */
  129030. int iCur; /* The VDBE cursor for the table */
  129031. int addrNxt; /* Where to jump to continue with the next IN case */
  129032. int bRev; /* True if we need to scan in reverse order */
  129033. WhereLoop *pLoop; /* The WhereLoop object being coded */
  129034. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  129035. WhereTerm *pTerm; /* A WHERE clause term */
  129036. sqlite3 *db; /* Database connection */
  129037. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  129038. int addrBrk; /* Jump here to break out of the loop */
  129039. int addrHalt; /* addrBrk for the outermost loop */
  129040. int addrCont; /* Jump here to continue with next cycle */
  129041. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  129042. int iReleaseReg = 0; /* Temp register to free before returning */
  129043. Index *pIdx = 0; /* Index used by loop (if any) */
  129044. int iLoop; /* Iteration of constraint generator loop */
  129045. pWC = &pWInfo->sWC;
  129046. db = pParse->db;
  129047. pLoop = pLevel->pWLoop;
  129048. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  129049. iCur = pTabItem->iCursor;
  129050. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  129051. bRev = (pWInfo->revMask>>iLevel)&1;
  129052. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  129053. /* Create labels for the "break" and "continue" instructions
  129054. ** for the current loop. Jump to addrBrk to break out of a loop.
  129055. ** Jump to cont to go immediately to the next iteration of the
  129056. ** loop.
  129057. **
  129058. ** When there is an IN operator, we also have a "addrNxt" label that
  129059. ** means to continue with the next IN value combination. When
  129060. ** there are no IN operators in the constraints, the "addrNxt" label
  129061. ** is the same as "addrBrk".
  129062. */
  129063. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
  129064. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);
  129065. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  129066. ** initialize a memory cell that records if this table matches any
  129067. ** row of the left table of the join.
  129068. */
  129069. assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  129070. || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
  129071. );
  129072. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  129073. pLevel->iLeftJoin = ++pParse->nMem;
  129074. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  129075. VdbeComment((v, "init LEFT JOIN no-match flag"));
  129076. }
  129077. /* Compute a safe address to jump to if we discover that the table for
  129078. ** this loop is empty and can never contribute content. */
  129079. for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
  129080. addrHalt = pWInfo->a[j].addrBrk;
  129081. /* Special case of a FROM clause subquery implemented as a co-routine */
  129082. if( pTabItem->fg.viaCoroutine ){
  129083. int regYield = pTabItem->regReturn;
  129084. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  129085. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  129086. VdbeCoverage(v);
  129087. VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
  129088. pLevel->op = OP_Goto;
  129089. }else
  129090. #ifndef SQLITE_OMIT_VIRTUALTABLE
  129091. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  129092. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  129093. ** to access the data.
  129094. */
  129095. int iReg; /* P3 Value for OP_VFilter */
  129096. int addrNotFound;
  129097. int nConstraint = pLoop->nLTerm;
  129098. int iIn; /* Counter for IN constraints */
  129099. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  129100. addrNotFound = pLevel->addrBrk;
  129101. for(j=0; j<nConstraint; j++){
  129102. int iTarget = iReg+j+2;
  129103. pTerm = pLoop->aLTerm[j];
  129104. if( NEVER(pTerm==0) ) continue;
  129105. if( pTerm->eOperator & WO_IN ){
  129106. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  129107. addrNotFound = pLevel->addrNxt;
  129108. }else{
  129109. Expr *pRight = pTerm->pExpr->pRight;
  129110. codeExprOrVector(pParse, pRight, iTarget, 1);
  129111. }
  129112. }
  129113. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  129114. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  129115. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  129116. pLoop->u.vtab.idxStr,
  129117. pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
  129118. VdbeCoverage(v);
  129119. pLoop->u.vtab.needFree = 0;
  129120. pLevel->p1 = iCur;
  129121. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  129122. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  129123. iIn = pLevel->u.in.nIn;
  129124. for(j=nConstraint-1; j>=0; j--){
  129125. pTerm = pLoop->aLTerm[j];
  129126. if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
  129127. disableTerm(pLevel, pTerm);
  129128. }else if( (pTerm->eOperator & WO_IN)!=0 ){
  129129. Expr *pCompare; /* The comparison operator */
  129130. Expr *pRight; /* RHS of the comparison */
  129131. VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
  129132. /* Reload the constraint value into reg[iReg+j+2]. The same value
  129133. ** was loaded into the same register prior to the OP_VFilter, but
  129134. ** the xFilter implementation might have changed the datatype or
  129135. ** encoding of the value in the register, so it *must* be reloaded. */
  129136. assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
  129137. if( !db->mallocFailed ){
  129138. assert( iIn>0 );
  129139. pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
  129140. assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
  129141. assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
  129142. assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
  129143. testcase( pOp->opcode==OP_Rowid );
  129144. sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
  129145. }
  129146. /* Generate code that will continue to the next row if
  129147. ** the IN constraint is not satisfied */
  129148. pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
  129149. assert( pCompare!=0 || db->mallocFailed );
  129150. if( pCompare ){
  129151. pCompare->pLeft = pTerm->pExpr->pLeft;
  129152. pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
  129153. if( pRight ){
  129154. pRight->iTable = iReg+j+2;
  129155. sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
  129156. }
  129157. pCompare->pLeft = 0;
  129158. sqlite3ExprDelete(db, pCompare);
  129159. }
  129160. }
  129161. }
  129162. /* These registers need to be preserved in case there is an IN operator
  129163. ** loop. So we could deallocate the registers here (and potentially
  129164. ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
  129165. ** simpler and safer to simply not reuse the registers.
  129166. **
  129167. ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  129168. */
  129169. }else
  129170. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  129171. if( (pLoop->wsFlags & WHERE_IPK)!=0
  129172. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  129173. ){
  129174. /* Case 2: We can directly reference a single row using an
  129175. ** equality comparison against the ROWID field. Or
  129176. ** we reference multiple rows using a "rowid IN (...)"
  129177. ** construct.
  129178. */
  129179. assert( pLoop->u.btree.nEq==1 );
  129180. pTerm = pLoop->aLTerm[0];
  129181. assert( pTerm!=0 );
  129182. assert( pTerm->pExpr!=0 );
  129183. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  129184. iReleaseReg = ++pParse->nMem;
  129185. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  129186. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  129187. addrNxt = pLevel->addrNxt;
  129188. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
  129189. VdbeCoverage(v);
  129190. pLevel->op = OP_Noop;
  129191. if( (pTerm->prereqAll & pLevel->notReady)==0 ){
  129192. pTerm->wtFlags |= TERM_CODED;
  129193. }
  129194. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  129195. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  129196. ){
  129197. /* Case 3: We have an inequality comparison against the ROWID field.
  129198. */
  129199. int testOp = OP_Noop;
  129200. int start;
  129201. int memEndValue = 0;
  129202. WhereTerm *pStart, *pEnd;
  129203. j = 0;
  129204. pStart = pEnd = 0;
  129205. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  129206. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  129207. assert( pStart!=0 || pEnd!=0 );
  129208. if( bRev ){
  129209. pTerm = pStart;
  129210. pStart = pEnd;
  129211. pEnd = pTerm;
  129212. }
  129213. codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
  129214. if( pStart ){
  129215. Expr *pX; /* The expression that defines the start bound */
  129216. int r1, rTemp; /* Registers for holding the start boundary */
  129217. int op; /* Cursor seek operation */
  129218. /* The following constant maps TK_xx codes into corresponding
  129219. ** seek opcodes. It depends on a particular ordering of TK_xx
  129220. */
  129221. const u8 aMoveOp[] = {
  129222. /* TK_GT */ OP_SeekGT,
  129223. /* TK_LE */ OP_SeekLE,
  129224. /* TK_LT */ OP_SeekLT,
  129225. /* TK_GE */ OP_SeekGE
  129226. };
  129227. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  129228. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  129229. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  129230. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  129231. testcase( pStart->wtFlags & TERM_VIRTUAL );
  129232. pX = pStart->pExpr;
  129233. assert( pX!=0 );
  129234. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  129235. if( sqlite3ExprIsVector(pX->pRight) ){
  129236. r1 = rTemp = sqlite3GetTempReg(pParse);
  129237. codeExprOrVector(pParse, pX->pRight, r1, 1);
  129238. testcase( pX->op==TK_GT );
  129239. testcase( pX->op==TK_GE );
  129240. testcase( pX->op==TK_LT );
  129241. testcase( pX->op==TK_LE );
  129242. op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
  129243. assert( pX->op!=TK_GT || op==OP_SeekGE );
  129244. assert( pX->op!=TK_GE || op==OP_SeekGE );
  129245. assert( pX->op!=TK_LT || op==OP_SeekLE );
  129246. assert( pX->op!=TK_LE || op==OP_SeekLE );
  129247. }else{
  129248. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  129249. disableTerm(pLevel, pStart);
  129250. op = aMoveOp[(pX->op - TK_GT)];
  129251. }
  129252. sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
  129253. VdbeComment((v, "pk"));
  129254. VdbeCoverageIf(v, pX->op==TK_GT);
  129255. VdbeCoverageIf(v, pX->op==TK_LE);
  129256. VdbeCoverageIf(v, pX->op==TK_LT);
  129257. VdbeCoverageIf(v, pX->op==TK_GE);
  129258. sqlite3ReleaseTempReg(pParse, rTemp);
  129259. }else{
  129260. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
  129261. VdbeCoverageIf(v, bRev==0);
  129262. VdbeCoverageIf(v, bRev!=0);
  129263. }
  129264. if( pEnd ){
  129265. Expr *pX;
  129266. pX = pEnd->pExpr;
  129267. assert( pX!=0 );
  129268. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  129269. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  129270. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  129271. memEndValue = ++pParse->nMem;
  129272. codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
  129273. if( 0==sqlite3ExprIsVector(pX->pRight)
  129274. && (pX->op==TK_LT || pX->op==TK_GT)
  129275. ){
  129276. testOp = bRev ? OP_Le : OP_Ge;
  129277. }else{
  129278. testOp = bRev ? OP_Lt : OP_Gt;
  129279. }
  129280. if( 0==sqlite3ExprIsVector(pX->pRight) ){
  129281. disableTerm(pLevel, pEnd);
  129282. }
  129283. }
  129284. start = sqlite3VdbeCurrentAddr(v);
  129285. pLevel->op = bRev ? OP_Prev : OP_Next;
  129286. pLevel->p1 = iCur;
  129287. pLevel->p2 = start;
  129288. assert( pLevel->p5==0 );
  129289. if( testOp!=OP_Noop ){
  129290. iRowidReg = ++pParse->nMem;
  129291. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  129292. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  129293. VdbeCoverageIf(v, testOp==OP_Le);
  129294. VdbeCoverageIf(v, testOp==OP_Lt);
  129295. VdbeCoverageIf(v, testOp==OP_Ge);
  129296. VdbeCoverageIf(v, testOp==OP_Gt);
  129297. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  129298. }
  129299. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  129300. /* Case 4: A scan using an index.
  129301. **
  129302. ** The WHERE clause may contain zero or more equality
  129303. ** terms ("==" or "IN" operators) that refer to the N
  129304. ** left-most columns of the index. It may also contain
  129305. ** inequality constraints (>, <, >= or <=) on the indexed
  129306. ** column that immediately follows the N equalities. Only
  129307. ** the right-most column can be an inequality - the rest must
  129308. ** use the "==" and "IN" operators. For example, if the
  129309. ** index is on (x,y,z), then the following clauses are all
  129310. ** optimized:
  129311. **
  129312. ** x=5
  129313. ** x=5 AND y=10
  129314. ** x=5 AND y<10
  129315. ** x=5 AND y>5 AND y<10
  129316. ** x=5 AND y=5 AND z<=10
  129317. **
  129318. ** The z<10 term of the following cannot be used, only
  129319. ** the x=5 term:
  129320. **
  129321. ** x=5 AND z<10
  129322. **
  129323. ** N may be zero if there are inequality constraints.
  129324. ** If there are no inequality constraints, then N is at
  129325. ** least one.
  129326. **
  129327. ** This case is also used when there are no WHERE clause
  129328. ** constraints but an index is selected anyway, in order
  129329. ** to force the output order to conform to an ORDER BY.
  129330. */
  129331. static const u8 aStartOp[] = {
  129332. 0,
  129333. 0,
  129334. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  129335. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  129336. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  129337. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  129338. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  129339. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  129340. };
  129341. static const u8 aEndOp[] = {
  129342. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  129343. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  129344. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  129345. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  129346. };
  129347. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  129348. u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
  129349. u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
  129350. int regBase; /* Base register holding constraint values */
  129351. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  129352. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  129353. int startEq; /* True if range start uses ==, >= or <= */
  129354. int endEq; /* True if range end uses ==, >= or <= */
  129355. int start_constraints; /* Start of range is constrained */
  129356. int nConstraint; /* Number of constraint terms */
  129357. int iIdxCur; /* The VDBE cursor for the index */
  129358. int nExtraReg = 0; /* Number of extra registers needed */
  129359. int op; /* Instruction opcode */
  129360. char *zStartAff; /* Affinity for start of range constraint */
  129361. char *zEndAff = 0; /* Affinity for end of range constraint */
  129362. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  129363. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  129364. int omitTable; /* True if we use the index only */
  129365. pIdx = pLoop->u.btree.pIndex;
  129366. iIdxCur = pLevel->iIdxCur;
  129367. assert( nEq>=pLoop->nSkip );
  129368. /* If this loop satisfies a sort order (pOrderBy) request that
  129369. ** was passed to this function to implement a "SELECT min(x) ..."
  129370. ** query, then the caller will only allow the loop to run for
  129371. ** a single iteration. This means that the first row returned
  129372. ** should not have a NULL value stored in 'x'. If column 'x' is
  129373. ** the first one after the nEq equality constraints in the index,
  129374. ** this requires some special handling.
  129375. */
  129376. assert( pWInfo->pOrderBy==0
  129377. || pWInfo->pOrderBy->nExpr==1
  129378. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  129379. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  129380. && pWInfo->nOBSat>0
  129381. && (pIdx->nKeyCol>nEq)
  129382. ){
  129383. assert( pLoop->nSkip==0 );
  129384. bSeekPastNull = 1;
  129385. nExtraReg = 1;
  129386. }
  129387. /* Find any inequality constraint terms for the start and end
  129388. ** of the range.
  129389. */
  129390. j = nEq;
  129391. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  129392. pRangeStart = pLoop->aLTerm[j++];
  129393. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
  129394. /* Like optimization range constraints always occur in pairs */
  129395. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  129396. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  129397. }
  129398. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  129399. pRangeEnd = pLoop->aLTerm[j++];
  129400. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
  129401. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  129402. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  129403. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  129404. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  129405. pLevel->iLikeRepCntr = (u32)++pParse->nMem;
  129406. sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
  129407. VdbeComment((v, "LIKE loop counter"));
  129408. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  129409. /* iLikeRepCntr actually stores 2x the counter register number. The
  129410. ** bottom bit indicates whether the search order is ASC or DESC. */
  129411. testcase( bRev );
  129412. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  129413. assert( (bRev & ~1)==0 );
  129414. pLevel->iLikeRepCntr <<=1;
  129415. pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
  129416. }
  129417. #endif
  129418. if( pRangeStart==0 ){
  129419. j = pIdx->aiColumn[nEq];
  129420. if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
  129421. bSeekPastNull = 1;
  129422. }
  129423. }
  129424. }
  129425. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  129426. /* If we are doing a reverse order scan on an ascending index, or
  129427. ** a forward order scan on a descending index, interchange the
  129428. ** start and end terms (pRangeStart and pRangeEnd).
  129429. */
  129430. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  129431. || (bRev && pIdx->nKeyCol==nEq)
  129432. ){
  129433. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  129434. SWAP(u8, bSeekPastNull, bStopAtNull);
  129435. SWAP(u8, nBtm, nTop);
  129436. }
  129437. /* Generate code to evaluate all constraint terms using == or IN
  129438. ** and store the values of those terms in an array of registers
  129439. ** starting at regBase.
  129440. */
  129441. codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
  129442. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  129443. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  129444. if( zStartAff && nTop ){
  129445. zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
  129446. }
  129447. addrNxt = pLevel->addrNxt;
  129448. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  129449. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  129450. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  129451. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  129452. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  129453. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  129454. start_constraints = pRangeStart || nEq>0;
  129455. /* Seek the index cursor to the start of the range. */
  129456. nConstraint = nEq;
  129457. if( pRangeStart ){
  129458. Expr *pRight = pRangeStart->pExpr->pRight;
  129459. codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
  129460. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  129461. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  129462. && sqlite3ExprCanBeNull(pRight)
  129463. ){
  129464. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  129465. VdbeCoverage(v);
  129466. }
  129467. if( zStartAff ){
  129468. updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
  129469. }
  129470. nConstraint += nBtm;
  129471. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  129472. if( sqlite3ExprIsVector(pRight)==0 ){
  129473. disableTerm(pLevel, pRangeStart);
  129474. }else{
  129475. startEq = 1;
  129476. }
  129477. bSeekPastNull = 0;
  129478. }else if( bSeekPastNull ){
  129479. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  129480. nConstraint++;
  129481. startEq = 0;
  129482. start_constraints = 1;
  129483. }
  129484. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  129485. if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
  129486. /* The skip-scan logic inside the call to codeAllEqualityConstraints()
  129487. ** above has already left the cursor sitting on the correct row,
  129488. ** so no further seeking is needed */
  129489. }else{
  129490. if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
  129491. sqlite3VdbeAddOp1(v, OP_SeekHit, iIdxCur);
  129492. }
  129493. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  129494. assert( op!=0 );
  129495. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  129496. VdbeCoverage(v);
  129497. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  129498. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  129499. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  129500. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  129501. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  129502. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  129503. }
  129504. /* Load the value for the inequality constraint at the end of the
  129505. ** range (if any).
  129506. */
  129507. nConstraint = nEq;
  129508. if( pRangeEnd ){
  129509. Expr *pRight = pRangeEnd->pExpr->pRight;
  129510. codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
  129511. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  129512. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  129513. && sqlite3ExprCanBeNull(pRight)
  129514. ){
  129515. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  129516. VdbeCoverage(v);
  129517. }
  129518. if( zEndAff ){
  129519. updateRangeAffinityStr(pRight, nTop, zEndAff);
  129520. codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
  129521. }else{
  129522. assert( pParse->db->mallocFailed );
  129523. }
  129524. nConstraint += nTop;
  129525. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  129526. if( sqlite3ExprIsVector(pRight)==0 ){
  129527. disableTerm(pLevel, pRangeEnd);
  129528. }else{
  129529. endEq = 1;
  129530. }
  129531. }else if( bStopAtNull ){
  129532. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  129533. endEq = 0;
  129534. nConstraint++;
  129535. }
  129536. sqlite3DbFree(db, zStartAff);
  129537. sqlite3DbFree(db, zEndAff);
  129538. /* Top of the loop body */
  129539. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  129540. /* Check if the index cursor is past the end of the range. */
  129541. if( nConstraint ){
  129542. op = aEndOp[bRev*2 + endEq];
  129543. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  129544. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  129545. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  129546. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  129547. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  129548. }
  129549. if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
  129550. sqlite3VdbeAddOp2(v, OP_SeekHit, iIdxCur, 1);
  129551. }
  129552. /* Seek the table cursor, if required */
  129553. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  129554. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
  129555. if( omitTable ){
  129556. /* pIdx is a covering index. No need to access the main table. */
  129557. }else if( HasRowid(pIdx->pTable) ){
  129558. if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
  129559. (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
  129560. && (pWInfo->eOnePass==ONEPASS_SINGLE)
  129561. )){
  129562. iRowidReg = ++pParse->nMem;
  129563. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  129564. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  129565. VdbeCoverage(v);
  129566. }else{
  129567. codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
  129568. }
  129569. }else if( iCur!=iIdxCur ){
  129570. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  129571. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  129572. for(j=0; j<pPk->nKeyCol; j++){
  129573. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  129574. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  129575. }
  129576. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  129577. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  129578. }
  129579. /* If pIdx is an index on one or more expressions, then look through
  129580. ** all the expressions in pWInfo and try to transform matching expressions
  129581. ** into reference to index columns.
  129582. **
  129583. ** Do not do this for the RHS of a LEFT JOIN. This is because the
  129584. ** expression may be evaluated after OP_NullRow has been executed on
  129585. ** the cursor. In this case it is important to do the full evaluation,
  129586. ** as the result of the expression may not be NULL, even if all table
  129587. ** column values are. https://www.sqlite.org/src/info/7fa8049685b50b5a
  129588. **
  129589. ** Also, do not do this when processing one index an a multi-index
  129590. ** OR clause, since the transformation will become invalid once we
  129591. ** move forward to the next index.
  129592. ** https://sqlite.org/src/info/4e8e4857d32d401f
  129593. */
  129594. if( pLevel->iLeftJoin==0 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  129595. whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
  129596. }
  129597. /* If a partial index is driving the loop, try to eliminate WHERE clause
  129598. ** terms from the query that must be true due to the WHERE clause of
  129599. ** the partial index
  129600. */
  129601. if( pIdx->pPartIdxWhere ){
  129602. whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);
  129603. }
  129604. /* Record the instruction used to terminate the loop. */
  129605. if( pLoop->wsFlags & WHERE_ONEROW ){
  129606. pLevel->op = OP_Noop;
  129607. }else if( bRev ){
  129608. pLevel->op = OP_Prev;
  129609. }else{
  129610. pLevel->op = OP_Next;
  129611. }
  129612. pLevel->p1 = iIdxCur;
  129613. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  129614. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  129615. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  129616. }else{
  129617. assert( pLevel->p5==0 );
  129618. }
  129619. if( omitTable ) pIdx = 0;
  129620. }else
  129621. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  129622. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  129623. /* Case 5: Two or more separately indexed terms connected by OR
  129624. **
  129625. ** Example:
  129626. **
  129627. ** CREATE TABLE t1(a,b,c,d);
  129628. ** CREATE INDEX i1 ON t1(a);
  129629. ** CREATE INDEX i2 ON t1(b);
  129630. ** CREATE INDEX i3 ON t1(c);
  129631. **
  129632. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  129633. **
  129634. ** In the example, there are three indexed terms connected by OR.
  129635. ** The top of the loop looks like this:
  129636. **
  129637. ** Null 1 # Zero the rowset in reg 1
  129638. **
  129639. ** Then, for each indexed term, the following. The arguments to
  129640. ** RowSetTest are such that the rowid of the current row is inserted
  129641. ** into the RowSet. If it is already present, control skips the
  129642. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  129643. **
  129644. ** sqlite3WhereBegin(<term>)
  129645. ** RowSetTest # Insert rowid into rowset
  129646. ** Gosub 2 A
  129647. ** sqlite3WhereEnd()
  129648. **
  129649. ** Following the above, code to terminate the loop. Label A, the target
  129650. ** of the Gosub above, jumps to the instruction right after the Goto.
  129651. **
  129652. ** Null 1 # Zero the rowset in reg 1
  129653. ** Goto B # The loop is finished.
  129654. **
  129655. ** A: <loop body> # Return data, whatever.
  129656. **
  129657. ** Return 2 # Jump back to the Gosub
  129658. **
  129659. ** B: <after the loop>
  129660. **
  129661. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  129662. ** use an ephemeral index instead of a RowSet to record the primary
  129663. ** keys of the rows we have already seen.
  129664. **
  129665. */
  129666. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  129667. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  129668. Index *pCov = 0; /* Potential covering index (or NULL) */
  129669. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  129670. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  129671. int regRowset = 0; /* Register for RowSet object */
  129672. int regRowid = 0; /* Register holding rowid */
  129673. int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */
  129674. int iRetInit; /* Address of regReturn init */
  129675. int untestedTerms = 0; /* Some terms not completely tested */
  129676. int ii; /* Loop counter */
  129677. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  129678. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  129679. Table *pTab = pTabItem->pTab;
  129680. pTerm = pLoop->aLTerm[0];
  129681. assert( pTerm!=0 );
  129682. assert( pTerm->eOperator & WO_OR );
  129683. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  129684. pOrWc = &pTerm->u.pOrInfo->wc;
  129685. pLevel->op = OP_Return;
  129686. pLevel->p1 = regReturn;
  129687. /* Set up a new SrcList in pOrTab containing the table being scanned
  129688. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  129689. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  129690. */
  129691. if( pWInfo->nLevel>1 ){
  129692. int nNotReady; /* The number of notReady tables */
  129693. struct SrcList_item *origSrc; /* Original list of tables */
  129694. nNotReady = pWInfo->nLevel - iLevel - 1;
  129695. pOrTab = sqlite3StackAllocRaw(db,
  129696. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  129697. if( pOrTab==0 ) return notReady;
  129698. pOrTab->nAlloc = (u8)(nNotReady + 1);
  129699. pOrTab->nSrc = pOrTab->nAlloc;
  129700. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  129701. origSrc = pWInfo->pTabList->a;
  129702. for(k=1; k<=nNotReady; k++){
  129703. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  129704. }
  129705. }else{
  129706. pOrTab = pWInfo->pTabList;
  129707. }
  129708. /* Initialize the rowset register to contain NULL. An SQL NULL is
  129709. ** equivalent to an empty rowset. Or, create an ephemeral index
  129710. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  129711. **
  129712. ** Also initialize regReturn to contain the address of the instruction
  129713. ** immediately following the OP_Return at the bottom of the loop. This
  129714. ** is required in a few obscure LEFT JOIN cases where control jumps
  129715. ** over the top of the loop into the body of it. In this case the
  129716. ** correct response for the end-of-loop code (the OP_Return) is to
  129717. ** fall through to the next instruction, just as an OP_Next does if
  129718. ** called on an uninitialized cursor.
  129719. */
  129720. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  129721. if( HasRowid(pTab) ){
  129722. regRowset = ++pParse->nMem;
  129723. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  129724. }else{
  129725. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  129726. regRowset = pParse->nTab++;
  129727. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  129728. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  129729. }
  129730. regRowid = ++pParse->nMem;
  129731. }
  129732. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  129733. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  129734. ** Then for every term xN, evaluate as the subexpression: xN AND z
  129735. ** That way, terms in y that are factored into the disjunction will
  129736. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  129737. **
  129738. ** Actually, each subexpression is converted to "xN AND w" where w is
  129739. ** the "interesting" terms of z - terms that did not originate in the
  129740. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  129741. ** indices.
  129742. **
  129743. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  129744. ** is not contained in the ON clause of a LEFT JOIN.
  129745. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  129746. */
  129747. if( pWC->nTerm>1 ){
  129748. int iTerm;
  129749. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  129750. Expr *pExpr = pWC->a[iTerm].pExpr;
  129751. if( &pWC->a[iTerm] == pTerm ) continue;
  129752. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  129753. testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
  129754. if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
  129755. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  129756. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  129757. pExpr = sqlite3ExprDup(db, pExpr, 0);
  129758. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  129759. }
  129760. if( pAndExpr ){
  129761. /* The extra 0x10000 bit on the opcode is masked off and does not
  129762. ** become part of the new Expr.op. However, it does make the
  129763. ** op==TK_AND comparison inside of sqlite3PExpr() false, and this
  129764. ** prevents sqlite3PExpr() from implementing AND short-circuit
  129765. ** optimization, which we do not want here. */
  129766. pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr);
  129767. }
  129768. }
  129769. /* Run a separate WHERE clause for each term of the OR clause. After
  129770. ** eliminating duplicates from other WHERE clauses, the action for each
  129771. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  129772. */
  129773. wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
  129774. ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
  129775. for(ii=0; ii<pOrWc->nTerm; ii++){
  129776. WhereTerm *pOrTerm = &pOrWc->a[ii];
  129777. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  129778. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  129779. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  129780. int jmp1 = 0; /* Address of jump operation */
  129781. assert( (pTabItem[0].fg.jointype & JT_LEFT)==0
  129782. || ExprHasProperty(pOrExpr, EP_FromJoin)
  129783. );
  129784. if( pAndExpr ){
  129785. pAndExpr->pLeft = pOrExpr;
  129786. pOrExpr = pAndExpr;
  129787. }
  129788. /* Loop through table entries that match term pOrTerm. */
  129789. ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1));
  129790. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  129791. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  129792. wctrlFlags, iCovCur);
  129793. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  129794. if( pSubWInfo ){
  129795. WhereLoop *pSubLoop;
  129796. int addrExplain = sqlite3WhereExplainOneScan(
  129797. pParse, pOrTab, &pSubWInfo->a[0], 0
  129798. );
  129799. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  129800. /* This is the sub-WHERE clause body. First skip over
  129801. ** duplicate rows from prior sub-WHERE clauses, and record the
  129802. ** rowid (or PRIMARY KEY) for the current row so that the same
  129803. ** row will be skipped in subsequent sub-WHERE clauses.
  129804. */
  129805. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  129806. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  129807. if( HasRowid(pTab) ){
  129808. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);
  129809. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  129810. regRowid, iSet);
  129811. VdbeCoverage(v);
  129812. }else{
  129813. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  129814. int nPk = pPk->nKeyCol;
  129815. int iPk;
  129816. int r;
  129817. /* Read the PK into an array of temp registers. */
  129818. r = sqlite3GetTempRange(pParse, nPk);
  129819. for(iPk=0; iPk<nPk; iPk++){
  129820. int iCol = pPk->aiColumn[iPk];
  129821. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, r+iPk);
  129822. }
  129823. /* Check if the temp table already contains this key. If so,
  129824. ** the row has already been included in the result set and
  129825. ** can be ignored (by jumping past the Gosub below). Otherwise,
  129826. ** insert the key into the temp table and proceed with processing
  129827. ** the row.
  129828. **
  129829. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  129830. ** is zero, assume that the key cannot already be present in
  129831. ** the temp table. And if iSet is -1, assume that there is no
  129832. ** need to insert the key into the temp table, as it will never
  129833. ** be tested for. */
  129834. if( iSet ){
  129835. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  129836. VdbeCoverage(v);
  129837. }
  129838. if( iSet>=0 ){
  129839. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  129840. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
  129841. r, nPk);
  129842. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  129843. }
  129844. /* Release the array of temp registers */
  129845. sqlite3ReleaseTempRange(pParse, r, nPk);
  129846. }
  129847. }
  129848. /* Invoke the main loop body as a subroutine */
  129849. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  129850. /* Jump here (skipping the main loop body subroutine) if the
  129851. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  129852. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  129853. /* The pSubWInfo->untestedTerms flag means that this OR term
  129854. ** contained one or more AND term from a notReady table. The
  129855. ** terms from the notReady table could not be tested and will
  129856. ** need to be tested later.
  129857. */
  129858. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  129859. /* If all of the OR-connected terms are optimized using the same
  129860. ** index, and the index is opened using the same cursor number
  129861. ** by each call to sqlite3WhereBegin() made by this loop, it may
  129862. ** be possible to use that index as a covering index.
  129863. **
  129864. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  129865. ** uses an index, and this is either the first OR-connected term
  129866. ** processed or the index is the same as that used by all previous
  129867. ** terms, set pCov to the candidate covering index. Otherwise, set
  129868. ** pCov to NULL to indicate that no candidate covering index will
  129869. ** be available.
  129870. */
  129871. pSubLoop = pSubWInfo->a[0].pWLoop;
  129872. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  129873. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  129874. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  129875. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  129876. ){
  129877. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  129878. pCov = pSubLoop->u.btree.pIndex;
  129879. }else{
  129880. pCov = 0;
  129881. }
  129882. /* Finish the loop through table entries that match term pOrTerm. */
  129883. sqlite3WhereEnd(pSubWInfo);
  129884. ExplainQueryPlanPop(pParse);
  129885. }
  129886. }
  129887. }
  129888. ExplainQueryPlanPop(pParse);
  129889. pLevel->u.pCovidx = pCov;
  129890. if( pCov ) pLevel->iIdxCur = iCovCur;
  129891. if( pAndExpr ){
  129892. pAndExpr->pLeft = 0;
  129893. sqlite3ExprDelete(db, pAndExpr);
  129894. }
  129895. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  129896. sqlite3VdbeGoto(v, pLevel->addrBrk);
  129897. sqlite3VdbeResolveLabel(v, iLoopBody);
  129898. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  129899. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  129900. }else
  129901. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  129902. {
  129903. /* Case 6: There is no usable index. We must do a complete
  129904. ** scan of the entire table.
  129905. */
  129906. static const u8 aStep[] = { OP_Next, OP_Prev };
  129907. static const u8 aStart[] = { OP_Rewind, OP_Last };
  129908. assert( bRev==0 || bRev==1 );
  129909. if( pTabItem->fg.isRecursive ){
  129910. /* Tables marked isRecursive have only a single row that is stored in
  129911. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  129912. pLevel->op = OP_Noop;
  129913. }else{
  129914. codeCursorHint(pTabItem, pWInfo, pLevel, 0);
  129915. pLevel->op = aStep[bRev];
  129916. pLevel->p1 = iCur;
  129917. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
  129918. VdbeCoverageIf(v, bRev==0);
  129919. VdbeCoverageIf(v, bRev!=0);
  129920. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  129921. }
  129922. }
  129923. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  129924. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  129925. #endif
  129926. /* Insert code to test every subexpression that can be completely
  129927. ** computed using the current set of tables.
  129928. **
  129929. ** This loop may run between one and three times, depending on the
  129930. ** constraints to be generated. The value of stack variable iLoop
  129931. ** determines the constraints coded by each iteration, as follows:
  129932. **
  129933. ** iLoop==1: Code only expressions that are entirely covered by pIdx.
  129934. ** iLoop==2: Code remaining expressions that do not contain correlated
  129935. ** sub-queries.
  129936. ** iLoop==3: Code all remaining expressions.
  129937. **
  129938. ** An effort is made to skip unnecessary iterations of the loop.
  129939. */
  129940. iLoop = (pIdx ? 1 : 2);
  129941. do{
  129942. int iNext = 0; /* Next value for iLoop */
  129943. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  129944. Expr *pE;
  129945. int skipLikeAddr = 0;
  129946. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  129947. testcase( pTerm->wtFlags & TERM_CODED );
  129948. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  129949. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  129950. testcase( pWInfo->untestedTerms==0
  129951. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
  129952. pWInfo->untestedTerms = 1;
  129953. continue;
  129954. }
  129955. pE = pTerm->pExpr;
  129956. assert( pE!=0 );
  129957. if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){
  129958. continue;
  129959. }
  129960. if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
  129961. iNext = 2;
  129962. continue;
  129963. }
  129964. if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
  129965. if( iNext==0 ) iNext = 3;
  129966. continue;
  129967. }
  129968. if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
  129969. /* If the TERM_LIKECOND flag is set, that means that the range search
  129970. ** is sufficient to guarantee that the LIKE operator is true, so we
  129971. ** can skip the call to the like(A,B) function. But this only works
  129972. ** for strings. So do not skip the call to the function on the pass
  129973. ** that compares BLOBs. */
  129974. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  129975. continue;
  129976. #else
  129977. u32 x = pLevel->iLikeRepCntr;
  129978. if( x>0 ){
  129979. skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));
  129980. VdbeCoverageIf(v, (x&1)==1);
  129981. VdbeCoverageIf(v, (x&1)==0);
  129982. }
  129983. #endif
  129984. }
  129985. #ifdef WHERETRACE_ENABLED /* 0xffff */
  129986. if( sqlite3WhereTrace ){
  129987. VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
  129988. pWC->nTerm-j, pTerm, iLoop));
  129989. }
  129990. #endif
  129991. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  129992. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  129993. pTerm->wtFlags |= TERM_CODED;
  129994. }
  129995. iLoop = iNext;
  129996. }while( iLoop>0 );
  129997. /* Insert code to test for implied constraints based on transitivity
  129998. ** of the "==" operator.
  129999. **
  130000. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  130001. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  130002. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  130003. ** the implied "t1.a=123" constraint.
  130004. */
  130005. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  130006. Expr *pE, sEAlt;
  130007. WhereTerm *pAlt;
  130008. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  130009. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  130010. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  130011. if( pTerm->leftCursor!=iCur ) continue;
  130012. if( pLevel->iLeftJoin ) continue;
  130013. pE = pTerm->pExpr;
  130014. assert( !ExprHasProperty(pE, EP_FromJoin) );
  130015. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  130016. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  130017. WO_EQ|WO_IN|WO_IS, 0);
  130018. if( pAlt==0 ) continue;
  130019. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  130020. if( (pAlt->eOperator & WO_IN)
  130021. && (pAlt->pExpr->flags & EP_xIsSelect)
  130022. && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
  130023. ){
  130024. continue;
  130025. }
  130026. testcase( pAlt->eOperator & WO_EQ );
  130027. testcase( pAlt->eOperator & WO_IS );
  130028. testcase( pAlt->eOperator & WO_IN );
  130029. VdbeModuleComment((v, "begin transitive constraint"));
  130030. sEAlt = *pAlt->pExpr;
  130031. sEAlt.pLeft = pE->pLeft;
  130032. sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
  130033. }
  130034. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  130035. ** at least one row of the right table has matched the left table.
  130036. */
  130037. if( pLevel->iLeftJoin ){
  130038. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  130039. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  130040. VdbeComment((v, "record LEFT JOIN hit"));
  130041. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  130042. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  130043. testcase( pTerm->wtFlags & TERM_CODED );
  130044. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  130045. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  130046. assert( pWInfo->untestedTerms );
  130047. continue;
  130048. }
  130049. assert( pTerm->pExpr );
  130050. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  130051. pTerm->wtFlags |= TERM_CODED;
  130052. }
  130053. }
  130054. return pLevel->notReady;
  130055. }
  130056. /************** End of wherecode.c *******************************************/
  130057. /************** Begin file whereexpr.c ***************************************/
  130058. /*
  130059. ** 2015-06-08
  130060. **
  130061. ** The author disclaims copyright to this source code. In place of
  130062. ** a legal notice, here is a blessing:
  130063. **
  130064. ** May you do good and not evil.
  130065. ** May you find forgiveness for yourself and forgive others.
  130066. ** May you share freely, never taking more than you give.
  130067. **
  130068. *************************************************************************
  130069. ** This module contains C code that generates VDBE code used to process
  130070. ** the WHERE clause of SQL statements.
  130071. **
  130072. ** This file was originally part of where.c but was split out to improve
  130073. ** readability and editabiliity. This file contains utility routines for
  130074. ** analyzing Expr objects in the WHERE clause.
  130075. */
  130076. /* #include "sqliteInt.h" */
  130077. /* #include "whereInt.h" */
  130078. /* Forward declarations */
  130079. static void exprAnalyze(SrcList*, WhereClause*, int);
  130080. /*
  130081. ** Deallocate all memory associated with a WhereOrInfo object.
  130082. */
  130083. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  130084. sqlite3WhereClauseClear(&p->wc);
  130085. sqlite3DbFree(db, p);
  130086. }
  130087. /*
  130088. ** Deallocate all memory associated with a WhereAndInfo object.
  130089. */
  130090. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  130091. sqlite3WhereClauseClear(&p->wc);
  130092. sqlite3DbFree(db, p);
  130093. }
  130094. /*
  130095. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  130096. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  130097. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  130098. ** 0 is returned if the new WhereTerm could not be added due to a memory
  130099. ** allocation error. The memory allocation failure will be recorded in
  130100. ** the db->mallocFailed flag so that higher-level functions can detect it.
  130101. **
  130102. ** This routine will increase the size of the pWC->a[] array as necessary.
  130103. **
  130104. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  130105. ** for freeing the expression p is assumed by the WhereClause object pWC.
  130106. ** This is true even if this routine fails to allocate a new WhereTerm.
  130107. **
  130108. ** WARNING: This routine might reallocate the space used to store
  130109. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  130110. ** calling this routine. Such pointers may be reinitialized by referencing
  130111. ** the pWC->a[] array.
  130112. */
  130113. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  130114. WhereTerm *pTerm;
  130115. int idx;
  130116. testcase( wtFlags & TERM_VIRTUAL );
  130117. if( pWC->nTerm>=pWC->nSlot ){
  130118. WhereTerm *pOld = pWC->a;
  130119. sqlite3 *db = pWC->pWInfo->pParse->db;
  130120. pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  130121. if( pWC->a==0 ){
  130122. if( wtFlags & TERM_DYNAMIC ){
  130123. sqlite3ExprDelete(db, p);
  130124. }
  130125. pWC->a = pOld;
  130126. return 0;
  130127. }
  130128. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  130129. if( pOld!=pWC->aStatic ){
  130130. sqlite3DbFree(db, pOld);
  130131. }
  130132. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  130133. }
  130134. pTerm = &pWC->a[idx = pWC->nTerm++];
  130135. if( p && ExprHasProperty(p, EP_Unlikely) ){
  130136. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  130137. }else{
  130138. pTerm->truthProb = 1;
  130139. }
  130140. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  130141. pTerm->wtFlags = wtFlags;
  130142. pTerm->pWC = pWC;
  130143. pTerm->iParent = -1;
  130144. memset(&pTerm->eOperator, 0,
  130145. sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
  130146. return idx;
  130147. }
  130148. /*
  130149. ** Return TRUE if the given operator is one of the operators that is
  130150. ** allowed for an indexable WHERE clause term. The allowed operators are
  130151. ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
  130152. */
  130153. static int allowedOp(int op){
  130154. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  130155. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  130156. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  130157. assert( TK_GE==TK_EQ+4 );
  130158. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  130159. }
  130160. /*
  130161. ** Commute a comparison operator. Expressions of the form "X op Y"
  130162. ** are converted into "Y op X".
  130163. **
  130164. ** If left/right precedence rules come into play when determining the
  130165. ** collating sequence, then COLLATE operators are adjusted to ensure
  130166. ** that the collating sequence does not change. For example:
  130167. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  130168. ** the left hand side of a comparison overrides any collation sequence
  130169. ** attached to the right. For the same reason the EP_Collate flag
  130170. ** is not commuted.
  130171. */
  130172. static void exprCommute(Parse *pParse, Expr *pExpr){
  130173. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  130174. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  130175. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  130176. if( expRight==expLeft ){
  130177. /* Either X and Y both have COLLATE operator or neither do */
  130178. if( expRight ){
  130179. /* Both X and Y have COLLATE operators. Make sure X is always
  130180. ** used by clearing the EP_Collate flag from Y. */
  130181. pExpr->pRight->flags &= ~EP_Collate;
  130182. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  130183. /* Neither X nor Y have COLLATE operators, but X has a non-default
  130184. ** collating sequence. So add the EP_Collate marker on X to cause
  130185. ** it to be searched first. */
  130186. pExpr->pLeft->flags |= EP_Collate;
  130187. }
  130188. }
  130189. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  130190. if( pExpr->op>=TK_GT ){
  130191. assert( TK_LT==TK_GT+2 );
  130192. assert( TK_GE==TK_LE+2 );
  130193. assert( TK_GT>TK_EQ );
  130194. assert( TK_GT<TK_LE );
  130195. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  130196. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  130197. }
  130198. }
  130199. /*
  130200. ** Translate from TK_xx operator to WO_xx bitmask.
  130201. */
  130202. static u16 operatorMask(int op){
  130203. u16 c;
  130204. assert( allowedOp(op) );
  130205. if( op==TK_IN ){
  130206. c = WO_IN;
  130207. }else if( op==TK_ISNULL ){
  130208. c = WO_ISNULL;
  130209. }else if( op==TK_IS ){
  130210. c = WO_IS;
  130211. }else{
  130212. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  130213. c = (u16)(WO_EQ<<(op-TK_EQ));
  130214. }
  130215. assert( op!=TK_ISNULL || c==WO_ISNULL );
  130216. assert( op!=TK_IN || c==WO_IN );
  130217. assert( op!=TK_EQ || c==WO_EQ );
  130218. assert( op!=TK_LT || c==WO_LT );
  130219. assert( op!=TK_LE || c==WO_LE );
  130220. assert( op!=TK_GT || c==WO_GT );
  130221. assert( op!=TK_GE || c==WO_GE );
  130222. assert( op!=TK_IS || c==WO_IS );
  130223. return c;
  130224. }
  130225. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  130226. /*
  130227. ** Check to see if the given expression is a LIKE or GLOB operator that
  130228. ** can be optimized using inequality constraints. Return TRUE if it is
  130229. ** so and false if not.
  130230. **
  130231. ** In order for the operator to be optimizible, the RHS must be a string
  130232. ** literal that does not begin with a wildcard. The LHS must be a column
  130233. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  130234. ** that virtual tables cannot participate in the LIKE optimization.) The
  130235. ** collating sequence for the column on the LHS must be appropriate for
  130236. ** the operator.
  130237. */
  130238. static int isLikeOrGlob(
  130239. Parse *pParse, /* Parsing and code generating context */
  130240. Expr *pExpr, /* Test this expression */
  130241. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  130242. int *pisComplete, /* True if the only wildcard is % in the last character */
  130243. int *pnoCase /* True if uppercase is equivalent to lowercase */
  130244. ){
  130245. const u8 *z = 0; /* String on RHS of LIKE operator */
  130246. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  130247. ExprList *pList; /* List of operands to the LIKE operator */
  130248. u8 c; /* One character in z[] */
  130249. int cnt; /* Number of non-wildcard prefix characters */
  130250. u8 wc[4]; /* Wildcard characters */
  130251. sqlite3 *db = pParse->db; /* Database connection */
  130252. sqlite3_value *pVal = 0;
  130253. int op; /* Opcode of pRight */
  130254. int rc; /* Result code to return */
  130255. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){
  130256. return 0;
  130257. }
  130258. #ifdef SQLITE_EBCDIC
  130259. if( *pnoCase ) return 0;
  130260. #endif
  130261. pList = pExpr->x.pList;
  130262. pLeft = pList->a[1].pExpr;
  130263. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  130264. op = pRight->op;
  130265. if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  130266. Vdbe *pReprepare = pParse->pReprepare;
  130267. int iCol = pRight->iColumn;
  130268. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  130269. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  130270. z = sqlite3_value_text(pVal);
  130271. }
  130272. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  130273. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  130274. }else if( op==TK_STRING ){
  130275. z = (u8*)pRight->u.zToken;
  130276. }
  130277. if( z ){
  130278. /* Count the number of prefix characters prior to the first wildcard */
  130279. cnt = 0;
  130280. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  130281. cnt++;
  130282. if( c==wc[3] && z[cnt]!=0 ) cnt++;
  130283. }
  130284. /* The optimization is possible only if (1) the pattern does not begin
  130285. ** with a wildcard and if (2) the non-wildcard prefix does not end with
  130286. ** an (illegal 0xff) character, or (3) the pattern does not consist of
  130287. ** a single escape character. The second condition is necessary so
  130288. ** that we can increment the prefix key to find an upper bound for the
  130289. ** range search. The third is because the caller assumes that the pattern
  130290. ** consists of at least one character after all escapes have been
  130291. ** removed. */
  130292. if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){
  130293. Expr *pPrefix;
  130294. /* A "complete" match if the pattern ends with "*" or "%" */
  130295. *pisComplete = c==wc[0] && z[cnt+1]==0;
  130296. /* Get the pattern prefix. Remove all escapes from the prefix. */
  130297. pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
  130298. if( pPrefix ){
  130299. int iFrom, iTo;
  130300. char *zNew = pPrefix->u.zToken;
  130301. zNew[cnt] = 0;
  130302. for(iFrom=iTo=0; iFrom<cnt; iFrom++){
  130303. if( zNew[iFrom]==wc[3] ) iFrom++;
  130304. zNew[iTo++] = zNew[iFrom];
  130305. }
  130306. zNew[iTo] = 0;
  130307. /* If the RHS begins with a digit or a minus sign, then the LHS must be
  130308. ** an ordinary column (not a virtual table column) with TEXT affinity.
  130309. ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
  130310. ** even though "lhs LIKE rhs" is true. But if the RHS does not start
  130311. ** with a digit or '-', then "lhs LIKE rhs" will always be false if
  130312. ** the LHS is numeric and so the optimization still works.
  130313. **
  130314. ** 2018-09-10 ticket c94369cae9b561b1f996d0054bfab11389f9d033
  130315. ** The RHS pattern must not be '/%' because the termination condition
  130316. ** will then become "x<'0'" and if the affinity is numeric, will then
  130317. ** be converted into "x<0", which is incorrect.
  130318. */
  130319. if( sqlite3Isdigit(zNew[0])
  130320. || zNew[0]=='-'
  130321. || (zNew[0]+1=='0' && iTo==1)
  130322. ){
  130323. if( pLeft->op!=TK_COLUMN
  130324. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  130325. || IsVirtual(pLeft->y.pTab) /* Value might be numeric */
  130326. ){
  130327. sqlite3ExprDelete(db, pPrefix);
  130328. sqlite3ValueFree(pVal);
  130329. return 0;
  130330. }
  130331. }
  130332. }
  130333. *ppPrefix = pPrefix;
  130334. /* If the RHS pattern is a bound parameter, make arrangements to
  130335. ** reprepare the statement when that parameter is rebound */
  130336. if( op==TK_VARIABLE ){
  130337. Vdbe *v = pParse->pVdbe;
  130338. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  130339. if( *pisComplete && pRight->u.zToken[1] ){
  130340. /* If the rhs of the LIKE expression is a variable, and the current
  130341. ** value of the variable means there is no need to invoke the LIKE
  130342. ** function, then no OP_Variable will be added to the program.
  130343. ** This causes problems for the sqlite3_bind_parameter_name()
  130344. ** API. To work around them, add a dummy OP_Variable here.
  130345. */
  130346. int r1 = sqlite3GetTempReg(pParse);
  130347. sqlite3ExprCodeTarget(pParse, pRight, r1);
  130348. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  130349. sqlite3ReleaseTempReg(pParse, r1);
  130350. }
  130351. }
  130352. }else{
  130353. z = 0;
  130354. }
  130355. }
  130356. rc = (z!=0);
  130357. sqlite3ValueFree(pVal);
  130358. return rc;
  130359. }
  130360. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  130361. #ifndef SQLITE_OMIT_VIRTUALTABLE
  130362. /*
  130363. ** Check to see if the pExpr expression is a form that needs to be passed
  130364. ** to the xBestIndex method of virtual tables. Forms of interest include:
  130365. **
  130366. ** Expression Virtual Table Operator
  130367. ** ----------------------- ---------------------------------
  130368. ** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
  130369. ** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
  130370. ** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
  130371. ** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
  130372. ** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
  130373. ** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
  130374. ** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
  130375. ** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
  130376. ** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
  130377. **
  130378. ** In every case, "column" must be a column of a virtual table. If there
  130379. ** is a match, set *ppLeft to the "column" expression, set *ppRight to the
  130380. ** "expr" expression (even though in forms (6) and (8) the column is on the
  130381. ** right and the expression is on the left). Also set *peOp2 to the
  130382. ** appropriate virtual table operator. The return value is 1 or 2 if there
  130383. ** is a match. The usual return is 1, but if the RHS is also a column
  130384. ** of virtual table in forms (5) or (7) then return 2.
  130385. **
  130386. ** If the expression matches none of the patterns above, return 0.
  130387. */
  130388. static int isAuxiliaryVtabOperator(
  130389. sqlite3 *db, /* Parsing context */
  130390. Expr *pExpr, /* Test this expression */
  130391. unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
  130392. Expr **ppLeft, /* Column expression to left of MATCH/op2 */
  130393. Expr **ppRight /* Expression to left of MATCH/op2 */
  130394. ){
  130395. if( pExpr->op==TK_FUNCTION ){
  130396. static const struct Op2 {
  130397. const char *zOp;
  130398. unsigned char eOp2;
  130399. } aOp[] = {
  130400. { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
  130401. { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
  130402. { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
  130403. { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
  130404. };
  130405. ExprList *pList;
  130406. Expr *pCol; /* Column reference */
  130407. int i;
  130408. pList = pExpr->x.pList;
  130409. if( pList==0 || pList->nExpr!=2 ){
  130410. return 0;
  130411. }
  130412. /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
  130413. ** virtual table on their second argument, which is the same as
  130414. ** the left-hand side operand in their in-fix form.
  130415. **
  130416. ** vtab_column MATCH expression
  130417. ** MATCH(expression,vtab_column)
  130418. */
  130419. pCol = pList->a[1].pExpr;
  130420. if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
  130421. for(i=0; i<ArraySize(aOp); i++){
  130422. if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
  130423. *peOp2 = aOp[i].eOp2;
  130424. *ppRight = pList->a[0].pExpr;
  130425. *ppLeft = pCol;
  130426. return 1;
  130427. }
  130428. }
  130429. }
  130430. /* We can also match against the first column of overloaded
  130431. ** functions where xFindFunction returns a value of at least
  130432. ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
  130433. **
  130434. ** OVERLOADED(vtab_column,expression)
  130435. **
  130436. ** Historically, xFindFunction expected to see lower-case function
  130437. ** names. But for this use case, xFindFunction is expected to deal
  130438. ** with function names in an arbitrary case.
  130439. */
  130440. pCol = pList->a[0].pExpr;
  130441. if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
  130442. sqlite3_vtab *pVtab;
  130443. sqlite3_module *pMod;
  130444. void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
  130445. void *pNotUsed;
  130446. pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
  130447. assert( pVtab!=0 );
  130448. assert( pVtab->pModule!=0 );
  130449. pMod = (sqlite3_module *)pVtab->pModule;
  130450. if( pMod->xFindFunction!=0 ){
  130451. i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
  130452. if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
  130453. *peOp2 = i;
  130454. *ppRight = pList->a[1].pExpr;
  130455. *ppLeft = pCol;
  130456. return 1;
  130457. }
  130458. }
  130459. }
  130460. }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
  130461. int res = 0;
  130462. Expr *pLeft = pExpr->pLeft;
  130463. Expr *pRight = pExpr->pRight;
  130464. if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->y.pTab) ){
  130465. res++;
  130466. }
  130467. if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->y.pTab) ){
  130468. res++;
  130469. SWAP(Expr*, pLeft, pRight);
  130470. }
  130471. *ppLeft = pLeft;
  130472. *ppRight = pRight;
  130473. if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
  130474. if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
  130475. if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
  130476. return res;
  130477. }
  130478. return 0;
  130479. }
  130480. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  130481. /*
  130482. ** If the pBase expression originated in the ON or USING clause of
  130483. ** a join, then transfer the appropriate markings over to derived.
  130484. */
  130485. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  130486. if( pDerived ){
  130487. pDerived->flags |= pBase->flags & EP_FromJoin;
  130488. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  130489. }
  130490. }
  130491. /*
  130492. ** Mark term iChild as being a child of term iParent
  130493. */
  130494. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  130495. pWC->a[iChild].iParent = iParent;
  130496. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  130497. pWC->a[iParent].nChild++;
  130498. }
  130499. /*
  130500. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  130501. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  130502. ** the number of available subterms, return NULL.
  130503. */
  130504. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  130505. if( pTerm->eOperator!=WO_AND ){
  130506. return N==0 ? pTerm : 0;
  130507. }
  130508. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  130509. return &pTerm->u.pAndInfo->wc.a[N];
  130510. }
  130511. return 0;
  130512. }
  130513. /*
  130514. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  130515. ** two subterms are in disjunction - they are OR-ed together.
  130516. **
  130517. ** If these two terms are both of the form: "A op B" with the same
  130518. ** A and B values but different operators and if the operators are
  130519. ** compatible (if one is = and the other is <, for example) then
  130520. ** add a new virtual AND term to pWC that is the combination of the
  130521. ** two.
  130522. **
  130523. ** Some examples:
  130524. **
  130525. ** x<y OR x=y --> x<=y
  130526. ** x=y OR x=y --> x=y
  130527. ** x<=y OR x<y --> x<=y
  130528. **
  130529. ** The following is NOT generated:
  130530. **
  130531. ** x<y OR x>y --> x!=y
  130532. */
  130533. static void whereCombineDisjuncts(
  130534. SrcList *pSrc, /* the FROM clause */
  130535. WhereClause *pWC, /* The complete WHERE clause */
  130536. WhereTerm *pOne, /* First disjunct */
  130537. WhereTerm *pTwo /* Second disjunct */
  130538. ){
  130539. u16 eOp = pOne->eOperator | pTwo->eOperator;
  130540. sqlite3 *db; /* Database connection (for malloc) */
  130541. Expr *pNew; /* New virtual expression */
  130542. int op; /* Operator for the combined expression */
  130543. int idxNew; /* Index in pWC of the next virtual term */
  130544. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  130545. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  130546. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  130547. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  130548. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  130549. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  130550. if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  130551. if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
  130552. /* If we reach this point, it means the two subterms can be combined */
  130553. if( (eOp & (eOp-1))!=0 ){
  130554. if( eOp & (WO_LT|WO_LE) ){
  130555. eOp = WO_LE;
  130556. }else{
  130557. assert( eOp & (WO_GT|WO_GE) );
  130558. eOp = WO_GE;
  130559. }
  130560. }
  130561. db = pWC->pWInfo->pParse->db;
  130562. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  130563. if( pNew==0 ) return;
  130564. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  130565. pNew->op = op;
  130566. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  130567. exprAnalyze(pSrc, pWC, idxNew);
  130568. }
  130569. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  130570. /*
  130571. ** Analyze a term that consists of two or more OR-connected
  130572. ** subterms. So in:
  130573. **
  130574. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  130575. ** ^^^^^^^^^^^^^^^^^^^^
  130576. **
  130577. ** This routine analyzes terms such as the middle term in the above example.
  130578. ** A WhereOrTerm object is computed and attached to the term under
  130579. ** analysis, regardless of the outcome of the analysis. Hence:
  130580. **
  130581. ** WhereTerm.wtFlags |= TERM_ORINFO
  130582. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  130583. **
  130584. ** The term being analyzed must have two or more of OR-connected subterms.
  130585. ** A single subterm might be a set of AND-connected sub-subterms.
  130586. ** Examples of terms under analysis:
  130587. **
  130588. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  130589. ** (B) x=expr1 OR expr2=x OR x=expr3
  130590. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  130591. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  130592. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  130593. ** (F) x>A OR (x=A AND y>=B)
  130594. **
  130595. ** CASE 1:
  130596. **
  130597. ** If all subterms are of the form T.C=expr for some single column of C and
  130598. ** a single table T (as shown in example B above) then create a new virtual
  130599. ** term that is an equivalent IN expression. In other words, if the term
  130600. ** being analyzed is:
  130601. **
  130602. ** x = expr1 OR expr2 = x OR x = expr3
  130603. **
  130604. ** then create a new virtual term like this:
  130605. **
  130606. ** x IN (expr1,expr2,expr3)
  130607. **
  130608. ** CASE 2:
  130609. **
  130610. ** If there are exactly two disjuncts and one side has x>A and the other side
  130611. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  130612. ** WHERE clause of the form "x>=A". Example:
  130613. **
  130614. ** x>A OR (x=A AND y>B) adds: x>=A
  130615. **
  130616. ** The added conjunct can sometimes be helpful in query planning.
  130617. **
  130618. ** CASE 3:
  130619. **
  130620. ** If all subterms are indexable by a single table T, then set
  130621. **
  130622. ** WhereTerm.eOperator = WO_OR
  130623. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  130624. **
  130625. ** A subterm is "indexable" if it is of the form
  130626. ** "T.C <op> <expr>" where C is any column of table T and
  130627. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  130628. ** A subterm is also indexable if it is an AND of two or more
  130629. ** subsubterms at least one of which is indexable. Indexable AND
  130630. ** subterms have their eOperator set to WO_AND and they have
  130631. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  130632. **
  130633. ** From another point of view, "indexable" means that the subterm could
  130634. ** potentially be used with an index if an appropriate index exists.
  130635. ** This analysis does not consider whether or not the index exists; that
  130636. ** is decided elsewhere. This analysis only looks at whether subterms
  130637. ** appropriate for indexing exist.
  130638. **
  130639. ** All examples A through E above satisfy case 3. But if a term
  130640. ** also satisfies case 1 (such as B) we know that the optimizer will
  130641. ** always prefer case 1, so in that case we pretend that case 3 is not
  130642. ** satisfied.
  130643. **
  130644. ** It might be the case that multiple tables are indexable. For example,
  130645. ** (E) above is indexable on tables P, Q, and R.
  130646. **
  130647. ** Terms that satisfy case 3 are candidates for lookup by using
  130648. ** separate indices to find rowids for each subterm and composing
  130649. ** the union of all rowids using a RowSet object. This is similar
  130650. ** to "bitmap indices" in other database engines.
  130651. **
  130652. ** OTHERWISE:
  130653. **
  130654. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  130655. ** zero. This term is not useful for search.
  130656. */
  130657. static void exprAnalyzeOrTerm(
  130658. SrcList *pSrc, /* the FROM clause */
  130659. WhereClause *pWC, /* the complete WHERE clause */
  130660. int idxTerm /* Index of the OR-term to be analyzed */
  130661. ){
  130662. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  130663. Parse *pParse = pWInfo->pParse; /* Parser context */
  130664. sqlite3 *db = pParse->db; /* Database connection */
  130665. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  130666. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  130667. int i; /* Loop counters */
  130668. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  130669. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  130670. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  130671. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  130672. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  130673. /*
  130674. ** Break the OR clause into its separate subterms. The subterms are
  130675. ** stored in a WhereClause structure containing within the WhereOrInfo
  130676. ** object that is attached to the original OR clause term.
  130677. */
  130678. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  130679. assert( pExpr->op==TK_OR );
  130680. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  130681. if( pOrInfo==0 ) return;
  130682. pTerm->wtFlags |= TERM_ORINFO;
  130683. pOrWc = &pOrInfo->wc;
  130684. memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
  130685. sqlite3WhereClauseInit(pOrWc, pWInfo);
  130686. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  130687. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  130688. if( db->mallocFailed ) return;
  130689. assert( pOrWc->nTerm>=2 );
  130690. /*
  130691. ** Compute the set of tables that might satisfy cases 1 or 3.
  130692. */
  130693. indexable = ~(Bitmask)0;
  130694. chngToIN = ~(Bitmask)0;
  130695. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  130696. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  130697. WhereAndInfo *pAndInfo;
  130698. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  130699. chngToIN = 0;
  130700. pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
  130701. if( pAndInfo ){
  130702. WhereClause *pAndWC;
  130703. WhereTerm *pAndTerm;
  130704. int j;
  130705. Bitmask b = 0;
  130706. pOrTerm->u.pAndInfo = pAndInfo;
  130707. pOrTerm->wtFlags |= TERM_ANDINFO;
  130708. pOrTerm->eOperator = WO_AND;
  130709. pAndWC = &pAndInfo->wc;
  130710. memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
  130711. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  130712. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  130713. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  130714. pAndWC->pOuter = pWC;
  130715. if( !db->mallocFailed ){
  130716. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  130717. assert( pAndTerm->pExpr );
  130718. if( allowedOp(pAndTerm->pExpr->op)
  130719. || pAndTerm->eOperator==WO_AUX
  130720. ){
  130721. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  130722. }
  130723. }
  130724. }
  130725. indexable &= b;
  130726. }
  130727. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  130728. /* Skip this term for now. We revisit it when we process the
  130729. ** corresponding TERM_VIRTUAL term */
  130730. }else{
  130731. Bitmask b;
  130732. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  130733. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  130734. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  130735. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  130736. }
  130737. indexable &= b;
  130738. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  130739. chngToIN = 0;
  130740. }else{
  130741. chngToIN &= b;
  130742. }
  130743. }
  130744. }
  130745. /*
  130746. ** Record the set of tables that satisfy case 3. The set might be
  130747. ** empty.
  130748. */
  130749. pOrInfo->indexable = indexable;
  130750. if( indexable ){
  130751. pTerm->eOperator = WO_OR;
  130752. pWC->hasOr = 1;
  130753. }else{
  130754. pTerm->eOperator = WO_OR;
  130755. }
  130756. /* For a two-way OR, attempt to implementation case 2.
  130757. */
  130758. if( indexable && pOrWc->nTerm==2 ){
  130759. int iOne = 0;
  130760. WhereTerm *pOne;
  130761. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  130762. int iTwo = 0;
  130763. WhereTerm *pTwo;
  130764. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  130765. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  130766. }
  130767. }
  130768. }
  130769. /*
  130770. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  130771. ** we have to do some additional checking to see if case 1 really
  130772. ** is satisfied.
  130773. **
  130774. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  130775. ** that there is no possibility of transforming the OR clause into an
  130776. ** IN operator because one or more terms in the OR clause contain
  130777. ** something other than == on a column in the single table. The 1-bit
  130778. ** case means that every term of the OR clause is of the form
  130779. ** "table.column=expr" for some single table. The one bit that is set
  130780. ** will correspond to the common table. We still need to check to make
  130781. ** sure the same column is used on all terms. The 2-bit case is when
  130782. ** the all terms are of the form "table1.column=table2.column". It
  130783. ** might be possible to form an IN operator with either table1.column
  130784. ** or table2.column as the LHS if either is common to every term of
  130785. ** the OR clause.
  130786. **
  130787. ** Note that terms of the form "table.column1=table.column2" (the
  130788. ** same table on both sizes of the ==) cannot be optimized.
  130789. */
  130790. if( chngToIN ){
  130791. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  130792. int iColumn = -1; /* Column index on lhs of IN operator */
  130793. int iCursor = -1; /* Table cursor common to all terms */
  130794. int j = 0; /* Loop counter */
  130795. /* Search for a table and column that appears on one side or the
  130796. ** other of the == operator in every subterm. That table and column
  130797. ** will be recorded in iCursor and iColumn. There might not be any
  130798. ** such table and column. Set okToChngToIN if an appropriate table
  130799. ** and column is found but leave okToChngToIN false if not found.
  130800. */
  130801. for(j=0; j<2 && !okToChngToIN; j++){
  130802. Expr *pLeft = 0;
  130803. pOrTerm = pOrWc->a;
  130804. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  130805. assert( pOrTerm->eOperator & WO_EQ );
  130806. pOrTerm->wtFlags &= ~TERM_OR_OK;
  130807. if( pOrTerm->leftCursor==iCursor ){
  130808. /* This is the 2-bit case and we are on the second iteration and
  130809. ** current term is from the first iteration. So skip this term. */
  130810. assert( j==1 );
  130811. continue;
  130812. }
  130813. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  130814. pOrTerm->leftCursor))==0 ){
  130815. /* This term must be of the form t1.a==t2.b where t2 is in the
  130816. ** chngToIN set but t1 is not. This term will be either preceded
  130817. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  130818. ** and use its inversion. */
  130819. testcase( pOrTerm->wtFlags & TERM_COPIED );
  130820. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  130821. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  130822. continue;
  130823. }
  130824. iColumn = pOrTerm->u.leftColumn;
  130825. iCursor = pOrTerm->leftCursor;
  130826. pLeft = pOrTerm->pExpr->pLeft;
  130827. break;
  130828. }
  130829. if( i<0 ){
  130830. /* No candidate table+column was found. This can only occur
  130831. ** on the second iteration */
  130832. assert( j==1 );
  130833. assert( IsPowerOfTwo(chngToIN) );
  130834. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  130835. break;
  130836. }
  130837. testcase( j==1 );
  130838. /* We have found a candidate table and column. Check to see if that
  130839. ** table and column is common to every term in the OR clause */
  130840. okToChngToIN = 1;
  130841. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  130842. assert( pOrTerm->eOperator & WO_EQ );
  130843. if( pOrTerm->leftCursor!=iCursor ){
  130844. pOrTerm->wtFlags &= ~TERM_OR_OK;
  130845. }else if( pOrTerm->u.leftColumn!=iColumn || (iColumn==XN_EXPR
  130846. && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
  130847. )){
  130848. okToChngToIN = 0;
  130849. }else{
  130850. int affLeft, affRight;
  130851. /* If the right-hand side is also a column, then the affinities
  130852. ** of both right and left sides must be such that no type
  130853. ** conversions are required on the right. (Ticket #2249)
  130854. */
  130855. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  130856. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  130857. if( affRight!=0 && affRight!=affLeft ){
  130858. okToChngToIN = 0;
  130859. }else{
  130860. pOrTerm->wtFlags |= TERM_OR_OK;
  130861. }
  130862. }
  130863. }
  130864. }
  130865. /* At this point, okToChngToIN is true if original pTerm satisfies
  130866. ** case 1. In that case, construct a new virtual term that is
  130867. ** pTerm converted into an IN operator.
  130868. */
  130869. if( okToChngToIN ){
  130870. Expr *pDup; /* A transient duplicate expression */
  130871. ExprList *pList = 0; /* The RHS of the IN operator */
  130872. Expr *pLeft = 0; /* The LHS of the IN operator */
  130873. Expr *pNew; /* The complete IN operator */
  130874. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  130875. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  130876. assert( pOrTerm->eOperator & WO_EQ );
  130877. assert( pOrTerm->leftCursor==iCursor );
  130878. assert( pOrTerm->u.leftColumn==iColumn );
  130879. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  130880. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  130881. pLeft = pOrTerm->pExpr->pLeft;
  130882. }
  130883. assert( pLeft!=0 );
  130884. pDup = sqlite3ExprDup(db, pLeft, 0);
  130885. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
  130886. if( pNew ){
  130887. int idxNew;
  130888. transferJoinMarkings(pNew, pExpr);
  130889. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  130890. pNew->x.pList = pList;
  130891. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  130892. testcase( idxNew==0 );
  130893. exprAnalyze(pSrc, pWC, idxNew);
  130894. /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */
  130895. markTermAsChild(pWC, idxNew, idxTerm);
  130896. }else{
  130897. sqlite3ExprListDelete(db, pList);
  130898. }
  130899. }
  130900. }
  130901. }
  130902. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  130903. /*
  130904. ** We already know that pExpr is a binary operator where both operands are
  130905. ** column references. This routine checks to see if pExpr is an equivalence
  130906. ** relation:
  130907. ** 1. The SQLITE_Transitive optimization must be enabled
  130908. ** 2. Must be either an == or an IS operator
  130909. ** 3. Not originating in the ON clause of an OUTER JOIN
  130910. ** 4. The affinities of A and B must be compatible
  130911. ** 5a. Both operands use the same collating sequence OR
  130912. ** 5b. The overall collating sequence is BINARY
  130913. ** If this routine returns TRUE, that means that the RHS can be substituted
  130914. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  130915. ** This is an optimization. No harm comes from returning 0. But if 1 is
  130916. ** returned when it should not be, then incorrect answers might result.
  130917. */
  130918. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  130919. char aff1, aff2;
  130920. CollSeq *pColl;
  130921. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  130922. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  130923. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  130924. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  130925. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  130926. if( aff1!=aff2
  130927. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  130928. ){
  130929. return 0;
  130930. }
  130931. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  130932. if( sqlite3IsBinary(pColl) ) return 1;
  130933. return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
  130934. }
  130935. /*
  130936. ** Recursively walk the expressions of a SELECT statement and generate
  130937. ** a bitmask indicating which tables are used in that expression
  130938. ** tree.
  130939. */
  130940. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  130941. Bitmask mask = 0;
  130942. while( pS ){
  130943. SrcList *pSrc = pS->pSrc;
  130944. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  130945. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  130946. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  130947. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  130948. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  130949. if( ALWAYS(pSrc!=0) ){
  130950. int i;
  130951. for(i=0; i<pSrc->nSrc; i++){
  130952. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  130953. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  130954. if( pSrc->a[i].fg.isTabFunc ){
  130955. mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
  130956. }
  130957. }
  130958. }
  130959. pS = pS->pPrior;
  130960. }
  130961. return mask;
  130962. }
  130963. /*
  130964. ** Expression pExpr is one operand of a comparison operator that might
  130965. ** be useful for indexing. This routine checks to see if pExpr appears
  130966. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  130967. ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
  130968. ** number of the table that is indexed and aiCurCol[1] to the column number
  130969. ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
  130970. ** indexed.
  130971. **
  130972. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  130973. ** true even if that particular column is not indexed, because the column
  130974. ** might be added to an automatic index later.
  130975. */
  130976. static SQLITE_NOINLINE int exprMightBeIndexed2(
  130977. SrcList *pFrom, /* The FROM clause */
  130978. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  130979. int *aiCurCol, /* Write the referenced table cursor and column here */
  130980. Expr *pExpr /* An operand of a comparison operator */
  130981. ){
  130982. Index *pIdx;
  130983. int i;
  130984. int iCur;
  130985. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  130986. iCur = pFrom->a[i].iCursor;
  130987. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  130988. if( pIdx->aColExpr==0 ) continue;
  130989. for(i=0; i<pIdx->nKeyCol; i++){
  130990. if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
  130991. if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  130992. aiCurCol[0] = iCur;
  130993. aiCurCol[1] = XN_EXPR;
  130994. return 1;
  130995. }
  130996. }
  130997. }
  130998. return 0;
  130999. }
  131000. static int exprMightBeIndexed(
  131001. SrcList *pFrom, /* The FROM clause */
  131002. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  131003. int *aiCurCol, /* Write the referenced table cursor & column here */
  131004. Expr *pExpr, /* An operand of a comparison operator */
  131005. int op /* The specific comparison operator */
  131006. ){
  131007. /* If this expression is a vector to the left or right of a
  131008. ** inequality constraint (>, <, >= or <=), perform the processing
  131009. ** on the first element of the vector. */
  131010. assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
  131011. assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
  131012. assert( op<=TK_GE );
  131013. if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
  131014. pExpr = pExpr->x.pList->a[0].pExpr;
  131015. }
  131016. if( pExpr->op==TK_COLUMN ){
  131017. aiCurCol[0] = pExpr->iTable;
  131018. aiCurCol[1] = pExpr->iColumn;
  131019. return 1;
  131020. }
  131021. if( mPrereq==0 ) return 0; /* No table references */
  131022. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  131023. return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
  131024. }
  131025. /*
  131026. ** The input to this routine is an WhereTerm structure with only the
  131027. ** "pExpr" field filled in. The job of this routine is to analyze the
  131028. ** subexpression and populate all the other fields of the WhereTerm
  131029. ** structure.
  131030. **
  131031. ** If the expression is of the form "<expr> <op> X" it gets commuted
  131032. ** to the standard form of "X <op> <expr>".
  131033. **
  131034. ** If the expression is of the form "X <op> Y" where both X and Y are
  131035. ** columns, then the original expression is unchanged and a new virtual
  131036. ** term of the form "Y <op> X" is added to the WHERE clause and
  131037. ** analyzed separately. The original term is marked with TERM_COPIED
  131038. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  131039. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  131040. ** is a commuted copy of a prior term.) The original term has nChild=1
  131041. ** and the copy has idxParent set to the index of the original term.
  131042. */
  131043. static void exprAnalyze(
  131044. SrcList *pSrc, /* the FROM clause */
  131045. WhereClause *pWC, /* the WHERE clause */
  131046. int idxTerm /* Index of the term to be analyzed */
  131047. ){
  131048. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  131049. WhereTerm *pTerm; /* The term to be analyzed */
  131050. WhereMaskSet *pMaskSet; /* Set of table index masks */
  131051. Expr *pExpr; /* The expression to be analyzed */
  131052. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  131053. Bitmask prereqAll; /* Prerequesites of pExpr */
  131054. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  131055. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  131056. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  131057. int noCase = 0; /* uppercase equivalent to lowercase */
  131058. int op; /* Top-level operator. pExpr->op */
  131059. Parse *pParse = pWInfo->pParse; /* Parsing context */
  131060. sqlite3 *db = pParse->db; /* Database connection */
  131061. unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */
  131062. int nLeft; /* Number of elements on left side vector */
  131063. if( db->mallocFailed ){
  131064. return;
  131065. }
  131066. pTerm = &pWC->a[idxTerm];
  131067. pMaskSet = &pWInfo->sMaskSet;
  131068. pExpr = pTerm->pExpr;
  131069. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  131070. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  131071. op = pExpr->op;
  131072. if( op==TK_IN ){
  131073. assert( pExpr->pRight==0 );
  131074. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  131075. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  131076. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  131077. }else{
  131078. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  131079. }
  131080. }else if( op==TK_ISNULL ){
  131081. pTerm->prereqRight = 0;
  131082. }else{
  131083. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  131084. }
  131085. pMaskSet->bVarSelect = 0;
  131086. prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
  131087. if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
  131088. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  131089. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  131090. prereqAll |= x;
  131091. extraRight = x-1; /* ON clause terms may not be used with an index
  131092. ** on left table of a LEFT JOIN. Ticket #3015 */
  131093. if( (prereqAll>>1)>=x ){
  131094. sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
  131095. return;
  131096. }
  131097. }
  131098. pTerm->prereqAll = prereqAll;
  131099. pTerm->leftCursor = -1;
  131100. pTerm->iParent = -1;
  131101. pTerm->eOperator = 0;
  131102. if( allowedOp(op) ){
  131103. int aiCurCol[2];
  131104. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  131105. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  131106. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  131107. if( pTerm->iField>0 ){
  131108. assert( op==TK_IN );
  131109. assert( pLeft->op==TK_VECTOR );
  131110. pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
  131111. }
  131112. if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
  131113. pTerm->leftCursor = aiCurCol[0];
  131114. pTerm->u.leftColumn = aiCurCol[1];
  131115. pTerm->eOperator = operatorMask(op) & opMask;
  131116. }
  131117. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  131118. if( pRight
  131119. && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
  131120. ){
  131121. WhereTerm *pNew;
  131122. Expr *pDup;
  131123. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  131124. assert( pTerm->iField==0 );
  131125. if( pTerm->leftCursor>=0 ){
  131126. int idxNew;
  131127. pDup = sqlite3ExprDup(db, pExpr, 0);
  131128. if( db->mallocFailed ){
  131129. sqlite3ExprDelete(db, pDup);
  131130. return;
  131131. }
  131132. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  131133. if( idxNew==0 ) return;
  131134. pNew = &pWC->a[idxNew];
  131135. markTermAsChild(pWC, idxNew, idxTerm);
  131136. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  131137. pTerm = &pWC->a[idxTerm];
  131138. pTerm->wtFlags |= TERM_COPIED;
  131139. if( termIsEquivalence(pParse, pDup) ){
  131140. pTerm->eOperator |= WO_EQUIV;
  131141. eExtraOp = WO_EQUIV;
  131142. }
  131143. }else{
  131144. pDup = pExpr;
  131145. pNew = pTerm;
  131146. }
  131147. exprCommute(pParse, pDup);
  131148. pNew->leftCursor = aiCurCol[0];
  131149. pNew->u.leftColumn = aiCurCol[1];
  131150. testcase( (prereqLeft | extraRight) != prereqLeft );
  131151. pNew->prereqRight = prereqLeft | extraRight;
  131152. pNew->prereqAll = prereqAll;
  131153. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  131154. }
  131155. }
  131156. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  131157. /* If a term is the BETWEEN operator, create two new virtual terms
  131158. ** that define the range that the BETWEEN implements. For example:
  131159. **
  131160. ** a BETWEEN b AND c
  131161. **
  131162. ** is converted into:
  131163. **
  131164. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  131165. **
  131166. ** The two new terms are added onto the end of the WhereClause object.
  131167. ** The new terms are "dynamic" and are children of the original BETWEEN
  131168. ** term. That means that if the BETWEEN term is coded, the children are
  131169. ** skipped. Or, if the children are satisfied by an index, the original
  131170. ** BETWEEN term is skipped.
  131171. */
  131172. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  131173. ExprList *pList = pExpr->x.pList;
  131174. int i;
  131175. static const u8 ops[] = {TK_GE, TK_LE};
  131176. assert( pList!=0 );
  131177. assert( pList->nExpr==2 );
  131178. for(i=0; i<2; i++){
  131179. Expr *pNewExpr;
  131180. int idxNew;
  131181. pNewExpr = sqlite3PExpr(pParse, ops[i],
  131182. sqlite3ExprDup(db, pExpr->pLeft, 0),
  131183. sqlite3ExprDup(db, pList->a[i].pExpr, 0));
  131184. transferJoinMarkings(pNewExpr, pExpr);
  131185. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  131186. testcase( idxNew==0 );
  131187. exprAnalyze(pSrc, pWC, idxNew);
  131188. pTerm = &pWC->a[idxTerm];
  131189. markTermAsChild(pWC, idxNew, idxTerm);
  131190. }
  131191. }
  131192. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  131193. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  131194. /* Analyze a term that is composed of two or more subterms connected by
  131195. ** an OR operator.
  131196. */
  131197. else if( pExpr->op==TK_OR ){
  131198. assert( pWC->op==TK_AND );
  131199. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  131200. pTerm = &pWC->a[idxTerm];
  131201. }
  131202. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  131203. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  131204. /* Add constraints to reduce the search space on a LIKE or GLOB
  131205. ** operator.
  131206. **
  131207. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  131208. **
  131209. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  131210. **
  131211. ** The last character of the prefix "abc" is incremented to form the
  131212. ** termination condition "abd". If case is not significant (the default
  131213. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  131214. ** bound is made all lowercase so that the bounds also work when comparing
  131215. ** BLOBs.
  131216. */
  131217. if( pWC->op==TK_AND
  131218. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  131219. ){
  131220. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  131221. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  131222. Expr *pNewExpr1;
  131223. Expr *pNewExpr2;
  131224. int idxNew1;
  131225. int idxNew2;
  131226. const char *zCollSeqName; /* Name of collating sequence */
  131227. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  131228. pLeft = pExpr->x.pList->a[1].pExpr;
  131229. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  131230. /* Convert the lower bound to upper-case and the upper bound to
  131231. ** lower-case (upper-case is less than lower-case in ASCII) so that
  131232. ** the range constraints also work for BLOBs
  131233. */
  131234. if( noCase && !pParse->db->mallocFailed ){
  131235. int i;
  131236. char c;
  131237. pTerm->wtFlags |= TERM_LIKE;
  131238. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  131239. pStr1->u.zToken[i] = sqlite3Toupper(c);
  131240. pStr2->u.zToken[i] = sqlite3Tolower(c);
  131241. }
  131242. }
  131243. if( !db->mallocFailed ){
  131244. u8 c, *pC; /* Last character before the first wildcard */
  131245. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  131246. c = *pC;
  131247. if( noCase ){
  131248. /* The point is to increment the last character before the first
  131249. ** wildcard. But if we increment '@', that will push it into the
  131250. ** alphabetic range where case conversions will mess up the
  131251. ** inequality. To avoid this, make sure to also run the full
  131252. ** LIKE on all candidate expressions by clearing the isComplete flag
  131253. */
  131254. if( c=='A'-1 ) isComplete = 0;
  131255. c = sqlite3UpperToLower[c];
  131256. }
  131257. *pC = c + 1;
  131258. }
  131259. zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY;
  131260. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  131261. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  131262. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  131263. pStr1);
  131264. transferJoinMarkings(pNewExpr1, pExpr);
  131265. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  131266. testcase( idxNew1==0 );
  131267. exprAnalyze(pSrc, pWC, idxNew1);
  131268. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  131269. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  131270. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  131271. pStr2);
  131272. transferJoinMarkings(pNewExpr2, pExpr);
  131273. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  131274. testcase( idxNew2==0 );
  131275. exprAnalyze(pSrc, pWC, idxNew2);
  131276. pTerm = &pWC->a[idxTerm];
  131277. if( isComplete ){
  131278. markTermAsChild(pWC, idxNew1, idxTerm);
  131279. markTermAsChild(pWC, idxNew2, idxTerm);
  131280. }
  131281. }
  131282. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  131283. #ifndef SQLITE_OMIT_VIRTUALTABLE
  131284. /* Add a WO_AUX auxiliary term to the constraint set if the
  131285. ** current expression is of the form "column OP expr" where OP
  131286. ** is an operator that gets passed into virtual tables but which is
  131287. ** not normally optimized for ordinary tables. In other words, OP
  131288. ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
  131289. ** This information is used by the xBestIndex methods of
  131290. ** virtual tables. The native query optimizer does not attempt
  131291. ** to do anything with MATCH functions.
  131292. */
  131293. if( pWC->op==TK_AND ){
  131294. Expr *pRight = 0, *pLeft = 0;
  131295. int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
  131296. while( res-- > 0 ){
  131297. int idxNew;
  131298. WhereTerm *pNewTerm;
  131299. Bitmask prereqColumn, prereqExpr;
  131300. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  131301. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  131302. if( (prereqExpr & prereqColumn)==0 ){
  131303. Expr *pNewExpr;
  131304. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  131305. 0, sqlite3ExprDup(db, pRight, 0));
  131306. if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
  131307. ExprSetProperty(pNewExpr, EP_FromJoin);
  131308. }
  131309. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  131310. testcase( idxNew==0 );
  131311. pNewTerm = &pWC->a[idxNew];
  131312. pNewTerm->prereqRight = prereqExpr;
  131313. pNewTerm->leftCursor = pLeft->iTable;
  131314. pNewTerm->u.leftColumn = pLeft->iColumn;
  131315. pNewTerm->eOperator = WO_AUX;
  131316. pNewTerm->eMatchOp = eOp2;
  131317. markTermAsChild(pWC, idxNew, idxTerm);
  131318. pTerm = &pWC->a[idxTerm];
  131319. pTerm->wtFlags |= TERM_COPIED;
  131320. pNewTerm->prereqAll = pTerm->prereqAll;
  131321. }
  131322. SWAP(Expr*, pLeft, pRight);
  131323. }
  131324. }
  131325. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  131326. /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
  131327. ** new terms for each component comparison - "a = ?" and "b = ?". The
  131328. ** new terms completely replace the original vector comparison, which is
  131329. ** no longer used.
  131330. **
  131331. ** This is only required if at least one side of the comparison operation
  131332. ** is not a sub-select. */
  131333. if( pWC->op==TK_AND
  131334. && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
  131335. && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
  131336. && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
  131337. && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
  131338. || (pExpr->pRight->flags & EP_xIsSelect)==0)
  131339. ){
  131340. int i;
  131341. for(i=0; i<nLeft; i++){
  131342. int idxNew;
  131343. Expr *pNew;
  131344. Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
  131345. Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
  131346. pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
  131347. transferJoinMarkings(pNew, pExpr);
  131348. idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
  131349. exprAnalyze(pSrc, pWC, idxNew);
  131350. }
  131351. pTerm = &pWC->a[idxTerm];
  131352. pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
  131353. pTerm->eOperator = 0;
  131354. }
  131355. /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
  131356. ** a virtual term for each vector component. The expression object
  131357. ** used by each such virtual term is pExpr (the full vector IN(...)
  131358. ** expression). The WhereTerm.iField variable identifies the index within
  131359. ** the vector on the LHS that the virtual term represents.
  131360. **
  131361. ** This only works if the RHS is a simple SELECT, not a compound
  131362. */
  131363. if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
  131364. && pExpr->pLeft->op==TK_VECTOR
  131365. && pExpr->x.pSelect->pPrior==0
  131366. ){
  131367. int i;
  131368. for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
  131369. int idxNew;
  131370. idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
  131371. pWC->a[idxNew].iField = i+1;
  131372. exprAnalyze(pSrc, pWC, idxNew);
  131373. markTermAsChild(pWC, idxNew, idxTerm);
  131374. }
  131375. }
  131376. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  131377. /* When sqlite_stat3 histogram data is available an operator of the
  131378. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  131379. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  131380. ** virtual term of that form.
  131381. **
  131382. ** Note that the virtual term must be tagged with TERM_VNULL.
  131383. */
  131384. if( pExpr->op==TK_NOTNULL
  131385. && pExpr->pLeft->op==TK_COLUMN
  131386. && pExpr->pLeft->iColumn>=0
  131387. && !ExprHasProperty(pExpr, EP_FromJoin)
  131388. && OptimizationEnabled(db, SQLITE_Stat34)
  131389. ){
  131390. Expr *pNewExpr;
  131391. Expr *pLeft = pExpr->pLeft;
  131392. int idxNew;
  131393. WhereTerm *pNewTerm;
  131394. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  131395. sqlite3ExprDup(db, pLeft, 0),
  131396. sqlite3ExprAlloc(db, TK_NULL, 0, 0));
  131397. idxNew = whereClauseInsert(pWC, pNewExpr,
  131398. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  131399. if( idxNew ){
  131400. pNewTerm = &pWC->a[idxNew];
  131401. pNewTerm->prereqRight = 0;
  131402. pNewTerm->leftCursor = pLeft->iTable;
  131403. pNewTerm->u.leftColumn = pLeft->iColumn;
  131404. pNewTerm->eOperator = WO_GT;
  131405. markTermAsChild(pWC, idxNew, idxTerm);
  131406. pTerm = &pWC->a[idxTerm];
  131407. pTerm->wtFlags |= TERM_COPIED;
  131408. pNewTerm->prereqAll = pTerm->prereqAll;
  131409. }
  131410. }
  131411. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  131412. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  131413. ** an index for tables to the left of the join.
  131414. */
  131415. testcase( pTerm!=&pWC->a[idxTerm] );
  131416. pTerm = &pWC->a[idxTerm];
  131417. pTerm->prereqRight |= extraRight;
  131418. }
  131419. /***************************************************************************
  131420. ** Routines with file scope above. Interface to the rest of the where.c
  131421. ** subsystem follows.
  131422. ***************************************************************************/
  131423. /*
  131424. ** This routine identifies subexpressions in the WHERE clause where
  131425. ** each subexpression is separated by the AND operator or some other
  131426. ** operator specified in the op parameter. The WhereClause structure
  131427. ** is filled with pointers to subexpressions. For example:
  131428. **
  131429. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  131430. ** \________/ \_______________/ \________________/
  131431. ** slot[0] slot[1] slot[2]
  131432. **
  131433. ** The original WHERE clause in pExpr is unaltered. All this routine
  131434. ** does is make slot[] entries point to substructure within pExpr.
  131435. **
  131436. ** In the previous sentence and in the diagram, "slot[]" refers to
  131437. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  131438. ** all terms of the WHERE clause.
  131439. */
  131440. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  131441. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  131442. pWC->op = op;
  131443. if( pE2==0 ) return;
  131444. if( pE2->op!=op ){
  131445. whereClauseInsert(pWC, pExpr, 0);
  131446. }else{
  131447. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  131448. sqlite3WhereSplit(pWC, pE2->pRight, op);
  131449. }
  131450. }
  131451. /*
  131452. ** Initialize a preallocated WhereClause structure.
  131453. */
  131454. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  131455. WhereClause *pWC, /* The WhereClause to be initialized */
  131456. WhereInfo *pWInfo /* The WHERE processing context */
  131457. ){
  131458. pWC->pWInfo = pWInfo;
  131459. pWC->hasOr = 0;
  131460. pWC->pOuter = 0;
  131461. pWC->nTerm = 0;
  131462. pWC->nSlot = ArraySize(pWC->aStatic);
  131463. pWC->a = pWC->aStatic;
  131464. }
  131465. /*
  131466. ** Deallocate a WhereClause structure. The WhereClause structure
  131467. ** itself is not freed. This routine is the inverse of
  131468. ** sqlite3WhereClauseInit().
  131469. */
  131470. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  131471. int i;
  131472. WhereTerm *a;
  131473. sqlite3 *db = pWC->pWInfo->pParse->db;
  131474. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  131475. if( a->wtFlags & TERM_DYNAMIC ){
  131476. sqlite3ExprDelete(db, a->pExpr);
  131477. }
  131478. if( a->wtFlags & TERM_ORINFO ){
  131479. whereOrInfoDelete(db, a->u.pOrInfo);
  131480. }else if( a->wtFlags & TERM_ANDINFO ){
  131481. whereAndInfoDelete(db, a->u.pAndInfo);
  131482. }
  131483. }
  131484. if( pWC->a!=pWC->aStatic ){
  131485. sqlite3DbFree(db, pWC->a);
  131486. }
  131487. }
  131488. /*
  131489. ** These routines walk (recursively) an expression tree and generate
  131490. ** a bitmask indicating which tables are used in that expression
  131491. ** tree.
  131492. */
  131493. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
  131494. Bitmask mask;
  131495. if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
  131496. return sqlite3WhereGetMask(pMaskSet, p->iTable);
  131497. }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  131498. assert( p->op!=TK_IF_NULL_ROW );
  131499. return 0;
  131500. }
  131501. mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
  131502. if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
  131503. if( p->pRight ){
  131504. mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
  131505. assert( p->x.pList==0 );
  131506. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  131507. if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
  131508. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  131509. }else if( p->x.pList ){
  131510. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  131511. }
  131512. #ifndef SQLITE_OMIT_WINDOWFUNC
  131513. if( p->op==TK_FUNCTION && p->y.pWin ){
  131514. mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);
  131515. mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);
  131516. }
  131517. #endif
  131518. return mask;
  131519. }
  131520. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  131521. return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
  131522. }
  131523. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  131524. int i;
  131525. Bitmask mask = 0;
  131526. if( pList ){
  131527. for(i=0; i<pList->nExpr; i++){
  131528. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  131529. }
  131530. }
  131531. return mask;
  131532. }
  131533. /*
  131534. ** Call exprAnalyze on all terms in a WHERE clause.
  131535. **
  131536. ** Note that exprAnalyze() might add new virtual terms onto the
  131537. ** end of the WHERE clause. We do not want to analyze these new
  131538. ** virtual terms, so start analyzing at the end and work forward
  131539. ** so that the added virtual terms are never processed.
  131540. */
  131541. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  131542. SrcList *pTabList, /* the FROM clause */
  131543. WhereClause *pWC /* the WHERE clause to be analyzed */
  131544. ){
  131545. int i;
  131546. for(i=pWC->nTerm-1; i>=0; i--){
  131547. exprAnalyze(pTabList, pWC, i);
  131548. }
  131549. }
  131550. /*
  131551. ** For table-valued-functions, transform the function arguments into
  131552. ** new WHERE clause terms.
  131553. **
  131554. ** Each function argument translates into an equality constraint against
  131555. ** a HIDDEN column in the table.
  131556. */
  131557. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  131558. Parse *pParse, /* Parsing context */
  131559. struct SrcList_item *pItem, /* The FROM clause term to process */
  131560. WhereClause *pWC /* Xfer function arguments to here */
  131561. ){
  131562. Table *pTab;
  131563. int j, k;
  131564. ExprList *pArgs;
  131565. Expr *pColRef;
  131566. Expr *pTerm;
  131567. if( pItem->fg.isTabFunc==0 ) return;
  131568. pTab = pItem->pTab;
  131569. assert( pTab!=0 );
  131570. pArgs = pItem->u1.pFuncArg;
  131571. if( pArgs==0 ) return;
  131572. for(j=k=0; j<pArgs->nExpr; j++){
  131573. Expr *pRhs;
  131574. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
  131575. if( k>=pTab->nCol ){
  131576. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  131577. pTab->zName, j);
  131578. return;
  131579. }
  131580. pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
  131581. if( pColRef==0 ) return;
  131582. pColRef->iTable = pItem->iCursor;
  131583. pColRef->iColumn = k++;
  131584. pColRef->y.pTab = pTab;
  131585. pRhs = sqlite3PExpr(pParse, TK_UPLUS,
  131586. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
  131587. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
  131588. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  131589. }
  131590. }
  131591. /************** End of whereexpr.c *******************************************/
  131592. /************** Begin file where.c *******************************************/
  131593. /*
  131594. ** 2001 September 15
  131595. **
  131596. ** The author disclaims copyright to this source code. In place of
  131597. ** a legal notice, here is a blessing:
  131598. **
  131599. ** May you do good and not evil.
  131600. ** May you find forgiveness for yourself and forgive others.
  131601. ** May you share freely, never taking more than you give.
  131602. **
  131603. *************************************************************************
  131604. ** This module contains C code that generates VDBE code used to process
  131605. ** the WHERE clause of SQL statements. This module is responsible for
  131606. ** generating the code that loops through a table looking for applicable
  131607. ** rows. Indices are selected and used to speed the search when doing
  131608. ** so is applicable. Because this module is responsible for selecting
  131609. ** indices, you might also think of this module as the "query optimizer".
  131610. */
  131611. /* #include "sqliteInt.h" */
  131612. /* #include "whereInt.h" */
  131613. /*
  131614. ** Extra information appended to the end of sqlite3_index_info but not
  131615. ** visible to the xBestIndex function, at least not directly. The
  131616. ** sqlite3_vtab_collation() interface knows how to reach it, however.
  131617. **
  131618. ** This object is not an API and can be changed from one release to the
  131619. ** next. As long as allocateIndexInfo() and sqlite3_vtab_collation()
  131620. ** agree on the structure, all will be well.
  131621. */
  131622. typedef struct HiddenIndexInfo HiddenIndexInfo;
  131623. struct HiddenIndexInfo {
  131624. WhereClause *pWC; /* The Where clause being analyzed */
  131625. Parse *pParse; /* The parsing context */
  131626. };
  131627. /* Forward declaration of methods */
  131628. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  131629. /* Test variable that can be set to enable WHERE tracing */
  131630. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  131631. /***/ int sqlite3WhereTrace = 0;
  131632. #endif
  131633. /*
  131634. ** Return the estimated number of output rows from a WHERE clause
  131635. */
  131636. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  131637. return pWInfo->nRowOut;
  131638. }
  131639. /*
  131640. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  131641. ** WHERE clause returns outputs for DISTINCT processing.
  131642. */
  131643. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  131644. return pWInfo->eDistinct;
  131645. }
  131646. /*
  131647. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  131648. ** Return FALSE if the output needs to be sorted.
  131649. */
  131650. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  131651. return pWInfo->nOBSat;
  131652. }
  131653. /*
  131654. ** In the ORDER BY LIMIT optimization, if the inner-most loop is known
  131655. ** to emit rows in increasing order, and if the last row emitted by the
  131656. ** inner-most loop did not fit within the sorter, then we can skip all
  131657. ** subsequent rows for the current iteration of the inner loop (because they
  131658. ** will not fit in the sorter either) and continue with the second inner
  131659. ** loop - the loop immediately outside the inner-most.
  131660. **
  131661. ** When a row does not fit in the sorter (because the sorter already
  131662. ** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the
  131663. ** label returned by this function.
  131664. **
  131665. ** If the ORDER BY LIMIT optimization applies, the jump destination should
  131666. ** be the continuation for the second-inner-most loop. If the ORDER BY
  131667. ** LIMIT optimization does not apply, then the jump destination should
  131668. ** be the continuation for the inner-most loop.
  131669. **
  131670. ** It is always safe for this routine to return the continuation of the
  131671. ** inner-most loop, in the sense that a correct answer will result.
  131672. ** Returning the continuation the second inner loop is an optimization
  131673. ** that might make the code run a little faster, but should not change
  131674. ** the final answer.
  131675. */
  131676. SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){
  131677. WhereLevel *pInner;
  131678. if( !pWInfo->bOrderedInnerLoop ){
  131679. /* The ORDER BY LIMIT optimization does not apply. Jump to the
  131680. ** continuation of the inner-most loop. */
  131681. return pWInfo->iContinue;
  131682. }
  131683. pInner = &pWInfo->a[pWInfo->nLevel-1];
  131684. assert( pInner->addrNxt!=0 );
  131685. return pInner->addrNxt;
  131686. }
  131687. /*
  131688. ** Return the VDBE address or label to jump to in order to continue
  131689. ** immediately with the next row of a WHERE clause.
  131690. */
  131691. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  131692. assert( pWInfo->iContinue!=0 );
  131693. return pWInfo->iContinue;
  131694. }
  131695. /*
  131696. ** Return the VDBE address or label to jump to in order to break
  131697. ** out of a WHERE loop.
  131698. */
  131699. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  131700. return pWInfo->iBreak;
  131701. }
  131702. /*
  131703. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  131704. ** operate directly on the rowis returned by a WHERE clause. Return
  131705. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  131706. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  131707. ** optimization can be used on multiple
  131708. **
  131709. ** If the ONEPASS optimization is used (if this routine returns true)
  131710. ** then also write the indices of open cursors used by ONEPASS
  131711. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  131712. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  131713. ** Either value may be -1, indicating that cursor is not used.
  131714. ** Any cursors returned will have been opened for writing.
  131715. **
  131716. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  131717. ** unable to use the ONEPASS optimization.
  131718. */
  131719. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  131720. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  131721. #ifdef WHERETRACE_ENABLED
  131722. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  131723. sqlite3DebugPrintf("%s cursors: %d %d\n",
  131724. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  131725. aiCur[0], aiCur[1]);
  131726. }
  131727. #endif
  131728. return pWInfo->eOnePass;
  131729. }
  131730. /*
  131731. ** Move the content of pSrc into pDest
  131732. */
  131733. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  131734. pDest->n = pSrc->n;
  131735. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  131736. }
  131737. /*
  131738. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  131739. **
  131740. ** The new entry might overwrite an existing entry, or it might be
  131741. ** appended, or it might be discarded. Do whatever is the right thing
  131742. ** so that pSet keeps the N_OR_COST best entries seen so far.
  131743. */
  131744. static int whereOrInsert(
  131745. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  131746. Bitmask prereq, /* Prerequisites of the new entry */
  131747. LogEst rRun, /* Run-cost of the new entry */
  131748. LogEst nOut /* Number of outputs for the new entry */
  131749. ){
  131750. u16 i;
  131751. WhereOrCost *p;
  131752. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  131753. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  131754. goto whereOrInsert_done;
  131755. }
  131756. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  131757. return 0;
  131758. }
  131759. }
  131760. if( pSet->n<N_OR_COST ){
  131761. p = &pSet->a[pSet->n++];
  131762. p->nOut = nOut;
  131763. }else{
  131764. p = pSet->a;
  131765. for(i=1; i<pSet->n; i++){
  131766. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  131767. }
  131768. if( p->rRun<=rRun ) return 0;
  131769. }
  131770. whereOrInsert_done:
  131771. p->prereq = prereq;
  131772. p->rRun = rRun;
  131773. if( p->nOut>nOut ) p->nOut = nOut;
  131774. return 1;
  131775. }
  131776. /*
  131777. ** Return the bitmask for the given cursor number. Return 0 if
  131778. ** iCursor is not in the set.
  131779. */
  131780. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  131781. int i;
  131782. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  131783. for(i=0; i<pMaskSet->n; i++){
  131784. if( pMaskSet->ix[i]==iCursor ){
  131785. return MASKBIT(i);
  131786. }
  131787. }
  131788. return 0;
  131789. }
  131790. /*
  131791. ** Create a new mask for cursor iCursor.
  131792. **
  131793. ** There is one cursor per table in the FROM clause. The number of
  131794. ** tables in the FROM clause is limited by a test early in the
  131795. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  131796. ** array will never overflow.
  131797. */
  131798. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  131799. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  131800. pMaskSet->ix[pMaskSet->n++] = iCursor;
  131801. }
  131802. /*
  131803. ** Advance to the next WhereTerm that matches according to the criteria
  131804. ** established when the pScan object was initialized by whereScanInit().
  131805. ** Return NULL if there are no more matching WhereTerms.
  131806. */
  131807. static WhereTerm *whereScanNext(WhereScan *pScan){
  131808. int iCur; /* The cursor on the LHS of the term */
  131809. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  131810. Expr *pX; /* An expression being tested */
  131811. WhereClause *pWC; /* Shorthand for pScan->pWC */
  131812. WhereTerm *pTerm; /* The term being tested */
  131813. int k = pScan->k; /* Where to start scanning */
  131814. assert( pScan->iEquiv<=pScan->nEquiv );
  131815. pWC = pScan->pWC;
  131816. while(1){
  131817. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  131818. iCur = pScan->aiCur[pScan->iEquiv-1];
  131819. assert( pWC!=0 );
  131820. do{
  131821. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  131822. if( pTerm->leftCursor==iCur
  131823. && pTerm->u.leftColumn==iColumn
  131824. && (iColumn!=XN_EXPR
  131825. || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
  131826. pScan->pIdxExpr,iCur)==0)
  131827. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  131828. ){
  131829. if( (pTerm->eOperator & WO_EQUIV)!=0
  131830. && pScan->nEquiv<ArraySize(pScan->aiCur)
  131831. && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
  131832. ){
  131833. int j;
  131834. for(j=0; j<pScan->nEquiv; j++){
  131835. if( pScan->aiCur[j]==pX->iTable
  131836. && pScan->aiColumn[j]==pX->iColumn ){
  131837. break;
  131838. }
  131839. }
  131840. if( j==pScan->nEquiv ){
  131841. pScan->aiCur[j] = pX->iTable;
  131842. pScan->aiColumn[j] = pX->iColumn;
  131843. pScan->nEquiv++;
  131844. }
  131845. }
  131846. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  131847. /* Verify the affinity and collating sequence match */
  131848. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  131849. CollSeq *pColl;
  131850. Parse *pParse = pWC->pWInfo->pParse;
  131851. pX = pTerm->pExpr;
  131852. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  131853. continue;
  131854. }
  131855. assert(pX->pLeft);
  131856. pColl = sqlite3BinaryCompareCollSeq(pParse,
  131857. pX->pLeft, pX->pRight);
  131858. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  131859. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  131860. continue;
  131861. }
  131862. }
  131863. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  131864. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  131865. && pX->iTable==pScan->aiCur[0]
  131866. && pX->iColumn==pScan->aiColumn[0]
  131867. ){
  131868. testcase( pTerm->eOperator & WO_IS );
  131869. continue;
  131870. }
  131871. pScan->pWC = pWC;
  131872. pScan->k = k+1;
  131873. return pTerm;
  131874. }
  131875. }
  131876. }
  131877. pWC = pWC->pOuter;
  131878. k = 0;
  131879. }while( pWC!=0 );
  131880. if( pScan->iEquiv>=pScan->nEquiv ) break;
  131881. pWC = pScan->pOrigWC;
  131882. k = 0;
  131883. pScan->iEquiv++;
  131884. }
  131885. return 0;
  131886. }
  131887. /*
  131888. ** This is whereScanInit() for the case of an index on an expression.
  131889. ** It is factored out into a separate tail-recursion subroutine so that
  131890. ** the normal whereScanInit() routine, which is a high-runner, does not
  131891. ** need to push registers onto the stack as part of its prologue.
  131892. */
  131893. static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){
  131894. pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);
  131895. return whereScanNext(pScan);
  131896. }
  131897. /*
  131898. ** Initialize a WHERE clause scanner object. Return a pointer to the
  131899. ** first match. Return NULL if there are no matches.
  131900. **
  131901. ** The scanner will be searching the WHERE clause pWC. It will look
  131902. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  131903. ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
  131904. ** must be one of the indexes of table iCur.
  131905. **
  131906. ** The <op> must be one of the operators described by opMask.
  131907. **
  131908. ** If the search is for X and the WHERE clause contains terms of the
  131909. ** form X=Y then this routine might also return terms of the form
  131910. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  131911. ** but is enough to handle most commonly occurring SQL statements.
  131912. **
  131913. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  131914. ** index pIdx.
  131915. */
  131916. static WhereTerm *whereScanInit(
  131917. WhereScan *pScan, /* The WhereScan object being initialized */
  131918. WhereClause *pWC, /* The WHERE clause to be scanned */
  131919. int iCur, /* Cursor to scan for */
  131920. int iColumn, /* Column to scan for */
  131921. u32 opMask, /* Operator(s) to scan for */
  131922. Index *pIdx /* Must be compatible with this index */
  131923. ){
  131924. pScan->pOrigWC = pWC;
  131925. pScan->pWC = pWC;
  131926. pScan->pIdxExpr = 0;
  131927. pScan->idxaff = 0;
  131928. pScan->zCollName = 0;
  131929. pScan->opMask = opMask;
  131930. pScan->k = 0;
  131931. pScan->aiCur[0] = iCur;
  131932. pScan->nEquiv = 1;
  131933. pScan->iEquiv = 1;
  131934. if( pIdx ){
  131935. int j = iColumn;
  131936. iColumn = pIdx->aiColumn[j];
  131937. if( iColumn==XN_EXPR ){
  131938. pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  131939. pScan->zCollName = pIdx->azColl[j];
  131940. pScan->aiColumn[0] = XN_EXPR;
  131941. return whereScanInitIndexExpr(pScan);
  131942. }else if( iColumn==pIdx->pTable->iPKey ){
  131943. iColumn = XN_ROWID;
  131944. }else if( iColumn>=0 ){
  131945. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  131946. pScan->zCollName = pIdx->azColl[j];
  131947. }
  131948. }else if( iColumn==XN_EXPR ){
  131949. return 0;
  131950. }
  131951. pScan->aiColumn[0] = iColumn;
  131952. return whereScanNext(pScan);
  131953. }
  131954. /*
  131955. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  131956. ** where X is a reference to the iColumn of table iCur or of index pIdx
  131957. ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
  131958. ** the op parameter. Return a pointer to the term. Return 0 if not found.
  131959. **
  131960. ** If pIdx!=0 then it must be one of the indexes of table iCur.
  131961. ** Search for terms matching the iColumn-th column of pIdx
  131962. ** rather than the iColumn-th column of table iCur.
  131963. **
  131964. ** The term returned might by Y=<expr> if there is another constraint in
  131965. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  131966. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  131967. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  131968. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  131969. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  131970. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  131971. **
  131972. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  131973. ** then try for the one with no dependencies on <expr> - in other words where
  131974. ** <expr> is a constant expression of some kind. Only return entries of
  131975. ** the form "X <op> Y" where Y is a column in another table if no terms of
  131976. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  131977. ** exist, try to return a term that does not use WO_EQUIV.
  131978. */
  131979. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  131980. WhereClause *pWC, /* The WHERE clause to be searched */
  131981. int iCur, /* Cursor number of LHS */
  131982. int iColumn, /* Column number of LHS */
  131983. Bitmask notReady, /* RHS must not overlap with this mask */
  131984. u32 op, /* Mask of WO_xx values describing operator */
  131985. Index *pIdx /* Must be compatible with this index, if not NULL */
  131986. ){
  131987. WhereTerm *pResult = 0;
  131988. WhereTerm *p;
  131989. WhereScan scan;
  131990. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  131991. op &= WO_EQ|WO_IS;
  131992. while( p ){
  131993. if( (p->prereqRight & notReady)==0 ){
  131994. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  131995. testcase( p->eOperator & WO_IS );
  131996. return p;
  131997. }
  131998. if( pResult==0 ) pResult = p;
  131999. }
  132000. p = whereScanNext(&scan);
  132001. }
  132002. return pResult;
  132003. }
  132004. /*
  132005. ** This function searches pList for an entry that matches the iCol-th column
  132006. ** of index pIdx.
  132007. **
  132008. ** If such an expression is found, its index in pList->a[] is returned. If
  132009. ** no expression is found, -1 is returned.
  132010. */
  132011. static int findIndexCol(
  132012. Parse *pParse, /* Parse context */
  132013. ExprList *pList, /* Expression list to search */
  132014. int iBase, /* Cursor for table associated with pIdx */
  132015. Index *pIdx, /* Index to match column of */
  132016. int iCol /* Column of index to match */
  132017. ){
  132018. int i;
  132019. const char *zColl = pIdx->azColl[iCol];
  132020. for(i=0; i<pList->nExpr; i++){
  132021. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  132022. if( p->op==TK_COLUMN
  132023. && p->iColumn==pIdx->aiColumn[iCol]
  132024. && p->iTable==iBase
  132025. ){
  132026. CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
  132027. if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
  132028. return i;
  132029. }
  132030. }
  132031. }
  132032. return -1;
  132033. }
  132034. /*
  132035. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  132036. */
  132037. static int indexColumnNotNull(Index *pIdx, int iCol){
  132038. int j;
  132039. assert( pIdx!=0 );
  132040. assert( iCol>=0 && iCol<pIdx->nColumn );
  132041. j = pIdx->aiColumn[iCol];
  132042. if( j>=0 ){
  132043. return pIdx->pTable->aCol[j].notNull;
  132044. }else if( j==(-1) ){
  132045. return 1;
  132046. }else{
  132047. assert( j==(-2) );
  132048. return 0; /* Assume an indexed expression can always yield a NULL */
  132049. }
  132050. }
  132051. /*
  132052. ** Return true if the DISTINCT expression-list passed as the third argument
  132053. ** is redundant.
  132054. **
  132055. ** A DISTINCT list is redundant if any subset of the columns in the
  132056. ** DISTINCT list are collectively unique and individually non-null.
  132057. */
  132058. static int isDistinctRedundant(
  132059. Parse *pParse, /* Parsing context */
  132060. SrcList *pTabList, /* The FROM clause */
  132061. WhereClause *pWC, /* The WHERE clause */
  132062. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  132063. ){
  132064. Table *pTab;
  132065. Index *pIdx;
  132066. int i;
  132067. int iBase;
  132068. /* If there is more than one table or sub-select in the FROM clause of
  132069. ** this query, then it will not be possible to show that the DISTINCT
  132070. ** clause is redundant. */
  132071. if( pTabList->nSrc!=1 ) return 0;
  132072. iBase = pTabList->a[0].iCursor;
  132073. pTab = pTabList->a[0].pTab;
  132074. /* If any of the expressions is an IPK column on table iBase, then return
  132075. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  132076. ** current SELECT is a correlated sub-query.
  132077. */
  132078. for(i=0; i<pDistinct->nExpr; i++){
  132079. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  132080. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  132081. }
  132082. /* Loop through all indices on the table, checking each to see if it makes
  132083. ** the DISTINCT qualifier redundant. It does so if:
  132084. **
  132085. ** 1. The index is itself UNIQUE, and
  132086. **
  132087. ** 2. All of the columns in the index are either part of the pDistinct
  132088. ** list, or else the WHERE clause contains a term of the form "col=X",
  132089. ** where X is a constant value. The collation sequences of the
  132090. ** comparison and select-list expressions must match those of the index.
  132091. **
  132092. ** 3. All of those index columns for which the WHERE clause does not
  132093. ** contain a "col=X" term are subject to a NOT NULL constraint.
  132094. */
  132095. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  132096. if( !IsUniqueIndex(pIdx) ) continue;
  132097. for(i=0; i<pIdx->nKeyCol; i++){
  132098. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  132099. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  132100. if( indexColumnNotNull(pIdx, i)==0 ) break;
  132101. }
  132102. }
  132103. if( i==pIdx->nKeyCol ){
  132104. /* This index implies that the DISTINCT qualifier is redundant. */
  132105. return 1;
  132106. }
  132107. }
  132108. return 0;
  132109. }
  132110. /*
  132111. ** Estimate the logarithm of the input value to base 2.
  132112. */
  132113. static LogEst estLog(LogEst N){
  132114. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  132115. }
  132116. /*
  132117. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  132118. **
  132119. ** This routine runs over generated VDBE code and translates OP_Column
  132120. ** opcodes into OP_Copy when the table is being accessed via co-routine
  132121. ** instead of via table lookup.
  132122. **
  132123. ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
  132124. ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
  132125. ** then each OP_Rowid is transformed into an instruction to increment the
  132126. ** value stored in its output register.
  132127. */
  132128. static void translateColumnToCopy(
  132129. Parse *pParse, /* Parsing context */
  132130. int iStart, /* Translate from this opcode to the end */
  132131. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  132132. int iRegister, /* The first column is in this register */
  132133. int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
  132134. ){
  132135. Vdbe *v = pParse->pVdbe;
  132136. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  132137. int iEnd = sqlite3VdbeCurrentAddr(v);
  132138. if( pParse->db->mallocFailed ) return;
  132139. for(; iStart<iEnd; iStart++, pOp++){
  132140. if( pOp->p1!=iTabCur ) continue;
  132141. if( pOp->opcode==OP_Column ){
  132142. pOp->opcode = OP_Copy;
  132143. pOp->p1 = pOp->p2 + iRegister;
  132144. pOp->p2 = pOp->p3;
  132145. pOp->p3 = 0;
  132146. }else if( pOp->opcode==OP_Rowid ){
  132147. if( bIncrRowid ){
  132148. /* Increment the value stored in the P2 operand of the OP_Rowid. */
  132149. pOp->opcode = OP_AddImm;
  132150. pOp->p1 = pOp->p2;
  132151. pOp->p2 = 1;
  132152. }else{
  132153. pOp->opcode = OP_Null;
  132154. pOp->p1 = 0;
  132155. pOp->p3 = 0;
  132156. }
  132157. }
  132158. }
  132159. }
  132160. /*
  132161. ** Two routines for printing the content of an sqlite3_index_info
  132162. ** structure. Used for testing and debugging only. If neither
  132163. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  132164. ** are no-ops.
  132165. */
  132166. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  132167. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  132168. int i;
  132169. if( !sqlite3WhereTrace ) return;
  132170. for(i=0; i<p->nConstraint; i++){
  132171. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  132172. i,
  132173. p->aConstraint[i].iColumn,
  132174. p->aConstraint[i].iTermOffset,
  132175. p->aConstraint[i].op,
  132176. p->aConstraint[i].usable);
  132177. }
  132178. for(i=0; i<p->nOrderBy; i++){
  132179. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  132180. i,
  132181. p->aOrderBy[i].iColumn,
  132182. p->aOrderBy[i].desc);
  132183. }
  132184. }
  132185. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  132186. int i;
  132187. if( !sqlite3WhereTrace ) return;
  132188. for(i=0; i<p->nConstraint; i++){
  132189. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  132190. i,
  132191. p->aConstraintUsage[i].argvIndex,
  132192. p->aConstraintUsage[i].omit);
  132193. }
  132194. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  132195. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  132196. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  132197. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  132198. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  132199. }
  132200. #else
  132201. #define TRACE_IDX_INPUTS(A)
  132202. #define TRACE_IDX_OUTPUTS(A)
  132203. #endif
  132204. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  132205. /*
  132206. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  132207. ** could be used with an index to access pSrc, assuming an appropriate
  132208. ** index existed.
  132209. */
  132210. static int termCanDriveIndex(
  132211. WhereTerm *pTerm, /* WHERE clause term to check */
  132212. struct SrcList_item *pSrc, /* Table we are trying to access */
  132213. Bitmask notReady /* Tables in outer loops of the join */
  132214. ){
  132215. char aff;
  132216. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  132217. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  132218. if( (pSrc->fg.jointype & JT_LEFT)
  132219. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  132220. && (pTerm->eOperator & WO_IS)
  132221. ){
  132222. /* Cannot use an IS term from the WHERE clause as an index driver for
  132223. ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
  132224. ** the ON clause. */
  132225. return 0;
  132226. }
  132227. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  132228. if( pTerm->u.leftColumn<0 ) return 0;
  132229. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  132230. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  132231. testcase( pTerm->pExpr->op==TK_IS );
  132232. return 1;
  132233. }
  132234. #endif
  132235. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  132236. /*
  132237. ** Generate code to construct the Index object for an automatic index
  132238. ** and to set up the WhereLevel object pLevel so that the code generator
  132239. ** makes use of the automatic index.
  132240. */
  132241. static void constructAutomaticIndex(
  132242. Parse *pParse, /* The parsing context */
  132243. WhereClause *pWC, /* The WHERE clause */
  132244. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  132245. Bitmask notReady, /* Mask of cursors that are not available */
  132246. WhereLevel *pLevel /* Write new index here */
  132247. ){
  132248. int nKeyCol; /* Number of columns in the constructed index */
  132249. WhereTerm *pTerm; /* A single term of the WHERE clause */
  132250. WhereTerm *pWCEnd; /* End of pWC->a[] */
  132251. Index *pIdx; /* Object describing the transient index */
  132252. Vdbe *v; /* Prepared statement under construction */
  132253. int addrInit; /* Address of the initialization bypass jump */
  132254. Table *pTable; /* The table being indexed */
  132255. int addrTop; /* Top of the index fill loop */
  132256. int regRecord; /* Register holding an index record */
  132257. int n; /* Column counter */
  132258. int i; /* Loop counter */
  132259. int mxBitCol; /* Maximum column in pSrc->colUsed */
  132260. CollSeq *pColl; /* Collating sequence to on a column */
  132261. WhereLoop *pLoop; /* The Loop object */
  132262. char *zNotUsed; /* Extra space on the end of pIdx */
  132263. Bitmask idxCols; /* Bitmap of columns used for indexing */
  132264. Bitmask extraCols; /* Bitmap of additional columns */
  132265. u8 sentWarning = 0; /* True if a warnning has been issued */
  132266. Expr *pPartial = 0; /* Partial Index Expression */
  132267. int iContinue = 0; /* Jump here to skip excluded rows */
  132268. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  132269. int addrCounter = 0; /* Address where integer counter is initialized */
  132270. int regBase; /* Array of registers where record is assembled */
  132271. /* Generate code to skip over the creation and initialization of the
  132272. ** transient index on 2nd and subsequent iterations of the loop. */
  132273. v = pParse->pVdbe;
  132274. assert( v!=0 );
  132275. addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  132276. /* Count the number of columns that will be added to the index
  132277. ** and used to match WHERE clause constraints */
  132278. nKeyCol = 0;
  132279. pTable = pSrc->pTab;
  132280. pWCEnd = &pWC->a[pWC->nTerm];
  132281. pLoop = pLevel->pWLoop;
  132282. idxCols = 0;
  132283. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  132284. Expr *pExpr = pTerm->pExpr;
  132285. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  132286. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  132287. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  132288. if( pLoop->prereq==0
  132289. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  132290. && !ExprHasProperty(pExpr, EP_FromJoin)
  132291. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  132292. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  132293. sqlite3ExprDup(pParse->db, pExpr, 0));
  132294. }
  132295. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  132296. int iCol = pTerm->u.leftColumn;
  132297. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  132298. testcase( iCol==BMS );
  132299. testcase( iCol==BMS-1 );
  132300. if( !sentWarning ){
  132301. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  132302. "automatic index on %s(%s)", pTable->zName,
  132303. pTable->aCol[iCol].zName);
  132304. sentWarning = 1;
  132305. }
  132306. if( (idxCols & cMask)==0 ){
  132307. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  132308. goto end_auto_index_create;
  132309. }
  132310. pLoop->aLTerm[nKeyCol++] = pTerm;
  132311. idxCols |= cMask;
  132312. }
  132313. }
  132314. }
  132315. assert( nKeyCol>0 );
  132316. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  132317. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  132318. | WHERE_AUTO_INDEX;
  132319. /* Count the number of additional columns needed to create a
  132320. ** covering index. A "covering index" is an index that contains all
  132321. ** columns that are needed by the query. With a covering index, the
  132322. ** original table never needs to be accessed. Automatic indices must
  132323. ** be a covering index because the index will not be updated if the
  132324. ** original table changes and the index and table cannot both be used
  132325. ** if they go out of sync.
  132326. */
  132327. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  132328. mxBitCol = MIN(BMS-1,pTable->nCol);
  132329. testcase( pTable->nCol==BMS-1 );
  132330. testcase( pTable->nCol==BMS-2 );
  132331. for(i=0; i<mxBitCol; i++){
  132332. if( extraCols & MASKBIT(i) ) nKeyCol++;
  132333. }
  132334. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  132335. nKeyCol += pTable->nCol - BMS + 1;
  132336. }
  132337. /* Construct the Index object to describe this index */
  132338. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  132339. if( pIdx==0 ) goto end_auto_index_create;
  132340. pLoop->u.btree.pIndex = pIdx;
  132341. pIdx->zName = "auto-index";
  132342. pIdx->pTable = pTable;
  132343. n = 0;
  132344. idxCols = 0;
  132345. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  132346. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  132347. int iCol = pTerm->u.leftColumn;
  132348. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  132349. testcase( iCol==BMS-1 );
  132350. testcase( iCol==BMS );
  132351. if( (idxCols & cMask)==0 ){
  132352. Expr *pX = pTerm->pExpr;
  132353. idxCols |= cMask;
  132354. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  132355. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  132356. pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
  132357. n++;
  132358. }
  132359. }
  132360. }
  132361. assert( (u32)n==pLoop->u.btree.nEq );
  132362. /* Add additional columns needed to make the automatic index into
  132363. ** a covering index */
  132364. for(i=0; i<mxBitCol; i++){
  132365. if( extraCols & MASKBIT(i) ){
  132366. pIdx->aiColumn[n] = i;
  132367. pIdx->azColl[n] = sqlite3StrBINARY;
  132368. n++;
  132369. }
  132370. }
  132371. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  132372. for(i=BMS-1; i<pTable->nCol; i++){
  132373. pIdx->aiColumn[n] = i;
  132374. pIdx->azColl[n] = sqlite3StrBINARY;
  132375. n++;
  132376. }
  132377. }
  132378. assert( n==nKeyCol );
  132379. pIdx->aiColumn[n] = XN_ROWID;
  132380. pIdx->azColl[n] = sqlite3StrBINARY;
  132381. /* Create the automatic index */
  132382. assert( pLevel->iIdxCur>=0 );
  132383. pLevel->iIdxCur = pParse->nTab++;
  132384. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  132385. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  132386. VdbeComment((v, "for %s", pTable->zName));
  132387. /* Fill the automatic index with content */
  132388. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  132389. if( pTabItem->fg.viaCoroutine ){
  132390. int regYield = pTabItem->regReturn;
  132391. addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
  132392. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  132393. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  132394. VdbeCoverage(v);
  132395. VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
  132396. }else{
  132397. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  132398. }
  132399. if( pPartial ){
  132400. iContinue = sqlite3VdbeMakeLabel(pParse);
  132401. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  132402. pLoop->wsFlags |= WHERE_PARTIALIDX;
  132403. }
  132404. regRecord = sqlite3GetTempReg(pParse);
  132405. regBase = sqlite3GenerateIndexKey(
  132406. pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  132407. );
  132408. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  132409. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  132410. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  132411. if( pTabItem->fg.viaCoroutine ){
  132412. sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
  132413. testcase( pParse->db->mallocFailed );
  132414. translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
  132415. pTabItem->regResult, 1);
  132416. sqlite3VdbeGoto(v, addrTop);
  132417. pTabItem->fg.viaCoroutine = 0;
  132418. }else{
  132419. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  132420. }
  132421. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  132422. sqlite3VdbeJumpHere(v, addrTop);
  132423. sqlite3ReleaseTempReg(pParse, regRecord);
  132424. /* Jump here when skipping the initialization */
  132425. sqlite3VdbeJumpHere(v, addrInit);
  132426. end_auto_index_create:
  132427. sqlite3ExprDelete(pParse->db, pPartial);
  132428. }
  132429. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  132430. #ifndef SQLITE_OMIT_VIRTUALTABLE
  132431. /*
  132432. ** Allocate and populate an sqlite3_index_info structure. It is the
  132433. ** responsibility of the caller to eventually release the structure
  132434. ** by passing the pointer returned by this function to sqlite3_free().
  132435. */
  132436. static sqlite3_index_info *allocateIndexInfo(
  132437. Parse *pParse, /* The parsing context */
  132438. WhereClause *pWC, /* The WHERE clause being analyzed */
  132439. Bitmask mUnusable, /* Ignore terms with these prereqs */
  132440. struct SrcList_item *pSrc, /* The FROM clause term that is the vtab */
  132441. ExprList *pOrderBy, /* The ORDER BY clause */
  132442. u16 *pmNoOmit /* Mask of terms not to omit */
  132443. ){
  132444. int i, j;
  132445. int nTerm;
  132446. struct sqlite3_index_constraint *pIdxCons;
  132447. struct sqlite3_index_orderby *pIdxOrderBy;
  132448. struct sqlite3_index_constraint_usage *pUsage;
  132449. struct HiddenIndexInfo *pHidden;
  132450. WhereTerm *pTerm;
  132451. int nOrderBy;
  132452. sqlite3_index_info *pIdxInfo;
  132453. u16 mNoOmit = 0;
  132454. /* Count the number of possible WHERE clause constraints referring
  132455. ** to this virtual table */
  132456. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  132457. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  132458. if( pTerm->prereqRight & mUnusable ) continue;
  132459. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  132460. testcase( pTerm->eOperator & WO_IN );
  132461. testcase( pTerm->eOperator & WO_ISNULL );
  132462. testcase( pTerm->eOperator & WO_IS );
  132463. testcase( pTerm->eOperator & WO_ALL );
  132464. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  132465. if( pTerm->wtFlags & TERM_VNULL ) continue;
  132466. assert( pTerm->u.leftColumn>=(-1) );
  132467. nTerm++;
  132468. }
  132469. /* If the ORDER BY clause contains only columns in the current
  132470. ** virtual table then allocate space for the aOrderBy part of
  132471. ** the sqlite3_index_info structure.
  132472. */
  132473. nOrderBy = 0;
  132474. if( pOrderBy ){
  132475. int n = pOrderBy->nExpr;
  132476. for(i=0; i<n; i++){
  132477. Expr *pExpr = pOrderBy->a[i].pExpr;
  132478. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  132479. }
  132480. if( i==n){
  132481. nOrderBy = n;
  132482. }
  132483. }
  132484. /* Allocate the sqlite3_index_info structure
  132485. */
  132486. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  132487. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  132488. + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) );
  132489. if( pIdxInfo==0 ){
  132490. sqlite3ErrorMsg(pParse, "out of memory");
  132491. return 0;
  132492. }
  132493. /* Initialize the structure. The sqlite3_index_info structure contains
  132494. ** many fields that are declared "const" to prevent xBestIndex from
  132495. ** changing them. We have to do some funky casting in order to
  132496. ** initialize those fields.
  132497. */
  132498. pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
  132499. pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];
  132500. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  132501. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  132502. *(int*)&pIdxInfo->nConstraint = nTerm;
  132503. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  132504. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  132505. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  132506. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  132507. pUsage;
  132508. pHidden->pWC = pWC;
  132509. pHidden->pParse = pParse;
  132510. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  132511. u16 op;
  132512. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  132513. if( pTerm->prereqRight & mUnusable ) continue;
  132514. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  132515. testcase( pTerm->eOperator & WO_IN );
  132516. testcase( pTerm->eOperator & WO_IS );
  132517. testcase( pTerm->eOperator & WO_ISNULL );
  132518. testcase( pTerm->eOperator & WO_ALL );
  132519. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  132520. if( pTerm->wtFlags & TERM_VNULL ) continue;
  132521. if( (pSrc->fg.jointype & JT_LEFT)!=0
  132522. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  132523. && (pTerm->eOperator & (WO_IS|WO_ISNULL))
  132524. ){
  132525. /* An "IS" term in the WHERE clause where the virtual table is the rhs
  132526. ** of a LEFT JOIN. Do not pass this term to the virtual table
  132527. ** implementation, as this can lead to incorrect results from SQL such
  132528. ** as:
  132529. **
  132530. ** "LEFT JOIN vtab WHERE vtab.col IS NULL" */
  132531. testcase( pTerm->eOperator & WO_ISNULL );
  132532. testcase( pTerm->eOperator & WO_IS );
  132533. continue;
  132534. }
  132535. assert( pTerm->u.leftColumn>=(-1) );
  132536. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  132537. pIdxCons[j].iTermOffset = i;
  132538. op = pTerm->eOperator & WO_ALL;
  132539. if( op==WO_IN ) op = WO_EQ;
  132540. if( op==WO_AUX ){
  132541. pIdxCons[j].op = pTerm->eMatchOp;
  132542. }else if( op & (WO_ISNULL|WO_IS) ){
  132543. if( op==WO_ISNULL ){
  132544. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
  132545. }else{
  132546. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
  132547. }
  132548. }else{
  132549. pIdxCons[j].op = (u8)op;
  132550. /* The direct assignment in the previous line is possible only because
  132551. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  132552. ** following asserts verify this fact. */
  132553. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  132554. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  132555. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  132556. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  132557. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  132558. assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
  132559. if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
  132560. && sqlite3ExprIsVector(pTerm->pExpr->pRight)
  132561. ){
  132562. if( i<16 ) mNoOmit |= (1 << i);
  132563. if( op==WO_LT ) pIdxCons[j].op = WO_LE;
  132564. if( op==WO_GT ) pIdxCons[j].op = WO_GE;
  132565. }
  132566. }
  132567. j++;
  132568. }
  132569. for(i=0; i<nOrderBy; i++){
  132570. Expr *pExpr = pOrderBy->a[i].pExpr;
  132571. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  132572. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  132573. }
  132574. *pmNoOmit = mNoOmit;
  132575. return pIdxInfo;
  132576. }
  132577. /*
  132578. ** The table object reference passed as the second argument to this function
  132579. ** must represent a virtual table. This function invokes the xBestIndex()
  132580. ** method of the virtual table with the sqlite3_index_info object that
  132581. ** comes in as the 3rd argument to this function.
  132582. **
  132583. ** If an error occurs, pParse is populated with an error message and an
  132584. ** appropriate error code is returned. A return of SQLITE_CONSTRAINT from
  132585. ** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that
  132586. ** the current configuration of "unusable" flags in sqlite3_index_info can
  132587. ** not result in a valid plan.
  132588. **
  132589. ** Whether or not an error is returned, it is the responsibility of the
  132590. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  132591. ** that this is required.
  132592. */
  132593. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  132594. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  132595. int rc;
  132596. TRACE_IDX_INPUTS(p);
  132597. rc = pVtab->pModule->xBestIndex(pVtab, p);
  132598. TRACE_IDX_OUTPUTS(p);
  132599. if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
  132600. if( rc==SQLITE_NOMEM ){
  132601. sqlite3OomFault(pParse->db);
  132602. }else if( !pVtab->zErrMsg ){
  132603. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  132604. }else{
  132605. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  132606. }
  132607. }
  132608. sqlite3_free(pVtab->zErrMsg);
  132609. pVtab->zErrMsg = 0;
  132610. return rc;
  132611. }
  132612. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  132613. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  132614. /*
  132615. ** Estimate the location of a particular key among all keys in an
  132616. ** index. Store the results in aStat as follows:
  132617. **
  132618. ** aStat[0] Est. number of rows less than pRec
  132619. ** aStat[1] Est. number of rows equal to pRec
  132620. **
  132621. ** Return the index of the sample that is the smallest sample that
  132622. ** is greater than or equal to pRec. Note that this index is not an index
  132623. ** into the aSample[] array - it is an index into a virtual set of samples
  132624. ** based on the contents of aSample[] and the number of fields in record
  132625. ** pRec.
  132626. */
  132627. static int whereKeyStats(
  132628. Parse *pParse, /* Database connection */
  132629. Index *pIdx, /* Index to consider domain of */
  132630. UnpackedRecord *pRec, /* Vector of values to consider */
  132631. int roundUp, /* Round up if true. Round down if false */
  132632. tRowcnt *aStat /* OUT: stats written here */
  132633. ){
  132634. IndexSample *aSample = pIdx->aSample;
  132635. int iCol; /* Index of required stats in anEq[] etc. */
  132636. int i; /* Index of first sample >= pRec */
  132637. int iSample; /* Smallest sample larger than or equal to pRec */
  132638. int iMin = 0; /* Smallest sample not yet tested */
  132639. int iTest; /* Next sample to test */
  132640. int res; /* Result of comparison operation */
  132641. int nField; /* Number of fields in pRec */
  132642. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  132643. #ifndef SQLITE_DEBUG
  132644. UNUSED_PARAMETER( pParse );
  132645. #endif
  132646. assert( pRec!=0 );
  132647. assert( pIdx->nSample>0 );
  132648. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  132649. /* Do a binary search to find the first sample greater than or equal
  132650. ** to pRec. If pRec contains a single field, the set of samples to search
  132651. ** is simply the aSample[] array. If the samples in aSample[] contain more
  132652. ** than one fields, all fields following the first are ignored.
  132653. **
  132654. ** If pRec contains N fields, where N is more than one, then as well as the
  132655. ** samples in aSample[] (truncated to N fields), the search also has to
  132656. ** consider prefixes of those samples. For example, if the set of samples
  132657. ** in aSample is:
  132658. **
  132659. ** aSample[0] = (a, 5)
  132660. ** aSample[1] = (a, 10)
  132661. ** aSample[2] = (b, 5)
  132662. ** aSample[3] = (c, 100)
  132663. ** aSample[4] = (c, 105)
  132664. **
  132665. ** Then the search space should ideally be the samples above and the
  132666. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  132667. ** the code actually searches this set:
  132668. **
  132669. ** 0: (a)
  132670. ** 1: (a, 5)
  132671. ** 2: (a, 10)
  132672. ** 3: (a, 10)
  132673. ** 4: (b)
  132674. ** 5: (b, 5)
  132675. ** 6: (c)
  132676. ** 7: (c, 100)
  132677. ** 8: (c, 105)
  132678. ** 9: (c, 105)
  132679. **
  132680. ** For each sample in the aSample[] array, N samples are present in the
  132681. ** effective sample array. In the above, samples 0 and 1 are based on
  132682. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  132683. **
  132684. ** Often, sample i of each block of N effective samples has (i+1) fields.
  132685. ** Except, each sample may be extended to ensure that it is greater than or
  132686. ** equal to the previous sample in the array. For example, in the above,
  132687. ** sample 2 is the first sample of a block of N samples, so at first it
  132688. ** appears that it should be 1 field in size. However, that would make it
  132689. ** smaller than sample 1, so the binary search would not work. As a result,
  132690. ** it is extended to two fields. The duplicates that this creates do not
  132691. ** cause any problems.
  132692. */
  132693. nField = pRec->nField;
  132694. iCol = 0;
  132695. iSample = pIdx->nSample * nField;
  132696. do{
  132697. int iSamp; /* Index in aSample[] of test sample */
  132698. int n; /* Number of fields in test sample */
  132699. iTest = (iMin+iSample)/2;
  132700. iSamp = iTest / nField;
  132701. if( iSamp>0 ){
  132702. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  132703. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  132704. ** fields that is greater than the previous effective sample. */
  132705. for(n=(iTest % nField) + 1; n<nField; n++){
  132706. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  132707. }
  132708. }else{
  132709. n = iTest + 1;
  132710. }
  132711. pRec->nField = n;
  132712. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  132713. if( res<0 ){
  132714. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  132715. iMin = iTest+1;
  132716. }else if( res==0 && n<nField ){
  132717. iLower = aSample[iSamp].anLt[n-1];
  132718. iMin = iTest+1;
  132719. res = -1;
  132720. }else{
  132721. iSample = iTest;
  132722. iCol = n-1;
  132723. }
  132724. }while( res && iMin<iSample );
  132725. i = iSample / nField;
  132726. #ifdef SQLITE_DEBUG
  132727. /* The following assert statements check that the binary search code
  132728. ** above found the right answer. This block serves no purpose other
  132729. ** than to invoke the asserts. */
  132730. if( pParse->db->mallocFailed==0 ){
  132731. if( res==0 ){
  132732. /* If (res==0) is true, then pRec must be equal to sample i. */
  132733. assert( i<pIdx->nSample );
  132734. assert( iCol==nField-1 );
  132735. pRec->nField = nField;
  132736. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  132737. || pParse->db->mallocFailed
  132738. );
  132739. }else{
  132740. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  132741. ** all samples in the aSample[] array, pRec must be smaller than the
  132742. ** (iCol+1) field prefix of sample i. */
  132743. assert( i<=pIdx->nSample && i>=0 );
  132744. pRec->nField = iCol+1;
  132745. assert( i==pIdx->nSample
  132746. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  132747. || pParse->db->mallocFailed );
  132748. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  132749. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  132750. ** be greater than or equal to the (iCol) field prefix of sample i.
  132751. ** If (i>0), then pRec must also be greater than sample (i-1). */
  132752. if( iCol>0 ){
  132753. pRec->nField = iCol;
  132754. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  132755. || pParse->db->mallocFailed );
  132756. }
  132757. if( i>0 ){
  132758. pRec->nField = nField;
  132759. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  132760. || pParse->db->mallocFailed );
  132761. }
  132762. }
  132763. }
  132764. #endif /* ifdef SQLITE_DEBUG */
  132765. if( res==0 ){
  132766. /* Record pRec is equal to sample i */
  132767. assert( iCol==nField-1 );
  132768. aStat[0] = aSample[i].anLt[iCol];
  132769. aStat[1] = aSample[i].anEq[iCol];
  132770. }else{
  132771. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  132772. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  132773. ** is larger than all samples in the array. */
  132774. tRowcnt iUpper, iGap;
  132775. if( i>=pIdx->nSample ){
  132776. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  132777. }else{
  132778. iUpper = aSample[i].anLt[iCol];
  132779. }
  132780. if( iLower>=iUpper ){
  132781. iGap = 0;
  132782. }else{
  132783. iGap = iUpper - iLower;
  132784. }
  132785. if( roundUp ){
  132786. iGap = (iGap*2)/3;
  132787. }else{
  132788. iGap = iGap/3;
  132789. }
  132790. aStat[0] = iLower + iGap;
  132791. aStat[1] = pIdx->aAvgEq[nField-1];
  132792. }
  132793. /* Restore the pRec->nField value before returning. */
  132794. pRec->nField = nField;
  132795. return i;
  132796. }
  132797. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  132798. /*
  132799. ** If it is not NULL, pTerm is a term that provides an upper or lower
  132800. ** bound on a range scan. Without considering pTerm, it is estimated
  132801. ** that the scan will visit nNew rows. This function returns the number
  132802. ** estimated to be visited after taking pTerm into account.
  132803. **
  132804. ** If the user explicitly specified a likelihood() value for this term,
  132805. ** then the return value is the likelihood multiplied by the number of
  132806. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  132807. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  132808. */
  132809. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  132810. LogEst nRet = nNew;
  132811. if( pTerm ){
  132812. if( pTerm->truthProb<=0 ){
  132813. nRet += pTerm->truthProb;
  132814. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  132815. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  132816. }
  132817. }
  132818. return nRet;
  132819. }
  132820. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  132821. /*
  132822. ** Return the affinity for a single column of an index.
  132823. */
  132824. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  132825. assert( iCol>=0 && iCol<pIdx->nColumn );
  132826. if( !pIdx->zColAff ){
  132827. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  132828. }
  132829. return pIdx->zColAff[iCol];
  132830. }
  132831. #endif
  132832. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  132833. /*
  132834. ** This function is called to estimate the number of rows visited by a
  132835. ** range-scan on a skip-scan index. For example:
  132836. **
  132837. ** CREATE INDEX i1 ON t1(a, b, c);
  132838. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  132839. **
  132840. ** Value pLoop->nOut is currently set to the estimated number of rows
  132841. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  132842. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  132843. ** on the stat4 data for the index. this scan will be peformed multiple
  132844. ** times (once for each (a,b) combination that matches a=?) is dealt with
  132845. ** by the caller.
  132846. **
  132847. ** It does this by scanning through all stat4 samples, comparing values
  132848. ** extracted from pLower and pUpper with the corresponding column in each
  132849. ** sample. If L and U are the number of samples found to be less than or
  132850. ** equal to the values extracted from pLower and pUpper respectively, and
  132851. ** N is the total number of samples, the pLoop->nOut value is adjusted
  132852. ** as follows:
  132853. **
  132854. ** nOut = nOut * ( min(U - L, 1) / N )
  132855. **
  132856. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  132857. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  132858. ** U is set to N.
  132859. **
  132860. ** Normally, this function sets *pbDone to 1 before returning. However,
  132861. ** if no value can be extracted from either pLower or pUpper (and so the
  132862. ** estimate of the number of rows delivered remains unchanged), *pbDone
  132863. ** is left as is.
  132864. **
  132865. ** If an error occurs, an SQLite error code is returned. Otherwise,
  132866. ** SQLITE_OK.
  132867. */
  132868. static int whereRangeSkipScanEst(
  132869. Parse *pParse, /* Parsing & code generating context */
  132870. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  132871. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  132872. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  132873. int *pbDone /* Set to true if at least one expr. value extracted */
  132874. ){
  132875. Index *p = pLoop->u.btree.pIndex;
  132876. int nEq = pLoop->u.btree.nEq;
  132877. sqlite3 *db = pParse->db;
  132878. int nLower = -1;
  132879. int nUpper = p->nSample+1;
  132880. int rc = SQLITE_OK;
  132881. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  132882. CollSeq *pColl;
  132883. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  132884. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  132885. sqlite3_value *pVal = 0; /* Value extracted from record */
  132886. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  132887. if( pLower ){
  132888. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  132889. nLower = 0;
  132890. }
  132891. if( pUpper && rc==SQLITE_OK ){
  132892. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  132893. nUpper = p2 ? 0 : p->nSample;
  132894. }
  132895. if( p1 || p2 ){
  132896. int i;
  132897. int nDiff;
  132898. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  132899. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  132900. if( rc==SQLITE_OK && p1 ){
  132901. int res = sqlite3MemCompare(p1, pVal, pColl);
  132902. if( res>=0 ) nLower++;
  132903. }
  132904. if( rc==SQLITE_OK && p2 ){
  132905. int res = sqlite3MemCompare(p2, pVal, pColl);
  132906. if( res>=0 ) nUpper++;
  132907. }
  132908. }
  132909. nDiff = (nUpper - nLower);
  132910. if( nDiff<=0 ) nDiff = 1;
  132911. /* If there is both an upper and lower bound specified, and the
  132912. ** comparisons indicate that they are close together, use the fallback
  132913. ** method (assume that the scan visits 1/64 of the rows) for estimating
  132914. ** the number of rows visited. Otherwise, estimate the number of rows
  132915. ** using the method described in the header comment for this function. */
  132916. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  132917. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  132918. pLoop->nOut -= nAdjust;
  132919. *pbDone = 1;
  132920. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  132921. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  132922. }
  132923. }else{
  132924. assert( *pbDone==0 );
  132925. }
  132926. sqlite3ValueFree(p1);
  132927. sqlite3ValueFree(p2);
  132928. sqlite3ValueFree(pVal);
  132929. return rc;
  132930. }
  132931. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  132932. /*
  132933. ** This function is used to estimate the number of rows that will be visited
  132934. ** by scanning an index for a range of values. The range may have an upper
  132935. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  132936. ** and lower bounds are represented by pLower and pUpper respectively. For
  132937. ** example, assuming that index p is on t1(a):
  132938. **
  132939. ** ... FROM t1 WHERE a > ? AND a < ? ...
  132940. ** |_____| |_____|
  132941. ** | |
  132942. ** pLower pUpper
  132943. **
  132944. ** If either of the upper or lower bound is not present, then NULL is passed in
  132945. ** place of the corresponding WhereTerm.
  132946. **
  132947. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  132948. ** column subject to the range constraint. Or, equivalently, the number of
  132949. ** equality constraints optimized by the proposed index scan. For example,
  132950. ** assuming index p is on t1(a, b), and the SQL query is:
  132951. **
  132952. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  132953. **
  132954. ** then nEq is set to 1 (as the range restricted column, b, is the second
  132955. ** left-most column of the index). Or, if the query is:
  132956. **
  132957. ** ... FROM t1 WHERE a > ? AND a < ? ...
  132958. **
  132959. ** then nEq is set to 0.
  132960. **
  132961. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  132962. ** number of rows that the index scan is expected to visit without
  132963. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  132964. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  132965. ** to account for the range constraints pLower and pUpper.
  132966. **
  132967. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  132968. ** used, a single range inequality reduces the search space by a factor of 4.
  132969. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  132970. ** rows visited by a factor of 64.
  132971. */
  132972. static int whereRangeScanEst(
  132973. Parse *pParse, /* Parsing & code generating context */
  132974. WhereLoopBuilder *pBuilder,
  132975. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  132976. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  132977. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  132978. ){
  132979. int rc = SQLITE_OK;
  132980. int nOut = pLoop->nOut;
  132981. LogEst nNew;
  132982. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  132983. Index *p = pLoop->u.btree.pIndex;
  132984. int nEq = pLoop->u.btree.nEq;
  132985. if( p->nSample>0 && nEq<p->nSampleCol
  132986. && OptimizationEnabled(pParse->db, SQLITE_Stat34)
  132987. ){
  132988. if( nEq==pBuilder->nRecValid ){
  132989. UnpackedRecord *pRec = pBuilder->pRec;
  132990. tRowcnt a[2];
  132991. int nBtm = pLoop->u.btree.nBtm;
  132992. int nTop = pLoop->u.btree.nTop;
  132993. /* Variable iLower will be set to the estimate of the number of rows in
  132994. ** the index that are less than the lower bound of the range query. The
  132995. ** lower bound being the concatenation of $P and $L, where $P is the
  132996. ** key-prefix formed by the nEq values matched against the nEq left-most
  132997. ** columns of the index, and $L is the value in pLower.
  132998. **
  132999. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  133000. ** is not a simple variable or literal value), the lower bound of the
  133001. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  133002. ** if $L is available, whereKeyStats() is called for both ($P) and
  133003. ** ($P:$L) and the larger of the two returned values is used.
  133004. **
  133005. ** Similarly, iUpper is to be set to the estimate of the number of rows
  133006. ** less than the upper bound of the range query. Where the upper bound
  133007. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  133008. ** of iUpper are requested of whereKeyStats() and the smaller used.
  133009. **
  133010. ** The number of rows between the two bounds is then just iUpper-iLower.
  133011. */
  133012. tRowcnt iLower; /* Rows less than the lower bound */
  133013. tRowcnt iUpper; /* Rows less than the upper bound */
  133014. int iLwrIdx = -2; /* aSample[] for the lower bound */
  133015. int iUprIdx = -1; /* aSample[] for the upper bound */
  133016. if( pRec ){
  133017. testcase( pRec->nField!=pBuilder->nRecValid );
  133018. pRec->nField = pBuilder->nRecValid;
  133019. }
  133020. /* Determine iLower and iUpper using ($P) only. */
  133021. if( nEq==0 ){
  133022. iLower = 0;
  133023. iUpper = p->nRowEst0;
  133024. }else{
  133025. /* Note: this call could be optimized away - since the same values must
  133026. ** have been requested when testing key $P in whereEqualScanEst(). */
  133027. whereKeyStats(pParse, p, pRec, 0, a);
  133028. iLower = a[0];
  133029. iUpper = a[0] + a[1];
  133030. }
  133031. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  133032. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  133033. assert( p->aSortOrder!=0 );
  133034. if( p->aSortOrder[nEq] ){
  133035. /* The roles of pLower and pUpper are swapped for a DESC index */
  133036. SWAP(WhereTerm*, pLower, pUpper);
  133037. SWAP(int, nBtm, nTop);
  133038. }
  133039. /* If possible, improve on the iLower estimate using ($P:$L). */
  133040. if( pLower ){
  133041. int n; /* Values extracted from pExpr */
  133042. Expr *pExpr = pLower->pExpr->pRight;
  133043. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
  133044. if( rc==SQLITE_OK && n ){
  133045. tRowcnt iNew;
  133046. u16 mask = WO_GT|WO_LE;
  133047. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  133048. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  133049. iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
  133050. if( iNew>iLower ) iLower = iNew;
  133051. nOut--;
  133052. pLower = 0;
  133053. }
  133054. }
  133055. /* If possible, improve on the iUpper estimate using ($P:$U). */
  133056. if( pUpper ){
  133057. int n; /* Values extracted from pExpr */
  133058. Expr *pExpr = pUpper->pExpr->pRight;
  133059. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
  133060. if( rc==SQLITE_OK && n ){
  133061. tRowcnt iNew;
  133062. u16 mask = WO_GT|WO_LE;
  133063. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  133064. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  133065. iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
  133066. if( iNew<iUpper ) iUpper = iNew;
  133067. nOut--;
  133068. pUpper = 0;
  133069. }
  133070. }
  133071. pBuilder->pRec = pRec;
  133072. if( rc==SQLITE_OK ){
  133073. if( iUpper>iLower ){
  133074. nNew = sqlite3LogEst(iUpper - iLower);
  133075. /* TUNING: If both iUpper and iLower are derived from the same
  133076. ** sample, then assume they are 4x more selective. This brings
  133077. ** the estimated selectivity more in line with what it would be
  133078. ** if estimated without the use of STAT3/4 tables. */
  133079. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  133080. }else{
  133081. nNew = 10; assert( 10==sqlite3LogEst(2) );
  133082. }
  133083. if( nNew<nOut ){
  133084. nOut = nNew;
  133085. }
  133086. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  133087. (u32)iLower, (u32)iUpper, nOut));
  133088. }
  133089. }else{
  133090. int bDone = 0;
  133091. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  133092. if( bDone ) return rc;
  133093. }
  133094. }
  133095. #else
  133096. UNUSED_PARAMETER(pParse);
  133097. UNUSED_PARAMETER(pBuilder);
  133098. assert( pLower || pUpper );
  133099. #endif
  133100. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  133101. nNew = whereRangeAdjust(pLower, nOut);
  133102. nNew = whereRangeAdjust(pUpper, nNew);
  133103. /* TUNING: If there is both an upper and lower limit and neither limit
  133104. ** has an application-defined likelihood(), assume the range is
  133105. ** reduced by an additional 75%. This means that, by default, an open-ended
  133106. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  133107. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  133108. ** match 1/64 of the index. */
  133109. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  133110. nNew -= 20;
  133111. }
  133112. nOut -= (pLower!=0) + (pUpper!=0);
  133113. if( nNew<10 ) nNew = 10;
  133114. if( nNew<nOut ) nOut = nNew;
  133115. #if defined(WHERETRACE_ENABLED)
  133116. if( pLoop->nOut>nOut ){
  133117. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  133118. pLoop->nOut, nOut));
  133119. }
  133120. #endif
  133121. pLoop->nOut = (LogEst)nOut;
  133122. return rc;
  133123. }
  133124. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133125. /*
  133126. ** Estimate the number of rows that will be returned based on
  133127. ** an equality constraint x=VALUE and where that VALUE occurs in
  133128. ** the histogram data. This only works when x is the left-most
  133129. ** column of an index and sqlite_stat3 histogram data is available
  133130. ** for that index. When pExpr==NULL that means the constraint is
  133131. ** "x IS NULL" instead of "x=VALUE".
  133132. **
  133133. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  133134. ** If unable to make an estimate, leave *pnRow unchanged and return
  133135. ** non-zero.
  133136. **
  133137. ** This routine can fail if it is unable to load a collating sequence
  133138. ** required for string comparison, or if unable to allocate memory
  133139. ** for a UTF conversion required for comparison. The error is stored
  133140. ** in the pParse structure.
  133141. */
  133142. static int whereEqualScanEst(
  133143. Parse *pParse, /* Parsing & code generating context */
  133144. WhereLoopBuilder *pBuilder,
  133145. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  133146. tRowcnt *pnRow /* Write the revised row estimate here */
  133147. ){
  133148. Index *p = pBuilder->pNew->u.btree.pIndex;
  133149. int nEq = pBuilder->pNew->u.btree.nEq;
  133150. UnpackedRecord *pRec = pBuilder->pRec;
  133151. int rc; /* Subfunction return code */
  133152. tRowcnt a[2]; /* Statistics */
  133153. int bOk;
  133154. assert( nEq>=1 );
  133155. assert( nEq<=p->nColumn );
  133156. assert( p->aSample!=0 );
  133157. assert( p->nSample>0 );
  133158. assert( pBuilder->nRecValid<nEq );
  133159. /* If values are not available for all fields of the index to the left
  133160. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  133161. if( pBuilder->nRecValid<(nEq-1) ){
  133162. return SQLITE_NOTFOUND;
  133163. }
  133164. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  133165. ** below would return the same value. */
  133166. if( nEq>=p->nColumn ){
  133167. *pnRow = 1;
  133168. return SQLITE_OK;
  133169. }
  133170. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
  133171. pBuilder->pRec = pRec;
  133172. if( rc!=SQLITE_OK ) return rc;
  133173. if( bOk==0 ) return SQLITE_NOTFOUND;
  133174. pBuilder->nRecValid = nEq;
  133175. whereKeyStats(pParse, p, pRec, 0, a);
  133176. WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
  133177. p->zName, nEq-1, (int)a[1]));
  133178. *pnRow = a[1];
  133179. return rc;
  133180. }
  133181. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  133182. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133183. /*
  133184. ** Estimate the number of rows that will be returned based on
  133185. ** an IN constraint where the right-hand side of the IN operator
  133186. ** is a list of values. Example:
  133187. **
  133188. ** WHERE x IN (1,2,3,4)
  133189. **
  133190. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  133191. ** If unable to make an estimate, leave *pnRow unchanged and return
  133192. ** non-zero.
  133193. **
  133194. ** This routine can fail if it is unable to load a collating sequence
  133195. ** required for string comparison, or if unable to allocate memory
  133196. ** for a UTF conversion required for comparison. The error is stored
  133197. ** in the pParse structure.
  133198. */
  133199. static int whereInScanEst(
  133200. Parse *pParse, /* Parsing & code generating context */
  133201. WhereLoopBuilder *pBuilder,
  133202. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  133203. tRowcnt *pnRow /* Write the revised row estimate here */
  133204. ){
  133205. Index *p = pBuilder->pNew->u.btree.pIndex;
  133206. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  133207. int nRecValid = pBuilder->nRecValid;
  133208. int rc = SQLITE_OK; /* Subfunction return code */
  133209. tRowcnt nEst; /* Number of rows for a single term */
  133210. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  133211. int i; /* Loop counter */
  133212. assert( p->aSample!=0 );
  133213. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  133214. nEst = nRow0;
  133215. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  133216. nRowEst += nEst;
  133217. pBuilder->nRecValid = nRecValid;
  133218. }
  133219. if( rc==SQLITE_OK ){
  133220. if( nRowEst > nRow0 ) nRowEst = nRow0;
  133221. *pnRow = nRowEst;
  133222. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  133223. }
  133224. assert( pBuilder->nRecValid==nRecValid );
  133225. return rc;
  133226. }
  133227. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  133228. #ifdef WHERETRACE_ENABLED
  133229. /*
  133230. ** Print the content of a WhereTerm object
  133231. */
  133232. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  133233. if( pTerm==0 ){
  133234. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  133235. }else{
  133236. char zType[4];
  133237. char zLeft[50];
  133238. memcpy(zType, "...", 4);
  133239. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  133240. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  133241. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  133242. if( pTerm->eOperator & WO_SINGLE ){
  133243. sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
  133244. pTerm->leftCursor, pTerm->u.leftColumn);
  133245. }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
  133246. sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
  133247. pTerm->u.pOrInfo->indexable);
  133248. }else{
  133249. sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
  133250. }
  133251. sqlite3DebugPrintf(
  133252. "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
  133253. iTerm, pTerm, zType, zLeft, pTerm->truthProb,
  133254. pTerm->eOperator, pTerm->wtFlags);
  133255. if( pTerm->iField ){
  133256. sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
  133257. }else{
  133258. sqlite3DebugPrintf("\n");
  133259. }
  133260. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  133261. }
  133262. }
  133263. #endif
  133264. #ifdef WHERETRACE_ENABLED
  133265. /*
  133266. ** Show the complete content of a WhereClause
  133267. */
  133268. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
  133269. int i;
  133270. for(i=0; i<pWC->nTerm; i++){
  133271. whereTermPrint(&pWC->a[i], i);
  133272. }
  133273. }
  133274. #endif
  133275. #ifdef WHERETRACE_ENABLED
  133276. /*
  133277. ** Print a WhereLoop object for debugging purposes
  133278. */
  133279. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  133280. WhereInfo *pWInfo = pWC->pWInfo;
  133281. int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
  133282. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  133283. Table *pTab = pItem->pTab;
  133284. Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
  133285. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  133286. p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
  133287. sqlite3DebugPrintf(" %12s",
  133288. pItem->zAlias ? pItem->zAlias : pTab->zName);
  133289. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  133290. const char *zName;
  133291. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  133292. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  133293. int i = sqlite3Strlen30(zName) - 1;
  133294. while( zName[i]!='_' ) i--;
  133295. zName += i;
  133296. }
  133297. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  133298. }else{
  133299. sqlite3DebugPrintf("%20s","");
  133300. }
  133301. }else{
  133302. char *z;
  133303. if( p->u.vtab.idxStr ){
  133304. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  133305. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  133306. }else{
  133307. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  133308. }
  133309. sqlite3DebugPrintf(" %-19s", z);
  133310. sqlite3_free(z);
  133311. }
  133312. if( p->wsFlags & WHERE_SKIPSCAN ){
  133313. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  133314. }else{
  133315. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  133316. }
  133317. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  133318. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  133319. int i;
  133320. for(i=0; i<p->nLTerm; i++){
  133321. whereTermPrint(p->aLTerm[i], i);
  133322. }
  133323. }
  133324. }
  133325. #endif
  133326. /*
  133327. ** Convert bulk memory into a valid WhereLoop that can be passed
  133328. ** to whereLoopClear harmlessly.
  133329. */
  133330. static void whereLoopInit(WhereLoop *p){
  133331. p->aLTerm = p->aLTermSpace;
  133332. p->nLTerm = 0;
  133333. p->nLSlot = ArraySize(p->aLTermSpace);
  133334. p->wsFlags = 0;
  133335. }
  133336. /*
  133337. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  133338. */
  133339. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  133340. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  133341. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  133342. sqlite3_free(p->u.vtab.idxStr);
  133343. p->u.vtab.needFree = 0;
  133344. p->u.vtab.idxStr = 0;
  133345. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  133346. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  133347. sqlite3DbFreeNN(db, p->u.btree.pIndex);
  133348. p->u.btree.pIndex = 0;
  133349. }
  133350. }
  133351. }
  133352. /*
  133353. ** Deallocate internal memory used by a WhereLoop object
  133354. */
  133355. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  133356. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  133357. whereLoopClearUnion(db, p);
  133358. whereLoopInit(p);
  133359. }
  133360. /*
  133361. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  133362. */
  133363. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  133364. WhereTerm **paNew;
  133365. if( p->nLSlot>=n ) return SQLITE_OK;
  133366. n = (n+7)&~7;
  133367. paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
  133368. if( paNew==0 ) return SQLITE_NOMEM_BKPT;
  133369. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  133370. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  133371. p->aLTerm = paNew;
  133372. p->nLSlot = n;
  133373. return SQLITE_OK;
  133374. }
  133375. /*
  133376. ** Transfer content from the second pLoop into the first.
  133377. */
  133378. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  133379. whereLoopClearUnion(db, pTo);
  133380. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  133381. memset(&pTo->u, 0, sizeof(pTo->u));
  133382. return SQLITE_NOMEM_BKPT;
  133383. }
  133384. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  133385. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  133386. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  133387. pFrom->u.vtab.needFree = 0;
  133388. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  133389. pFrom->u.btree.pIndex = 0;
  133390. }
  133391. return SQLITE_OK;
  133392. }
  133393. /*
  133394. ** Delete a WhereLoop object
  133395. */
  133396. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  133397. whereLoopClear(db, p);
  133398. sqlite3DbFreeNN(db, p);
  133399. }
  133400. /*
  133401. ** Free a WhereInfo structure
  133402. */
  133403. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  133404. int i;
  133405. assert( pWInfo!=0 );
  133406. for(i=0; i<pWInfo->nLevel; i++){
  133407. WhereLevel *pLevel = &pWInfo->a[i];
  133408. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  133409. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  133410. }
  133411. }
  133412. sqlite3WhereClauseClear(&pWInfo->sWC);
  133413. while( pWInfo->pLoops ){
  133414. WhereLoop *p = pWInfo->pLoops;
  133415. pWInfo->pLoops = p->pNextLoop;
  133416. whereLoopDelete(db, p);
  133417. }
  133418. sqlite3DbFreeNN(db, pWInfo);
  133419. }
  133420. /*
  133421. ** Return TRUE if all of the following are true:
  133422. **
  133423. ** (1) X has the same or lower cost that Y
  133424. ** (2) X uses fewer WHERE clause terms than Y
  133425. ** (3) Every WHERE clause term used by X is also used by Y
  133426. ** (4) X skips at least as many columns as Y
  133427. ** (5) If X is a covering index, than Y is too
  133428. **
  133429. ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
  133430. ** If X is a proper subset of Y then Y is a better choice and ought
  133431. ** to have a lower cost. This routine returns TRUE when that cost
  133432. ** relationship is inverted and needs to be adjusted. Constraint (4)
  133433. ** was added because if X uses skip-scan less than Y it still might
  133434. ** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
  133435. ** was added because a covering index probably deserves to have a lower cost
  133436. ** than a non-covering index even if it is a proper subset.
  133437. */
  133438. static int whereLoopCheaperProperSubset(
  133439. const WhereLoop *pX, /* First WhereLoop to compare */
  133440. const WhereLoop *pY /* Compare against this WhereLoop */
  133441. ){
  133442. int i, j;
  133443. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  133444. return 0; /* X is not a subset of Y */
  133445. }
  133446. if( pY->nSkip > pX->nSkip ) return 0;
  133447. if( pX->rRun >= pY->rRun ){
  133448. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  133449. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  133450. }
  133451. for(i=pX->nLTerm-1; i>=0; i--){
  133452. if( pX->aLTerm[i]==0 ) continue;
  133453. for(j=pY->nLTerm-1; j>=0; j--){
  133454. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  133455. }
  133456. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  133457. }
  133458. if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
  133459. && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
  133460. return 0; /* Constraint (5) */
  133461. }
  133462. return 1; /* All conditions meet */
  133463. }
  133464. /*
  133465. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  133466. ** that:
  133467. **
  133468. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  133469. ** subset of pTemplate
  133470. **
  133471. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  133472. ** is a proper subset.
  133473. **
  133474. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  133475. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  133476. ** also used by Y.
  133477. */
  133478. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  133479. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  133480. for(; p; p=p->pNextLoop){
  133481. if( p->iTab!=pTemplate->iTab ) continue;
  133482. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  133483. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  133484. /* Adjust pTemplate cost downward so that it is cheaper than its
  133485. ** subset p. */
  133486. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  133487. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  133488. pTemplate->rRun = p->rRun;
  133489. pTemplate->nOut = p->nOut - 1;
  133490. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  133491. /* Adjust pTemplate cost upward so that it is costlier than p since
  133492. ** pTemplate is a proper subset of p */
  133493. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  133494. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  133495. pTemplate->rRun = p->rRun;
  133496. pTemplate->nOut = p->nOut + 1;
  133497. }
  133498. }
  133499. }
  133500. /*
  133501. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  133502. ** replaced by pTemplate.
  133503. **
  133504. ** Return NULL if pTemplate does not belong on the WhereLoop list.
  133505. ** In other words if pTemplate ought to be dropped from further consideration.
  133506. **
  133507. ** If pX is a WhereLoop that pTemplate can replace, then return the
  133508. ** link that points to pX.
  133509. **
  133510. ** If pTemplate cannot replace any existing element of the list but needs
  133511. ** to be added to the list as a new entry, then return a pointer to the
  133512. ** tail of the list.
  133513. */
  133514. static WhereLoop **whereLoopFindLesser(
  133515. WhereLoop **ppPrev,
  133516. const WhereLoop *pTemplate
  133517. ){
  133518. WhereLoop *p;
  133519. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  133520. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  133521. /* If either the iTab or iSortIdx values for two WhereLoop are different
  133522. ** then those WhereLoops need to be considered separately. Neither is
  133523. ** a candidate to replace the other. */
  133524. continue;
  133525. }
  133526. /* In the current implementation, the rSetup value is either zero
  133527. ** or the cost of building an automatic index (NlogN) and the NlogN
  133528. ** is the same for compatible WhereLoops. */
  133529. assert( p->rSetup==0 || pTemplate->rSetup==0
  133530. || p->rSetup==pTemplate->rSetup );
  133531. /* whereLoopAddBtree() always generates and inserts the automatic index
  133532. ** case first. Hence compatible candidate WhereLoops never have a larger
  133533. ** rSetup. Call this SETUP-INVARIANT */
  133534. assert( p->rSetup>=pTemplate->rSetup );
  133535. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  133536. ** UNIQUE constraint) with one or more == constraints is better
  133537. ** than an automatic index. Unless it is a skip-scan. */
  133538. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  133539. && (pTemplate->nSkip)==0
  133540. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  133541. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  133542. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  133543. ){
  133544. break;
  133545. }
  133546. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  133547. ** discarded. WhereLoop p is better if:
  133548. ** (1) p has no more dependencies than pTemplate, and
  133549. ** (2) p has an equal or lower cost than pTemplate
  133550. */
  133551. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  133552. && p->rSetup<=pTemplate->rSetup /* (2a) */
  133553. && p->rRun<=pTemplate->rRun /* (2b) */
  133554. && p->nOut<=pTemplate->nOut /* (2c) */
  133555. ){
  133556. return 0; /* Discard pTemplate */
  133557. }
  133558. /* If pTemplate is always better than p, then cause p to be overwritten
  133559. ** with pTemplate. pTemplate is better than p if:
  133560. ** (1) pTemplate has no more dependences than p, and
  133561. ** (2) pTemplate has an equal or lower cost than p.
  133562. */
  133563. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  133564. && p->rRun>=pTemplate->rRun /* (2a) */
  133565. && p->nOut>=pTemplate->nOut /* (2b) */
  133566. ){
  133567. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  133568. break; /* Cause p to be overwritten by pTemplate */
  133569. }
  133570. }
  133571. return ppPrev;
  133572. }
  133573. /*
  133574. ** Insert or replace a WhereLoop entry using the template supplied.
  133575. **
  133576. ** An existing WhereLoop entry might be overwritten if the new template
  133577. ** is better and has fewer dependencies. Or the template will be ignored
  133578. ** and no insert will occur if an existing WhereLoop is faster and has
  133579. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  133580. ** added based on the template.
  133581. **
  133582. ** If pBuilder->pOrSet is not NULL then we care about only the
  133583. ** prerequisites and rRun and nOut costs of the N best loops. That
  133584. ** information is gathered in the pBuilder->pOrSet object. This special
  133585. ** processing mode is used only for OR clause processing.
  133586. **
  133587. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  133588. ** still might overwrite similar loops with the new template if the
  133589. ** new template is better. Loops may be overwritten if the following
  133590. ** conditions are met:
  133591. **
  133592. ** (1) They have the same iTab.
  133593. ** (2) They have the same iSortIdx.
  133594. ** (3) The template has same or fewer dependencies than the current loop
  133595. ** (4) The template has the same or lower cost than the current loop
  133596. */
  133597. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  133598. WhereLoop **ppPrev, *p;
  133599. WhereInfo *pWInfo = pBuilder->pWInfo;
  133600. sqlite3 *db = pWInfo->pParse->db;
  133601. int rc;
  133602. /* Stop the search once we hit the query planner search limit */
  133603. if( pBuilder->iPlanLimit==0 ){
  133604. WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
  133605. if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
  133606. return SQLITE_DONE;
  133607. }
  133608. pBuilder->iPlanLimit--;
  133609. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  133610. ** and prereqs.
  133611. */
  133612. if( pBuilder->pOrSet!=0 ){
  133613. if( pTemplate->nLTerm ){
  133614. #if WHERETRACE_ENABLED
  133615. u16 n = pBuilder->pOrSet->n;
  133616. int x =
  133617. #endif
  133618. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  133619. pTemplate->nOut);
  133620. #if WHERETRACE_ENABLED /* 0x8 */
  133621. if( sqlite3WhereTrace & 0x8 ){
  133622. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  133623. whereLoopPrint(pTemplate, pBuilder->pWC);
  133624. }
  133625. #endif
  133626. }
  133627. return SQLITE_OK;
  133628. }
  133629. /* Look for an existing WhereLoop to replace with pTemplate
  133630. */
  133631. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  133632. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  133633. if( ppPrev==0 ){
  133634. /* There already exists a WhereLoop on the list that is better
  133635. ** than pTemplate, so just ignore pTemplate */
  133636. #if WHERETRACE_ENABLED /* 0x8 */
  133637. if( sqlite3WhereTrace & 0x8 ){
  133638. sqlite3DebugPrintf(" skip: ");
  133639. whereLoopPrint(pTemplate, pBuilder->pWC);
  133640. }
  133641. #endif
  133642. return SQLITE_OK;
  133643. }else{
  133644. p = *ppPrev;
  133645. }
  133646. /* If we reach this point it means that either p[] should be overwritten
  133647. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  133648. ** WhereLoop and insert it.
  133649. */
  133650. #if WHERETRACE_ENABLED /* 0x8 */
  133651. if( sqlite3WhereTrace & 0x8 ){
  133652. if( p!=0 ){
  133653. sqlite3DebugPrintf("replace: ");
  133654. whereLoopPrint(p, pBuilder->pWC);
  133655. sqlite3DebugPrintf(" with: ");
  133656. }else{
  133657. sqlite3DebugPrintf(" add: ");
  133658. }
  133659. whereLoopPrint(pTemplate, pBuilder->pWC);
  133660. }
  133661. #endif
  133662. if( p==0 ){
  133663. /* Allocate a new WhereLoop to add to the end of the list */
  133664. *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
  133665. if( p==0 ) return SQLITE_NOMEM_BKPT;
  133666. whereLoopInit(p);
  133667. p->pNextLoop = 0;
  133668. }else{
  133669. /* We will be overwriting WhereLoop p[]. But before we do, first
  133670. ** go through the rest of the list and delete any other entries besides
  133671. ** p[] that are also supplated by pTemplate */
  133672. WhereLoop **ppTail = &p->pNextLoop;
  133673. WhereLoop *pToDel;
  133674. while( *ppTail ){
  133675. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  133676. if( ppTail==0 ) break;
  133677. pToDel = *ppTail;
  133678. if( pToDel==0 ) break;
  133679. *ppTail = pToDel->pNextLoop;
  133680. #if WHERETRACE_ENABLED /* 0x8 */
  133681. if( sqlite3WhereTrace & 0x8 ){
  133682. sqlite3DebugPrintf(" delete: ");
  133683. whereLoopPrint(pToDel, pBuilder->pWC);
  133684. }
  133685. #endif
  133686. whereLoopDelete(db, pToDel);
  133687. }
  133688. }
  133689. rc = whereLoopXfer(db, p, pTemplate);
  133690. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  133691. Index *pIndex = p->u.btree.pIndex;
  133692. if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){
  133693. p->u.btree.pIndex = 0;
  133694. }
  133695. }
  133696. return rc;
  133697. }
  133698. /*
  133699. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  133700. ** WHERE clause that reference the loop but which are not used by an
  133701. ** index.
  133702. *
  133703. ** For every WHERE clause term that is not used by the index
  133704. ** and which has a truth probability assigned by one of the likelihood(),
  133705. ** likely(), or unlikely() SQL functions, reduce the estimated number
  133706. ** of output rows by the probability specified.
  133707. **
  133708. ** TUNING: For every WHERE clause term that is not used by the index
  133709. ** and which does not have an assigned truth probability, heuristics
  133710. ** described below are used to try to estimate the truth probability.
  133711. ** TODO --> Perhaps this is something that could be improved by better
  133712. ** table statistics.
  133713. **
  133714. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  133715. ** value corresponds to -1 in LogEst notation, so this means decrement
  133716. ** the WhereLoop.nOut field for every such WHERE clause term.
  133717. **
  133718. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  133719. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  133720. ** final output row estimate is no greater than 1/4 of the total number
  133721. ** of rows in the table. In other words, assume that x==EXPR will filter
  133722. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  133723. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  133724. ** on the "x" column and so in that case only cap the output row estimate
  133725. ** at 1/2 instead of 1/4.
  133726. */
  133727. static void whereLoopOutputAdjust(
  133728. WhereClause *pWC, /* The WHERE clause */
  133729. WhereLoop *pLoop, /* The loop to adjust downward */
  133730. LogEst nRow /* Number of rows in the entire table */
  133731. ){
  133732. WhereTerm *pTerm, *pX;
  133733. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  133734. int i, j, k;
  133735. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  133736. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  133737. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  133738. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  133739. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  133740. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  133741. for(j=pLoop->nLTerm-1; j>=0; j--){
  133742. pX = pLoop->aLTerm[j];
  133743. if( pX==0 ) continue;
  133744. if( pX==pTerm ) break;
  133745. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  133746. }
  133747. if( j<0 ){
  133748. if( pTerm->truthProb<=0 ){
  133749. /* If a truth probability is specified using the likelihood() hints,
  133750. ** then use the probability provided by the application. */
  133751. pLoop->nOut += pTerm->truthProb;
  133752. }else{
  133753. /* In the absence of explicit truth probabilities, use heuristics to
  133754. ** guess a reasonable truth probability. */
  133755. pLoop->nOut--;
  133756. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  133757. Expr *pRight = pTerm->pExpr->pRight;
  133758. testcase( pTerm->pExpr->op==TK_IS );
  133759. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  133760. k = 10;
  133761. }else{
  133762. k = 20;
  133763. }
  133764. if( iReduce<k ) iReduce = k;
  133765. }
  133766. }
  133767. }
  133768. }
  133769. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  133770. }
  133771. /*
  133772. ** Term pTerm is a vector range comparison operation. The first comparison
  133773. ** in the vector can be optimized using column nEq of the index. This
  133774. ** function returns the total number of vector elements that can be used
  133775. ** as part of the range comparison.
  133776. **
  133777. ** For example, if the query is:
  133778. **
  133779. ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
  133780. **
  133781. ** and the index:
  133782. **
  133783. ** CREATE INDEX ... ON (a, b, c, d, e)
  133784. **
  133785. ** then this function would be invoked with nEq=1. The value returned in
  133786. ** this case is 3.
  133787. */
  133788. static int whereRangeVectorLen(
  133789. Parse *pParse, /* Parsing context */
  133790. int iCur, /* Cursor open on pIdx */
  133791. Index *pIdx, /* The index to be used for a inequality constraint */
  133792. int nEq, /* Number of prior equality constraints on same index */
  133793. WhereTerm *pTerm /* The vector inequality constraint */
  133794. ){
  133795. int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
  133796. int i;
  133797. nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
  133798. for(i=1; i<nCmp; i++){
  133799. /* Test if comparison i of pTerm is compatible with column (i+nEq)
  133800. ** of the index. If not, exit the loop. */
  133801. char aff; /* Comparison affinity */
  133802. char idxaff = 0; /* Indexed columns affinity */
  133803. CollSeq *pColl; /* Comparison collation sequence */
  133804. Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
  133805. Expr *pRhs = pTerm->pExpr->pRight;
  133806. if( pRhs->flags & EP_xIsSelect ){
  133807. pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
  133808. }else{
  133809. pRhs = pRhs->x.pList->a[i].pExpr;
  133810. }
  133811. /* Check that the LHS of the comparison is a column reference to
  133812. ** the right column of the right source table. And that the sort
  133813. ** order of the index column is the same as the sort order of the
  133814. ** leftmost index column. */
  133815. if( pLhs->op!=TK_COLUMN
  133816. || pLhs->iTable!=iCur
  133817. || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
  133818. || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
  133819. ){
  133820. break;
  133821. }
  133822. testcase( pLhs->iColumn==XN_ROWID );
  133823. aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
  133824. idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
  133825. if( aff!=idxaff ) break;
  133826. pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  133827. if( pColl==0 ) break;
  133828. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
  133829. }
  133830. return i;
  133831. }
  133832. /*
  133833. ** Adjust the cost C by the costMult facter T. This only occurs if
  133834. ** compiled with -DSQLITE_ENABLE_COSTMULT
  133835. */
  133836. #ifdef SQLITE_ENABLE_COSTMULT
  133837. # define ApplyCostMultiplier(C,T) C += T
  133838. #else
  133839. # define ApplyCostMultiplier(C,T)
  133840. #endif
  133841. /*
  133842. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  133843. ** index pIndex. Try to match one more.
  133844. **
  133845. ** When this function is called, pBuilder->pNew->nOut contains the
  133846. ** number of rows expected to be visited by filtering using the nEq
  133847. ** terms only. If it is modified, this value is restored before this
  133848. ** function returns.
  133849. **
  133850. ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
  133851. ** a fake index used for the INTEGER PRIMARY KEY.
  133852. */
  133853. static int whereLoopAddBtreeIndex(
  133854. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  133855. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  133856. Index *pProbe, /* An index on pSrc */
  133857. LogEst nInMul /* log(Number of iterations due to IN) */
  133858. ){
  133859. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  133860. Parse *pParse = pWInfo->pParse; /* Parsing context */
  133861. sqlite3 *db = pParse->db; /* Database connection malloc context */
  133862. WhereLoop *pNew; /* Template WhereLoop under construction */
  133863. WhereTerm *pTerm; /* A WhereTerm under consideration */
  133864. int opMask; /* Valid operators for constraints */
  133865. WhereScan scan; /* Iterator for WHERE terms */
  133866. Bitmask saved_prereq; /* Original value of pNew->prereq */
  133867. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  133868. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  133869. u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
  133870. u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
  133871. u16 saved_nSkip; /* Original value of pNew->nSkip */
  133872. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  133873. LogEst saved_nOut; /* Original value of pNew->nOut */
  133874. int rc = SQLITE_OK; /* Return code */
  133875. LogEst rSize; /* Number of rows in the table */
  133876. LogEst rLogSize; /* Logarithm of table size */
  133877. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  133878. pNew = pBuilder->pNew;
  133879. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  133880. WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d\n",
  133881. pProbe->pTable->zName,pProbe->zName, pNew->u.btree.nEq));
  133882. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  133883. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  133884. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  133885. opMask = WO_LT|WO_LE;
  133886. }else{
  133887. assert( pNew->u.btree.nBtm==0 );
  133888. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  133889. }
  133890. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  133891. assert( pNew->u.btree.nEq<pProbe->nColumn );
  133892. saved_nEq = pNew->u.btree.nEq;
  133893. saved_nBtm = pNew->u.btree.nBtm;
  133894. saved_nTop = pNew->u.btree.nTop;
  133895. saved_nSkip = pNew->nSkip;
  133896. saved_nLTerm = pNew->nLTerm;
  133897. saved_wsFlags = pNew->wsFlags;
  133898. saved_prereq = pNew->prereq;
  133899. saved_nOut = pNew->nOut;
  133900. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  133901. opMask, pProbe);
  133902. pNew->rSetup = 0;
  133903. rSize = pProbe->aiRowLogEst[0];
  133904. rLogSize = estLog(rSize);
  133905. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  133906. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  133907. LogEst rCostIdx;
  133908. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  133909. int nIn = 0;
  133910. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  133911. int nRecValid = pBuilder->nRecValid;
  133912. #endif
  133913. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  133914. && indexColumnNotNull(pProbe, saved_nEq)
  133915. ){
  133916. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  133917. }
  133918. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  133919. /* Do not allow the upper bound of a LIKE optimization range constraint
  133920. ** to mix with a lower range bound from some other source */
  133921. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  133922. /* Do not allow constraints from the WHERE clause to be used by the
  133923. ** right table of a LEFT JOIN. Only constraints in the ON clause are
  133924. ** allowed */
  133925. if( (pSrc->fg.jointype & JT_LEFT)!=0
  133926. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  133927. ){
  133928. continue;
  133929. }
  133930. if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
  133931. pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
  133932. }else{
  133933. pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
  133934. }
  133935. pNew->wsFlags = saved_wsFlags;
  133936. pNew->u.btree.nEq = saved_nEq;
  133937. pNew->u.btree.nBtm = saved_nBtm;
  133938. pNew->u.btree.nTop = saved_nTop;
  133939. pNew->nLTerm = saved_nLTerm;
  133940. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  133941. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  133942. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  133943. assert( nInMul==0
  133944. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  133945. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  133946. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  133947. );
  133948. if( eOp & WO_IN ){
  133949. Expr *pExpr = pTerm->pExpr;
  133950. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  133951. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  133952. int i;
  133953. nIn = 46; assert( 46==sqlite3LogEst(25) );
  133954. /* The expression may actually be of the form (x, y) IN (SELECT...).
  133955. ** In this case there is a separate term for each of (x) and (y).
  133956. ** However, the nIn multiplier should only be applied once, not once
  133957. ** for each such term. The following loop checks that pTerm is the
  133958. ** first such term in use, and sets nIn back to 0 if it is not. */
  133959. for(i=0; i<pNew->nLTerm-1; i++){
  133960. if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
  133961. }
  133962. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  133963. /* "x IN (value, value, ...)" */
  133964. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  133965. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  133966. ** changes "x IN (?)" into "x=?". */
  133967. }
  133968. if( pProbe->hasStat1 ){
  133969. LogEst M, logK, safetyMargin;
  133970. /* Let:
  133971. ** N = the total number of rows in the table
  133972. ** K = the number of entries on the RHS of the IN operator
  133973. ** M = the number of rows in the table that match terms to the
  133974. ** to the left in the same index. If the IN operator is on
  133975. ** the left-most index column, M==N.
  133976. **
  133977. ** Given the definitions above, it is better to omit the IN operator
  133978. ** from the index lookup and instead do a scan of the M elements,
  133979. ** testing each scanned row against the IN operator separately, if:
  133980. **
  133981. ** M*log(K) < K*log(N)
  133982. **
  133983. ** Our estimates for M, K, and N might be inaccurate, so we build in
  133984. ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
  133985. ** with the index, as using an index has better worst-case behavior.
  133986. ** If we do not have real sqlite_stat1 data, always prefer to use
  133987. ** the index.
  133988. */
  133989. M = pProbe->aiRowLogEst[saved_nEq];
  133990. logK = estLog(nIn);
  133991. safetyMargin = 10; /* TUNING: extra weight for indexed IN */
  133992. if( M + logK + safetyMargin < nIn + rLogSize ){
  133993. WHERETRACE(0x40,
  133994. ("Scan preferred over IN operator on column %d of \"%s\" (%d<%d)\n",
  133995. saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
  133996. continue;
  133997. }else{
  133998. WHERETRACE(0x40,
  133999. ("IN operator preferred on column %d of \"%s\" (%d>=%d)\n",
  134000. saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
  134001. }
  134002. }
  134003. pNew->wsFlags |= WHERE_COLUMN_IN;
  134004. }else if( eOp & (WO_EQ|WO_IS) ){
  134005. int iCol = pProbe->aiColumn[saved_nEq];
  134006. pNew->wsFlags |= WHERE_COLUMN_EQ;
  134007. assert( saved_nEq==pNew->u.btree.nEq );
  134008. if( iCol==XN_ROWID
  134009. || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  134010. ){
  134011. if( iCol==XN_ROWID || pProbe->uniqNotNull
  134012. || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
  134013. ){
  134014. pNew->wsFlags |= WHERE_ONEROW;
  134015. }else{
  134016. pNew->wsFlags |= WHERE_UNQ_WANTED;
  134017. }
  134018. }
  134019. }else if( eOp & WO_ISNULL ){
  134020. pNew->wsFlags |= WHERE_COLUMN_NULL;
  134021. }else if( eOp & (WO_GT|WO_GE) ){
  134022. testcase( eOp & WO_GT );
  134023. testcase( eOp & WO_GE );
  134024. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  134025. pNew->u.btree.nBtm = whereRangeVectorLen(
  134026. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  134027. );
  134028. pBtm = pTerm;
  134029. pTop = 0;
  134030. if( pTerm->wtFlags & TERM_LIKEOPT ){
  134031. /* Range contraints that come from the LIKE optimization are
  134032. ** always used in pairs. */
  134033. pTop = &pTerm[1];
  134034. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  134035. assert( pTop->wtFlags & TERM_LIKEOPT );
  134036. assert( pTop->eOperator==WO_LT );
  134037. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  134038. pNew->aLTerm[pNew->nLTerm++] = pTop;
  134039. pNew->wsFlags |= WHERE_TOP_LIMIT;
  134040. pNew->u.btree.nTop = 1;
  134041. }
  134042. }else{
  134043. assert( eOp & (WO_LT|WO_LE) );
  134044. testcase( eOp & WO_LT );
  134045. testcase( eOp & WO_LE );
  134046. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  134047. pNew->u.btree.nTop = whereRangeVectorLen(
  134048. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  134049. );
  134050. pTop = pTerm;
  134051. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  134052. pNew->aLTerm[pNew->nLTerm-2] : 0;
  134053. }
  134054. /* At this point pNew->nOut is set to the number of rows expected to
  134055. ** be visited by the index scan before considering term pTerm, or the
  134056. ** values of nIn and nInMul. In other words, assuming that all
  134057. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  134058. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  134059. assert( pNew->nOut==saved_nOut );
  134060. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  134061. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  134062. ** data, using some other estimate. */
  134063. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  134064. }else{
  134065. int nEq = ++pNew->u.btree.nEq;
  134066. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  134067. assert( pNew->nOut==saved_nOut );
  134068. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  134069. assert( (eOp & WO_IN) || nIn==0 );
  134070. testcase( eOp & WO_IN );
  134071. pNew->nOut += pTerm->truthProb;
  134072. pNew->nOut -= nIn;
  134073. }else{
  134074. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  134075. tRowcnt nOut = 0;
  134076. if( nInMul==0
  134077. && pProbe->nSample
  134078. && pNew->u.btree.nEq<=pProbe->nSampleCol
  134079. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  134080. && OptimizationEnabled(db, SQLITE_Stat34)
  134081. ){
  134082. Expr *pExpr = pTerm->pExpr;
  134083. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  134084. testcase( eOp & WO_EQ );
  134085. testcase( eOp & WO_IS );
  134086. testcase( eOp & WO_ISNULL );
  134087. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  134088. }else{
  134089. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  134090. }
  134091. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  134092. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  134093. if( nOut ){
  134094. pNew->nOut = sqlite3LogEst(nOut);
  134095. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  134096. pNew->nOut -= nIn;
  134097. }
  134098. }
  134099. if( nOut==0 )
  134100. #endif
  134101. {
  134102. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  134103. if( eOp & WO_ISNULL ){
  134104. /* TUNING: If there is no likelihood() value, assume that a
  134105. ** "col IS NULL" expression matches twice as many rows
  134106. ** as (col=?). */
  134107. pNew->nOut += 10;
  134108. }
  134109. }
  134110. }
  134111. }
  134112. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  134113. ** it to pNew->rRun, which is currently set to the cost of the index
  134114. ** seek only. Then, if this is a non-covering index, add the cost of
  134115. ** visiting the rows in the main table. */
  134116. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  134117. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  134118. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  134119. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  134120. }
  134121. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  134122. nOutUnadjusted = pNew->nOut;
  134123. pNew->rRun += nInMul + nIn;
  134124. pNew->nOut += nInMul + nIn;
  134125. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  134126. rc = whereLoopInsert(pBuilder, pNew);
  134127. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  134128. pNew->nOut = saved_nOut;
  134129. }else{
  134130. pNew->nOut = nOutUnadjusted;
  134131. }
  134132. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  134133. && pNew->u.btree.nEq<pProbe->nColumn
  134134. ){
  134135. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  134136. }
  134137. pNew->nOut = saved_nOut;
  134138. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  134139. pBuilder->nRecValid = nRecValid;
  134140. #endif
  134141. }
  134142. pNew->prereq = saved_prereq;
  134143. pNew->u.btree.nEq = saved_nEq;
  134144. pNew->u.btree.nBtm = saved_nBtm;
  134145. pNew->u.btree.nTop = saved_nTop;
  134146. pNew->nSkip = saved_nSkip;
  134147. pNew->wsFlags = saved_wsFlags;
  134148. pNew->nOut = saved_nOut;
  134149. pNew->nLTerm = saved_nLTerm;
  134150. /* Consider using a skip-scan if there are no WHERE clause constraints
  134151. ** available for the left-most terms of the index, and if the average
  134152. ** number of repeats in the left-most terms is at least 18.
  134153. **
  134154. ** The magic number 18 is selected on the basis that scanning 17 rows
  134155. ** is almost always quicker than an index seek (even though if the index
  134156. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  134157. ** the code). And, even if it is not, it should not be too much slower.
  134158. ** On the other hand, the extra seeks could end up being significantly
  134159. ** more expensive. */
  134160. assert( 42==sqlite3LogEst(18) );
  134161. if( saved_nEq==saved_nSkip
  134162. && saved_nEq+1<pProbe->nKeyCol
  134163. && pProbe->noSkipScan==0
  134164. && OptimizationEnabled(db, SQLITE_SkipScan)
  134165. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  134166. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  134167. ){
  134168. LogEst nIter;
  134169. pNew->u.btree.nEq++;
  134170. pNew->nSkip++;
  134171. pNew->aLTerm[pNew->nLTerm++] = 0;
  134172. pNew->wsFlags |= WHERE_SKIPSCAN;
  134173. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  134174. pNew->nOut -= nIter;
  134175. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  134176. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  134177. nIter += 5;
  134178. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  134179. pNew->nOut = saved_nOut;
  134180. pNew->u.btree.nEq = saved_nEq;
  134181. pNew->nSkip = saved_nSkip;
  134182. pNew->wsFlags = saved_wsFlags;
  134183. }
  134184. WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
  134185. pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
  134186. return rc;
  134187. }
  134188. /*
  134189. ** Return True if it is possible that pIndex might be useful in
  134190. ** implementing the ORDER BY clause in pBuilder.
  134191. **
  134192. ** Return False if pBuilder does not contain an ORDER BY clause or
  134193. ** if there is no way for pIndex to be useful in implementing that
  134194. ** ORDER BY clause.
  134195. */
  134196. static int indexMightHelpWithOrderBy(
  134197. WhereLoopBuilder *pBuilder,
  134198. Index *pIndex,
  134199. int iCursor
  134200. ){
  134201. ExprList *pOB;
  134202. ExprList *aColExpr;
  134203. int ii, jj;
  134204. if( pIndex->bUnordered ) return 0;
  134205. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  134206. for(ii=0; ii<pOB->nExpr; ii++){
  134207. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  134208. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  134209. if( pExpr->iColumn<0 ) return 1;
  134210. for(jj=0; jj<pIndex->nKeyCol; jj++){
  134211. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  134212. }
  134213. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  134214. for(jj=0; jj<pIndex->nKeyCol; jj++){
  134215. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  134216. if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  134217. return 1;
  134218. }
  134219. }
  134220. }
  134221. }
  134222. return 0;
  134223. }
  134224. /* Check to see if a partial index with pPartIndexWhere can be used
  134225. ** in the current query. Return true if it can be and false if not.
  134226. */
  134227. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  134228. int i;
  134229. WhereTerm *pTerm;
  134230. Parse *pParse = pWC->pWInfo->pParse;
  134231. while( pWhere->op==TK_AND ){
  134232. if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
  134233. pWhere = pWhere->pRight;
  134234. }
  134235. if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
  134236. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  134237. Expr *pExpr = pTerm->pExpr;
  134238. if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  134239. && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
  134240. ){
  134241. return 1;
  134242. }
  134243. }
  134244. return 0;
  134245. }
  134246. /*
  134247. ** Add all WhereLoop objects for a single table of the join where the table
  134248. ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
  134249. ** a b-tree table, not a virtual table.
  134250. **
  134251. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  134252. ** are calculated as follows:
  134253. **
  134254. ** For a full scan, assuming the table (or index) contains nRow rows:
  134255. **
  134256. ** cost = nRow * 3.0 // full-table scan
  134257. ** cost = nRow * K // scan of covering index
  134258. ** cost = nRow * (K+3.0) // scan of non-covering index
  134259. **
  134260. ** where K is a value between 1.1 and 3.0 set based on the relative
  134261. ** estimated average size of the index and table records.
  134262. **
  134263. ** For an index scan, where nVisit is the number of index rows visited
  134264. ** by the scan, and nSeek is the number of seek operations required on
  134265. ** the index b-tree:
  134266. **
  134267. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  134268. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  134269. **
  134270. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  134271. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  134272. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  134273. **
  134274. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  134275. ** of uncertainty. For this reason, scoring is designed to pick plans that
  134276. ** "do the least harm" if the estimates are inaccurate. For example, a
  134277. ** log(nRow) factor is omitted from a non-covering index scan in order to
  134278. ** bias the scoring in favor of using an index, since the worst-case
  134279. ** performance of using an index is far better than the worst-case performance
  134280. ** of a full table scan.
  134281. */
  134282. static int whereLoopAddBtree(
  134283. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  134284. Bitmask mPrereq /* Extra prerequesites for using this table */
  134285. ){
  134286. WhereInfo *pWInfo; /* WHERE analysis context */
  134287. Index *pProbe; /* An index we are evaluating */
  134288. Index sPk; /* A fake index object for the primary key */
  134289. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  134290. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  134291. SrcList *pTabList; /* The FROM clause */
  134292. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  134293. WhereLoop *pNew; /* Template WhereLoop object */
  134294. int rc = SQLITE_OK; /* Return code */
  134295. int iSortIdx = 1; /* Index number */
  134296. int b; /* A boolean value */
  134297. LogEst rSize; /* number of rows in the table */
  134298. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  134299. WhereClause *pWC; /* The parsed WHERE clause */
  134300. Table *pTab; /* Table being queried */
  134301. pNew = pBuilder->pNew;
  134302. pWInfo = pBuilder->pWInfo;
  134303. pTabList = pWInfo->pTabList;
  134304. pSrc = pTabList->a + pNew->iTab;
  134305. pTab = pSrc->pTab;
  134306. pWC = pBuilder->pWC;
  134307. assert( !IsVirtual(pSrc->pTab) );
  134308. if( pSrc->pIBIndex ){
  134309. /* An INDEXED BY clause specifies a particular index to use */
  134310. pProbe = pSrc->pIBIndex;
  134311. }else if( !HasRowid(pTab) ){
  134312. pProbe = pTab->pIndex;
  134313. }else{
  134314. /* There is no INDEXED BY clause. Create a fake Index object in local
  134315. ** variable sPk to represent the rowid primary key index. Make this
  134316. ** fake index the first in a chain of Index objects with all of the real
  134317. ** indices to follow */
  134318. Index *pFirst; /* First of real indices on the table */
  134319. memset(&sPk, 0, sizeof(Index));
  134320. sPk.nKeyCol = 1;
  134321. sPk.nColumn = 1;
  134322. sPk.aiColumn = &aiColumnPk;
  134323. sPk.aiRowLogEst = aiRowEstPk;
  134324. sPk.onError = OE_Replace;
  134325. sPk.pTable = pTab;
  134326. sPk.szIdxRow = pTab->szTabRow;
  134327. sPk.idxType = SQLITE_IDXTYPE_IPK;
  134328. aiRowEstPk[0] = pTab->nRowLogEst;
  134329. aiRowEstPk[1] = 0;
  134330. pFirst = pSrc->pTab->pIndex;
  134331. if( pSrc->fg.notIndexed==0 ){
  134332. /* The real indices of the table are only considered if the
  134333. ** NOT INDEXED qualifier is omitted from the FROM clause */
  134334. sPk.pNext = pFirst;
  134335. }
  134336. pProbe = &sPk;
  134337. }
  134338. rSize = pTab->nRowLogEst;
  134339. rLogSize = estLog(rSize);
  134340. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  134341. /* Automatic indexes */
  134342. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  134343. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  134344. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  134345. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  134346. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  134347. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  134348. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  134349. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  134350. ){
  134351. /* Generate auto-index WhereLoops */
  134352. WhereTerm *pTerm;
  134353. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  134354. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  134355. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  134356. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  134357. pNew->u.btree.nEq = 1;
  134358. pNew->nSkip = 0;
  134359. pNew->u.btree.pIndex = 0;
  134360. pNew->nLTerm = 1;
  134361. pNew->aLTerm[0] = pTerm;
  134362. /* TUNING: One-time cost for computing the automatic index is
  134363. ** estimated to be X*N*log2(N) where N is the number of rows in
  134364. ** the table being indexed and where X is 7 (LogEst=28) for normal
  134365. ** tables or 0.5 (LogEst=-10) for views and subqueries. The value
  134366. ** of X is smaller for views and subqueries so that the query planner
  134367. ** will be more aggressive about generating automatic indexes for
  134368. ** those objects, since there is no opportunity to add schema
  134369. ** indexes on subqueries and views. */
  134370. pNew->rSetup = rLogSize + rSize;
  134371. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  134372. pNew->rSetup += 28;
  134373. }else{
  134374. pNew->rSetup -= 10;
  134375. }
  134376. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  134377. if( pNew->rSetup<0 ) pNew->rSetup = 0;
  134378. /* TUNING: Each index lookup yields 20 rows in the table. This
  134379. ** is more than the usual guess of 10 rows, since we have no way
  134380. ** of knowing how selective the index will ultimately be. It would
  134381. ** not be unreasonable to make this value much larger. */
  134382. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  134383. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  134384. pNew->wsFlags = WHERE_AUTO_INDEX;
  134385. pNew->prereq = mPrereq | pTerm->prereqRight;
  134386. rc = whereLoopInsert(pBuilder, pNew);
  134387. }
  134388. }
  134389. }
  134390. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  134391. /* Loop over all indices. If there was an INDEXED BY clause, then only
  134392. ** consider index pProbe. */
  134393. for(; rc==SQLITE_OK && pProbe;
  134394. pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++
  134395. ){
  134396. if( pProbe->pPartIdxWhere!=0
  134397. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  134398. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  134399. continue; /* Partial index inappropriate for this query */
  134400. }
  134401. if( pProbe->bNoQuery ) continue;
  134402. rSize = pProbe->aiRowLogEst[0];
  134403. pNew->u.btree.nEq = 0;
  134404. pNew->u.btree.nBtm = 0;
  134405. pNew->u.btree.nTop = 0;
  134406. pNew->nSkip = 0;
  134407. pNew->nLTerm = 0;
  134408. pNew->iSortIdx = 0;
  134409. pNew->rSetup = 0;
  134410. pNew->prereq = mPrereq;
  134411. pNew->nOut = rSize;
  134412. pNew->u.btree.pIndex = pProbe;
  134413. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  134414. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  134415. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  134416. if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
  134417. /* Integer primary key index */
  134418. pNew->wsFlags = WHERE_IPK;
  134419. /* Full table scan */
  134420. pNew->iSortIdx = b ? iSortIdx : 0;
  134421. /* TUNING: Cost of full table scan is (N*3.0). */
  134422. pNew->rRun = rSize + 16;
  134423. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  134424. whereLoopOutputAdjust(pWC, pNew, rSize);
  134425. rc = whereLoopInsert(pBuilder, pNew);
  134426. pNew->nOut = rSize;
  134427. if( rc ) break;
  134428. }else{
  134429. Bitmask m;
  134430. if( pProbe->isCovering ){
  134431. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  134432. m = 0;
  134433. }else{
  134434. m = pSrc->colUsed & pProbe->colNotIdxed;
  134435. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  134436. }
  134437. /* Full scan via index */
  134438. if( b
  134439. || !HasRowid(pTab)
  134440. || pProbe->pPartIdxWhere!=0
  134441. || ( m==0
  134442. && pProbe->bUnordered==0
  134443. && (pProbe->szIdxRow<pTab->szTabRow)
  134444. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  134445. && sqlite3GlobalConfig.bUseCis
  134446. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  134447. )
  134448. ){
  134449. pNew->iSortIdx = b ? iSortIdx : 0;
  134450. /* The cost of visiting the index rows is N*K, where K is
  134451. ** between 1.1 and 3.0, depending on the relative sizes of the
  134452. ** index and table rows. */
  134453. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  134454. if( m!=0 ){
  134455. /* If this is a non-covering index scan, add in the cost of
  134456. ** doing table lookups. The cost will be 3x the number of
  134457. ** lookups. Take into account WHERE clause terms that can be
  134458. ** satisfied using just the index, and that do not require a
  134459. ** table lookup. */
  134460. LogEst nLookup = rSize + 16; /* Base cost: N*3 */
  134461. int ii;
  134462. int iCur = pSrc->iCursor;
  134463. WhereClause *pWC2 = &pWInfo->sWC;
  134464. for(ii=0; ii<pWC2->nTerm; ii++){
  134465. WhereTerm *pTerm = &pWC2->a[ii];
  134466. if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
  134467. break;
  134468. }
  134469. /* pTerm can be evaluated using just the index. So reduce
  134470. ** the expected number of table lookups accordingly */
  134471. if( pTerm->truthProb<=0 ){
  134472. nLookup += pTerm->truthProb;
  134473. }else{
  134474. nLookup--;
  134475. if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
  134476. }
  134477. }
  134478. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
  134479. }
  134480. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  134481. whereLoopOutputAdjust(pWC, pNew, rSize);
  134482. rc = whereLoopInsert(pBuilder, pNew);
  134483. pNew->nOut = rSize;
  134484. if( rc ) break;
  134485. }
  134486. }
  134487. pBuilder->bldFlags = 0;
  134488. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  134489. if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
  134490. /* If a non-unique index is used, or if a prefix of the key for
  134491. ** unique index is used (making the index functionally non-unique)
  134492. ** then the sqlite_stat1 data becomes important for scoring the
  134493. ** plan */
  134494. pTab->tabFlags |= TF_StatsUsed;
  134495. }
  134496. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  134497. sqlite3Stat4ProbeFree(pBuilder->pRec);
  134498. pBuilder->nRecValid = 0;
  134499. pBuilder->pRec = 0;
  134500. #endif
  134501. }
  134502. return rc;
  134503. }
  134504. #ifndef SQLITE_OMIT_VIRTUALTABLE
  134505. /*
  134506. ** Argument pIdxInfo is already populated with all constraints that may
  134507. ** be used by the virtual table identified by pBuilder->pNew->iTab. This
  134508. ** function marks a subset of those constraints usable, invokes the
  134509. ** xBestIndex method and adds the returned plan to pBuilder.
  134510. **
  134511. ** A constraint is marked usable if:
  134512. **
  134513. ** * Argument mUsable indicates that its prerequisites are available, and
  134514. **
  134515. ** * It is not one of the operators specified in the mExclude mask passed
  134516. ** as the fourth argument (which in practice is either WO_IN or 0).
  134517. **
  134518. ** Argument mPrereq is a mask of tables that must be scanned before the
  134519. ** virtual table in question. These are added to the plans prerequisites
  134520. ** before it is added to pBuilder.
  134521. **
  134522. ** Output parameter *pbIn is set to true if the plan added to pBuilder
  134523. ** uses one or more WO_IN terms, or false otherwise.
  134524. */
  134525. static int whereLoopAddVirtualOne(
  134526. WhereLoopBuilder *pBuilder,
  134527. Bitmask mPrereq, /* Mask of tables that must be used. */
  134528. Bitmask mUsable, /* Mask of usable tables */
  134529. u16 mExclude, /* Exclude terms using these operators */
  134530. sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
  134531. u16 mNoOmit, /* Do not omit these constraints */
  134532. int *pbIn /* OUT: True if plan uses an IN(...) op */
  134533. ){
  134534. WhereClause *pWC = pBuilder->pWC;
  134535. struct sqlite3_index_constraint *pIdxCons;
  134536. struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
  134537. int i;
  134538. int mxTerm;
  134539. int rc = SQLITE_OK;
  134540. WhereLoop *pNew = pBuilder->pNew;
  134541. Parse *pParse = pBuilder->pWInfo->pParse;
  134542. struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
  134543. int nConstraint = pIdxInfo->nConstraint;
  134544. assert( (mUsable & mPrereq)==mPrereq );
  134545. *pbIn = 0;
  134546. pNew->prereq = mPrereq;
  134547. /* Set the usable flag on the subset of constraints identified by
  134548. ** arguments mUsable and mExclude. */
  134549. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  134550. for(i=0; i<nConstraint; i++, pIdxCons++){
  134551. WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
  134552. pIdxCons->usable = 0;
  134553. if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
  134554. && (pTerm->eOperator & mExclude)==0
  134555. ){
  134556. pIdxCons->usable = 1;
  134557. }
  134558. }
  134559. /* Initialize the output fields of the sqlite3_index_info structure */
  134560. memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
  134561. assert( pIdxInfo->needToFreeIdxStr==0 );
  134562. pIdxInfo->idxStr = 0;
  134563. pIdxInfo->idxNum = 0;
  134564. pIdxInfo->orderByConsumed = 0;
  134565. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  134566. pIdxInfo->estimatedRows = 25;
  134567. pIdxInfo->idxFlags = 0;
  134568. pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
  134569. /* Invoke the virtual table xBestIndex() method */
  134570. rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
  134571. if( rc ){
  134572. if( rc==SQLITE_CONSTRAINT ){
  134573. /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
  134574. ** that the particular combination of parameters provided is unusable.
  134575. ** Make no entries in the loop table.
  134576. */
  134577. WHERETRACE(0xffff, (" ^^^^--- non-viable plan rejected!\n"));
  134578. return SQLITE_OK;
  134579. }
  134580. return rc;
  134581. }
  134582. mxTerm = -1;
  134583. assert( pNew->nLSlot>=nConstraint );
  134584. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  134585. pNew->u.vtab.omitMask = 0;
  134586. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  134587. for(i=0; i<nConstraint; i++, pIdxCons++){
  134588. int iTerm;
  134589. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  134590. WhereTerm *pTerm;
  134591. int j = pIdxCons->iTermOffset;
  134592. if( iTerm>=nConstraint
  134593. || j<0
  134594. || j>=pWC->nTerm
  134595. || pNew->aLTerm[iTerm]!=0
  134596. || pIdxCons->usable==0
  134597. ){
  134598. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  134599. testcase( pIdxInfo->needToFreeIdxStr );
  134600. return SQLITE_ERROR;
  134601. }
  134602. testcase( iTerm==nConstraint-1 );
  134603. testcase( j==0 );
  134604. testcase( j==pWC->nTerm-1 );
  134605. pTerm = &pWC->a[j];
  134606. pNew->prereq |= pTerm->prereqRight;
  134607. assert( iTerm<pNew->nLSlot );
  134608. pNew->aLTerm[iTerm] = pTerm;
  134609. if( iTerm>mxTerm ) mxTerm = iTerm;
  134610. testcase( iTerm==15 );
  134611. testcase( iTerm==16 );
  134612. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  134613. if( (pTerm->eOperator & WO_IN)!=0 ){
  134614. /* A virtual table that is constrained by an IN clause may not
  134615. ** consume the ORDER BY clause because (1) the order of IN terms
  134616. ** is not necessarily related to the order of output terms and
  134617. ** (2) Multiple outputs from a single IN value will not merge
  134618. ** together. */
  134619. pIdxInfo->orderByConsumed = 0;
  134620. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  134621. *pbIn = 1; assert( (mExclude & WO_IN)==0 );
  134622. }
  134623. }
  134624. }
  134625. pNew->u.vtab.omitMask &= ~mNoOmit;
  134626. pNew->nLTerm = mxTerm+1;
  134627. for(i=0; i<=mxTerm; i++){
  134628. if( pNew->aLTerm[i]==0 ){
  134629. /* The non-zero argvIdx values must be contiguous. Raise an
  134630. ** error if they are not */
  134631. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  134632. testcase( pIdxInfo->needToFreeIdxStr );
  134633. return SQLITE_ERROR;
  134634. }
  134635. }
  134636. assert( pNew->nLTerm<=pNew->nLSlot );
  134637. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  134638. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  134639. pIdxInfo->needToFreeIdxStr = 0;
  134640. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  134641. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  134642. pIdxInfo->nOrderBy : 0);
  134643. pNew->rSetup = 0;
  134644. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  134645. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  134646. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  134647. ** that the scan will visit at most one row. Clear it otherwise. */
  134648. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  134649. pNew->wsFlags |= WHERE_ONEROW;
  134650. }else{
  134651. pNew->wsFlags &= ~WHERE_ONEROW;
  134652. }
  134653. rc = whereLoopInsert(pBuilder, pNew);
  134654. if( pNew->u.vtab.needFree ){
  134655. sqlite3_free(pNew->u.vtab.idxStr);
  134656. pNew->u.vtab.needFree = 0;
  134657. }
  134658. WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
  134659. *pbIn, (sqlite3_uint64)mPrereq,
  134660. (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
  134661. return rc;
  134662. }
  134663. /*
  134664. ** If this function is invoked from within an xBestIndex() callback, it
  134665. ** returns a pointer to a buffer containing the name of the collation
  134666. ** sequence associated with element iCons of the sqlite3_index_info.aConstraint
  134667. ** array. Or, if iCons is out of range or there is no active xBestIndex
  134668. ** call, return NULL.
  134669. */
  134670. SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
  134671. HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  134672. const char *zRet = 0;
  134673. if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
  134674. CollSeq *pC = 0;
  134675. int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
  134676. Expr *pX = pHidden->pWC->a[iTerm].pExpr;
  134677. if( pX->pLeft ){
  134678. pC = sqlite3BinaryCompareCollSeq(pHidden->pParse, pX->pLeft, pX->pRight);
  134679. }
  134680. zRet = (pC ? pC->zName : sqlite3StrBINARY);
  134681. }
  134682. return zRet;
  134683. }
  134684. /*
  134685. ** Add all WhereLoop objects for a table of the join identified by
  134686. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  134687. **
  134688. ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
  134689. ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
  134690. ** entries that occur before the virtual table in the FROM clause and are
  134691. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  134692. ** mUnusable mask contains all FROM clause entries that occur after the
  134693. ** virtual table and are separated from it by at least one LEFT or
  134694. ** CROSS JOIN.
  134695. **
  134696. ** For example, if the query were:
  134697. **
  134698. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  134699. **
  134700. ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
  134701. **
  134702. ** All the tables in mPrereq must be scanned before the current virtual
  134703. ** table. So any terms for which all prerequisites are satisfied by
  134704. ** mPrereq may be specified as "usable" in all calls to xBestIndex.
  134705. ** Conversely, all tables in mUnusable must be scanned after the current
  134706. ** virtual table, so any terms for which the prerequisites overlap with
  134707. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  134708. */
  134709. static int whereLoopAddVirtual(
  134710. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  134711. Bitmask mPrereq, /* Tables that must be scanned before this one */
  134712. Bitmask mUnusable /* Tables that must be scanned after this one */
  134713. ){
  134714. int rc = SQLITE_OK; /* Return code */
  134715. WhereInfo *pWInfo; /* WHERE analysis context */
  134716. Parse *pParse; /* The parsing context */
  134717. WhereClause *pWC; /* The WHERE clause */
  134718. struct SrcList_item *pSrc; /* The FROM clause term to search */
  134719. sqlite3_index_info *p; /* Object to pass to xBestIndex() */
  134720. int nConstraint; /* Number of constraints in p */
  134721. int bIn; /* True if plan uses IN(...) operator */
  134722. WhereLoop *pNew;
  134723. Bitmask mBest; /* Tables used by best possible plan */
  134724. u16 mNoOmit;
  134725. assert( (mPrereq & mUnusable)==0 );
  134726. pWInfo = pBuilder->pWInfo;
  134727. pParse = pWInfo->pParse;
  134728. pWC = pBuilder->pWC;
  134729. pNew = pBuilder->pNew;
  134730. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  134731. assert( IsVirtual(pSrc->pTab) );
  134732. p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
  134733. &mNoOmit);
  134734. if( p==0 ) return SQLITE_NOMEM_BKPT;
  134735. pNew->rSetup = 0;
  134736. pNew->wsFlags = WHERE_VIRTUALTABLE;
  134737. pNew->nLTerm = 0;
  134738. pNew->u.vtab.needFree = 0;
  134739. nConstraint = p->nConstraint;
  134740. if( whereLoopResize(pParse->db, pNew, nConstraint) ){
  134741. sqlite3DbFree(pParse->db, p);
  134742. return SQLITE_NOMEM_BKPT;
  134743. }
  134744. /* First call xBestIndex() with all constraints usable. */
  134745. WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
  134746. WHERETRACE(0x40, (" VirtualOne: all usable\n"));
  134747. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
  134748. /* If the call to xBestIndex() with all terms enabled produced a plan
  134749. ** that does not require any source tables (IOW: a plan with mBest==0)
  134750. ** and does not use an IN(...) operator, then there is no point in making
  134751. ** any further calls to xBestIndex() since they will all return the same
  134752. ** result (if the xBestIndex() implementation is sane). */
  134753. if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
  134754. int seenZero = 0; /* True if a plan with no prereqs seen */
  134755. int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
  134756. Bitmask mPrev = 0;
  134757. Bitmask mBestNoIn = 0;
  134758. /* If the plan produced by the earlier call uses an IN(...) term, call
  134759. ** xBestIndex again, this time with IN(...) terms disabled. */
  134760. if( bIn ){
  134761. WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
  134762. rc = whereLoopAddVirtualOne(
  134763. pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
  134764. assert( bIn==0 );
  134765. mBestNoIn = pNew->prereq & ~mPrereq;
  134766. if( mBestNoIn==0 ){
  134767. seenZero = 1;
  134768. seenZeroNoIN = 1;
  134769. }
  134770. }
  134771. /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
  134772. ** in the set of terms that apply to the current virtual table. */
  134773. while( rc==SQLITE_OK ){
  134774. int i;
  134775. Bitmask mNext = ALLBITS;
  134776. assert( mNext>0 );
  134777. for(i=0; i<nConstraint; i++){
  134778. Bitmask mThis = (
  134779. pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
  134780. );
  134781. if( mThis>mPrev && mThis<mNext ) mNext = mThis;
  134782. }
  134783. mPrev = mNext;
  134784. if( mNext==ALLBITS ) break;
  134785. if( mNext==mBest || mNext==mBestNoIn ) continue;
  134786. WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
  134787. (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
  134788. rc = whereLoopAddVirtualOne(
  134789. pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
  134790. if( pNew->prereq==mPrereq ){
  134791. seenZero = 1;
  134792. if( bIn==0 ) seenZeroNoIN = 1;
  134793. }
  134794. }
  134795. /* If the calls to xBestIndex() in the above loop did not find a plan
  134796. ** that requires no source tables at all (i.e. one guaranteed to be
  134797. ** usable), make a call here with all source tables disabled */
  134798. if( rc==SQLITE_OK && seenZero==0 ){
  134799. WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
  134800. rc = whereLoopAddVirtualOne(
  134801. pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
  134802. if( bIn==0 ) seenZeroNoIN = 1;
  134803. }
  134804. /* If the calls to xBestIndex() have so far failed to find a plan
  134805. ** that requires no source tables at all and does not use an IN(...)
  134806. ** operator, make a final call to obtain one here. */
  134807. if( rc==SQLITE_OK && seenZeroNoIN==0 ){
  134808. WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
  134809. rc = whereLoopAddVirtualOne(
  134810. pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
  134811. }
  134812. }
  134813. if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
  134814. sqlite3DbFreeNN(pParse->db, p);
  134815. WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
  134816. return rc;
  134817. }
  134818. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  134819. /*
  134820. ** Add WhereLoop entries to handle OR terms. This works for either
  134821. ** btrees or virtual tables.
  134822. */
  134823. static int whereLoopAddOr(
  134824. WhereLoopBuilder *pBuilder,
  134825. Bitmask mPrereq,
  134826. Bitmask mUnusable
  134827. ){
  134828. WhereInfo *pWInfo = pBuilder->pWInfo;
  134829. WhereClause *pWC;
  134830. WhereLoop *pNew;
  134831. WhereTerm *pTerm, *pWCEnd;
  134832. int rc = SQLITE_OK;
  134833. int iCur;
  134834. WhereClause tempWC;
  134835. WhereLoopBuilder sSubBuild;
  134836. WhereOrSet sSum, sCur;
  134837. struct SrcList_item *pItem;
  134838. pWC = pBuilder->pWC;
  134839. pWCEnd = pWC->a + pWC->nTerm;
  134840. pNew = pBuilder->pNew;
  134841. memset(&sSum, 0, sizeof(sSum));
  134842. pItem = pWInfo->pTabList->a + pNew->iTab;
  134843. iCur = pItem->iCursor;
  134844. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  134845. if( (pTerm->eOperator & WO_OR)!=0
  134846. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  134847. ){
  134848. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  134849. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  134850. WhereTerm *pOrTerm;
  134851. int once = 1;
  134852. int i, j;
  134853. sSubBuild = *pBuilder;
  134854. sSubBuild.pOrderBy = 0;
  134855. sSubBuild.pOrSet = &sCur;
  134856. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  134857. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  134858. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  134859. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  134860. }else if( pOrTerm->leftCursor==iCur ){
  134861. tempWC.pWInfo = pWC->pWInfo;
  134862. tempWC.pOuter = pWC;
  134863. tempWC.op = TK_AND;
  134864. tempWC.nTerm = 1;
  134865. tempWC.a = pOrTerm;
  134866. sSubBuild.pWC = &tempWC;
  134867. }else{
  134868. continue;
  134869. }
  134870. sCur.n = 0;
  134871. #ifdef WHERETRACE_ENABLED
  134872. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  134873. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  134874. if( sqlite3WhereTrace & 0x400 ){
  134875. sqlite3WhereClausePrint(sSubBuild.pWC);
  134876. }
  134877. #endif
  134878. #ifndef SQLITE_OMIT_VIRTUALTABLE
  134879. if( IsVirtual(pItem->pTab) ){
  134880. rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
  134881. }else
  134882. #endif
  134883. {
  134884. rc = whereLoopAddBtree(&sSubBuild, mPrereq);
  134885. }
  134886. if( rc==SQLITE_OK ){
  134887. rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
  134888. }
  134889. assert( rc==SQLITE_OK || sCur.n==0 );
  134890. if( sCur.n==0 ){
  134891. sSum.n = 0;
  134892. break;
  134893. }else if( once ){
  134894. whereOrMove(&sSum, &sCur);
  134895. once = 0;
  134896. }else{
  134897. WhereOrSet sPrev;
  134898. whereOrMove(&sPrev, &sSum);
  134899. sSum.n = 0;
  134900. for(i=0; i<sPrev.n; i++){
  134901. for(j=0; j<sCur.n; j++){
  134902. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  134903. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  134904. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  134905. }
  134906. }
  134907. }
  134908. }
  134909. pNew->nLTerm = 1;
  134910. pNew->aLTerm[0] = pTerm;
  134911. pNew->wsFlags = WHERE_MULTI_OR;
  134912. pNew->rSetup = 0;
  134913. pNew->iSortIdx = 0;
  134914. memset(&pNew->u, 0, sizeof(pNew->u));
  134915. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  134916. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  134917. ** of all sub-scans required by the OR-scan. However, due to rounding
  134918. ** errors, it may be that the cost of the OR-scan is equal to its
  134919. ** most expensive sub-scan. Add the smallest possible penalty
  134920. ** (equivalent to multiplying the cost by 1.07) to ensure that
  134921. ** this does not happen. Otherwise, for WHERE clauses such as the
  134922. ** following where there is an index on "y":
  134923. **
  134924. ** WHERE likelihood(x=?, 0.99) OR y=?
  134925. **
  134926. ** the planner may elect to "OR" together a full-table scan and an
  134927. ** index lookup. And other similarly odd results. */
  134928. pNew->rRun = sSum.a[i].rRun + 1;
  134929. pNew->nOut = sSum.a[i].nOut;
  134930. pNew->prereq = sSum.a[i].prereq;
  134931. rc = whereLoopInsert(pBuilder, pNew);
  134932. }
  134933. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  134934. }
  134935. }
  134936. return rc;
  134937. }
  134938. /*
  134939. ** Add all WhereLoop objects for all tables
  134940. */
  134941. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  134942. WhereInfo *pWInfo = pBuilder->pWInfo;
  134943. Bitmask mPrereq = 0;
  134944. Bitmask mPrior = 0;
  134945. int iTab;
  134946. SrcList *pTabList = pWInfo->pTabList;
  134947. struct SrcList_item *pItem;
  134948. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  134949. sqlite3 *db = pWInfo->pParse->db;
  134950. int rc = SQLITE_OK;
  134951. WhereLoop *pNew;
  134952. u8 priorJointype = 0;
  134953. /* Loop over the tables in the join, from left to right */
  134954. pNew = pBuilder->pNew;
  134955. whereLoopInit(pNew);
  134956. pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
  134957. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  134958. Bitmask mUnusable = 0;
  134959. pNew->iTab = iTab;
  134960. pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
  134961. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  134962. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  134963. /* This condition is true when pItem is the FROM clause term on the
  134964. ** right-hand-side of a LEFT or CROSS JOIN. */
  134965. mPrereq = mPrior;
  134966. }
  134967. priorJointype = pItem->fg.jointype;
  134968. #ifndef SQLITE_OMIT_VIRTUALTABLE
  134969. if( IsVirtual(pItem->pTab) ){
  134970. struct SrcList_item *p;
  134971. for(p=&pItem[1]; p<pEnd; p++){
  134972. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  134973. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  134974. }
  134975. }
  134976. rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
  134977. }else
  134978. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  134979. {
  134980. rc = whereLoopAddBtree(pBuilder, mPrereq);
  134981. }
  134982. if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
  134983. rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
  134984. }
  134985. mPrior |= pNew->maskSelf;
  134986. if( rc || db->mallocFailed ){
  134987. if( rc==SQLITE_DONE ){
  134988. /* We hit the query planner search limit set by iPlanLimit */
  134989. sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
  134990. rc = SQLITE_OK;
  134991. }else{
  134992. break;
  134993. }
  134994. }
  134995. }
  134996. whereLoopClear(db, pNew);
  134997. return rc;
  134998. }
  134999. /*
  135000. ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
  135001. ** parameters) to see if it outputs rows in the requested ORDER BY
  135002. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  135003. **
  135004. ** N>0: N terms of the ORDER BY clause are satisfied
  135005. ** N==0: No terms of the ORDER BY clause are satisfied
  135006. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  135007. **
  135008. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  135009. ** strict. With GROUP BY and DISTINCT the only requirement is that
  135010. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  135011. ** and DISTINCT do not require rows to appear in any particular order as long
  135012. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  135013. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  135014. ** pOrderBy terms must be matched in strict left-to-right order.
  135015. */
  135016. static i8 wherePathSatisfiesOrderBy(
  135017. WhereInfo *pWInfo, /* The WHERE clause */
  135018. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  135019. WherePath *pPath, /* The WherePath to check */
  135020. u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
  135021. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  135022. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  135023. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  135024. ){
  135025. u8 revSet; /* True if rev is known */
  135026. u8 rev; /* Composite sort order */
  135027. u8 revIdx; /* Index sort order */
  135028. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  135029. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  135030. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  135031. u16 eqOpMask; /* Allowed equality operators */
  135032. u16 nKeyCol; /* Number of key columns in pIndex */
  135033. u16 nColumn; /* Total number of ordered columns in the index */
  135034. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  135035. int iLoop; /* Index of WhereLoop in pPath being processed */
  135036. int i, j; /* Loop counters */
  135037. int iCur; /* Cursor number for current WhereLoop */
  135038. int iColumn; /* A column number within table iCur */
  135039. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  135040. WhereTerm *pTerm; /* A single term of the WHERE clause */
  135041. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  135042. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  135043. Index *pIndex; /* The index associated with pLoop */
  135044. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  135045. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  135046. Bitmask obDone; /* Mask of all ORDER BY terms */
  135047. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  135048. Bitmask ready; /* Mask of inner loops */
  135049. /*
  135050. ** We say the WhereLoop is "one-row" if it generates no more than one
  135051. ** row of output. A WhereLoop is one-row if all of the following are true:
  135052. ** (a) All index columns match with WHERE_COLUMN_EQ.
  135053. ** (b) The index is unique
  135054. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  135055. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  135056. **
  135057. ** We say the WhereLoop is "order-distinct" if the set of columns from
  135058. ** that WhereLoop that are in the ORDER BY clause are different for every
  135059. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  135060. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  135061. ** is not order-distinct. To be order-distinct is not quite the same as being
  135062. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  135063. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  135064. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  135065. **
  135066. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  135067. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  135068. ** automatically order-distinct.
  135069. */
  135070. assert( pOrderBy!=0 );
  135071. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  135072. nOrderBy = pOrderBy->nExpr;
  135073. testcase( nOrderBy==BMS-1 );
  135074. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  135075. isOrderDistinct = 1;
  135076. obDone = MASKBIT(nOrderBy)-1;
  135077. orderDistinctMask = 0;
  135078. ready = 0;
  135079. eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
  135080. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
  135081. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  135082. if( iLoop>0 ) ready |= pLoop->maskSelf;
  135083. if( iLoop<nLoop ){
  135084. pLoop = pPath->aLoop[iLoop];
  135085. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
  135086. }else{
  135087. pLoop = pLast;
  135088. }
  135089. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  135090. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  135091. break;
  135092. }else{
  135093. pLoop->u.btree.nIdxCol = 0;
  135094. }
  135095. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  135096. /* Mark off any ORDER BY term X that is a column in the table of
  135097. ** the current loop for which there is term in the WHERE
  135098. ** clause of the form X IS NULL or X=? that reference only outer
  135099. ** loops.
  135100. */
  135101. for(i=0; i<nOrderBy; i++){
  135102. if( MASKBIT(i) & obSat ) continue;
  135103. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  135104. if( pOBExpr->op!=TK_COLUMN ) continue;
  135105. if( pOBExpr->iTable!=iCur ) continue;
  135106. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  135107. ~ready, eqOpMask, 0);
  135108. if( pTerm==0 ) continue;
  135109. if( pTerm->eOperator==WO_IN ){
  135110. /* IN terms are only valid for sorting in the ORDER BY LIMIT
  135111. ** optimization, and then only if they are actually used
  135112. ** by the query plan */
  135113. assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
  135114. for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
  135115. if( j>=pLoop->nLTerm ) continue;
  135116. }
  135117. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  135118. if( sqlite3ExprCollSeqMatch(pWInfo->pParse,
  135119. pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){
  135120. continue;
  135121. }
  135122. testcase( pTerm->pExpr->op==TK_IS );
  135123. }
  135124. obSat |= MASKBIT(i);
  135125. }
  135126. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  135127. if( pLoop->wsFlags & WHERE_IPK ){
  135128. pIndex = 0;
  135129. nKeyCol = 0;
  135130. nColumn = 1;
  135131. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  135132. return 0;
  135133. }else{
  135134. nKeyCol = pIndex->nKeyCol;
  135135. nColumn = pIndex->nColumn;
  135136. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  135137. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  135138. || !HasRowid(pIndex->pTable));
  135139. isOrderDistinct = IsUniqueIndex(pIndex);
  135140. }
  135141. /* Loop through all columns of the index and deal with the ones
  135142. ** that are not constrained by == or IN.
  135143. */
  135144. rev = revSet = 0;
  135145. distinctColumns = 0;
  135146. for(j=0; j<nColumn; j++){
  135147. u8 bOnce = 1; /* True to run the ORDER BY search loop */
  135148. assert( j>=pLoop->u.btree.nEq
  135149. || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
  135150. );
  135151. if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
  135152. u16 eOp = pLoop->aLTerm[j]->eOperator;
  135153. /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
  135154. ** doing WHERE_ORDERBY_LIMIT processing).
  135155. **
  135156. ** If the current term is a column of an ((?,?) IN (SELECT...))
  135157. ** expression for which the SELECT returns more than one column,
  135158. ** check that it is the only column used by this loop. Otherwise,
  135159. ** if it is one of two or more, none of the columns can be
  135160. ** considered to match an ORDER BY term. */
  135161. if( (eOp & eqOpMask)!=0 ){
  135162. if( eOp & WO_ISNULL ){
  135163. testcase( isOrderDistinct );
  135164. isOrderDistinct = 0;
  135165. }
  135166. continue;
  135167. }else if( ALWAYS(eOp & WO_IN) ){
  135168. /* ALWAYS() justification: eOp is an equality operator due to the
  135169. ** j<pLoop->u.btree.nEq constraint above. Any equality other
  135170. ** than WO_IN is captured by the previous "if". So this one
  135171. ** always has to be WO_IN. */
  135172. Expr *pX = pLoop->aLTerm[j]->pExpr;
  135173. for(i=j+1; i<pLoop->u.btree.nEq; i++){
  135174. if( pLoop->aLTerm[i]->pExpr==pX ){
  135175. assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
  135176. bOnce = 0;
  135177. break;
  135178. }
  135179. }
  135180. }
  135181. }
  135182. /* Get the column number in the table (iColumn) and sort order
  135183. ** (revIdx) for the j-th column of the index.
  135184. */
  135185. if( pIndex ){
  135186. iColumn = pIndex->aiColumn[j];
  135187. revIdx = pIndex->aSortOrder[j];
  135188. if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
  135189. }else{
  135190. iColumn = XN_ROWID;
  135191. revIdx = 0;
  135192. }
  135193. /* An unconstrained column that might be NULL means that this
  135194. ** WhereLoop is not well-ordered
  135195. */
  135196. if( isOrderDistinct
  135197. && iColumn>=0
  135198. && j>=pLoop->u.btree.nEq
  135199. && pIndex->pTable->aCol[iColumn].notNull==0
  135200. ){
  135201. isOrderDistinct = 0;
  135202. }
  135203. /* Find the ORDER BY term that corresponds to the j-th column
  135204. ** of the index and mark that ORDER BY term off
  135205. */
  135206. isMatch = 0;
  135207. for(i=0; bOnce && i<nOrderBy; i++){
  135208. if( MASKBIT(i) & obSat ) continue;
  135209. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  135210. testcase( wctrlFlags & WHERE_GROUPBY );
  135211. testcase( wctrlFlags & WHERE_DISTINCTBY );
  135212. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  135213. if( iColumn>=XN_ROWID ){
  135214. if( pOBExpr->op!=TK_COLUMN ) continue;
  135215. if( pOBExpr->iTable!=iCur ) continue;
  135216. if( pOBExpr->iColumn!=iColumn ) continue;
  135217. }else{
  135218. Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
  135219. if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
  135220. continue;
  135221. }
  135222. }
  135223. if( iColumn!=XN_ROWID ){
  135224. pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  135225. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  135226. }
  135227. pLoop->u.btree.nIdxCol = j+1;
  135228. isMatch = 1;
  135229. break;
  135230. }
  135231. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  135232. /* Make sure the sort order is compatible in an ORDER BY clause.
  135233. ** Sort order is irrelevant for a GROUP BY clause. */
  135234. if( revSet ){
  135235. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  135236. }else{
  135237. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  135238. if( rev ) *pRevMask |= MASKBIT(iLoop);
  135239. revSet = 1;
  135240. }
  135241. }
  135242. if( isMatch ){
  135243. if( iColumn==XN_ROWID ){
  135244. testcase( distinctColumns==0 );
  135245. distinctColumns = 1;
  135246. }
  135247. obSat |= MASKBIT(i);
  135248. }else{
  135249. /* No match found */
  135250. if( j==0 || j<nKeyCol ){
  135251. testcase( isOrderDistinct!=0 );
  135252. isOrderDistinct = 0;
  135253. }
  135254. break;
  135255. }
  135256. } /* end Loop over all index columns */
  135257. if( distinctColumns ){
  135258. testcase( isOrderDistinct==0 );
  135259. isOrderDistinct = 1;
  135260. }
  135261. } /* end-if not one-row */
  135262. /* Mark off any other ORDER BY terms that reference pLoop */
  135263. if( isOrderDistinct ){
  135264. orderDistinctMask |= pLoop->maskSelf;
  135265. for(i=0; i<nOrderBy; i++){
  135266. Expr *p;
  135267. Bitmask mTerm;
  135268. if( MASKBIT(i) & obSat ) continue;
  135269. p = pOrderBy->a[i].pExpr;
  135270. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  135271. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  135272. if( (mTerm&~orderDistinctMask)==0 ){
  135273. obSat |= MASKBIT(i);
  135274. }
  135275. }
  135276. }
  135277. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  135278. if( obSat==obDone ) return (i8)nOrderBy;
  135279. if( !isOrderDistinct ){
  135280. for(i=nOrderBy-1; i>0; i--){
  135281. Bitmask m = MASKBIT(i) - 1;
  135282. if( (obSat&m)==m ) return i;
  135283. }
  135284. return 0;
  135285. }
  135286. return -1;
  135287. }
  135288. /*
  135289. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  135290. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  135291. ** BY clause - and so any order that groups rows as required satisfies the
  135292. ** request.
  135293. **
  135294. ** Normally, in this case it is not possible for the caller to determine
  135295. ** whether or not the rows are really being delivered in sorted order, or
  135296. ** just in some other order that provides the required grouping. However,
  135297. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  135298. ** this function may be called on the returned WhereInfo object. It returns
  135299. ** true if the rows really will be sorted in the specified order, or false
  135300. ** otherwise.
  135301. **
  135302. ** For example, assuming:
  135303. **
  135304. ** CREATE INDEX i1 ON t1(x, Y);
  135305. **
  135306. ** then
  135307. **
  135308. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  135309. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  135310. */
  135311. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  135312. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  135313. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  135314. return pWInfo->sorted;
  135315. }
  135316. #ifdef WHERETRACE_ENABLED
  135317. /* For debugging use only: */
  135318. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  135319. static char zName[65];
  135320. int i;
  135321. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  135322. if( pLast ) zName[i++] = pLast->cId;
  135323. zName[i] = 0;
  135324. return zName;
  135325. }
  135326. #endif
  135327. /*
  135328. ** Return the cost of sorting nRow rows, assuming that the keys have
  135329. ** nOrderby columns and that the first nSorted columns are already in
  135330. ** order.
  135331. */
  135332. static LogEst whereSortingCost(
  135333. WhereInfo *pWInfo,
  135334. LogEst nRow,
  135335. int nOrderBy,
  135336. int nSorted
  135337. ){
  135338. /* TUNING: Estimated cost of a full external sort, where N is
  135339. ** the number of rows to sort is:
  135340. **
  135341. ** cost = (3.0 * N * log(N)).
  135342. **
  135343. ** Or, if the order-by clause has X terms but only the last Y
  135344. ** terms are out of order, then block-sorting will reduce the
  135345. ** sorting cost to:
  135346. **
  135347. ** cost = (3.0 * N * log(N)) * (Y/X)
  135348. **
  135349. ** The (Y/X) term is implemented using stack variable rScale
  135350. ** below. */
  135351. LogEst rScale, rSortCost;
  135352. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  135353. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  135354. rSortCost = nRow + rScale + 16;
  135355. /* Multiple by log(M) where M is the number of output rows.
  135356. ** Use the LIMIT for M if it is smaller */
  135357. if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
  135358. nRow = pWInfo->iLimit;
  135359. }
  135360. rSortCost += estLog(nRow);
  135361. return rSortCost;
  135362. }
  135363. /*
  135364. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  135365. ** attempts to find the lowest cost path that visits each WhereLoop
  135366. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  135367. **
  135368. ** Assume that the total number of output rows that will need to be sorted
  135369. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  135370. ** costs if nRowEst==0.
  135371. **
  135372. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  135373. ** error occurs.
  135374. */
  135375. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  135376. int mxChoice; /* Maximum number of simultaneous paths tracked */
  135377. int nLoop; /* Number of terms in the join */
  135378. Parse *pParse; /* Parsing context */
  135379. sqlite3 *db; /* The database connection */
  135380. int iLoop; /* Loop counter over the terms of the join */
  135381. int ii, jj; /* Loop counters */
  135382. int mxI = 0; /* Index of next entry to replace */
  135383. int nOrderBy; /* Number of ORDER BY clause terms */
  135384. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  135385. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  135386. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  135387. WherePath *aFrom; /* All nFrom paths at the previous level */
  135388. WherePath *aTo; /* The nTo best paths at the current level */
  135389. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  135390. WherePath *pTo; /* An element of aTo[] that we are working on */
  135391. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  135392. WhereLoop **pX; /* Used to divy up the pSpace memory */
  135393. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  135394. char *pSpace; /* Temporary memory used by this routine */
  135395. int nSpace; /* Bytes of space allocated at pSpace */
  135396. pParse = pWInfo->pParse;
  135397. db = pParse->db;
  135398. nLoop = pWInfo->nLevel;
  135399. /* TUNING: For simple queries, only the best path is tracked.
  135400. ** For 2-way joins, the 5 best paths are followed.
  135401. ** For joins of 3 or more tables, track the 10 best paths */
  135402. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  135403. assert( nLoop<=pWInfo->pTabList->nSrc );
  135404. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  135405. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  135406. ** case the purpose of this call is to estimate the number of rows returned
  135407. ** by the overall query. Once this estimate has been obtained, the caller
  135408. ** will invoke this function a second time, passing the estimate as the
  135409. ** nRowEst parameter. */
  135410. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  135411. nOrderBy = 0;
  135412. }else{
  135413. nOrderBy = pWInfo->pOrderBy->nExpr;
  135414. }
  135415. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  135416. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  135417. nSpace += sizeof(LogEst) * nOrderBy;
  135418. pSpace = sqlite3DbMallocRawNN(db, nSpace);
  135419. if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
  135420. aTo = (WherePath*)pSpace;
  135421. aFrom = aTo+mxChoice;
  135422. memset(aFrom, 0, sizeof(aFrom[0]));
  135423. pX = (WhereLoop**)(aFrom+mxChoice);
  135424. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  135425. pFrom->aLoop = pX;
  135426. }
  135427. if( nOrderBy ){
  135428. /* If there is an ORDER BY clause and it is not being ignored, set up
  135429. ** space for the aSortCost[] array. Each element of the aSortCost array
  135430. ** is either zero - meaning it has not yet been initialized - or the
  135431. ** cost of sorting nRowEst rows of data where the first X terms of
  135432. ** the ORDER BY clause are already in order, where X is the array
  135433. ** index. */
  135434. aSortCost = (LogEst*)pX;
  135435. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  135436. }
  135437. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  135438. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  135439. /* Seed the search with a single WherePath containing zero WhereLoops.
  135440. **
  135441. ** TUNING: Do not let the number of iterations go above 28. If the cost
  135442. ** of computing an automatic index is not paid back within the first 28
  135443. ** rows, then do not use the automatic index. */
  135444. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  135445. nFrom = 1;
  135446. assert( aFrom[0].isOrdered==0 );
  135447. if( nOrderBy ){
  135448. /* If nLoop is zero, then there are no FROM terms in the query. Since
  135449. ** in this case the query may return a maximum of one row, the results
  135450. ** are already in the requested order. Set isOrdered to nOrderBy to
  135451. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  135452. ** -1, indicating that the result set may or may not be ordered,
  135453. ** depending on the loops added to the current plan. */
  135454. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  135455. }
  135456. /* Compute successively longer WherePaths using the previous generation
  135457. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  135458. ** best paths at each generation */
  135459. for(iLoop=0; iLoop<nLoop; iLoop++){
  135460. nTo = 0;
  135461. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  135462. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  135463. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  135464. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  135465. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  135466. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  135467. Bitmask maskNew; /* Mask of src visited by (..) */
  135468. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  135469. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  135470. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  135471. if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
  135472. /* Do not use an automatic index if the this loop is expected
  135473. ** to run less than 1.25 times. It is tempting to also exclude
  135474. ** automatic index usage on an outer loop, but sometimes an automatic
  135475. ** index is useful in the outer loop of a correlated subquery. */
  135476. assert( 10==sqlite3LogEst(2) );
  135477. continue;
  135478. }
  135479. /* At this point, pWLoop is a candidate to be the next loop.
  135480. ** Compute its cost */
  135481. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  135482. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  135483. nOut = pFrom->nRow + pWLoop->nOut;
  135484. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  135485. if( isOrdered<0 ){
  135486. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  135487. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  135488. iLoop, pWLoop, &revMask);
  135489. }else{
  135490. revMask = pFrom->revLoop;
  135491. }
  135492. if( isOrdered>=0 && isOrdered<nOrderBy ){
  135493. if( aSortCost[isOrdered]==0 ){
  135494. aSortCost[isOrdered] = whereSortingCost(
  135495. pWInfo, nRowEst, nOrderBy, isOrdered
  135496. );
  135497. }
  135498. /* TUNING: Add a small extra penalty (5) to sorting as an
  135499. ** extra encouragment to the query planner to select a plan
  135500. ** where the rows emerge in the correct order without any sorting
  135501. ** required. */
  135502. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 5;
  135503. WHERETRACE(0x002,
  135504. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  135505. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  135506. rUnsorted, rCost));
  135507. }else{
  135508. rCost = rUnsorted;
  135509. rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
  135510. }
  135511. /* Check to see if pWLoop should be added to the set of
  135512. ** mxChoice best-so-far paths.
  135513. **
  135514. ** First look for an existing path among best-so-far paths
  135515. ** that covers the same set of loops and has the same isOrdered
  135516. ** setting as the current path candidate.
  135517. **
  135518. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  135519. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  135520. ** of legal values for isOrdered, -1..64.
  135521. */
  135522. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  135523. if( pTo->maskLoop==maskNew
  135524. && ((pTo->isOrdered^isOrdered)&0x80)==0
  135525. ){
  135526. testcase( jj==nTo-1 );
  135527. break;
  135528. }
  135529. }
  135530. if( jj>=nTo ){
  135531. /* None of the existing best-so-far paths match the candidate. */
  135532. if( nTo>=mxChoice
  135533. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  135534. ){
  135535. /* The current candidate is no better than any of the mxChoice
  135536. ** paths currently in the best-so-far buffer. So discard
  135537. ** this candidate as not viable. */
  135538. #ifdef WHERETRACE_ENABLED /* 0x4 */
  135539. if( sqlite3WhereTrace&0x4 ){
  135540. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
  135541. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  135542. isOrdered>=0 ? isOrdered+'0' : '?');
  135543. }
  135544. #endif
  135545. continue;
  135546. }
  135547. /* If we reach this points it means that the new candidate path
  135548. ** needs to be added to the set of best-so-far paths. */
  135549. if( nTo<mxChoice ){
  135550. /* Increase the size of the aTo set by one */
  135551. jj = nTo++;
  135552. }else{
  135553. /* New path replaces the prior worst to keep count below mxChoice */
  135554. jj = mxI;
  135555. }
  135556. pTo = &aTo[jj];
  135557. #ifdef WHERETRACE_ENABLED /* 0x4 */
  135558. if( sqlite3WhereTrace&0x4 ){
  135559. sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
  135560. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  135561. isOrdered>=0 ? isOrdered+'0' : '?');
  135562. }
  135563. #endif
  135564. }else{
  135565. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  135566. ** same set of loops and has the same isOrdered setting as the
  135567. ** candidate path. Check to see if the candidate should replace
  135568. ** pTo or if the candidate should be skipped.
  135569. **
  135570. ** The conditional is an expanded vector comparison equivalent to:
  135571. ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
  135572. */
  135573. if( pTo->rCost<rCost
  135574. || (pTo->rCost==rCost
  135575. && (pTo->nRow<nOut
  135576. || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
  135577. )
  135578. )
  135579. ){
  135580. #ifdef WHERETRACE_ENABLED /* 0x4 */
  135581. if( sqlite3WhereTrace&0x4 ){
  135582. sqlite3DebugPrintf(
  135583. "Skip %s cost=%-3d,%3d,%3d order=%c",
  135584. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  135585. isOrdered>=0 ? isOrdered+'0' : '?');
  135586. sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
  135587. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  135588. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  135589. }
  135590. #endif
  135591. /* Discard the candidate path from further consideration */
  135592. testcase( pTo->rCost==rCost );
  135593. continue;
  135594. }
  135595. testcase( pTo->rCost==rCost+1 );
  135596. /* Control reaches here if the candidate path is better than the
  135597. ** pTo path. Replace pTo with the candidate. */
  135598. #ifdef WHERETRACE_ENABLED /* 0x4 */
  135599. if( sqlite3WhereTrace&0x4 ){
  135600. sqlite3DebugPrintf(
  135601. "Update %s cost=%-3d,%3d,%3d order=%c",
  135602. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  135603. isOrdered>=0 ? isOrdered+'0' : '?');
  135604. sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
  135605. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  135606. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  135607. }
  135608. #endif
  135609. }
  135610. /* pWLoop is a winner. Add it to the set of best so far */
  135611. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  135612. pTo->revLoop = revMask;
  135613. pTo->nRow = nOut;
  135614. pTo->rCost = rCost;
  135615. pTo->rUnsorted = rUnsorted;
  135616. pTo->isOrdered = isOrdered;
  135617. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  135618. pTo->aLoop[iLoop] = pWLoop;
  135619. if( nTo>=mxChoice ){
  135620. mxI = 0;
  135621. mxCost = aTo[0].rCost;
  135622. mxUnsorted = aTo[0].nRow;
  135623. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  135624. if( pTo->rCost>mxCost
  135625. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  135626. ){
  135627. mxCost = pTo->rCost;
  135628. mxUnsorted = pTo->rUnsorted;
  135629. mxI = jj;
  135630. }
  135631. }
  135632. }
  135633. }
  135634. }
  135635. #ifdef WHERETRACE_ENABLED /* >=2 */
  135636. if( sqlite3WhereTrace & 0x02 ){
  135637. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  135638. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  135639. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  135640. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  135641. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  135642. if( pTo->isOrdered>0 ){
  135643. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  135644. }else{
  135645. sqlite3DebugPrintf("\n");
  135646. }
  135647. }
  135648. }
  135649. #endif
  135650. /* Swap the roles of aFrom and aTo for the next generation */
  135651. pFrom = aTo;
  135652. aTo = aFrom;
  135653. aFrom = pFrom;
  135654. nFrom = nTo;
  135655. }
  135656. if( nFrom==0 ){
  135657. sqlite3ErrorMsg(pParse, "no query solution");
  135658. sqlite3DbFreeNN(db, pSpace);
  135659. return SQLITE_ERROR;
  135660. }
  135661. /* Find the lowest cost path. pFrom will be left pointing to that path */
  135662. pFrom = aFrom;
  135663. for(ii=1; ii<nFrom; ii++){
  135664. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  135665. }
  135666. assert( pWInfo->nLevel==nLoop );
  135667. /* Load the lowest cost path into pWInfo */
  135668. for(iLoop=0; iLoop<nLoop; iLoop++){
  135669. WhereLevel *pLevel = pWInfo->a + iLoop;
  135670. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  135671. pLevel->iFrom = pWLoop->iTab;
  135672. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  135673. }
  135674. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  135675. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  135676. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  135677. && nRowEst
  135678. ){
  135679. Bitmask notUsed;
  135680. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  135681. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  135682. if( rc==pWInfo->pResultSet->nExpr ){
  135683. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  135684. }
  135685. }
  135686. pWInfo->bOrderedInnerLoop = 0;
  135687. if( pWInfo->pOrderBy ){
  135688. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  135689. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  135690. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  135691. }
  135692. }else{
  135693. pWInfo->nOBSat = pFrom->isOrdered;
  135694. pWInfo->revMask = pFrom->revLoop;
  135695. if( pWInfo->nOBSat<=0 ){
  135696. pWInfo->nOBSat = 0;
  135697. if( nLoop>0 ){
  135698. u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
  135699. if( (wsFlags & WHERE_ONEROW)==0
  135700. && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
  135701. ){
  135702. Bitmask m = 0;
  135703. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
  135704. WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
  135705. testcase( wsFlags & WHERE_IPK );
  135706. testcase( wsFlags & WHERE_COLUMN_IN );
  135707. if( rc==pWInfo->pOrderBy->nExpr ){
  135708. pWInfo->bOrderedInnerLoop = 1;
  135709. pWInfo->revMask = m;
  135710. }
  135711. }
  135712. }
  135713. }
  135714. }
  135715. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  135716. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  135717. ){
  135718. Bitmask revMask = 0;
  135719. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  135720. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  135721. );
  135722. assert( pWInfo->sorted==0 );
  135723. if( nOrder==pWInfo->pOrderBy->nExpr ){
  135724. pWInfo->sorted = 1;
  135725. pWInfo->revMask = revMask;
  135726. }
  135727. }
  135728. }
  135729. pWInfo->nRowOut = pFrom->nRow;
  135730. /* Free temporary memory and return success */
  135731. sqlite3DbFreeNN(db, pSpace);
  135732. return SQLITE_OK;
  135733. }
  135734. /*
  135735. ** Most queries use only a single table (they are not joins) and have
  135736. ** simple == constraints against indexed fields. This routine attempts
  135737. ** to plan those simple cases using much less ceremony than the
  135738. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  135739. ** times for the common case.
  135740. **
  135741. ** Return non-zero on success, if this query can be handled by this
  135742. ** no-frills query planner. Return zero if this query needs the
  135743. ** general-purpose query planner.
  135744. */
  135745. static int whereShortCut(WhereLoopBuilder *pBuilder){
  135746. WhereInfo *pWInfo;
  135747. struct SrcList_item *pItem;
  135748. WhereClause *pWC;
  135749. WhereTerm *pTerm;
  135750. WhereLoop *pLoop;
  135751. int iCur;
  135752. int j;
  135753. Table *pTab;
  135754. Index *pIdx;
  135755. pWInfo = pBuilder->pWInfo;
  135756. if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
  135757. assert( pWInfo->pTabList->nSrc>=1 );
  135758. pItem = pWInfo->pTabList->a;
  135759. pTab = pItem->pTab;
  135760. if( IsVirtual(pTab) ) return 0;
  135761. if( pItem->fg.isIndexedBy ) return 0;
  135762. iCur = pItem->iCursor;
  135763. pWC = &pWInfo->sWC;
  135764. pLoop = pBuilder->pNew;
  135765. pLoop->wsFlags = 0;
  135766. pLoop->nSkip = 0;
  135767. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  135768. if( pTerm ){
  135769. testcase( pTerm->eOperator & WO_IS );
  135770. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  135771. pLoop->aLTerm[0] = pTerm;
  135772. pLoop->nLTerm = 1;
  135773. pLoop->u.btree.nEq = 1;
  135774. /* TUNING: Cost of a rowid lookup is 10 */
  135775. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  135776. }else{
  135777. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  135778. int opMask;
  135779. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  135780. if( !IsUniqueIndex(pIdx)
  135781. || pIdx->pPartIdxWhere!=0
  135782. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  135783. ) continue;
  135784. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  135785. for(j=0; j<pIdx->nKeyCol; j++){
  135786. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  135787. if( pTerm==0 ) break;
  135788. testcase( pTerm->eOperator & WO_IS );
  135789. pLoop->aLTerm[j] = pTerm;
  135790. }
  135791. if( j!=pIdx->nKeyCol ) continue;
  135792. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  135793. if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
  135794. pLoop->wsFlags |= WHERE_IDX_ONLY;
  135795. }
  135796. pLoop->nLTerm = j;
  135797. pLoop->u.btree.nEq = j;
  135798. pLoop->u.btree.pIndex = pIdx;
  135799. /* TUNING: Cost of a unique index lookup is 15 */
  135800. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  135801. break;
  135802. }
  135803. }
  135804. if( pLoop->wsFlags ){
  135805. pLoop->nOut = (LogEst)1;
  135806. pWInfo->a[0].pWLoop = pLoop;
  135807. assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
  135808. pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
  135809. pWInfo->a[0].iTabCur = iCur;
  135810. pWInfo->nRowOut = 1;
  135811. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  135812. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  135813. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  135814. }
  135815. #ifdef SQLITE_DEBUG
  135816. pLoop->cId = '0';
  135817. #endif
  135818. return 1;
  135819. }
  135820. return 0;
  135821. }
  135822. /*
  135823. ** Helper function for exprIsDeterministic().
  135824. */
  135825. static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
  135826. if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
  135827. pWalker->eCode = 0;
  135828. return WRC_Abort;
  135829. }
  135830. return WRC_Continue;
  135831. }
  135832. /*
  135833. ** Return true if the expression contains no non-deterministic SQL
  135834. ** functions. Do not consider non-deterministic SQL functions that are
  135835. ** part of sub-select statements.
  135836. */
  135837. static int exprIsDeterministic(Expr *p){
  135838. Walker w;
  135839. memset(&w, 0, sizeof(w));
  135840. w.eCode = 1;
  135841. w.xExprCallback = exprNodeIsDeterministic;
  135842. w.xSelectCallback = sqlite3SelectWalkFail;
  135843. sqlite3WalkExpr(&w, p);
  135844. return w.eCode;
  135845. }
  135846. /*
  135847. ** Generate the beginning of the loop used for WHERE clause processing.
  135848. ** The return value is a pointer to an opaque structure that contains
  135849. ** information needed to terminate the loop. Later, the calling routine
  135850. ** should invoke sqlite3WhereEnd() with the return value of this function
  135851. ** in order to complete the WHERE clause processing.
  135852. **
  135853. ** If an error occurs, this routine returns NULL.
  135854. **
  135855. ** The basic idea is to do a nested loop, one loop for each table in
  135856. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  135857. ** same as a SELECT with only a single table in the FROM clause.) For
  135858. ** example, if the SQL is this:
  135859. **
  135860. ** SELECT * FROM t1, t2, t3 WHERE ...;
  135861. **
  135862. ** Then the code generated is conceptually like the following:
  135863. **
  135864. ** foreach row1 in t1 do \ Code generated
  135865. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  135866. ** foreach row3 in t3 do /
  135867. ** ...
  135868. ** end \ Code generated
  135869. ** end |-- by sqlite3WhereEnd()
  135870. ** end /
  135871. **
  135872. ** Note that the loops might not be nested in the order in which they
  135873. ** appear in the FROM clause if a different order is better able to make
  135874. ** use of indices. Note also that when the IN operator appears in
  135875. ** the WHERE clause, it might result in additional nested loops for
  135876. ** scanning through all values on the right-hand side of the IN.
  135877. **
  135878. ** There are Btree cursors associated with each table. t1 uses cursor
  135879. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  135880. ** And so forth. This routine generates code to open those VDBE cursors
  135881. ** and sqlite3WhereEnd() generates the code to close them.
  135882. **
  135883. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  135884. ** in pTabList pointing at their appropriate entries. The [...] code
  135885. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  135886. ** data from the various tables of the loop.
  135887. **
  135888. ** If the WHERE clause is empty, the foreach loops must each scan their
  135889. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  135890. ** the tables have indices and there are terms in the WHERE clause that
  135891. ** refer to those indices, a complete table scan can be avoided and the
  135892. ** code will run much faster. Most of the work of this routine is checking
  135893. ** to see if there are indices that can be used to speed up the loop.
  135894. **
  135895. ** Terms of the WHERE clause are also used to limit which rows actually
  135896. ** make it to the "..." in the middle of the loop. After each "foreach",
  135897. ** terms of the WHERE clause that use only terms in that loop and outer
  135898. ** loops are evaluated and if false a jump is made around all subsequent
  135899. ** inner loops (or around the "..." if the test occurs within the inner-
  135900. ** most loop)
  135901. **
  135902. ** OUTER JOINS
  135903. **
  135904. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  135905. **
  135906. ** foreach row1 in t1 do
  135907. ** flag = 0
  135908. ** foreach row2 in t2 do
  135909. ** start:
  135910. ** ...
  135911. ** flag = 1
  135912. ** end
  135913. ** if flag==0 then
  135914. ** move the row2 cursor to a null row
  135915. ** goto start
  135916. ** fi
  135917. ** end
  135918. **
  135919. ** ORDER BY CLAUSE PROCESSING
  135920. **
  135921. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  135922. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  135923. ** if there is one. If there is no ORDER BY clause or if this routine
  135924. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  135925. **
  135926. ** The iIdxCur parameter is the cursor number of an index. If
  135927. ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
  135928. ** to use for OR clause processing. The WHERE clause should use this
  135929. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  135930. ** the first cursor in an array of cursors for all indices. iIdxCur should
  135931. ** be used to compute the appropriate cursor depending on which index is
  135932. ** used.
  135933. */
  135934. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  135935. Parse *pParse, /* The parser context */
  135936. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  135937. Expr *pWhere, /* The WHERE clause */
  135938. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  135939. ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
  135940. u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
  135941. int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
  135942. ** If WHERE_USE_LIMIT, then the limit amount */
  135943. ){
  135944. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  135945. int nTabList; /* Number of elements in pTabList */
  135946. WhereInfo *pWInfo; /* Will become the return value of this function */
  135947. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  135948. Bitmask notReady; /* Cursors that are not yet positioned */
  135949. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  135950. WhereMaskSet *pMaskSet; /* The expression mask set */
  135951. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  135952. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  135953. int ii; /* Loop counter */
  135954. sqlite3 *db; /* Database connection */
  135955. int rc; /* Return code */
  135956. u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
  135957. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  135958. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  135959. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  135960. ));
  135961. /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
  135962. assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  135963. || (wctrlFlags & WHERE_USE_LIMIT)==0 );
  135964. /* Variable initialization */
  135965. db = pParse->db;
  135966. memset(&sWLB, 0, sizeof(sWLB));
  135967. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  135968. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  135969. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  135970. sWLB.pOrderBy = pOrderBy;
  135971. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  135972. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  135973. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  135974. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  135975. }
  135976. /* The number of tables in the FROM clause is limited by the number of
  135977. ** bits in a Bitmask
  135978. */
  135979. testcase( pTabList->nSrc==BMS );
  135980. if( pTabList->nSrc>BMS ){
  135981. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  135982. return 0;
  135983. }
  135984. /* This function normally generates a nested loop for all tables in
  135985. ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
  135986. ** only generate code for the first table in pTabList and assume that
  135987. ** any cursors associated with subsequent tables are uninitialized.
  135988. */
  135989. nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
  135990. /* Allocate and initialize the WhereInfo structure that will become the
  135991. ** return value. A single allocation is used to store the WhereInfo
  135992. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  135993. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  135994. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  135995. ** some architectures. Hence the ROUND8() below.
  135996. */
  135997. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  135998. pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
  135999. if( db->mallocFailed ){
  136000. sqlite3DbFree(db, pWInfo);
  136001. pWInfo = 0;
  136002. goto whereBeginError;
  136003. }
  136004. pWInfo->pParse = pParse;
  136005. pWInfo->pTabList = pTabList;
  136006. pWInfo->pOrderBy = pOrderBy;
  136007. pWInfo->pWhere = pWhere;
  136008. pWInfo->pResultSet = pResultSet;
  136009. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  136010. pWInfo->nLevel = nTabList;
  136011. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
  136012. pWInfo->wctrlFlags = wctrlFlags;
  136013. pWInfo->iLimit = iAuxArg;
  136014. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  136015. memset(&pWInfo->nOBSat, 0,
  136016. offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
  136017. memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
  136018. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  136019. pMaskSet = &pWInfo->sMaskSet;
  136020. sWLB.pWInfo = pWInfo;
  136021. sWLB.pWC = &pWInfo->sWC;
  136022. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  136023. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  136024. whereLoopInit(sWLB.pNew);
  136025. #ifdef SQLITE_DEBUG
  136026. sWLB.pNew->cId = '*';
  136027. #endif
  136028. /* Split the WHERE clause into separate subexpressions where each
  136029. ** subexpression is separated by an AND operator.
  136030. */
  136031. initMaskSet(pMaskSet);
  136032. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  136033. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  136034. /* Special case: No FROM clause
  136035. */
  136036. if( nTabList==0 ){
  136037. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  136038. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  136039. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  136040. }
  136041. ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
  136042. }else{
  136043. /* Assign a bit from the bitmask to every term in the FROM clause.
  136044. **
  136045. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  136046. **
  136047. ** The rule of the previous sentence ensures thta if X is the bitmask for
  136048. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  136049. ** Knowing the bitmask for all tables to the left of a left join is
  136050. ** important. Ticket #3015.
  136051. **
  136052. ** Note that bitmasks are created for all pTabList->nSrc tables in
  136053. ** pTabList, not just the first nTabList tables. nTabList is normally
  136054. ** equal to pTabList->nSrc but might be shortened to 1 if the
  136055. ** WHERE_OR_SUBCLAUSE flag is set.
  136056. */
  136057. ii = 0;
  136058. do{
  136059. createMask(pMaskSet, pTabList->a[ii].iCursor);
  136060. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  136061. }while( (++ii)<pTabList->nSrc );
  136062. #ifdef SQLITE_DEBUG
  136063. {
  136064. Bitmask mx = 0;
  136065. for(ii=0; ii<pTabList->nSrc; ii++){
  136066. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  136067. assert( m>=mx );
  136068. mx = m;
  136069. }
  136070. }
  136071. #endif
  136072. }
  136073. /* Analyze all of the subexpressions. */
  136074. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  136075. if( db->mallocFailed ) goto whereBeginError;
  136076. /* Special case: WHERE terms that do not refer to any tables in the join
  136077. ** (constant expressions). Evaluate each such term, and jump over all the
  136078. ** generated code if the result is not true.
  136079. **
  136080. ** Do not do this if the expression contains non-deterministic functions
  136081. ** that are not within a sub-select. This is not strictly required, but
  136082. ** preserves SQLite's legacy behaviour in the following two cases:
  136083. **
  136084. ** FROM ... WHERE random()>0; -- eval random() once per row
  136085. ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall
  136086. */
  136087. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  136088. WhereTerm *pT = &sWLB.pWC->a[ii];
  136089. if( pT->wtFlags & TERM_VIRTUAL ) continue;
  136090. if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
  136091. sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  136092. pT->wtFlags |= TERM_CODED;
  136093. }
  136094. }
  136095. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  136096. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  136097. /* The DISTINCT marking is pointless. Ignore it. */
  136098. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  136099. }else if( pOrderBy==0 ){
  136100. /* Try to ORDER BY the result set to make distinct processing easier */
  136101. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  136102. pWInfo->pOrderBy = pResultSet;
  136103. }
  136104. }
  136105. /* Construct the WhereLoop objects */
  136106. #if defined(WHERETRACE_ENABLED)
  136107. if( sqlite3WhereTrace & 0xffff ){
  136108. sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
  136109. if( wctrlFlags & WHERE_USE_LIMIT ){
  136110. sqlite3DebugPrintf(", limit: %d", iAuxArg);
  136111. }
  136112. sqlite3DebugPrintf(")\n");
  136113. }
  136114. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  136115. sqlite3WhereClausePrint(sWLB.pWC);
  136116. }
  136117. #endif
  136118. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  136119. rc = whereLoopAddAll(&sWLB);
  136120. if( rc ) goto whereBeginError;
  136121. #ifdef WHERETRACE_ENABLED
  136122. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  136123. WhereLoop *p;
  136124. int i;
  136125. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  136126. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  136127. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  136128. p->cId = zLabel[i%(sizeof(zLabel)-1)];
  136129. whereLoopPrint(p, sWLB.pWC);
  136130. }
  136131. }
  136132. #endif
  136133. wherePathSolver(pWInfo, 0);
  136134. if( db->mallocFailed ) goto whereBeginError;
  136135. if( pWInfo->pOrderBy ){
  136136. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  136137. if( db->mallocFailed ) goto whereBeginError;
  136138. }
  136139. }
  136140. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  136141. pWInfo->revMask = ALLBITS;
  136142. }
  136143. if( pParse->nErr || NEVER(db->mallocFailed) ){
  136144. goto whereBeginError;
  136145. }
  136146. #ifdef WHERETRACE_ENABLED
  136147. if( sqlite3WhereTrace ){
  136148. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  136149. if( pWInfo->nOBSat>0 ){
  136150. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  136151. }
  136152. switch( pWInfo->eDistinct ){
  136153. case WHERE_DISTINCT_UNIQUE: {
  136154. sqlite3DebugPrintf(" DISTINCT=unique");
  136155. break;
  136156. }
  136157. case WHERE_DISTINCT_ORDERED: {
  136158. sqlite3DebugPrintf(" DISTINCT=ordered");
  136159. break;
  136160. }
  136161. case WHERE_DISTINCT_UNORDERED: {
  136162. sqlite3DebugPrintf(" DISTINCT=unordered");
  136163. break;
  136164. }
  136165. }
  136166. sqlite3DebugPrintf("\n");
  136167. for(ii=0; ii<pWInfo->nLevel; ii++){
  136168. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  136169. }
  136170. }
  136171. #endif
  136172. /* Attempt to omit tables from the join that do not affect the result.
  136173. ** For a table to not affect the result, the following must be true:
  136174. **
  136175. ** 1) The query must not be an aggregate.
  136176. ** 2) The table must be the RHS of a LEFT JOIN.
  136177. ** 3) Either the query must be DISTINCT, or else the ON or USING clause
  136178. ** must contain a constraint that limits the scan of the table to
  136179. ** at most a single row.
  136180. ** 4) The table must not be referenced by any part of the query apart
  136181. ** from its own USING or ON clause.
  136182. **
  136183. ** For example, given:
  136184. **
  136185. ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
  136186. ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
  136187. ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
  136188. **
  136189. ** then table t2 can be omitted from the following:
  136190. **
  136191. ** SELECT v1, v3 FROM t1
  136192. ** LEFT JOIN t2 USING (t1.ipk=t2.ipk)
  136193. ** LEFT JOIN t3 USING (t1.ipk=t3.ipk)
  136194. **
  136195. ** or from:
  136196. **
  136197. ** SELECT DISTINCT v1, v3 FROM t1
  136198. ** LEFT JOIN t2
  136199. ** LEFT JOIN t3 USING (t1.ipk=t3.ipk)
  136200. */
  136201. notReady = ~(Bitmask)0;
  136202. if( pWInfo->nLevel>=2
  136203. && pResultSet!=0 /* guarantees condition (1) above */
  136204. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  136205. ){
  136206. int i;
  136207. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  136208. if( sWLB.pOrderBy ){
  136209. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  136210. }
  136211. for(i=pWInfo->nLevel-1; i>=1; i--){
  136212. WhereTerm *pTerm, *pEnd;
  136213. struct SrcList_item *pItem;
  136214. pLoop = pWInfo->a[i].pWLoop;
  136215. pItem = &pWInfo->pTabList->a[pLoop->iTab];
  136216. if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
  136217. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  136218. && (pLoop->wsFlags & WHERE_ONEROW)==0
  136219. ){
  136220. continue;
  136221. }
  136222. if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
  136223. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  136224. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  136225. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  136226. if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  136227. || pTerm->pExpr->iRightJoinTable!=pItem->iCursor
  136228. ){
  136229. break;
  136230. }
  136231. }
  136232. }
  136233. if( pTerm<pEnd ) continue;
  136234. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  136235. notReady &= ~pLoop->maskSelf;
  136236. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  136237. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  136238. pTerm->wtFlags |= TERM_CODED;
  136239. }
  136240. }
  136241. if( i!=pWInfo->nLevel-1 ){
  136242. int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
  136243. memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
  136244. }
  136245. pWInfo->nLevel--;
  136246. nTabList--;
  136247. }
  136248. }
  136249. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  136250. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  136251. /* If the caller is an UPDATE or DELETE statement that is requesting
  136252. ** to use a one-pass algorithm, determine if this is appropriate.
  136253. **
  136254. ** A one-pass approach can be used if the caller has requested one
  136255. ** and either (a) the scan visits at most one row or (b) each
  136256. ** of the following are true:
  136257. **
  136258. ** * the caller has indicated that a one-pass approach can be used
  136259. ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
  136260. ** * the table is not a virtual table, and
  136261. ** * either the scan does not use the OR optimization or the caller
  136262. ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
  136263. ** for DELETE).
  136264. **
  136265. ** The last qualification is because an UPDATE statement uses
  136266. ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
  136267. ** use a one-pass approach, and this is not set accurately for scans
  136268. ** that use the OR optimization.
  136269. */
  136270. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  136271. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  136272. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  136273. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  136274. assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
  136275. if( bOnerow || (
  136276. 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
  136277. && !IsVirtual(pTabList->a[0].pTab)
  136278. && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
  136279. )){
  136280. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  136281. if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
  136282. if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
  136283. bFordelete = OPFLAG_FORDELETE;
  136284. }
  136285. pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
  136286. }
  136287. }
  136288. }
  136289. /* Open all tables in the pTabList and any indices selected for
  136290. ** searching those tables.
  136291. */
  136292. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  136293. Table *pTab; /* Table to open */
  136294. int iDb; /* Index of database containing table/index */
  136295. struct SrcList_item *pTabItem;
  136296. pTabItem = &pTabList->a[pLevel->iFrom];
  136297. pTab = pTabItem->pTab;
  136298. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  136299. pLoop = pLevel->pWLoop;
  136300. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  136301. /* Do nothing */
  136302. }else
  136303. #ifndef SQLITE_OMIT_VIRTUALTABLE
  136304. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  136305. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  136306. int iCur = pTabItem->iCursor;
  136307. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  136308. }else if( IsVirtual(pTab) ){
  136309. /* noop */
  136310. }else
  136311. #endif
  136312. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  136313. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  136314. int op = OP_OpenRead;
  136315. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  136316. op = OP_OpenWrite;
  136317. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  136318. };
  136319. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  136320. assert( pTabItem->iCursor==pLevel->iTabCur );
  136321. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  136322. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  136323. if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
  136324. Bitmask b = pTabItem->colUsed;
  136325. int n = 0;
  136326. for(; b; b=b>>1, n++){}
  136327. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
  136328. assert( n<=pTab->nCol );
  136329. }
  136330. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  136331. if( pLoop->u.btree.pIndex!=0 ){
  136332. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
  136333. }else
  136334. #endif
  136335. {
  136336. sqlite3VdbeChangeP5(v, bFordelete);
  136337. }
  136338. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  136339. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  136340. (const u8*)&pTabItem->colUsed, P4_INT64);
  136341. #endif
  136342. }else{
  136343. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  136344. }
  136345. if( pLoop->wsFlags & WHERE_INDEXED ){
  136346. Index *pIx = pLoop->u.btree.pIndex;
  136347. int iIndexCur;
  136348. int op = OP_OpenRead;
  136349. /* iAuxArg is always set to a positive value if ONEPASS is possible */
  136350. assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  136351. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  136352. && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
  136353. ){
  136354. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  136355. ** WITHOUT ROWID table. No need for a separate index */
  136356. iIndexCur = pLevel->iTabCur;
  136357. op = 0;
  136358. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  136359. Index *pJ = pTabItem->pTab->pIndex;
  136360. iIndexCur = iAuxArg;
  136361. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  136362. while( ALWAYS(pJ) && pJ!=pIx ){
  136363. iIndexCur++;
  136364. pJ = pJ->pNext;
  136365. }
  136366. op = OP_OpenWrite;
  136367. pWInfo->aiCurOnePass[1] = iIndexCur;
  136368. }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
  136369. iIndexCur = iAuxArg;
  136370. op = OP_ReopenIdx;
  136371. }else{
  136372. iIndexCur = pParse->nTab++;
  136373. }
  136374. pLevel->iIdxCur = iIndexCur;
  136375. assert( pIx->pSchema==pTab->pSchema );
  136376. assert( iIndexCur>=0 );
  136377. if( op ){
  136378. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  136379. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  136380. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  136381. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  136382. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  136383. && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
  136384. ){
  136385. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  136386. }
  136387. VdbeComment((v, "%s", pIx->zName));
  136388. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  136389. {
  136390. u64 colUsed = 0;
  136391. int ii, jj;
  136392. for(ii=0; ii<pIx->nColumn; ii++){
  136393. jj = pIx->aiColumn[ii];
  136394. if( jj<0 ) continue;
  136395. if( jj>63 ) jj = 63;
  136396. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  136397. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  136398. }
  136399. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  136400. (u8*)&colUsed, P4_INT64);
  136401. }
  136402. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  136403. }
  136404. }
  136405. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  136406. }
  136407. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  136408. if( db->mallocFailed ) goto whereBeginError;
  136409. /* Generate the code to do the search. Each iteration of the for
  136410. ** loop below generates code for a single nested loop of the VM
  136411. ** program.
  136412. */
  136413. for(ii=0; ii<nTabList; ii++){
  136414. int addrExplain;
  136415. int wsFlags;
  136416. pLevel = &pWInfo->a[ii];
  136417. wsFlags = pLevel->pWLoop->wsFlags;
  136418. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  136419. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  136420. constructAutomaticIndex(pParse, &pWInfo->sWC,
  136421. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  136422. if( db->mallocFailed ) goto whereBeginError;
  136423. }
  136424. #endif
  136425. addrExplain = sqlite3WhereExplainOneScan(
  136426. pParse, pTabList, pLevel, wctrlFlags
  136427. );
  136428. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  136429. notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);
  136430. pWInfo->iContinue = pLevel->addrCont;
  136431. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
  136432. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  136433. }
  136434. }
  136435. /* Done. */
  136436. VdbeModuleComment((v, "Begin WHERE-core"));
  136437. return pWInfo;
  136438. /* Jump here if malloc fails */
  136439. whereBeginError:
  136440. if( pWInfo ){
  136441. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  136442. whereInfoFree(db, pWInfo);
  136443. }
  136444. return 0;
  136445. }
  136446. /*
  136447. ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
  136448. ** index rather than the main table. In SQLITE_DEBUG mode, we want
  136449. ** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine
  136450. ** does that.
  136451. */
  136452. #ifndef SQLITE_DEBUG
  136453. # define OpcodeRewriteTrace(D,K,P) /* no-op */
  136454. #else
  136455. # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
  136456. static void sqlite3WhereOpcodeRewriteTrace(
  136457. sqlite3 *db,
  136458. int pc,
  136459. VdbeOp *pOp
  136460. ){
  136461. if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
  136462. sqlite3VdbePrintOp(0, pc, pOp);
  136463. }
  136464. #endif
  136465. /*
  136466. ** Generate the end of the WHERE loop. See comments on
  136467. ** sqlite3WhereBegin() for additional information.
  136468. */
  136469. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  136470. Parse *pParse = pWInfo->pParse;
  136471. Vdbe *v = pParse->pVdbe;
  136472. int i;
  136473. WhereLevel *pLevel;
  136474. WhereLoop *pLoop;
  136475. SrcList *pTabList = pWInfo->pTabList;
  136476. sqlite3 *db = pParse->db;
  136477. /* Generate loop termination code.
  136478. */
  136479. VdbeModuleComment((v, "End WHERE-core"));
  136480. for(i=pWInfo->nLevel-1; i>=0; i--){
  136481. int addr;
  136482. pLevel = &pWInfo->a[i];
  136483. pLoop = pLevel->pWLoop;
  136484. if( pLevel->op!=OP_Noop ){
  136485. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  136486. int addrSeek = 0;
  136487. Index *pIdx;
  136488. int n;
  136489. if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
  136490. && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
  136491. && (pLoop->wsFlags & WHERE_INDEXED)!=0
  136492. && (pIdx = pLoop->u.btree.pIndex)->hasStat1
  136493. && (n = pLoop->u.btree.nIdxCol)>0
  136494. && pIdx->aiRowLogEst[n]>=36
  136495. ){
  136496. int r1 = pParse->nMem+1;
  136497. int j, op;
  136498. for(j=0; j<n; j++){
  136499. sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
  136500. }
  136501. pParse->nMem += n+1;
  136502. op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
  136503. addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
  136504. VdbeCoverageIf(v, op==OP_SeekLT);
  136505. VdbeCoverageIf(v, op==OP_SeekGT);
  136506. sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
  136507. }
  136508. #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
  136509. /* The common case: Advance to the next row */
  136510. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  136511. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  136512. sqlite3VdbeChangeP5(v, pLevel->p5);
  136513. VdbeCoverage(v);
  136514. VdbeCoverageIf(v, pLevel->op==OP_Next);
  136515. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  136516. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  136517. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  136518. if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
  136519. #endif
  136520. }else{
  136521. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  136522. }
  136523. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  136524. struct InLoop *pIn;
  136525. int j;
  136526. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  136527. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  136528. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  136529. if( pIn->eEndLoopOp!=OP_Noop ){
  136530. if( pIn->nPrefix ){
  136531. assert( pLoop->wsFlags & WHERE_IN_EARLYOUT );
  136532. sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
  136533. sqlite3VdbeCurrentAddr(v)+2,
  136534. pIn->iBase, pIn->nPrefix);
  136535. VdbeCoverage(v);
  136536. }
  136537. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  136538. VdbeCoverage(v);
  136539. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
  136540. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
  136541. }
  136542. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  136543. }
  136544. }
  136545. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  136546. if( pLevel->addrSkip ){
  136547. sqlite3VdbeGoto(v, pLevel->addrSkip);
  136548. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  136549. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  136550. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  136551. }
  136552. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  136553. if( pLevel->addrLikeRep ){
  136554. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
  136555. pLevel->addrLikeRep);
  136556. VdbeCoverage(v);
  136557. }
  136558. #endif
  136559. if( pLevel->iLeftJoin ){
  136560. int ws = pLoop->wsFlags;
  136561. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  136562. assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
  136563. if( (ws & WHERE_IDX_ONLY)==0 ){
  136564. assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
  136565. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
  136566. }
  136567. if( (ws & WHERE_INDEXED)
  136568. || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
  136569. ){
  136570. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  136571. }
  136572. if( pLevel->op==OP_Return ){
  136573. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  136574. }else{
  136575. sqlite3VdbeGoto(v, pLevel->addrFirst);
  136576. }
  136577. sqlite3VdbeJumpHere(v, addr);
  136578. }
  136579. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  136580. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  136581. }
  136582. /* The "break" point is here, just past the end of the outer loop.
  136583. ** Set it.
  136584. */
  136585. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  136586. assert( pWInfo->nLevel<=pTabList->nSrc );
  136587. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  136588. int k, last;
  136589. VdbeOp *pOp;
  136590. Index *pIdx = 0;
  136591. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  136592. Table *pTab = pTabItem->pTab;
  136593. assert( pTab!=0 );
  136594. pLoop = pLevel->pWLoop;
  136595. /* For a co-routine, change all OP_Column references to the table of
  136596. ** the co-routine into OP_Copy of result contained in a register.
  136597. ** OP_Rowid becomes OP_Null.
  136598. */
  136599. if( pTabItem->fg.viaCoroutine ){
  136600. testcase( pParse->db->mallocFailed );
  136601. translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
  136602. pTabItem->regResult, 0);
  136603. continue;
  136604. }
  136605. #ifdef SQLITE_ENABLE_EARLY_CURSOR_CLOSE
  136606. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  136607. ** Except, do not close cursors that will be reused by the OR optimization
  136608. ** (WHERE_OR_SUBCLAUSE). And do not close the OP_OpenWrite cursors
  136609. ** created for the ONEPASS optimization.
  136610. */
  136611. if( (pTab->tabFlags & TF_Ephemeral)==0
  136612. && pTab->pSelect==0
  136613. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  136614. ){
  136615. int ws = pLoop->wsFlags;
  136616. if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
  136617. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  136618. }
  136619. if( (ws & WHERE_INDEXED)!=0
  136620. && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
  136621. && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
  136622. ){
  136623. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  136624. }
  136625. }
  136626. #endif
  136627. /* If this scan uses an index, make VDBE code substitutions to read data
  136628. ** from the index instead of from the table where possible. In some cases
  136629. ** this optimization prevents the table from ever being read, which can
  136630. ** yield a significant performance boost.
  136631. **
  136632. ** Calls to the code generator in between sqlite3WhereBegin and
  136633. ** sqlite3WhereEnd will have created code that references the table
  136634. ** directly. This loop scans all that code looking for opcodes
  136635. ** that reference the table and converts them into opcodes that
  136636. ** reference the index.
  136637. */
  136638. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  136639. pIdx = pLoop->u.btree.pIndex;
  136640. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  136641. pIdx = pLevel->u.pCovidx;
  136642. }
  136643. if( pIdx
  136644. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  136645. && !db->mallocFailed
  136646. ){
  136647. last = sqlite3VdbeCurrentAddr(v);
  136648. k = pLevel->addrBody;
  136649. #ifdef SQLITE_DEBUG
  136650. if( db->flags & SQLITE_VdbeAddopTrace ){
  136651. printf("TRANSLATE opcodes in range %d..%d\n", k, last-1);
  136652. }
  136653. #endif
  136654. pOp = sqlite3VdbeGetOp(v, k);
  136655. for(; k<last; k++, pOp++){
  136656. if( pOp->p1!=pLevel->iTabCur ) continue;
  136657. if( pOp->opcode==OP_Column
  136658. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  136659. || pOp->opcode==OP_Offset
  136660. #endif
  136661. ){
  136662. int x = pOp->p2;
  136663. assert( pIdx->pTable==pTab );
  136664. if( !HasRowid(pTab) ){
  136665. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  136666. x = pPk->aiColumn[x];
  136667. assert( x>=0 );
  136668. }
  136669. x = sqlite3ColumnOfIndex(pIdx, x);
  136670. if( x>=0 ){
  136671. pOp->p2 = x;
  136672. pOp->p1 = pLevel->iIdxCur;
  136673. OpcodeRewriteTrace(db, k, pOp);
  136674. }
  136675. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
  136676. || pWInfo->eOnePass );
  136677. }else if( pOp->opcode==OP_Rowid ){
  136678. pOp->p1 = pLevel->iIdxCur;
  136679. pOp->opcode = OP_IdxRowid;
  136680. OpcodeRewriteTrace(db, k, pOp);
  136681. }else if( pOp->opcode==OP_IfNullRow ){
  136682. pOp->p1 = pLevel->iIdxCur;
  136683. OpcodeRewriteTrace(db, k, pOp);
  136684. }
  136685. }
  136686. #ifdef SQLITE_DEBUG
  136687. if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
  136688. #endif
  136689. }
  136690. }
  136691. /* Final cleanup
  136692. */
  136693. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  136694. whereInfoFree(db, pWInfo);
  136695. return;
  136696. }
  136697. /************** End of where.c ***********************************************/
  136698. /************** Begin file window.c ******************************************/
  136699. /*
  136700. ** 2018 May 08
  136701. **
  136702. ** The author disclaims copyright to this source code. In place of
  136703. ** a legal notice, here is a blessing:
  136704. **
  136705. ** May you do good and not evil.
  136706. ** May you find forgiveness for yourself and forgive others.
  136707. ** May you share freely, never taking more than you give.
  136708. **
  136709. *************************************************************************
  136710. */
  136711. /* #include "sqliteInt.h" */
  136712. #ifndef SQLITE_OMIT_WINDOWFUNC
  136713. /*
  136714. ** SELECT REWRITING
  136715. **
  136716. ** Any SELECT statement that contains one or more window functions in
  136717. ** either the select list or ORDER BY clause (the only two places window
  136718. ** functions may be used) is transformed by function sqlite3WindowRewrite()
  136719. ** in order to support window function processing. For example, with the
  136720. ** schema:
  136721. **
  136722. ** CREATE TABLE t1(a, b, c, d, e, f, g);
  136723. **
  136724. ** the statement:
  136725. **
  136726. ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
  136727. **
  136728. ** is transformed to:
  136729. **
  136730. ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (
  136731. ** SELECT a, e, c, d, b FROM t1 ORDER BY c, d
  136732. ** ) ORDER BY e;
  136733. **
  136734. ** The flattening optimization is disabled when processing this transformed
  136735. ** SELECT statement. This allows the implementation of the window function
  136736. ** (in this case max()) to process rows sorted in order of (c, d), which
  136737. ** makes things easier for obvious reasons. More generally:
  136738. **
  136739. ** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
  136740. ** the sub-query.
  136741. **
  136742. ** * ORDER BY, LIMIT and OFFSET remain part of the parent query.
  136743. **
  136744. ** * Terminals from each of the expression trees that make up the
  136745. ** select-list and ORDER BY expressions in the parent query are
  136746. ** selected by the sub-query. For the purposes of the transformation,
  136747. ** terminals are column references and aggregate functions.
  136748. **
  136749. ** If there is more than one window function in the SELECT that uses
  136750. ** the same window declaration (the OVER bit), then a single scan may
  136751. ** be used to process more than one window function. For example:
  136752. **
  136753. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
  136754. ** min(e) OVER (PARTITION BY c ORDER BY d)
  136755. ** FROM t1;
  136756. **
  136757. ** is transformed in the same way as the example above. However:
  136758. **
  136759. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
  136760. ** min(e) OVER (PARTITION BY a ORDER BY b)
  136761. ** FROM t1;
  136762. **
  136763. ** Must be transformed to:
  136764. **
  136765. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (
  136766. ** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM
  136767. ** SELECT a, e, c, d, b FROM t1 ORDER BY a, b
  136768. ** ) ORDER BY c, d
  136769. ** ) ORDER BY e;
  136770. **
  136771. ** so that both min() and max() may process rows in the order defined by
  136772. ** their respective window declarations.
  136773. **
  136774. ** INTERFACE WITH SELECT.C
  136775. **
  136776. ** When processing the rewritten SELECT statement, code in select.c calls
  136777. ** sqlite3WhereBegin() to begin iterating through the results of the
  136778. ** sub-query, which is always implemented as a co-routine. It then calls
  136779. ** sqlite3WindowCodeStep() to process rows and finish the scan by calling
  136780. ** sqlite3WhereEnd().
  136781. **
  136782. ** sqlite3WindowCodeStep() generates VM code so that, for each row returned
  136783. ** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
  136784. ** When the sub-routine is invoked:
  136785. **
  136786. ** * The results of all window-functions for the row are stored
  136787. ** in the associated Window.regResult registers.
  136788. **
  136789. ** * The required terminal values are stored in the current row of
  136790. ** temp table Window.iEphCsr.
  136791. **
  136792. ** In some cases, depending on the window frame and the specific window
  136793. ** functions invoked, sqlite3WindowCodeStep() caches each entire partition
  136794. ** in a temp table before returning any rows. In other cases it does not.
  136795. ** This detail is encapsulated within this file, the code generated by
  136796. ** select.c is the same in either case.
  136797. **
  136798. ** BUILT-IN WINDOW FUNCTIONS
  136799. **
  136800. ** This implementation features the following built-in window functions:
  136801. **
  136802. ** row_number()
  136803. ** rank()
  136804. ** dense_rank()
  136805. ** percent_rank()
  136806. ** cume_dist()
  136807. ** ntile(N)
  136808. ** lead(expr [, offset [, default]])
  136809. ** lag(expr [, offset [, default]])
  136810. ** first_value(expr)
  136811. ** last_value(expr)
  136812. ** nth_value(expr, N)
  136813. **
  136814. ** These are the same built-in window functions supported by Postgres.
  136815. ** Although the behaviour of aggregate window functions (functions that
  136816. ** can be used as either aggregates or window funtions) allows them to
  136817. ** be implemented using an API, built-in window functions are much more
  136818. ** esoteric. Additionally, some window functions (e.g. nth_value())
  136819. ** may only be implemented by caching the entire partition in memory.
  136820. ** As such, some built-in window functions use the same API as aggregate
  136821. ** window functions and some are implemented directly using VDBE
  136822. ** instructions. Additionally, for those functions that use the API, the
  136823. ** window frame is sometimes modified before the SELECT statement is
  136824. ** rewritten. For example, regardless of the specified window frame, the
  136825. ** row_number() function always uses:
  136826. **
  136827. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  136828. **
  136829. ** See sqlite3WindowUpdate() for details.
  136830. **
  136831. ** As well as some of the built-in window functions, aggregate window
  136832. ** functions min() and max() are implemented using VDBE instructions if
  136833. ** the start of the window frame is declared as anything other than
  136834. ** UNBOUNDED PRECEDING.
  136835. */
  136836. /*
  136837. ** Implementation of built-in window function row_number(). Assumes that the
  136838. ** window frame has been coerced to:
  136839. **
  136840. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  136841. */
  136842. static void row_numberStepFunc(
  136843. sqlite3_context *pCtx,
  136844. int nArg,
  136845. sqlite3_value **apArg
  136846. ){
  136847. i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136848. if( p ) (*p)++;
  136849. UNUSED_PARAMETER(nArg);
  136850. UNUSED_PARAMETER(apArg);
  136851. }
  136852. static void row_numberValueFunc(sqlite3_context *pCtx){
  136853. i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136854. sqlite3_result_int64(pCtx, (p ? *p : 0));
  136855. }
  136856. /*
  136857. ** Context object type used by rank(), dense_rank(), percent_rank() and
  136858. ** cume_dist().
  136859. */
  136860. struct CallCount {
  136861. i64 nValue;
  136862. i64 nStep;
  136863. i64 nTotal;
  136864. };
  136865. /*
  136866. ** Implementation of built-in window function dense_rank(). Assumes that
  136867. ** the window frame has been set to:
  136868. **
  136869. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  136870. */
  136871. static void dense_rankStepFunc(
  136872. sqlite3_context *pCtx,
  136873. int nArg,
  136874. sqlite3_value **apArg
  136875. ){
  136876. struct CallCount *p;
  136877. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136878. if( p ) p->nStep = 1;
  136879. UNUSED_PARAMETER(nArg);
  136880. UNUSED_PARAMETER(apArg);
  136881. }
  136882. static void dense_rankValueFunc(sqlite3_context *pCtx){
  136883. struct CallCount *p;
  136884. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136885. if( p ){
  136886. if( p->nStep ){
  136887. p->nValue++;
  136888. p->nStep = 0;
  136889. }
  136890. sqlite3_result_int64(pCtx, p->nValue);
  136891. }
  136892. }
  136893. /*
  136894. ** Implementation of built-in window function nth_value(). This
  136895. ** implementation is used in "slow mode" only - when the EXCLUDE clause
  136896. ** is not set to the default value "NO OTHERS".
  136897. */
  136898. struct NthValueCtx {
  136899. i64 nStep;
  136900. sqlite3_value *pValue;
  136901. };
  136902. static void nth_valueStepFunc(
  136903. sqlite3_context *pCtx,
  136904. int nArg,
  136905. sqlite3_value **apArg
  136906. ){
  136907. struct NthValueCtx *p;
  136908. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136909. if( p ){
  136910. i64 iVal;
  136911. switch( sqlite3_value_numeric_type(apArg[1]) ){
  136912. case SQLITE_INTEGER:
  136913. iVal = sqlite3_value_int64(apArg[1]);
  136914. break;
  136915. case SQLITE_FLOAT: {
  136916. double fVal = sqlite3_value_double(apArg[1]);
  136917. if( ((i64)fVal)!=fVal ) goto error_out;
  136918. iVal = (i64)fVal;
  136919. break;
  136920. }
  136921. default:
  136922. goto error_out;
  136923. }
  136924. if( iVal<=0 ) goto error_out;
  136925. p->nStep++;
  136926. if( iVal==p->nStep ){
  136927. p->pValue = sqlite3_value_dup(apArg[0]);
  136928. if( !p->pValue ){
  136929. sqlite3_result_error_nomem(pCtx);
  136930. }
  136931. }
  136932. }
  136933. UNUSED_PARAMETER(nArg);
  136934. UNUSED_PARAMETER(apArg);
  136935. return;
  136936. error_out:
  136937. sqlite3_result_error(
  136938. pCtx, "second argument to nth_value must be a positive integer", -1
  136939. );
  136940. }
  136941. static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
  136942. struct NthValueCtx *p;
  136943. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);
  136944. if( p && p->pValue ){
  136945. sqlite3_result_value(pCtx, p->pValue);
  136946. sqlite3_value_free(p->pValue);
  136947. p->pValue = 0;
  136948. }
  136949. }
  136950. #define nth_valueInvFunc noopStepFunc
  136951. #define nth_valueValueFunc noopValueFunc
  136952. static void first_valueStepFunc(
  136953. sqlite3_context *pCtx,
  136954. int nArg,
  136955. sqlite3_value **apArg
  136956. ){
  136957. struct NthValueCtx *p;
  136958. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136959. if( p && p->pValue==0 ){
  136960. p->pValue = sqlite3_value_dup(apArg[0]);
  136961. if( !p->pValue ){
  136962. sqlite3_result_error_nomem(pCtx);
  136963. }
  136964. }
  136965. UNUSED_PARAMETER(nArg);
  136966. UNUSED_PARAMETER(apArg);
  136967. }
  136968. static void first_valueFinalizeFunc(sqlite3_context *pCtx){
  136969. struct NthValueCtx *p;
  136970. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136971. if( p && p->pValue ){
  136972. sqlite3_result_value(pCtx, p->pValue);
  136973. sqlite3_value_free(p->pValue);
  136974. p->pValue = 0;
  136975. }
  136976. }
  136977. #define first_valueInvFunc noopStepFunc
  136978. #define first_valueValueFunc noopValueFunc
  136979. /*
  136980. ** Implementation of built-in window function rank(). Assumes that
  136981. ** the window frame has been set to:
  136982. **
  136983. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  136984. */
  136985. static void rankStepFunc(
  136986. sqlite3_context *pCtx,
  136987. int nArg,
  136988. sqlite3_value **apArg
  136989. ){
  136990. struct CallCount *p;
  136991. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  136992. if( p ){
  136993. p->nStep++;
  136994. if( p->nValue==0 ){
  136995. p->nValue = p->nStep;
  136996. }
  136997. }
  136998. UNUSED_PARAMETER(nArg);
  136999. UNUSED_PARAMETER(apArg);
  137000. }
  137001. static void rankValueFunc(sqlite3_context *pCtx){
  137002. struct CallCount *p;
  137003. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137004. if( p ){
  137005. sqlite3_result_int64(pCtx, p->nValue);
  137006. p->nValue = 0;
  137007. }
  137008. }
  137009. /*
  137010. ** Implementation of built-in window function percent_rank(). Assumes that
  137011. ** the window frame has been set to:
  137012. **
  137013. ** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
  137014. */
  137015. static void percent_rankStepFunc(
  137016. sqlite3_context *pCtx,
  137017. int nArg,
  137018. sqlite3_value **apArg
  137019. ){
  137020. struct CallCount *p;
  137021. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  137022. UNUSED_PARAMETER(apArg);
  137023. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137024. if( p ){
  137025. p->nTotal++;
  137026. }
  137027. }
  137028. static void percent_rankInvFunc(
  137029. sqlite3_context *pCtx,
  137030. int nArg,
  137031. sqlite3_value **apArg
  137032. ){
  137033. struct CallCount *p;
  137034. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  137035. UNUSED_PARAMETER(apArg);
  137036. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137037. p->nStep++;
  137038. }
  137039. static void percent_rankValueFunc(sqlite3_context *pCtx){
  137040. struct CallCount *p;
  137041. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137042. if( p ){
  137043. p->nValue = p->nStep;
  137044. if( p->nTotal>1 ){
  137045. double r = (double)p->nValue / (double)(p->nTotal-1);
  137046. sqlite3_result_double(pCtx, r);
  137047. }else{
  137048. sqlite3_result_double(pCtx, 0.0);
  137049. }
  137050. }
  137051. }
  137052. #define percent_rankFinalizeFunc percent_rankValueFunc
  137053. /*
  137054. ** Implementation of built-in window function cume_dist(). Assumes that
  137055. ** the window frame has been set to:
  137056. **
  137057. ** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
  137058. */
  137059. static void cume_distStepFunc(
  137060. sqlite3_context *pCtx,
  137061. int nArg,
  137062. sqlite3_value **apArg
  137063. ){
  137064. struct CallCount *p;
  137065. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  137066. UNUSED_PARAMETER(apArg);
  137067. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137068. if( p ){
  137069. p->nTotal++;
  137070. }
  137071. }
  137072. static void cume_distInvFunc(
  137073. sqlite3_context *pCtx,
  137074. int nArg,
  137075. sqlite3_value **apArg
  137076. ){
  137077. struct CallCount *p;
  137078. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  137079. UNUSED_PARAMETER(apArg);
  137080. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137081. p->nStep++;
  137082. }
  137083. static void cume_distValueFunc(sqlite3_context *pCtx){
  137084. struct CallCount *p;
  137085. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
  137086. if( p ){
  137087. double r = (double)(p->nStep) / (double)(p->nTotal);
  137088. sqlite3_result_double(pCtx, r);
  137089. }
  137090. }
  137091. #define cume_distFinalizeFunc cume_distValueFunc
  137092. /*
  137093. ** Context object for ntile() window function.
  137094. */
  137095. struct NtileCtx {
  137096. i64 nTotal; /* Total rows in partition */
  137097. i64 nParam; /* Parameter passed to ntile(N) */
  137098. i64 iRow; /* Current row */
  137099. };
  137100. /*
  137101. ** Implementation of ntile(). This assumes that the window frame has
  137102. ** been coerced to:
  137103. **
  137104. ** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
  137105. */
  137106. static void ntileStepFunc(
  137107. sqlite3_context *pCtx,
  137108. int nArg,
  137109. sqlite3_value **apArg
  137110. ){
  137111. struct NtileCtx *p;
  137112. assert( nArg==1 ); UNUSED_PARAMETER(nArg);
  137113. p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137114. if( p ){
  137115. if( p->nTotal==0 ){
  137116. p->nParam = sqlite3_value_int64(apArg[0]);
  137117. if( p->nParam<=0 ){
  137118. sqlite3_result_error(
  137119. pCtx, "argument of ntile must be a positive integer", -1
  137120. );
  137121. }
  137122. }
  137123. p->nTotal++;
  137124. }
  137125. }
  137126. static void ntileInvFunc(
  137127. sqlite3_context *pCtx,
  137128. int nArg,
  137129. sqlite3_value **apArg
  137130. ){
  137131. struct NtileCtx *p;
  137132. assert( nArg==1 ); UNUSED_PARAMETER(nArg);
  137133. UNUSED_PARAMETER(apArg);
  137134. p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137135. p->iRow++;
  137136. }
  137137. static void ntileValueFunc(sqlite3_context *pCtx){
  137138. struct NtileCtx *p;
  137139. p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137140. if( p && p->nParam>0 ){
  137141. int nSize = (p->nTotal / p->nParam);
  137142. if( nSize==0 ){
  137143. sqlite3_result_int64(pCtx, p->iRow+1);
  137144. }else{
  137145. i64 nLarge = p->nTotal - p->nParam*nSize;
  137146. i64 iSmall = nLarge*(nSize+1);
  137147. i64 iRow = p->iRow;
  137148. assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
  137149. if( iRow<iSmall ){
  137150. sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
  137151. }else{
  137152. sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
  137153. }
  137154. }
  137155. }
  137156. }
  137157. #define ntileFinalizeFunc ntileValueFunc
  137158. /*
  137159. ** Context object for last_value() window function.
  137160. */
  137161. struct LastValueCtx {
  137162. sqlite3_value *pVal;
  137163. int nVal;
  137164. };
  137165. /*
  137166. ** Implementation of last_value().
  137167. */
  137168. static void last_valueStepFunc(
  137169. sqlite3_context *pCtx,
  137170. int nArg,
  137171. sqlite3_value **apArg
  137172. ){
  137173. struct LastValueCtx *p;
  137174. UNUSED_PARAMETER(nArg);
  137175. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137176. if( p ){
  137177. sqlite3_value_free(p->pVal);
  137178. p->pVal = sqlite3_value_dup(apArg[0]);
  137179. if( p->pVal==0 ){
  137180. sqlite3_result_error_nomem(pCtx);
  137181. }else{
  137182. p->nVal++;
  137183. }
  137184. }
  137185. }
  137186. static void last_valueInvFunc(
  137187. sqlite3_context *pCtx,
  137188. int nArg,
  137189. sqlite3_value **apArg
  137190. ){
  137191. struct LastValueCtx *p;
  137192. UNUSED_PARAMETER(nArg);
  137193. UNUSED_PARAMETER(apArg);
  137194. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137195. if( ALWAYS(p) ){
  137196. p->nVal--;
  137197. if( p->nVal==0 ){
  137198. sqlite3_value_free(p->pVal);
  137199. p->pVal = 0;
  137200. }
  137201. }
  137202. }
  137203. static void last_valueValueFunc(sqlite3_context *pCtx){
  137204. struct LastValueCtx *p;
  137205. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
  137206. if( p && p->pVal ){
  137207. sqlite3_result_value(pCtx, p->pVal);
  137208. }
  137209. }
  137210. static void last_valueFinalizeFunc(sqlite3_context *pCtx){
  137211. struct LastValueCtx *p;
  137212. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  137213. if( p && p->pVal ){
  137214. sqlite3_result_value(pCtx, p->pVal);
  137215. sqlite3_value_free(p->pVal);
  137216. p->pVal = 0;
  137217. }
  137218. }
  137219. /*
  137220. ** Static names for the built-in window function names. These static
  137221. ** names are used, rather than string literals, so that FuncDef objects
  137222. ** can be associated with a particular window function by direct
  137223. ** comparison of the zName pointer. Example:
  137224. **
  137225. ** if( pFuncDef->zName==row_valueName ){ ... }
  137226. */
  137227. static const char row_numberName[] = "row_number";
  137228. static const char dense_rankName[] = "dense_rank";
  137229. static const char rankName[] = "rank";
  137230. static const char percent_rankName[] = "percent_rank";
  137231. static const char cume_distName[] = "cume_dist";
  137232. static const char ntileName[] = "ntile";
  137233. static const char last_valueName[] = "last_value";
  137234. static const char nth_valueName[] = "nth_value";
  137235. static const char first_valueName[] = "first_value";
  137236. static const char leadName[] = "lead";
  137237. static const char lagName[] = "lag";
  137238. /*
  137239. ** No-op implementations of xStep() and xFinalize(). Used as place-holders
  137240. ** for built-in window functions that never call those interfaces.
  137241. **
  137242. ** The noopValueFunc() is called but is expected to do nothing. The
  137243. ** noopStepFunc() is never called, and so it is marked with NO_TEST to
  137244. ** let the test coverage routine know not to expect this function to be
  137245. ** invoked.
  137246. */
  137247. static void noopStepFunc( /*NO_TEST*/
  137248. sqlite3_context *p, /*NO_TEST*/
  137249. int n, /*NO_TEST*/
  137250. sqlite3_value **a /*NO_TEST*/
  137251. ){ /*NO_TEST*/
  137252. UNUSED_PARAMETER(p); /*NO_TEST*/
  137253. UNUSED_PARAMETER(n); /*NO_TEST*/
  137254. UNUSED_PARAMETER(a); /*NO_TEST*/
  137255. assert(0); /*NO_TEST*/
  137256. } /*NO_TEST*/
  137257. static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
  137258. /* Window functions that use all window interfaces: xStep, xFinal,
  137259. ** xValue, and xInverse */
  137260. #define WINDOWFUNCALL(name,nArg,extra) { \
  137261. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  137262. name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
  137263. name ## InvFunc, name ## Name, {0} \
  137264. }
  137265. /* Window functions that are implemented using bytecode and thus have
  137266. ** no-op routines for their methods */
  137267. #define WINDOWFUNCNOOP(name,nArg,extra) { \
  137268. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  137269. noopStepFunc, noopValueFunc, noopValueFunc, \
  137270. noopStepFunc, name ## Name, {0} \
  137271. }
  137272. /* Window functions that use all window interfaces: xStep, the
  137273. ** same routine for xFinalize and xValue and which never call
  137274. ** xInverse. */
  137275. #define WINDOWFUNCX(name,nArg,extra) { \
  137276. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  137277. name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
  137278. noopStepFunc, name ## Name, {0} \
  137279. }
  137280. /*
  137281. ** Register those built-in window functions that are not also aggregates.
  137282. */
  137283. SQLITE_PRIVATE void sqlite3WindowFunctions(void){
  137284. static FuncDef aWindowFuncs[] = {
  137285. WINDOWFUNCX(row_number, 0, 0),
  137286. WINDOWFUNCX(dense_rank, 0, 0),
  137287. WINDOWFUNCX(rank, 0, 0),
  137288. WINDOWFUNCALL(percent_rank, 0, 0),
  137289. WINDOWFUNCALL(cume_dist, 0, 0),
  137290. WINDOWFUNCALL(ntile, 1, 0),
  137291. WINDOWFUNCALL(last_value, 1, 0),
  137292. WINDOWFUNCALL(nth_value, 2, 0),
  137293. WINDOWFUNCALL(first_value, 1, 0),
  137294. WINDOWFUNCNOOP(lead, 1, 0),
  137295. WINDOWFUNCNOOP(lead, 2, 0),
  137296. WINDOWFUNCNOOP(lead, 3, 0),
  137297. WINDOWFUNCNOOP(lag, 1, 0),
  137298. WINDOWFUNCNOOP(lag, 2, 0),
  137299. WINDOWFUNCNOOP(lag, 3, 0),
  137300. };
  137301. sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
  137302. }
  137303. static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
  137304. Window *p;
  137305. for(p=pList; p; p=p->pNextWin){
  137306. if( sqlite3StrICmp(p->zName, zName)==0 ) break;
  137307. }
  137308. if( p==0 ){
  137309. sqlite3ErrorMsg(pParse, "no such window: %s", zName);
  137310. }
  137311. return p;
  137312. }
  137313. /*
  137314. ** This function is called immediately after resolving the function name
  137315. ** for a window function within a SELECT statement. Argument pList is a
  137316. ** linked list of WINDOW definitions for the current SELECT statement.
  137317. ** Argument pFunc is the function definition just resolved and pWin
  137318. ** is the Window object representing the associated OVER clause. This
  137319. ** function updates the contents of pWin as follows:
  137320. **
  137321. ** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
  137322. ** search list pList for a matching WINDOW definition, and update pWin
  137323. ** accordingly. If no such WINDOW clause can be found, leave an error
  137324. ** in pParse.
  137325. **
  137326. ** * If the function is a built-in window function that requires the
  137327. ** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
  137328. ** of this file), pWin is updated here.
  137329. */
  137330. SQLITE_PRIVATE void sqlite3WindowUpdate(
  137331. Parse *pParse,
  137332. Window *pList, /* List of named windows for this SELECT */
  137333. Window *pWin, /* Window frame to update */
  137334. FuncDef *pFunc /* Window function definition */
  137335. ){
  137336. if( pWin->zName && pWin->eFrmType==0 ){
  137337. Window *p = windowFind(pParse, pList, pWin->zName);
  137338. if( p==0 ) return;
  137339. pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
  137340. pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
  137341. pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
  137342. pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
  137343. pWin->eStart = p->eStart;
  137344. pWin->eEnd = p->eEnd;
  137345. pWin->eFrmType = p->eFrmType;
  137346. pWin->eExclude = p->eExclude;
  137347. }else{
  137348. sqlite3WindowChain(pParse, pWin, pList);
  137349. }
  137350. if( (pWin->eFrmType==TK_RANGE)
  137351. && (pWin->pStart || pWin->pEnd)
  137352. && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
  137353. ){
  137354. sqlite3ErrorMsg(pParse,
  137355. "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
  137356. );
  137357. }else
  137358. if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
  137359. sqlite3 *db = pParse->db;
  137360. if( pWin->pFilter ){
  137361. sqlite3ErrorMsg(pParse,
  137362. "FILTER clause may only be used with aggregate window functions"
  137363. );
  137364. }else{
  137365. struct WindowUpdate {
  137366. const char *zFunc;
  137367. int eFrmType;
  137368. int eStart;
  137369. int eEnd;
  137370. } aUp[] = {
  137371. { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
  137372. { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
  137373. { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
  137374. { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED },
  137375. { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
  137376. { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED },
  137377. { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED },
  137378. { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
  137379. };
  137380. int i;
  137381. for(i=0; i<ArraySize(aUp); i++){
  137382. if( pFunc->zName==aUp[i].zFunc ){
  137383. sqlite3ExprDelete(db, pWin->pStart);
  137384. sqlite3ExprDelete(db, pWin->pEnd);
  137385. pWin->pEnd = pWin->pStart = 0;
  137386. pWin->eFrmType = aUp[i].eFrmType;
  137387. pWin->eStart = aUp[i].eStart;
  137388. pWin->eEnd = aUp[i].eEnd;
  137389. pWin->eExclude = 0;
  137390. if( pWin->eStart==TK_FOLLOWING ){
  137391. pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
  137392. }
  137393. break;
  137394. }
  137395. }
  137396. }
  137397. }
  137398. pWin->pFunc = pFunc;
  137399. }
  137400. /*
  137401. ** Context object passed through sqlite3WalkExprList() to
  137402. ** selectWindowRewriteExprCb() by selectWindowRewriteEList().
  137403. */
  137404. typedef struct WindowRewrite WindowRewrite;
  137405. struct WindowRewrite {
  137406. Window *pWin;
  137407. SrcList *pSrc;
  137408. ExprList *pSub;
  137409. Select *pSubSelect; /* Current sub-select, if any */
  137410. };
  137411. /*
  137412. ** Callback function used by selectWindowRewriteEList(). If necessary,
  137413. ** this function appends to the output expression-list and updates
  137414. ** expression (*ppExpr) in place.
  137415. */
  137416. static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
  137417. struct WindowRewrite *p = pWalker->u.pRewrite;
  137418. Parse *pParse = pWalker->pParse;
  137419. /* If this function is being called from within a scalar sub-select
  137420. ** that used by the SELECT statement being processed, only process
  137421. ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
  137422. ** not process aggregates or window functions at all, as they belong
  137423. ** to the scalar sub-select. */
  137424. if( p->pSubSelect ){
  137425. if( pExpr->op!=TK_COLUMN ){
  137426. return WRC_Continue;
  137427. }else{
  137428. int nSrc = p->pSrc->nSrc;
  137429. int i;
  137430. for(i=0; i<nSrc; i++){
  137431. if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
  137432. }
  137433. if( i==nSrc ) return WRC_Continue;
  137434. }
  137435. }
  137436. switch( pExpr->op ){
  137437. case TK_FUNCTION:
  137438. if( !ExprHasProperty(pExpr, EP_WinFunc) ){
  137439. break;
  137440. }else{
  137441. Window *pWin;
  137442. for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
  137443. if( pExpr->y.pWin==pWin ){
  137444. assert( pWin->pOwner==pExpr );
  137445. return WRC_Prune;
  137446. }
  137447. }
  137448. }
  137449. /* Fall through. */
  137450. case TK_AGG_FUNCTION:
  137451. case TK_COLUMN: {
  137452. Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
  137453. p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
  137454. if( p->pSub ){
  137455. assert( ExprHasProperty(pExpr, EP_Static)==0 );
  137456. ExprSetProperty(pExpr, EP_Static);
  137457. sqlite3ExprDelete(pParse->db, pExpr);
  137458. ExprClearProperty(pExpr, EP_Static);
  137459. memset(pExpr, 0, sizeof(Expr));
  137460. pExpr->op = TK_COLUMN;
  137461. pExpr->iColumn = p->pSub->nExpr-1;
  137462. pExpr->iTable = p->pWin->iEphCsr;
  137463. }
  137464. break;
  137465. }
  137466. default: /* no-op */
  137467. break;
  137468. }
  137469. return WRC_Continue;
  137470. }
  137471. static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
  137472. struct WindowRewrite *p = pWalker->u.pRewrite;
  137473. Select *pSave = p->pSubSelect;
  137474. if( pSave==pSelect ){
  137475. return WRC_Continue;
  137476. }else{
  137477. p->pSubSelect = pSelect;
  137478. sqlite3WalkSelect(pWalker, pSelect);
  137479. p->pSubSelect = pSave;
  137480. }
  137481. return WRC_Prune;
  137482. }
  137483. /*
  137484. ** Iterate through each expression in expression-list pEList. For each:
  137485. **
  137486. ** * TK_COLUMN,
  137487. ** * aggregate function, or
  137488. ** * window function with a Window object that is not a member of the
  137489. ** Window list passed as the second argument (pWin).
  137490. **
  137491. ** Append the node to output expression-list (*ppSub). And replace it
  137492. ** with a TK_COLUMN that reads the (N-1)th element of table
  137493. ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
  137494. ** appending the new one.
  137495. */
  137496. static void selectWindowRewriteEList(
  137497. Parse *pParse,
  137498. Window *pWin,
  137499. SrcList *pSrc,
  137500. ExprList *pEList, /* Rewrite expressions in this list */
  137501. ExprList **ppSub /* IN/OUT: Sub-select expression-list */
  137502. ){
  137503. Walker sWalker;
  137504. WindowRewrite sRewrite;
  137505. memset(&sWalker, 0, sizeof(Walker));
  137506. memset(&sRewrite, 0, sizeof(WindowRewrite));
  137507. sRewrite.pSub = *ppSub;
  137508. sRewrite.pWin = pWin;
  137509. sRewrite.pSrc = pSrc;
  137510. sWalker.pParse = pParse;
  137511. sWalker.xExprCallback = selectWindowRewriteExprCb;
  137512. sWalker.xSelectCallback = selectWindowRewriteSelectCb;
  137513. sWalker.u.pRewrite = &sRewrite;
  137514. (void)sqlite3WalkExprList(&sWalker, pEList);
  137515. *ppSub = sRewrite.pSub;
  137516. }
  137517. /*
  137518. ** Append a copy of each expression in expression-list pAppend to
  137519. ** expression list pList. Return a pointer to the result list.
  137520. */
  137521. static ExprList *exprListAppendList(
  137522. Parse *pParse, /* Parsing context */
  137523. ExprList *pList, /* List to which to append. Might be NULL */
  137524. ExprList *pAppend /* List of values to append. Might be NULL */
  137525. ){
  137526. if( pAppend ){
  137527. int i;
  137528. int nInit = pList ? pList->nExpr : 0;
  137529. for(i=0; i<pAppend->nExpr; i++){
  137530. Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
  137531. pList = sqlite3ExprListAppend(pParse, pList, pDup);
  137532. if( pList ) pList->a[nInit+i].sortOrder = pAppend->a[i].sortOrder;
  137533. }
  137534. }
  137535. return pList;
  137536. }
  137537. /*
  137538. ** If the SELECT statement passed as the second argument does not invoke
  137539. ** any SQL window functions, this function is a no-op. Otherwise, it
  137540. ** rewrites the SELECT statement so that window function xStep functions
  137541. ** are invoked in the correct order as described under "SELECT REWRITING"
  137542. ** at the top of this file.
  137543. */
  137544. SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
  137545. int rc = SQLITE_OK;
  137546. if( p->pWin && p->pPrior==0 ){
  137547. Vdbe *v = sqlite3GetVdbe(pParse);
  137548. sqlite3 *db = pParse->db;
  137549. Select *pSub = 0; /* The subquery */
  137550. SrcList *pSrc = p->pSrc;
  137551. Expr *pWhere = p->pWhere;
  137552. ExprList *pGroupBy = p->pGroupBy;
  137553. Expr *pHaving = p->pHaving;
  137554. ExprList *pSort = 0;
  137555. ExprList *pSublist = 0; /* Expression list for sub-query */
  137556. Window *pMWin = p->pWin; /* Master window object */
  137557. Window *pWin; /* Window object iterator */
  137558. p->pSrc = 0;
  137559. p->pWhere = 0;
  137560. p->pGroupBy = 0;
  137561. p->pHaving = 0;
  137562. /* Create the ORDER BY clause for the sub-select. This is the concatenation
  137563. ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
  137564. ** redundant, remove the ORDER BY from the parent SELECT. */
  137565. pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
  137566. pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy);
  137567. if( pSort && p->pOrderBy ){
  137568. if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
  137569. sqlite3ExprListDelete(db, p->pOrderBy);
  137570. p->pOrderBy = 0;
  137571. }
  137572. }
  137573. /* Assign a cursor number for the ephemeral table used to buffer rows.
  137574. ** The OpenEphemeral instruction is coded later, after it is known how
  137575. ** many columns the table will have. */
  137576. pMWin->iEphCsr = pParse->nTab++;
  137577. pParse->nTab += 3;
  137578. selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, &pSublist);
  137579. selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, &pSublist);
  137580. pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
  137581. /* Append the PARTITION BY and ORDER BY expressions to the to the
  137582. ** sub-select expression list. They are required to figure out where
  137583. ** boundaries for partitions and sets of peer rows lie. */
  137584. pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition);
  137585. pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy);
  137586. /* Append the arguments passed to each window function to the
  137587. ** sub-select expression list. Also allocate two registers for each
  137588. ** window function - one for the accumulator, another for interim
  137589. ** results. */
  137590. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  137591. pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
  137592. pSublist = exprListAppendList(pParse, pSublist, pWin->pOwner->x.pList);
  137593. if( pWin->pFilter ){
  137594. Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
  137595. pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
  137596. }
  137597. pWin->regAccum = ++pParse->nMem;
  137598. pWin->regResult = ++pParse->nMem;
  137599. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  137600. }
  137601. /* If there is no ORDER BY or PARTITION BY clause, and the window
  137602. ** function accepts zero arguments, and there are no other columns
  137603. ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
  137604. ** that pSublist is still NULL here. Add a constant expression here to
  137605. ** keep everything legal in this case.
  137606. */
  137607. if( pSublist==0 ){
  137608. pSublist = sqlite3ExprListAppend(pParse, 0,
  137609. sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0)
  137610. );
  137611. }
  137612. pSub = sqlite3SelectNew(
  137613. pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
  137614. );
  137615. p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  137616. if( p->pSrc ){
  137617. p->pSrc->a[0].pSelect = pSub;
  137618. sqlite3SrcListAssignCursors(pParse, p->pSrc);
  137619. if( sqlite3ExpandSubquery(pParse, &p->pSrc->a[0]) ){
  137620. rc = SQLITE_NOMEM;
  137621. }else{
  137622. pSub->selFlags |= SF_Expanded;
  137623. p->selFlags &= ~SF_Aggregate;
  137624. sqlite3SelectPrep(pParse, pSub, 0);
  137625. }
  137626. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
  137627. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
  137628. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
  137629. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
  137630. }else{
  137631. sqlite3SelectDelete(db, pSub);
  137632. }
  137633. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  137634. }
  137635. return rc;
  137636. }
  137637. /*
  137638. ** Free the Window object passed as the second argument.
  137639. */
  137640. SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3 *db, Window *p){
  137641. if( p ){
  137642. sqlite3ExprDelete(db, p->pFilter);
  137643. sqlite3ExprListDelete(db, p->pPartition);
  137644. sqlite3ExprListDelete(db, p->pOrderBy);
  137645. sqlite3ExprDelete(db, p->pEnd);
  137646. sqlite3ExprDelete(db, p->pStart);
  137647. sqlite3DbFree(db, p->zName);
  137648. sqlite3DbFree(db, p->zBase);
  137649. sqlite3DbFree(db, p);
  137650. }
  137651. }
  137652. /*
  137653. ** Free the linked list of Window objects starting at the second argument.
  137654. */
  137655. SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p){
  137656. while( p ){
  137657. Window *pNext = p->pNextWin;
  137658. sqlite3WindowDelete(db, p);
  137659. p = pNext;
  137660. }
  137661. }
  137662. /*
  137663. ** The argument expression is an PRECEDING or FOLLOWING offset. The
  137664. ** value should be a non-negative integer. If the value is not a
  137665. ** constant, change it to NULL. The fact that it is then a non-negative
  137666. ** integer will be caught later. But it is important not to leave
  137667. ** variable values in the expression tree.
  137668. */
  137669. static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
  137670. if( 0==sqlite3ExprIsConstant(pExpr) ){
  137671. if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
  137672. sqlite3ExprDelete(pParse->db, pExpr);
  137673. pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
  137674. }
  137675. return pExpr;
  137676. }
  137677. /*
  137678. ** Allocate and return a new Window object describing a Window Definition.
  137679. */
  137680. SQLITE_PRIVATE Window *sqlite3WindowAlloc(
  137681. Parse *pParse, /* Parsing context */
  137682. int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
  137683. int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
  137684. Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
  137685. int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
  137686. Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
  137687. u8 eExclude /* EXCLUDE clause */
  137688. ){
  137689. Window *pWin = 0;
  137690. int bImplicitFrame = 0;
  137691. /* Parser assures the following: */
  137692. assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
  137693. assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
  137694. || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
  137695. assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
  137696. || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
  137697. assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
  137698. assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
  137699. if( eType==0 ){
  137700. bImplicitFrame = 1;
  137701. eType = TK_RANGE;
  137702. }
  137703. /* Additionally, the
  137704. ** starting boundary type may not occur earlier in the following list than
  137705. ** the ending boundary type:
  137706. **
  137707. ** UNBOUNDED PRECEDING
  137708. ** <expr> PRECEDING
  137709. ** CURRENT ROW
  137710. ** <expr> FOLLOWING
  137711. ** UNBOUNDED FOLLOWING
  137712. **
  137713. ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
  137714. ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
  137715. ** frame boundary.
  137716. */
  137717. if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
  137718. || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
  137719. ){
  137720. sqlite3ErrorMsg(pParse, "unsupported frame specification");
  137721. goto windowAllocErr;
  137722. }
  137723. pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  137724. if( pWin==0 ) goto windowAllocErr;
  137725. pWin->eFrmType = eType;
  137726. pWin->eStart = eStart;
  137727. pWin->eEnd = eEnd;
  137728. if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
  137729. eExclude = TK_NO;
  137730. }
  137731. pWin->eExclude = eExclude;
  137732. pWin->bImplicitFrame = bImplicitFrame;
  137733. pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
  137734. pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
  137735. return pWin;
  137736. windowAllocErr:
  137737. sqlite3ExprDelete(pParse->db, pEnd);
  137738. sqlite3ExprDelete(pParse->db, pStart);
  137739. return 0;
  137740. }
  137741. /*
  137742. ** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
  137743. ** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
  137744. ** equivalent nul-terminated string.
  137745. */
  137746. SQLITE_PRIVATE Window *sqlite3WindowAssemble(
  137747. Parse *pParse,
  137748. Window *pWin,
  137749. ExprList *pPartition,
  137750. ExprList *pOrderBy,
  137751. Token *pBase
  137752. ){
  137753. if( pWin ){
  137754. pWin->pPartition = pPartition;
  137755. pWin->pOrderBy = pOrderBy;
  137756. if( pBase ){
  137757. pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
  137758. }
  137759. }else{
  137760. sqlite3ExprListDelete(pParse->db, pPartition);
  137761. sqlite3ExprListDelete(pParse->db, pOrderBy);
  137762. }
  137763. return pWin;
  137764. }
  137765. /*
  137766. ** Window *pWin has just been created from a WINDOW clause. Tokne pBase
  137767. ** is the base window. Earlier windows from the same WINDOW clause are
  137768. ** stored in the linked list starting at pWin->pNextWin. This function
  137769. ** either updates *pWin according to the base specification, or else
  137770. ** leaves an error in pParse.
  137771. */
  137772. SQLITE_PRIVATE void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
  137773. if( pWin->zBase ){
  137774. sqlite3 *db = pParse->db;
  137775. Window *pExist = windowFind(pParse, pList, pWin->zBase);
  137776. if( pExist ){
  137777. const char *zErr = 0;
  137778. /* Check for errors */
  137779. if( pWin->pPartition ){
  137780. zErr = "PARTITION clause";
  137781. }else if( pExist->pOrderBy && pWin->pOrderBy ){
  137782. zErr = "ORDER BY clause";
  137783. }else if( pExist->bImplicitFrame==0 ){
  137784. zErr = "frame specification";
  137785. }
  137786. if( zErr ){
  137787. sqlite3ErrorMsg(pParse,
  137788. "cannot override %s of window: %s", zErr, pWin->zBase
  137789. );
  137790. }else{
  137791. pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
  137792. if( pExist->pOrderBy ){
  137793. assert( pWin->pOrderBy==0 );
  137794. pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
  137795. }
  137796. sqlite3DbFree(db, pWin->zBase);
  137797. pWin->zBase = 0;
  137798. }
  137799. }
  137800. }
  137801. }
  137802. /*
  137803. ** Attach window object pWin to expression p.
  137804. */
  137805. SQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
  137806. if( p ){
  137807. assert( p->op==TK_FUNCTION );
  137808. /* This routine is only called for the parser. If pWin was not
  137809. ** allocated due to an OOM, then the parser would fail before ever
  137810. ** invoking this routine */
  137811. if( ALWAYS(pWin) ){
  137812. p->y.pWin = pWin;
  137813. ExprSetProperty(p, EP_WinFunc);
  137814. pWin->pOwner = p;
  137815. if( p->flags & EP_Distinct ){
  137816. sqlite3ErrorMsg(pParse,
  137817. "DISTINCT is not supported for window functions");
  137818. }
  137819. }
  137820. }else{
  137821. sqlite3WindowDelete(pParse->db, pWin);
  137822. }
  137823. }
  137824. /*
  137825. ** Return 0 if the two window objects are identical, or non-zero otherwise.
  137826. ** Identical window objects can be processed in a single scan.
  137827. */
  137828. SQLITE_PRIVATE int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2){
  137829. if( p1->eFrmType!=p2->eFrmType ) return 1;
  137830. if( p1->eStart!=p2->eStart ) return 1;
  137831. if( p1->eEnd!=p2->eEnd ) return 1;
  137832. if( p1->eExclude!=p2->eExclude ) return 1;
  137833. if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
  137834. if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
  137835. if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
  137836. if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
  137837. return 0;
  137838. }
  137839. /*
  137840. ** This is called by code in select.c before it calls sqlite3WhereBegin()
  137841. ** to begin iterating through the sub-query results. It is used to allocate
  137842. ** and initialize registers and cursors used by sqlite3WindowCodeStep().
  137843. */
  137844. SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
  137845. Window *pWin;
  137846. Vdbe *v = sqlite3GetVdbe(pParse);
  137847. /* Allocate registers to use for PARTITION BY values, if any. Initialize
  137848. ** said registers to NULL. */
  137849. if( pMWin->pPartition ){
  137850. int nExpr = pMWin->pPartition->nExpr;
  137851. pMWin->regPart = pParse->nMem+1;
  137852. pParse->nMem += nExpr;
  137853. sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
  137854. }
  137855. pMWin->regOne = ++pParse->nMem;
  137856. sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
  137857. if( pMWin->eExclude ){
  137858. pMWin->regStartRowid = ++pParse->nMem;
  137859. pMWin->regEndRowid = ++pParse->nMem;
  137860. pMWin->csrApp = pParse->nTab++;
  137861. sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
  137862. sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
  137863. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
  137864. return;
  137865. }
  137866. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  137867. FuncDef *p = pWin->pFunc;
  137868. if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
  137869. /* The inline versions of min() and max() require a single ephemeral
  137870. ** table and 3 registers. The registers are used as follows:
  137871. **
  137872. ** regApp+0: slot to copy min()/max() argument to for MakeRecord
  137873. ** regApp+1: integer value used to ensure keys are unique
  137874. ** regApp+2: output of MakeRecord
  137875. */
  137876. ExprList *pList = pWin->pOwner->x.pList;
  137877. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
  137878. pWin->csrApp = pParse->nTab++;
  137879. pWin->regApp = pParse->nMem+1;
  137880. pParse->nMem += 3;
  137881. if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
  137882. assert( pKeyInfo->aSortOrder[0]==0 );
  137883. pKeyInfo->aSortOrder[0] = 1;
  137884. }
  137885. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
  137886. sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  137887. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  137888. }
  137889. else if( p->zName==nth_valueName || p->zName==first_valueName ){
  137890. /* Allocate two registers at pWin->regApp. These will be used to
  137891. ** store the start and end index of the current frame. */
  137892. pWin->regApp = pParse->nMem+1;
  137893. pWin->csrApp = pParse->nTab++;
  137894. pParse->nMem += 2;
  137895. sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
  137896. }
  137897. else if( p->zName==leadName || p->zName==lagName ){
  137898. pWin->csrApp = pParse->nTab++;
  137899. sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
  137900. }
  137901. }
  137902. }
  137903. #define WINDOW_STARTING_INT 0
  137904. #define WINDOW_ENDING_INT 1
  137905. #define WINDOW_NTH_VALUE_INT 2
  137906. #define WINDOW_STARTING_NUM 3
  137907. #define WINDOW_ENDING_NUM 4
  137908. /*
  137909. ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
  137910. ** value of the second argument to nth_value() (eCond==2) has just been
  137911. ** evaluated and the result left in register reg. This function generates VM
  137912. ** code to check that the value is a non-negative integer and throws an
  137913. ** exception if it is not.
  137914. */
  137915. static void windowCheckValue(Parse *pParse, int reg, int eCond){
  137916. static const char *azErr[] = {
  137917. "frame starting offset must be a non-negative integer",
  137918. "frame ending offset must be a non-negative integer",
  137919. "second argument to nth_value must be a positive integer",
  137920. "frame starting offset must be a non-negative number",
  137921. "frame ending offset must be a non-negative number",
  137922. };
  137923. static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
  137924. Vdbe *v = sqlite3GetVdbe(pParse);
  137925. int regZero = sqlite3GetTempReg(pParse);
  137926. assert( eCond>=0 && eCond<ArraySize(azErr) );
  137927. sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
  137928. if( eCond>=WINDOW_STARTING_NUM ){
  137929. int regString = sqlite3GetTempReg(pParse);
  137930. sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
  137931. sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
  137932. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
  137933. VdbeCoverage(v);
  137934. assert( eCond==3 || eCond==4 );
  137935. VdbeCoverageIf(v, eCond==3);
  137936. VdbeCoverageIf(v, eCond==4);
  137937. }else{
  137938. sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
  137939. VdbeCoverage(v);
  137940. assert( eCond==0 || eCond==1 || eCond==2 );
  137941. VdbeCoverageIf(v, eCond==0);
  137942. VdbeCoverageIf(v, eCond==1);
  137943. VdbeCoverageIf(v, eCond==2);
  137944. }
  137945. sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
  137946. VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
  137947. VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */
  137948. VdbeCoverageNeverNullIf(v, eCond==2);
  137949. VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
  137950. VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */
  137951. sqlite3MayAbort(pParse);
  137952. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
  137953. sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
  137954. sqlite3ReleaseTempReg(pParse, regZero);
  137955. }
  137956. /*
  137957. ** Return the number of arguments passed to the window-function associated
  137958. ** with the object passed as the only argument to this function.
  137959. */
  137960. static int windowArgCount(Window *pWin){
  137961. ExprList *pList = pWin->pOwner->x.pList;
  137962. return (pList ? pList->nExpr : 0);
  137963. }
  137964. /*
  137965. ** Generate VM code to invoke either xStep() (if bInverse is 0) or
  137966. ** xInverse (if bInverse is non-zero) for each window function in the
  137967. ** linked list starting at pMWin. Or, for built-in window functions
  137968. ** that do not use the standard function API, generate the required
  137969. ** inline VM code.
  137970. **
  137971. ** If argument csr is greater than or equal to 0, then argument reg is
  137972. ** the first register in an array of registers guaranteed to be large
  137973. ** enough to hold the array of arguments for each function. In this case
  137974. ** the arguments are extracted from the current row of csr into the
  137975. ** array of registers before invoking OP_AggStep or OP_AggInverse
  137976. **
  137977. ** Or, if csr is less than zero, then the array of registers at reg is
  137978. ** already populated with all columns from the current row of the sub-query.
  137979. **
  137980. ** If argument regPartSize is non-zero, then it is a register containing the
  137981. ** number of rows in the current partition.
  137982. */
  137983. static void windowAggStep(
  137984. Parse *pParse,
  137985. Window *pMWin, /* Linked list of window functions */
  137986. int csr, /* Read arguments from this cursor */
  137987. int bInverse, /* True to invoke xInverse instead of xStep */
  137988. int reg /* Array of registers */
  137989. ){
  137990. Vdbe *v = sqlite3GetVdbe(pParse);
  137991. Window *pWin;
  137992. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  137993. FuncDef *pFunc = pWin->pFunc;
  137994. int regArg;
  137995. int nArg = windowArgCount(pWin);
  137996. int i;
  137997. for(i=0; i<nArg; i++){
  137998. if( i!=1 || pFunc->zName!=nth_valueName ){
  137999. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
  138000. }else{
  138001. sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
  138002. }
  138003. }
  138004. regArg = reg;
  138005. if( pMWin->regStartRowid==0
  138006. && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
  138007. && (pWin->eStart!=TK_UNBOUNDED)
  138008. ){
  138009. int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
  138010. VdbeCoverage(v);
  138011. if( bInverse==0 ){
  138012. sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
  138013. sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
  138014. sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
  138015. sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
  138016. }else{
  138017. sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
  138018. VdbeCoverageNeverTaken(v);
  138019. sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
  138020. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  138021. }
  138022. sqlite3VdbeJumpHere(v, addrIsNull);
  138023. }else if( pWin->regApp ){
  138024. assert( pFunc->zName==nth_valueName
  138025. || pFunc->zName==first_valueName
  138026. );
  138027. assert( bInverse==0 || bInverse==1 );
  138028. sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
  138029. }else if( pFunc->xSFunc!=noopStepFunc ){
  138030. int addrIf = 0;
  138031. if( pWin->pFilter ){
  138032. int regTmp;
  138033. assert( nArg==0 || nArg==pWin->pOwner->x.pList->nExpr );
  138034. assert( nArg || pWin->pOwner->x.pList==0 );
  138035. regTmp = sqlite3GetTempReg(pParse);
  138036. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
  138037. addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
  138038. VdbeCoverage(v);
  138039. sqlite3ReleaseTempReg(pParse, regTmp);
  138040. }
  138041. if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  138042. CollSeq *pColl;
  138043. assert( nArg>0 );
  138044. pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
  138045. sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
  138046. }
  138047. sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
  138048. bInverse, regArg, pWin->regAccum);
  138049. sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
  138050. sqlite3VdbeChangeP5(v, (u8)nArg);
  138051. if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
  138052. }
  138053. }
  138054. }
  138055. typedef struct WindowCodeArg WindowCodeArg;
  138056. typedef struct WindowCsrAndReg WindowCsrAndReg;
  138057. struct WindowCsrAndReg {
  138058. int csr;
  138059. int reg;
  138060. };
  138061. struct WindowCodeArg {
  138062. Parse *pParse;
  138063. Window *pMWin;
  138064. Vdbe *pVdbe;
  138065. int regGosub;
  138066. int addrGosub;
  138067. int regArg;
  138068. int eDelete;
  138069. WindowCsrAndReg start;
  138070. WindowCsrAndReg current;
  138071. WindowCsrAndReg end;
  138072. };
  138073. /*
  138074. ** Values that may be passed as the second argument to windowCodeOp().
  138075. */
  138076. #define WINDOW_RETURN_ROW 1
  138077. #define WINDOW_AGGINVERSE 2
  138078. #define WINDOW_AGGSTEP 3
  138079. /*
  138080. ** Generate VM code to read the window frames peer values from cursor csr into
  138081. ** an array of registers starting at reg.
  138082. */
  138083. static void windowReadPeerValues(
  138084. WindowCodeArg *p,
  138085. int csr,
  138086. int reg
  138087. ){
  138088. Window *pMWin = p->pMWin;
  138089. ExprList *pOrderBy = pMWin->pOrderBy;
  138090. if( pOrderBy ){
  138091. Vdbe *v = sqlite3GetVdbe(p->pParse);
  138092. ExprList *pPart = pMWin->pPartition;
  138093. int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
  138094. int i;
  138095. for(i=0; i<pOrderBy->nExpr; i++){
  138096. sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
  138097. }
  138098. }
  138099. }
  138100. /*
  138101. ** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
  138102. ** (bFin==1) for each window function in the linked list starting at
  138103. ** pMWin. Or, for built-in window-functions that do not use the standard
  138104. ** API, generate the equivalent VM code.
  138105. */
  138106. static void windowAggFinal(WindowCodeArg *p, int bFin){
  138107. Parse *pParse = p->pParse;
  138108. Window *pMWin = p->pMWin;
  138109. Vdbe *v = sqlite3GetVdbe(pParse);
  138110. Window *pWin;
  138111. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138112. if( pMWin->regStartRowid==0
  138113. && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
  138114. && (pWin->eStart!=TK_UNBOUNDED)
  138115. ){
  138116. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  138117. sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
  138118. VdbeCoverage(v);
  138119. sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
  138120. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  138121. }else if( pWin->regApp ){
  138122. assert( pMWin->regStartRowid==0 );
  138123. }else{
  138124. int nArg = windowArgCount(pWin);
  138125. if( bFin ){
  138126. sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
  138127. sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
  138128. sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
  138129. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  138130. }else{
  138131. sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
  138132. sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
  138133. }
  138134. }
  138135. }
  138136. }
  138137. /*
  138138. ** Generate code to calculate the current values of all window functions in the
  138139. ** p->pMWin list by doing a full scan of the current window frame. Store the
  138140. ** results in the Window.regResult registers, ready to return the upper
  138141. ** layer.
  138142. */
  138143. static void windowFullScan(WindowCodeArg *p){
  138144. Window *pWin;
  138145. Parse *pParse = p->pParse;
  138146. Window *pMWin = p->pMWin;
  138147. Vdbe *v = p->pVdbe;
  138148. int regCRowid = 0; /* Current rowid value */
  138149. int regCPeer = 0; /* Current peer values */
  138150. int regRowid = 0; /* AggStep rowid value */
  138151. int regPeer = 0; /* AggStep peer values */
  138152. int nPeer;
  138153. int lblNext;
  138154. int lblBrk;
  138155. int addrNext;
  138156. int csr = pMWin->csrApp;
  138157. nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
  138158. lblNext = sqlite3VdbeMakeLabel(pParse);
  138159. lblBrk = sqlite3VdbeMakeLabel(pParse);
  138160. regCRowid = sqlite3GetTempReg(pParse);
  138161. regRowid = sqlite3GetTempReg(pParse);
  138162. if( nPeer ){
  138163. regCPeer = sqlite3GetTempRange(pParse, nPeer);
  138164. regPeer = sqlite3GetTempRange(pParse, nPeer);
  138165. }
  138166. sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
  138167. windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
  138168. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138169. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  138170. }
  138171. sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
  138172. VdbeCoverage(v);
  138173. addrNext = sqlite3VdbeCurrentAddr(v);
  138174. sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
  138175. sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
  138176. VdbeCoverageNeverNull(v);
  138177. if( pMWin->eExclude==TK_CURRENT ){
  138178. sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
  138179. VdbeCoverageNeverNull(v);
  138180. }else if( pMWin->eExclude!=TK_NO ){
  138181. int addr;
  138182. int addrEq = 0;
  138183. KeyInfo *pKeyInfo = 0;
  138184. if( pMWin->pOrderBy ){
  138185. pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
  138186. }
  138187. if( pMWin->eExclude==TK_TIES ){
  138188. addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
  138189. VdbeCoverageNeverNull(v);
  138190. }
  138191. if( pKeyInfo ){
  138192. windowReadPeerValues(p, csr, regPeer);
  138193. sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
  138194. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  138195. addr = sqlite3VdbeCurrentAddr(v)+1;
  138196. sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
  138197. VdbeCoverageEqNe(v);
  138198. }else{
  138199. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
  138200. }
  138201. if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
  138202. }
  138203. windowAggStep(pParse, pMWin, csr, 0, p->regArg);
  138204. sqlite3VdbeResolveLabel(v, lblNext);
  138205. sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
  138206. VdbeCoverage(v);
  138207. sqlite3VdbeJumpHere(v, addrNext-1);
  138208. sqlite3VdbeJumpHere(v, addrNext+1);
  138209. sqlite3ReleaseTempReg(pParse, regRowid);
  138210. sqlite3ReleaseTempReg(pParse, regCRowid);
  138211. if( nPeer ){
  138212. sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
  138213. sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
  138214. }
  138215. windowAggFinal(p, 1);
  138216. }
  138217. /*
  138218. ** Invoke the sub-routine at regGosub (generated by code in select.c) to
  138219. ** return the current row of Window.iEphCsr. If all window functions are
  138220. ** aggregate window functions that use the standard API, a single
  138221. ** OP_Gosub instruction is all that this routine generates. Extra VM code
  138222. ** for per-row processing is only generated for the following built-in window
  138223. ** functions:
  138224. **
  138225. ** nth_value()
  138226. ** first_value()
  138227. ** lag()
  138228. ** lead()
  138229. */
  138230. static void windowReturnOneRow(WindowCodeArg *p){
  138231. Window *pMWin = p->pMWin;
  138232. Vdbe *v = p->pVdbe;
  138233. if( pMWin->regStartRowid ){
  138234. windowFullScan(p);
  138235. }else{
  138236. Parse *pParse = p->pParse;
  138237. Window *pWin;
  138238. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138239. FuncDef *pFunc = pWin->pFunc;
  138240. if( pFunc->zName==nth_valueName
  138241. || pFunc->zName==first_valueName
  138242. ){
  138243. int csr = pWin->csrApp;
  138244. int lbl = sqlite3VdbeMakeLabel(pParse);
  138245. int tmpReg = sqlite3GetTempReg(pParse);
  138246. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  138247. if( pFunc->zName==nth_valueName ){
  138248. sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
  138249. windowCheckValue(pParse, tmpReg, 2);
  138250. }else{
  138251. sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
  138252. }
  138253. sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
  138254. sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
  138255. VdbeCoverageNeverNull(v);
  138256. sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
  138257. VdbeCoverageNeverTaken(v);
  138258. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
  138259. sqlite3VdbeResolveLabel(v, lbl);
  138260. sqlite3ReleaseTempReg(pParse, tmpReg);
  138261. }
  138262. else if( pFunc->zName==leadName || pFunc->zName==lagName ){
  138263. int nArg = pWin->pOwner->x.pList->nExpr;
  138264. int csr = pWin->csrApp;
  138265. int lbl = sqlite3VdbeMakeLabel(pParse);
  138266. int tmpReg = sqlite3GetTempReg(pParse);
  138267. int iEph = pMWin->iEphCsr;
  138268. if( nArg<3 ){
  138269. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  138270. }else{
  138271. sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
  138272. }
  138273. sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
  138274. if( nArg<2 ){
  138275. int val = (pFunc->zName==leadName ? 1 : -1);
  138276. sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
  138277. }else{
  138278. int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
  138279. int tmpReg2 = sqlite3GetTempReg(pParse);
  138280. sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
  138281. sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
  138282. sqlite3ReleaseTempReg(pParse, tmpReg2);
  138283. }
  138284. sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
  138285. VdbeCoverage(v);
  138286. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
  138287. sqlite3VdbeResolveLabel(v, lbl);
  138288. sqlite3ReleaseTempReg(pParse, tmpReg);
  138289. }
  138290. }
  138291. }
  138292. sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
  138293. }
  138294. /*
  138295. ** Generate code to set the accumulator register for each window function
  138296. ** in the linked list passed as the second argument to NULL. And perform
  138297. ** any equivalent initialization required by any built-in window functions
  138298. ** in the list.
  138299. */
  138300. static int windowInitAccum(Parse *pParse, Window *pMWin){
  138301. Vdbe *v = sqlite3GetVdbe(pParse);
  138302. int regArg;
  138303. int nArg = 0;
  138304. Window *pWin;
  138305. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138306. FuncDef *pFunc = pWin->pFunc;
  138307. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  138308. nArg = MAX(nArg, windowArgCount(pWin));
  138309. if( pMWin->regStartRowid==0 ){
  138310. if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
  138311. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
  138312. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  138313. }
  138314. if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
  138315. assert( pWin->eStart!=TK_UNBOUNDED );
  138316. sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
  138317. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  138318. }
  138319. }
  138320. }
  138321. regArg = pParse->nMem+1;
  138322. pParse->nMem += nArg;
  138323. return regArg;
  138324. }
  138325. /*
  138326. ** Return true if the current frame should be cached in the ephemeral table,
  138327. ** even if there are no xInverse() calls required.
  138328. */
  138329. static int windowCacheFrame(Window *pMWin){
  138330. Window *pWin;
  138331. if( pMWin->regStartRowid ) return 1;
  138332. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  138333. FuncDef *pFunc = pWin->pFunc;
  138334. if( (pFunc->zName==nth_valueName)
  138335. || (pFunc->zName==first_valueName)
  138336. || (pFunc->zName==leadName)
  138337. || (pFunc->zName==lagName)
  138338. ){
  138339. return 1;
  138340. }
  138341. }
  138342. return 0;
  138343. }
  138344. /*
  138345. ** regOld and regNew are each the first register in an array of size
  138346. ** pOrderBy->nExpr. This function generates code to compare the two
  138347. ** arrays of registers using the collation sequences and other comparison
  138348. ** parameters specified by pOrderBy.
  138349. **
  138350. ** If the two arrays are not equal, the contents of regNew is copied to
  138351. ** regOld and control falls through. Otherwise, if the contents of the arrays
  138352. ** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
  138353. */
  138354. static void windowIfNewPeer(
  138355. Parse *pParse,
  138356. ExprList *pOrderBy,
  138357. int regNew, /* First in array of new values */
  138358. int regOld, /* First in array of old values */
  138359. int addr /* Jump here */
  138360. ){
  138361. Vdbe *v = sqlite3GetVdbe(pParse);
  138362. if( pOrderBy ){
  138363. int nVal = pOrderBy->nExpr;
  138364. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
  138365. sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
  138366. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  138367. sqlite3VdbeAddOp3(v, OP_Jump,
  138368. sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
  138369. );
  138370. VdbeCoverageEqNe(v);
  138371. sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
  138372. }else{
  138373. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  138374. }
  138375. }
  138376. /*
  138377. ** This function is called as part of generating VM programs for RANGE
  138378. ** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
  138379. ** the ORDER BY term in the window, it generates code equivalent to:
  138380. **
  138381. ** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
  138382. **
  138383. ** A special type of arithmetic is used such that if csr.peerVal is not
  138384. ** a numeric type (real or integer), then the result of the addition is
  138385. ** a copy of csr1.peerVal.
  138386. */
  138387. static void windowCodeRangeTest(
  138388. WindowCodeArg *p,
  138389. int op, /* OP_Ge or OP_Gt */
  138390. int csr1,
  138391. int regVal,
  138392. int csr2,
  138393. int lbl
  138394. ){
  138395. Parse *pParse = p->pParse;
  138396. Vdbe *v = sqlite3GetVdbe(pParse);
  138397. int reg1 = sqlite3GetTempReg(pParse);
  138398. int reg2 = sqlite3GetTempReg(pParse);
  138399. int arith = OP_Add;
  138400. int addrGe;
  138401. int regString = ++pParse->nMem;
  138402. assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
  138403. assert( p->pMWin->pOrderBy && p->pMWin->pOrderBy->nExpr==1 );
  138404. if( p->pMWin->pOrderBy->a[0].sortOrder ){
  138405. switch( op ){
  138406. case OP_Ge: op = OP_Le; break;
  138407. case OP_Gt: op = OP_Lt; break;
  138408. default: assert( op==OP_Le ); op = OP_Ge; break;
  138409. }
  138410. arith = OP_Subtract;
  138411. }
  138412. windowReadPeerValues(p, csr1, reg1);
  138413. windowReadPeerValues(p, csr2, reg2);
  138414. /* Check if the peer value for csr1 value is a text or blob by comparing
  138415. ** it to the smallest possible string - ''. If it is, jump over the
  138416. ** OP_Add or OP_Subtract operation and proceed directly to the comparison. */
  138417. sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
  138418. addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
  138419. VdbeCoverage(v);
  138420. sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
  138421. sqlite3VdbeJumpHere(v, addrGe);
  138422. sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
  138423. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  138424. assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
  138425. testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
  138426. testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
  138427. testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
  138428. testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
  138429. sqlite3ReleaseTempReg(pParse, reg1);
  138430. sqlite3ReleaseTempReg(pParse, reg2);
  138431. }
  138432. /*
  138433. ** Helper function for sqlite3WindowCodeStep(). Each call to this function
  138434. ** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
  138435. ** operation. Refer to the header comment for sqlite3WindowCodeStep() for
  138436. ** details.
  138437. */
  138438. static int windowCodeOp(
  138439. WindowCodeArg *p, /* Context object */
  138440. int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
  138441. int regCountdown, /* Register for OP_IfPos countdown */
  138442. int jumpOnEof /* Jump here if stepped cursor reaches EOF */
  138443. ){
  138444. int csr, reg;
  138445. Parse *pParse = p->pParse;
  138446. Window *pMWin = p->pMWin;
  138447. int ret = 0;
  138448. Vdbe *v = p->pVdbe;
  138449. int addrIf = 0;
  138450. int addrContinue = 0;
  138451. int addrGoto = 0;
  138452. int bPeer = (pMWin->eFrmType!=TK_ROWS);
  138453. int lblDone = sqlite3VdbeMakeLabel(pParse);
  138454. int addrNextRange = 0;
  138455. /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
  138456. ** starts with UNBOUNDED PRECEDING. */
  138457. if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
  138458. assert( regCountdown==0 && jumpOnEof==0 );
  138459. return 0;
  138460. }
  138461. if( regCountdown>0 ){
  138462. if( pMWin->eFrmType==TK_RANGE ){
  138463. addrNextRange = sqlite3VdbeCurrentAddr(v);
  138464. assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
  138465. if( op==WINDOW_AGGINVERSE ){
  138466. if( pMWin->eStart==TK_FOLLOWING ){
  138467. windowCodeRangeTest(
  138468. p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
  138469. );
  138470. }else{
  138471. windowCodeRangeTest(
  138472. p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
  138473. );
  138474. }
  138475. }else{
  138476. windowCodeRangeTest(
  138477. p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
  138478. );
  138479. }
  138480. }else{
  138481. addrIf = sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, 0, 1);
  138482. VdbeCoverage(v);
  138483. }
  138484. }
  138485. if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
  138486. windowAggFinal(p, 0);
  138487. }
  138488. addrContinue = sqlite3VdbeCurrentAddr(v);
  138489. switch( op ){
  138490. case WINDOW_RETURN_ROW:
  138491. csr = p->current.csr;
  138492. reg = p->current.reg;
  138493. windowReturnOneRow(p);
  138494. break;
  138495. case WINDOW_AGGINVERSE:
  138496. csr = p->start.csr;
  138497. reg = p->start.reg;
  138498. if( pMWin->regStartRowid ){
  138499. assert( pMWin->regEndRowid );
  138500. sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
  138501. }else{
  138502. windowAggStep(pParse, pMWin, csr, 1, p->regArg);
  138503. }
  138504. break;
  138505. default:
  138506. assert( op==WINDOW_AGGSTEP );
  138507. csr = p->end.csr;
  138508. reg = p->end.reg;
  138509. if( pMWin->regStartRowid ){
  138510. assert( pMWin->regEndRowid );
  138511. sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
  138512. }else{
  138513. windowAggStep(pParse, pMWin, csr, 0, p->regArg);
  138514. }
  138515. break;
  138516. }
  138517. if( op==p->eDelete ){
  138518. sqlite3VdbeAddOp1(v, OP_Delete, csr);
  138519. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  138520. }
  138521. if( jumpOnEof ){
  138522. sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
  138523. VdbeCoverage(v);
  138524. ret = sqlite3VdbeAddOp0(v, OP_Goto);
  138525. }else{
  138526. sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
  138527. VdbeCoverage(v);
  138528. if( bPeer ){
  138529. addrGoto = sqlite3VdbeAddOp0(v, OP_Goto);
  138530. }
  138531. }
  138532. if( bPeer ){
  138533. int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
  138534. int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
  138535. windowReadPeerValues(p, csr, regTmp);
  138536. windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
  138537. sqlite3ReleaseTempRange(pParse, regTmp, nReg);
  138538. }
  138539. if( addrNextRange ){
  138540. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
  138541. }
  138542. sqlite3VdbeResolveLabel(v, lblDone);
  138543. if( addrGoto ) sqlite3VdbeJumpHere(v, addrGoto);
  138544. if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
  138545. return ret;
  138546. }
  138547. /*
  138548. ** Allocate and return a duplicate of the Window object indicated by the
  138549. ** third argument. Set the Window.pOwner field of the new object to
  138550. ** pOwner.
  138551. */
  138552. SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
  138553. Window *pNew = 0;
  138554. if( ALWAYS(p) ){
  138555. pNew = sqlite3DbMallocZero(db, sizeof(Window));
  138556. if( pNew ){
  138557. pNew->zName = sqlite3DbStrDup(db, p->zName);
  138558. pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
  138559. pNew->pFunc = p->pFunc;
  138560. pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
  138561. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
  138562. pNew->eFrmType = p->eFrmType;
  138563. pNew->eEnd = p->eEnd;
  138564. pNew->eStart = p->eStart;
  138565. pNew->eExclude = p->eExclude;
  138566. pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
  138567. pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
  138568. pNew->pOwner = pOwner;
  138569. }
  138570. }
  138571. return pNew;
  138572. }
  138573. /*
  138574. ** Return a copy of the linked list of Window objects passed as the
  138575. ** second argument.
  138576. */
  138577. SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
  138578. Window *pWin;
  138579. Window *pRet = 0;
  138580. Window **pp = &pRet;
  138581. for(pWin=p; pWin; pWin=pWin->pNextWin){
  138582. *pp = sqlite3WindowDup(db, 0, pWin);
  138583. if( *pp==0 ) break;
  138584. pp = &((*pp)->pNextWin);
  138585. }
  138586. return pRet;
  138587. }
  138588. /*
  138589. ** Return true if it can be determined at compile time that expression
  138590. ** pExpr evaluates to a value that, when cast to an integer, is greater
  138591. ** than zero. False otherwise.
  138592. **
  138593. ** If an OOM error occurs, this function sets the Parse.db.mallocFailed
  138594. ** flag and returns zero.
  138595. */
  138596. static int windowExprGtZero(Parse *pParse, Expr *pExpr){
  138597. int ret = 0;
  138598. sqlite3 *db = pParse->db;
  138599. sqlite3_value *pVal = 0;
  138600. sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
  138601. if( pVal && sqlite3_value_int(pVal)>0 ){
  138602. ret = 1;
  138603. }
  138604. sqlite3ValueFree(pVal);
  138605. return ret;
  138606. }
  138607. /*
  138608. ** sqlite3WhereBegin() has already been called for the SELECT statement
  138609. ** passed as the second argument when this function is invoked. It generates
  138610. ** code to populate the Window.regResult register for each window function
  138611. ** and invoke the sub-routine at instruction addrGosub once for each row.
  138612. ** sqlite3WhereEnd() is always called before returning.
  138613. **
  138614. ** This function handles several different types of window frames, which
  138615. ** require slightly different processing. The following pseudo code is
  138616. ** used to implement window frames of the form:
  138617. **
  138618. ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
  138619. **
  138620. ** Other window frame types use variants of the following:
  138621. **
  138622. ** ... loop started by sqlite3WhereBegin() ...
  138623. ** if( new partition ){
  138624. ** Gosub flush
  138625. ** }
  138626. ** Insert new row into eph table.
  138627. **
  138628. ** if( first row of partition ){
  138629. ** // Rewind three cursors, all open on the eph table.
  138630. ** Rewind(csrEnd);
  138631. ** Rewind(csrStart);
  138632. ** Rewind(csrCurrent);
  138633. **
  138634. ** regEnd = <expr2> // FOLLOWING expression
  138635. ** regStart = <expr1> // PRECEDING expression
  138636. ** }else{
  138637. ** // First time this branch is taken, the eph table contains two
  138638. ** // rows. The first row in the partition, which all three cursors
  138639. ** // currently point to, and the following row.
  138640. ** AGGSTEP
  138641. ** if( (regEnd--)<=0 ){
  138642. ** RETURN_ROW
  138643. ** if( (regStart--)<=0 ){
  138644. ** AGGINVERSE
  138645. ** }
  138646. ** }
  138647. ** }
  138648. ** }
  138649. ** flush:
  138650. ** AGGSTEP
  138651. ** while( 1 ){
  138652. ** RETURN ROW
  138653. ** if( csrCurrent is EOF ) break;
  138654. ** if( (regStart--)<=0 ){
  138655. ** AggInverse(csrStart)
  138656. ** Next(csrStart)
  138657. ** }
  138658. ** }
  138659. **
  138660. ** The pseudo-code above uses the following shorthand:
  138661. **
  138662. ** AGGSTEP: invoke the aggregate xStep() function for each window function
  138663. ** with arguments read from the current row of cursor csrEnd, then
  138664. ** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
  138665. **
  138666. ** RETURN_ROW: return a row to the caller based on the contents of the
  138667. ** current row of csrCurrent and the current state of all
  138668. ** aggregates. Then step cursor csrCurrent forward one row.
  138669. **
  138670. ** AGGINVERSE: invoke the aggregate xInverse() function for each window
  138671. ** functions with arguments read from the current row of cursor
  138672. ** csrStart. Then step csrStart forward one row.
  138673. **
  138674. ** There are two other ROWS window frames that are handled significantly
  138675. ** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
  138676. ** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
  138677. ** cases because they change the order in which the three cursors (csrStart,
  138678. ** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
  138679. ** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
  138680. ** three.
  138681. **
  138682. ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
  138683. **
  138684. ** ... loop started by sqlite3WhereBegin() ...
  138685. ** if( new partition ){
  138686. ** Gosub flush
  138687. ** }
  138688. ** Insert new row into eph table.
  138689. ** if( first row of partition ){
  138690. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  138691. ** regEnd = <expr2>
  138692. ** regStart = <expr1>
  138693. ** }else{
  138694. ** if( (regEnd--)<=0 ){
  138695. ** AGGSTEP
  138696. ** }
  138697. ** RETURN_ROW
  138698. ** if( (regStart--)<=0 ){
  138699. ** AGGINVERSE
  138700. ** }
  138701. ** }
  138702. ** }
  138703. ** flush:
  138704. ** if( (regEnd--)<=0 ){
  138705. ** AGGSTEP
  138706. ** }
  138707. ** RETURN_ROW
  138708. **
  138709. **
  138710. ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
  138711. **
  138712. ** ... loop started by sqlite3WhereBegin() ...
  138713. ** if( new partition ){
  138714. ** Gosub flush
  138715. ** }
  138716. ** Insert new row into eph table.
  138717. ** if( first row of partition ){
  138718. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  138719. ** regEnd = <expr2>
  138720. ** regStart = regEnd - <expr1>
  138721. ** }else{
  138722. ** AGGSTEP
  138723. ** if( (regEnd--)<=0 ){
  138724. ** RETURN_ROW
  138725. ** }
  138726. ** if( (regStart--)<=0 ){
  138727. ** AGGINVERSE
  138728. ** }
  138729. ** }
  138730. ** }
  138731. ** flush:
  138732. ** AGGSTEP
  138733. ** while( 1 ){
  138734. ** if( (regEnd--)<=0 ){
  138735. ** RETURN_ROW
  138736. ** if( eof ) break;
  138737. ** }
  138738. ** if( (regStart--)<=0 ){
  138739. ** AGGINVERSE
  138740. ** if( eof ) break
  138741. ** }
  138742. ** }
  138743. ** while( !eof csrCurrent ){
  138744. ** RETURN_ROW
  138745. ** }
  138746. **
  138747. ** For the most part, the patterns above are adapted to support UNBOUNDED by
  138748. ** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
  138749. ** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
  138750. ** This is optimized of course - branches that will never be taken and
  138751. ** conditions that are always true are omitted from the VM code. The only
  138752. ** exceptional case is:
  138753. **
  138754. ** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
  138755. **
  138756. ** ... loop started by sqlite3WhereBegin() ...
  138757. ** if( new partition ){
  138758. ** Gosub flush
  138759. ** }
  138760. ** Insert new row into eph table.
  138761. ** if( first row of partition ){
  138762. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  138763. ** regStart = <expr1>
  138764. ** }else{
  138765. ** AGGSTEP
  138766. ** }
  138767. ** }
  138768. ** flush:
  138769. ** AGGSTEP
  138770. ** while( 1 ){
  138771. ** if( (regStart--)<=0 ){
  138772. ** AGGINVERSE
  138773. ** if( eof ) break
  138774. ** }
  138775. ** RETURN_ROW
  138776. ** }
  138777. ** while( !eof csrCurrent ){
  138778. ** RETURN_ROW
  138779. ** }
  138780. **
  138781. ** Also requiring special handling are the cases:
  138782. **
  138783. ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
  138784. ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
  138785. **
  138786. ** when (expr1 < expr2). This is detected at runtime, not by this function.
  138787. ** To handle this case, the pseudo-code programs depicted above are modified
  138788. ** slightly to be:
  138789. **
  138790. ** ... loop started by sqlite3WhereBegin() ...
  138791. ** if( new partition ){
  138792. ** Gosub flush
  138793. ** }
  138794. ** Insert new row into eph table.
  138795. ** if( first row of partition ){
  138796. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  138797. ** regEnd = <expr2>
  138798. ** regStart = <expr1>
  138799. ** if( regEnd < regStart ){
  138800. ** RETURN_ROW
  138801. ** delete eph table contents
  138802. ** continue
  138803. ** }
  138804. ** ...
  138805. **
  138806. ** The new "continue" statement in the above jumps to the next iteration
  138807. ** of the outer loop - the one started by sqlite3WhereBegin().
  138808. **
  138809. ** The various GROUPS cases are implemented using the same patterns as
  138810. ** ROWS. The VM code is modified slightly so that:
  138811. **
  138812. ** 1. The else branch in the main loop is only taken if the row just
  138813. ** added to the ephemeral table is the start of a new group. In
  138814. ** other words, it becomes:
  138815. **
  138816. ** ... loop started by sqlite3WhereBegin() ...
  138817. ** if( new partition ){
  138818. ** Gosub flush
  138819. ** }
  138820. ** Insert new row into eph table.
  138821. ** if( first row of partition ){
  138822. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  138823. ** regEnd = <expr2>
  138824. ** regStart = <expr1>
  138825. ** }else if( new group ){
  138826. ** ...
  138827. ** }
  138828. ** }
  138829. **
  138830. ** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
  138831. ** AGGINVERSE step processes the current row of the relevant cursor and
  138832. ** all subsequent rows belonging to the same group.
  138833. **
  138834. ** RANGE window frames are a little different again. As for GROUPS, the
  138835. ** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
  138836. ** deal in groups instead of rows. As for ROWS and GROUPS, there are three
  138837. ** basic cases:
  138838. **
  138839. ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
  138840. **
  138841. ** ... loop started by sqlite3WhereBegin() ...
  138842. ** if( new partition ){
  138843. ** Gosub flush
  138844. ** }
  138845. ** Insert new row into eph table.
  138846. ** if( first row of partition ){
  138847. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  138848. ** regEnd = <expr2>
  138849. ** regStart = <expr1>
  138850. ** }else{
  138851. ** AGGSTEP
  138852. ** while( (csrCurrent.key + regEnd) < csrEnd.key ){
  138853. ** RETURN_ROW
  138854. ** while( csrStart.key + regStart) < csrCurrent.key ){
  138855. ** AGGINVERSE
  138856. ** }
  138857. ** }
  138858. ** }
  138859. ** }
  138860. ** flush:
  138861. ** AGGSTEP
  138862. ** while( 1 ){
  138863. ** RETURN ROW
  138864. ** if( csrCurrent is EOF ) break;
  138865. ** while( csrStart.key + regStart) < csrCurrent.key ){
  138866. ** AGGINVERSE
  138867. ** }
  138868. ** }
  138869. ** }
  138870. **
  138871. ** In the above notation, "csr.key" means the current value of the ORDER BY
  138872. ** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
  138873. ** or <expr PRECEDING) read from cursor csr.
  138874. **
  138875. ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
  138876. **
  138877. ** ... loop started by sqlite3WhereBegin() ...
  138878. ** if( new partition ){
  138879. ** Gosub flush
  138880. ** }
  138881. ** Insert new row into eph table.
  138882. ** if( first row of partition ){
  138883. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  138884. ** regEnd = <expr2>
  138885. ** regStart = <expr1>
  138886. ** }else{
  138887. ** if( (csrEnd.key + regEnd) <= csrCurrent.key ){
  138888. ** AGGSTEP
  138889. ** }
  138890. ** while( (csrStart.key + regStart) < csrCurrent.key ){
  138891. ** AGGINVERSE
  138892. ** }
  138893. ** RETURN_ROW
  138894. ** }
  138895. ** }
  138896. ** flush:
  138897. ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
  138898. ** AGGSTEP
  138899. ** }
  138900. ** while( (csrStart.key + regStart) < csrCurrent.key ){
  138901. ** AGGINVERSE
  138902. ** }
  138903. ** RETURN_ROW
  138904. **
  138905. ** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
  138906. **
  138907. ** ... loop started by sqlite3WhereBegin() ...
  138908. ** if( new partition ){
  138909. ** Gosub flush
  138910. ** }
  138911. ** Insert new row into eph table.
  138912. ** if( first row of partition ){
  138913. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  138914. ** regEnd = <expr2>
  138915. ** regStart = <expr1>
  138916. ** }else{
  138917. ** AGGSTEP
  138918. ** while( (csrCurrent.key + regEnd) < csrEnd.key ){
  138919. ** while( (csrCurrent.key + regStart) > csrStart.key ){
  138920. ** AGGINVERSE
  138921. ** }
  138922. ** RETURN_ROW
  138923. ** }
  138924. ** }
  138925. ** }
  138926. ** flush:
  138927. ** AGGSTEP
  138928. ** while( 1 ){
  138929. ** while( (csrCurrent.key + regStart) > csrStart.key ){
  138930. ** AGGINVERSE
  138931. ** if( eof ) break "while( 1 )" loop.
  138932. ** }
  138933. ** RETURN_ROW
  138934. ** }
  138935. ** while( !eof csrCurrent ){
  138936. ** RETURN_ROW
  138937. ** }
  138938. **
  138939. ** The text above leaves out many details. Refer to the code and comments
  138940. ** below for a more complete picture.
  138941. */
  138942. SQLITE_PRIVATE void sqlite3WindowCodeStep(
  138943. Parse *pParse, /* Parse context */
  138944. Select *p, /* Rewritten SELECT statement */
  138945. WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
  138946. int regGosub, /* Register for OP_Gosub */
  138947. int addrGosub /* OP_Gosub here to return each row */
  138948. ){
  138949. Window *pMWin = p->pWin;
  138950. ExprList *pOrderBy = pMWin->pOrderBy;
  138951. Vdbe *v = sqlite3GetVdbe(pParse);
  138952. int csrWrite; /* Cursor used to write to eph. table */
  138953. int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
  138954. int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
  138955. int iInput; /* To iterate through sub cols */
  138956. int addrNe; /* Address of OP_Ne */
  138957. int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */
  138958. int addrInteger = 0; /* Address of OP_Integer */
  138959. int addrEmpty; /* Address of OP_Rewind in flush: */
  138960. int regStart = 0; /* Value of <expr> PRECEDING */
  138961. int regEnd = 0; /* Value of <expr> FOLLOWING */
  138962. int regNew; /* Array of registers holding new input row */
  138963. int regRecord; /* regNew array in record form */
  138964. int regRowid; /* Rowid for regRecord in eph table */
  138965. int regNewPeer = 0; /* Peer values for new row (part of regNew) */
  138966. int regPeer = 0; /* Peer values for current row */
  138967. int regFlushPart = 0; /* Register for "Gosub flush_partition" */
  138968. WindowCodeArg s; /* Context object for sub-routines */
  138969. int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
  138970. assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
  138971. || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
  138972. );
  138973. assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
  138974. || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
  138975. );
  138976. assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
  138977. || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
  138978. || pMWin->eExclude==TK_NO
  138979. );
  138980. lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
  138981. /* Fill in the context object */
  138982. memset(&s, 0, sizeof(WindowCodeArg));
  138983. s.pParse = pParse;
  138984. s.pMWin = pMWin;
  138985. s.pVdbe = v;
  138986. s.regGosub = regGosub;
  138987. s.addrGosub = addrGosub;
  138988. s.current.csr = pMWin->iEphCsr;
  138989. csrWrite = s.current.csr+1;
  138990. s.start.csr = s.current.csr+2;
  138991. s.end.csr = s.current.csr+3;
  138992. /* Figure out when rows may be deleted from the ephemeral table. There
  138993. ** are four options - they may never be deleted (eDelete==0), they may
  138994. ** be deleted as soon as they are no longer part of the window frame
  138995. ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
  138996. ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
  138997. ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
  138998. switch( pMWin->eStart ){
  138999. case TK_FOLLOWING:
  139000. if( pMWin->eFrmType!=TK_RANGE
  139001. && windowExprGtZero(pParse, pMWin->pStart)
  139002. ){
  139003. s.eDelete = WINDOW_RETURN_ROW;
  139004. }
  139005. break;
  139006. case TK_UNBOUNDED:
  139007. if( windowCacheFrame(pMWin)==0 ){
  139008. if( pMWin->eEnd==TK_PRECEDING ){
  139009. if( pMWin->eFrmType!=TK_RANGE
  139010. && windowExprGtZero(pParse, pMWin->pEnd)
  139011. ){
  139012. s.eDelete = WINDOW_AGGSTEP;
  139013. }
  139014. }else{
  139015. s.eDelete = WINDOW_RETURN_ROW;
  139016. }
  139017. }
  139018. break;
  139019. default:
  139020. s.eDelete = WINDOW_AGGINVERSE;
  139021. break;
  139022. }
  139023. /* Allocate registers for the array of values from the sub-query, the
  139024. ** samve values in record form, and the rowid used to insert said record
  139025. ** into the ephemeral table. */
  139026. regNew = pParse->nMem+1;
  139027. pParse->nMem += nInput;
  139028. regRecord = ++pParse->nMem;
  139029. regRowid = ++pParse->nMem;
  139030. /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
  139031. ** clause, allocate registers to store the results of evaluating each
  139032. ** <expr>. */
  139033. if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
  139034. regStart = ++pParse->nMem;
  139035. }
  139036. if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
  139037. regEnd = ++pParse->nMem;
  139038. }
  139039. /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
  139040. ** registers to store copies of the ORDER BY expressions (peer values)
  139041. ** for the main loop, and for each cursor (start, current and end). */
  139042. if( pMWin->eFrmType!=TK_ROWS ){
  139043. int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
  139044. regNewPeer = regNew + pMWin->nBufferCol;
  139045. if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
  139046. regPeer = pParse->nMem+1; pParse->nMem += nPeer;
  139047. s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
  139048. s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
  139049. s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
  139050. }
  139051. /* Load the column values for the row returned by the sub-select
  139052. ** into an array of registers starting at regNew. Assemble them into
  139053. ** a record in register regRecord. */
  139054. for(iInput=0; iInput<nInput; iInput++){
  139055. sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
  139056. }
  139057. sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
  139058. /* An input row has just been read into an array of registers starting
  139059. ** at regNew. If the window has a PARTITION clause, this block generates
  139060. ** VM code to check if the input row is the start of a new partition.
  139061. ** If so, it does an OP_Gosub to an address to be filled in later. The
  139062. ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
  139063. if( pMWin->pPartition ){
  139064. int addr;
  139065. ExprList *pPart = pMWin->pPartition;
  139066. int nPart = pPart->nExpr;
  139067. int regNewPart = regNew + pMWin->nBufferCol;
  139068. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
  139069. regFlushPart = ++pParse->nMem;
  139070. addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
  139071. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  139072. sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
  139073. VdbeCoverageEqNe(v);
  139074. addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
  139075. VdbeComment((v, "call flush_partition"));
  139076. sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
  139077. }
  139078. /* Insert the new row into the ephemeral table */
  139079. sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
  139080. sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
  139081. addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
  139082. VdbeCoverageNeverNull(v);
  139083. /* This block is run for the first row of each partition */
  139084. s.regArg = windowInitAccum(pParse, pMWin);
  139085. if( regStart ){
  139086. sqlite3ExprCode(pParse, pMWin->pStart, regStart);
  139087. windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE ? 3 : 0));
  139088. }
  139089. if( regEnd ){
  139090. sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
  139091. windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE ? 3 : 0));
  139092. }
  139093. if( pMWin->eStart==pMWin->eEnd && regStart ){
  139094. int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
  139095. int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
  139096. VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
  139097. VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */
  139098. windowAggFinal(&s, 0);
  139099. sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
  139100. VdbeCoverageNeverTaken(v);
  139101. windowReturnOneRow(&s);
  139102. sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
  139103. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
  139104. sqlite3VdbeJumpHere(v, addrGe);
  139105. }
  139106. if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
  139107. assert( pMWin->eEnd==TK_FOLLOWING );
  139108. sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
  139109. }
  139110. if( pMWin->eStart!=TK_UNBOUNDED ){
  139111. sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
  139112. VdbeCoverageNeverTaken(v);
  139113. }
  139114. sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
  139115. VdbeCoverageNeverTaken(v);
  139116. sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
  139117. VdbeCoverageNeverTaken(v);
  139118. if( regPeer && pOrderBy ){
  139119. sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
  139120. sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
  139121. sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
  139122. sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
  139123. }
  139124. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
  139125. sqlite3VdbeJumpHere(v, addrNe);
  139126. /* Beginning of the block executed for the second and subsequent rows. */
  139127. if( regPeer ){
  139128. windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
  139129. }
  139130. if( pMWin->eStart==TK_FOLLOWING ){
  139131. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  139132. if( pMWin->eEnd!=TK_UNBOUNDED ){
  139133. if( pMWin->eFrmType==TK_RANGE ){
  139134. int lbl = sqlite3VdbeMakeLabel(pParse);
  139135. int addrNext = sqlite3VdbeCurrentAddr(v);
  139136. windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
  139137. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139138. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  139139. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
  139140. sqlite3VdbeResolveLabel(v, lbl);
  139141. }else{
  139142. windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
  139143. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139144. }
  139145. }
  139146. }else
  139147. if( pMWin->eEnd==TK_PRECEDING ){
  139148. int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
  139149. windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
  139150. if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139151. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  139152. if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139153. }else{
  139154. int addr = 0;
  139155. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  139156. if( pMWin->eEnd!=TK_UNBOUNDED ){
  139157. if( pMWin->eFrmType==TK_RANGE ){
  139158. int lbl = 0;
  139159. addr = sqlite3VdbeCurrentAddr(v);
  139160. if( regEnd ){
  139161. lbl = sqlite3VdbeMakeLabel(pParse);
  139162. windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
  139163. }
  139164. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  139165. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139166. if( regEnd ){
  139167. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  139168. sqlite3VdbeResolveLabel(v, lbl);
  139169. }
  139170. }else{
  139171. if( regEnd ){
  139172. addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
  139173. VdbeCoverage(v);
  139174. }
  139175. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  139176. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139177. if( regEnd ) sqlite3VdbeJumpHere(v, addr);
  139178. }
  139179. }
  139180. }
  139181. /* End of the main input loop */
  139182. sqlite3VdbeResolveLabel(v, lblWhereEnd);
  139183. sqlite3WhereEnd(pWInfo);
  139184. /* Fall through */
  139185. if( pMWin->pPartition ){
  139186. addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
  139187. sqlite3VdbeJumpHere(v, addrGosubFlush);
  139188. }
  139189. addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
  139190. VdbeCoverage(v);
  139191. if( pMWin->eEnd==TK_PRECEDING ){
  139192. int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
  139193. windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
  139194. if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139195. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  139196. }else if( pMWin->eStart==TK_FOLLOWING ){
  139197. int addrStart;
  139198. int addrBreak1;
  139199. int addrBreak2;
  139200. int addrBreak3;
  139201. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  139202. if( pMWin->eFrmType==TK_RANGE ){
  139203. addrStart = sqlite3VdbeCurrentAddr(v);
  139204. addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
  139205. addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
  139206. }else
  139207. if( pMWin->eEnd==TK_UNBOUNDED ){
  139208. addrStart = sqlite3VdbeCurrentAddr(v);
  139209. addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
  139210. addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
  139211. }else{
  139212. assert( pMWin->eEnd==TK_FOLLOWING );
  139213. addrStart = sqlite3VdbeCurrentAddr(v);
  139214. addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
  139215. addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
  139216. }
  139217. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
  139218. sqlite3VdbeJumpHere(v, addrBreak2);
  139219. addrStart = sqlite3VdbeCurrentAddr(v);
  139220. addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
  139221. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
  139222. sqlite3VdbeJumpHere(v, addrBreak1);
  139223. sqlite3VdbeJumpHere(v, addrBreak3);
  139224. }else{
  139225. int addrBreak;
  139226. int addrStart;
  139227. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  139228. addrStart = sqlite3VdbeCurrentAddr(v);
  139229. addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
  139230. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  139231. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
  139232. sqlite3VdbeJumpHere(v, addrBreak);
  139233. }
  139234. sqlite3VdbeJumpHere(v, addrEmpty);
  139235. sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
  139236. if( pMWin->pPartition ){
  139237. if( pMWin->regStartRowid ){
  139238. sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
  139239. sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
  139240. }
  139241. sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
  139242. sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
  139243. }
  139244. }
  139245. #endif /* SQLITE_OMIT_WINDOWFUNC */
  139246. /************** End of window.c **********************************************/
  139247. /************** Begin file parse.c *******************************************/
  139248. /*
  139249. ** 2000-05-29
  139250. **
  139251. ** The author disclaims copyright to this source code. In place of
  139252. ** a legal notice, here is a blessing:
  139253. **
  139254. ** May you do good and not evil.
  139255. ** May you find forgiveness for yourself and forgive others.
  139256. ** May you share freely, never taking more than you give.
  139257. **
  139258. *************************************************************************
  139259. ** Driver template for the LEMON parser generator.
  139260. **
  139261. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  139262. ** this template to construct a parser. The "lemon" program inserts text
  139263. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  139264. ** interstitial "-" characters) contained in this template is changed into
  139265. ** the value of the %name directive from the grammar. Otherwise, the content
  139266. ** of this template is copied straight through into the generate parser
  139267. ** source file.
  139268. **
  139269. ** The following is the concatenation of all %include directives from the
  139270. ** input grammar file:
  139271. */
  139272. /* #include <stdio.h> */
  139273. /* #include <assert.h> */
  139274. /************ Begin %include sections from the grammar ************************/
  139275. /* #include "sqliteInt.h" */
  139276. /*
  139277. ** Disable all error recovery processing in the parser push-down
  139278. ** automaton.
  139279. */
  139280. #define YYNOERRORRECOVERY 1
  139281. /*
  139282. ** Make yytestcase() the same as testcase()
  139283. */
  139284. #define yytestcase(X) testcase(X)
  139285. /*
  139286. ** Indicate that sqlite3ParserFree() will never be called with a null
  139287. ** pointer.
  139288. */
  139289. #define YYPARSEFREENEVERNULL 1
  139290. /*
  139291. ** In the amalgamation, the parse.c file generated by lemon and the
  139292. ** tokenize.c file are concatenated. In that case, sqlite3RunParser()
  139293. ** has access to the the size of the yyParser object and so the parser
  139294. ** engine can be allocated from stack. In that case, only the
  139295. ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
  139296. ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
  139297. ** omitted.
  139298. */
  139299. #ifdef SQLITE_AMALGAMATION
  139300. # define sqlite3Parser_ENGINEALWAYSONSTACK 1
  139301. #endif
  139302. /*
  139303. ** Alternative datatype for the argument to the malloc() routine passed
  139304. ** into sqlite3ParserAlloc(). The default is size_t.
  139305. */
  139306. #define YYMALLOCARGTYPE u64
  139307. /*
  139308. ** An instance of the following structure describes the event of a
  139309. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  139310. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  139311. **
  139312. ** UPDATE ON (a,b,c)
  139313. **
  139314. ** Then the "b" IdList records the list "a,b,c".
  139315. */
  139316. struct TrigEvent { int a; IdList * b; };
  139317. struct FrameBound { int eType; Expr *pExpr; };
  139318. /*
  139319. ** Disable lookaside memory allocation for objects that might be
  139320. ** shared across database connections.
  139321. */
  139322. static void disableLookaside(Parse *pParse){
  139323. pParse->disableLookaside++;
  139324. pParse->db->lookaside.bDisable++;
  139325. }
  139326. /*
  139327. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  139328. ** all elements in the list. And make sure list length does not exceed
  139329. ** SQLITE_LIMIT_COMPOUND_SELECT.
  139330. */
  139331. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  139332. if( p->pPrior ){
  139333. Select *pNext = 0, *pLoop;
  139334. int mxSelect, cnt = 0;
  139335. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  139336. pLoop->pNext = pNext;
  139337. pLoop->selFlags |= SF_Compound;
  139338. }
  139339. if( (p->selFlags & SF_MultiValue)==0 &&
  139340. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  139341. cnt>mxSelect
  139342. ){
  139343. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  139344. }
  139345. }
  139346. }
  139347. /* Construct a new Expr object from a single identifier. Use the
  139348. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  139349. ** that created the expression.
  139350. */
  139351. static Expr *tokenExpr(Parse *pParse, int op, Token t){
  139352. Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
  139353. if( p ){
  139354. /* memset(p, 0, sizeof(Expr)); */
  139355. p->op = (u8)op;
  139356. p->affinity = 0;
  139357. p->flags = EP_Leaf;
  139358. p->iAgg = -1;
  139359. p->pLeft = p->pRight = 0;
  139360. p->x.pList = 0;
  139361. p->pAggInfo = 0;
  139362. p->y.pTab = 0;
  139363. p->op2 = 0;
  139364. p->iTable = 0;
  139365. p->iColumn = 0;
  139366. p->u.zToken = (char*)&p[1];
  139367. memcpy(p->u.zToken, t.z, t.n);
  139368. p->u.zToken[t.n] = 0;
  139369. if( sqlite3Isquote(p->u.zToken[0]) ){
  139370. sqlite3DequoteExpr(p);
  139371. }
  139372. #if SQLITE_MAX_EXPR_DEPTH>0
  139373. p->nHeight = 1;
  139374. #endif
  139375. if( IN_RENAME_OBJECT ){
  139376. return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);
  139377. }
  139378. }
  139379. return p;
  139380. }
  139381. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  139382. ** unary TK_ISNULL or TK_NOTNULL expression. */
  139383. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  139384. sqlite3 *db = pParse->db;
  139385. if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){
  139386. pA->op = (u8)op;
  139387. sqlite3ExprDelete(db, pA->pRight);
  139388. pA->pRight = 0;
  139389. }
  139390. }
  139391. /* Add a single new term to an ExprList that is used to store a
  139392. ** list of identifiers. Report an error if the ID list contains
  139393. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  139394. ** error while parsing a legacy schema.
  139395. */
  139396. static ExprList *parserAddExprIdListTerm(
  139397. Parse *pParse,
  139398. ExprList *pPrior,
  139399. Token *pIdToken,
  139400. int hasCollate,
  139401. int sortOrder
  139402. ){
  139403. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  139404. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  139405. && pParse->db->init.busy==0
  139406. ){
  139407. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  139408. pIdToken->n, pIdToken->z);
  139409. }
  139410. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  139411. return p;
  139412. }
  139413. #if TK_SPAN>255
  139414. # error too many tokens in the grammar
  139415. #endif
  139416. /**************** End of %include directives **********************************/
  139417. /* These constants specify the various numeric values for terminal symbols
  139418. ** in a format understandable to "makeheaders". This section is blank unless
  139419. ** "lemon" is run with the "-m" command-line option.
  139420. ***************** Begin makeheaders token definitions *************************/
  139421. /**************** End makeheaders token definitions ***************************/
  139422. /* The next sections is a series of control #defines.
  139423. ** various aspects of the generated parser.
  139424. ** YYCODETYPE is the data type used to store the integer codes
  139425. ** that represent terminal and non-terminal symbols.
  139426. ** "unsigned char" is used if there are fewer than
  139427. ** 256 symbols. Larger types otherwise.
  139428. ** YYNOCODE is a number of type YYCODETYPE that is not used for
  139429. ** any terminal or nonterminal symbol.
  139430. ** YYFALLBACK If defined, this indicates that one or more tokens
  139431. ** (also known as: "terminal symbols") have fall-back
  139432. ** values which should be used if the original symbol
  139433. ** would not parse. This permits keywords to sometimes
  139434. ** be used as identifiers, for example.
  139435. ** YYACTIONTYPE is the data type used for "action codes" - numbers
  139436. ** that indicate what to do in response to the next
  139437. ** token.
  139438. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
  139439. ** symbols. Background: A "minor type" is a semantic
  139440. ** value associated with a terminal or non-terminal
  139441. ** symbols. For example, for an "ID" terminal symbol,
  139442. ** the minor type might be the name of the identifier.
  139443. ** Each non-terminal can have a different minor type.
  139444. ** Terminal symbols all have the same minor type, though.
  139445. ** This macros defines the minor type for terminal
  139446. ** symbols.
  139447. ** YYMINORTYPE is the data type used for all minor types.
  139448. ** This is typically a union of many types, one of
  139449. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  139450. ** for terminal symbols is called "yy0".
  139451. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  139452. ** zero the stack is dynamically sized using realloc()
  139453. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  139454. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  139455. ** sqlite3ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
  139456. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  139457. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  139458. ** sqlite3ParserCTX_* As sqlite3ParserARG_ except for %extra_context
  139459. ** YYERRORSYMBOL is the code number of the error symbol. If not
  139460. ** defined, then do no error processing.
  139461. ** YYNSTATE the combined number of states.
  139462. ** YYNRULE the number of rules in the grammar
  139463. ** YYNTOKEN Number of terminal symbols
  139464. ** YY_MAX_SHIFT Maximum value for shift actions
  139465. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  139466. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  139467. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  139468. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  139469. ** YY_NO_ACTION The yy_action[] code for no-op
  139470. ** YY_MIN_REDUCE Minimum value for reduce actions
  139471. ** YY_MAX_REDUCE Maximum value for reduce actions
  139472. */
  139473. #ifndef INTERFACE
  139474. # define INTERFACE 1
  139475. #endif
  139476. /************* Begin control #defines *****************************************/
  139477. #define YYCODETYPE unsigned short int
  139478. #define YYNOCODE 301
  139479. #define YYACTIONTYPE unsigned short int
  139480. #define YYWILDCARD 95
  139481. #define sqlite3ParserTOKENTYPE Token
  139482. typedef union {
  139483. int yyinit;
  139484. sqlite3ParserTOKENTYPE yy0;
  139485. With* yy59;
  139486. IdList* yy62;
  139487. struct TrigEvent yy90;
  139488. Upsert* yy136;
  139489. struct FrameBound yy201;
  139490. u8 yy238;
  139491. const char* yy294;
  139492. Window* yy295;
  139493. struct {int value; int mask;} yy355;
  139494. ExprList* yy434;
  139495. TriggerStep* yy455;
  139496. Select* yy457;
  139497. SrcList* yy483;
  139498. int yy494;
  139499. Expr* yy524;
  139500. } YYMINORTYPE;
  139501. #ifndef YYSTACKDEPTH
  139502. #define YYSTACKDEPTH 100
  139503. #endif
  139504. #define sqlite3ParserARG_SDECL
  139505. #define sqlite3ParserARG_PDECL
  139506. #define sqlite3ParserARG_PARAM
  139507. #define sqlite3ParserARG_FETCH
  139508. #define sqlite3ParserARG_STORE
  139509. #define sqlite3ParserCTX_SDECL Parse *pParse;
  139510. #define sqlite3ParserCTX_PDECL ,Parse *pParse
  139511. #define sqlite3ParserCTX_PARAM ,pParse
  139512. #define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
  139513. #define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
  139514. #define YYFALLBACK 1
  139515. #define YYNSTATE 541
  139516. #define YYNRULE 375
  139517. #define YYNTOKEN 176
  139518. #define YY_MAX_SHIFT 540
  139519. #define YY_MIN_SHIFTREDUCE 784
  139520. #define YY_MAX_SHIFTREDUCE 1158
  139521. #define YY_ERROR_ACTION 1159
  139522. #define YY_ACCEPT_ACTION 1160
  139523. #define YY_NO_ACTION 1161
  139524. #define YY_MIN_REDUCE 1162
  139525. #define YY_MAX_REDUCE 1536
  139526. /************* End control #defines *******************************************/
  139527. #define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))
  139528. /* Define the yytestcase() macro to be a no-op if is not already defined
  139529. ** otherwise.
  139530. **
  139531. ** Applications can choose to define yytestcase() in the %include section
  139532. ** to a macro that can assist in verifying code coverage. For production
  139533. ** code the yytestcase() macro should be turned off. But it is useful
  139534. ** for testing.
  139535. */
  139536. #ifndef yytestcase
  139537. # define yytestcase(X)
  139538. #endif
  139539. /* Next are the tables used to determine what action to take based on the
  139540. ** current state and lookahead token. These tables are used to implement
  139541. ** functions that take a state number and lookahead value and return an
  139542. ** action integer.
  139543. **
  139544. ** Suppose the action integer is N. Then the action is determined as
  139545. ** follows
  139546. **
  139547. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  139548. ** token onto the stack and goto state N.
  139549. **
  139550. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  139551. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  139552. **
  139553. ** N == YY_ERROR_ACTION A syntax error has occurred.
  139554. **
  139555. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  139556. **
  139557. ** N == YY_NO_ACTION No such action. Denotes unused
  139558. ** slots in the yy_action[] table.
  139559. **
  139560. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  139561. ** and YY_MAX_REDUCE
  139562. **
  139563. ** The action table is constructed as a single large table named yy_action[].
  139564. ** Given state S and lookahead X, the action is computed as either:
  139565. **
  139566. ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
  139567. ** (B) N = yy_default[S]
  139568. **
  139569. ** The (A) formula is preferred. The B formula is used instead if
  139570. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X.
  139571. **
  139572. ** The formulas above are for computing the action when the lookahead is
  139573. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  139574. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  139575. ** the yy_shift_ofst[] array.
  139576. **
  139577. ** The following are the tables generated in this section:
  139578. **
  139579. ** yy_action[] A single table containing all actions.
  139580. ** yy_lookahead[] A table containing the lookahead for each entry in
  139581. ** yy_action. Used to detect hash collisions.
  139582. ** yy_shift_ofst[] For each state, the offset into yy_action for
  139583. ** shifting terminals.
  139584. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  139585. ** shifting non-terminals after a reduce.
  139586. ** yy_default[] Default action for each state.
  139587. **
  139588. *********** Begin parsing tables **********************************************/
  139589. #define YY_ACTTAB_COUNT (2142)
  139590. static const YYACTIONTYPE yy_action[] = {
  139591. /* 0 */ 535, 1323, 112, 109, 209, 112, 109, 209, 1160, 1,
  139592. /* 10 */ 1, 540, 2, 1164, 535, 1292, 1228, 1207, 289, 384,
  139593. /* 20 */ 134, 42, 42, 1427, 382, 1228, 9, 1241, 242, 492,
  139594. /* 30 */ 1291, 915, 373, 379, 1026, 70, 70, 427, 1026, 916,
  139595. /* 40 */ 529, 529, 529, 119, 120, 110, 1136, 1136, 981, 984,
  139596. /* 50 */ 974, 974, 117, 117, 118, 118, 118, 118, 380, 264,
  139597. /* 60 */ 264, 264, 264, 1134, 264, 264, 112, 109, 209, 397,
  139598. /* 70 */ 454, 517, 532, 491, 532, 1233, 1233, 532, 239, 206,
  139599. /* 80 */ 493, 112, 109, 209, 464, 219, 118, 118, 118, 118,
  139600. /* 90 */ 111, 393, 440, 444, 16, 16, 116, 116, 116, 116,
  139601. /* 100 */ 115, 115, 114, 114, 114, 113, 415, 971, 971, 982,
  139602. /* 110 */ 985, 235, 1463, 351, 1134, 419, 384, 116, 116, 116,
  139603. /* 120 */ 116, 115, 115, 114, 114, 114, 113, 415, 116, 116,
  139604. /* 130 */ 116, 116, 115, 115, 114, 114, 114, 113, 415, 961,
  139605. /* 140 */ 119, 120, 110, 1136, 1136, 981, 984, 974, 974, 117,
  139606. /* 150 */ 117, 118, 118, 118, 118, 952, 415, 941, 298, 951,
  139607. /* 160 */ 941, 1480, 540, 2, 1164, 1115, 535, 1458, 160, 289,
  139608. /* 170 */ 6, 134, 1504, 389, 406, 975, 338, 1024, 1241, 337,
  139609. /* 180 */ 1089, 1476, 1089, 118, 118, 118, 118, 42, 42, 329,
  139610. /* 190 */ 951, 951, 953, 116, 116, 116, 116, 115, 115, 114,
  139611. /* 200 */ 114, 114, 113, 415, 311, 430, 299, 311, 881, 160,
  139612. /* 210 */ 264, 264, 401, 384, 324, 1115, 1116, 1117, 288, 526,
  139613. /* 220 */ 96, 159, 1441, 532, 141, 116, 116, 116, 116, 115,
  139614. /* 230 */ 115, 114, 114, 114, 113, 415, 219, 119, 120, 110,
  139615. /* 240 */ 1136, 1136, 981, 984, 974, 974, 117, 117, 118, 118,
  139616. /* 250 */ 118, 118, 115, 115, 114, 114, 114, 113, 415, 288,
  139617. /* 260 */ 526, 403, 533, 121, 870, 870, 419, 250, 267, 336,
  139618. /* 270 */ 475, 331, 474, 236, 160, 319, 1084, 322, 1465, 329,
  139619. /* 280 */ 350, 12, 535, 384, 502, 1115, 1084, 435, 312, 1084,
  139620. /* 290 */ 116, 116, 116, 116, 115, 115, 114, 114, 114, 113,
  139621. /* 300 */ 415, 535, 836, 42, 42, 138, 426, 119, 120, 110,
  139622. /* 310 */ 1136, 1136, 981, 984, 974, 974, 117, 117, 118, 118,
  139623. /* 320 */ 118, 118, 70, 70, 288, 526, 412, 411, 480, 1457,
  139624. /* 330 */ 335, 79, 6, 473, 1140, 1115, 1116, 1117, 501, 1142,
  139625. /* 340 */ 334, 837, 811, 1484, 512, 1164, 534, 1141, 123, 187,
  139626. /* 350 */ 289, 384, 134, 448, 434, 1115, 80, 349, 498, 1241,
  139627. /* 360 */ 116, 116, 116, 116, 115, 115, 114, 114, 114, 113,
  139628. /* 370 */ 415, 1143, 1115, 1143, 459, 119, 120, 110, 1136, 1136,
  139629. /* 380 */ 981, 984, 974, 974, 117, 117, 118, 118, 118, 118,
  139630. /* 390 */ 404, 264, 264, 811, 1463, 506, 368, 1156, 535, 114,
  139631. /* 400 */ 114, 114, 113, 415, 532, 1115, 1116, 1117, 231, 518,
  139632. /* 410 */ 1500, 472, 469, 468, 175, 497, 422, 219, 1202, 70,
  139633. /* 420 */ 70, 467, 1115, 1116, 1117, 176, 201, 200, 116, 116,
  139634. /* 430 */ 116, 116, 115, 115, 114, 114, 114, 113, 415, 535,
  139635. /* 440 */ 1115, 264, 264, 435, 312, 1115, 273, 419, 384, 513,
  139636. /* 450 */ 1450, 1115, 326, 1084, 532, 517, 82, 1084, 167, 388,
  139637. /* 460 */ 69, 69, 1115, 1084, 519, 509, 1084, 1084, 12, 1157,
  139638. /* 470 */ 1084, 420, 119, 120, 110, 1136, 1136, 981, 984, 974,
  139639. /* 480 */ 974, 117, 117, 118, 118, 118, 118, 258, 258, 535,
  139640. /* 490 */ 1115, 1116, 1117, 1045, 535, 1115, 1116, 1117, 1323, 535,
  139641. /* 500 */ 532, 1115, 1116, 1117, 296, 483, 1211, 818, 1046, 448,
  139642. /* 510 */ 70, 70, 1115, 1116, 1117, 50, 50, 448, 356, 500,
  139643. /* 520 */ 70, 70, 207, 1047, 32, 116, 116, 116, 116, 115,
  139644. /* 530 */ 115, 114, 114, 114, 113, 415, 453, 264, 264, 1115,
  139645. /* 540 */ 450, 449, 961, 508, 856, 384, 517, 5, 900, 822,
  139646. /* 550 */ 532, 484, 181, 1115, 857, 516, 517, 818, 952, 507,
  139647. /* 560 */ 3, 1115, 951, 1231, 1231, 482, 398, 1115, 1095, 119,
  139648. /* 570 */ 120, 110, 1136, 1136, 981, 984, 974, 974, 117, 117,
  139649. /* 580 */ 118, 118, 118, 118, 1115, 535, 238, 1115, 1391, 1115,
  139650. /* 590 */ 1116, 1117, 159, 951, 951, 953, 231, 1115, 259, 472,
  139651. /* 600 */ 469, 468, 310, 1115, 1116, 1117, 13, 13, 297, 467,
  139652. /* 610 */ 276, 1115, 1116, 1117, 412, 411, 1095, 1115, 1116, 1117,
  139653. /* 620 */ 395, 355, 116, 116, 116, 116, 115, 115, 114, 114,
  139654. /* 630 */ 114, 113, 415, 208, 1115, 1116, 1117, 1115, 1116, 1117,
  139655. /* 640 */ 264, 264, 384, 337, 902, 393, 815, 1115, 1116, 1117,
  139656. /* 650 */ 413, 413, 413, 532, 112, 109, 209, 309, 900, 1143,
  139657. /* 660 */ 535, 1143, 535, 393, 901, 1210, 119, 120, 110, 1136,
  139658. /* 670 */ 1136, 981, 984, 974, 974, 117, 117, 118, 118, 118,
  139659. /* 680 */ 118, 13, 13, 13, 13, 265, 265, 535, 143, 264,
  139660. /* 690 */ 264, 288, 526, 535, 1119, 400, 535, 402, 532, 510,
  139661. /* 700 */ 1457, 512, 532, 6, 113, 415, 1067, 1530, 70, 70,
  139662. /* 710 */ 1530, 535, 271, 535, 70, 70, 535, 13, 13, 116,
  139663. /* 720 */ 116, 116, 116, 115, 115, 114, 114, 114, 113, 415,
  139664. /* 730 */ 272, 277, 13, 13, 13, 13, 535, 13, 13, 384,
  139665. /* 740 */ 535, 304, 425, 1100, 284, 1119, 184, 801, 185, 338,
  139666. /* 750 */ 285, 514, 1532, 369, 1239, 1438, 1182, 70, 70, 425,
  139667. /* 760 */ 424, 70, 70, 119, 120, 110, 1136, 1136, 981, 984,
  139668. /* 770 */ 974, 974, 117, 117, 118, 118, 118, 118, 190, 1065,
  139669. /* 780 */ 1067, 1531, 442, 107, 1531, 408, 264, 264, 264, 264,
  139670. /* 790 */ 383, 1396, 261, 410, 95, 900, 485, 414, 421, 532,
  139671. /* 800 */ 1045, 532, 301, 1133, 303, 488, 433, 1451, 1396, 1398,
  139672. /* 810 */ 278, 535, 278, 520, 1435, 1046, 116, 116, 116, 116,
  139673. /* 820 */ 115, 115, 114, 114, 114, 113, 415, 425, 264, 264,
  139674. /* 830 */ 1047, 190, 54, 54, 535, 291, 384, 264, 264, 362,
  139675. /* 840 */ 962, 532, 1004, 376, 1084, 264, 264, 1029, 1029, 456,
  139676. /* 850 */ 532, 523, 270, 1065, 1084, 55, 55, 1084, 532, 442,
  139677. /* 860 */ 119, 120, 110, 1136, 1136, 981, 984, 974, 974, 117,
  139678. /* 870 */ 117, 118, 118, 118, 118, 535, 1396, 190, 302, 1383,
  139679. /* 880 */ 208, 535, 789, 790, 791, 535, 515, 535, 1323, 371,
  139680. /* 890 */ 337, 234, 233, 232, 459, 515, 15, 15, 459, 477,
  139681. /* 900 */ 459, 459, 44, 44, 136, 900, 56, 56, 57, 57,
  139682. /* 910 */ 1185, 390, 197, 116, 116, 116, 116, 115, 115, 114,
  139683. /* 920 */ 114, 114, 113, 415, 535, 876, 535, 442, 535, 274,
  139684. /* 930 */ 875, 1323, 357, 384, 353, 140, 1426, 946, 1455, 1323,
  139685. /* 940 */ 1390, 6, 1240, 1236, 292, 58, 58, 59, 59, 60,
  139686. /* 950 */ 60, 535, 1456, 384, 535, 6, 399, 119, 120, 110,
  139687. /* 960 */ 1136, 1136, 981, 984, 974, 974, 117, 117, 118, 118,
  139688. /* 970 */ 118, 118, 61, 61, 535, 45, 45, 119, 120, 110,
  139689. /* 980 */ 1136, 1136, 981, 984, 974, 974, 117, 117, 118, 118,
  139690. /* 990 */ 118, 118, 1477, 479, 202, 46, 46, 275, 95, 455,
  139691. /* 1000 */ 535, 212, 535, 337, 535, 1454, 535, 409, 6, 242,
  139692. /* 1010 */ 116, 116, 116, 116, 115, 115, 114, 114, 114, 113,
  139693. /* 1020 */ 415, 48, 48, 49, 49, 62, 62, 63, 63, 535,
  139694. /* 1030 */ 116, 116, 116, 116, 115, 115, 114, 114, 114, 113,
  139695. /* 1040 */ 415, 535, 459, 535, 1134, 535, 1151, 535, 142, 535,
  139696. /* 1050 */ 64, 64, 535, 1338, 535, 494, 535, 446, 535, 1264,
  139697. /* 1060 */ 535, 1337, 14, 14, 65, 65, 125, 125, 66, 66,
  139698. /* 1070 */ 51, 51, 535, 67, 67, 68, 68, 52, 52, 147,
  139699. /* 1080 */ 147, 148, 148, 1453, 317, 98, 6, 535, 1245, 481,
  139700. /* 1090 */ 535, 827, 535, 75, 75, 1134, 102, 481, 100, 535,
  139701. /* 1100 */ 532, 535, 368, 1066, 1503, 384, 535, 845, 53, 53,
  139702. /* 1110 */ 93, 71, 71, 126, 126, 295, 528, 390, 288, 526,
  139703. /* 1120 */ 72, 72, 127, 127, 139, 384, 38, 128, 128, 119,
  139704. /* 1130 */ 120, 110, 1136, 1136, 981, 984, 974, 974, 117, 117,
  139705. /* 1140 */ 118, 118, 118, 118, 535, 495, 535, 447, 535, 119,
  139706. /* 1150 */ 120, 110, 1136, 1136, 981, 984, 974, 974, 117, 117,
  139707. /* 1160 */ 118, 118, 118, 118, 235, 124, 124, 146, 146, 145,
  139708. /* 1170 */ 145, 287, 535, 1277, 535, 1157, 535, 391, 161, 263,
  139709. /* 1180 */ 206, 381, 116, 116, 116, 116, 115, 115, 114, 114,
  139710. /* 1190 */ 114, 113, 415, 132, 132, 131, 131, 129, 129, 535,
  139711. /* 1200 */ 30, 535, 116, 116, 116, 116, 115, 115, 114, 114,
  139712. /* 1210 */ 114, 113, 415, 535, 216, 1062, 1276, 535, 370, 535,
  139713. /* 1220 */ 130, 130, 74, 74, 535, 915, 389, 876, 17, 437,
  139714. /* 1230 */ 429, 31, 875, 916, 76, 76, 266, 101, 73, 73,
  139715. /* 1240 */ 43, 43, 835, 834, 308, 47, 47, 95, 825, 943,
  139716. /* 1250 */ 441, 938, 241, 241, 305, 443, 313, 384, 241, 95,
  139717. /* 1260 */ 842, 843, 193, 465, 1209, 327, 237, 436, 95, 1011,
  139718. /* 1270 */ 1007, 909, 873, 237, 241, 107, 1023, 384, 1023, 955,
  139719. /* 1280 */ 1415, 119, 120, 110, 1136, 1136, 981, 984, 974, 974,
  139720. /* 1290 */ 117, 117, 118, 118, 118, 118, 1022, 809, 1022, 825,
  139721. /* 1300 */ 137, 119, 108, 110, 1136, 1136, 981, 984, 974, 974,
  139722. /* 1310 */ 117, 117, 118, 118, 118, 118, 874, 1414, 451, 107,
  139723. /* 1320 */ 1011, 314, 1273, 318, 218, 321, 323, 325, 1224, 1208,
  139724. /* 1330 */ 955, 330, 339, 340, 116, 116, 116, 116, 115, 115,
  139725. /* 1340 */ 114, 114, 114, 113, 415, 1285, 1322, 1260, 1493, 1470,
  139726. /* 1350 */ 1271, 283, 521, 1328, 116, 116, 116, 116, 115, 115,
  139727. /* 1360 */ 114, 114, 114, 113, 415, 1191, 1184, 1173, 1172, 1174,
  139728. /* 1370 */ 522, 1487, 211, 460, 384, 256, 199, 367, 1257, 342,
  139729. /* 1380 */ 195, 470, 307, 344, 11, 333, 525, 445, 1307, 1315,
  139730. /* 1390 */ 375, 203, 1207, 1151, 384, 346, 1387, 188, 360, 120,
  139731. /* 1400 */ 110, 1136, 1136, 981, 984, 974, 974, 117, 117, 118,
  139732. /* 1410 */ 118, 118, 118, 1386, 428, 1490, 245, 300, 348, 1148,
  139733. /* 1420 */ 110, 1136, 1136, 981, 984, 974, 974, 117, 117, 118,
  139734. /* 1430 */ 118, 118, 118, 189, 198, 1434, 1432, 78, 81, 163,
  139735. /* 1440 */ 82, 392, 439, 1392, 173, 105, 527, 35, 4, 157,
  139736. /* 1450 */ 1312, 116, 116, 116, 116, 115, 115, 114, 114, 114,
  139737. /* 1460 */ 113, 415, 530, 165, 93, 1304, 431, 432, 168, 463,
  139738. /* 1470 */ 221, 116, 116, 116, 116, 115, 115, 114, 114, 114,
  139739. /* 1480 */ 113, 415, 169, 452, 170, 416, 171, 374, 372, 438,
  139740. /* 1490 */ 36, 1318, 177, 225, 1381, 87, 458, 524, 1403, 316,
  139741. /* 1500 */ 257, 105, 527, 227, 4, 182, 461, 160, 320, 228,
  139742. /* 1510 */ 377, 1175, 476, 229, 1227, 1226, 405, 1225, 530, 1218,
  139743. /* 1520 */ 961, 378, 1199, 1198, 827, 332, 103, 103, 1197, 407,
  139744. /* 1530 */ 8, 1217, 1502, 104, 487, 416, 537, 536, 281, 282,
  139745. /* 1540 */ 951, 416, 490, 1268, 496, 92, 341, 243, 1269, 343,
  139746. /* 1550 */ 244, 1267, 122, 524, 345, 1461, 515, 288, 526, 10,
  139747. /* 1560 */ 354, 1266, 1460, 352, 504, 1250, 99, 1367, 94, 503,
  139748. /* 1570 */ 499, 951, 951, 953, 954, 27, 961, 347, 1249, 194,
  139749. /* 1580 */ 251, 358, 103, 103, 359, 1181, 34, 538, 1110, 104,
  139750. /* 1590 */ 255, 416, 537, 536, 286, 252, 951, 254, 539, 149,
  139751. /* 1600 */ 1170, 1419, 1165, 1420, 1418, 150, 1417, 135, 279, 785,
  139752. /* 1610 */ 151, 417, 1195, 196, 290, 210, 386, 1194, 269, 387,
  139753. /* 1620 */ 162, 1021, 133, 77, 1192, 1019, 935, 951, 951, 953,
  139754. /* 1630 */ 954, 27, 1479, 1104, 418, 164, 153, 268, 217, 166,
  139755. /* 1640 */ 859, 306, 366, 366, 365, 253, 363, 220, 1035, 798,
  139756. /* 1650 */ 172, 939, 105, 527, 155, 4, 394, 174, 396, 156,
  139757. /* 1660 */ 83, 1038, 213, 84, 294, 85, 86, 223, 222, 530,
  139758. /* 1670 */ 1034, 144, 293, 18, 224, 315, 241, 1027, 1145, 178,
  139759. /* 1680 */ 457, 226, 179, 37, 800, 334, 462, 230, 328, 466,
  139760. /* 1690 */ 180, 471, 416, 88, 19, 20, 89, 280, 838, 158,
  139761. /* 1700 */ 191, 90, 215, 478, 524, 1097, 204, 192, 987, 91,
  139762. /* 1710 */ 152, 1070, 39, 154, 1071, 504, 486, 40, 489, 205,
  139763. /* 1720 */ 505, 260, 105, 527, 214, 4, 908, 961, 262, 183,
  139764. /* 1730 */ 240, 21, 903, 103, 103, 107, 22, 1086, 23, 530,
  139765. /* 1740 */ 104, 1088, 416, 537, 536, 24, 1093, 951, 25, 1074,
  139766. /* 1750 */ 1090, 1094, 7, 33, 511, 186, 26, 1002, 385, 95,
  139767. /* 1760 */ 988, 986, 416, 288, 526, 990, 1044, 246, 1043, 247,
  139768. /* 1770 */ 991, 28, 41, 106, 524, 956, 810, 29, 951, 951,
  139769. /* 1780 */ 953, 954, 27, 531, 361, 504, 423, 248, 869, 249,
  139770. /* 1790 */ 503, 1495, 364, 1105, 1161, 1494, 1161, 961, 1161, 1161,
  139771. /* 1800 */ 1161, 1161, 1161, 103, 103, 1161, 1161, 1161, 1161, 1161,
  139772. /* 1810 */ 104, 1161, 416, 537, 536, 1104, 418, 951, 1161, 268,
  139773. /* 1820 */ 1161, 1161, 1161, 1161, 366, 366, 365, 253, 363, 1161,
  139774. /* 1830 */ 1161, 798, 1161, 1161, 1161, 1161, 105, 527, 1161, 4,
  139775. /* 1840 */ 1161, 1161, 1161, 1161, 213, 1161, 294, 1161, 951, 951,
  139776. /* 1850 */ 953, 954, 27, 530, 293, 1161, 1161, 1161, 1161, 1161,
  139777. /* 1860 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
  139778. /* 1870 */ 1161, 1161, 1161, 1161, 1161, 1161, 416, 1161, 1161, 1161,
  139779. /* 1880 */ 1161, 1161, 1161, 1161, 215, 1161, 1161, 1161, 524, 1161,
  139780. /* 1890 */ 1161, 1161, 152, 1161, 1161, 154, 105, 527, 1161, 4,
  139781. /* 1900 */ 1161, 1161, 1161, 1161, 1161, 1161, 214, 1161, 1161, 1161,
  139782. /* 1910 */ 1161, 961, 1161, 530, 1161, 1161, 1161, 103, 103, 880,
  139783. /* 1920 */ 1161, 1161, 1161, 1161, 104, 1161, 416, 537, 536, 1161,
  139784. /* 1930 */ 1161, 951, 1161, 1161, 1161, 1161, 416, 1161, 1161, 1161,
  139785. /* 1940 */ 385, 1161, 1161, 1161, 1161, 288, 526, 1161, 524, 1161,
  139786. /* 1950 */ 1161, 1161, 1161, 1161, 1161, 1161, 97, 527, 1161, 4,
  139787. /* 1960 */ 1161, 1161, 951, 951, 953, 954, 27, 1161, 423, 1161,
  139788. /* 1970 */ 1161, 961, 1161, 530, 1161, 1161, 1161, 103, 103, 1161,
  139789. /* 1980 */ 1161, 1161, 1161, 1161, 104, 1161, 416, 537, 536, 1161,
  139790. /* 1990 */ 1161, 951, 268, 1161, 1161, 1161, 416, 366, 366, 365,
  139791. /* 2000 */ 253, 363, 1161, 1161, 798, 1161, 1161, 1161, 524, 1161,
  139792. /* 2010 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 213, 1161, 294,
  139793. /* 2020 */ 1161, 1161, 951, 951, 953, 954, 27, 293, 1161, 1161,
  139794. /* 2030 */ 1161, 961, 1161, 1161, 1161, 1161, 1161, 103, 103, 1161,
  139795. /* 2040 */ 1161, 1161, 1161, 1161, 104, 1161, 416, 537, 536, 1161,
  139796. /* 2050 */ 1161, 951, 1161, 1161, 1161, 1161, 1161, 215, 1161, 1161,
  139797. /* 2060 */ 1161, 1161, 1161, 1161, 1161, 152, 1161, 1161, 154, 1161,
  139798. /* 2070 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 214,
  139799. /* 2080 */ 1161, 1161, 951, 951, 953, 954, 27, 1161, 1161, 1161,
  139800. /* 2090 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
  139801. /* 2100 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
  139802. /* 2110 */ 1161, 1161, 1161, 385, 1161, 1161, 1161, 1161, 288, 526,
  139803. /* 2120 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
  139804. /* 2130 */ 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161, 1161,
  139805. /* 2140 */ 1161, 423,
  139806. };
  139807. static const YYCODETYPE yy_lookahead[] = {
  139808. /* 0 */ 184, 184, 259, 260, 261, 259, 260, 261, 176, 177,
  139809. /* 10 */ 178, 179, 180, 181, 184, 208, 212, 213, 186, 19,
  139810. /* 20 */ 188, 205, 206, 280, 205, 221, 22, 195, 24, 195,
  139811. /* 30 */ 208, 31, 195, 205, 29, 205, 206, 255, 33, 39,
  139812. /* 40 */ 200, 201, 202, 43, 44, 45, 46, 47, 48, 49,
  139813. /* 50 */ 50, 51, 52, 53, 54, 55, 56, 57, 205, 227,
  139814. /* 60 */ 228, 227, 228, 59, 227, 228, 259, 260, 261, 252,
  139815. /* 70 */ 65, 241, 240, 184, 240, 223, 224, 240, 244, 245,
  139816. /* 80 */ 250, 259, 260, 261, 19, 253, 54, 55, 56, 57,
  139817. /* 90 */ 58, 184, 255, 184, 205, 206, 96, 97, 98, 99,
  139818. /* 100 */ 100, 101, 102, 103, 104, 105, 106, 46, 47, 48,
  139819. /* 110 */ 49, 46, 296, 297, 110, 283, 19, 96, 97, 98,
  139820. /* 120 */ 99, 100, 101, 102, 103, 104, 105, 106, 96, 97,
  139821. /* 130 */ 98, 99, 100, 101, 102, 103, 104, 105, 106, 94,
  139822. /* 140 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  139823. /* 150 */ 53, 54, 55, 56, 57, 110, 106, 73, 251, 114,
  139824. /* 160 */ 73, 178, 179, 180, 181, 59, 184, 292, 81, 186,
  139825. /* 170 */ 295, 188, 218, 108, 19, 114, 184, 11, 195, 184,
  139826. /* 180 */ 83, 184, 85, 54, 55, 56, 57, 205, 206, 124,
  139827. /* 190 */ 145, 146, 147, 96, 97, 98, 99, 100, 101, 102,
  139828. /* 200 */ 103, 104, 105, 106, 120, 121, 122, 120, 102, 81,
  139829. /* 210 */ 227, 228, 220, 19, 16, 109, 110, 111, 131, 132,
  139830. /* 220 */ 26, 184, 184, 240, 229, 96, 97, 98, 99, 100,
  139831. /* 230 */ 101, 102, 103, 104, 105, 106, 253, 43, 44, 45,
  139832. /* 240 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  139833. /* 250 */ 56, 57, 100, 101, 102, 103, 104, 105, 106, 131,
  139834. /* 260 */ 132, 106, 127, 69, 129, 130, 283, 112, 113, 114,
  139835. /* 270 */ 115, 116, 117, 118, 81, 77, 76, 79, 296, 124,
  139836. /* 280 */ 298, 203, 184, 19, 84, 59, 86, 121, 122, 89,
  139837. /* 290 */ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
  139838. /* 300 */ 106, 184, 35, 205, 206, 22, 113, 43, 44, 45,
  139839. /* 310 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  139840. /* 320 */ 56, 57, 205, 206, 131, 132, 100, 101, 291, 292,
  139841. /* 330 */ 114, 67, 295, 66, 108, 109, 110, 111, 138, 113,
  139842. /* 340 */ 124, 74, 59, 179, 184, 181, 184, 121, 22, 271,
  139843. /* 350 */ 186, 19, 188, 184, 276, 59, 24, 184, 241, 195,
  139844. /* 360 */ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
  139845. /* 370 */ 106, 145, 59, 147, 184, 43, 44, 45, 46, 47,
  139846. /* 380 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  139847. /* 390 */ 123, 227, 228, 110, 296, 297, 22, 23, 184, 102,
  139848. /* 400 */ 103, 104, 105, 106, 240, 109, 110, 111, 112, 195,
  139849. /* 410 */ 204, 115, 116, 117, 22, 184, 226, 253, 212, 205,
  139850. /* 420 */ 206, 125, 109, 110, 111, 22, 100, 101, 96, 97,
  139851. /* 430 */ 98, 99, 100, 101, 102, 103, 104, 105, 106, 184,
  139852. /* 440 */ 59, 227, 228, 121, 122, 59, 277, 283, 19, 289,
  139853. /* 450 */ 290, 59, 23, 76, 240, 241, 143, 76, 72, 189,
  139854. /* 460 */ 205, 206, 59, 86, 250, 84, 89, 86, 203, 95,
  139855. /* 470 */ 89, 281, 43, 44, 45, 46, 47, 48, 49, 50,
  139856. /* 480 */ 51, 52, 53, 54, 55, 56, 57, 227, 228, 184,
  139857. /* 490 */ 109, 110, 111, 12, 184, 109, 110, 111, 184, 184,
  139858. /* 500 */ 240, 109, 110, 111, 184, 195, 214, 59, 27, 184,
  139859. /* 510 */ 205, 206, 109, 110, 111, 205, 206, 184, 263, 138,
  139860. /* 520 */ 205, 206, 184, 42, 22, 96, 97, 98, 99, 100,
  139861. /* 530 */ 101, 102, 103, 104, 105, 106, 266, 227, 228, 59,
  139862. /* 540 */ 270, 276, 94, 66, 63, 19, 241, 22, 26, 23,
  139863. /* 550 */ 240, 241, 72, 59, 73, 250, 241, 109, 110, 82,
  139864. /* 560 */ 22, 59, 114, 223, 224, 250, 252, 59, 91, 43,
  139865. /* 570 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  139866. /* 580 */ 54, 55, 56, 57, 59, 184, 26, 59, 268, 109,
  139867. /* 590 */ 110, 111, 184, 145, 146, 147, 112, 59, 203, 115,
  139868. /* 600 */ 116, 117, 277, 109, 110, 111, 205, 206, 195, 125,
  139869. /* 610 */ 277, 109, 110, 111, 100, 101, 139, 109, 110, 111,
  139870. /* 620 */ 219, 184, 96, 97, 98, 99, 100, 101, 102, 103,
  139871. /* 630 */ 104, 105, 106, 111, 109, 110, 111, 109, 110, 111,
  139872. /* 640 */ 227, 228, 19, 184, 136, 184, 23, 109, 110, 111,
  139873. /* 650 */ 200, 201, 202, 240, 259, 260, 261, 195, 136, 145,
  139874. /* 660 */ 184, 147, 184, 184, 136, 214, 43, 44, 45, 46,
  139875. /* 670 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  139876. /* 680 */ 57, 205, 206, 205, 206, 227, 228, 184, 229, 227,
  139877. /* 690 */ 228, 131, 132, 184, 59, 219, 184, 219, 240, 291,
  139878. /* 700 */ 292, 184, 240, 295, 105, 106, 22, 23, 205, 206,
  139879. /* 710 */ 26, 184, 251, 184, 205, 206, 184, 205, 206, 96,
  139880. /* 720 */ 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  139881. /* 730 */ 251, 219, 205, 206, 205, 206, 184, 205, 206, 19,
  139882. /* 740 */ 184, 16, 184, 23, 241, 110, 219, 21, 219, 184,
  139883. /* 750 */ 241, 219, 286, 287, 195, 184, 195, 205, 206, 201,
  139884. /* 760 */ 202, 205, 206, 43, 44, 45, 46, 47, 48, 49,
  139885. /* 770 */ 50, 51, 52, 53, 54, 55, 56, 57, 184, 95,
  139886. /* 780 */ 22, 23, 184, 26, 26, 220, 227, 228, 227, 228,
  139887. /* 790 */ 196, 184, 23, 241, 26, 26, 195, 241, 184, 240,
  139888. /* 800 */ 12, 240, 77, 26, 79, 195, 80, 290, 201, 202,
  139889. /* 810 */ 216, 184, 218, 195, 184, 27, 96, 97, 98, 99,
  139890. /* 820 */ 100, 101, 102, 103, 104, 105, 106, 269, 227, 228,
  139891. /* 830 */ 42, 184, 205, 206, 184, 184, 19, 227, 228, 192,
  139892. /* 840 */ 23, 240, 116, 196, 76, 227, 228, 120, 121, 122,
  139893. /* 850 */ 240, 63, 254, 95, 86, 205, 206, 89, 240, 184,
  139894. /* 860 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  139895. /* 870 */ 53, 54, 55, 56, 57, 184, 269, 184, 153, 153,
  139896. /* 880 */ 111, 184, 7, 8, 9, 184, 138, 184, 184, 196,
  139897. /* 890 */ 184, 120, 121, 122, 184, 138, 205, 206, 184, 102,
  139898. /* 900 */ 184, 184, 205, 206, 156, 136, 205, 206, 205, 206,
  139899. /* 910 */ 198, 199, 135, 96, 97, 98, 99, 100, 101, 102,
  139900. /* 920 */ 103, 104, 105, 106, 184, 128, 184, 184, 184, 254,
  139901. /* 930 */ 133, 184, 237, 19, 239, 229, 226, 23, 292, 184,
  139902. /* 940 */ 226, 295, 226, 226, 184, 205, 206, 205, 206, 205,
  139903. /* 950 */ 206, 184, 292, 19, 184, 295, 252, 43, 44, 45,
  139904. /* 960 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  139905. /* 970 */ 56, 57, 205, 206, 184, 205, 206, 43, 44, 45,
  139906. /* 980 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  139907. /* 990 */ 56, 57, 157, 158, 26, 205, 206, 254, 26, 252,
  139908. /* 1000 */ 184, 15, 184, 184, 184, 292, 184, 252, 295, 24,
  139909. /* 1010 */ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
  139910. /* 1020 */ 106, 205, 206, 205, 206, 205, 206, 205, 206, 184,
  139911. /* 1030 */ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
  139912. /* 1040 */ 106, 184, 184, 184, 59, 184, 60, 184, 229, 184,
  139913. /* 1050 */ 205, 206, 184, 258, 184, 19, 184, 19, 184, 246,
  139914. /* 1060 */ 184, 258, 205, 206, 205, 206, 205, 206, 205, 206,
  139915. /* 1070 */ 205, 206, 184, 205, 206, 205, 206, 205, 206, 205,
  139916. /* 1080 */ 206, 205, 206, 292, 226, 151, 295, 184, 228, 294,
  139917. /* 1090 */ 184, 119, 184, 205, 206, 110, 150, 294, 152, 184,
  139918. /* 1100 */ 240, 184, 22, 23, 23, 19, 184, 26, 205, 206,
  139919. /* 1110 */ 142, 205, 206, 205, 206, 184, 198, 199, 131, 132,
  139920. /* 1120 */ 205, 206, 205, 206, 22, 19, 24, 205, 206, 43,
  139921. /* 1130 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  139922. /* 1140 */ 54, 55, 56, 57, 184, 109, 184, 109, 184, 43,
  139923. /* 1150 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  139924. /* 1160 */ 54, 55, 56, 57, 46, 205, 206, 205, 206, 205,
  139925. /* 1170 */ 206, 232, 184, 184, 184, 95, 184, 284, 285, 244,
  139926. /* 1180 */ 245, 242, 96, 97, 98, 99, 100, 101, 102, 103,
  139927. /* 1190 */ 104, 105, 106, 205, 206, 205, 206, 205, 206, 184,
  139928. /* 1200 */ 22, 184, 96, 97, 98, 99, 100, 101, 102, 103,
  139929. /* 1210 */ 104, 105, 106, 184, 24, 23, 184, 184, 26, 184,
  139930. /* 1220 */ 205, 206, 205, 206, 184, 31, 108, 128, 22, 122,
  139931. /* 1230 */ 184, 53, 133, 39, 205, 206, 22, 151, 205, 206,
  139932. /* 1240 */ 205, 206, 113, 114, 23, 205, 206, 26, 59, 23,
  139933. /* 1250 */ 23, 144, 26, 26, 184, 23, 23, 19, 26, 26,
  139934. /* 1260 */ 7, 8, 24, 23, 214, 23, 26, 61, 26, 59,
  139935. /* 1270 */ 23, 23, 23, 26, 26, 26, 145, 19, 147, 59,
  139936. /* 1280 */ 184, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  139937. /* 1290 */ 52, 53, 54, 55, 56, 57, 145, 23, 147, 110,
  139938. /* 1300 */ 26, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  139939. /* 1310 */ 52, 53, 54, 55, 56, 57, 23, 184, 184, 26,
  139940. /* 1320 */ 110, 184, 184, 184, 134, 184, 184, 184, 184, 184,
  139941. /* 1330 */ 110, 184, 184, 184, 96, 97, 98, 99, 100, 101,
  139942. /* 1340 */ 102, 103, 104, 105, 106, 184, 184, 184, 134, 300,
  139943. /* 1350 */ 184, 243, 184, 184, 96, 97, 98, 99, 100, 101,
  139944. /* 1360 */ 102, 103, 104, 105, 106, 184, 184, 184, 184, 184,
  139945. /* 1370 */ 224, 184, 282, 273, 19, 272, 203, 182, 243, 243,
  139946. /* 1380 */ 230, 209, 278, 243, 231, 208, 265, 278, 234, 234,
  139947. /* 1390 */ 234, 217, 213, 60, 19, 243, 208, 237, 233, 44,
  139948. /* 1400 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
  139949. /* 1410 */ 55, 56, 57, 208, 247, 187, 134, 247, 247, 38,
  139950. /* 1420 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
  139951. /* 1430 */ 55, 56, 57, 237, 231, 191, 191, 279, 279, 282,
  139952. /* 1440 */ 143, 191, 108, 268, 22, 19, 20, 256, 22, 43,
  139953. /* 1450 */ 257, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  139954. /* 1460 */ 105, 106, 36, 222, 142, 234, 18, 191, 225, 18,
  139955. /* 1470 */ 190, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  139956. /* 1480 */ 105, 106, 225, 191, 225, 59, 225, 257, 234, 234,
  139957. /* 1490 */ 256, 222, 222, 190, 234, 150, 62, 71, 275, 274,
  139958. /* 1500 */ 191, 19, 20, 190, 22, 22, 210, 81, 191, 190,
  139959. /* 1510 */ 210, 191, 108, 190, 207, 207, 64, 207, 36, 215,
  139960. /* 1520 */ 94, 210, 207, 209, 119, 207, 100, 101, 207, 106,
  139961. /* 1530 */ 48, 215, 207, 107, 210, 109, 110, 111, 267, 267,
  139962. /* 1540 */ 114, 59, 210, 249, 137, 108, 248, 191, 249, 248,
  139963. /* 1550 */ 88, 249, 141, 71, 248, 299, 138, 131, 132, 22,
  139964. /* 1560 */ 191, 249, 299, 237, 82, 238, 150, 262, 140, 87,
  139965. /* 1570 */ 139, 145, 146, 147, 148, 149, 94, 248, 238, 236,
  139966. /* 1580 */ 25, 235, 100, 101, 234, 194, 26, 193, 13, 107,
  139967. /* 1590 */ 6, 109, 110, 111, 264, 185, 114, 185, 183, 197,
  139968. /* 1600 */ 183, 203, 183, 203, 203, 197, 203, 211, 211, 4,
  139969. /* 1610 */ 197, 3, 203, 22, 155, 15, 288, 203, 93, 288,
  139970. /* 1620 */ 285, 23, 16, 203, 203, 23, 132, 145, 146, 147,
  139971. /* 1630 */ 148, 149, 0, 1, 2, 143, 123, 5, 24, 135,
  139972. /* 1640 */ 20, 16, 10, 11, 12, 13, 14, 137, 1, 17,
  139973. /* 1650 */ 135, 144, 19, 20, 123, 22, 61, 143, 37, 123,
  139974. /* 1660 */ 53, 109, 30, 53, 32, 53, 53, 134, 34, 36,
  139975. /* 1670 */ 1, 5, 40, 22, 108, 153, 26, 68, 75, 68,
  139976. /* 1680 */ 41, 134, 108, 24, 20, 124, 19, 118, 23, 67,
  139977. /* 1690 */ 22, 67, 59, 22, 22, 22, 22, 67, 28, 37,
  139978. /* 1700 */ 23, 142, 70, 22, 71, 23, 157, 23, 23, 26,
  139979. /* 1710 */ 78, 23, 22, 81, 23, 82, 24, 22, 24, 134,
  139980. /* 1720 */ 87, 23, 19, 20, 92, 22, 109, 94, 23, 22,
  139981. /* 1730 */ 34, 34, 136, 100, 101, 26, 34, 85, 34, 36,
  139982. /* 1740 */ 107, 83, 109, 110, 111, 34, 90, 114, 34, 23,
  139983. /* 1750 */ 75, 75, 44, 22, 24, 26, 34, 23, 126, 26,
  139984. /* 1760 */ 23, 23, 59, 131, 132, 23, 23, 26, 23, 22,
  139985. /* 1770 */ 11, 22, 22, 22, 71, 23, 23, 22, 145, 146,
  139986. /* 1780 */ 147, 148, 149, 26, 23, 82, 154, 134, 128, 134,
  139987. /* 1790 */ 87, 134, 15, 1, 301, 134, 301, 94, 301, 301,
  139988. /* 1800 */ 301, 301, 301, 100, 101, 301, 301, 301, 301, 301,
  139989. /* 1810 */ 107, 301, 109, 110, 111, 1, 2, 114, 301, 5,
  139990. /* 1820 */ 301, 301, 301, 301, 10, 11, 12, 13, 14, 301,
  139991. /* 1830 */ 301, 17, 301, 301, 301, 301, 19, 20, 301, 22,
  139992. /* 1840 */ 301, 301, 301, 301, 30, 301, 32, 301, 145, 146,
  139993. /* 1850 */ 147, 148, 149, 36, 40, 301, 301, 301, 301, 301,
  139994. /* 1860 */ 301, 301, 301, 301, 301, 301, 301, 301, 301, 301,
  139995. /* 1870 */ 301, 301, 301, 301, 301, 301, 59, 301, 301, 301,
  139996. /* 1880 */ 301, 301, 301, 301, 70, 301, 301, 301, 71, 301,
  139997. /* 1890 */ 301, 301, 78, 301, 301, 81, 19, 20, 301, 22,
  139998. /* 1900 */ 301, 301, 301, 301, 301, 301, 92, 301, 301, 301,
  139999. /* 1910 */ 301, 94, 301, 36, 301, 301, 301, 100, 101, 102,
  140000. /* 1920 */ 301, 301, 301, 301, 107, 301, 109, 110, 111, 301,
  140001. /* 1930 */ 301, 114, 301, 301, 301, 301, 59, 301, 301, 301,
  140002. /* 1940 */ 126, 301, 301, 301, 301, 131, 132, 301, 71, 301,
  140003. /* 1950 */ 301, 301, 301, 301, 301, 301, 19, 20, 301, 22,
  140004. /* 1960 */ 301, 301, 145, 146, 147, 148, 149, 301, 154, 301,
  140005. /* 1970 */ 301, 94, 301, 36, 301, 301, 301, 100, 101, 301,
  140006. /* 1980 */ 301, 301, 301, 301, 107, 301, 109, 110, 111, 301,
  140007. /* 1990 */ 301, 114, 5, 301, 301, 301, 59, 10, 11, 12,
  140008. /* 2000 */ 13, 14, 301, 301, 17, 301, 301, 301, 71, 301,
  140009. /* 2010 */ 301, 301, 301, 301, 301, 301, 301, 30, 301, 32,
  140010. /* 2020 */ 301, 301, 145, 146, 147, 148, 149, 40, 301, 301,
  140011. /* 2030 */ 301, 94, 301, 301, 301, 301, 301, 100, 101, 301,
  140012. /* 2040 */ 301, 301, 301, 301, 107, 301, 109, 110, 111, 301,
  140013. /* 2050 */ 301, 114, 301, 301, 301, 301, 301, 70, 301, 301,
  140014. /* 2060 */ 301, 301, 301, 301, 301, 78, 301, 301, 81, 301,
  140015. /* 2070 */ 301, 301, 301, 301, 301, 301, 301, 301, 301, 92,
  140016. /* 2080 */ 301, 301, 145, 146, 147, 148, 149, 301, 301, 301,
  140017. /* 2090 */ 301, 301, 301, 301, 301, 301, 301, 301, 301, 301,
  140018. /* 2100 */ 301, 301, 301, 301, 301, 301, 301, 301, 301, 301,
  140019. /* 2110 */ 301, 301, 301, 126, 301, 301, 301, 301, 131, 132,
  140020. /* 2120 */ 301, 301, 301, 301, 301, 301, 301, 301, 301, 301,
  140021. /* 2130 */ 301, 301, 301, 301, 301, 301, 301, 301, 301, 301,
  140022. /* 2140 */ 301, 154, 301, 301, 301, 301, 301, 301, 301, 301,
  140023. /* 2150 */ 301, 301, 301, 301, 301, 301, 301, 301, 301, 301,
  140024. /* 2160 */ 301, 301, 301, 301, 301, 301, 301, 301, 301,
  140025. };
  140026. #define YY_SHIFT_COUNT (540)
  140027. #define YY_SHIFT_MIN (0)
  140028. #define YY_SHIFT_MAX (1987)
  140029. static const unsigned short int yy_shift_ofst[] = {
  140030. /* 0 */ 1814, 1632, 1987, 1426, 1426, 128, 1482, 1633, 1703, 1877,
  140031. /* 10 */ 1877, 1877, 87, 0, 0, 264, 1106, 1877, 1877, 1877,
  140032. /* 20 */ 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877,
  140033. /* 30 */ 226, 226, 381, 381, 296, 193, 128, 128, 128, 128,
  140034. /* 40 */ 128, 128, 97, 194, 332, 429, 526, 623, 720, 817,
  140035. /* 50 */ 914, 934, 1086, 1238, 1106, 1106, 1106, 1106, 1106, 1106,
  140036. /* 60 */ 1106, 1106, 1106, 1106, 1106, 1106, 1106, 1106, 1106, 1106,
  140037. /* 70 */ 1106, 1106, 1258, 1106, 1355, 1375, 1375, 1817, 1877, 1877,
  140038. /* 80 */ 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877,
  140039. /* 90 */ 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877,
  140040. /* 100 */ 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877,
  140041. /* 110 */ 1937, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877, 1877,
  140042. /* 120 */ 1877, 1877, 1877, 1877, 32, 129, 129, 129, 129, 129,
  140043. /* 130 */ 21, 152, 297, 494, 726, 65, 494, 514, 514, 494,
  140044. /* 140 */ 560, 560, 560, 560, 322, 599, 50, 2142, 2142, 155,
  140045. /* 150 */ 155, 155, 313, 392, 386, 392, 392, 481, 481, 200,
  140046. /* 160 */ 480, 684, 758, 494, 494, 494, 494, 494, 494, 494,
  140047. /* 170 */ 494, 494, 494, 494, 494, 494, 494, 494, 494, 494,
  140048. /* 180 */ 494, 494, 494, 494, 768, 768, 494, 166, 377, 377,
  140049. /* 190 */ 635, 835, 835, 635, 748, 987, 2142, 2142, 2142, 448,
  140050. /* 200 */ 45, 45, 403, 484, 502, 106, 525, 508, 528, 538,
  140051. /* 210 */ 494, 494, 494, 494, 494, 494, 494, 494, 494, 84,
  140052. /* 220 */ 494, 494, 494, 494, 494, 494, 494, 494, 494, 494,
  140053. /* 230 */ 494, 494, 267, 267, 267, 494, 494, 494, 494, 769,
  140054. /* 240 */ 494, 494, 494, 4, 477, 494, 494, 788, 494, 494,
  140055. /* 250 */ 494, 494, 494, 494, 494, 494, 727, 5, 135, 985,
  140056. /* 260 */ 985, 985, 985, 522, 135, 135, 797, 326, 875, 986,
  140057. /* 270 */ 968, 1036, 1036, 1038, 968, 968, 1038, 972, 1081, 1118,
  140058. /* 280 */ 1194, 1194, 1194, 1036, 757, 757, 946, 777, 1099, 1102,
  140059. /* 290 */ 1333, 1282, 1282, 1381, 1381, 1282, 1297, 1334, 1422, 1406,
  140060. /* 300 */ 1322, 1448, 1448, 1448, 1448, 1282, 1451, 1322, 1322, 1334,
  140061. /* 310 */ 1422, 1406, 1406, 1322, 1282, 1451, 1345, 1434, 1282, 1451,
  140062. /* 320 */ 1483, 1282, 1451, 1282, 1451, 1483, 1404, 1404, 1404, 1452,
  140063. /* 330 */ 1483, 1404, 1405, 1404, 1452, 1404, 1404, 1483, 1423, 1423,
  140064. /* 340 */ 1483, 1407, 1437, 1407, 1437, 1407, 1437, 1407, 1437, 1282,
  140065. /* 350 */ 1462, 1462, 1411, 1418, 1537, 1282, 1416, 1411, 1428, 1431,
  140066. /* 360 */ 1322, 1555, 1560, 1575, 1575, 1584, 1584, 1584, 2142, 2142,
  140067. /* 370 */ 2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142, 2142,
  140068. /* 380 */ 2142, 2142, 2142, 2142, 61, 725, 374, 1080, 198, 771,
  140069. /* 390 */ 283, 1192, 1178, 1190, 1107, 1221, 1206, 1226, 1227, 1232,
  140070. /* 400 */ 1233, 1240, 1242, 1189, 1129, 1253, 216, 1210, 1247, 1248,
  140071. /* 410 */ 1249, 1131, 1151, 1274, 1293, 1220, 1214, 1605, 1608, 1591,
  140072. /* 420 */ 1459, 1600, 1525, 1606, 1598, 1602, 1494, 1492, 1513, 1614,
  140073. /* 430 */ 1504, 1620, 1510, 1625, 1647, 1515, 1507, 1531, 1595, 1621,
  140074. /* 440 */ 1514, 1607, 1610, 1612, 1613, 1536, 1552, 1634, 1533, 1669,
  140075. /* 450 */ 1666, 1651, 1566, 1522, 1609, 1650, 1611, 1603, 1639, 1547,
  140076. /* 460 */ 1574, 1659, 1664, 1667, 1561, 1569, 1668, 1622, 1671, 1672,
  140077. /* 470 */ 1665, 1673, 1624, 1670, 1674, 1630, 1662, 1677, 1559, 1681,
  140078. /* 480 */ 1682, 1549, 1684, 1685, 1683, 1688, 1690, 1692, 1691, 1695,
  140079. /* 490 */ 1694, 1585, 1698, 1705, 1617, 1696, 1707, 1596, 1709, 1697,
  140080. /* 500 */ 1702, 1704, 1711, 1652, 1675, 1658, 1708, 1676, 1656, 1714,
  140081. /* 510 */ 1726, 1731, 1730, 1729, 1733, 1722, 1734, 1709, 1737, 1738,
  140082. /* 520 */ 1742, 1743, 1741, 1745, 1747, 1759, 1749, 1750, 1752, 1753,
  140083. /* 530 */ 1751, 1755, 1757, 1660, 1653, 1655, 1657, 1661, 1761, 1777,
  140084. /* 540 */ 1792,
  140085. };
  140086. #define YY_REDUCE_COUNT (383)
  140087. #define YY_REDUCE_MIN (-257)
  140088. #define YY_REDUCE_MAX (1421)
  140089. static const short yy_reduce_ofst[] = {
  140090. /* 0 */ -168, -17, 164, 214, 310, -166, -184, -18, 98, -170,
  140091. /* 10 */ 305, 315, -163, -193, -178, -257, 395, 401, 476, 478,
  140092. /* 20 */ 512, 117, 527, 529, 503, 509, 532, 255, 552, 556,
  140093. /* 30 */ 558, 607, 37, 408, 594, 413, 462, 559, 561, 601,
  140094. /* 40 */ 610, 618, -254, -254, -254, -254, -254, -254, -254, -254,
  140095. /* 50 */ -254, -254, -254, -254, -254, -254, -254, -254, -254, -254,
  140096. /* 60 */ -254, -254, -254, -254, -254, -254, -254, -254, -254, -254,
  140097. /* 70 */ -254, -254, -254, -254, -254, -254, -254, -111, 627, 650,
  140098. /* 80 */ 691, 697, 701, 703, 740, 742, 744, 767, 770, 790,
  140099. /* 90 */ 816, 818, 820, 822, 845, 857, 859, 861, 863, 865,
  140100. /* 100 */ 868, 870, 872, 874, 876, 888, 903, 906, 908, 915,
  140101. /* 110 */ 917, 922, 960, 962, 964, 988, 990, 992, 1015, 1017,
  140102. /* 120 */ 1029, 1033, 1035, 1040, -254, -254, -254, -254, -254, -254,
  140103. /* 130 */ -254, -254, -254, 190, 270, -196, 160, -160, 450, 647,
  140104. /* 140 */ 260, 458, 260, 458, 78, -254, -254, -254, -254, 206,
  140105. /* 150 */ 206, 206, 320, 598, -5, 675, 743, -148, 340, -125,
  140106. /* 160 */ 459, 466, 466, 693, -93, 461, 479, 706, 710, 714,
  140107. /* 170 */ 716, 717, 169, -183, 325, 314, 704, 333, 747, 858,
  140108. /* 180 */ -8, 819, 565, 755, 646, 660, 517, 265, 713, 791,
  140109. /* 190 */ 712, 795, 803, 918, 695, 860, 893, 935, 939, -181,
  140110. /* 200 */ -172, -147, -91, -46, -3, 162, 173, 231, 338, 437,
  140111. /* 210 */ 571, 614, 630, 651, 760, 931, 989, 1032, 1046, -218,
  140112. /* 220 */ 38, 1070, 1096, 1133, 1134, 1137, 1138, 1139, 1141, 1142,
  140113. /* 230 */ 1143, 1144, 292, 451, 1050, 1145, 1147, 1148, 1149, 813,
  140114. /* 240 */ 1161, 1162, 1163, 1108, 1049, 1166, 1168, 1146, 1169, 162,
  140115. /* 250 */ 1181, 1182, 1183, 1184, 1185, 1187, 1100, 1103, 1150, 1135,
  140116. /* 260 */ 1136, 1140, 1152, 813, 1150, 1150, 1153, 1173, 1195, 1090,
  140117. /* 270 */ 1154, 1167, 1170, 1104, 1155, 1156, 1109, 1172, 1174, 1179,
  140118. /* 280 */ 1177, 1188, 1205, 1171, 1160, 1196, 1121, 1165, 1203, 1228,
  140119. /* 290 */ 1157, 1244, 1245, 1158, 1159, 1250, 1175, 1193, 1191, 1241,
  140120. /* 300 */ 1231, 1243, 1257, 1259, 1261, 1276, 1280, 1254, 1255, 1230,
  140121. /* 310 */ 1234, 1269, 1270, 1260, 1292, 1303, 1223, 1225, 1309, 1313,
  140122. /* 320 */ 1296, 1317, 1319, 1320, 1323, 1300, 1307, 1308, 1310, 1304,
  140123. /* 330 */ 1311, 1315, 1314, 1318, 1316, 1321, 1325, 1324, 1271, 1272,
  140124. /* 340 */ 1332, 1294, 1298, 1299, 1301, 1302, 1306, 1312, 1329, 1356,
  140125. /* 350 */ 1256, 1263, 1327, 1326, 1305, 1369, 1330, 1340, 1343, 1346,
  140126. /* 360 */ 1350, 1391, 1394, 1410, 1412, 1415, 1417, 1419, 1328, 1331,
  140127. /* 370 */ 1335, 1402, 1398, 1400, 1401, 1403, 1408, 1396, 1397, 1409,
  140128. /* 380 */ 1414, 1420, 1421, 1413,
  140129. };
  140130. static const YYACTIONTYPE yy_default[] = {
  140131. /* 0 */ 1536, 1536, 1536, 1376, 1159, 1265, 1159, 1159, 1159, 1376,
  140132. /* 10 */ 1376, 1376, 1159, 1295, 1295, 1429, 1190, 1159, 1159, 1159,
  140133. /* 20 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1375, 1159, 1159,
  140134. /* 30 */ 1159, 1159, 1459, 1459, 1159, 1159, 1159, 1159, 1159, 1159,
  140135. /* 40 */ 1159, 1159, 1159, 1301, 1159, 1159, 1159, 1159, 1159, 1377,
  140136. /* 50 */ 1378, 1159, 1159, 1159, 1428, 1430, 1393, 1311, 1310, 1309,
  140137. /* 60 */ 1308, 1411, 1282, 1306, 1299, 1303, 1371, 1372, 1370, 1374,
  140138. /* 70 */ 1378, 1377, 1159, 1302, 1342, 1356, 1341, 1159, 1159, 1159,
  140139. /* 80 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140140. /* 90 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140141. /* 100 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140142. /* 110 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140143. /* 120 */ 1159, 1159, 1159, 1159, 1350, 1355, 1361, 1354, 1351, 1344,
  140144. /* 130 */ 1343, 1345, 1346, 1159, 1180, 1229, 1159, 1159, 1159, 1159,
  140145. /* 140 */ 1447, 1446, 1159, 1159, 1190, 1347, 1348, 1358, 1357, 1436,
  140146. /* 150 */ 1492, 1491, 1394, 1159, 1159, 1159, 1159, 1159, 1159, 1459,
  140147. /* 160 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140148. /* 170 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140149. /* 180 */ 1159, 1159, 1159, 1159, 1459, 1459, 1159, 1190, 1459, 1459,
  140150. /* 190 */ 1186, 1336, 1335, 1186, 1289, 1159, 1442, 1265, 1256, 1159,
  140151. /* 200 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140152. /* 210 */ 1159, 1159, 1159, 1433, 1431, 1159, 1159, 1159, 1159, 1159,
  140153. /* 220 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140154. /* 230 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140155. /* 240 */ 1159, 1159, 1159, 1261, 1159, 1159, 1159, 1159, 1159, 1159,
  140156. /* 250 */ 1159, 1159, 1159, 1159, 1159, 1486, 1159, 1406, 1243, 1261,
  140157. /* 260 */ 1261, 1261, 1261, 1263, 1244, 1242, 1255, 1190, 1166, 1528,
  140158. /* 270 */ 1305, 1284, 1284, 1525, 1305, 1305, 1525, 1204, 1506, 1201,
  140159. /* 280 */ 1295, 1295, 1295, 1284, 1289, 1289, 1373, 1262, 1255, 1159,
  140160. /* 290 */ 1528, 1270, 1270, 1527, 1527, 1270, 1394, 1314, 1320, 1232,
  140161. /* 300 */ 1305, 1238, 1238, 1238, 1238, 1270, 1177, 1305, 1305, 1314,
  140162. /* 310 */ 1320, 1232, 1232, 1305, 1270, 1177, 1410, 1522, 1270, 1177,
  140163. /* 320 */ 1384, 1270, 1177, 1270, 1177, 1384, 1230, 1230, 1230, 1219,
  140164. /* 330 */ 1384, 1230, 1204, 1230, 1219, 1230, 1230, 1384, 1388, 1388,
  140165. /* 340 */ 1384, 1288, 1283, 1288, 1283, 1288, 1283, 1288, 1283, 1270,
  140166. /* 350 */ 1469, 1469, 1300, 1289, 1379, 1270, 1159, 1300, 1298, 1296,
  140167. /* 360 */ 1305, 1183, 1222, 1489, 1489, 1485, 1485, 1485, 1533, 1533,
  140168. /* 370 */ 1442, 1501, 1190, 1190, 1190, 1190, 1501, 1206, 1206, 1190,
  140169. /* 380 */ 1190, 1190, 1190, 1501, 1159, 1159, 1159, 1159, 1159, 1159,
  140170. /* 390 */ 1496, 1159, 1395, 1274, 1159, 1159, 1159, 1159, 1159, 1159,
  140171. /* 400 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140172. /* 410 */ 1159, 1159, 1159, 1159, 1159, 1159, 1325, 1159, 1162, 1439,
  140173. /* 420 */ 1159, 1159, 1437, 1159, 1159, 1159, 1159, 1159, 1159, 1275,
  140174. /* 430 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140175. /* 440 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1524, 1159,
  140176. /* 450 */ 1159, 1159, 1159, 1159, 1159, 1409, 1408, 1159, 1159, 1272,
  140177. /* 460 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140178. /* 470 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140179. /* 480 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140180. /* 490 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1297, 1159,
  140181. /* 500 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140182. /* 510 */ 1159, 1159, 1159, 1474, 1290, 1159, 1159, 1515, 1159, 1159,
  140183. /* 520 */ 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159, 1159,
  140184. /* 530 */ 1159, 1159, 1510, 1246, 1327, 1159, 1326, 1330, 1159, 1171,
  140185. /* 540 */ 1159,
  140186. };
  140187. /********** End of lemon-generated parsing tables *****************************/
  140188. /* The next table maps tokens (terminal symbols) into fallback tokens.
  140189. ** If a construct like the following:
  140190. **
  140191. ** %fallback ID X Y Z.
  140192. **
  140193. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  140194. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  140195. ** but it does not parse, the type of the token is changed to ID and
  140196. ** the parse is retried before an error is thrown.
  140197. **
  140198. ** This feature can be used, for example, to cause some keywords in a language
  140199. ** to revert to identifiers if they keyword does not apply in the context where
  140200. ** it appears.
  140201. */
  140202. #ifdef YYFALLBACK
  140203. static const YYCODETYPE yyFallback[] = {
  140204. 0, /* $ => nothing */
  140205. 0, /* SEMI => nothing */
  140206. 59, /* EXPLAIN => ID */
  140207. 59, /* QUERY => ID */
  140208. 59, /* PLAN => ID */
  140209. 59, /* BEGIN => ID */
  140210. 0, /* TRANSACTION => nothing */
  140211. 59, /* DEFERRED => ID */
  140212. 59, /* IMMEDIATE => ID */
  140213. 59, /* EXCLUSIVE => ID */
  140214. 0, /* COMMIT => nothing */
  140215. 59, /* END => ID */
  140216. 59, /* ROLLBACK => ID */
  140217. 59, /* SAVEPOINT => ID */
  140218. 59, /* RELEASE => ID */
  140219. 0, /* TO => nothing */
  140220. 0, /* TABLE => nothing */
  140221. 0, /* CREATE => nothing */
  140222. 59, /* IF => ID */
  140223. 0, /* NOT => nothing */
  140224. 0, /* EXISTS => nothing */
  140225. 59, /* TEMP => ID */
  140226. 0, /* LP => nothing */
  140227. 0, /* RP => nothing */
  140228. 0, /* AS => nothing */
  140229. 59, /* WITHOUT => ID */
  140230. 0, /* COMMA => nothing */
  140231. 59, /* ABORT => ID */
  140232. 59, /* ACTION => ID */
  140233. 59, /* AFTER => ID */
  140234. 59, /* ANALYZE => ID */
  140235. 59, /* ASC => ID */
  140236. 59, /* ATTACH => ID */
  140237. 59, /* BEFORE => ID */
  140238. 59, /* BY => ID */
  140239. 59, /* CASCADE => ID */
  140240. 59, /* CAST => ID */
  140241. 59, /* CONFLICT => ID */
  140242. 59, /* DATABASE => ID */
  140243. 59, /* DESC => ID */
  140244. 59, /* DETACH => ID */
  140245. 59, /* EACH => ID */
  140246. 59, /* FAIL => ID */
  140247. 0, /* OR => nothing */
  140248. 0, /* AND => nothing */
  140249. 0, /* IS => nothing */
  140250. 59, /* MATCH => ID */
  140251. 59, /* LIKE_KW => ID */
  140252. 0, /* BETWEEN => nothing */
  140253. 0, /* IN => nothing */
  140254. 0, /* ISNULL => nothing */
  140255. 0, /* NOTNULL => nothing */
  140256. 0, /* NE => nothing */
  140257. 0, /* EQ => nothing */
  140258. 0, /* GT => nothing */
  140259. 0, /* LE => nothing */
  140260. 0, /* LT => nothing */
  140261. 0, /* GE => nothing */
  140262. 0, /* ESCAPE => nothing */
  140263. 0, /* ID => nothing */
  140264. 59, /* COLUMNKW => ID */
  140265. 59, /* DO => ID */
  140266. 59, /* FOR => ID */
  140267. 59, /* IGNORE => ID */
  140268. 59, /* INITIALLY => ID */
  140269. 59, /* INSTEAD => ID */
  140270. 59, /* NO => ID */
  140271. 59, /* KEY => ID */
  140272. 59, /* OF => ID */
  140273. 59, /* OFFSET => ID */
  140274. 59, /* PRAGMA => ID */
  140275. 59, /* RAISE => ID */
  140276. 59, /* RECURSIVE => ID */
  140277. 59, /* REPLACE => ID */
  140278. 59, /* RESTRICT => ID */
  140279. 59, /* ROW => ID */
  140280. 59, /* ROWS => ID */
  140281. 59, /* TRIGGER => ID */
  140282. 59, /* VACUUM => ID */
  140283. 59, /* VIEW => ID */
  140284. 59, /* VIRTUAL => ID */
  140285. 59, /* WITH => ID */
  140286. 59, /* CURRENT => ID */
  140287. 59, /* FOLLOWING => ID */
  140288. 59, /* PARTITION => ID */
  140289. 59, /* PRECEDING => ID */
  140290. 59, /* RANGE => ID */
  140291. 59, /* UNBOUNDED => ID */
  140292. 59, /* EXCLUDE => ID */
  140293. 59, /* GROUPS => ID */
  140294. 59, /* OTHERS => ID */
  140295. 59, /* TIES => ID */
  140296. 59, /* REINDEX => ID */
  140297. 59, /* RENAME => ID */
  140298. 59, /* CTIME_KW => ID */
  140299. };
  140300. #endif /* YYFALLBACK */
  140301. /* The following structure represents a single element of the
  140302. ** parser's stack. Information stored includes:
  140303. **
  140304. ** + The state number for the parser at this level of the stack.
  140305. **
  140306. ** + The value of the token stored at this level of the stack.
  140307. ** (In other words, the "major" token.)
  140308. **
  140309. ** + The semantic value stored at this level of the stack. This is
  140310. ** the information used by the action routines in the grammar.
  140311. ** It is sometimes called the "minor" token.
  140312. **
  140313. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  140314. ** actually contains the reduce action for the second half of the
  140315. ** SHIFTREDUCE.
  140316. */
  140317. struct yyStackEntry {
  140318. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  140319. YYCODETYPE major; /* The major token value. This is the code
  140320. ** number for the token at this stack level */
  140321. YYMINORTYPE minor; /* The user-supplied minor token value. This
  140322. ** is the value of the token */
  140323. };
  140324. typedef struct yyStackEntry yyStackEntry;
  140325. /* The state of the parser is completely contained in an instance of
  140326. ** the following structure */
  140327. struct yyParser {
  140328. yyStackEntry *yytos; /* Pointer to top element of the stack */
  140329. #ifdef YYTRACKMAXSTACKDEPTH
  140330. int yyhwm; /* High-water mark of the stack */
  140331. #endif
  140332. #ifndef YYNOERRORRECOVERY
  140333. int yyerrcnt; /* Shifts left before out of the error */
  140334. #endif
  140335. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  140336. sqlite3ParserCTX_SDECL /* A place to hold %extra_context */
  140337. #if YYSTACKDEPTH<=0
  140338. int yystksz; /* Current side of the stack */
  140339. yyStackEntry *yystack; /* The parser's stack */
  140340. yyStackEntry yystk0; /* First stack entry */
  140341. #else
  140342. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  140343. yyStackEntry *yystackEnd; /* Last entry in the stack */
  140344. #endif
  140345. };
  140346. typedef struct yyParser yyParser;
  140347. #ifndef NDEBUG
  140348. /* #include <stdio.h> */
  140349. static FILE *yyTraceFILE = 0;
  140350. static char *yyTracePrompt = 0;
  140351. #endif /* NDEBUG */
  140352. #ifndef NDEBUG
  140353. /*
  140354. ** Turn parser tracing on by giving a stream to which to write the trace
  140355. ** and a prompt to preface each trace message. Tracing is turned off
  140356. ** by making either argument NULL
  140357. **
  140358. ** Inputs:
  140359. ** <ul>
  140360. ** <li> A FILE* to which trace output should be written.
  140361. ** If NULL, then tracing is turned off.
  140362. ** <li> A prefix string written at the beginning of every
  140363. ** line of trace output. If NULL, then tracing is
  140364. ** turned off.
  140365. ** </ul>
  140366. **
  140367. ** Outputs:
  140368. ** None.
  140369. */
  140370. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  140371. yyTraceFILE = TraceFILE;
  140372. yyTracePrompt = zTracePrompt;
  140373. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  140374. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  140375. }
  140376. #endif /* NDEBUG */
  140377. #if defined(YYCOVERAGE) || !defined(NDEBUG)
  140378. /* For tracing shifts, the names of all terminals and nonterminals
  140379. ** are required. The following table supplies these names */
  140380. static const char *const yyTokenName[] = {
  140381. /* 0 */ "$",
  140382. /* 1 */ "SEMI",
  140383. /* 2 */ "EXPLAIN",
  140384. /* 3 */ "QUERY",
  140385. /* 4 */ "PLAN",
  140386. /* 5 */ "BEGIN",
  140387. /* 6 */ "TRANSACTION",
  140388. /* 7 */ "DEFERRED",
  140389. /* 8 */ "IMMEDIATE",
  140390. /* 9 */ "EXCLUSIVE",
  140391. /* 10 */ "COMMIT",
  140392. /* 11 */ "END",
  140393. /* 12 */ "ROLLBACK",
  140394. /* 13 */ "SAVEPOINT",
  140395. /* 14 */ "RELEASE",
  140396. /* 15 */ "TO",
  140397. /* 16 */ "TABLE",
  140398. /* 17 */ "CREATE",
  140399. /* 18 */ "IF",
  140400. /* 19 */ "NOT",
  140401. /* 20 */ "EXISTS",
  140402. /* 21 */ "TEMP",
  140403. /* 22 */ "LP",
  140404. /* 23 */ "RP",
  140405. /* 24 */ "AS",
  140406. /* 25 */ "WITHOUT",
  140407. /* 26 */ "COMMA",
  140408. /* 27 */ "ABORT",
  140409. /* 28 */ "ACTION",
  140410. /* 29 */ "AFTER",
  140411. /* 30 */ "ANALYZE",
  140412. /* 31 */ "ASC",
  140413. /* 32 */ "ATTACH",
  140414. /* 33 */ "BEFORE",
  140415. /* 34 */ "BY",
  140416. /* 35 */ "CASCADE",
  140417. /* 36 */ "CAST",
  140418. /* 37 */ "CONFLICT",
  140419. /* 38 */ "DATABASE",
  140420. /* 39 */ "DESC",
  140421. /* 40 */ "DETACH",
  140422. /* 41 */ "EACH",
  140423. /* 42 */ "FAIL",
  140424. /* 43 */ "OR",
  140425. /* 44 */ "AND",
  140426. /* 45 */ "IS",
  140427. /* 46 */ "MATCH",
  140428. /* 47 */ "LIKE_KW",
  140429. /* 48 */ "BETWEEN",
  140430. /* 49 */ "IN",
  140431. /* 50 */ "ISNULL",
  140432. /* 51 */ "NOTNULL",
  140433. /* 52 */ "NE",
  140434. /* 53 */ "EQ",
  140435. /* 54 */ "GT",
  140436. /* 55 */ "LE",
  140437. /* 56 */ "LT",
  140438. /* 57 */ "GE",
  140439. /* 58 */ "ESCAPE",
  140440. /* 59 */ "ID",
  140441. /* 60 */ "COLUMNKW",
  140442. /* 61 */ "DO",
  140443. /* 62 */ "FOR",
  140444. /* 63 */ "IGNORE",
  140445. /* 64 */ "INITIALLY",
  140446. /* 65 */ "INSTEAD",
  140447. /* 66 */ "NO",
  140448. /* 67 */ "KEY",
  140449. /* 68 */ "OF",
  140450. /* 69 */ "OFFSET",
  140451. /* 70 */ "PRAGMA",
  140452. /* 71 */ "RAISE",
  140453. /* 72 */ "RECURSIVE",
  140454. /* 73 */ "REPLACE",
  140455. /* 74 */ "RESTRICT",
  140456. /* 75 */ "ROW",
  140457. /* 76 */ "ROWS",
  140458. /* 77 */ "TRIGGER",
  140459. /* 78 */ "VACUUM",
  140460. /* 79 */ "VIEW",
  140461. /* 80 */ "VIRTUAL",
  140462. /* 81 */ "WITH",
  140463. /* 82 */ "CURRENT",
  140464. /* 83 */ "FOLLOWING",
  140465. /* 84 */ "PARTITION",
  140466. /* 85 */ "PRECEDING",
  140467. /* 86 */ "RANGE",
  140468. /* 87 */ "UNBOUNDED",
  140469. /* 88 */ "EXCLUDE",
  140470. /* 89 */ "GROUPS",
  140471. /* 90 */ "OTHERS",
  140472. /* 91 */ "TIES",
  140473. /* 92 */ "REINDEX",
  140474. /* 93 */ "RENAME",
  140475. /* 94 */ "CTIME_KW",
  140476. /* 95 */ "ANY",
  140477. /* 96 */ "BITAND",
  140478. /* 97 */ "BITOR",
  140479. /* 98 */ "LSHIFT",
  140480. /* 99 */ "RSHIFT",
  140481. /* 100 */ "PLUS",
  140482. /* 101 */ "MINUS",
  140483. /* 102 */ "STAR",
  140484. /* 103 */ "SLASH",
  140485. /* 104 */ "REM",
  140486. /* 105 */ "CONCAT",
  140487. /* 106 */ "COLLATE",
  140488. /* 107 */ "BITNOT",
  140489. /* 108 */ "ON",
  140490. /* 109 */ "INDEXED",
  140491. /* 110 */ "STRING",
  140492. /* 111 */ "JOIN_KW",
  140493. /* 112 */ "CONSTRAINT",
  140494. /* 113 */ "DEFAULT",
  140495. /* 114 */ "NULL",
  140496. /* 115 */ "PRIMARY",
  140497. /* 116 */ "UNIQUE",
  140498. /* 117 */ "CHECK",
  140499. /* 118 */ "REFERENCES",
  140500. /* 119 */ "AUTOINCR",
  140501. /* 120 */ "INSERT",
  140502. /* 121 */ "DELETE",
  140503. /* 122 */ "UPDATE",
  140504. /* 123 */ "SET",
  140505. /* 124 */ "DEFERRABLE",
  140506. /* 125 */ "FOREIGN",
  140507. /* 126 */ "DROP",
  140508. /* 127 */ "UNION",
  140509. /* 128 */ "ALL",
  140510. /* 129 */ "EXCEPT",
  140511. /* 130 */ "INTERSECT",
  140512. /* 131 */ "SELECT",
  140513. /* 132 */ "VALUES",
  140514. /* 133 */ "DISTINCT",
  140515. /* 134 */ "DOT",
  140516. /* 135 */ "FROM",
  140517. /* 136 */ "JOIN",
  140518. /* 137 */ "USING",
  140519. /* 138 */ "ORDER",
  140520. /* 139 */ "GROUP",
  140521. /* 140 */ "HAVING",
  140522. /* 141 */ "LIMIT",
  140523. /* 142 */ "WHERE",
  140524. /* 143 */ "INTO",
  140525. /* 144 */ "NOTHING",
  140526. /* 145 */ "FLOAT",
  140527. /* 146 */ "BLOB",
  140528. /* 147 */ "INTEGER",
  140529. /* 148 */ "VARIABLE",
  140530. /* 149 */ "CASE",
  140531. /* 150 */ "WHEN",
  140532. /* 151 */ "THEN",
  140533. /* 152 */ "ELSE",
  140534. /* 153 */ "INDEX",
  140535. /* 154 */ "ALTER",
  140536. /* 155 */ "ADD",
  140537. /* 156 */ "WINDOW",
  140538. /* 157 */ "OVER",
  140539. /* 158 */ "FILTER",
  140540. /* 159 */ "TRUEFALSE",
  140541. /* 160 */ "ISNOT",
  140542. /* 161 */ "FUNCTION",
  140543. /* 162 */ "COLUMN",
  140544. /* 163 */ "AGG_FUNCTION",
  140545. /* 164 */ "AGG_COLUMN",
  140546. /* 165 */ "UMINUS",
  140547. /* 166 */ "UPLUS",
  140548. /* 167 */ "TRUTH",
  140549. /* 168 */ "REGISTER",
  140550. /* 169 */ "VECTOR",
  140551. /* 170 */ "SELECT_COLUMN",
  140552. /* 171 */ "IF_NULL_ROW",
  140553. /* 172 */ "ASTERISK",
  140554. /* 173 */ "SPAN",
  140555. /* 174 */ "SPACE",
  140556. /* 175 */ "ILLEGAL",
  140557. /* 176 */ "input",
  140558. /* 177 */ "cmdlist",
  140559. /* 178 */ "ecmd",
  140560. /* 179 */ "cmdx",
  140561. /* 180 */ "explain",
  140562. /* 181 */ "cmd",
  140563. /* 182 */ "transtype",
  140564. /* 183 */ "trans_opt",
  140565. /* 184 */ "nm",
  140566. /* 185 */ "savepoint_opt",
  140567. /* 186 */ "create_table",
  140568. /* 187 */ "create_table_args",
  140569. /* 188 */ "createkw",
  140570. /* 189 */ "temp",
  140571. /* 190 */ "ifnotexists",
  140572. /* 191 */ "dbnm",
  140573. /* 192 */ "columnlist",
  140574. /* 193 */ "conslist_opt",
  140575. /* 194 */ "table_options",
  140576. /* 195 */ "select",
  140577. /* 196 */ "columnname",
  140578. /* 197 */ "carglist",
  140579. /* 198 */ "typetoken",
  140580. /* 199 */ "typename",
  140581. /* 200 */ "signed",
  140582. /* 201 */ "plus_num",
  140583. /* 202 */ "minus_num",
  140584. /* 203 */ "scanpt",
  140585. /* 204 */ "ccons",
  140586. /* 205 */ "term",
  140587. /* 206 */ "expr",
  140588. /* 207 */ "onconf",
  140589. /* 208 */ "sortorder",
  140590. /* 209 */ "autoinc",
  140591. /* 210 */ "eidlist_opt",
  140592. /* 211 */ "refargs",
  140593. /* 212 */ "defer_subclause",
  140594. /* 213 */ "refarg",
  140595. /* 214 */ "refact",
  140596. /* 215 */ "init_deferred_pred_opt",
  140597. /* 216 */ "conslist",
  140598. /* 217 */ "tconscomma",
  140599. /* 218 */ "tcons",
  140600. /* 219 */ "sortlist",
  140601. /* 220 */ "eidlist",
  140602. /* 221 */ "defer_subclause_opt",
  140603. /* 222 */ "orconf",
  140604. /* 223 */ "resolvetype",
  140605. /* 224 */ "raisetype",
  140606. /* 225 */ "ifexists",
  140607. /* 226 */ "fullname",
  140608. /* 227 */ "selectnowith",
  140609. /* 228 */ "oneselect",
  140610. /* 229 */ "wqlist",
  140611. /* 230 */ "multiselect_op",
  140612. /* 231 */ "distinct",
  140613. /* 232 */ "selcollist",
  140614. /* 233 */ "from",
  140615. /* 234 */ "where_opt",
  140616. /* 235 */ "groupby_opt",
  140617. /* 236 */ "having_opt",
  140618. /* 237 */ "orderby_opt",
  140619. /* 238 */ "limit_opt",
  140620. /* 239 */ "window_clause",
  140621. /* 240 */ "values",
  140622. /* 241 */ "nexprlist",
  140623. /* 242 */ "sclp",
  140624. /* 243 */ "as",
  140625. /* 244 */ "seltablist",
  140626. /* 245 */ "stl_prefix",
  140627. /* 246 */ "joinop",
  140628. /* 247 */ "indexed_opt",
  140629. /* 248 */ "on_opt",
  140630. /* 249 */ "using_opt",
  140631. /* 250 */ "exprlist",
  140632. /* 251 */ "xfullname",
  140633. /* 252 */ "idlist",
  140634. /* 253 */ "with",
  140635. /* 254 */ "setlist",
  140636. /* 255 */ "insert_cmd",
  140637. /* 256 */ "idlist_opt",
  140638. /* 257 */ "upsert",
  140639. /* 258 */ "over_clause",
  140640. /* 259 */ "likeop",
  140641. /* 260 */ "between_op",
  140642. /* 261 */ "in_op",
  140643. /* 262 */ "paren_exprlist",
  140644. /* 263 */ "case_operand",
  140645. /* 264 */ "case_exprlist",
  140646. /* 265 */ "case_else",
  140647. /* 266 */ "uniqueflag",
  140648. /* 267 */ "collate",
  140649. /* 268 */ "vinto",
  140650. /* 269 */ "nmnum",
  140651. /* 270 */ "trigger_decl",
  140652. /* 271 */ "trigger_cmd_list",
  140653. /* 272 */ "trigger_time",
  140654. /* 273 */ "trigger_event",
  140655. /* 274 */ "foreach_clause",
  140656. /* 275 */ "when_clause",
  140657. /* 276 */ "trigger_cmd",
  140658. /* 277 */ "trnm",
  140659. /* 278 */ "tridxby",
  140660. /* 279 */ "database_kw_opt",
  140661. /* 280 */ "key_opt",
  140662. /* 281 */ "add_column_fullname",
  140663. /* 282 */ "kwcolumn_opt",
  140664. /* 283 */ "create_vtab",
  140665. /* 284 */ "vtabarglist",
  140666. /* 285 */ "vtabarg",
  140667. /* 286 */ "vtabargtoken",
  140668. /* 287 */ "lp",
  140669. /* 288 */ "anylist",
  140670. /* 289 */ "windowdefn_list",
  140671. /* 290 */ "windowdefn",
  140672. /* 291 */ "window",
  140673. /* 292 */ "frame_opt",
  140674. /* 293 */ "part_opt",
  140675. /* 294 */ "filter_opt",
  140676. /* 295 */ "range_or_rows",
  140677. /* 296 */ "frame_bound",
  140678. /* 297 */ "frame_bound_s",
  140679. /* 298 */ "frame_bound_e",
  140680. /* 299 */ "frame_exclude_opt",
  140681. /* 300 */ "frame_exclude",
  140682. };
  140683. #endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
  140684. #ifndef NDEBUG
  140685. /* For tracing reduce actions, the names of all rules are required.
  140686. */
  140687. static const char *const yyRuleName[] = {
  140688. /* 0 */ "explain ::= EXPLAIN",
  140689. /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
  140690. /* 2 */ "cmdx ::= cmd",
  140691. /* 3 */ "cmd ::= BEGIN transtype trans_opt",
  140692. /* 4 */ "transtype ::=",
  140693. /* 5 */ "transtype ::= DEFERRED",
  140694. /* 6 */ "transtype ::= IMMEDIATE",
  140695. /* 7 */ "transtype ::= EXCLUSIVE",
  140696. /* 8 */ "cmd ::= COMMIT|END trans_opt",
  140697. /* 9 */ "cmd ::= ROLLBACK trans_opt",
  140698. /* 10 */ "cmd ::= SAVEPOINT nm",
  140699. /* 11 */ "cmd ::= RELEASE savepoint_opt nm",
  140700. /* 12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  140701. /* 13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  140702. /* 14 */ "createkw ::= CREATE",
  140703. /* 15 */ "ifnotexists ::=",
  140704. /* 16 */ "ifnotexists ::= IF NOT EXISTS",
  140705. /* 17 */ "temp ::= TEMP",
  140706. /* 18 */ "temp ::=",
  140707. /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  140708. /* 20 */ "create_table_args ::= AS select",
  140709. /* 21 */ "table_options ::=",
  140710. /* 22 */ "table_options ::= WITHOUT nm",
  140711. /* 23 */ "columnname ::= nm typetoken",
  140712. /* 24 */ "typetoken ::=",
  140713. /* 25 */ "typetoken ::= typename LP signed RP",
  140714. /* 26 */ "typetoken ::= typename LP signed COMMA signed RP",
  140715. /* 27 */ "typename ::= typename ID|STRING",
  140716. /* 28 */ "scanpt ::=",
  140717. /* 29 */ "ccons ::= CONSTRAINT nm",
  140718. /* 30 */ "ccons ::= DEFAULT scanpt term scanpt",
  140719. /* 31 */ "ccons ::= DEFAULT LP expr RP",
  140720. /* 32 */ "ccons ::= DEFAULT PLUS term scanpt",
  140721. /* 33 */ "ccons ::= DEFAULT MINUS term scanpt",
  140722. /* 34 */ "ccons ::= DEFAULT scanpt ID|INDEXED",
  140723. /* 35 */ "ccons ::= NOT NULL onconf",
  140724. /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  140725. /* 37 */ "ccons ::= UNIQUE onconf",
  140726. /* 38 */ "ccons ::= CHECK LP expr RP",
  140727. /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  140728. /* 40 */ "ccons ::= defer_subclause",
  140729. /* 41 */ "ccons ::= COLLATE ID|STRING",
  140730. /* 42 */ "autoinc ::=",
  140731. /* 43 */ "autoinc ::= AUTOINCR",
  140732. /* 44 */ "refargs ::=",
  140733. /* 45 */ "refargs ::= refargs refarg",
  140734. /* 46 */ "refarg ::= MATCH nm",
  140735. /* 47 */ "refarg ::= ON INSERT refact",
  140736. /* 48 */ "refarg ::= ON DELETE refact",
  140737. /* 49 */ "refarg ::= ON UPDATE refact",
  140738. /* 50 */ "refact ::= SET NULL",
  140739. /* 51 */ "refact ::= SET DEFAULT",
  140740. /* 52 */ "refact ::= CASCADE",
  140741. /* 53 */ "refact ::= RESTRICT",
  140742. /* 54 */ "refact ::= NO ACTION",
  140743. /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  140744. /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  140745. /* 57 */ "init_deferred_pred_opt ::=",
  140746. /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  140747. /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  140748. /* 60 */ "conslist_opt ::=",
  140749. /* 61 */ "tconscomma ::= COMMA",
  140750. /* 62 */ "tcons ::= CONSTRAINT nm",
  140751. /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  140752. /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  140753. /* 65 */ "tcons ::= CHECK LP expr RP onconf",
  140754. /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  140755. /* 67 */ "defer_subclause_opt ::=",
  140756. /* 68 */ "onconf ::=",
  140757. /* 69 */ "onconf ::= ON CONFLICT resolvetype",
  140758. /* 70 */ "orconf ::=",
  140759. /* 71 */ "orconf ::= OR resolvetype",
  140760. /* 72 */ "resolvetype ::= IGNORE",
  140761. /* 73 */ "resolvetype ::= REPLACE",
  140762. /* 74 */ "cmd ::= DROP TABLE ifexists fullname",
  140763. /* 75 */ "ifexists ::= IF EXISTS",
  140764. /* 76 */ "ifexists ::=",
  140765. /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  140766. /* 78 */ "cmd ::= DROP VIEW ifexists fullname",
  140767. /* 79 */ "cmd ::= select",
  140768. /* 80 */ "select ::= WITH wqlist selectnowith",
  140769. /* 81 */ "select ::= WITH RECURSIVE wqlist selectnowith",
  140770. /* 82 */ "select ::= selectnowith",
  140771. /* 83 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  140772. /* 84 */ "multiselect_op ::= UNION",
  140773. /* 85 */ "multiselect_op ::= UNION ALL",
  140774. /* 86 */ "multiselect_op ::= EXCEPT|INTERSECT",
  140775. /* 87 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  140776. /* 88 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt",
  140777. /* 89 */ "values ::= VALUES LP nexprlist RP",
  140778. /* 90 */ "values ::= values COMMA LP nexprlist RP",
  140779. /* 91 */ "distinct ::= DISTINCT",
  140780. /* 92 */ "distinct ::= ALL",
  140781. /* 93 */ "distinct ::=",
  140782. /* 94 */ "sclp ::=",
  140783. /* 95 */ "selcollist ::= sclp scanpt expr scanpt as",
  140784. /* 96 */ "selcollist ::= sclp scanpt STAR",
  140785. /* 97 */ "selcollist ::= sclp scanpt nm DOT STAR",
  140786. /* 98 */ "as ::= AS nm",
  140787. /* 99 */ "as ::=",
  140788. /* 100 */ "from ::=",
  140789. /* 101 */ "from ::= FROM seltablist",
  140790. /* 102 */ "stl_prefix ::= seltablist joinop",
  140791. /* 103 */ "stl_prefix ::=",
  140792. /* 104 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  140793. /* 105 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  140794. /* 106 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  140795. /* 107 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  140796. /* 108 */ "dbnm ::=",
  140797. /* 109 */ "dbnm ::= DOT nm",
  140798. /* 110 */ "fullname ::= nm",
  140799. /* 111 */ "fullname ::= nm DOT nm",
  140800. /* 112 */ "xfullname ::= nm",
  140801. /* 113 */ "xfullname ::= nm DOT nm",
  140802. /* 114 */ "xfullname ::= nm DOT nm AS nm",
  140803. /* 115 */ "xfullname ::= nm AS nm",
  140804. /* 116 */ "joinop ::= COMMA|JOIN",
  140805. /* 117 */ "joinop ::= JOIN_KW JOIN",
  140806. /* 118 */ "joinop ::= JOIN_KW nm JOIN",
  140807. /* 119 */ "joinop ::= JOIN_KW nm nm JOIN",
  140808. /* 120 */ "on_opt ::= ON expr",
  140809. /* 121 */ "on_opt ::=",
  140810. /* 122 */ "indexed_opt ::=",
  140811. /* 123 */ "indexed_opt ::= INDEXED BY nm",
  140812. /* 124 */ "indexed_opt ::= NOT INDEXED",
  140813. /* 125 */ "using_opt ::= USING LP idlist RP",
  140814. /* 126 */ "using_opt ::=",
  140815. /* 127 */ "orderby_opt ::=",
  140816. /* 128 */ "orderby_opt ::= ORDER BY sortlist",
  140817. /* 129 */ "sortlist ::= sortlist COMMA expr sortorder",
  140818. /* 130 */ "sortlist ::= expr sortorder",
  140819. /* 131 */ "sortorder ::= ASC",
  140820. /* 132 */ "sortorder ::= DESC",
  140821. /* 133 */ "sortorder ::=",
  140822. /* 134 */ "groupby_opt ::=",
  140823. /* 135 */ "groupby_opt ::= GROUP BY nexprlist",
  140824. /* 136 */ "having_opt ::=",
  140825. /* 137 */ "having_opt ::= HAVING expr",
  140826. /* 138 */ "limit_opt ::=",
  140827. /* 139 */ "limit_opt ::= LIMIT expr",
  140828. /* 140 */ "limit_opt ::= LIMIT expr OFFSET expr",
  140829. /* 141 */ "limit_opt ::= LIMIT expr COMMA expr",
  140830. /* 142 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt",
  140831. /* 143 */ "where_opt ::=",
  140832. /* 144 */ "where_opt ::= WHERE expr",
  140833. /* 145 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt",
  140834. /* 146 */ "setlist ::= setlist COMMA nm EQ expr",
  140835. /* 147 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
  140836. /* 148 */ "setlist ::= nm EQ expr",
  140837. /* 149 */ "setlist ::= LP idlist RP EQ expr",
  140838. /* 150 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
  140839. /* 151 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES",
  140840. /* 152 */ "upsert ::=",
  140841. /* 153 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt",
  140842. /* 154 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING",
  140843. /* 155 */ "upsert ::= ON CONFLICT DO NOTHING",
  140844. /* 156 */ "insert_cmd ::= INSERT orconf",
  140845. /* 157 */ "insert_cmd ::= REPLACE",
  140846. /* 158 */ "idlist_opt ::=",
  140847. /* 159 */ "idlist_opt ::= LP idlist RP",
  140848. /* 160 */ "idlist ::= idlist COMMA nm",
  140849. /* 161 */ "idlist ::= nm",
  140850. /* 162 */ "expr ::= LP expr RP",
  140851. /* 163 */ "expr ::= ID|INDEXED",
  140852. /* 164 */ "expr ::= JOIN_KW",
  140853. /* 165 */ "expr ::= nm DOT nm",
  140854. /* 166 */ "expr ::= nm DOT nm DOT nm",
  140855. /* 167 */ "term ::= NULL|FLOAT|BLOB",
  140856. /* 168 */ "term ::= STRING",
  140857. /* 169 */ "term ::= INTEGER",
  140858. /* 170 */ "expr ::= VARIABLE",
  140859. /* 171 */ "expr ::= expr COLLATE ID|STRING",
  140860. /* 172 */ "expr ::= CAST LP expr AS typetoken RP",
  140861. /* 173 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  140862. /* 174 */ "expr ::= ID|INDEXED LP STAR RP",
  140863. /* 175 */ "expr ::= ID|INDEXED LP distinct exprlist RP over_clause",
  140864. /* 176 */ "expr ::= ID|INDEXED LP STAR RP over_clause",
  140865. /* 177 */ "term ::= CTIME_KW",
  140866. /* 178 */ "expr ::= LP nexprlist COMMA expr RP",
  140867. /* 179 */ "expr ::= expr AND expr",
  140868. /* 180 */ "expr ::= expr OR expr",
  140869. /* 181 */ "expr ::= expr LT|GT|GE|LE expr",
  140870. /* 182 */ "expr ::= expr EQ|NE expr",
  140871. /* 183 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  140872. /* 184 */ "expr ::= expr PLUS|MINUS expr",
  140873. /* 185 */ "expr ::= expr STAR|SLASH|REM expr",
  140874. /* 186 */ "expr ::= expr CONCAT expr",
  140875. /* 187 */ "likeop ::= NOT LIKE_KW|MATCH",
  140876. /* 188 */ "expr ::= expr likeop expr",
  140877. /* 189 */ "expr ::= expr likeop expr ESCAPE expr",
  140878. /* 190 */ "expr ::= expr ISNULL|NOTNULL",
  140879. /* 191 */ "expr ::= expr NOT NULL",
  140880. /* 192 */ "expr ::= expr IS expr",
  140881. /* 193 */ "expr ::= expr IS NOT expr",
  140882. /* 194 */ "expr ::= NOT expr",
  140883. /* 195 */ "expr ::= BITNOT expr",
  140884. /* 196 */ "expr ::= PLUS|MINUS expr",
  140885. /* 197 */ "between_op ::= BETWEEN",
  140886. /* 198 */ "between_op ::= NOT BETWEEN",
  140887. /* 199 */ "expr ::= expr between_op expr AND expr",
  140888. /* 200 */ "in_op ::= IN",
  140889. /* 201 */ "in_op ::= NOT IN",
  140890. /* 202 */ "expr ::= expr in_op LP exprlist RP",
  140891. /* 203 */ "expr ::= LP select RP",
  140892. /* 204 */ "expr ::= expr in_op LP select RP",
  140893. /* 205 */ "expr ::= expr in_op nm dbnm paren_exprlist",
  140894. /* 206 */ "expr ::= EXISTS LP select RP",
  140895. /* 207 */ "expr ::= CASE case_operand case_exprlist case_else END",
  140896. /* 208 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  140897. /* 209 */ "case_exprlist ::= WHEN expr THEN expr",
  140898. /* 210 */ "case_else ::= ELSE expr",
  140899. /* 211 */ "case_else ::=",
  140900. /* 212 */ "case_operand ::= expr",
  140901. /* 213 */ "case_operand ::=",
  140902. /* 214 */ "exprlist ::=",
  140903. /* 215 */ "nexprlist ::= nexprlist COMMA expr",
  140904. /* 216 */ "nexprlist ::= expr",
  140905. /* 217 */ "paren_exprlist ::=",
  140906. /* 218 */ "paren_exprlist ::= LP exprlist RP",
  140907. /* 219 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  140908. /* 220 */ "uniqueflag ::= UNIQUE",
  140909. /* 221 */ "uniqueflag ::=",
  140910. /* 222 */ "eidlist_opt ::=",
  140911. /* 223 */ "eidlist_opt ::= LP eidlist RP",
  140912. /* 224 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  140913. /* 225 */ "eidlist ::= nm collate sortorder",
  140914. /* 226 */ "collate ::=",
  140915. /* 227 */ "collate ::= COLLATE ID|STRING",
  140916. /* 228 */ "cmd ::= DROP INDEX ifexists fullname",
  140917. /* 229 */ "cmd ::= VACUUM vinto",
  140918. /* 230 */ "cmd ::= VACUUM nm vinto",
  140919. /* 231 */ "vinto ::= INTO expr",
  140920. /* 232 */ "vinto ::=",
  140921. /* 233 */ "cmd ::= PRAGMA nm dbnm",
  140922. /* 234 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  140923. /* 235 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  140924. /* 236 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  140925. /* 237 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  140926. /* 238 */ "plus_num ::= PLUS INTEGER|FLOAT",
  140927. /* 239 */ "minus_num ::= MINUS INTEGER|FLOAT",
  140928. /* 240 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  140929. /* 241 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  140930. /* 242 */ "trigger_time ::= BEFORE|AFTER",
  140931. /* 243 */ "trigger_time ::= INSTEAD OF",
  140932. /* 244 */ "trigger_time ::=",
  140933. /* 245 */ "trigger_event ::= DELETE|INSERT",
  140934. /* 246 */ "trigger_event ::= UPDATE",
  140935. /* 247 */ "trigger_event ::= UPDATE OF idlist",
  140936. /* 248 */ "when_clause ::=",
  140937. /* 249 */ "when_clause ::= WHEN expr",
  140938. /* 250 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  140939. /* 251 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  140940. /* 252 */ "trnm ::= nm DOT nm",
  140941. /* 253 */ "tridxby ::= INDEXED BY nm",
  140942. /* 254 */ "tridxby ::= NOT INDEXED",
  140943. /* 255 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt",
  140944. /* 256 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
  140945. /* 257 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
  140946. /* 258 */ "trigger_cmd ::= scanpt select scanpt",
  140947. /* 259 */ "expr ::= RAISE LP IGNORE RP",
  140948. /* 260 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  140949. /* 261 */ "raisetype ::= ROLLBACK",
  140950. /* 262 */ "raisetype ::= ABORT",
  140951. /* 263 */ "raisetype ::= FAIL",
  140952. /* 264 */ "cmd ::= DROP TRIGGER ifexists fullname",
  140953. /* 265 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  140954. /* 266 */ "cmd ::= DETACH database_kw_opt expr",
  140955. /* 267 */ "key_opt ::=",
  140956. /* 268 */ "key_opt ::= KEY expr",
  140957. /* 269 */ "cmd ::= REINDEX",
  140958. /* 270 */ "cmd ::= REINDEX nm dbnm",
  140959. /* 271 */ "cmd ::= ANALYZE",
  140960. /* 272 */ "cmd ::= ANALYZE nm dbnm",
  140961. /* 273 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  140962. /* 274 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
  140963. /* 275 */ "add_column_fullname ::= fullname",
  140964. /* 276 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
  140965. /* 277 */ "cmd ::= create_vtab",
  140966. /* 278 */ "cmd ::= create_vtab LP vtabarglist RP",
  140967. /* 279 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  140968. /* 280 */ "vtabarg ::=",
  140969. /* 281 */ "vtabargtoken ::= ANY",
  140970. /* 282 */ "vtabargtoken ::= lp anylist RP",
  140971. /* 283 */ "lp ::= LP",
  140972. /* 284 */ "with ::= WITH wqlist",
  140973. /* 285 */ "with ::= WITH RECURSIVE wqlist",
  140974. /* 286 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  140975. /* 287 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  140976. /* 288 */ "windowdefn_list ::= windowdefn",
  140977. /* 289 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
  140978. /* 290 */ "windowdefn ::= nm AS LP window RP",
  140979. /* 291 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
  140980. /* 292 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
  140981. /* 293 */ "window ::= ORDER BY sortlist frame_opt",
  140982. /* 294 */ "window ::= nm ORDER BY sortlist frame_opt",
  140983. /* 295 */ "window ::= frame_opt",
  140984. /* 296 */ "window ::= nm frame_opt",
  140985. /* 297 */ "frame_opt ::=",
  140986. /* 298 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
  140987. /* 299 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
  140988. /* 300 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
  140989. /* 301 */ "frame_bound_s ::= frame_bound",
  140990. /* 302 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
  140991. /* 303 */ "frame_bound_e ::= frame_bound",
  140992. /* 304 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
  140993. /* 305 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
  140994. /* 306 */ "frame_bound ::= CURRENT ROW",
  140995. /* 307 */ "frame_exclude_opt ::=",
  140996. /* 308 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
  140997. /* 309 */ "frame_exclude ::= NO OTHERS",
  140998. /* 310 */ "frame_exclude ::= CURRENT ROW",
  140999. /* 311 */ "frame_exclude ::= GROUP|TIES",
  141000. /* 312 */ "window_clause ::= WINDOW windowdefn_list",
  141001. /* 313 */ "over_clause ::= filter_opt OVER LP window RP",
  141002. /* 314 */ "over_clause ::= filter_opt OVER nm",
  141003. /* 315 */ "filter_opt ::=",
  141004. /* 316 */ "filter_opt ::= FILTER LP WHERE expr RP",
  141005. /* 317 */ "input ::= cmdlist",
  141006. /* 318 */ "cmdlist ::= cmdlist ecmd",
  141007. /* 319 */ "cmdlist ::= ecmd",
  141008. /* 320 */ "ecmd ::= SEMI",
  141009. /* 321 */ "ecmd ::= cmdx SEMI",
  141010. /* 322 */ "ecmd ::= explain cmdx",
  141011. /* 323 */ "trans_opt ::=",
  141012. /* 324 */ "trans_opt ::= TRANSACTION",
  141013. /* 325 */ "trans_opt ::= TRANSACTION nm",
  141014. /* 326 */ "savepoint_opt ::= SAVEPOINT",
  141015. /* 327 */ "savepoint_opt ::=",
  141016. /* 328 */ "cmd ::= create_table create_table_args",
  141017. /* 329 */ "columnlist ::= columnlist COMMA columnname carglist",
  141018. /* 330 */ "columnlist ::= columnname carglist",
  141019. /* 331 */ "nm ::= ID|INDEXED",
  141020. /* 332 */ "nm ::= STRING",
  141021. /* 333 */ "nm ::= JOIN_KW",
  141022. /* 334 */ "typetoken ::= typename",
  141023. /* 335 */ "typename ::= ID|STRING",
  141024. /* 336 */ "signed ::= plus_num",
  141025. /* 337 */ "signed ::= minus_num",
  141026. /* 338 */ "carglist ::= carglist ccons",
  141027. /* 339 */ "carglist ::=",
  141028. /* 340 */ "ccons ::= NULL onconf",
  141029. /* 341 */ "conslist_opt ::= COMMA conslist",
  141030. /* 342 */ "conslist ::= conslist tconscomma tcons",
  141031. /* 343 */ "conslist ::= tcons",
  141032. /* 344 */ "tconscomma ::=",
  141033. /* 345 */ "defer_subclause_opt ::= defer_subclause",
  141034. /* 346 */ "resolvetype ::= raisetype",
  141035. /* 347 */ "selectnowith ::= oneselect",
  141036. /* 348 */ "oneselect ::= values",
  141037. /* 349 */ "sclp ::= selcollist COMMA",
  141038. /* 350 */ "as ::= ID|STRING",
  141039. /* 351 */ "expr ::= term",
  141040. /* 352 */ "likeop ::= LIKE_KW|MATCH",
  141041. /* 353 */ "exprlist ::= nexprlist",
  141042. /* 354 */ "nmnum ::= plus_num",
  141043. /* 355 */ "nmnum ::= nm",
  141044. /* 356 */ "nmnum ::= ON",
  141045. /* 357 */ "nmnum ::= DELETE",
  141046. /* 358 */ "nmnum ::= DEFAULT",
  141047. /* 359 */ "plus_num ::= INTEGER|FLOAT",
  141048. /* 360 */ "foreach_clause ::=",
  141049. /* 361 */ "foreach_clause ::= FOR EACH ROW",
  141050. /* 362 */ "trnm ::= nm",
  141051. /* 363 */ "tridxby ::=",
  141052. /* 364 */ "database_kw_opt ::= DATABASE",
  141053. /* 365 */ "database_kw_opt ::=",
  141054. /* 366 */ "kwcolumn_opt ::=",
  141055. /* 367 */ "kwcolumn_opt ::= COLUMNKW",
  141056. /* 368 */ "vtabarglist ::= vtabarg",
  141057. /* 369 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  141058. /* 370 */ "vtabarg ::= vtabarg vtabargtoken",
  141059. /* 371 */ "anylist ::=",
  141060. /* 372 */ "anylist ::= anylist LP anylist RP",
  141061. /* 373 */ "anylist ::= anylist ANY",
  141062. /* 374 */ "with ::=",
  141063. };
  141064. #endif /* NDEBUG */
  141065. #if YYSTACKDEPTH<=0
  141066. /*
  141067. ** Try to increase the size of the parser stack. Return the number
  141068. ** of errors. Return 0 on success.
  141069. */
  141070. static int yyGrowStack(yyParser *p){
  141071. int newSize;
  141072. int idx;
  141073. yyStackEntry *pNew;
  141074. newSize = p->yystksz*2 + 100;
  141075. idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
  141076. if( p->yystack==&p->yystk0 ){
  141077. pNew = malloc(newSize*sizeof(pNew[0]));
  141078. if( pNew ) pNew[0] = p->yystk0;
  141079. }else{
  141080. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  141081. }
  141082. if( pNew ){
  141083. p->yystack = pNew;
  141084. p->yytos = &p->yystack[idx];
  141085. #ifndef NDEBUG
  141086. if( yyTraceFILE ){
  141087. fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  141088. yyTracePrompt, p->yystksz, newSize);
  141089. }
  141090. #endif
  141091. p->yystksz = newSize;
  141092. }
  141093. return pNew==0;
  141094. }
  141095. #endif
  141096. /* Datatype of the argument to the memory allocated passed as the
  141097. ** second argument to sqlite3ParserAlloc() below. This can be changed by
  141098. ** putting an appropriate #define in the %include section of the input
  141099. ** grammar.
  141100. */
  141101. #ifndef YYMALLOCARGTYPE
  141102. # define YYMALLOCARGTYPE size_t
  141103. #endif
  141104. /* Initialize a new parser that has already been allocated.
  141105. */
  141106. SQLITE_PRIVATE void sqlite3ParserInit(void *yypRawParser sqlite3ParserCTX_PDECL){
  141107. yyParser *yypParser = (yyParser*)yypRawParser;
  141108. sqlite3ParserCTX_STORE
  141109. #ifdef YYTRACKMAXSTACKDEPTH
  141110. yypParser->yyhwm = 0;
  141111. #endif
  141112. #if YYSTACKDEPTH<=0
  141113. yypParser->yytos = NULL;
  141114. yypParser->yystack = NULL;
  141115. yypParser->yystksz = 0;
  141116. if( yyGrowStack(yypParser) ){
  141117. yypParser->yystack = &yypParser->yystk0;
  141118. yypParser->yystksz = 1;
  141119. }
  141120. #endif
  141121. #ifndef YYNOERRORRECOVERY
  141122. yypParser->yyerrcnt = -1;
  141123. #endif
  141124. yypParser->yytos = yypParser->yystack;
  141125. yypParser->yystack[0].stateno = 0;
  141126. yypParser->yystack[0].major = 0;
  141127. #if YYSTACKDEPTH>0
  141128. yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1];
  141129. #endif
  141130. }
  141131. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  141132. /*
  141133. ** This function allocates a new parser.
  141134. ** The only argument is a pointer to a function which works like
  141135. ** malloc.
  141136. **
  141137. ** Inputs:
  141138. ** A pointer to the function used to allocate memory.
  141139. **
  141140. ** Outputs:
  141141. ** A pointer to a parser. This pointer is used in subsequent calls
  141142. ** to sqlite3Parser and sqlite3ParserFree.
  141143. */
  141144. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) sqlite3ParserCTX_PDECL){
  141145. yyParser *yypParser;
  141146. yypParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
  141147. if( yypParser ){
  141148. sqlite3ParserCTX_STORE
  141149. sqlite3ParserInit(yypParser sqlite3ParserCTX_PARAM);
  141150. }
  141151. return (void*)yypParser;
  141152. }
  141153. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  141154. /* The following function deletes the "minor type" or semantic value
  141155. ** associated with a symbol. The symbol can be either a terminal
  141156. ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
  141157. ** a pointer to the value to be deleted. The code used to do the
  141158. ** deletions is derived from the %destructor and/or %token_destructor
  141159. ** directives of the input grammar.
  141160. */
  141161. static void yy_destructor(
  141162. yyParser *yypParser, /* The parser */
  141163. YYCODETYPE yymajor, /* Type code for object to destroy */
  141164. YYMINORTYPE *yypminor /* The object to be destroyed */
  141165. ){
  141166. sqlite3ParserARG_FETCH
  141167. sqlite3ParserCTX_FETCH
  141168. switch( yymajor ){
  141169. /* Here is inserted the actions which take place when a
  141170. ** terminal or non-terminal is destroyed. This can happen
  141171. ** when the symbol is popped from the stack during a
  141172. ** reduce or during error processing or when a parser is
  141173. ** being destroyed before it is finished parsing.
  141174. **
  141175. ** Note: during a reduce, the only symbols destroyed are those
  141176. ** which appear on the RHS of the rule, but which are *not* used
  141177. ** inside the C code.
  141178. */
  141179. /********* Begin destructor definitions ***************************************/
  141180. case 195: /* select */
  141181. case 227: /* selectnowith */
  141182. case 228: /* oneselect */
  141183. case 240: /* values */
  141184. {
  141185. sqlite3SelectDelete(pParse->db, (yypminor->yy457));
  141186. }
  141187. break;
  141188. case 205: /* term */
  141189. case 206: /* expr */
  141190. case 234: /* where_opt */
  141191. case 236: /* having_opt */
  141192. case 248: /* on_opt */
  141193. case 263: /* case_operand */
  141194. case 265: /* case_else */
  141195. case 268: /* vinto */
  141196. case 275: /* when_clause */
  141197. case 280: /* key_opt */
  141198. case 294: /* filter_opt */
  141199. {
  141200. sqlite3ExprDelete(pParse->db, (yypminor->yy524));
  141201. }
  141202. break;
  141203. case 210: /* eidlist_opt */
  141204. case 219: /* sortlist */
  141205. case 220: /* eidlist */
  141206. case 232: /* selcollist */
  141207. case 235: /* groupby_opt */
  141208. case 237: /* orderby_opt */
  141209. case 241: /* nexprlist */
  141210. case 242: /* sclp */
  141211. case 250: /* exprlist */
  141212. case 254: /* setlist */
  141213. case 262: /* paren_exprlist */
  141214. case 264: /* case_exprlist */
  141215. case 293: /* part_opt */
  141216. {
  141217. sqlite3ExprListDelete(pParse->db, (yypminor->yy434));
  141218. }
  141219. break;
  141220. case 226: /* fullname */
  141221. case 233: /* from */
  141222. case 244: /* seltablist */
  141223. case 245: /* stl_prefix */
  141224. case 251: /* xfullname */
  141225. {
  141226. sqlite3SrcListDelete(pParse->db, (yypminor->yy483));
  141227. }
  141228. break;
  141229. case 229: /* wqlist */
  141230. {
  141231. sqlite3WithDelete(pParse->db, (yypminor->yy59));
  141232. }
  141233. break;
  141234. case 239: /* window_clause */
  141235. case 289: /* windowdefn_list */
  141236. {
  141237. sqlite3WindowListDelete(pParse->db, (yypminor->yy295));
  141238. }
  141239. break;
  141240. case 249: /* using_opt */
  141241. case 252: /* idlist */
  141242. case 256: /* idlist_opt */
  141243. {
  141244. sqlite3IdListDelete(pParse->db, (yypminor->yy62));
  141245. }
  141246. break;
  141247. case 258: /* over_clause */
  141248. case 290: /* windowdefn */
  141249. case 291: /* window */
  141250. case 292: /* frame_opt */
  141251. {
  141252. sqlite3WindowDelete(pParse->db, (yypminor->yy295));
  141253. }
  141254. break;
  141255. case 271: /* trigger_cmd_list */
  141256. case 276: /* trigger_cmd */
  141257. {
  141258. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy455));
  141259. }
  141260. break;
  141261. case 273: /* trigger_event */
  141262. {
  141263. sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
  141264. }
  141265. break;
  141266. case 296: /* frame_bound */
  141267. case 297: /* frame_bound_s */
  141268. case 298: /* frame_bound_e */
  141269. {
  141270. sqlite3ExprDelete(pParse->db, (yypminor->yy201).pExpr);
  141271. }
  141272. break;
  141273. /********* End destructor definitions *****************************************/
  141274. default: break; /* If no destructor action specified: do nothing */
  141275. }
  141276. }
  141277. /*
  141278. ** Pop the parser's stack once.
  141279. **
  141280. ** If there is a destructor routine associated with the token which
  141281. ** is popped from the stack, then call it.
  141282. */
  141283. static void yy_pop_parser_stack(yyParser *pParser){
  141284. yyStackEntry *yytos;
  141285. assert( pParser->yytos!=0 );
  141286. assert( pParser->yytos > pParser->yystack );
  141287. yytos = pParser->yytos--;
  141288. #ifndef NDEBUG
  141289. if( yyTraceFILE ){
  141290. fprintf(yyTraceFILE,"%sPopping %s\n",
  141291. yyTracePrompt,
  141292. yyTokenName[yytos->major]);
  141293. }
  141294. #endif
  141295. yy_destructor(pParser, yytos->major, &yytos->minor);
  141296. }
  141297. /*
  141298. ** Clear all secondary memory allocations from the parser
  141299. */
  141300. SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
  141301. yyParser *pParser = (yyParser*)p;
  141302. while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
  141303. #if YYSTACKDEPTH<=0
  141304. if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
  141305. #endif
  141306. }
  141307. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  141308. /*
  141309. ** Deallocate and destroy a parser. Destructors are called for
  141310. ** all stack elements before shutting the parser down.
  141311. **
  141312. ** If the YYPARSEFREENEVERNULL macro exists (for example because it
  141313. ** is defined in a %include section of the input grammar) then it is
  141314. ** assumed that the input pointer is never NULL.
  141315. */
  141316. SQLITE_PRIVATE void sqlite3ParserFree(
  141317. void *p, /* The parser to be deleted */
  141318. void (*freeProc)(void*) /* Function used to reclaim memory */
  141319. ){
  141320. #ifndef YYPARSEFREENEVERNULL
  141321. if( p==0 ) return;
  141322. #endif
  141323. sqlite3ParserFinalize(p);
  141324. (*freeProc)(p);
  141325. }
  141326. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  141327. /*
  141328. ** Return the peak depth of the stack for a parser.
  141329. */
  141330. #ifdef YYTRACKMAXSTACKDEPTH
  141331. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  141332. yyParser *pParser = (yyParser*)p;
  141333. return pParser->yyhwm;
  141334. }
  141335. #endif
  141336. /* This array of booleans keeps track of the parser statement
  141337. ** coverage. The element yycoverage[X][Y] is set when the parser
  141338. ** is in state X and has a lookahead token Y. In a well-tested
  141339. ** systems, every element of this matrix should end up being set.
  141340. */
  141341. #if defined(YYCOVERAGE)
  141342. static unsigned char yycoverage[YYNSTATE][YYNTOKEN];
  141343. #endif
  141344. /*
  141345. ** Write into out a description of every state/lookahead combination that
  141346. **
  141347. ** (1) has not been used by the parser, and
  141348. ** (2) is not a syntax error.
  141349. **
  141350. ** Return the number of missed state/lookahead combinations.
  141351. */
  141352. #if defined(YYCOVERAGE)
  141353. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){
  141354. int stateno, iLookAhead, i;
  141355. int nMissed = 0;
  141356. for(stateno=0; stateno<YYNSTATE; stateno++){
  141357. i = yy_shift_ofst[stateno];
  141358. for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){
  141359. if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  141360. if( yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  141361. if( out ){
  141362. fprintf(out,"State %d lookahead %s %s\n", stateno,
  141363. yyTokenName[iLookAhead],
  141364. yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  141365. }
  141366. }
  141367. }
  141368. return nMissed;
  141369. }
  141370. #endif
  141371. /*
  141372. ** Find the appropriate action for a parser given the terminal
  141373. ** look-ahead token iLookAhead.
  141374. */
  141375. static YYACTIONTYPE yy_find_shift_action(
  141376. YYCODETYPE iLookAhead, /* The look-ahead token */
  141377. YYACTIONTYPE stateno /* Current state number */
  141378. ){
  141379. int i;
  141380. if( stateno>YY_MAX_SHIFT ) return stateno;
  141381. assert( stateno <= YY_SHIFT_COUNT );
  141382. #if defined(YYCOVERAGE)
  141383. yycoverage[stateno][iLookAhead] = 1;
  141384. #endif
  141385. do{
  141386. i = yy_shift_ofst[stateno];
  141387. assert( i>=0 );
  141388. /* assert( i+YYNTOKEN<=(int)YY_NLOOKAHEAD ); */
  141389. assert( iLookAhead!=YYNOCODE );
  141390. assert( iLookAhead < YYNTOKEN );
  141391. i += iLookAhead;
  141392. if( i>=YY_NLOOKAHEAD || yy_lookahead[i]!=iLookAhead ){
  141393. #ifdef YYFALLBACK
  141394. YYCODETYPE iFallback; /* Fallback token */
  141395. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  141396. && (iFallback = yyFallback[iLookAhead])!=0 ){
  141397. #ifndef NDEBUG
  141398. if( yyTraceFILE ){
  141399. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  141400. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  141401. }
  141402. #endif
  141403. assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  141404. iLookAhead = iFallback;
  141405. continue;
  141406. }
  141407. #endif
  141408. #ifdef YYWILDCARD
  141409. {
  141410. int j = i - iLookAhead + YYWILDCARD;
  141411. if(
  141412. #if YY_SHIFT_MIN+YYWILDCARD<0
  141413. j>=0 &&
  141414. #endif
  141415. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  141416. j<YY_ACTTAB_COUNT &&
  141417. #endif
  141418. j<(int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])) &&
  141419. yy_lookahead[j]==YYWILDCARD && iLookAhead>0
  141420. ){
  141421. #ifndef NDEBUG
  141422. if( yyTraceFILE ){
  141423. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  141424. yyTracePrompt, yyTokenName[iLookAhead],
  141425. yyTokenName[YYWILDCARD]);
  141426. }
  141427. #endif /* NDEBUG */
  141428. return yy_action[j];
  141429. }
  141430. }
  141431. #endif /* YYWILDCARD */
  141432. return yy_default[stateno];
  141433. }else{
  141434. return yy_action[i];
  141435. }
  141436. }while(1);
  141437. }
  141438. /*
  141439. ** Find the appropriate action for a parser given the non-terminal
  141440. ** look-ahead token iLookAhead.
  141441. */
  141442. static YYACTIONTYPE yy_find_reduce_action(
  141443. YYACTIONTYPE stateno, /* Current state number */
  141444. YYCODETYPE iLookAhead /* The look-ahead token */
  141445. ){
  141446. int i;
  141447. #ifdef YYERRORSYMBOL
  141448. if( stateno>YY_REDUCE_COUNT ){
  141449. return yy_default[stateno];
  141450. }
  141451. #else
  141452. assert( stateno<=YY_REDUCE_COUNT );
  141453. #endif
  141454. i = yy_reduce_ofst[stateno];
  141455. assert( iLookAhead!=YYNOCODE );
  141456. i += iLookAhead;
  141457. #ifdef YYERRORSYMBOL
  141458. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  141459. return yy_default[stateno];
  141460. }
  141461. #else
  141462. assert( i>=0 && i<YY_ACTTAB_COUNT );
  141463. assert( yy_lookahead[i]==iLookAhead );
  141464. #endif
  141465. return yy_action[i];
  141466. }
  141467. /*
  141468. ** The following routine is called if the stack overflows.
  141469. */
  141470. static void yyStackOverflow(yyParser *yypParser){
  141471. sqlite3ParserARG_FETCH
  141472. sqlite3ParserCTX_FETCH
  141473. #ifndef NDEBUG
  141474. if( yyTraceFILE ){
  141475. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  141476. }
  141477. #endif
  141478. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  141479. /* Here code is inserted which will execute if the parser
  141480. ** stack every overflows */
  141481. /******** Begin %stack_overflow code ******************************************/
  141482. sqlite3ErrorMsg(pParse, "parser stack overflow");
  141483. /******** End %stack_overflow code ********************************************/
  141484. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */
  141485. sqlite3ParserCTX_STORE
  141486. }
  141487. /*
  141488. ** Print tracing information for a SHIFT action
  141489. */
  141490. #ifndef NDEBUG
  141491. static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){
  141492. if( yyTraceFILE ){
  141493. if( yyNewState<YYNSTATE ){
  141494. fprintf(yyTraceFILE,"%s%s '%s', go to state %d\n",
  141495. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  141496. yyNewState);
  141497. }else{
  141498. fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  141499. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  141500. yyNewState - YY_MIN_REDUCE);
  141501. }
  141502. }
  141503. }
  141504. #else
  141505. # define yyTraceShift(X,Y,Z)
  141506. #endif
  141507. /*
  141508. ** Perform a shift action.
  141509. */
  141510. static void yy_shift(
  141511. yyParser *yypParser, /* The parser to be shifted */
  141512. YYACTIONTYPE yyNewState, /* The new state to shift in */
  141513. YYCODETYPE yyMajor, /* The major token to shift in */
  141514. sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
  141515. ){
  141516. yyStackEntry *yytos;
  141517. yypParser->yytos++;
  141518. #ifdef YYTRACKMAXSTACKDEPTH
  141519. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  141520. yypParser->yyhwm++;
  141521. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
  141522. }
  141523. #endif
  141524. #if YYSTACKDEPTH>0
  141525. if( yypParser->yytos>yypParser->yystackEnd ){
  141526. yypParser->yytos--;
  141527. yyStackOverflow(yypParser);
  141528. return;
  141529. }
  141530. #else
  141531. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
  141532. if( yyGrowStack(yypParser) ){
  141533. yypParser->yytos--;
  141534. yyStackOverflow(yypParser);
  141535. return;
  141536. }
  141537. }
  141538. #endif
  141539. if( yyNewState > YY_MAX_SHIFT ){
  141540. yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  141541. }
  141542. yytos = yypParser->yytos;
  141543. yytos->stateno = yyNewState;
  141544. yytos->major = yyMajor;
  141545. yytos->minor.yy0 = yyMinor;
  141546. yyTraceShift(yypParser, yyNewState, "Shift");
  141547. }
  141548. /* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side
  141549. ** of that rule */
  141550. static const YYCODETYPE yyRuleInfoLhs[] = {
  141551. 180, /* (0) explain ::= EXPLAIN */
  141552. 180, /* (1) explain ::= EXPLAIN QUERY PLAN */
  141553. 179, /* (2) cmdx ::= cmd */
  141554. 181, /* (3) cmd ::= BEGIN transtype trans_opt */
  141555. 182, /* (4) transtype ::= */
  141556. 182, /* (5) transtype ::= DEFERRED */
  141557. 182, /* (6) transtype ::= IMMEDIATE */
  141558. 182, /* (7) transtype ::= EXCLUSIVE */
  141559. 181, /* (8) cmd ::= COMMIT|END trans_opt */
  141560. 181, /* (9) cmd ::= ROLLBACK trans_opt */
  141561. 181, /* (10) cmd ::= SAVEPOINT nm */
  141562. 181, /* (11) cmd ::= RELEASE savepoint_opt nm */
  141563. 181, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  141564. 186, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  141565. 188, /* (14) createkw ::= CREATE */
  141566. 190, /* (15) ifnotexists ::= */
  141567. 190, /* (16) ifnotexists ::= IF NOT EXISTS */
  141568. 189, /* (17) temp ::= TEMP */
  141569. 189, /* (18) temp ::= */
  141570. 187, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
  141571. 187, /* (20) create_table_args ::= AS select */
  141572. 194, /* (21) table_options ::= */
  141573. 194, /* (22) table_options ::= WITHOUT nm */
  141574. 196, /* (23) columnname ::= nm typetoken */
  141575. 198, /* (24) typetoken ::= */
  141576. 198, /* (25) typetoken ::= typename LP signed RP */
  141577. 198, /* (26) typetoken ::= typename LP signed COMMA signed RP */
  141578. 199, /* (27) typename ::= typename ID|STRING */
  141579. 203, /* (28) scanpt ::= */
  141580. 204, /* (29) ccons ::= CONSTRAINT nm */
  141581. 204, /* (30) ccons ::= DEFAULT scanpt term scanpt */
  141582. 204, /* (31) ccons ::= DEFAULT LP expr RP */
  141583. 204, /* (32) ccons ::= DEFAULT PLUS term scanpt */
  141584. 204, /* (33) ccons ::= DEFAULT MINUS term scanpt */
  141585. 204, /* (34) ccons ::= DEFAULT scanpt ID|INDEXED */
  141586. 204, /* (35) ccons ::= NOT NULL onconf */
  141587. 204, /* (36) ccons ::= PRIMARY KEY sortorder onconf autoinc */
  141588. 204, /* (37) ccons ::= UNIQUE onconf */
  141589. 204, /* (38) ccons ::= CHECK LP expr RP */
  141590. 204, /* (39) ccons ::= REFERENCES nm eidlist_opt refargs */
  141591. 204, /* (40) ccons ::= defer_subclause */
  141592. 204, /* (41) ccons ::= COLLATE ID|STRING */
  141593. 209, /* (42) autoinc ::= */
  141594. 209, /* (43) autoinc ::= AUTOINCR */
  141595. 211, /* (44) refargs ::= */
  141596. 211, /* (45) refargs ::= refargs refarg */
  141597. 213, /* (46) refarg ::= MATCH nm */
  141598. 213, /* (47) refarg ::= ON INSERT refact */
  141599. 213, /* (48) refarg ::= ON DELETE refact */
  141600. 213, /* (49) refarg ::= ON UPDATE refact */
  141601. 214, /* (50) refact ::= SET NULL */
  141602. 214, /* (51) refact ::= SET DEFAULT */
  141603. 214, /* (52) refact ::= CASCADE */
  141604. 214, /* (53) refact ::= RESTRICT */
  141605. 214, /* (54) refact ::= NO ACTION */
  141606. 212, /* (55) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  141607. 212, /* (56) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  141608. 215, /* (57) init_deferred_pred_opt ::= */
  141609. 215, /* (58) init_deferred_pred_opt ::= INITIALLY DEFERRED */
  141610. 215, /* (59) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  141611. 193, /* (60) conslist_opt ::= */
  141612. 217, /* (61) tconscomma ::= COMMA */
  141613. 218, /* (62) tcons ::= CONSTRAINT nm */
  141614. 218, /* (63) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  141615. 218, /* (64) tcons ::= UNIQUE LP sortlist RP onconf */
  141616. 218, /* (65) tcons ::= CHECK LP expr RP onconf */
  141617. 218, /* (66) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  141618. 221, /* (67) defer_subclause_opt ::= */
  141619. 207, /* (68) onconf ::= */
  141620. 207, /* (69) onconf ::= ON CONFLICT resolvetype */
  141621. 222, /* (70) orconf ::= */
  141622. 222, /* (71) orconf ::= OR resolvetype */
  141623. 223, /* (72) resolvetype ::= IGNORE */
  141624. 223, /* (73) resolvetype ::= REPLACE */
  141625. 181, /* (74) cmd ::= DROP TABLE ifexists fullname */
  141626. 225, /* (75) ifexists ::= IF EXISTS */
  141627. 225, /* (76) ifexists ::= */
  141628. 181, /* (77) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  141629. 181, /* (78) cmd ::= DROP VIEW ifexists fullname */
  141630. 181, /* (79) cmd ::= select */
  141631. 195, /* (80) select ::= WITH wqlist selectnowith */
  141632. 195, /* (81) select ::= WITH RECURSIVE wqlist selectnowith */
  141633. 195, /* (82) select ::= selectnowith */
  141634. 227, /* (83) selectnowith ::= selectnowith multiselect_op oneselect */
  141635. 230, /* (84) multiselect_op ::= UNION */
  141636. 230, /* (85) multiselect_op ::= UNION ALL */
  141637. 230, /* (86) multiselect_op ::= EXCEPT|INTERSECT */
  141638. 228, /* (87) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  141639. 228, /* (88) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
  141640. 240, /* (89) values ::= VALUES LP nexprlist RP */
  141641. 240, /* (90) values ::= values COMMA LP nexprlist RP */
  141642. 231, /* (91) distinct ::= DISTINCT */
  141643. 231, /* (92) distinct ::= ALL */
  141644. 231, /* (93) distinct ::= */
  141645. 242, /* (94) sclp ::= */
  141646. 232, /* (95) selcollist ::= sclp scanpt expr scanpt as */
  141647. 232, /* (96) selcollist ::= sclp scanpt STAR */
  141648. 232, /* (97) selcollist ::= sclp scanpt nm DOT STAR */
  141649. 243, /* (98) as ::= AS nm */
  141650. 243, /* (99) as ::= */
  141651. 233, /* (100) from ::= */
  141652. 233, /* (101) from ::= FROM seltablist */
  141653. 245, /* (102) stl_prefix ::= seltablist joinop */
  141654. 245, /* (103) stl_prefix ::= */
  141655. 244, /* (104) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  141656. 244, /* (105) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  141657. 244, /* (106) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  141658. 244, /* (107) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  141659. 191, /* (108) dbnm ::= */
  141660. 191, /* (109) dbnm ::= DOT nm */
  141661. 226, /* (110) fullname ::= nm */
  141662. 226, /* (111) fullname ::= nm DOT nm */
  141663. 251, /* (112) xfullname ::= nm */
  141664. 251, /* (113) xfullname ::= nm DOT nm */
  141665. 251, /* (114) xfullname ::= nm DOT nm AS nm */
  141666. 251, /* (115) xfullname ::= nm AS nm */
  141667. 246, /* (116) joinop ::= COMMA|JOIN */
  141668. 246, /* (117) joinop ::= JOIN_KW JOIN */
  141669. 246, /* (118) joinop ::= JOIN_KW nm JOIN */
  141670. 246, /* (119) joinop ::= JOIN_KW nm nm JOIN */
  141671. 248, /* (120) on_opt ::= ON expr */
  141672. 248, /* (121) on_opt ::= */
  141673. 247, /* (122) indexed_opt ::= */
  141674. 247, /* (123) indexed_opt ::= INDEXED BY nm */
  141675. 247, /* (124) indexed_opt ::= NOT INDEXED */
  141676. 249, /* (125) using_opt ::= USING LP idlist RP */
  141677. 249, /* (126) using_opt ::= */
  141678. 237, /* (127) orderby_opt ::= */
  141679. 237, /* (128) orderby_opt ::= ORDER BY sortlist */
  141680. 219, /* (129) sortlist ::= sortlist COMMA expr sortorder */
  141681. 219, /* (130) sortlist ::= expr sortorder */
  141682. 208, /* (131) sortorder ::= ASC */
  141683. 208, /* (132) sortorder ::= DESC */
  141684. 208, /* (133) sortorder ::= */
  141685. 235, /* (134) groupby_opt ::= */
  141686. 235, /* (135) groupby_opt ::= GROUP BY nexprlist */
  141687. 236, /* (136) having_opt ::= */
  141688. 236, /* (137) having_opt ::= HAVING expr */
  141689. 238, /* (138) limit_opt ::= */
  141690. 238, /* (139) limit_opt ::= LIMIT expr */
  141691. 238, /* (140) limit_opt ::= LIMIT expr OFFSET expr */
  141692. 238, /* (141) limit_opt ::= LIMIT expr COMMA expr */
  141693. 181, /* (142) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  141694. 234, /* (143) where_opt ::= */
  141695. 234, /* (144) where_opt ::= WHERE expr */
  141696. 181, /* (145) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  141697. 254, /* (146) setlist ::= setlist COMMA nm EQ expr */
  141698. 254, /* (147) setlist ::= setlist COMMA LP idlist RP EQ expr */
  141699. 254, /* (148) setlist ::= nm EQ expr */
  141700. 254, /* (149) setlist ::= LP idlist RP EQ expr */
  141701. 181, /* (150) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  141702. 181, /* (151) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  141703. 257, /* (152) upsert ::= */
  141704. 257, /* (153) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  141705. 257, /* (154) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  141706. 257, /* (155) upsert ::= ON CONFLICT DO NOTHING */
  141707. 255, /* (156) insert_cmd ::= INSERT orconf */
  141708. 255, /* (157) insert_cmd ::= REPLACE */
  141709. 256, /* (158) idlist_opt ::= */
  141710. 256, /* (159) idlist_opt ::= LP idlist RP */
  141711. 252, /* (160) idlist ::= idlist COMMA nm */
  141712. 252, /* (161) idlist ::= nm */
  141713. 206, /* (162) expr ::= LP expr RP */
  141714. 206, /* (163) expr ::= ID|INDEXED */
  141715. 206, /* (164) expr ::= JOIN_KW */
  141716. 206, /* (165) expr ::= nm DOT nm */
  141717. 206, /* (166) expr ::= nm DOT nm DOT nm */
  141718. 205, /* (167) term ::= NULL|FLOAT|BLOB */
  141719. 205, /* (168) term ::= STRING */
  141720. 205, /* (169) term ::= INTEGER */
  141721. 206, /* (170) expr ::= VARIABLE */
  141722. 206, /* (171) expr ::= expr COLLATE ID|STRING */
  141723. 206, /* (172) expr ::= CAST LP expr AS typetoken RP */
  141724. 206, /* (173) expr ::= ID|INDEXED LP distinct exprlist RP */
  141725. 206, /* (174) expr ::= ID|INDEXED LP STAR RP */
  141726. 206, /* (175) expr ::= ID|INDEXED LP distinct exprlist RP over_clause */
  141727. 206, /* (176) expr ::= ID|INDEXED LP STAR RP over_clause */
  141728. 205, /* (177) term ::= CTIME_KW */
  141729. 206, /* (178) expr ::= LP nexprlist COMMA expr RP */
  141730. 206, /* (179) expr ::= expr AND expr */
  141731. 206, /* (180) expr ::= expr OR expr */
  141732. 206, /* (181) expr ::= expr LT|GT|GE|LE expr */
  141733. 206, /* (182) expr ::= expr EQ|NE expr */
  141734. 206, /* (183) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
  141735. 206, /* (184) expr ::= expr PLUS|MINUS expr */
  141736. 206, /* (185) expr ::= expr STAR|SLASH|REM expr */
  141737. 206, /* (186) expr ::= expr CONCAT expr */
  141738. 259, /* (187) likeop ::= NOT LIKE_KW|MATCH */
  141739. 206, /* (188) expr ::= expr likeop expr */
  141740. 206, /* (189) expr ::= expr likeop expr ESCAPE expr */
  141741. 206, /* (190) expr ::= expr ISNULL|NOTNULL */
  141742. 206, /* (191) expr ::= expr NOT NULL */
  141743. 206, /* (192) expr ::= expr IS expr */
  141744. 206, /* (193) expr ::= expr IS NOT expr */
  141745. 206, /* (194) expr ::= NOT expr */
  141746. 206, /* (195) expr ::= BITNOT expr */
  141747. 206, /* (196) expr ::= PLUS|MINUS expr */
  141748. 260, /* (197) between_op ::= BETWEEN */
  141749. 260, /* (198) between_op ::= NOT BETWEEN */
  141750. 206, /* (199) expr ::= expr between_op expr AND expr */
  141751. 261, /* (200) in_op ::= IN */
  141752. 261, /* (201) in_op ::= NOT IN */
  141753. 206, /* (202) expr ::= expr in_op LP exprlist RP */
  141754. 206, /* (203) expr ::= LP select RP */
  141755. 206, /* (204) expr ::= expr in_op LP select RP */
  141756. 206, /* (205) expr ::= expr in_op nm dbnm paren_exprlist */
  141757. 206, /* (206) expr ::= EXISTS LP select RP */
  141758. 206, /* (207) expr ::= CASE case_operand case_exprlist case_else END */
  141759. 264, /* (208) case_exprlist ::= case_exprlist WHEN expr THEN expr */
  141760. 264, /* (209) case_exprlist ::= WHEN expr THEN expr */
  141761. 265, /* (210) case_else ::= ELSE expr */
  141762. 265, /* (211) case_else ::= */
  141763. 263, /* (212) case_operand ::= expr */
  141764. 263, /* (213) case_operand ::= */
  141765. 250, /* (214) exprlist ::= */
  141766. 241, /* (215) nexprlist ::= nexprlist COMMA expr */
  141767. 241, /* (216) nexprlist ::= expr */
  141768. 262, /* (217) paren_exprlist ::= */
  141769. 262, /* (218) paren_exprlist ::= LP exprlist RP */
  141770. 181, /* (219) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  141771. 266, /* (220) uniqueflag ::= UNIQUE */
  141772. 266, /* (221) uniqueflag ::= */
  141773. 210, /* (222) eidlist_opt ::= */
  141774. 210, /* (223) eidlist_opt ::= LP eidlist RP */
  141775. 220, /* (224) eidlist ::= eidlist COMMA nm collate sortorder */
  141776. 220, /* (225) eidlist ::= nm collate sortorder */
  141777. 267, /* (226) collate ::= */
  141778. 267, /* (227) collate ::= COLLATE ID|STRING */
  141779. 181, /* (228) cmd ::= DROP INDEX ifexists fullname */
  141780. 181, /* (229) cmd ::= VACUUM vinto */
  141781. 181, /* (230) cmd ::= VACUUM nm vinto */
  141782. 268, /* (231) vinto ::= INTO expr */
  141783. 268, /* (232) vinto ::= */
  141784. 181, /* (233) cmd ::= PRAGMA nm dbnm */
  141785. 181, /* (234) cmd ::= PRAGMA nm dbnm EQ nmnum */
  141786. 181, /* (235) cmd ::= PRAGMA nm dbnm LP nmnum RP */
  141787. 181, /* (236) cmd ::= PRAGMA nm dbnm EQ minus_num */
  141788. 181, /* (237) cmd ::= PRAGMA nm dbnm LP minus_num RP */
  141789. 201, /* (238) plus_num ::= PLUS INTEGER|FLOAT */
  141790. 202, /* (239) minus_num ::= MINUS INTEGER|FLOAT */
  141791. 181, /* (240) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  141792. 270, /* (241) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  141793. 272, /* (242) trigger_time ::= BEFORE|AFTER */
  141794. 272, /* (243) trigger_time ::= INSTEAD OF */
  141795. 272, /* (244) trigger_time ::= */
  141796. 273, /* (245) trigger_event ::= DELETE|INSERT */
  141797. 273, /* (246) trigger_event ::= UPDATE */
  141798. 273, /* (247) trigger_event ::= UPDATE OF idlist */
  141799. 275, /* (248) when_clause ::= */
  141800. 275, /* (249) when_clause ::= WHEN expr */
  141801. 271, /* (250) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  141802. 271, /* (251) trigger_cmd_list ::= trigger_cmd SEMI */
  141803. 277, /* (252) trnm ::= nm DOT nm */
  141804. 278, /* (253) tridxby ::= INDEXED BY nm */
  141805. 278, /* (254) tridxby ::= NOT INDEXED */
  141806. 276, /* (255) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  141807. 276, /* (256) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  141808. 276, /* (257) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  141809. 276, /* (258) trigger_cmd ::= scanpt select scanpt */
  141810. 206, /* (259) expr ::= RAISE LP IGNORE RP */
  141811. 206, /* (260) expr ::= RAISE LP raisetype COMMA nm RP */
  141812. 224, /* (261) raisetype ::= ROLLBACK */
  141813. 224, /* (262) raisetype ::= ABORT */
  141814. 224, /* (263) raisetype ::= FAIL */
  141815. 181, /* (264) cmd ::= DROP TRIGGER ifexists fullname */
  141816. 181, /* (265) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  141817. 181, /* (266) cmd ::= DETACH database_kw_opt expr */
  141818. 280, /* (267) key_opt ::= */
  141819. 280, /* (268) key_opt ::= KEY expr */
  141820. 181, /* (269) cmd ::= REINDEX */
  141821. 181, /* (270) cmd ::= REINDEX nm dbnm */
  141822. 181, /* (271) cmd ::= ANALYZE */
  141823. 181, /* (272) cmd ::= ANALYZE nm dbnm */
  141824. 181, /* (273) cmd ::= ALTER TABLE fullname RENAME TO nm */
  141825. 181, /* (274) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  141826. 281, /* (275) add_column_fullname ::= fullname */
  141827. 181, /* (276) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
  141828. 181, /* (277) cmd ::= create_vtab */
  141829. 181, /* (278) cmd ::= create_vtab LP vtabarglist RP */
  141830. 283, /* (279) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  141831. 285, /* (280) vtabarg ::= */
  141832. 286, /* (281) vtabargtoken ::= ANY */
  141833. 286, /* (282) vtabargtoken ::= lp anylist RP */
  141834. 287, /* (283) lp ::= LP */
  141835. 253, /* (284) with ::= WITH wqlist */
  141836. 253, /* (285) with ::= WITH RECURSIVE wqlist */
  141837. 229, /* (286) wqlist ::= nm eidlist_opt AS LP select RP */
  141838. 229, /* (287) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  141839. 289, /* (288) windowdefn_list ::= windowdefn */
  141840. 289, /* (289) windowdefn_list ::= windowdefn_list COMMA windowdefn */
  141841. 290, /* (290) windowdefn ::= nm AS LP window RP */
  141842. 291, /* (291) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
  141843. 291, /* (292) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
  141844. 291, /* (293) window ::= ORDER BY sortlist frame_opt */
  141845. 291, /* (294) window ::= nm ORDER BY sortlist frame_opt */
  141846. 291, /* (295) window ::= frame_opt */
  141847. 291, /* (296) window ::= nm frame_opt */
  141848. 292, /* (297) frame_opt ::= */
  141849. 292, /* (298) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
  141850. 292, /* (299) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
  141851. 295, /* (300) range_or_rows ::= RANGE|ROWS|GROUPS */
  141852. 297, /* (301) frame_bound_s ::= frame_bound */
  141853. 297, /* (302) frame_bound_s ::= UNBOUNDED PRECEDING */
  141854. 298, /* (303) frame_bound_e ::= frame_bound */
  141855. 298, /* (304) frame_bound_e ::= UNBOUNDED FOLLOWING */
  141856. 296, /* (305) frame_bound ::= expr PRECEDING|FOLLOWING */
  141857. 296, /* (306) frame_bound ::= CURRENT ROW */
  141858. 299, /* (307) frame_exclude_opt ::= */
  141859. 299, /* (308) frame_exclude_opt ::= EXCLUDE frame_exclude */
  141860. 300, /* (309) frame_exclude ::= NO OTHERS */
  141861. 300, /* (310) frame_exclude ::= CURRENT ROW */
  141862. 300, /* (311) frame_exclude ::= GROUP|TIES */
  141863. 239, /* (312) window_clause ::= WINDOW windowdefn_list */
  141864. 258, /* (313) over_clause ::= filter_opt OVER LP window RP */
  141865. 258, /* (314) over_clause ::= filter_opt OVER nm */
  141866. 294, /* (315) filter_opt ::= */
  141867. 294, /* (316) filter_opt ::= FILTER LP WHERE expr RP */
  141868. 176, /* (317) input ::= cmdlist */
  141869. 177, /* (318) cmdlist ::= cmdlist ecmd */
  141870. 177, /* (319) cmdlist ::= ecmd */
  141871. 178, /* (320) ecmd ::= SEMI */
  141872. 178, /* (321) ecmd ::= cmdx SEMI */
  141873. 178, /* (322) ecmd ::= explain cmdx */
  141874. 183, /* (323) trans_opt ::= */
  141875. 183, /* (324) trans_opt ::= TRANSACTION */
  141876. 183, /* (325) trans_opt ::= TRANSACTION nm */
  141877. 185, /* (326) savepoint_opt ::= SAVEPOINT */
  141878. 185, /* (327) savepoint_opt ::= */
  141879. 181, /* (328) cmd ::= create_table create_table_args */
  141880. 192, /* (329) columnlist ::= columnlist COMMA columnname carglist */
  141881. 192, /* (330) columnlist ::= columnname carglist */
  141882. 184, /* (331) nm ::= ID|INDEXED */
  141883. 184, /* (332) nm ::= STRING */
  141884. 184, /* (333) nm ::= JOIN_KW */
  141885. 198, /* (334) typetoken ::= typename */
  141886. 199, /* (335) typename ::= ID|STRING */
  141887. 200, /* (336) signed ::= plus_num */
  141888. 200, /* (337) signed ::= minus_num */
  141889. 197, /* (338) carglist ::= carglist ccons */
  141890. 197, /* (339) carglist ::= */
  141891. 204, /* (340) ccons ::= NULL onconf */
  141892. 193, /* (341) conslist_opt ::= COMMA conslist */
  141893. 216, /* (342) conslist ::= conslist tconscomma tcons */
  141894. 216, /* (343) conslist ::= tcons */
  141895. 217, /* (344) tconscomma ::= */
  141896. 221, /* (345) defer_subclause_opt ::= defer_subclause */
  141897. 223, /* (346) resolvetype ::= raisetype */
  141898. 227, /* (347) selectnowith ::= oneselect */
  141899. 228, /* (348) oneselect ::= values */
  141900. 242, /* (349) sclp ::= selcollist COMMA */
  141901. 243, /* (350) as ::= ID|STRING */
  141902. 206, /* (351) expr ::= term */
  141903. 259, /* (352) likeop ::= LIKE_KW|MATCH */
  141904. 250, /* (353) exprlist ::= nexprlist */
  141905. 269, /* (354) nmnum ::= plus_num */
  141906. 269, /* (355) nmnum ::= nm */
  141907. 269, /* (356) nmnum ::= ON */
  141908. 269, /* (357) nmnum ::= DELETE */
  141909. 269, /* (358) nmnum ::= DEFAULT */
  141910. 201, /* (359) plus_num ::= INTEGER|FLOAT */
  141911. 274, /* (360) foreach_clause ::= */
  141912. 274, /* (361) foreach_clause ::= FOR EACH ROW */
  141913. 277, /* (362) trnm ::= nm */
  141914. 278, /* (363) tridxby ::= */
  141915. 279, /* (364) database_kw_opt ::= DATABASE */
  141916. 279, /* (365) database_kw_opt ::= */
  141917. 282, /* (366) kwcolumn_opt ::= */
  141918. 282, /* (367) kwcolumn_opt ::= COLUMNKW */
  141919. 284, /* (368) vtabarglist ::= vtabarg */
  141920. 284, /* (369) vtabarglist ::= vtabarglist COMMA vtabarg */
  141921. 285, /* (370) vtabarg ::= vtabarg vtabargtoken */
  141922. 288, /* (371) anylist ::= */
  141923. 288, /* (372) anylist ::= anylist LP anylist RP */
  141924. 288, /* (373) anylist ::= anylist ANY */
  141925. 253, /* (374) with ::= */
  141926. };
  141927. /* For rule J, yyRuleInfoNRhs[J] contains the negative of the number
  141928. ** of symbols on the right-hand side of that rule. */
  141929. static const signed char yyRuleInfoNRhs[] = {
  141930. -1, /* (0) explain ::= EXPLAIN */
  141931. -3, /* (1) explain ::= EXPLAIN QUERY PLAN */
  141932. -1, /* (2) cmdx ::= cmd */
  141933. -3, /* (3) cmd ::= BEGIN transtype trans_opt */
  141934. 0, /* (4) transtype ::= */
  141935. -1, /* (5) transtype ::= DEFERRED */
  141936. -1, /* (6) transtype ::= IMMEDIATE */
  141937. -1, /* (7) transtype ::= EXCLUSIVE */
  141938. -2, /* (8) cmd ::= COMMIT|END trans_opt */
  141939. -2, /* (9) cmd ::= ROLLBACK trans_opt */
  141940. -2, /* (10) cmd ::= SAVEPOINT nm */
  141941. -3, /* (11) cmd ::= RELEASE savepoint_opt nm */
  141942. -5, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  141943. -6, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  141944. -1, /* (14) createkw ::= CREATE */
  141945. 0, /* (15) ifnotexists ::= */
  141946. -3, /* (16) ifnotexists ::= IF NOT EXISTS */
  141947. -1, /* (17) temp ::= TEMP */
  141948. 0, /* (18) temp ::= */
  141949. -5, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
  141950. -2, /* (20) create_table_args ::= AS select */
  141951. 0, /* (21) table_options ::= */
  141952. -2, /* (22) table_options ::= WITHOUT nm */
  141953. -2, /* (23) columnname ::= nm typetoken */
  141954. 0, /* (24) typetoken ::= */
  141955. -4, /* (25) typetoken ::= typename LP signed RP */
  141956. -6, /* (26) typetoken ::= typename LP signed COMMA signed RP */
  141957. -2, /* (27) typename ::= typename ID|STRING */
  141958. 0, /* (28) scanpt ::= */
  141959. -2, /* (29) ccons ::= CONSTRAINT nm */
  141960. -4, /* (30) ccons ::= DEFAULT scanpt term scanpt */
  141961. -4, /* (31) ccons ::= DEFAULT LP expr RP */
  141962. -4, /* (32) ccons ::= DEFAULT PLUS term scanpt */
  141963. -4, /* (33) ccons ::= DEFAULT MINUS term scanpt */
  141964. -3, /* (34) ccons ::= DEFAULT scanpt ID|INDEXED */
  141965. -3, /* (35) ccons ::= NOT NULL onconf */
  141966. -5, /* (36) ccons ::= PRIMARY KEY sortorder onconf autoinc */
  141967. -2, /* (37) ccons ::= UNIQUE onconf */
  141968. -4, /* (38) ccons ::= CHECK LP expr RP */
  141969. -4, /* (39) ccons ::= REFERENCES nm eidlist_opt refargs */
  141970. -1, /* (40) ccons ::= defer_subclause */
  141971. -2, /* (41) ccons ::= COLLATE ID|STRING */
  141972. 0, /* (42) autoinc ::= */
  141973. -1, /* (43) autoinc ::= AUTOINCR */
  141974. 0, /* (44) refargs ::= */
  141975. -2, /* (45) refargs ::= refargs refarg */
  141976. -2, /* (46) refarg ::= MATCH nm */
  141977. -3, /* (47) refarg ::= ON INSERT refact */
  141978. -3, /* (48) refarg ::= ON DELETE refact */
  141979. -3, /* (49) refarg ::= ON UPDATE refact */
  141980. -2, /* (50) refact ::= SET NULL */
  141981. -2, /* (51) refact ::= SET DEFAULT */
  141982. -1, /* (52) refact ::= CASCADE */
  141983. -1, /* (53) refact ::= RESTRICT */
  141984. -2, /* (54) refact ::= NO ACTION */
  141985. -3, /* (55) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  141986. -2, /* (56) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  141987. 0, /* (57) init_deferred_pred_opt ::= */
  141988. -2, /* (58) init_deferred_pred_opt ::= INITIALLY DEFERRED */
  141989. -2, /* (59) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  141990. 0, /* (60) conslist_opt ::= */
  141991. -1, /* (61) tconscomma ::= COMMA */
  141992. -2, /* (62) tcons ::= CONSTRAINT nm */
  141993. -7, /* (63) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  141994. -5, /* (64) tcons ::= UNIQUE LP sortlist RP onconf */
  141995. -5, /* (65) tcons ::= CHECK LP expr RP onconf */
  141996. -10, /* (66) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  141997. 0, /* (67) defer_subclause_opt ::= */
  141998. 0, /* (68) onconf ::= */
  141999. -3, /* (69) onconf ::= ON CONFLICT resolvetype */
  142000. 0, /* (70) orconf ::= */
  142001. -2, /* (71) orconf ::= OR resolvetype */
  142002. -1, /* (72) resolvetype ::= IGNORE */
  142003. -1, /* (73) resolvetype ::= REPLACE */
  142004. -4, /* (74) cmd ::= DROP TABLE ifexists fullname */
  142005. -2, /* (75) ifexists ::= IF EXISTS */
  142006. 0, /* (76) ifexists ::= */
  142007. -9, /* (77) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  142008. -4, /* (78) cmd ::= DROP VIEW ifexists fullname */
  142009. -1, /* (79) cmd ::= select */
  142010. -3, /* (80) select ::= WITH wqlist selectnowith */
  142011. -4, /* (81) select ::= WITH RECURSIVE wqlist selectnowith */
  142012. -1, /* (82) select ::= selectnowith */
  142013. -3, /* (83) selectnowith ::= selectnowith multiselect_op oneselect */
  142014. -1, /* (84) multiselect_op ::= UNION */
  142015. -2, /* (85) multiselect_op ::= UNION ALL */
  142016. -1, /* (86) multiselect_op ::= EXCEPT|INTERSECT */
  142017. -9, /* (87) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  142018. -10, /* (88) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
  142019. -4, /* (89) values ::= VALUES LP nexprlist RP */
  142020. -5, /* (90) values ::= values COMMA LP nexprlist RP */
  142021. -1, /* (91) distinct ::= DISTINCT */
  142022. -1, /* (92) distinct ::= ALL */
  142023. 0, /* (93) distinct ::= */
  142024. 0, /* (94) sclp ::= */
  142025. -5, /* (95) selcollist ::= sclp scanpt expr scanpt as */
  142026. -3, /* (96) selcollist ::= sclp scanpt STAR */
  142027. -5, /* (97) selcollist ::= sclp scanpt nm DOT STAR */
  142028. -2, /* (98) as ::= AS nm */
  142029. 0, /* (99) as ::= */
  142030. 0, /* (100) from ::= */
  142031. -2, /* (101) from ::= FROM seltablist */
  142032. -2, /* (102) stl_prefix ::= seltablist joinop */
  142033. 0, /* (103) stl_prefix ::= */
  142034. -7, /* (104) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  142035. -9, /* (105) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  142036. -7, /* (106) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  142037. -7, /* (107) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  142038. 0, /* (108) dbnm ::= */
  142039. -2, /* (109) dbnm ::= DOT nm */
  142040. -1, /* (110) fullname ::= nm */
  142041. -3, /* (111) fullname ::= nm DOT nm */
  142042. -1, /* (112) xfullname ::= nm */
  142043. -3, /* (113) xfullname ::= nm DOT nm */
  142044. -5, /* (114) xfullname ::= nm DOT nm AS nm */
  142045. -3, /* (115) xfullname ::= nm AS nm */
  142046. -1, /* (116) joinop ::= COMMA|JOIN */
  142047. -2, /* (117) joinop ::= JOIN_KW JOIN */
  142048. -3, /* (118) joinop ::= JOIN_KW nm JOIN */
  142049. -4, /* (119) joinop ::= JOIN_KW nm nm JOIN */
  142050. -2, /* (120) on_opt ::= ON expr */
  142051. 0, /* (121) on_opt ::= */
  142052. 0, /* (122) indexed_opt ::= */
  142053. -3, /* (123) indexed_opt ::= INDEXED BY nm */
  142054. -2, /* (124) indexed_opt ::= NOT INDEXED */
  142055. -4, /* (125) using_opt ::= USING LP idlist RP */
  142056. 0, /* (126) using_opt ::= */
  142057. 0, /* (127) orderby_opt ::= */
  142058. -3, /* (128) orderby_opt ::= ORDER BY sortlist */
  142059. -4, /* (129) sortlist ::= sortlist COMMA expr sortorder */
  142060. -2, /* (130) sortlist ::= expr sortorder */
  142061. -1, /* (131) sortorder ::= ASC */
  142062. -1, /* (132) sortorder ::= DESC */
  142063. 0, /* (133) sortorder ::= */
  142064. 0, /* (134) groupby_opt ::= */
  142065. -3, /* (135) groupby_opt ::= GROUP BY nexprlist */
  142066. 0, /* (136) having_opt ::= */
  142067. -2, /* (137) having_opt ::= HAVING expr */
  142068. 0, /* (138) limit_opt ::= */
  142069. -2, /* (139) limit_opt ::= LIMIT expr */
  142070. -4, /* (140) limit_opt ::= LIMIT expr OFFSET expr */
  142071. -4, /* (141) limit_opt ::= LIMIT expr COMMA expr */
  142072. -6, /* (142) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  142073. 0, /* (143) where_opt ::= */
  142074. -2, /* (144) where_opt ::= WHERE expr */
  142075. -8, /* (145) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  142076. -5, /* (146) setlist ::= setlist COMMA nm EQ expr */
  142077. -7, /* (147) setlist ::= setlist COMMA LP idlist RP EQ expr */
  142078. -3, /* (148) setlist ::= nm EQ expr */
  142079. -5, /* (149) setlist ::= LP idlist RP EQ expr */
  142080. -7, /* (150) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  142081. -7, /* (151) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  142082. 0, /* (152) upsert ::= */
  142083. -11, /* (153) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  142084. -8, /* (154) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  142085. -4, /* (155) upsert ::= ON CONFLICT DO NOTHING */
  142086. -2, /* (156) insert_cmd ::= INSERT orconf */
  142087. -1, /* (157) insert_cmd ::= REPLACE */
  142088. 0, /* (158) idlist_opt ::= */
  142089. -3, /* (159) idlist_opt ::= LP idlist RP */
  142090. -3, /* (160) idlist ::= idlist COMMA nm */
  142091. -1, /* (161) idlist ::= nm */
  142092. -3, /* (162) expr ::= LP expr RP */
  142093. -1, /* (163) expr ::= ID|INDEXED */
  142094. -1, /* (164) expr ::= JOIN_KW */
  142095. -3, /* (165) expr ::= nm DOT nm */
  142096. -5, /* (166) expr ::= nm DOT nm DOT nm */
  142097. -1, /* (167) term ::= NULL|FLOAT|BLOB */
  142098. -1, /* (168) term ::= STRING */
  142099. -1, /* (169) term ::= INTEGER */
  142100. -1, /* (170) expr ::= VARIABLE */
  142101. -3, /* (171) expr ::= expr COLLATE ID|STRING */
  142102. -6, /* (172) expr ::= CAST LP expr AS typetoken RP */
  142103. -5, /* (173) expr ::= ID|INDEXED LP distinct exprlist RP */
  142104. -4, /* (174) expr ::= ID|INDEXED LP STAR RP */
  142105. -6, /* (175) expr ::= ID|INDEXED LP distinct exprlist RP over_clause */
  142106. -5, /* (176) expr ::= ID|INDEXED LP STAR RP over_clause */
  142107. -1, /* (177) term ::= CTIME_KW */
  142108. -5, /* (178) expr ::= LP nexprlist COMMA expr RP */
  142109. -3, /* (179) expr ::= expr AND expr */
  142110. -3, /* (180) expr ::= expr OR expr */
  142111. -3, /* (181) expr ::= expr LT|GT|GE|LE expr */
  142112. -3, /* (182) expr ::= expr EQ|NE expr */
  142113. -3, /* (183) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
  142114. -3, /* (184) expr ::= expr PLUS|MINUS expr */
  142115. -3, /* (185) expr ::= expr STAR|SLASH|REM expr */
  142116. -3, /* (186) expr ::= expr CONCAT expr */
  142117. -2, /* (187) likeop ::= NOT LIKE_KW|MATCH */
  142118. -3, /* (188) expr ::= expr likeop expr */
  142119. -5, /* (189) expr ::= expr likeop expr ESCAPE expr */
  142120. -2, /* (190) expr ::= expr ISNULL|NOTNULL */
  142121. -3, /* (191) expr ::= expr NOT NULL */
  142122. -3, /* (192) expr ::= expr IS expr */
  142123. -4, /* (193) expr ::= expr IS NOT expr */
  142124. -2, /* (194) expr ::= NOT expr */
  142125. -2, /* (195) expr ::= BITNOT expr */
  142126. -2, /* (196) expr ::= PLUS|MINUS expr */
  142127. -1, /* (197) between_op ::= BETWEEN */
  142128. -2, /* (198) between_op ::= NOT BETWEEN */
  142129. -5, /* (199) expr ::= expr between_op expr AND expr */
  142130. -1, /* (200) in_op ::= IN */
  142131. -2, /* (201) in_op ::= NOT IN */
  142132. -5, /* (202) expr ::= expr in_op LP exprlist RP */
  142133. -3, /* (203) expr ::= LP select RP */
  142134. -5, /* (204) expr ::= expr in_op LP select RP */
  142135. -5, /* (205) expr ::= expr in_op nm dbnm paren_exprlist */
  142136. -4, /* (206) expr ::= EXISTS LP select RP */
  142137. -5, /* (207) expr ::= CASE case_operand case_exprlist case_else END */
  142138. -5, /* (208) case_exprlist ::= case_exprlist WHEN expr THEN expr */
  142139. -4, /* (209) case_exprlist ::= WHEN expr THEN expr */
  142140. -2, /* (210) case_else ::= ELSE expr */
  142141. 0, /* (211) case_else ::= */
  142142. -1, /* (212) case_operand ::= expr */
  142143. 0, /* (213) case_operand ::= */
  142144. 0, /* (214) exprlist ::= */
  142145. -3, /* (215) nexprlist ::= nexprlist COMMA expr */
  142146. -1, /* (216) nexprlist ::= expr */
  142147. 0, /* (217) paren_exprlist ::= */
  142148. -3, /* (218) paren_exprlist ::= LP exprlist RP */
  142149. -12, /* (219) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  142150. -1, /* (220) uniqueflag ::= UNIQUE */
  142151. 0, /* (221) uniqueflag ::= */
  142152. 0, /* (222) eidlist_opt ::= */
  142153. -3, /* (223) eidlist_opt ::= LP eidlist RP */
  142154. -5, /* (224) eidlist ::= eidlist COMMA nm collate sortorder */
  142155. -3, /* (225) eidlist ::= nm collate sortorder */
  142156. 0, /* (226) collate ::= */
  142157. -2, /* (227) collate ::= COLLATE ID|STRING */
  142158. -4, /* (228) cmd ::= DROP INDEX ifexists fullname */
  142159. -2, /* (229) cmd ::= VACUUM vinto */
  142160. -3, /* (230) cmd ::= VACUUM nm vinto */
  142161. -2, /* (231) vinto ::= INTO expr */
  142162. 0, /* (232) vinto ::= */
  142163. -3, /* (233) cmd ::= PRAGMA nm dbnm */
  142164. -5, /* (234) cmd ::= PRAGMA nm dbnm EQ nmnum */
  142165. -6, /* (235) cmd ::= PRAGMA nm dbnm LP nmnum RP */
  142166. -5, /* (236) cmd ::= PRAGMA nm dbnm EQ minus_num */
  142167. -6, /* (237) cmd ::= PRAGMA nm dbnm LP minus_num RP */
  142168. -2, /* (238) plus_num ::= PLUS INTEGER|FLOAT */
  142169. -2, /* (239) minus_num ::= MINUS INTEGER|FLOAT */
  142170. -5, /* (240) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  142171. -11, /* (241) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  142172. -1, /* (242) trigger_time ::= BEFORE|AFTER */
  142173. -2, /* (243) trigger_time ::= INSTEAD OF */
  142174. 0, /* (244) trigger_time ::= */
  142175. -1, /* (245) trigger_event ::= DELETE|INSERT */
  142176. -1, /* (246) trigger_event ::= UPDATE */
  142177. -3, /* (247) trigger_event ::= UPDATE OF idlist */
  142178. 0, /* (248) when_clause ::= */
  142179. -2, /* (249) when_clause ::= WHEN expr */
  142180. -3, /* (250) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  142181. -2, /* (251) trigger_cmd_list ::= trigger_cmd SEMI */
  142182. -3, /* (252) trnm ::= nm DOT nm */
  142183. -3, /* (253) tridxby ::= INDEXED BY nm */
  142184. -2, /* (254) tridxby ::= NOT INDEXED */
  142185. -8, /* (255) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  142186. -8, /* (256) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  142187. -6, /* (257) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  142188. -3, /* (258) trigger_cmd ::= scanpt select scanpt */
  142189. -4, /* (259) expr ::= RAISE LP IGNORE RP */
  142190. -6, /* (260) expr ::= RAISE LP raisetype COMMA nm RP */
  142191. -1, /* (261) raisetype ::= ROLLBACK */
  142192. -1, /* (262) raisetype ::= ABORT */
  142193. -1, /* (263) raisetype ::= FAIL */
  142194. -4, /* (264) cmd ::= DROP TRIGGER ifexists fullname */
  142195. -6, /* (265) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  142196. -3, /* (266) cmd ::= DETACH database_kw_opt expr */
  142197. 0, /* (267) key_opt ::= */
  142198. -2, /* (268) key_opt ::= KEY expr */
  142199. -1, /* (269) cmd ::= REINDEX */
  142200. -3, /* (270) cmd ::= REINDEX nm dbnm */
  142201. -1, /* (271) cmd ::= ANALYZE */
  142202. -3, /* (272) cmd ::= ANALYZE nm dbnm */
  142203. -6, /* (273) cmd ::= ALTER TABLE fullname RENAME TO nm */
  142204. -7, /* (274) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  142205. -1, /* (275) add_column_fullname ::= fullname */
  142206. -8, /* (276) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
  142207. -1, /* (277) cmd ::= create_vtab */
  142208. -4, /* (278) cmd ::= create_vtab LP vtabarglist RP */
  142209. -8, /* (279) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  142210. 0, /* (280) vtabarg ::= */
  142211. -1, /* (281) vtabargtoken ::= ANY */
  142212. -3, /* (282) vtabargtoken ::= lp anylist RP */
  142213. -1, /* (283) lp ::= LP */
  142214. -2, /* (284) with ::= WITH wqlist */
  142215. -3, /* (285) with ::= WITH RECURSIVE wqlist */
  142216. -6, /* (286) wqlist ::= nm eidlist_opt AS LP select RP */
  142217. -8, /* (287) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  142218. -1, /* (288) windowdefn_list ::= windowdefn */
  142219. -3, /* (289) windowdefn_list ::= windowdefn_list COMMA windowdefn */
  142220. -5, /* (290) windowdefn ::= nm AS LP window RP */
  142221. -5, /* (291) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
  142222. -6, /* (292) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
  142223. -4, /* (293) window ::= ORDER BY sortlist frame_opt */
  142224. -5, /* (294) window ::= nm ORDER BY sortlist frame_opt */
  142225. -1, /* (295) window ::= frame_opt */
  142226. -2, /* (296) window ::= nm frame_opt */
  142227. 0, /* (297) frame_opt ::= */
  142228. -3, /* (298) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
  142229. -6, /* (299) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
  142230. -1, /* (300) range_or_rows ::= RANGE|ROWS|GROUPS */
  142231. -1, /* (301) frame_bound_s ::= frame_bound */
  142232. -2, /* (302) frame_bound_s ::= UNBOUNDED PRECEDING */
  142233. -1, /* (303) frame_bound_e ::= frame_bound */
  142234. -2, /* (304) frame_bound_e ::= UNBOUNDED FOLLOWING */
  142235. -2, /* (305) frame_bound ::= expr PRECEDING|FOLLOWING */
  142236. -2, /* (306) frame_bound ::= CURRENT ROW */
  142237. 0, /* (307) frame_exclude_opt ::= */
  142238. -2, /* (308) frame_exclude_opt ::= EXCLUDE frame_exclude */
  142239. -2, /* (309) frame_exclude ::= NO OTHERS */
  142240. -2, /* (310) frame_exclude ::= CURRENT ROW */
  142241. -1, /* (311) frame_exclude ::= GROUP|TIES */
  142242. -2, /* (312) window_clause ::= WINDOW windowdefn_list */
  142243. -5, /* (313) over_clause ::= filter_opt OVER LP window RP */
  142244. -3, /* (314) over_clause ::= filter_opt OVER nm */
  142245. 0, /* (315) filter_opt ::= */
  142246. -5, /* (316) filter_opt ::= FILTER LP WHERE expr RP */
  142247. -1, /* (317) input ::= cmdlist */
  142248. -2, /* (318) cmdlist ::= cmdlist ecmd */
  142249. -1, /* (319) cmdlist ::= ecmd */
  142250. -1, /* (320) ecmd ::= SEMI */
  142251. -2, /* (321) ecmd ::= cmdx SEMI */
  142252. -2, /* (322) ecmd ::= explain cmdx */
  142253. 0, /* (323) trans_opt ::= */
  142254. -1, /* (324) trans_opt ::= TRANSACTION */
  142255. -2, /* (325) trans_opt ::= TRANSACTION nm */
  142256. -1, /* (326) savepoint_opt ::= SAVEPOINT */
  142257. 0, /* (327) savepoint_opt ::= */
  142258. -2, /* (328) cmd ::= create_table create_table_args */
  142259. -4, /* (329) columnlist ::= columnlist COMMA columnname carglist */
  142260. -2, /* (330) columnlist ::= columnname carglist */
  142261. -1, /* (331) nm ::= ID|INDEXED */
  142262. -1, /* (332) nm ::= STRING */
  142263. -1, /* (333) nm ::= JOIN_KW */
  142264. -1, /* (334) typetoken ::= typename */
  142265. -1, /* (335) typename ::= ID|STRING */
  142266. -1, /* (336) signed ::= plus_num */
  142267. -1, /* (337) signed ::= minus_num */
  142268. -2, /* (338) carglist ::= carglist ccons */
  142269. 0, /* (339) carglist ::= */
  142270. -2, /* (340) ccons ::= NULL onconf */
  142271. -2, /* (341) conslist_opt ::= COMMA conslist */
  142272. -3, /* (342) conslist ::= conslist tconscomma tcons */
  142273. -1, /* (343) conslist ::= tcons */
  142274. 0, /* (344) tconscomma ::= */
  142275. -1, /* (345) defer_subclause_opt ::= defer_subclause */
  142276. -1, /* (346) resolvetype ::= raisetype */
  142277. -1, /* (347) selectnowith ::= oneselect */
  142278. -1, /* (348) oneselect ::= values */
  142279. -2, /* (349) sclp ::= selcollist COMMA */
  142280. -1, /* (350) as ::= ID|STRING */
  142281. -1, /* (351) expr ::= term */
  142282. -1, /* (352) likeop ::= LIKE_KW|MATCH */
  142283. -1, /* (353) exprlist ::= nexprlist */
  142284. -1, /* (354) nmnum ::= plus_num */
  142285. -1, /* (355) nmnum ::= nm */
  142286. -1, /* (356) nmnum ::= ON */
  142287. -1, /* (357) nmnum ::= DELETE */
  142288. -1, /* (358) nmnum ::= DEFAULT */
  142289. -1, /* (359) plus_num ::= INTEGER|FLOAT */
  142290. 0, /* (360) foreach_clause ::= */
  142291. -3, /* (361) foreach_clause ::= FOR EACH ROW */
  142292. -1, /* (362) trnm ::= nm */
  142293. 0, /* (363) tridxby ::= */
  142294. -1, /* (364) database_kw_opt ::= DATABASE */
  142295. 0, /* (365) database_kw_opt ::= */
  142296. 0, /* (366) kwcolumn_opt ::= */
  142297. -1, /* (367) kwcolumn_opt ::= COLUMNKW */
  142298. -1, /* (368) vtabarglist ::= vtabarg */
  142299. -3, /* (369) vtabarglist ::= vtabarglist COMMA vtabarg */
  142300. -2, /* (370) vtabarg ::= vtabarg vtabargtoken */
  142301. 0, /* (371) anylist ::= */
  142302. -4, /* (372) anylist ::= anylist LP anylist RP */
  142303. -2, /* (373) anylist ::= anylist ANY */
  142304. 0, /* (374) with ::= */
  142305. };
  142306. static void yy_accept(yyParser*); /* Forward Declaration */
  142307. /*
  142308. ** Perform a reduce action and the shift that must immediately
  142309. ** follow the reduce.
  142310. **
  142311. ** The yyLookahead and yyLookaheadToken parameters provide reduce actions
  142312. ** access to the lookahead token (if any). The yyLookahead will be YYNOCODE
  142313. ** if the lookahead token has already been consumed. As this procedure is
  142314. ** only called from one place, optimizing compilers will in-line it, which
  142315. ** means that the extra parameters have no performance impact.
  142316. */
  142317. static YYACTIONTYPE yy_reduce(
  142318. yyParser *yypParser, /* The parser */
  142319. unsigned int yyruleno, /* Number of the rule by which to reduce */
  142320. int yyLookahead, /* Lookahead token, or YYNOCODE if none */
  142321. sqlite3ParserTOKENTYPE yyLookaheadToken /* Value of the lookahead token */
  142322. sqlite3ParserCTX_PDECL /* %extra_context */
  142323. ){
  142324. int yygoto; /* The next state */
  142325. YYACTIONTYPE yyact; /* The next action */
  142326. yyStackEntry *yymsp; /* The top of the parser's stack */
  142327. int yysize; /* Amount to pop the stack */
  142328. sqlite3ParserARG_FETCH
  142329. (void)yyLookahead;
  142330. (void)yyLookaheadToken;
  142331. yymsp = yypParser->yytos;
  142332. #ifndef NDEBUG
  142333. if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  142334. yysize = yyRuleInfoNRhs[yyruleno];
  142335. if( yysize ){
  142336. fprintf(yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
  142337. yyTracePrompt,
  142338. yyruleno, yyRuleName[yyruleno], yymsp[yysize].stateno);
  142339. }else{
  142340. fprintf(yyTraceFILE, "%sReduce %d [%s].\n",
  142341. yyTracePrompt, yyruleno, yyRuleName[yyruleno]);
  142342. }
  142343. }
  142344. #endif /* NDEBUG */
  142345. /* Check that the stack is large enough to grow by a single entry
  142346. ** if the RHS of the rule is empty. This ensures that there is room
  142347. ** enough on the stack to push the LHS value */
  142348. if( yyRuleInfoNRhs[yyruleno]==0 ){
  142349. #ifdef YYTRACKMAXSTACKDEPTH
  142350. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  142351. yypParser->yyhwm++;
  142352. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
  142353. }
  142354. #endif
  142355. #if YYSTACKDEPTH>0
  142356. if( yypParser->yytos>=yypParser->yystackEnd ){
  142357. yyStackOverflow(yypParser);
  142358. /* The call to yyStackOverflow() above pops the stack until it is
  142359. ** empty, causing the main parser loop to exit. So the return value
  142360. ** is never used and does not matter. */
  142361. return 0;
  142362. }
  142363. #else
  142364. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
  142365. if( yyGrowStack(yypParser) ){
  142366. yyStackOverflow(yypParser);
  142367. /* The call to yyStackOverflow() above pops the stack until it is
  142368. ** empty, causing the main parser loop to exit. So the return value
  142369. ** is never used and does not matter. */
  142370. return 0;
  142371. }
  142372. yymsp = yypParser->yytos;
  142373. }
  142374. #endif
  142375. }
  142376. switch( yyruleno ){
  142377. /* Beginning here are the reduction cases. A typical example
  142378. ** follows:
  142379. ** case 0:
  142380. ** #line <lineno> <grammarfile>
  142381. ** { ... } // User supplied code
  142382. ** #line <lineno> <thisfile>
  142383. ** break;
  142384. */
  142385. /********** Begin reduce actions **********************************************/
  142386. YYMINORTYPE yylhsminor;
  142387. case 0: /* explain ::= EXPLAIN */
  142388. { pParse->explain = 1; }
  142389. break;
  142390. case 1: /* explain ::= EXPLAIN QUERY PLAN */
  142391. { pParse->explain = 2; }
  142392. break;
  142393. case 2: /* cmdx ::= cmd */
  142394. { sqlite3FinishCoding(pParse); }
  142395. break;
  142396. case 3: /* cmd ::= BEGIN transtype trans_opt */
  142397. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy494);}
  142398. break;
  142399. case 4: /* transtype ::= */
  142400. {yymsp[1].minor.yy494 = TK_DEFERRED;}
  142401. break;
  142402. case 5: /* transtype ::= DEFERRED */
  142403. case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
  142404. case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
  142405. case 300: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==300);
  142406. {yymsp[0].minor.yy494 = yymsp[0].major; /*A-overwrites-X*/}
  142407. break;
  142408. case 8: /* cmd ::= COMMIT|END trans_opt */
  142409. case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
  142410. {sqlite3EndTransaction(pParse,yymsp[-1].major);}
  142411. break;
  142412. case 10: /* cmd ::= SAVEPOINT nm */
  142413. {
  142414. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  142415. }
  142416. break;
  142417. case 11: /* cmd ::= RELEASE savepoint_opt nm */
  142418. {
  142419. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  142420. }
  142421. break;
  142422. case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  142423. {
  142424. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  142425. }
  142426. break;
  142427. case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  142428. {
  142429. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy494,0,0,yymsp[-2].minor.yy494);
  142430. }
  142431. break;
  142432. case 14: /* createkw ::= CREATE */
  142433. {disableLookaside(pParse);}
  142434. break;
  142435. case 15: /* ifnotexists ::= */
  142436. case 18: /* temp ::= */ yytestcase(yyruleno==18);
  142437. case 21: /* table_options ::= */ yytestcase(yyruleno==21);
  142438. case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
  142439. case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
  142440. case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
  142441. case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
  142442. case 93: /* distinct ::= */ yytestcase(yyruleno==93);
  142443. case 226: /* collate ::= */ yytestcase(yyruleno==226);
  142444. {yymsp[1].minor.yy494 = 0;}
  142445. break;
  142446. case 16: /* ifnotexists ::= IF NOT EXISTS */
  142447. {yymsp[-2].minor.yy494 = 1;}
  142448. break;
  142449. case 17: /* temp ::= TEMP */
  142450. case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
  142451. {yymsp[0].minor.yy494 = 1;}
  142452. break;
  142453. case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  142454. {
  142455. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy494,0);
  142456. }
  142457. break;
  142458. case 20: /* create_table_args ::= AS select */
  142459. {
  142460. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy457);
  142461. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy457);
  142462. }
  142463. break;
  142464. case 22: /* table_options ::= WITHOUT nm */
  142465. {
  142466. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  142467. yymsp[-1].minor.yy494 = TF_WithoutRowid | TF_NoVisibleRowid;
  142468. }else{
  142469. yymsp[-1].minor.yy494 = 0;
  142470. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  142471. }
  142472. }
  142473. break;
  142474. case 23: /* columnname ::= nm typetoken */
  142475. {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  142476. break;
  142477. case 24: /* typetoken ::= */
  142478. case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
  142479. case 99: /* as ::= */ yytestcase(yyruleno==99);
  142480. {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
  142481. break;
  142482. case 25: /* typetoken ::= typename LP signed RP */
  142483. {
  142484. yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  142485. }
  142486. break;
  142487. case 26: /* typetoken ::= typename LP signed COMMA signed RP */
  142488. {
  142489. yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  142490. }
  142491. break;
  142492. case 27: /* typename ::= typename ID|STRING */
  142493. {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  142494. break;
  142495. case 28: /* scanpt ::= */
  142496. {
  142497. assert( yyLookahead!=YYNOCODE );
  142498. yymsp[1].minor.yy294 = yyLookaheadToken.z;
  142499. }
  142500. break;
  142501. case 29: /* ccons ::= CONSTRAINT nm */
  142502. case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
  142503. {pParse->constraintName = yymsp[0].minor.yy0;}
  142504. break;
  142505. case 30: /* ccons ::= DEFAULT scanpt term scanpt */
  142506. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy524,yymsp[-2].minor.yy294,yymsp[0].minor.yy294);}
  142507. break;
  142508. case 31: /* ccons ::= DEFAULT LP expr RP */
  142509. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy524,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
  142510. break;
  142511. case 32: /* ccons ::= DEFAULT PLUS term scanpt */
  142512. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy524,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy294);}
  142513. break;
  142514. case 33: /* ccons ::= DEFAULT MINUS term scanpt */
  142515. {
  142516. Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[-1].minor.yy524, 0);
  142517. sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy294);
  142518. }
  142519. break;
  142520. case 34: /* ccons ::= DEFAULT scanpt ID|INDEXED */
  142521. {
  142522. Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);
  142523. if( p ){
  142524. sqlite3ExprIdToTrueFalse(p);
  142525. testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
  142526. }
  142527. sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);
  142528. }
  142529. break;
  142530. case 35: /* ccons ::= NOT NULL onconf */
  142531. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy494);}
  142532. break;
  142533. case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  142534. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy494,yymsp[0].minor.yy494,yymsp[-2].minor.yy494);}
  142535. break;
  142536. case 37: /* ccons ::= UNIQUE onconf */
  142537. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy494,0,0,0,0,
  142538. SQLITE_IDXTYPE_UNIQUE);}
  142539. break;
  142540. case 38: /* ccons ::= CHECK LP expr RP */
  142541. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy524);}
  142542. break;
  142543. case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  142544. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy434,yymsp[0].minor.yy494);}
  142545. break;
  142546. case 40: /* ccons ::= defer_subclause */
  142547. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy494);}
  142548. break;
  142549. case 41: /* ccons ::= COLLATE ID|STRING */
  142550. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  142551. break;
  142552. case 44: /* refargs ::= */
  142553. { yymsp[1].minor.yy494 = OE_None*0x0101; /* EV: R-19803-45884 */}
  142554. break;
  142555. case 45: /* refargs ::= refargs refarg */
  142556. { yymsp[-1].minor.yy494 = (yymsp[-1].minor.yy494 & ~yymsp[0].minor.yy355.mask) | yymsp[0].minor.yy355.value; }
  142557. break;
  142558. case 46: /* refarg ::= MATCH nm */
  142559. { yymsp[-1].minor.yy355.value = 0; yymsp[-1].minor.yy355.mask = 0x000000; }
  142560. break;
  142561. case 47: /* refarg ::= ON INSERT refact */
  142562. { yymsp[-2].minor.yy355.value = 0; yymsp[-2].minor.yy355.mask = 0x000000; }
  142563. break;
  142564. case 48: /* refarg ::= ON DELETE refact */
  142565. { yymsp[-2].minor.yy355.value = yymsp[0].minor.yy494; yymsp[-2].minor.yy355.mask = 0x0000ff; }
  142566. break;
  142567. case 49: /* refarg ::= ON UPDATE refact */
  142568. { yymsp[-2].minor.yy355.value = yymsp[0].minor.yy494<<8; yymsp[-2].minor.yy355.mask = 0x00ff00; }
  142569. break;
  142570. case 50: /* refact ::= SET NULL */
  142571. { yymsp[-1].minor.yy494 = OE_SetNull; /* EV: R-33326-45252 */}
  142572. break;
  142573. case 51: /* refact ::= SET DEFAULT */
  142574. { yymsp[-1].minor.yy494 = OE_SetDflt; /* EV: R-33326-45252 */}
  142575. break;
  142576. case 52: /* refact ::= CASCADE */
  142577. { yymsp[0].minor.yy494 = OE_Cascade; /* EV: R-33326-45252 */}
  142578. break;
  142579. case 53: /* refact ::= RESTRICT */
  142580. { yymsp[0].minor.yy494 = OE_Restrict; /* EV: R-33326-45252 */}
  142581. break;
  142582. case 54: /* refact ::= NO ACTION */
  142583. { yymsp[-1].minor.yy494 = OE_None; /* EV: R-33326-45252 */}
  142584. break;
  142585. case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  142586. {yymsp[-2].minor.yy494 = 0;}
  142587. break;
  142588. case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  142589. case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
  142590. case 156: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==156);
  142591. {yymsp[-1].minor.yy494 = yymsp[0].minor.yy494;}
  142592. break;
  142593. case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  142594. case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
  142595. case 198: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==198);
  142596. case 201: /* in_op ::= NOT IN */ yytestcase(yyruleno==201);
  142597. case 227: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==227);
  142598. {yymsp[-1].minor.yy494 = 1;}
  142599. break;
  142600. case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  142601. {yymsp[-1].minor.yy494 = 0;}
  142602. break;
  142603. case 61: /* tconscomma ::= COMMA */
  142604. {pParse->constraintName.n = 0;}
  142605. break;
  142606. case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  142607. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy434,yymsp[0].minor.yy494,yymsp[-2].minor.yy494,0);}
  142608. break;
  142609. case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
  142610. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy434,yymsp[0].minor.yy494,0,0,0,0,
  142611. SQLITE_IDXTYPE_UNIQUE);}
  142612. break;
  142613. case 65: /* tcons ::= CHECK LP expr RP onconf */
  142614. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy524);}
  142615. break;
  142616. case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  142617. {
  142618. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy434, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy434, yymsp[-1].minor.yy494);
  142619. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy494);
  142620. }
  142621. break;
  142622. case 68: /* onconf ::= */
  142623. case 70: /* orconf ::= */ yytestcase(yyruleno==70);
  142624. {yymsp[1].minor.yy494 = OE_Default;}
  142625. break;
  142626. case 69: /* onconf ::= ON CONFLICT resolvetype */
  142627. {yymsp[-2].minor.yy494 = yymsp[0].minor.yy494;}
  142628. break;
  142629. case 72: /* resolvetype ::= IGNORE */
  142630. {yymsp[0].minor.yy494 = OE_Ignore;}
  142631. break;
  142632. case 73: /* resolvetype ::= REPLACE */
  142633. case 157: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==157);
  142634. {yymsp[0].minor.yy494 = OE_Replace;}
  142635. break;
  142636. case 74: /* cmd ::= DROP TABLE ifexists fullname */
  142637. {
  142638. sqlite3DropTable(pParse, yymsp[0].minor.yy483, 0, yymsp[-1].minor.yy494);
  142639. }
  142640. break;
  142641. case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  142642. {
  142643. sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy434, yymsp[0].minor.yy457, yymsp[-7].minor.yy494, yymsp[-5].minor.yy494);
  142644. }
  142645. break;
  142646. case 78: /* cmd ::= DROP VIEW ifexists fullname */
  142647. {
  142648. sqlite3DropTable(pParse, yymsp[0].minor.yy483, 1, yymsp[-1].minor.yy494);
  142649. }
  142650. break;
  142651. case 79: /* cmd ::= select */
  142652. {
  142653. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  142654. sqlite3Select(pParse, yymsp[0].minor.yy457, &dest);
  142655. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy457);
  142656. }
  142657. break;
  142658. case 80: /* select ::= WITH wqlist selectnowith */
  142659. {
  142660. Select *p = yymsp[0].minor.yy457;
  142661. if( p ){
  142662. p->pWith = yymsp[-1].minor.yy59;
  142663. parserDoubleLinkSelect(pParse, p);
  142664. }else{
  142665. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
  142666. }
  142667. yymsp[-2].minor.yy457 = p;
  142668. }
  142669. break;
  142670. case 81: /* select ::= WITH RECURSIVE wqlist selectnowith */
  142671. {
  142672. Select *p = yymsp[0].minor.yy457;
  142673. if( p ){
  142674. p->pWith = yymsp[-1].minor.yy59;
  142675. parserDoubleLinkSelect(pParse, p);
  142676. }else{
  142677. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
  142678. }
  142679. yymsp[-3].minor.yy457 = p;
  142680. }
  142681. break;
  142682. case 82: /* select ::= selectnowith */
  142683. {
  142684. Select *p = yymsp[0].minor.yy457;
  142685. if( p ){
  142686. parserDoubleLinkSelect(pParse, p);
  142687. }
  142688. yymsp[0].minor.yy457 = p; /*A-overwrites-X*/
  142689. }
  142690. break;
  142691. case 83: /* selectnowith ::= selectnowith multiselect_op oneselect */
  142692. {
  142693. Select *pRhs = yymsp[0].minor.yy457;
  142694. Select *pLhs = yymsp[-2].minor.yy457;
  142695. if( pRhs && pRhs->pPrior ){
  142696. SrcList *pFrom;
  142697. Token x;
  142698. x.n = 0;
  142699. parserDoubleLinkSelect(pParse, pRhs);
  142700. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  142701. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
  142702. }
  142703. if( pRhs ){
  142704. pRhs->op = (u8)yymsp[-1].minor.yy494;
  142705. pRhs->pPrior = pLhs;
  142706. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  142707. pRhs->selFlags &= ~SF_MultiValue;
  142708. if( yymsp[-1].minor.yy494!=TK_ALL ) pParse->hasCompound = 1;
  142709. }else{
  142710. sqlite3SelectDelete(pParse->db, pLhs);
  142711. }
  142712. yymsp[-2].minor.yy457 = pRhs;
  142713. }
  142714. break;
  142715. case 84: /* multiselect_op ::= UNION */
  142716. case 86: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==86);
  142717. {yymsp[0].minor.yy494 = yymsp[0].major; /*A-overwrites-OP*/}
  142718. break;
  142719. case 85: /* multiselect_op ::= UNION ALL */
  142720. {yymsp[-1].minor.yy494 = TK_ALL;}
  142721. break;
  142722. case 87: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  142723. {
  142724. yymsp[-8].minor.yy457 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy434,yymsp[-5].minor.yy483,yymsp[-4].minor.yy524,yymsp[-3].minor.yy434,yymsp[-2].minor.yy524,yymsp[-1].minor.yy434,yymsp[-7].minor.yy494,yymsp[0].minor.yy524);
  142725. }
  142726. break;
  142727. case 88: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
  142728. {
  142729. yymsp[-9].minor.yy457 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy434,yymsp[-6].minor.yy483,yymsp[-5].minor.yy524,yymsp[-4].minor.yy434,yymsp[-3].minor.yy524,yymsp[-1].minor.yy434,yymsp[-8].minor.yy494,yymsp[0].minor.yy524);
  142730. if( yymsp[-9].minor.yy457 ){
  142731. yymsp[-9].minor.yy457->pWinDefn = yymsp[-2].minor.yy295;
  142732. }else{
  142733. sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy295);
  142734. }
  142735. }
  142736. break;
  142737. case 89: /* values ::= VALUES LP nexprlist RP */
  142738. {
  142739. yymsp[-3].minor.yy457 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy434,0,0,0,0,0,SF_Values,0);
  142740. }
  142741. break;
  142742. case 90: /* values ::= values COMMA LP nexprlist RP */
  142743. {
  142744. Select *pRight, *pLeft = yymsp[-4].minor.yy457;
  142745. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy434,0,0,0,0,0,SF_Values|SF_MultiValue,0);
  142746. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  142747. if( pRight ){
  142748. pRight->op = TK_ALL;
  142749. pRight->pPrior = pLeft;
  142750. yymsp[-4].minor.yy457 = pRight;
  142751. }else{
  142752. yymsp[-4].minor.yy457 = pLeft;
  142753. }
  142754. }
  142755. break;
  142756. case 91: /* distinct ::= DISTINCT */
  142757. {yymsp[0].minor.yy494 = SF_Distinct;}
  142758. break;
  142759. case 92: /* distinct ::= ALL */
  142760. {yymsp[0].minor.yy494 = SF_All;}
  142761. break;
  142762. case 94: /* sclp ::= */
  142763. case 127: /* orderby_opt ::= */ yytestcase(yyruleno==127);
  142764. case 134: /* groupby_opt ::= */ yytestcase(yyruleno==134);
  142765. case 214: /* exprlist ::= */ yytestcase(yyruleno==214);
  142766. case 217: /* paren_exprlist ::= */ yytestcase(yyruleno==217);
  142767. case 222: /* eidlist_opt ::= */ yytestcase(yyruleno==222);
  142768. {yymsp[1].minor.yy434 = 0;}
  142769. break;
  142770. case 95: /* selcollist ::= sclp scanpt expr scanpt as */
  142771. {
  142772. yymsp[-4].minor.yy434 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy434, yymsp[-2].minor.yy524);
  142773. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy434, &yymsp[0].minor.yy0, 1);
  142774. sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy434,yymsp[-3].minor.yy294,yymsp[-1].minor.yy294);
  142775. }
  142776. break;
  142777. case 96: /* selcollist ::= sclp scanpt STAR */
  142778. {
  142779. Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
  142780. yymsp[-2].minor.yy434 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy434, p);
  142781. }
  142782. break;
  142783. case 97: /* selcollist ::= sclp scanpt nm DOT STAR */
  142784. {
  142785. Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
  142786. Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  142787. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  142788. yymsp[-4].minor.yy434 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy434, pDot);
  142789. }
  142790. break;
  142791. case 98: /* as ::= AS nm */
  142792. case 109: /* dbnm ::= DOT nm */ yytestcase(yyruleno==109);
  142793. case 238: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==238);
  142794. case 239: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==239);
  142795. {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
  142796. break;
  142797. case 100: /* from ::= */
  142798. {yymsp[1].minor.yy483 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy483));}
  142799. break;
  142800. case 101: /* from ::= FROM seltablist */
  142801. {
  142802. yymsp[-1].minor.yy483 = yymsp[0].minor.yy483;
  142803. sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy483);
  142804. }
  142805. break;
  142806. case 102: /* stl_prefix ::= seltablist joinop */
  142807. {
  142808. if( ALWAYS(yymsp[-1].minor.yy483 && yymsp[-1].minor.yy483->nSrc>0) ) yymsp[-1].minor.yy483->a[yymsp[-1].minor.yy483->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy494;
  142809. }
  142810. break;
  142811. case 103: /* stl_prefix ::= */
  142812. {yymsp[1].minor.yy483 = 0;}
  142813. break;
  142814. case 104: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  142815. {
  142816. yymsp[-6].minor.yy483 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy483,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy524,yymsp[0].minor.yy62);
  142817. sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy483, &yymsp[-2].minor.yy0);
  142818. }
  142819. break;
  142820. case 105: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  142821. {
  142822. yymsp[-8].minor.yy483 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy483,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy524,yymsp[0].minor.yy62);
  142823. sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy483, yymsp[-4].minor.yy434);
  142824. }
  142825. break;
  142826. case 106: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  142827. {
  142828. yymsp[-6].minor.yy483 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy483,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy457,yymsp[-1].minor.yy524,yymsp[0].minor.yy62);
  142829. }
  142830. break;
  142831. case 107: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  142832. {
  142833. if( yymsp[-6].minor.yy483==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy524==0 && yymsp[0].minor.yy62==0 ){
  142834. yymsp[-6].minor.yy483 = yymsp[-4].minor.yy483;
  142835. }else if( yymsp[-4].minor.yy483->nSrc==1 ){
  142836. yymsp[-6].minor.yy483 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy483,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy524,yymsp[0].minor.yy62);
  142837. if( yymsp[-6].minor.yy483 ){
  142838. struct SrcList_item *pNew = &yymsp[-6].minor.yy483->a[yymsp[-6].minor.yy483->nSrc-1];
  142839. struct SrcList_item *pOld = yymsp[-4].minor.yy483->a;
  142840. pNew->zName = pOld->zName;
  142841. pNew->zDatabase = pOld->zDatabase;
  142842. pNew->pSelect = pOld->pSelect;
  142843. if( pOld->fg.isTabFunc ){
  142844. pNew->u1.pFuncArg = pOld->u1.pFuncArg;
  142845. pOld->u1.pFuncArg = 0;
  142846. pOld->fg.isTabFunc = 0;
  142847. pNew->fg.isTabFunc = 1;
  142848. }
  142849. pOld->zName = pOld->zDatabase = 0;
  142850. pOld->pSelect = 0;
  142851. }
  142852. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy483);
  142853. }else{
  142854. Select *pSubquery;
  142855. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy483);
  142856. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy483,0,0,0,0,SF_NestedFrom,0);
  142857. yymsp[-6].minor.yy483 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy483,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy524,yymsp[0].minor.yy62);
  142858. }
  142859. }
  142860. break;
  142861. case 108: /* dbnm ::= */
  142862. case 122: /* indexed_opt ::= */ yytestcase(yyruleno==122);
  142863. {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
  142864. break;
  142865. case 110: /* fullname ::= nm */
  142866. {
  142867. yylhsminor.yy483 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0);
  142868. if( IN_RENAME_OBJECT && yylhsminor.yy483 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy483->a[0].zName, &yymsp[0].minor.yy0);
  142869. }
  142870. yymsp[0].minor.yy483 = yylhsminor.yy483;
  142871. break;
  142872. case 111: /* fullname ::= nm DOT nm */
  142873. {
  142874. yylhsminor.yy483 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  142875. if( IN_RENAME_OBJECT && yylhsminor.yy483 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy483->a[0].zName, &yymsp[0].minor.yy0);
  142876. }
  142877. yymsp[-2].minor.yy483 = yylhsminor.yy483;
  142878. break;
  142879. case 112: /* xfullname ::= nm */
  142880. {yymsp[0].minor.yy483 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
  142881. break;
  142882. case 113: /* xfullname ::= nm DOT nm */
  142883. {yymsp[-2].minor.yy483 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
  142884. break;
  142885. case 114: /* xfullname ::= nm DOT nm AS nm */
  142886. {
  142887. yymsp[-4].minor.yy483 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
  142888. if( yymsp[-4].minor.yy483 ) yymsp[-4].minor.yy483->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
  142889. }
  142890. break;
  142891. case 115: /* xfullname ::= nm AS nm */
  142892. {
  142893. yymsp[-2].minor.yy483 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
  142894. if( yymsp[-2].minor.yy483 ) yymsp[-2].minor.yy483->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
  142895. }
  142896. break;
  142897. case 116: /* joinop ::= COMMA|JOIN */
  142898. { yymsp[0].minor.yy494 = JT_INNER; }
  142899. break;
  142900. case 117: /* joinop ::= JOIN_KW JOIN */
  142901. {yymsp[-1].minor.yy494 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
  142902. break;
  142903. case 118: /* joinop ::= JOIN_KW nm JOIN */
  142904. {yymsp[-2].minor.yy494 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
  142905. break;
  142906. case 119: /* joinop ::= JOIN_KW nm nm JOIN */
  142907. {yymsp[-3].minor.yy494 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
  142908. break;
  142909. case 120: /* on_opt ::= ON expr */
  142910. case 137: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==137);
  142911. case 144: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==144);
  142912. case 210: /* case_else ::= ELSE expr */ yytestcase(yyruleno==210);
  142913. case 231: /* vinto ::= INTO expr */ yytestcase(yyruleno==231);
  142914. {yymsp[-1].minor.yy524 = yymsp[0].minor.yy524;}
  142915. break;
  142916. case 121: /* on_opt ::= */
  142917. case 136: /* having_opt ::= */ yytestcase(yyruleno==136);
  142918. case 138: /* limit_opt ::= */ yytestcase(yyruleno==138);
  142919. case 143: /* where_opt ::= */ yytestcase(yyruleno==143);
  142920. case 211: /* case_else ::= */ yytestcase(yyruleno==211);
  142921. case 213: /* case_operand ::= */ yytestcase(yyruleno==213);
  142922. case 232: /* vinto ::= */ yytestcase(yyruleno==232);
  142923. {yymsp[1].minor.yy524 = 0;}
  142924. break;
  142925. case 123: /* indexed_opt ::= INDEXED BY nm */
  142926. {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
  142927. break;
  142928. case 124: /* indexed_opt ::= NOT INDEXED */
  142929. {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
  142930. break;
  142931. case 125: /* using_opt ::= USING LP idlist RP */
  142932. {yymsp[-3].minor.yy62 = yymsp[-1].minor.yy62;}
  142933. break;
  142934. case 126: /* using_opt ::= */
  142935. case 158: /* idlist_opt ::= */ yytestcase(yyruleno==158);
  142936. {yymsp[1].minor.yy62 = 0;}
  142937. break;
  142938. case 128: /* orderby_opt ::= ORDER BY sortlist */
  142939. case 135: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==135);
  142940. {yymsp[-2].minor.yy434 = yymsp[0].minor.yy434;}
  142941. break;
  142942. case 129: /* sortlist ::= sortlist COMMA expr sortorder */
  142943. {
  142944. yymsp[-3].minor.yy434 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy434,yymsp[-1].minor.yy524);
  142945. sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy434,yymsp[0].minor.yy494);
  142946. }
  142947. break;
  142948. case 130: /* sortlist ::= expr sortorder */
  142949. {
  142950. yymsp[-1].minor.yy434 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy524); /*A-overwrites-Y*/
  142951. sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy434,yymsp[0].minor.yy494);
  142952. }
  142953. break;
  142954. case 131: /* sortorder ::= ASC */
  142955. {yymsp[0].minor.yy494 = SQLITE_SO_ASC;}
  142956. break;
  142957. case 132: /* sortorder ::= DESC */
  142958. {yymsp[0].minor.yy494 = SQLITE_SO_DESC;}
  142959. break;
  142960. case 133: /* sortorder ::= */
  142961. {yymsp[1].minor.yy494 = SQLITE_SO_UNDEFINED;}
  142962. break;
  142963. case 139: /* limit_opt ::= LIMIT expr */
  142964. {yymsp[-1].minor.yy524 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy524,0);}
  142965. break;
  142966. case 140: /* limit_opt ::= LIMIT expr OFFSET expr */
  142967. {yymsp[-3].minor.yy524 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy524,yymsp[0].minor.yy524);}
  142968. break;
  142969. case 141: /* limit_opt ::= LIMIT expr COMMA expr */
  142970. {yymsp[-3].minor.yy524 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy524,yymsp[-2].minor.yy524);}
  142971. break;
  142972. case 142: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  142973. {
  142974. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy483, &yymsp[-1].minor.yy0);
  142975. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy483,yymsp[0].minor.yy524,0,0);
  142976. }
  142977. break;
  142978. case 145: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  142979. {
  142980. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy483, &yymsp[-3].minor.yy0);
  142981. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy434,"set list");
  142982. sqlite3Update(pParse,yymsp[-4].minor.yy483,yymsp[-1].minor.yy434,yymsp[0].minor.yy524,yymsp[-5].minor.yy494,0,0,0);
  142983. }
  142984. break;
  142985. case 146: /* setlist ::= setlist COMMA nm EQ expr */
  142986. {
  142987. yymsp[-4].minor.yy434 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy434, yymsp[0].minor.yy524);
  142988. sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy434, &yymsp[-2].minor.yy0, 1);
  142989. }
  142990. break;
  142991. case 147: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
  142992. {
  142993. yymsp[-6].minor.yy434 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy434, yymsp[-3].minor.yy62, yymsp[0].minor.yy524);
  142994. }
  142995. break;
  142996. case 148: /* setlist ::= nm EQ expr */
  142997. {
  142998. yylhsminor.yy434 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy524);
  142999. sqlite3ExprListSetName(pParse, yylhsminor.yy434, &yymsp[-2].minor.yy0, 1);
  143000. }
  143001. yymsp[-2].minor.yy434 = yylhsminor.yy434;
  143002. break;
  143003. case 149: /* setlist ::= LP idlist RP EQ expr */
  143004. {
  143005. yymsp[-4].minor.yy434 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy62, yymsp[0].minor.yy524);
  143006. }
  143007. break;
  143008. case 150: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  143009. {
  143010. sqlite3Insert(pParse, yymsp[-3].minor.yy483, yymsp[-1].minor.yy457, yymsp[-2].minor.yy62, yymsp[-5].minor.yy494, yymsp[0].minor.yy136);
  143011. }
  143012. break;
  143013. case 151: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  143014. {
  143015. sqlite3Insert(pParse, yymsp[-3].minor.yy483, 0, yymsp[-2].minor.yy62, yymsp[-5].minor.yy494, 0);
  143016. }
  143017. break;
  143018. case 152: /* upsert ::= */
  143019. { yymsp[1].minor.yy136 = 0; }
  143020. break;
  143021. case 153: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  143022. { yymsp[-10].minor.yy136 = sqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy434,yymsp[-5].minor.yy524,yymsp[-1].minor.yy434,yymsp[0].minor.yy524);}
  143023. break;
  143024. case 154: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  143025. { yymsp[-7].minor.yy136 = sqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy434,yymsp[-2].minor.yy524,0,0); }
  143026. break;
  143027. case 155: /* upsert ::= ON CONFLICT DO NOTHING */
  143028. { yymsp[-3].minor.yy136 = sqlite3UpsertNew(pParse->db,0,0,0,0); }
  143029. break;
  143030. case 159: /* idlist_opt ::= LP idlist RP */
  143031. {yymsp[-2].minor.yy62 = yymsp[-1].minor.yy62;}
  143032. break;
  143033. case 160: /* idlist ::= idlist COMMA nm */
  143034. {yymsp[-2].minor.yy62 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy62,&yymsp[0].minor.yy0);}
  143035. break;
  143036. case 161: /* idlist ::= nm */
  143037. {yymsp[0].minor.yy62 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
  143038. break;
  143039. case 162: /* expr ::= LP expr RP */
  143040. {yymsp[-2].minor.yy524 = yymsp[-1].minor.yy524;}
  143041. break;
  143042. case 163: /* expr ::= ID|INDEXED */
  143043. case 164: /* expr ::= JOIN_KW */ yytestcase(yyruleno==164);
  143044. {yymsp[0].minor.yy524=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  143045. break;
  143046. case 165: /* expr ::= nm DOT nm */
  143047. {
  143048. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  143049. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  143050. if( IN_RENAME_OBJECT ){
  143051. sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[0].minor.yy0);
  143052. sqlite3RenameTokenMap(pParse, (void*)temp1, &yymsp[-2].minor.yy0);
  143053. }
  143054. yylhsminor.yy524 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
  143055. }
  143056. yymsp[-2].minor.yy524 = yylhsminor.yy524;
  143057. break;
  143058. case 166: /* expr ::= nm DOT nm DOT nm */
  143059. {
  143060. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
  143061. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  143062. Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  143063. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
  143064. if( IN_RENAME_OBJECT ){
  143065. sqlite3RenameTokenMap(pParse, (void*)temp3, &yymsp[0].minor.yy0);
  143066. sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[-2].minor.yy0);
  143067. }
  143068. yylhsminor.yy524 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
  143069. }
  143070. yymsp[-4].minor.yy524 = yylhsminor.yy524;
  143071. break;
  143072. case 167: /* term ::= NULL|FLOAT|BLOB */
  143073. case 168: /* term ::= STRING */ yytestcase(yyruleno==168);
  143074. {yymsp[0].minor.yy524=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  143075. break;
  143076. case 169: /* term ::= INTEGER */
  143077. {
  143078. yylhsminor.yy524 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
  143079. }
  143080. yymsp[0].minor.yy524 = yylhsminor.yy524;
  143081. break;
  143082. case 170: /* expr ::= VARIABLE */
  143083. {
  143084. if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
  143085. u32 n = yymsp[0].minor.yy0.n;
  143086. yymsp[0].minor.yy524 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
  143087. sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy524, n);
  143088. }else{
  143089. /* When doing a nested parse, one can include terms in an expression
  143090. ** that look like this: #1 #2 ... These terms refer to registers
  143091. ** in the virtual machine. #N is the N-th register. */
  143092. Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
  143093. assert( t.n>=2 );
  143094. if( pParse->nested==0 ){
  143095. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
  143096. yymsp[0].minor.yy524 = 0;
  143097. }else{
  143098. yymsp[0].minor.yy524 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
  143099. if( yymsp[0].minor.yy524 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy524->iTable);
  143100. }
  143101. }
  143102. }
  143103. break;
  143104. case 171: /* expr ::= expr COLLATE ID|STRING */
  143105. {
  143106. yymsp[-2].minor.yy524 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy524, &yymsp[0].minor.yy0, 1);
  143107. }
  143108. break;
  143109. case 172: /* expr ::= CAST LP expr AS typetoken RP */
  143110. {
  143111. yymsp[-5].minor.yy524 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
  143112. sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy524, yymsp[-3].minor.yy524, 0);
  143113. }
  143114. break;
  143115. case 173: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  143116. {
  143117. yylhsminor.yy524 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy434, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy494);
  143118. }
  143119. yymsp[-4].minor.yy524 = yylhsminor.yy524;
  143120. break;
  143121. case 174: /* expr ::= ID|INDEXED LP STAR RP */
  143122. {
  143123. yylhsminor.yy524 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
  143124. }
  143125. yymsp[-3].minor.yy524 = yylhsminor.yy524;
  143126. break;
  143127. case 175: /* expr ::= ID|INDEXED LP distinct exprlist RP over_clause */
  143128. {
  143129. yylhsminor.yy524 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy434, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy494);
  143130. sqlite3WindowAttach(pParse, yylhsminor.yy524, yymsp[0].minor.yy295);
  143131. }
  143132. yymsp[-5].minor.yy524 = yylhsminor.yy524;
  143133. break;
  143134. case 176: /* expr ::= ID|INDEXED LP STAR RP over_clause */
  143135. {
  143136. yylhsminor.yy524 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
  143137. sqlite3WindowAttach(pParse, yylhsminor.yy524, yymsp[0].minor.yy295);
  143138. }
  143139. yymsp[-4].minor.yy524 = yylhsminor.yy524;
  143140. break;
  143141. case 177: /* term ::= CTIME_KW */
  143142. {
  143143. yylhsminor.yy524 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
  143144. }
  143145. yymsp[0].minor.yy524 = yylhsminor.yy524;
  143146. break;
  143147. case 178: /* expr ::= LP nexprlist COMMA expr RP */
  143148. {
  143149. ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy434, yymsp[-1].minor.yy524);
  143150. yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  143151. if( yymsp[-4].minor.yy524 ){
  143152. yymsp[-4].minor.yy524->x.pList = pList;
  143153. }else{
  143154. sqlite3ExprListDelete(pParse->db, pList);
  143155. }
  143156. }
  143157. break;
  143158. case 179: /* expr ::= expr AND expr */
  143159. case 180: /* expr ::= expr OR expr */ yytestcase(yyruleno==180);
  143160. case 181: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==181);
  143161. case 182: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==182);
  143162. case 183: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==183);
  143163. case 184: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==184);
  143164. case 185: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==185);
  143165. case 186: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==186);
  143166. {yymsp[-2].minor.yy524=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy524,yymsp[0].minor.yy524);}
  143167. break;
  143168. case 187: /* likeop ::= NOT LIKE_KW|MATCH */
  143169. {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
  143170. break;
  143171. case 188: /* expr ::= expr likeop expr */
  143172. {
  143173. ExprList *pList;
  143174. int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
  143175. yymsp[-1].minor.yy0.n &= 0x7fffffff;
  143176. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy524);
  143177. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy524);
  143178. yymsp[-2].minor.yy524 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
  143179. if( bNot ) yymsp[-2].minor.yy524 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy524, 0);
  143180. if( yymsp[-2].minor.yy524 ) yymsp[-2].minor.yy524->flags |= EP_InfixFunc;
  143181. }
  143182. break;
  143183. case 189: /* expr ::= expr likeop expr ESCAPE expr */
  143184. {
  143185. ExprList *pList;
  143186. int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
  143187. yymsp[-3].minor.yy0.n &= 0x7fffffff;
  143188. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy524);
  143189. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy524);
  143190. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy524);
  143191. yymsp[-4].minor.yy524 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
  143192. if( bNot ) yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy524, 0);
  143193. if( yymsp[-4].minor.yy524 ) yymsp[-4].minor.yy524->flags |= EP_InfixFunc;
  143194. }
  143195. break;
  143196. case 190: /* expr ::= expr ISNULL|NOTNULL */
  143197. {yymsp[-1].minor.yy524 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy524,0);}
  143198. break;
  143199. case 191: /* expr ::= expr NOT NULL */
  143200. {yymsp[-2].minor.yy524 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy524,0);}
  143201. break;
  143202. case 192: /* expr ::= expr IS expr */
  143203. {
  143204. yymsp[-2].minor.yy524 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy524,yymsp[0].minor.yy524);
  143205. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy524, yymsp[-2].minor.yy524, TK_ISNULL);
  143206. }
  143207. break;
  143208. case 193: /* expr ::= expr IS NOT expr */
  143209. {
  143210. yymsp[-3].minor.yy524 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy524,yymsp[0].minor.yy524);
  143211. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy524, yymsp[-3].minor.yy524, TK_NOTNULL);
  143212. }
  143213. break;
  143214. case 194: /* expr ::= NOT expr */
  143215. case 195: /* expr ::= BITNOT expr */ yytestcase(yyruleno==195);
  143216. {yymsp[-1].minor.yy524 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy524, 0);/*A-overwrites-B*/}
  143217. break;
  143218. case 196: /* expr ::= PLUS|MINUS expr */
  143219. {
  143220. yymsp[-1].minor.yy524 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy524, 0);
  143221. /*A-overwrites-B*/
  143222. }
  143223. break;
  143224. case 197: /* between_op ::= BETWEEN */
  143225. case 200: /* in_op ::= IN */ yytestcase(yyruleno==200);
  143226. {yymsp[0].minor.yy494 = 0;}
  143227. break;
  143228. case 199: /* expr ::= expr between_op expr AND expr */
  143229. {
  143230. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy524);
  143231. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy524);
  143232. yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy524, 0);
  143233. if( yymsp[-4].minor.yy524 ){
  143234. yymsp[-4].minor.yy524->x.pList = pList;
  143235. }else{
  143236. sqlite3ExprListDelete(pParse->db, pList);
  143237. }
  143238. if( yymsp[-3].minor.yy494 ) yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy524, 0);
  143239. }
  143240. break;
  143241. case 202: /* expr ::= expr in_op LP exprlist RP */
  143242. {
  143243. if( yymsp[-1].minor.yy434==0 ){
  143244. /* Expressions of the form
  143245. **
  143246. ** expr1 IN ()
  143247. ** expr1 NOT IN ()
  143248. **
  143249. ** simplify to constants 0 (false) and 1 (true), respectively,
  143250. ** regardless of the value of expr1.
  143251. */
  143252. if( IN_RENAME_OBJECT==0 ){
  143253. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy524);
  143254. yymsp[-4].minor.yy524 = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy494],1);
  143255. }
  143256. }else if( yymsp[-1].minor.yy434->nExpr==1 ){
  143257. /* Expressions of the form:
  143258. **
  143259. ** expr1 IN (?1)
  143260. ** expr1 NOT IN (?2)
  143261. **
  143262. ** with exactly one value on the RHS can be simplified to something
  143263. ** like this:
  143264. **
  143265. ** expr1 == ?1
  143266. ** expr1 <> ?2
  143267. **
  143268. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  143269. ** so that it may not contribute to the computation of comparison
  143270. ** affinity or the collating sequence to use for comparison. Otherwise,
  143271. ** the semantics would be subtly different from IN or NOT IN.
  143272. */
  143273. Expr *pRHS = yymsp[-1].minor.yy434->a[0].pExpr;
  143274. yymsp[-1].minor.yy434->a[0].pExpr = 0;
  143275. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy434);
  143276. /* pRHS cannot be NULL because a malloc error would have been detected
  143277. ** before now and control would have never reached this point */
  143278. if( ALWAYS(pRHS) ){
  143279. pRHS->flags &= ~EP_Collate;
  143280. pRHS->flags |= EP_Generic;
  143281. }
  143282. yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, yymsp[-3].minor.yy494 ? TK_NE : TK_EQ, yymsp[-4].minor.yy524, pRHS);
  143283. }else{
  143284. yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy524, 0);
  143285. if( yymsp[-4].minor.yy524 ){
  143286. yymsp[-4].minor.yy524->x.pList = yymsp[-1].minor.yy434;
  143287. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy524);
  143288. }else{
  143289. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy434);
  143290. }
  143291. if( yymsp[-3].minor.yy494 ) yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy524, 0);
  143292. }
  143293. }
  143294. break;
  143295. case 203: /* expr ::= LP select RP */
  143296. {
  143297. yymsp[-2].minor.yy524 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  143298. sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy524, yymsp[-1].minor.yy457);
  143299. }
  143300. break;
  143301. case 204: /* expr ::= expr in_op LP select RP */
  143302. {
  143303. yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy524, 0);
  143304. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy524, yymsp[-1].minor.yy457);
  143305. if( yymsp[-3].minor.yy494 ) yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy524, 0);
  143306. }
  143307. break;
  143308. case 205: /* expr ::= expr in_op nm dbnm paren_exprlist */
  143309. {
  143310. SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
  143311. Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
  143312. if( yymsp[0].minor.yy434 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy434);
  143313. yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy524, 0);
  143314. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy524, pSelect);
  143315. if( yymsp[-3].minor.yy494 ) yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy524, 0);
  143316. }
  143317. break;
  143318. case 206: /* expr ::= EXISTS LP select RP */
  143319. {
  143320. Expr *p;
  143321. p = yymsp[-3].minor.yy524 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
  143322. sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy457);
  143323. }
  143324. break;
  143325. case 207: /* expr ::= CASE case_operand case_exprlist case_else END */
  143326. {
  143327. yymsp[-4].minor.yy524 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy524, 0);
  143328. if( yymsp[-4].minor.yy524 ){
  143329. yymsp[-4].minor.yy524->x.pList = yymsp[-1].minor.yy524 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy434,yymsp[-1].minor.yy524) : yymsp[-2].minor.yy434;
  143330. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy524);
  143331. }else{
  143332. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy434);
  143333. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy524);
  143334. }
  143335. }
  143336. break;
  143337. case 208: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  143338. {
  143339. yymsp[-4].minor.yy434 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy434, yymsp[-2].minor.yy524);
  143340. yymsp[-4].minor.yy434 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy434, yymsp[0].minor.yy524);
  143341. }
  143342. break;
  143343. case 209: /* case_exprlist ::= WHEN expr THEN expr */
  143344. {
  143345. yymsp[-3].minor.yy434 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy524);
  143346. yymsp[-3].minor.yy434 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy434, yymsp[0].minor.yy524);
  143347. }
  143348. break;
  143349. case 212: /* case_operand ::= expr */
  143350. {yymsp[0].minor.yy524 = yymsp[0].minor.yy524; /*A-overwrites-X*/}
  143351. break;
  143352. case 215: /* nexprlist ::= nexprlist COMMA expr */
  143353. {yymsp[-2].minor.yy434 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy434,yymsp[0].minor.yy524);}
  143354. break;
  143355. case 216: /* nexprlist ::= expr */
  143356. {yymsp[0].minor.yy434 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy524); /*A-overwrites-Y*/}
  143357. break;
  143358. case 218: /* paren_exprlist ::= LP exprlist RP */
  143359. case 223: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==223);
  143360. {yymsp[-2].minor.yy434 = yymsp[-1].minor.yy434;}
  143361. break;
  143362. case 219: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  143363. {
  143364. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  143365. sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy434, yymsp[-10].minor.yy494,
  143366. &yymsp[-11].minor.yy0, yymsp[0].minor.yy524, SQLITE_SO_ASC, yymsp[-8].minor.yy494, SQLITE_IDXTYPE_APPDEF);
  143367. if( IN_RENAME_OBJECT && pParse->pNewIndex ){
  143368. sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
  143369. }
  143370. }
  143371. break;
  143372. case 220: /* uniqueflag ::= UNIQUE */
  143373. case 262: /* raisetype ::= ABORT */ yytestcase(yyruleno==262);
  143374. {yymsp[0].minor.yy494 = OE_Abort;}
  143375. break;
  143376. case 221: /* uniqueflag ::= */
  143377. {yymsp[1].minor.yy494 = OE_None;}
  143378. break;
  143379. case 224: /* eidlist ::= eidlist COMMA nm collate sortorder */
  143380. {
  143381. yymsp[-4].minor.yy434 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy434, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy494, yymsp[0].minor.yy494);
  143382. }
  143383. break;
  143384. case 225: /* eidlist ::= nm collate sortorder */
  143385. {
  143386. yymsp[-2].minor.yy434 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy494, yymsp[0].minor.yy494); /*A-overwrites-Y*/
  143387. }
  143388. break;
  143389. case 228: /* cmd ::= DROP INDEX ifexists fullname */
  143390. {sqlite3DropIndex(pParse, yymsp[0].minor.yy483, yymsp[-1].minor.yy494);}
  143391. break;
  143392. case 229: /* cmd ::= VACUUM vinto */
  143393. {sqlite3Vacuum(pParse,0,yymsp[0].minor.yy524);}
  143394. break;
  143395. case 230: /* cmd ::= VACUUM nm vinto */
  143396. {sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy524);}
  143397. break;
  143398. case 233: /* cmd ::= PRAGMA nm dbnm */
  143399. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  143400. break;
  143401. case 234: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  143402. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  143403. break;
  143404. case 235: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  143405. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  143406. break;
  143407. case 236: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  143408. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  143409. break;
  143410. case 237: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  143411. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  143412. break;
  143413. case 240: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  143414. {
  143415. Token all;
  143416. all.z = yymsp[-3].minor.yy0.z;
  143417. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  143418. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy455, &all);
  143419. }
  143420. break;
  143421. case 241: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  143422. {
  143423. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy494, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy483, yymsp[0].minor.yy524, yymsp[-10].minor.yy494, yymsp[-8].minor.yy494);
  143424. yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
  143425. }
  143426. break;
  143427. case 242: /* trigger_time ::= BEFORE|AFTER */
  143428. { yymsp[0].minor.yy494 = yymsp[0].major; /*A-overwrites-X*/ }
  143429. break;
  143430. case 243: /* trigger_time ::= INSTEAD OF */
  143431. { yymsp[-1].minor.yy494 = TK_INSTEAD;}
  143432. break;
  143433. case 244: /* trigger_time ::= */
  143434. { yymsp[1].minor.yy494 = TK_BEFORE; }
  143435. break;
  143436. case 245: /* trigger_event ::= DELETE|INSERT */
  143437. case 246: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==246);
  143438. {yymsp[0].minor.yy90.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy90.b = 0;}
  143439. break;
  143440. case 247: /* trigger_event ::= UPDATE OF idlist */
  143441. {yymsp[-2].minor.yy90.a = TK_UPDATE; yymsp[-2].minor.yy90.b = yymsp[0].minor.yy62;}
  143442. break;
  143443. case 248: /* when_clause ::= */
  143444. case 267: /* key_opt ::= */ yytestcase(yyruleno==267);
  143445. case 315: /* filter_opt ::= */ yytestcase(yyruleno==315);
  143446. { yymsp[1].minor.yy524 = 0; }
  143447. break;
  143448. case 249: /* when_clause ::= WHEN expr */
  143449. case 268: /* key_opt ::= KEY expr */ yytestcase(yyruleno==268);
  143450. { yymsp[-1].minor.yy524 = yymsp[0].minor.yy524; }
  143451. break;
  143452. case 250: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  143453. {
  143454. assert( yymsp[-2].minor.yy455!=0 );
  143455. yymsp[-2].minor.yy455->pLast->pNext = yymsp[-1].minor.yy455;
  143456. yymsp[-2].minor.yy455->pLast = yymsp[-1].minor.yy455;
  143457. }
  143458. break;
  143459. case 251: /* trigger_cmd_list ::= trigger_cmd SEMI */
  143460. {
  143461. assert( yymsp[-1].minor.yy455!=0 );
  143462. yymsp[-1].minor.yy455->pLast = yymsp[-1].minor.yy455;
  143463. }
  143464. break;
  143465. case 252: /* trnm ::= nm DOT nm */
  143466. {
  143467. yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  143468. sqlite3ErrorMsg(pParse,
  143469. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  143470. "statements within triggers");
  143471. }
  143472. break;
  143473. case 253: /* tridxby ::= INDEXED BY nm */
  143474. {
  143475. sqlite3ErrorMsg(pParse,
  143476. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  143477. "within triggers");
  143478. }
  143479. break;
  143480. case 254: /* tridxby ::= NOT INDEXED */
  143481. {
  143482. sqlite3ErrorMsg(pParse,
  143483. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  143484. "within triggers");
  143485. }
  143486. break;
  143487. case 255: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  143488. {yylhsminor.yy455 = sqlite3TriggerUpdateStep(pParse, &yymsp[-5].minor.yy0, yymsp[-2].minor.yy434, yymsp[-1].minor.yy524, yymsp[-6].minor.yy494, yymsp[-7].minor.yy0.z, yymsp[0].minor.yy294);}
  143489. yymsp[-7].minor.yy455 = yylhsminor.yy455;
  143490. break;
  143491. case 256: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  143492. {
  143493. yylhsminor.yy455 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy62,yymsp[-2].minor.yy457,yymsp[-6].minor.yy494,yymsp[-1].minor.yy136,yymsp[-7].minor.yy294,yymsp[0].minor.yy294);/*yylhsminor.yy455-overwrites-yymsp[-6].minor.yy494*/
  143494. }
  143495. yymsp[-7].minor.yy455 = yylhsminor.yy455;
  143496. break;
  143497. case 257: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  143498. {yylhsminor.yy455 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy524, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy294);}
  143499. yymsp[-5].minor.yy455 = yylhsminor.yy455;
  143500. break;
  143501. case 258: /* trigger_cmd ::= scanpt select scanpt */
  143502. {yylhsminor.yy455 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy457, yymsp[-2].minor.yy294, yymsp[0].minor.yy294); /*yylhsminor.yy455-overwrites-yymsp[-1].minor.yy457*/}
  143503. yymsp[-2].minor.yy455 = yylhsminor.yy455;
  143504. break;
  143505. case 259: /* expr ::= RAISE LP IGNORE RP */
  143506. {
  143507. yymsp[-3].minor.yy524 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  143508. if( yymsp[-3].minor.yy524 ){
  143509. yymsp[-3].minor.yy524->affinity = OE_Ignore;
  143510. }
  143511. }
  143512. break;
  143513. case 260: /* expr ::= RAISE LP raisetype COMMA nm RP */
  143514. {
  143515. yymsp[-5].minor.yy524 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  143516. if( yymsp[-5].minor.yy524 ) {
  143517. yymsp[-5].minor.yy524->affinity = (char)yymsp[-3].minor.yy494;
  143518. }
  143519. }
  143520. break;
  143521. case 261: /* raisetype ::= ROLLBACK */
  143522. {yymsp[0].minor.yy494 = OE_Rollback;}
  143523. break;
  143524. case 263: /* raisetype ::= FAIL */
  143525. {yymsp[0].minor.yy494 = OE_Fail;}
  143526. break;
  143527. case 264: /* cmd ::= DROP TRIGGER ifexists fullname */
  143528. {
  143529. sqlite3DropTrigger(pParse,yymsp[0].minor.yy483,yymsp[-1].minor.yy494);
  143530. }
  143531. break;
  143532. case 265: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  143533. {
  143534. sqlite3Attach(pParse, yymsp[-3].minor.yy524, yymsp[-1].minor.yy524, yymsp[0].minor.yy524);
  143535. }
  143536. break;
  143537. case 266: /* cmd ::= DETACH database_kw_opt expr */
  143538. {
  143539. sqlite3Detach(pParse, yymsp[0].minor.yy524);
  143540. }
  143541. break;
  143542. case 269: /* cmd ::= REINDEX */
  143543. {sqlite3Reindex(pParse, 0, 0);}
  143544. break;
  143545. case 270: /* cmd ::= REINDEX nm dbnm */
  143546. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  143547. break;
  143548. case 271: /* cmd ::= ANALYZE */
  143549. {sqlite3Analyze(pParse, 0, 0);}
  143550. break;
  143551. case 272: /* cmd ::= ANALYZE nm dbnm */
  143552. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  143553. break;
  143554. case 273: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  143555. {
  143556. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy483,&yymsp[0].minor.yy0);
  143557. }
  143558. break;
  143559. case 274: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  143560. {
  143561. yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  143562. sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
  143563. }
  143564. break;
  143565. case 275: /* add_column_fullname ::= fullname */
  143566. {
  143567. disableLookaside(pParse);
  143568. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy483);
  143569. }
  143570. break;
  143571. case 276: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
  143572. {
  143573. sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy483, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
  143574. }
  143575. break;
  143576. case 277: /* cmd ::= create_vtab */
  143577. {sqlite3VtabFinishParse(pParse,0);}
  143578. break;
  143579. case 278: /* cmd ::= create_vtab LP vtabarglist RP */
  143580. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  143581. break;
  143582. case 279: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  143583. {
  143584. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy494);
  143585. }
  143586. break;
  143587. case 280: /* vtabarg ::= */
  143588. {sqlite3VtabArgInit(pParse);}
  143589. break;
  143590. case 281: /* vtabargtoken ::= ANY */
  143591. case 282: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==282);
  143592. case 283: /* lp ::= LP */ yytestcase(yyruleno==283);
  143593. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  143594. break;
  143595. case 284: /* with ::= WITH wqlist */
  143596. case 285: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==285);
  143597. { sqlite3WithPush(pParse, yymsp[0].minor.yy59, 1); }
  143598. break;
  143599. case 286: /* wqlist ::= nm eidlist_opt AS LP select RP */
  143600. {
  143601. yymsp[-5].minor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy434, yymsp[-1].minor.yy457); /*A-overwrites-X*/
  143602. }
  143603. break;
  143604. case 287: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  143605. {
  143606. yymsp[-7].minor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy434, yymsp[-1].minor.yy457);
  143607. }
  143608. break;
  143609. case 288: /* windowdefn_list ::= windowdefn */
  143610. { yylhsminor.yy295 = yymsp[0].minor.yy295; }
  143611. yymsp[0].minor.yy295 = yylhsminor.yy295;
  143612. break;
  143613. case 289: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
  143614. {
  143615. assert( yymsp[0].minor.yy295!=0 );
  143616. sqlite3WindowChain(pParse, yymsp[0].minor.yy295, yymsp[-2].minor.yy295);
  143617. yymsp[0].minor.yy295->pNextWin = yymsp[-2].minor.yy295;
  143618. yylhsminor.yy295 = yymsp[0].minor.yy295;
  143619. }
  143620. yymsp[-2].minor.yy295 = yylhsminor.yy295;
  143621. break;
  143622. case 290: /* windowdefn ::= nm AS LP window RP */
  143623. {
  143624. if( ALWAYS(yymsp[-1].minor.yy295) ){
  143625. yymsp[-1].minor.yy295->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
  143626. }
  143627. yylhsminor.yy295 = yymsp[-1].minor.yy295;
  143628. }
  143629. yymsp[-4].minor.yy295 = yylhsminor.yy295;
  143630. break;
  143631. case 291: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
  143632. {
  143633. yymsp[-4].minor.yy295 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy295, yymsp[-2].minor.yy434, yymsp[-1].minor.yy434, 0);
  143634. }
  143635. break;
  143636. case 292: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
  143637. {
  143638. yylhsminor.yy295 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy295, yymsp[-2].minor.yy434, yymsp[-1].minor.yy434, &yymsp[-5].minor.yy0);
  143639. }
  143640. yymsp[-5].minor.yy295 = yylhsminor.yy295;
  143641. break;
  143642. case 293: /* window ::= ORDER BY sortlist frame_opt */
  143643. {
  143644. yymsp[-3].minor.yy295 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy295, 0, yymsp[-1].minor.yy434, 0);
  143645. }
  143646. break;
  143647. case 294: /* window ::= nm ORDER BY sortlist frame_opt */
  143648. {
  143649. yylhsminor.yy295 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy295, 0, yymsp[-1].minor.yy434, &yymsp[-4].minor.yy0);
  143650. }
  143651. yymsp[-4].minor.yy295 = yylhsminor.yy295;
  143652. break;
  143653. case 295: /* window ::= frame_opt */
  143654. {
  143655. yylhsminor.yy295 = yymsp[0].minor.yy295;
  143656. }
  143657. yymsp[0].minor.yy295 = yylhsminor.yy295;
  143658. break;
  143659. case 296: /* window ::= nm frame_opt */
  143660. {
  143661. yylhsminor.yy295 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy295, 0, 0, &yymsp[-1].minor.yy0);
  143662. }
  143663. yymsp[-1].minor.yy295 = yylhsminor.yy295;
  143664. break;
  143665. case 297: /* frame_opt ::= */
  143666. {
  143667. yymsp[1].minor.yy295 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
  143668. }
  143669. break;
  143670. case 298: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
  143671. {
  143672. yylhsminor.yy295 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy494, yymsp[-1].minor.yy201.eType, yymsp[-1].minor.yy201.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy238);
  143673. }
  143674. yymsp[-2].minor.yy295 = yylhsminor.yy295;
  143675. break;
  143676. case 299: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
  143677. {
  143678. yylhsminor.yy295 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy494, yymsp[-3].minor.yy201.eType, yymsp[-3].minor.yy201.pExpr, yymsp[-1].minor.yy201.eType, yymsp[-1].minor.yy201.pExpr, yymsp[0].minor.yy238);
  143679. }
  143680. yymsp[-5].minor.yy295 = yylhsminor.yy295;
  143681. break;
  143682. case 301: /* frame_bound_s ::= frame_bound */
  143683. case 303: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==303);
  143684. {yylhsminor.yy201 = yymsp[0].minor.yy201;}
  143685. yymsp[0].minor.yy201 = yylhsminor.yy201;
  143686. break;
  143687. case 302: /* frame_bound_s ::= UNBOUNDED PRECEDING */
  143688. case 304: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==304);
  143689. case 306: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==306);
  143690. {yylhsminor.yy201.eType = yymsp[-1].major; yylhsminor.yy201.pExpr = 0;}
  143691. yymsp[-1].minor.yy201 = yylhsminor.yy201;
  143692. break;
  143693. case 305: /* frame_bound ::= expr PRECEDING|FOLLOWING */
  143694. {yylhsminor.yy201.eType = yymsp[0].major; yylhsminor.yy201.pExpr = yymsp[-1].minor.yy524;}
  143695. yymsp[-1].minor.yy201 = yylhsminor.yy201;
  143696. break;
  143697. case 307: /* frame_exclude_opt ::= */
  143698. {yymsp[1].minor.yy238 = 0;}
  143699. break;
  143700. case 308: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
  143701. {yymsp[-1].minor.yy238 = yymsp[0].minor.yy238;}
  143702. break;
  143703. case 309: /* frame_exclude ::= NO OTHERS */
  143704. case 310: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==310);
  143705. {yymsp[-1].minor.yy238 = yymsp[-1].major; /*A-overwrites-X*/}
  143706. break;
  143707. case 311: /* frame_exclude ::= GROUP|TIES */
  143708. {yymsp[0].minor.yy238 = yymsp[0].major; /*A-overwrites-X*/}
  143709. break;
  143710. case 312: /* window_clause ::= WINDOW windowdefn_list */
  143711. { yymsp[-1].minor.yy295 = yymsp[0].minor.yy295; }
  143712. break;
  143713. case 313: /* over_clause ::= filter_opt OVER LP window RP */
  143714. {
  143715. yylhsminor.yy295 = yymsp[-1].minor.yy295;
  143716. assert( yylhsminor.yy295!=0 );
  143717. yylhsminor.yy295->pFilter = yymsp[-4].minor.yy524;
  143718. }
  143719. yymsp[-4].minor.yy295 = yylhsminor.yy295;
  143720. break;
  143721. case 314: /* over_clause ::= filter_opt OVER nm */
  143722. {
  143723. yylhsminor.yy295 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  143724. if( yylhsminor.yy295 ){
  143725. yylhsminor.yy295->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
  143726. yylhsminor.yy295->pFilter = yymsp[-2].minor.yy524;
  143727. }else{
  143728. sqlite3ExprDelete(pParse->db, yymsp[-2].minor.yy524);
  143729. }
  143730. }
  143731. yymsp[-2].minor.yy295 = yylhsminor.yy295;
  143732. break;
  143733. case 316: /* filter_opt ::= FILTER LP WHERE expr RP */
  143734. { yymsp[-4].minor.yy524 = yymsp[-1].minor.yy524; }
  143735. break;
  143736. default:
  143737. /* (317) input ::= cmdlist */ yytestcase(yyruleno==317);
  143738. /* (318) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==318);
  143739. /* (319) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=319);
  143740. /* (320) ecmd ::= SEMI */ yytestcase(yyruleno==320);
  143741. /* (321) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==321);
  143742. /* (322) ecmd ::= explain cmdx */ yytestcase(yyruleno==322);
  143743. /* (323) trans_opt ::= */ yytestcase(yyruleno==323);
  143744. /* (324) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==324);
  143745. /* (325) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==325);
  143746. /* (326) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==326);
  143747. /* (327) savepoint_opt ::= */ yytestcase(yyruleno==327);
  143748. /* (328) cmd ::= create_table create_table_args */ yytestcase(yyruleno==328);
  143749. /* (329) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==329);
  143750. /* (330) columnlist ::= columnname carglist */ yytestcase(yyruleno==330);
  143751. /* (331) nm ::= ID|INDEXED */ yytestcase(yyruleno==331);
  143752. /* (332) nm ::= STRING */ yytestcase(yyruleno==332);
  143753. /* (333) nm ::= JOIN_KW */ yytestcase(yyruleno==333);
  143754. /* (334) typetoken ::= typename */ yytestcase(yyruleno==334);
  143755. /* (335) typename ::= ID|STRING */ yytestcase(yyruleno==335);
  143756. /* (336) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=336);
  143757. /* (337) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=337);
  143758. /* (338) carglist ::= carglist ccons */ yytestcase(yyruleno==338);
  143759. /* (339) carglist ::= */ yytestcase(yyruleno==339);
  143760. /* (340) ccons ::= NULL onconf */ yytestcase(yyruleno==340);
  143761. /* (341) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==341);
  143762. /* (342) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==342);
  143763. /* (343) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=343);
  143764. /* (344) tconscomma ::= */ yytestcase(yyruleno==344);
  143765. /* (345) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=345);
  143766. /* (346) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=346);
  143767. /* (347) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=347);
  143768. /* (348) oneselect ::= values */ yytestcase(yyruleno==348);
  143769. /* (349) sclp ::= selcollist COMMA */ yytestcase(yyruleno==349);
  143770. /* (350) as ::= ID|STRING */ yytestcase(yyruleno==350);
  143771. /* (351) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=351);
  143772. /* (352) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==352);
  143773. /* (353) exprlist ::= nexprlist */ yytestcase(yyruleno==353);
  143774. /* (354) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=354);
  143775. /* (355) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=355);
  143776. /* (356) nmnum ::= ON */ yytestcase(yyruleno==356);
  143777. /* (357) nmnum ::= DELETE */ yytestcase(yyruleno==357);
  143778. /* (358) nmnum ::= DEFAULT */ yytestcase(yyruleno==358);
  143779. /* (359) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==359);
  143780. /* (360) foreach_clause ::= */ yytestcase(yyruleno==360);
  143781. /* (361) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==361);
  143782. /* (362) trnm ::= nm */ yytestcase(yyruleno==362);
  143783. /* (363) tridxby ::= */ yytestcase(yyruleno==363);
  143784. /* (364) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==364);
  143785. /* (365) database_kw_opt ::= */ yytestcase(yyruleno==365);
  143786. /* (366) kwcolumn_opt ::= */ yytestcase(yyruleno==366);
  143787. /* (367) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==367);
  143788. /* (368) vtabarglist ::= vtabarg */ yytestcase(yyruleno==368);
  143789. /* (369) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==369);
  143790. /* (370) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==370);
  143791. /* (371) anylist ::= */ yytestcase(yyruleno==371);
  143792. /* (372) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==372);
  143793. /* (373) anylist ::= anylist ANY */ yytestcase(yyruleno==373);
  143794. /* (374) with ::= */ yytestcase(yyruleno==374);
  143795. break;
  143796. /********** End reduce actions ************************************************/
  143797. };
  143798. assert( yyruleno<sizeof(yyRuleInfoLhs)/sizeof(yyRuleInfoLhs[0]) );
  143799. yygoto = yyRuleInfoLhs[yyruleno];
  143800. yysize = yyRuleInfoNRhs[yyruleno];
  143801. yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
  143802. /* There are no SHIFTREDUCE actions on nonterminals because the table
  143803. ** generator has simplified them to pure REDUCE actions. */
  143804. assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
  143805. /* It is not possible for a REDUCE to be followed by an error */
  143806. assert( yyact!=YY_ERROR_ACTION );
  143807. yymsp += yysize+1;
  143808. yypParser->yytos = yymsp;
  143809. yymsp->stateno = (YYACTIONTYPE)yyact;
  143810. yymsp->major = (YYCODETYPE)yygoto;
  143811. yyTraceShift(yypParser, yyact, "... then shift");
  143812. return yyact;
  143813. }
  143814. /*
  143815. ** The following code executes when the parse fails
  143816. */
  143817. #ifndef YYNOERRORRECOVERY
  143818. static void yy_parse_failed(
  143819. yyParser *yypParser /* The parser */
  143820. ){
  143821. sqlite3ParserARG_FETCH
  143822. sqlite3ParserCTX_FETCH
  143823. #ifndef NDEBUG
  143824. if( yyTraceFILE ){
  143825. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  143826. }
  143827. #endif
  143828. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  143829. /* Here code is inserted which will be executed whenever the
  143830. ** parser fails */
  143831. /************ Begin %parse_failure code ***************************************/
  143832. /************ End %parse_failure code *****************************************/
  143833. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  143834. sqlite3ParserCTX_STORE
  143835. }
  143836. #endif /* YYNOERRORRECOVERY */
  143837. /*
  143838. ** The following code executes when a syntax error first occurs.
  143839. */
  143840. static void yy_syntax_error(
  143841. yyParser *yypParser, /* The parser */
  143842. int yymajor, /* The major type of the error token */
  143843. sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
  143844. ){
  143845. sqlite3ParserARG_FETCH
  143846. sqlite3ParserCTX_FETCH
  143847. #define TOKEN yyminor
  143848. /************ Begin %syntax_error code ****************************************/
  143849. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  143850. if( TOKEN.z[0] ){
  143851. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  143852. }else{
  143853. sqlite3ErrorMsg(pParse, "incomplete input");
  143854. }
  143855. /************ End %syntax_error code ******************************************/
  143856. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  143857. sqlite3ParserCTX_STORE
  143858. }
  143859. /*
  143860. ** The following is executed when the parser accepts
  143861. */
  143862. static void yy_accept(
  143863. yyParser *yypParser /* The parser */
  143864. ){
  143865. sqlite3ParserARG_FETCH
  143866. sqlite3ParserCTX_FETCH
  143867. #ifndef NDEBUG
  143868. if( yyTraceFILE ){
  143869. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  143870. }
  143871. #endif
  143872. #ifndef YYNOERRORRECOVERY
  143873. yypParser->yyerrcnt = -1;
  143874. #endif
  143875. assert( yypParser->yytos==yypParser->yystack );
  143876. /* Here code is inserted which will be executed whenever the
  143877. ** parser accepts */
  143878. /*********** Begin %parse_accept code *****************************************/
  143879. /*********** End %parse_accept code *******************************************/
  143880. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  143881. sqlite3ParserCTX_STORE
  143882. }
  143883. /* The main parser program.
  143884. ** The first argument is a pointer to a structure obtained from
  143885. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  143886. ** The second argument is the major token number. The third is
  143887. ** the minor token. The fourth optional argument is whatever the
  143888. ** user wants (and specified in the grammar) and is available for
  143889. ** use by the action routines.
  143890. **
  143891. ** Inputs:
  143892. ** <ul>
  143893. ** <li> A pointer to the parser (an opaque structure.)
  143894. ** <li> The major token number.
  143895. ** <li> The minor token number.
  143896. ** <li> An option argument of a grammar-specified type.
  143897. ** </ul>
  143898. **
  143899. ** Outputs:
  143900. ** None.
  143901. */
  143902. SQLITE_PRIVATE void sqlite3Parser(
  143903. void *yyp, /* The parser */
  143904. int yymajor, /* The major token code number */
  143905. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  143906. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  143907. ){
  143908. YYMINORTYPE yyminorunion;
  143909. YYACTIONTYPE yyact; /* The parser action. */
  143910. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  143911. int yyendofinput; /* True if we are at the end of input */
  143912. #endif
  143913. #ifdef YYERRORSYMBOL
  143914. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  143915. #endif
  143916. yyParser *yypParser = (yyParser*)yyp; /* The parser */
  143917. sqlite3ParserCTX_FETCH
  143918. sqlite3ParserARG_STORE
  143919. assert( yypParser->yytos!=0 );
  143920. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  143921. yyendofinput = (yymajor==0);
  143922. #endif
  143923. yyact = yypParser->yytos->stateno;
  143924. #ifndef NDEBUG
  143925. if( yyTraceFILE ){
  143926. if( yyact < YY_MIN_REDUCE ){
  143927. fprintf(yyTraceFILE,"%sInput '%s' in state %d\n",
  143928. yyTracePrompt,yyTokenName[yymajor],yyact);
  143929. }else{
  143930. fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  143931. yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE);
  143932. }
  143933. }
  143934. #endif
  143935. do{
  143936. assert( yyact==yypParser->yytos->stateno );
  143937. yyact = yy_find_shift_action((YYCODETYPE)yymajor,yyact);
  143938. if( yyact >= YY_MIN_REDUCE ){
  143939. yyact = yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor,
  143940. yyminor sqlite3ParserCTX_PARAM);
  143941. }else if( yyact <= YY_MAX_SHIFTREDUCE ){
  143942. yy_shift(yypParser,yyact,(YYCODETYPE)yymajor,yyminor);
  143943. #ifndef YYNOERRORRECOVERY
  143944. yypParser->yyerrcnt--;
  143945. #endif
  143946. break;
  143947. }else if( yyact==YY_ACCEPT_ACTION ){
  143948. yypParser->yytos--;
  143949. yy_accept(yypParser);
  143950. return;
  143951. }else{
  143952. assert( yyact == YY_ERROR_ACTION );
  143953. yyminorunion.yy0 = yyminor;
  143954. #ifdef YYERRORSYMBOL
  143955. int yymx;
  143956. #endif
  143957. #ifndef NDEBUG
  143958. if( yyTraceFILE ){
  143959. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  143960. }
  143961. #endif
  143962. #ifdef YYERRORSYMBOL
  143963. /* A syntax error has occurred.
  143964. ** The response to an error depends upon whether or not the
  143965. ** grammar defines an error token "ERROR".
  143966. **
  143967. ** This is what we do if the grammar does define ERROR:
  143968. **
  143969. ** * Call the %syntax_error function.
  143970. **
  143971. ** * Begin popping the stack until we enter a state where
  143972. ** it is legal to shift the error symbol, then shift
  143973. ** the error symbol.
  143974. **
  143975. ** * Set the error count to three.
  143976. **
  143977. ** * Begin accepting and shifting new tokens. No new error
  143978. ** processing will occur until three tokens have been
  143979. ** shifted successfully.
  143980. **
  143981. */
  143982. if( yypParser->yyerrcnt<0 ){
  143983. yy_syntax_error(yypParser,yymajor,yyminor);
  143984. }
  143985. yymx = yypParser->yytos->major;
  143986. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  143987. #ifndef NDEBUG
  143988. if( yyTraceFILE ){
  143989. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  143990. yyTracePrompt,yyTokenName[yymajor]);
  143991. }
  143992. #endif
  143993. yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
  143994. yymajor = YYNOCODE;
  143995. }else{
  143996. while( yypParser->yytos >= yypParser->yystack
  143997. && (yyact = yy_find_reduce_action(
  143998. yypParser->yytos->stateno,
  143999. YYERRORSYMBOL)) > YY_MAX_SHIFTREDUCE
  144000. ){
  144001. yy_pop_parser_stack(yypParser);
  144002. }
  144003. if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
  144004. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  144005. yy_parse_failed(yypParser);
  144006. #ifndef YYNOERRORRECOVERY
  144007. yypParser->yyerrcnt = -1;
  144008. #endif
  144009. yymajor = YYNOCODE;
  144010. }else if( yymx!=YYERRORSYMBOL ){
  144011. yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
  144012. }
  144013. }
  144014. yypParser->yyerrcnt = 3;
  144015. yyerrorhit = 1;
  144016. if( yymajor==YYNOCODE ) break;
  144017. yyact = yypParser->yytos->stateno;
  144018. #elif defined(YYNOERRORRECOVERY)
  144019. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  144020. ** do any kind of error recovery. Instead, simply invoke the syntax
  144021. ** error routine and continue going as if nothing had happened.
  144022. **
  144023. ** Applications can set this macro (for example inside %include) if
  144024. ** they intend to abandon the parse upon the first syntax error seen.
  144025. */
  144026. yy_syntax_error(yypParser,yymajor, yyminor);
  144027. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  144028. break;
  144029. #else /* YYERRORSYMBOL is not defined */
  144030. /* This is what we do if the grammar does not define ERROR:
  144031. **
  144032. ** * Report an error message, and throw away the input token.
  144033. **
  144034. ** * If the input token is $, then fail the parse.
  144035. **
  144036. ** As before, subsequent error messages are suppressed until
  144037. ** three input tokens have been successfully shifted.
  144038. */
  144039. if( yypParser->yyerrcnt<=0 ){
  144040. yy_syntax_error(yypParser,yymajor, yyminor);
  144041. }
  144042. yypParser->yyerrcnt = 3;
  144043. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  144044. if( yyendofinput ){
  144045. yy_parse_failed(yypParser);
  144046. #ifndef YYNOERRORRECOVERY
  144047. yypParser->yyerrcnt = -1;
  144048. #endif
  144049. }
  144050. break;
  144051. #endif
  144052. }
  144053. }while( yypParser->yytos>yypParser->yystack );
  144054. #ifndef NDEBUG
  144055. if( yyTraceFILE ){
  144056. yyStackEntry *i;
  144057. char cDiv = '[';
  144058. fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
  144059. for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
  144060. fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
  144061. cDiv = ' ';
  144062. }
  144063. fprintf(yyTraceFILE,"]\n");
  144064. }
  144065. #endif
  144066. return;
  144067. }
  144068. /*
  144069. ** Return the fallback token corresponding to canonical token iToken, or
  144070. ** 0 if iToken has no fallback.
  144071. */
  144072. SQLITE_PRIVATE int sqlite3ParserFallback(int iToken){
  144073. #ifdef YYFALLBACK
  144074. if( iToken<(int)(sizeof(yyFallback)/sizeof(yyFallback[0])) ){
  144075. return yyFallback[iToken];
  144076. }
  144077. #else
  144078. (void)iToken;
  144079. #endif
  144080. return 0;
  144081. }
  144082. /************** End of parse.c ***********************************************/
  144083. /************** Begin file tokenize.c ****************************************/
  144084. /*
  144085. ** 2001 September 15
  144086. **
  144087. ** The author disclaims copyright to this source code. In place of
  144088. ** a legal notice, here is a blessing:
  144089. **
  144090. ** May you do good and not evil.
  144091. ** May you find forgiveness for yourself and forgive others.
  144092. ** May you share freely, never taking more than you give.
  144093. **
  144094. *************************************************************************
  144095. ** An tokenizer for SQL
  144096. **
  144097. ** This file contains C code that splits an SQL input string up into
  144098. ** individual tokens and sends those tokens one-by-one over to the
  144099. ** parser for analysis.
  144100. */
  144101. /* #include "sqliteInt.h" */
  144102. /* #include <stdlib.h> */
  144103. /* Character classes for tokenizing
  144104. **
  144105. ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
  144106. ** using a lookup table, whereas a switch() directly on c uses a binary search.
  144107. ** The lookup table is much faster. To maximize speed, and to ensure that
  144108. ** a lookup table is used, all of the classes need to be small integers and
  144109. ** all of them need to be used within the switch.
  144110. */
  144111. #define CC_X 0 /* The letter 'x', or start of BLOB literal */
  144112. #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
  144113. #define CC_ID 2 /* unicode characters usable in IDs */
  144114. #define CC_DIGIT 3 /* Digits */
  144115. #define CC_DOLLAR 4 /* '$' */
  144116. #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
  144117. #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
  144118. #define CC_SPACE 7 /* Space characters */
  144119. #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
  144120. #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
  144121. #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
  144122. #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
  144123. #define CC_LT 12 /* '<'. Part of < or <= or <> */
  144124. #define CC_GT 13 /* '>'. Part of > or >= */
  144125. #define CC_EQ 14 /* '='. Part of = or == */
  144126. #define CC_BANG 15 /* '!'. Part of != */
  144127. #define CC_SLASH 16 /* '/'. / or c-style comment */
  144128. #define CC_LP 17 /* '(' */
  144129. #define CC_RP 18 /* ')' */
  144130. #define CC_SEMI 19 /* ';' */
  144131. #define CC_PLUS 20 /* '+' */
  144132. #define CC_STAR 21 /* '*' */
  144133. #define CC_PERCENT 22 /* '%' */
  144134. #define CC_COMMA 23 /* ',' */
  144135. #define CC_AND 24 /* '&' */
  144136. #define CC_TILDA 25 /* '~' */
  144137. #define CC_DOT 26 /* '.' */
  144138. #define CC_ILLEGAL 27 /* Illegal character */
  144139. #define CC_NUL 28 /* 0x00 */
  144140. static const unsigned char aiClass[] = {
  144141. #ifdef SQLITE_ASCII
  144142. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  144143. /* 0x */ 28, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
  144144. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  144145. /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
  144146. /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
  144147. /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  144148. /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
  144149. /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  144150. /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
  144151. /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144152. /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144153. /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144154. /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144155. /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144156. /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144157. /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  144158. /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
  144159. #endif
  144160. #ifdef SQLITE_EBCDIC
  144161. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  144162. /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
  144163. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  144164. /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  144165. /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  144166. /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
  144167. /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
  144168. /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6,
  144169. /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
  144170. /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  144171. /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  144172. /* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  144173. /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
  144174. /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  144175. /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  144176. /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  144177. /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
  144178. #endif
  144179. };
  144180. /*
  144181. ** The charMap() macro maps alphabetic characters (only) into their
  144182. ** lower-case ASCII equivalent. On ASCII machines, this is just
  144183. ** an upper-to-lower case map. On EBCDIC machines we also need
  144184. ** to adjust the encoding. The mapping is only valid for alphabetics
  144185. ** which are the only characters for which this feature is used.
  144186. **
  144187. ** Used by keywordhash.h
  144188. */
  144189. #ifdef SQLITE_ASCII
  144190. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  144191. #endif
  144192. #ifdef SQLITE_EBCDIC
  144193. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  144194. const unsigned char ebcdicToAscii[] = {
  144195. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  144196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  144197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  144198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  144199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  144200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  144201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  144202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  144203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  144204. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  144205. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  144206. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  144207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  144208. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  144209. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  144210. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  144211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  144212. };
  144213. #endif
  144214. /*
  144215. ** The sqlite3KeywordCode function looks up an identifier to determine if
  144216. ** it is a keyword. If it is a keyword, the token code of that keyword is
  144217. ** returned. If the input is not a keyword, TK_ID is returned.
  144218. **
  144219. ** The implementation of this routine was generated by a program,
  144220. ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
  144221. ** The output of the mkkeywordhash.c program is written into a file
  144222. ** named keywordhash.h and then included into this source file by
  144223. ** the #include below.
  144224. */
  144225. /************** Include keywordhash.h in the middle of tokenize.c ************/
  144226. /************** Begin file keywordhash.h *************************************/
  144227. /***** This file contains automatically generated code ******
  144228. **
  144229. ** The code in this file has been automatically generated by
  144230. **
  144231. ** sqlite/tool/mkkeywordhash.c
  144232. **
  144233. ** The code in this file implements a function that determines whether
  144234. ** or not a given identifier is really an SQL keyword. The same thing
  144235. ** might be implemented more directly using a hand-written hash table.
  144236. ** But by using this automatically generated code, the size of the code
  144237. ** is substantially reduced. This is important for embedded applications
  144238. ** on platforms with limited memory.
  144239. */
  144240. /* Hash score: 214 */
  144241. /* zKWText[] encodes 950 bytes of keyword text in 629 bytes */
  144242. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  144243. /* ABLEFTHENDEFERRABLELSEXCLUDELETEMPORARYCONSTRAINTERSECTIES */
  144244. /* AVEPOINTOFFSETRANSACTIONATURALTERAISEXCEPTRIGGEREFERENCES */
  144245. /* UNIQUERYWITHOUTERELEASEXCLUSIVEXISTSATTACHAVINGLOBEGINNERANGE */
  144246. /* BETWEENOTHINGROUPSCASCADETACHCASECOLLATECREATECURRENT_DATE */
  144247. /* IMMEDIATEJOINSERTLIKEMATCHPLANALYZEPRAGMABORTUPDATEVALUES */
  144248. /* VIRTUALIMITWHENOTNULLWHERECURSIVEAFTERENAMEANDEFAULT */
  144249. /* AUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSSCURRENT_TIMESTAMP */
  144250. /* ARTITIONDEFERREDISTINCTDROPRECEDINGFAILFILTEREPLACEFOLLOWING */
  144251. /* FROMFULLIFISNULLORDERESTRICTOTHERSOVERIGHTROLLBACKROWS */
  144252. /* UNBOUNDEDUNIONUSINGVACUUMVIEWINDOWBYINITIALLYPRIMARY */
  144253. static const char zKWText[628] = {
  144254. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  144255. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  144256. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  144257. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  144258. 'E','R','R','A','B','L','E','L','S','E','X','C','L','U','D','E','L','E',
  144259. 'T','E','M','P','O','R','A','R','Y','C','O','N','S','T','R','A','I','N',
  144260. 'T','E','R','S','E','C','T','I','E','S','A','V','E','P','O','I','N','T',
  144261. 'O','F','F','S','E','T','R','A','N','S','A','C','T','I','O','N','A','T',
  144262. 'U','R','A','L','T','E','R','A','I','S','E','X','C','E','P','T','R','I',
  144263. 'G','G','E','R','E','F','E','R','E','N','C','E','S','U','N','I','Q','U',
  144264. 'E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S','E',
  144265. 'X','C','L','U','S','I','V','E','X','I','S','T','S','A','T','T','A','C',
  144266. 'H','A','V','I','N','G','L','O','B','E','G','I','N','N','E','R','A','N',
  144267. 'G','E','B','E','T','W','E','E','N','O','T','H','I','N','G','R','O','U',
  144268. 'P','S','C','A','S','C','A','D','E','T','A','C','H','C','A','S','E','C',
  144269. 'O','L','L','A','T','E','C','R','E','A','T','E','C','U','R','R','E','N',
  144270. 'T','_','D','A','T','E','I','M','M','E','D','I','A','T','E','J','O','I',
  144271. 'N','S','E','R','T','L','I','K','E','M','A','T','C','H','P','L','A','N',
  144272. 'A','L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','U','P','D',
  144273. 'A','T','E','V','A','L','U','E','S','V','I','R','T','U','A','L','I','M',
  144274. 'I','T','W','H','E','N','O','T','N','U','L','L','W','H','E','R','E','C',
  144275. 'U','R','S','I','V','E','A','F','T','E','R','E','N','A','M','E','A','N',
  144276. 'D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E','M','E',
  144277. 'N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M','I','T',
  144278. 'C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R','R','E',
  144279. 'N','T','_','T','I','M','E','S','T','A','M','P','A','R','T','I','T','I',
  144280. 'O','N','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  144281. 'R','O','P','R','E','C','E','D','I','N','G','F','A','I','L','F','I','L',
  144282. 'T','E','R','E','P','L','A','C','E','F','O','L','L','O','W','I','N','G',
  144283. 'F','R','O','M','F','U','L','L','I','F','I','S','N','U','L','L','O','R',
  144284. 'D','E','R','E','S','T','R','I','C','T','O','T','H','E','R','S','O','V',
  144285. 'E','R','I','G','H','T','R','O','L','L','B','A','C','K','R','O','W','S',
  144286. 'U','N','B','O','U','N','D','E','D','U','N','I','O','N','U','S','I','N',
  144287. 'G','V','A','C','U','U','M','V','I','E','W','I','N','D','O','W','B','Y',
  144288. 'I','N','I','T','I','A','L','L','Y','P','R','I','M','A','R','Y',
  144289. };
  144290. /* aKWHash[i] is the hash value for the i-th keyword */
  144291. static const unsigned char aKWHash[127] = {
  144292. 75, 111, 127, 73, 108, 29, 0, 0, 83, 0, 77, 63, 0,
  144293. 37, 33, 78, 15, 0, 126, 86, 57, 120, 128, 19, 0, 0,
  144294. 133, 0, 131, 123, 0, 22, 98, 0, 9, 0, 0, 117, 71,
  144295. 0, 69, 6, 0, 49, 95, 140, 0, 129, 106, 0, 0, 54,
  144296. 0, 109, 24, 0, 17, 0, 134, 56, 23, 26, 5, 58, 135,
  144297. 101, 0, 0, 139, 112, 62, 138, 59, 115, 65, 0, 96, 0,
  144298. 105, 45, 0, 104, 0, 0, 0, 100, 97, 102, 107, 119, 14,
  144299. 31, 118, 0, 81, 0, 136, 116, 137, 61, 124, 132, 80, 121,
  144300. 88, 30, 85, 0, 0, 99, 35, 125, 122, 0, 130, 0, 0,
  144301. 41, 0, 91, 89, 90, 0, 20, 87, 113, 82,
  144302. };
  144303. /* aKWNext[] forms the hash collision chain. If aKWHash[i]==0
  144304. ** then the i-th keyword has no more hash collisions. Otherwise,
  144305. ** the next keyword with the same hash is aKWHash[i]-1. */
  144306. static const unsigned char aKWNext[140] = {
  144307. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  144308. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  144309. 0, 0, 0, 21, 0, 0, 12, 0, 0, 0, 0, 0, 0,
  144310. 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  144311. 51, 28, 0, 0, 38, 0, 0, 0, 44, 0, 0, 0, 3,
  144312. 0, 0, 67, 1, 66, 0, 0, 0, 36, 0, 47, 0, 0,
  144313. 0, 0, 0, 48, 50, 76, 0, 0, 42, 0, 60, 0, 0,
  144314. 0, 43, 0, 16, 55, 10, 0, 0, 0, 0, 0, 0, 0,
  144315. 11, 72, 93, 0, 0, 8, 0, 110, 0, 103, 40, 53, 70,
  144316. 0, 114, 0, 74, 52, 0, 0, 92, 39, 46, 0, 68, 32,
  144317. 84, 0, 34, 27, 25, 18, 94, 0, 64, 79,
  144318. };
  144319. /* aKWLen[i] is the length (in bytes) of the i-th keyword */
  144320. static const unsigned char aKWLen[140] = {
  144321. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  144322. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 7,
  144323. 6, 9, 4, 2, 10, 9, 4, 9, 4, 6, 2, 3, 11,
  144324. 6, 2, 7, 5, 5, 6, 7, 10, 6, 5, 7, 4, 5,
  144325. 7, 9, 6, 6, 6, 4, 5, 5, 5, 7, 7, 6, 5,
  144326. 7, 3, 6, 4, 7, 6, 12, 9, 4, 6, 4, 5, 4,
  144327. 7, 6, 5, 6, 6, 7, 5, 4, 7, 3, 2, 4, 5,
  144328. 9, 5, 6, 3, 7, 13, 2, 2, 4, 6, 6, 8, 5,
  144329. 17, 12, 7, 9, 8, 8, 2, 4, 9, 4, 6, 7, 9,
  144330. 4, 4, 2, 6, 5, 8, 6, 4, 5, 8, 4, 3, 9,
  144331. 5, 5, 6, 4, 6, 2, 2, 9, 3, 7,
  144332. };
  144333. /* aKWOffset[i] is the index into zKWText[] of the start of
  144334. ** the text for the i-th keyword. */
  144335. static const unsigned short int aKWOffset[140] = {
  144336. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  144337. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  144338. 86, 90, 90, 94, 99, 106, 114, 117, 123, 126, 126, 129, 131,
  144339. 136, 140, 141, 146, 150, 154, 159, 165, 175, 178, 183, 183, 187,
  144340. 191, 197, 205, 211, 216, 221, 224, 227, 231, 236, 242, 248, 248,
  144341. 254, 255, 259, 265, 269, 276, 282, 294, 303, 305, 311, 315, 320,
  144342. 322, 329, 334, 339, 345, 351, 357, 362, 365, 365, 365, 368, 372,
  144343. 375, 384, 388, 394, 396, 403, 405, 407, 416, 420, 426, 432, 440,
  144344. 445, 445, 445, 461, 470, 477, 478, 485, 488, 497, 501, 506, 513,
  144345. 522, 526, 530, 532, 538, 542, 550, 556, 559, 564, 572, 572, 576,
  144346. 585, 590, 595, 601, 604, 607, 610, 612, 617, 621,
  144347. };
  144348. /* aKWCode[i] is the parser symbol code for the i-th keyword */
  144349. static const unsigned char aKWCode[140] = {
  144350. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  144351. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  144352. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  144353. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  144354. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  144355. TK_EXCLUDE, TK_DELETE, TK_TEMP, TK_TEMP, TK_OR,
  144356. TK_CONSTRAINT, TK_INTERSECT, TK_TIES, TK_SAVEPOINT, TK_INTO,
  144357. TK_OFFSET, TK_OF, TK_SET, TK_TRANSACTION,TK_ACTION,
  144358. TK_ON, TK_JOIN_KW, TK_ALTER, TK_RAISE, TK_EXCEPT,
  144359. TK_TRIGGER, TK_REFERENCES, TK_UNIQUE, TK_QUERY, TK_WITHOUT,
  144360. TK_WITH, TK_JOIN_KW, TK_RELEASE, TK_EXCLUSIVE, TK_EXISTS,
  144361. TK_ATTACH, TK_HAVING, TK_LIKE_KW, TK_BEGIN, TK_JOIN_KW,
  144362. TK_RANGE, TK_BETWEEN, TK_NOTHING, TK_GROUPS, TK_GROUP,
  144363. TK_CASCADE, TK_ASC, TK_DETACH, TK_CASE, TK_COLLATE,
  144364. TK_CREATE, TK_CTIME_KW, TK_IMMEDIATE, TK_JOIN, TK_INSERT,
  144365. TK_LIKE_KW, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  144366. TK_ABORT, TK_UPDATE, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
  144367. TK_WHEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
  144368. TK_WHERE, TK_RECURSIVE, TK_AFTER, TK_RENAME, TK_AND,
  144369. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  144370. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  144371. TK_CTIME_KW, TK_CURRENT, TK_PARTITION, TK_DEFERRED, TK_DISTINCT,
  144372. TK_IS, TK_DROP, TK_PRECEDING, TK_FAIL, TK_FILTER,
  144373. TK_REPLACE, TK_FOLLOWING, TK_FROM, TK_JOIN_KW, TK_IF,
  144374. TK_ISNULL, TK_ORDER, TK_RESTRICT, TK_OTHERS, TK_OVER,
  144375. TK_JOIN_KW, TK_ROLLBACK, TK_ROWS, TK_ROW, TK_UNBOUNDED,
  144376. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_WINDOW,
  144377. TK_DO, TK_BY, TK_INITIALLY, TK_ALL, TK_PRIMARY,
  144378. };
  144379. /* Check to see if z[0..n-1] is a keyword. If it is, write the
  144380. ** parser symbol code for that keyword into *pType. Always
  144381. ** return the integer n (the length of the token). */
  144382. static int keywordCode(const char *z, int n, int *pType){
  144383. int i, j;
  144384. const char *zKW;
  144385. if( n>=2 ){
  144386. i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
  144387. for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
  144388. if( aKWLen[i]!=n ) continue;
  144389. j = 0;
  144390. zKW = &zKWText[aKWOffset[i]];
  144391. #ifdef SQLITE_ASCII
  144392. while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
  144393. #endif
  144394. #ifdef SQLITE_EBCDIC
  144395. while( j<n && toupper(z[j])==zKW[j] ){ j++; }
  144396. #endif
  144397. if( j<n ) continue;
  144398. testcase( i==0 ); /* REINDEX */
  144399. testcase( i==1 ); /* INDEXED */
  144400. testcase( i==2 ); /* INDEX */
  144401. testcase( i==3 ); /* DESC */
  144402. testcase( i==4 ); /* ESCAPE */
  144403. testcase( i==5 ); /* EACH */
  144404. testcase( i==6 ); /* CHECK */
  144405. testcase( i==7 ); /* KEY */
  144406. testcase( i==8 ); /* BEFORE */
  144407. testcase( i==9 ); /* FOREIGN */
  144408. testcase( i==10 ); /* FOR */
  144409. testcase( i==11 ); /* IGNORE */
  144410. testcase( i==12 ); /* REGEXP */
  144411. testcase( i==13 ); /* EXPLAIN */
  144412. testcase( i==14 ); /* INSTEAD */
  144413. testcase( i==15 ); /* ADD */
  144414. testcase( i==16 ); /* DATABASE */
  144415. testcase( i==17 ); /* AS */
  144416. testcase( i==18 ); /* SELECT */
  144417. testcase( i==19 ); /* TABLE */
  144418. testcase( i==20 ); /* LEFT */
  144419. testcase( i==21 ); /* THEN */
  144420. testcase( i==22 ); /* END */
  144421. testcase( i==23 ); /* DEFERRABLE */
  144422. testcase( i==24 ); /* ELSE */
  144423. testcase( i==25 ); /* EXCLUDE */
  144424. testcase( i==26 ); /* DELETE */
  144425. testcase( i==27 ); /* TEMPORARY */
  144426. testcase( i==28 ); /* TEMP */
  144427. testcase( i==29 ); /* OR */
  144428. testcase( i==30 ); /* CONSTRAINT */
  144429. testcase( i==31 ); /* INTERSECT */
  144430. testcase( i==32 ); /* TIES */
  144431. testcase( i==33 ); /* SAVEPOINT */
  144432. testcase( i==34 ); /* INTO */
  144433. testcase( i==35 ); /* OFFSET */
  144434. testcase( i==36 ); /* OF */
  144435. testcase( i==37 ); /* SET */
  144436. testcase( i==38 ); /* TRANSACTION */
  144437. testcase( i==39 ); /* ACTION */
  144438. testcase( i==40 ); /* ON */
  144439. testcase( i==41 ); /* NATURAL */
  144440. testcase( i==42 ); /* ALTER */
  144441. testcase( i==43 ); /* RAISE */
  144442. testcase( i==44 ); /* EXCEPT */
  144443. testcase( i==45 ); /* TRIGGER */
  144444. testcase( i==46 ); /* REFERENCES */
  144445. testcase( i==47 ); /* UNIQUE */
  144446. testcase( i==48 ); /* QUERY */
  144447. testcase( i==49 ); /* WITHOUT */
  144448. testcase( i==50 ); /* WITH */
  144449. testcase( i==51 ); /* OUTER */
  144450. testcase( i==52 ); /* RELEASE */
  144451. testcase( i==53 ); /* EXCLUSIVE */
  144452. testcase( i==54 ); /* EXISTS */
  144453. testcase( i==55 ); /* ATTACH */
  144454. testcase( i==56 ); /* HAVING */
  144455. testcase( i==57 ); /* GLOB */
  144456. testcase( i==58 ); /* BEGIN */
  144457. testcase( i==59 ); /* INNER */
  144458. testcase( i==60 ); /* RANGE */
  144459. testcase( i==61 ); /* BETWEEN */
  144460. testcase( i==62 ); /* NOTHING */
  144461. testcase( i==63 ); /* GROUPS */
  144462. testcase( i==64 ); /* GROUP */
  144463. testcase( i==65 ); /* CASCADE */
  144464. testcase( i==66 ); /* ASC */
  144465. testcase( i==67 ); /* DETACH */
  144466. testcase( i==68 ); /* CASE */
  144467. testcase( i==69 ); /* COLLATE */
  144468. testcase( i==70 ); /* CREATE */
  144469. testcase( i==71 ); /* CURRENT_DATE */
  144470. testcase( i==72 ); /* IMMEDIATE */
  144471. testcase( i==73 ); /* JOIN */
  144472. testcase( i==74 ); /* INSERT */
  144473. testcase( i==75 ); /* LIKE */
  144474. testcase( i==76 ); /* MATCH */
  144475. testcase( i==77 ); /* PLAN */
  144476. testcase( i==78 ); /* ANALYZE */
  144477. testcase( i==79 ); /* PRAGMA */
  144478. testcase( i==80 ); /* ABORT */
  144479. testcase( i==81 ); /* UPDATE */
  144480. testcase( i==82 ); /* VALUES */
  144481. testcase( i==83 ); /* VIRTUAL */
  144482. testcase( i==84 ); /* LIMIT */
  144483. testcase( i==85 ); /* WHEN */
  144484. testcase( i==86 ); /* NOTNULL */
  144485. testcase( i==87 ); /* NOT */
  144486. testcase( i==88 ); /* NO */
  144487. testcase( i==89 ); /* NULL */
  144488. testcase( i==90 ); /* WHERE */
  144489. testcase( i==91 ); /* RECURSIVE */
  144490. testcase( i==92 ); /* AFTER */
  144491. testcase( i==93 ); /* RENAME */
  144492. testcase( i==94 ); /* AND */
  144493. testcase( i==95 ); /* DEFAULT */
  144494. testcase( i==96 ); /* AUTOINCREMENT */
  144495. testcase( i==97 ); /* TO */
  144496. testcase( i==98 ); /* IN */
  144497. testcase( i==99 ); /* CAST */
  144498. testcase( i==100 ); /* COLUMN */
  144499. testcase( i==101 ); /* COMMIT */
  144500. testcase( i==102 ); /* CONFLICT */
  144501. testcase( i==103 ); /* CROSS */
  144502. testcase( i==104 ); /* CURRENT_TIMESTAMP */
  144503. testcase( i==105 ); /* CURRENT_TIME */
  144504. testcase( i==106 ); /* CURRENT */
  144505. testcase( i==107 ); /* PARTITION */
  144506. testcase( i==108 ); /* DEFERRED */
  144507. testcase( i==109 ); /* DISTINCT */
  144508. testcase( i==110 ); /* IS */
  144509. testcase( i==111 ); /* DROP */
  144510. testcase( i==112 ); /* PRECEDING */
  144511. testcase( i==113 ); /* FAIL */
  144512. testcase( i==114 ); /* FILTER */
  144513. testcase( i==115 ); /* REPLACE */
  144514. testcase( i==116 ); /* FOLLOWING */
  144515. testcase( i==117 ); /* FROM */
  144516. testcase( i==118 ); /* FULL */
  144517. testcase( i==119 ); /* IF */
  144518. testcase( i==120 ); /* ISNULL */
  144519. testcase( i==121 ); /* ORDER */
  144520. testcase( i==122 ); /* RESTRICT */
  144521. testcase( i==123 ); /* OTHERS */
  144522. testcase( i==124 ); /* OVER */
  144523. testcase( i==125 ); /* RIGHT */
  144524. testcase( i==126 ); /* ROLLBACK */
  144525. testcase( i==127 ); /* ROWS */
  144526. testcase( i==128 ); /* ROW */
  144527. testcase( i==129 ); /* UNBOUNDED */
  144528. testcase( i==130 ); /* UNION */
  144529. testcase( i==131 ); /* USING */
  144530. testcase( i==132 ); /* VACUUM */
  144531. testcase( i==133 ); /* VIEW */
  144532. testcase( i==134 ); /* WINDOW */
  144533. testcase( i==135 ); /* DO */
  144534. testcase( i==136 ); /* BY */
  144535. testcase( i==137 ); /* INITIALLY */
  144536. testcase( i==138 ); /* ALL */
  144537. testcase( i==139 ); /* PRIMARY */
  144538. *pType = aKWCode[i];
  144539. break;
  144540. }
  144541. }
  144542. return n;
  144543. }
  144544. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  144545. int id = TK_ID;
  144546. keywordCode((char*)z, n, &id);
  144547. return id;
  144548. }
  144549. #define SQLITE_N_KEYWORD 140
  144550. SQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){
  144551. if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;
  144552. *pzName = zKWText + aKWOffset[i];
  144553. *pnName = aKWLen[i];
  144554. return SQLITE_OK;
  144555. }
  144556. SQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; }
  144557. SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){
  144558. return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName);
  144559. }
  144560. /************** End of keywordhash.h *****************************************/
  144561. /************** Continuing where we left off in tokenize.c *******************/
  144562. /*
  144563. ** If X is a character that can be used in an identifier then
  144564. ** IdChar(X) will be true. Otherwise it is false.
  144565. **
  144566. ** For ASCII, any character with the high-order bit set is
  144567. ** allowed in an identifier. For 7-bit characters,
  144568. ** sqlite3IsIdChar[X] must be 1.
  144569. **
  144570. ** For EBCDIC, the rules are more complex but have the same
  144571. ** end result.
  144572. **
  144573. ** Ticket #1066. the SQL standard does not allow '$' in the
  144574. ** middle of identifiers. But many SQL implementations do.
  144575. ** SQLite will allow '$' in identifiers for compatibility.
  144576. ** But the feature is undocumented.
  144577. */
  144578. #ifdef SQLITE_ASCII
  144579. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  144580. #endif
  144581. #ifdef SQLITE_EBCDIC
  144582. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  144583. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  144584. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  144585. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  144586. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  144587. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  144588. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  144589. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  144590. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  144591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  144592. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  144593. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  144594. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  144595. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  144596. };
  144597. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  144598. #endif
  144599. /* Make the IdChar function accessible from ctime.c and alter.c */
  144600. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  144601. #ifndef SQLITE_OMIT_WINDOWFUNC
  144602. /*
  144603. ** Return the id of the next token in string (*pz). Before returning, set
  144604. ** (*pz) to point to the byte following the parsed token.
  144605. */
  144606. static int getToken(const unsigned char **pz){
  144607. const unsigned char *z = *pz;
  144608. int t; /* Token type to return */
  144609. do {
  144610. z += sqlite3GetToken(z, &t);
  144611. }while( t==TK_SPACE );
  144612. if( t==TK_ID
  144613. || t==TK_STRING
  144614. || t==TK_JOIN_KW
  144615. || t==TK_WINDOW
  144616. || t==TK_OVER
  144617. || sqlite3ParserFallback(t)==TK_ID
  144618. ){
  144619. t = TK_ID;
  144620. }
  144621. *pz = z;
  144622. return t;
  144623. }
  144624. /*
  144625. ** The following three functions are called immediately after the tokenizer
  144626. ** reads the keywords WINDOW, OVER and FILTER, respectively, to determine
  144627. ** whether the token should be treated as a keyword or an SQL identifier.
  144628. ** This cannot be handled by the usual lemon %fallback method, due to
  144629. ** the ambiguity in some constructions. e.g.
  144630. **
  144631. ** SELECT sum(x) OVER ...
  144632. **
  144633. ** In the above, "OVER" might be a keyword, or it might be an alias for the
  144634. ** sum(x) expression. If a "%fallback ID OVER" directive were added to
  144635. ** grammar, then SQLite would always treat "OVER" as an alias, making it
  144636. ** impossible to call a window-function without a FILTER clause.
  144637. **
  144638. ** WINDOW is treated as a keyword if:
  144639. **
  144640. ** * the following token is an identifier, or a keyword that can fallback
  144641. ** to being an identifier, and
  144642. ** * the token after than one is TK_AS.
  144643. **
  144644. ** OVER is a keyword if:
  144645. **
  144646. ** * the previous token was TK_RP, and
  144647. ** * the next token is either TK_LP or an identifier.
  144648. **
  144649. ** FILTER is a keyword if:
  144650. **
  144651. ** * the previous token was TK_RP, and
  144652. ** * the next token is TK_LP.
  144653. */
  144654. static int analyzeWindowKeyword(const unsigned char *z){
  144655. int t;
  144656. t = getToken(&z);
  144657. if( t!=TK_ID ) return TK_ID;
  144658. t = getToken(&z);
  144659. if( t!=TK_AS ) return TK_ID;
  144660. return TK_WINDOW;
  144661. }
  144662. static int analyzeOverKeyword(const unsigned char *z, int lastToken){
  144663. if( lastToken==TK_RP ){
  144664. int t = getToken(&z);
  144665. if( t==TK_LP || t==TK_ID ) return TK_OVER;
  144666. }
  144667. return TK_ID;
  144668. }
  144669. static int analyzeFilterKeyword(const unsigned char *z, int lastToken){
  144670. if( lastToken==TK_RP && getToken(&z)==TK_LP ){
  144671. return TK_FILTER;
  144672. }
  144673. return TK_ID;
  144674. }
  144675. #endif /* SQLITE_OMIT_WINDOWFUNC */
  144676. /*
  144677. ** Return the length (in bytes) of the token that begins at z[0].
  144678. ** Store the token type in *tokenType before returning.
  144679. */
  144680. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  144681. int i, c;
  144682. switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
  144683. ** of the token. See the comment on the CC_ defines
  144684. ** above. */
  144685. case CC_SPACE: {
  144686. testcase( z[0]==' ' );
  144687. testcase( z[0]=='\t' );
  144688. testcase( z[0]=='\n' );
  144689. testcase( z[0]=='\f' );
  144690. testcase( z[0]=='\r' );
  144691. for(i=1; sqlite3Isspace(z[i]); i++){}
  144692. *tokenType = TK_SPACE;
  144693. return i;
  144694. }
  144695. case CC_MINUS: {
  144696. if( z[1]=='-' ){
  144697. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  144698. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  144699. return i;
  144700. }
  144701. *tokenType = TK_MINUS;
  144702. return 1;
  144703. }
  144704. case CC_LP: {
  144705. *tokenType = TK_LP;
  144706. return 1;
  144707. }
  144708. case CC_RP: {
  144709. *tokenType = TK_RP;
  144710. return 1;
  144711. }
  144712. case CC_SEMI: {
  144713. *tokenType = TK_SEMI;
  144714. return 1;
  144715. }
  144716. case CC_PLUS: {
  144717. *tokenType = TK_PLUS;
  144718. return 1;
  144719. }
  144720. case CC_STAR: {
  144721. *tokenType = TK_STAR;
  144722. return 1;
  144723. }
  144724. case CC_SLASH: {
  144725. if( z[1]!='*' || z[2]==0 ){
  144726. *tokenType = TK_SLASH;
  144727. return 1;
  144728. }
  144729. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  144730. if( c ) i++;
  144731. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  144732. return i;
  144733. }
  144734. case CC_PERCENT: {
  144735. *tokenType = TK_REM;
  144736. return 1;
  144737. }
  144738. case CC_EQ: {
  144739. *tokenType = TK_EQ;
  144740. return 1 + (z[1]=='=');
  144741. }
  144742. case CC_LT: {
  144743. if( (c=z[1])=='=' ){
  144744. *tokenType = TK_LE;
  144745. return 2;
  144746. }else if( c=='>' ){
  144747. *tokenType = TK_NE;
  144748. return 2;
  144749. }else if( c=='<' ){
  144750. *tokenType = TK_LSHIFT;
  144751. return 2;
  144752. }else{
  144753. *tokenType = TK_LT;
  144754. return 1;
  144755. }
  144756. }
  144757. case CC_GT: {
  144758. if( (c=z[1])=='=' ){
  144759. *tokenType = TK_GE;
  144760. return 2;
  144761. }else if( c=='>' ){
  144762. *tokenType = TK_RSHIFT;
  144763. return 2;
  144764. }else{
  144765. *tokenType = TK_GT;
  144766. return 1;
  144767. }
  144768. }
  144769. case CC_BANG: {
  144770. if( z[1]!='=' ){
  144771. *tokenType = TK_ILLEGAL;
  144772. return 1;
  144773. }else{
  144774. *tokenType = TK_NE;
  144775. return 2;
  144776. }
  144777. }
  144778. case CC_PIPE: {
  144779. if( z[1]!='|' ){
  144780. *tokenType = TK_BITOR;
  144781. return 1;
  144782. }else{
  144783. *tokenType = TK_CONCAT;
  144784. return 2;
  144785. }
  144786. }
  144787. case CC_COMMA: {
  144788. *tokenType = TK_COMMA;
  144789. return 1;
  144790. }
  144791. case CC_AND: {
  144792. *tokenType = TK_BITAND;
  144793. return 1;
  144794. }
  144795. case CC_TILDA: {
  144796. *tokenType = TK_BITNOT;
  144797. return 1;
  144798. }
  144799. case CC_QUOTE: {
  144800. int delim = z[0];
  144801. testcase( delim=='`' );
  144802. testcase( delim=='\'' );
  144803. testcase( delim=='"' );
  144804. for(i=1; (c=z[i])!=0; i++){
  144805. if( c==delim ){
  144806. if( z[i+1]==delim ){
  144807. i++;
  144808. }else{
  144809. break;
  144810. }
  144811. }
  144812. }
  144813. if( c=='\'' ){
  144814. *tokenType = TK_STRING;
  144815. return i+1;
  144816. }else if( c!=0 ){
  144817. *tokenType = TK_ID;
  144818. return i+1;
  144819. }else{
  144820. *tokenType = TK_ILLEGAL;
  144821. return i;
  144822. }
  144823. }
  144824. case CC_DOT: {
  144825. #ifndef SQLITE_OMIT_FLOATING_POINT
  144826. if( !sqlite3Isdigit(z[1]) )
  144827. #endif
  144828. {
  144829. *tokenType = TK_DOT;
  144830. return 1;
  144831. }
  144832. /* If the next character is a digit, this is a floating point
  144833. ** number that begins with ".". Fall thru into the next case */
  144834. }
  144835. case CC_DIGIT: {
  144836. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  144837. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  144838. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  144839. testcase( z[0]=='9' );
  144840. *tokenType = TK_INTEGER;
  144841. #ifndef SQLITE_OMIT_HEX_INTEGER
  144842. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  144843. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  144844. return i;
  144845. }
  144846. #endif
  144847. for(i=0; sqlite3Isdigit(z[i]); i++){}
  144848. #ifndef SQLITE_OMIT_FLOATING_POINT
  144849. if( z[i]=='.' ){
  144850. i++;
  144851. while( sqlite3Isdigit(z[i]) ){ i++; }
  144852. *tokenType = TK_FLOAT;
  144853. }
  144854. if( (z[i]=='e' || z[i]=='E') &&
  144855. ( sqlite3Isdigit(z[i+1])
  144856. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  144857. )
  144858. ){
  144859. i += 2;
  144860. while( sqlite3Isdigit(z[i]) ){ i++; }
  144861. *tokenType = TK_FLOAT;
  144862. }
  144863. #endif
  144864. while( IdChar(z[i]) ){
  144865. *tokenType = TK_ILLEGAL;
  144866. i++;
  144867. }
  144868. return i;
  144869. }
  144870. case CC_QUOTE2: {
  144871. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  144872. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  144873. return i;
  144874. }
  144875. case CC_VARNUM: {
  144876. *tokenType = TK_VARIABLE;
  144877. for(i=1; sqlite3Isdigit(z[i]); i++){}
  144878. return i;
  144879. }
  144880. case CC_DOLLAR:
  144881. case CC_VARALPHA: {
  144882. int n = 0;
  144883. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  144884. testcase( z[0]==':' ); testcase( z[0]=='#' );
  144885. *tokenType = TK_VARIABLE;
  144886. for(i=1; (c=z[i])!=0; i++){
  144887. if( IdChar(c) ){
  144888. n++;
  144889. #ifndef SQLITE_OMIT_TCL_VARIABLE
  144890. }else if( c=='(' && n>0 ){
  144891. do{
  144892. i++;
  144893. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  144894. if( c==')' ){
  144895. i++;
  144896. }else{
  144897. *tokenType = TK_ILLEGAL;
  144898. }
  144899. break;
  144900. }else if( c==':' && z[i+1]==':' ){
  144901. i++;
  144902. #endif
  144903. }else{
  144904. break;
  144905. }
  144906. }
  144907. if( n==0 ) *tokenType = TK_ILLEGAL;
  144908. return i;
  144909. }
  144910. case CC_KYWD: {
  144911. for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
  144912. if( IdChar(z[i]) ){
  144913. /* This token started out using characters that can appear in keywords,
  144914. ** but z[i] is a character not allowed within keywords, so this must
  144915. ** be an identifier instead */
  144916. i++;
  144917. break;
  144918. }
  144919. *tokenType = TK_ID;
  144920. return keywordCode((char*)z, i, tokenType);
  144921. }
  144922. case CC_X: {
  144923. #ifndef SQLITE_OMIT_BLOB_LITERAL
  144924. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  144925. if( z[1]=='\'' ){
  144926. *tokenType = TK_BLOB;
  144927. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  144928. if( z[i]!='\'' || i%2 ){
  144929. *tokenType = TK_ILLEGAL;
  144930. while( z[i] && z[i]!='\'' ){ i++; }
  144931. }
  144932. if( z[i] ) i++;
  144933. return i;
  144934. }
  144935. #endif
  144936. /* If it is not a BLOB literal, then it must be an ID, since no
  144937. ** SQL keywords start with the letter 'x'. Fall through */
  144938. }
  144939. case CC_ID: {
  144940. i = 1;
  144941. break;
  144942. }
  144943. case CC_NUL: {
  144944. *tokenType = TK_ILLEGAL;
  144945. return 0;
  144946. }
  144947. default: {
  144948. *tokenType = TK_ILLEGAL;
  144949. return 1;
  144950. }
  144951. }
  144952. while( IdChar(z[i]) ){ i++; }
  144953. *tokenType = TK_ID;
  144954. return i;
  144955. }
  144956. /*
  144957. ** Run the parser on the given SQL string. The parser structure is
  144958. ** passed in. An SQLITE_ status code is returned. If an error occurs
  144959. ** then an and attempt is made to write an error message into
  144960. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  144961. ** error message.
  144962. */
  144963. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  144964. int nErr = 0; /* Number of errors encountered */
  144965. void *pEngine; /* The LEMON-generated LALR(1) parser */
  144966. int n = 0; /* Length of the next token token */
  144967. int tokenType; /* type of the next token */
  144968. int lastTokenParsed = -1; /* type of the previous token */
  144969. sqlite3 *db = pParse->db; /* The database connection */
  144970. int mxSqlLen; /* Max length of an SQL string */
  144971. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  144972. yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
  144973. #endif
  144974. VVA_ONLY( u8 startedWithOom = db->mallocFailed );
  144975. assert( zSql!=0 );
  144976. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  144977. if( db->nVdbeActive==0 ){
  144978. db->u1.isInterrupted = 0;
  144979. }
  144980. pParse->rc = SQLITE_OK;
  144981. pParse->zTail = zSql;
  144982. assert( pzErrMsg!=0 );
  144983. #ifdef SQLITE_DEBUG
  144984. if( db->flags & SQLITE_ParserTrace ){
  144985. printf("parser: [[[%s]]]\n", zSql);
  144986. sqlite3ParserTrace(stdout, "parser: ");
  144987. }else{
  144988. sqlite3ParserTrace(0, 0);
  144989. }
  144990. #endif
  144991. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  144992. pEngine = &sEngine;
  144993. sqlite3ParserInit(pEngine, pParse);
  144994. #else
  144995. pEngine = sqlite3ParserAlloc(sqlite3Malloc, pParse);
  144996. if( pEngine==0 ){
  144997. sqlite3OomFault(db);
  144998. return SQLITE_NOMEM_BKPT;
  144999. }
  145000. #endif
  145001. assert( pParse->pNewTable==0 );
  145002. assert( pParse->pNewTrigger==0 );
  145003. assert( pParse->nVar==0 );
  145004. assert( pParse->pVList==0 );
  145005. pParse->pParentParse = db->pParse;
  145006. db->pParse = pParse;
  145007. while( 1 ){
  145008. n = sqlite3GetToken((u8*)zSql, &tokenType);
  145009. mxSqlLen -= n;
  145010. if( mxSqlLen<0 ){
  145011. pParse->rc = SQLITE_TOOBIG;
  145012. break;
  145013. }
  145014. #ifndef SQLITE_OMIT_WINDOWFUNC
  145015. if( tokenType>=TK_WINDOW ){
  145016. assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER
  145017. || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW
  145018. );
  145019. #else
  145020. if( tokenType>=TK_SPACE ){
  145021. assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
  145022. #endif /* SQLITE_OMIT_WINDOWFUNC */
  145023. if( db->u1.isInterrupted ){
  145024. pParse->rc = SQLITE_INTERRUPT;
  145025. break;
  145026. }
  145027. if( tokenType==TK_SPACE ){
  145028. zSql += n;
  145029. continue;
  145030. }
  145031. if( zSql[0]==0 ){
  145032. /* Upon reaching the end of input, call the parser two more times
  145033. ** with tokens TK_SEMI and 0, in that order. */
  145034. if( lastTokenParsed==TK_SEMI ){
  145035. tokenType = 0;
  145036. }else if( lastTokenParsed==0 ){
  145037. break;
  145038. }else{
  145039. tokenType = TK_SEMI;
  145040. }
  145041. n = 0;
  145042. #ifndef SQLITE_OMIT_WINDOWFUNC
  145043. }else if( tokenType==TK_WINDOW ){
  145044. assert( n==6 );
  145045. tokenType = analyzeWindowKeyword((const u8*)&zSql[6]);
  145046. }else if( tokenType==TK_OVER ){
  145047. assert( n==4 );
  145048. tokenType = analyzeOverKeyword((const u8*)&zSql[4], lastTokenParsed);
  145049. }else if( tokenType==TK_FILTER ){
  145050. assert( n==6 );
  145051. tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed);
  145052. #endif /* SQLITE_OMIT_WINDOWFUNC */
  145053. }else{
  145054. sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
  145055. break;
  145056. }
  145057. }
  145058. pParse->sLastToken.z = zSql;
  145059. pParse->sLastToken.n = n;
  145060. sqlite3Parser(pEngine, tokenType, pParse->sLastToken);
  145061. lastTokenParsed = tokenType;
  145062. zSql += n;
  145063. assert( db->mallocFailed==0 || pParse->rc!=SQLITE_OK || startedWithOom );
  145064. if( pParse->rc!=SQLITE_OK ) break;
  145065. }
  145066. assert( nErr==0 );
  145067. #ifdef YYTRACKMAXSTACKDEPTH
  145068. sqlite3_mutex_enter(sqlite3MallocMutex());
  145069. sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
  145070. sqlite3ParserStackPeak(pEngine)
  145071. );
  145072. sqlite3_mutex_leave(sqlite3MallocMutex());
  145073. #endif /* YYDEBUG */
  145074. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  145075. sqlite3ParserFinalize(pEngine);
  145076. #else
  145077. sqlite3ParserFree(pEngine, sqlite3_free);
  145078. #endif
  145079. if( db->mallocFailed ){
  145080. pParse->rc = SQLITE_NOMEM_BKPT;
  145081. }
  145082. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  145083. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  145084. }
  145085. assert( pzErrMsg!=0 );
  145086. if( pParse->zErrMsg ){
  145087. *pzErrMsg = pParse->zErrMsg;
  145088. sqlite3_log(pParse->rc, "%s in \"%s\"",
  145089. *pzErrMsg, pParse->zTail);
  145090. pParse->zErrMsg = 0;
  145091. nErr++;
  145092. }
  145093. pParse->zTail = zSql;
  145094. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  145095. sqlite3VdbeDelete(pParse->pVdbe);
  145096. pParse->pVdbe = 0;
  145097. }
  145098. #ifndef SQLITE_OMIT_SHARED_CACHE
  145099. if( pParse->nested==0 ){
  145100. sqlite3DbFree(db, pParse->aTableLock);
  145101. pParse->aTableLock = 0;
  145102. pParse->nTableLock = 0;
  145103. }
  145104. #endif
  145105. #ifndef SQLITE_OMIT_VIRTUALTABLE
  145106. sqlite3_free(pParse->apVtabLock);
  145107. #endif
  145108. if( !IN_SPECIAL_PARSE ){
  145109. /* If the pParse->declareVtab flag is set, do not delete any table
  145110. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  145111. ** will take responsibility for freeing the Table structure.
  145112. */
  145113. sqlite3DeleteTable(db, pParse->pNewTable);
  145114. }
  145115. if( !IN_RENAME_OBJECT ){
  145116. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  145117. }
  145118. if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
  145119. sqlite3DbFree(db, pParse->pVList);
  145120. while( pParse->pAinc ){
  145121. AutoincInfo *p = pParse->pAinc;
  145122. pParse->pAinc = p->pNext;
  145123. sqlite3DbFreeNN(db, p);
  145124. }
  145125. while( pParse->pZombieTab ){
  145126. Table *p = pParse->pZombieTab;
  145127. pParse->pZombieTab = p->pNextZombie;
  145128. sqlite3DeleteTable(db, p);
  145129. }
  145130. db->pParse = pParse->pParentParse;
  145131. pParse->pParentParse = 0;
  145132. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  145133. return nErr;
  145134. }
  145135. #ifdef SQLITE_ENABLE_NORMALIZE
  145136. /*
  145137. ** Insert a single space character into pStr if the current string
  145138. ** ends with an identifier
  145139. */
  145140. static void addSpaceSeparator(sqlite3_str *pStr){
  145141. if( pStr->nChar && sqlite3IsIdChar(pStr->zText[pStr->nChar-1]) ){
  145142. sqlite3_str_append(pStr, " ", 1);
  145143. }
  145144. }
  145145. /*
  145146. ** Compute a normalization of the SQL given by zSql[0..nSql-1]. Return
  145147. ** the normalization in space obtained from sqlite3DbMalloc(). Or return
  145148. ** NULL if anything goes wrong or if zSql is NULL.
  145149. */
  145150. SQLITE_PRIVATE char *sqlite3Normalize(
  145151. Vdbe *pVdbe, /* VM being reprepared */
  145152. const char *zSql /* The original SQL string */
  145153. ){
  145154. sqlite3 *db; /* The database connection */
  145155. int i; /* Next unread byte of zSql[] */
  145156. int n; /* length of current token */
  145157. int tokenType; /* type of current token */
  145158. int prevType = 0; /* Previous non-whitespace token */
  145159. int nParen; /* Number of nested levels of parentheses */
  145160. int iStartIN; /* Start of RHS of IN operator in z[] */
  145161. int nParenAtIN; /* Value of nParent at start of RHS of IN operator */
  145162. int j; /* Bytes of normalized SQL generated so far */
  145163. sqlite3_str *pStr; /* The normalized SQL string under construction */
  145164. db = sqlite3VdbeDb(pVdbe);
  145165. tokenType = -1;
  145166. nParen = iStartIN = nParenAtIN = 0;
  145167. pStr = sqlite3_str_new(db);
  145168. assert( pStr!=0 ); /* sqlite3_str_new() never returns NULL */
  145169. for(i=0; zSql[i] && pStr->accError==0; i+=n){
  145170. if( tokenType!=TK_SPACE ){
  145171. prevType = tokenType;
  145172. }
  145173. n = sqlite3GetToken((unsigned char*)zSql+i, &tokenType);
  145174. if( NEVER(n<=0) ) break;
  145175. switch( tokenType ){
  145176. case TK_SPACE: {
  145177. break;
  145178. }
  145179. case TK_NULL: {
  145180. if( prevType==TK_IS || prevType==TK_NOT ){
  145181. sqlite3_str_append(pStr, " NULL", 5);
  145182. break;
  145183. }
  145184. /* Fall through */
  145185. }
  145186. case TK_STRING:
  145187. case TK_INTEGER:
  145188. case TK_FLOAT:
  145189. case TK_VARIABLE:
  145190. case TK_BLOB: {
  145191. sqlite3_str_append(pStr, "?", 1);
  145192. break;
  145193. }
  145194. case TK_LP: {
  145195. nParen++;
  145196. if( prevType==TK_IN ){
  145197. iStartIN = pStr->nChar;
  145198. nParenAtIN = nParen;
  145199. }
  145200. sqlite3_str_append(pStr, "(", 1);
  145201. break;
  145202. }
  145203. case TK_RP: {
  145204. if( iStartIN>0 && nParen==nParenAtIN ){
  145205. assert( pStr->nChar>=iStartIN );
  145206. pStr->nChar = iStartIN+1;
  145207. sqlite3_str_append(pStr, "?,?,?", 5);
  145208. iStartIN = 0;
  145209. }
  145210. nParen--;
  145211. sqlite3_str_append(pStr, ")", 1);
  145212. break;
  145213. }
  145214. case TK_ID: {
  145215. iStartIN = 0;
  145216. j = pStr->nChar;
  145217. if( sqlite3Isquote(zSql[i]) ){
  145218. char *zId = sqlite3DbStrNDup(db, zSql+i, n);
  145219. int nId;
  145220. int eType = 0;
  145221. if( zId==0 ) break;
  145222. sqlite3Dequote(zId);
  145223. if( zSql[i]=='"' && sqlite3VdbeUsesDoubleQuotedString(pVdbe, zId) ){
  145224. sqlite3_str_append(pStr, "?", 1);
  145225. sqlite3DbFree(db, zId);
  145226. break;
  145227. }
  145228. nId = sqlite3Strlen30(zId);
  145229. if( sqlite3GetToken((u8*)zId, &eType)==nId && eType==TK_ID ){
  145230. addSpaceSeparator(pStr);
  145231. sqlite3_str_append(pStr, zId, nId);
  145232. }else{
  145233. sqlite3_str_appendf(pStr, "\"%w\"", zId);
  145234. }
  145235. sqlite3DbFree(db, zId);
  145236. }else{
  145237. addSpaceSeparator(pStr);
  145238. sqlite3_str_append(pStr, zSql+i, n);
  145239. }
  145240. while( j<pStr->nChar ){
  145241. pStr->zText[j] = sqlite3Tolower(pStr->zText[j]);
  145242. j++;
  145243. }
  145244. break;
  145245. }
  145246. case TK_SELECT: {
  145247. iStartIN = 0;
  145248. /* fall through */
  145249. }
  145250. default: {
  145251. if( sqlite3IsIdChar(zSql[i]) ) addSpaceSeparator(pStr);
  145252. j = pStr->nChar;
  145253. sqlite3_str_append(pStr, zSql+i, n);
  145254. while( j<pStr->nChar ){
  145255. pStr->zText[j] = sqlite3Toupper(pStr->zText[j]);
  145256. j++;
  145257. }
  145258. break;
  145259. }
  145260. }
  145261. }
  145262. if( tokenType!=TK_SEMI ) sqlite3_str_append(pStr, ";", 1);
  145263. return sqlite3_str_finish(pStr);
  145264. }
  145265. #endif /* SQLITE_ENABLE_NORMALIZE */
  145266. /************** End of tokenize.c ********************************************/
  145267. /************** Begin file complete.c ****************************************/
  145268. /*
  145269. ** 2001 September 15
  145270. **
  145271. ** The author disclaims copyright to this source code. In place of
  145272. ** a legal notice, here is a blessing:
  145273. **
  145274. ** May you do good and not evil.
  145275. ** May you find forgiveness for yourself and forgive others.
  145276. ** May you share freely, never taking more than you give.
  145277. **
  145278. *************************************************************************
  145279. ** An tokenizer for SQL
  145280. **
  145281. ** This file contains C code that implements the sqlite3_complete() API.
  145282. ** This code used to be part of the tokenizer.c source file. But by
  145283. ** separating it out, the code will be automatically omitted from
  145284. ** static links that do not use it.
  145285. */
  145286. /* #include "sqliteInt.h" */
  145287. #ifndef SQLITE_OMIT_COMPLETE
  145288. /*
  145289. ** This is defined in tokenize.c. We just have to import the definition.
  145290. */
  145291. #ifndef SQLITE_AMALGAMATION
  145292. #ifdef SQLITE_ASCII
  145293. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  145294. #endif
  145295. #ifdef SQLITE_EBCDIC
  145296. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  145297. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  145298. #endif
  145299. #endif /* SQLITE_AMALGAMATION */
  145300. /*
  145301. ** Token types used by the sqlite3_complete() routine. See the header
  145302. ** comments on that procedure for additional information.
  145303. */
  145304. #define tkSEMI 0
  145305. #define tkWS 1
  145306. #define tkOTHER 2
  145307. #ifndef SQLITE_OMIT_TRIGGER
  145308. #define tkEXPLAIN 3
  145309. #define tkCREATE 4
  145310. #define tkTEMP 5
  145311. #define tkTRIGGER 6
  145312. #define tkEND 7
  145313. #endif
  145314. /*
  145315. ** Return TRUE if the given SQL string ends in a semicolon.
  145316. **
  145317. ** Special handling is require for CREATE TRIGGER statements.
  145318. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  145319. ** must end with ";END;".
  145320. **
  145321. ** This implementation uses a state machine with 8 states:
  145322. **
  145323. ** (0) INVALID We have not yet seen a non-whitespace character.
  145324. **
  145325. ** (1) START At the beginning or end of an SQL statement. This routine
  145326. ** returns 1 if it ends in the START state and 0 if it ends
  145327. ** in any other state.
  145328. **
  145329. ** (2) NORMAL We are in the middle of statement which ends with a single
  145330. ** semicolon.
  145331. **
  145332. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  145333. ** a statement.
  145334. **
  145335. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  145336. ** statement, possibly preceded by EXPLAIN and/or followed by
  145337. ** TEMP or TEMPORARY
  145338. **
  145339. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  145340. ** ended by a semicolon, the keyword END, and another semicolon.
  145341. **
  145342. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  145343. ** the end of a trigger definition.
  145344. **
  145345. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  145346. ** of a trigger definition.
  145347. **
  145348. ** Transitions between states above are determined by tokens extracted
  145349. ** from the input. The following tokens are significant:
  145350. **
  145351. ** (0) tkSEMI A semicolon.
  145352. ** (1) tkWS Whitespace.
  145353. ** (2) tkOTHER Any other SQL token.
  145354. ** (3) tkEXPLAIN The "explain" keyword.
  145355. ** (4) tkCREATE The "create" keyword.
  145356. ** (5) tkTEMP The "temp" or "temporary" keyword.
  145357. ** (6) tkTRIGGER The "trigger" keyword.
  145358. ** (7) tkEND The "end" keyword.
  145359. **
  145360. ** Whitespace never causes a state transition and is always ignored.
  145361. ** This means that a SQL string of all whitespace is invalid.
  145362. **
  145363. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  145364. ** to recognize the end of a trigger can be omitted. All we have to do
  145365. ** is look for a semicolon that is not part of an string or comment.
  145366. */
  145367. SQLITE_API int sqlite3_complete(const char *zSql){
  145368. u8 state = 0; /* Current state, using numbers defined in header comment */
  145369. u8 token; /* Value of the next token */
  145370. #ifndef SQLITE_OMIT_TRIGGER
  145371. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  145372. ** statement. This is the normal case.
  145373. */
  145374. static const u8 trans[8][8] = {
  145375. /* Token: */
  145376. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  145377. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  145378. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  145379. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  145380. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  145381. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  145382. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  145383. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  145384. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  145385. };
  145386. #else
  145387. /* If triggers are not supported by this compile then the statement machine
  145388. ** used to detect the end of a statement is much simpler
  145389. */
  145390. static const u8 trans[3][3] = {
  145391. /* Token: */
  145392. /* State: ** SEMI WS OTHER */
  145393. /* 0 INVALID: */ { 1, 0, 2, },
  145394. /* 1 START: */ { 1, 1, 2, },
  145395. /* 2 NORMAL: */ { 1, 2, 2, },
  145396. };
  145397. #endif /* SQLITE_OMIT_TRIGGER */
  145398. #ifdef SQLITE_ENABLE_API_ARMOR
  145399. if( zSql==0 ){
  145400. (void)SQLITE_MISUSE_BKPT;
  145401. return 0;
  145402. }
  145403. #endif
  145404. while( *zSql ){
  145405. switch( *zSql ){
  145406. case ';': { /* A semicolon */
  145407. token = tkSEMI;
  145408. break;
  145409. }
  145410. case ' ':
  145411. case '\r':
  145412. case '\t':
  145413. case '\n':
  145414. case '\f': { /* White space is ignored */
  145415. token = tkWS;
  145416. break;
  145417. }
  145418. case '/': { /* C-style comments */
  145419. if( zSql[1]!='*' ){
  145420. token = tkOTHER;
  145421. break;
  145422. }
  145423. zSql += 2;
  145424. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  145425. if( zSql[0]==0 ) return 0;
  145426. zSql++;
  145427. token = tkWS;
  145428. break;
  145429. }
  145430. case '-': { /* SQL-style comments from "--" to end of line */
  145431. if( zSql[1]!='-' ){
  145432. token = tkOTHER;
  145433. break;
  145434. }
  145435. while( *zSql && *zSql!='\n' ){ zSql++; }
  145436. if( *zSql==0 ) return state==1;
  145437. token = tkWS;
  145438. break;
  145439. }
  145440. case '[': { /* Microsoft-style identifiers in [...] */
  145441. zSql++;
  145442. while( *zSql && *zSql!=']' ){ zSql++; }
  145443. if( *zSql==0 ) return 0;
  145444. token = tkOTHER;
  145445. break;
  145446. }
  145447. case '`': /* Grave-accent quoted symbols used by MySQL */
  145448. case '"': /* single- and double-quoted strings */
  145449. case '\'': {
  145450. int c = *zSql;
  145451. zSql++;
  145452. while( *zSql && *zSql!=c ){ zSql++; }
  145453. if( *zSql==0 ) return 0;
  145454. token = tkOTHER;
  145455. break;
  145456. }
  145457. default: {
  145458. #ifdef SQLITE_EBCDIC
  145459. unsigned char c;
  145460. #endif
  145461. if( IdChar((u8)*zSql) ){
  145462. /* Keywords and unquoted identifiers */
  145463. int nId;
  145464. for(nId=1; IdChar(zSql[nId]); nId++){}
  145465. #ifdef SQLITE_OMIT_TRIGGER
  145466. token = tkOTHER;
  145467. #else
  145468. switch( *zSql ){
  145469. case 'c': case 'C': {
  145470. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  145471. token = tkCREATE;
  145472. }else{
  145473. token = tkOTHER;
  145474. }
  145475. break;
  145476. }
  145477. case 't': case 'T': {
  145478. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  145479. token = tkTRIGGER;
  145480. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  145481. token = tkTEMP;
  145482. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  145483. token = tkTEMP;
  145484. }else{
  145485. token = tkOTHER;
  145486. }
  145487. break;
  145488. }
  145489. case 'e': case 'E': {
  145490. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  145491. token = tkEND;
  145492. }else
  145493. #ifndef SQLITE_OMIT_EXPLAIN
  145494. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  145495. token = tkEXPLAIN;
  145496. }else
  145497. #endif
  145498. {
  145499. token = tkOTHER;
  145500. }
  145501. break;
  145502. }
  145503. default: {
  145504. token = tkOTHER;
  145505. break;
  145506. }
  145507. }
  145508. #endif /* SQLITE_OMIT_TRIGGER */
  145509. zSql += nId-1;
  145510. }else{
  145511. /* Operators and special symbols */
  145512. token = tkOTHER;
  145513. }
  145514. break;
  145515. }
  145516. }
  145517. state = trans[state][token];
  145518. zSql++;
  145519. }
  145520. return state==1;
  145521. }
  145522. #ifndef SQLITE_OMIT_UTF16
  145523. /*
  145524. ** This routine is the same as the sqlite3_complete() routine described
  145525. ** above, except that the parameter is required to be UTF-16 encoded, not
  145526. ** UTF-8.
  145527. */
  145528. SQLITE_API int sqlite3_complete16(const void *zSql){
  145529. sqlite3_value *pVal;
  145530. char const *zSql8;
  145531. int rc;
  145532. #ifndef SQLITE_OMIT_AUTOINIT
  145533. rc = sqlite3_initialize();
  145534. if( rc ) return rc;
  145535. #endif
  145536. pVal = sqlite3ValueNew(0);
  145537. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  145538. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  145539. if( zSql8 ){
  145540. rc = sqlite3_complete(zSql8);
  145541. }else{
  145542. rc = SQLITE_NOMEM_BKPT;
  145543. }
  145544. sqlite3ValueFree(pVal);
  145545. return rc & 0xff;
  145546. }
  145547. #endif /* SQLITE_OMIT_UTF16 */
  145548. #endif /* SQLITE_OMIT_COMPLETE */
  145549. /************** End of complete.c ********************************************/
  145550. /************** Begin file main.c ********************************************/
  145551. /*
  145552. ** 2001 September 15
  145553. **
  145554. ** The author disclaims copyright to this source code. In place of
  145555. ** a legal notice, here is a blessing:
  145556. **
  145557. ** May you do good and not evil.
  145558. ** May you find forgiveness for yourself and forgive others.
  145559. ** May you share freely, never taking more than you give.
  145560. **
  145561. *************************************************************************
  145562. ** Main file for the SQLite library. The routines in this file
  145563. ** implement the programmer interface to the library. Routines in
  145564. ** other files are for internal use by SQLite and should not be
  145565. ** accessed by users of the library.
  145566. */
  145567. /* #include "sqliteInt.h" */
  145568. #ifdef SQLITE_ENABLE_FTS3
  145569. /************** Include fts3.h in the middle of main.c ***********************/
  145570. /************** Begin file fts3.h ********************************************/
  145571. /*
  145572. ** 2006 Oct 10
  145573. **
  145574. ** The author disclaims copyright to this source code. In place of
  145575. ** a legal notice, here is a blessing:
  145576. **
  145577. ** May you do good and not evil.
  145578. ** May you find forgiveness for yourself and forgive others.
  145579. ** May you share freely, never taking more than you give.
  145580. **
  145581. ******************************************************************************
  145582. **
  145583. ** This header file is used by programs that want to link against the
  145584. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  145585. */
  145586. /* #include "sqlite3.h" */
  145587. #if 0
  145588. extern "C" {
  145589. #endif /* __cplusplus */
  145590. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  145591. #if 0
  145592. } /* extern "C" */
  145593. #endif /* __cplusplus */
  145594. /************** End of fts3.h ************************************************/
  145595. /************** Continuing where we left off in main.c ***********************/
  145596. #endif
  145597. #ifdef SQLITE_ENABLE_RTREE
  145598. /************** Include rtree.h in the middle of main.c **********************/
  145599. /************** Begin file rtree.h *******************************************/
  145600. /*
  145601. ** 2008 May 26
  145602. **
  145603. ** The author disclaims copyright to this source code. In place of
  145604. ** a legal notice, here is a blessing:
  145605. **
  145606. ** May you do good and not evil.
  145607. ** May you find forgiveness for yourself and forgive others.
  145608. ** May you share freely, never taking more than you give.
  145609. **
  145610. ******************************************************************************
  145611. **
  145612. ** This header file is used by programs that want to link against the
  145613. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  145614. */
  145615. /* #include "sqlite3.h" */
  145616. #ifdef SQLITE_OMIT_VIRTUALTABLE
  145617. # undef SQLITE_ENABLE_RTREE
  145618. #endif
  145619. #if 0
  145620. extern "C" {
  145621. #endif /* __cplusplus */
  145622. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  145623. #if 0
  145624. } /* extern "C" */
  145625. #endif /* __cplusplus */
  145626. /************** End of rtree.h ***********************************************/
  145627. /************** Continuing where we left off in main.c ***********************/
  145628. #endif
  145629. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  145630. /************** Include sqliteicu.h in the middle of main.c ******************/
  145631. /************** Begin file sqliteicu.h ***************************************/
  145632. /*
  145633. ** 2008 May 26
  145634. **
  145635. ** The author disclaims copyright to this source code. In place of
  145636. ** a legal notice, here is a blessing:
  145637. **
  145638. ** May you do good and not evil.
  145639. ** May you find forgiveness for yourself and forgive others.
  145640. ** May you share freely, never taking more than you give.
  145641. **
  145642. ******************************************************************************
  145643. **
  145644. ** This header file is used by programs that want to link against the
  145645. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  145646. */
  145647. /* #include "sqlite3.h" */
  145648. #if 0
  145649. extern "C" {
  145650. #endif /* __cplusplus */
  145651. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  145652. #if 0
  145653. } /* extern "C" */
  145654. #endif /* __cplusplus */
  145655. /************** End of sqliteicu.h *******************************************/
  145656. /************** Continuing where we left off in main.c ***********************/
  145657. #endif
  145658. #ifdef SQLITE_ENABLE_JSON1
  145659. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  145660. #endif
  145661. #ifdef SQLITE_ENABLE_STMTVTAB
  145662. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
  145663. #endif
  145664. #ifdef SQLITE_ENABLE_FTS5
  145665. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  145666. #endif
  145667. #ifndef SQLITE_AMALGAMATION
  145668. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  145669. ** contains the text of SQLITE_VERSION macro.
  145670. */
  145671. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  145672. #endif
  145673. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  145674. ** a pointer to the to the sqlite3_version[] string constant.
  145675. */
  145676. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  145677. /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
  145678. ** pointer to a string constant whose value is the same as the
  145679. ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
  145680. ** an edited copy of the amalgamation, then the last four characters of
  145681. ** the hash might be different from SQLITE_SOURCE_ID.
  145682. */
  145683. /* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
  145684. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  145685. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  145686. */
  145687. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  145688. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  145689. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  145690. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  145691. */
  145692. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  145693. /*
  145694. ** When compiling the test fixture or with debugging enabled (on Win32),
  145695. ** this variable being set to non-zero will cause OSTRACE macros to emit
  145696. ** extra diagnostic information.
  145697. */
  145698. #ifdef SQLITE_HAVE_OS_TRACE
  145699. # ifndef SQLITE_DEBUG_OS_TRACE
  145700. # define SQLITE_DEBUG_OS_TRACE 0
  145701. # endif
  145702. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  145703. #endif
  145704. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  145705. /*
  145706. ** If the following function pointer is not NULL and if
  145707. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  145708. ** I/O active are written using this function. These messages
  145709. ** are intended for debugging activity only.
  145710. */
  145711. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  145712. #endif
  145713. /*
  145714. ** If the following global variable points to a string which is the
  145715. ** name of a directory, then that directory will be used to store
  145716. ** temporary files.
  145717. **
  145718. ** See also the "PRAGMA temp_store_directory" SQL command.
  145719. */
  145720. SQLITE_API char *sqlite3_temp_directory = 0;
  145721. /*
  145722. ** If the following global variable points to a string which is the
  145723. ** name of a directory, then that directory will be used to store
  145724. ** all database files specified with a relative pathname.
  145725. **
  145726. ** See also the "PRAGMA data_store_directory" SQL command.
  145727. */
  145728. SQLITE_API char *sqlite3_data_directory = 0;
  145729. /*
  145730. ** Initialize SQLite.
  145731. **
  145732. ** This routine must be called to initialize the memory allocation,
  145733. ** VFS, and mutex subsystems prior to doing any serious work with
  145734. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  145735. ** this routine will be called automatically by key routines such as
  145736. ** sqlite3_open().
  145737. **
  145738. ** This routine is a no-op except on its very first call for the process,
  145739. ** or for the first call after a call to sqlite3_shutdown.
  145740. **
  145741. ** The first thread to call this routine runs the initialization to
  145742. ** completion. If subsequent threads call this routine before the first
  145743. ** thread has finished the initialization process, then the subsequent
  145744. ** threads must block until the first thread finishes with the initialization.
  145745. **
  145746. ** The first thread might call this routine recursively. Recursive
  145747. ** calls to this routine should not block, of course. Otherwise the
  145748. ** initialization process would never complete.
  145749. **
  145750. ** Let X be the first thread to enter this routine. Let Y be some other
  145751. ** thread. Then while the initial invocation of this routine by X is
  145752. ** incomplete, it is required that:
  145753. **
  145754. ** * Calls to this routine from Y must block until the outer-most
  145755. ** call by X completes.
  145756. **
  145757. ** * Recursive calls to this routine from thread X return immediately
  145758. ** without blocking.
  145759. */
  145760. SQLITE_API int sqlite3_initialize(void){
  145761. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  145762. int rc; /* Result code */
  145763. #ifdef SQLITE_EXTRA_INIT
  145764. int bRunExtraInit = 0; /* Extra initialization needed */
  145765. #endif
  145766. #ifdef SQLITE_OMIT_WSD
  145767. rc = sqlite3_wsd_init(4096, 24);
  145768. if( rc!=SQLITE_OK ){
  145769. return rc;
  145770. }
  145771. #endif
  145772. /* If the following assert() fails on some obscure processor/compiler
  145773. ** combination, the work-around is to set the correct pointer
  145774. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  145775. assert( SQLITE_PTRSIZE==sizeof(char*) );
  145776. /* If SQLite is already completely initialized, then this call
  145777. ** to sqlite3_initialize() should be a no-op. But the initialization
  145778. ** must be complete. So isInit must not be set until the very end
  145779. ** of this routine.
  145780. */
  145781. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  145782. /* Make sure the mutex subsystem is initialized. If unable to
  145783. ** initialize the mutex subsystem, return early with the error.
  145784. ** If the system is so sick that we are unable to allocate a mutex,
  145785. ** there is not much SQLite is going to be able to do.
  145786. **
  145787. ** The mutex subsystem must take care of serializing its own
  145788. ** initialization.
  145789. */
  145790. rc = sqlite3MutexInit();
  145791. if( rc ) return rc;
  145792. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  145793. ** This operation is protected by the STATIC_MASTER mutex. Note that
  145794. ** MutexAlloc() is called for a static mutex prior to initializing the
  145795. ** malloc subsystem - this implies that the allocation of a static
  145796. ** mutex must not require support from the malloc subsystem.
  145797. */
  145798. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  145799. sqlite3_mutex_enter(pMaster);
  145800. sqlite3GlobalConfig.isMutexInit = 1;
  145801. if( !sqlite3GlobalConfig.isMallocInit ){
  145802. rc = sqlite3MallocInit();
  145803. }
  145804. if( rc==SQLITE_OK ){
  145805. sqlite3GlobalConfig.isMallocInit = 1;
  145806. if( !sqlite3GlobalConfig.pInitMutex ){
  145807. sqlite3GlobalConfig.pInitMutex =
  145808. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  145809. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  145810. rc = SQLITE_NOMEM_BKPT;
  145811. }
  145812. }
  145813. }
  145814. if( rc==SQLITE_OK ){
  145815. sqlite3GlobalConfig.nRefInitMutex++;
  145816. }
  145817. sqlite3_mutex_leave(pMaster);
  145818. /* If rc is not SQLITE_OK at this point, then either the malloc
  145819. ** subsystem could not be initialized or the system failed to allocate
  145820. ** the pInitMutex mutex. Return an error in either case. */
  145821. if( rc!=SQLITE_OK ){
  145822. return rc;
  145823. }
  145824. /* Do the rest of the initialization under the recursive mutex so
  145825. ** that we will be able to handle recursive calls into
  145826. ** sqlite3_initialize(). The recursive calls normally come through
  145827. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  145828. ** recursive calls might also be possible.
  145829. **
  145830. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  145831. ** to the xInit method, so the xInit method need not be threadsafe.
  145832. **
  145833. ** The following mutex is what serializes access to the appdef pcache xInit
  145834. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  145835. ** call to sqlite3PcacheInitialize().
  145836. */
  145837. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  145838. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  145839. sqlite3GlobalConfig.inProgress = 1;
  145840. #ifdef SQLITE_ENABLE_SQLLOG
  145841. {
  145842. extern void sqlite3_init_sqllog(void);
  145843. sqlite3_init_sqllog();
  145844. }
  145845. #endif
  145846. memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
  145847. sqlite3RegisterBuiltinFunctions();
  145848. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  145849. rc = sqlite3PcacheInitialize();
  145850. }
  145851. if( rc==SQLITE_OK ){
  145852. sqlite3GlobalConfig.isPCacheInit = 1;
  145853. rc = sqlite3OsInit();
  145854. }
  145855. #ifdef SQLITE_ENABLE_DESERIALIZE
  145856. if( rc==SQLITE_OK ){
  145857. rc = sqlite3MemdbInit();
  145858. }
  145859. #endif
  145860. if( rc==SQLITE_OK ){
  145861. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  145862. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  145863. sqlite3GlobalConfig.isInit = 1;
  145864. #ifdef SQLITE_EXTRA_INIT
  145865. bRunExtraInit = 1;
  145866. #endif
  145867. }
  145868. sqlite3GlobalConfig.inProgress = 0;
  145869. }
  145870. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  145871. /* Go back under the static mutex and clean up the recursive
  145872. ** mutex to prevent a resource leak.
  145873. */
  145874. sqlite3_mutex_enter(pMaster);
  145875. sqlite3GlobalConfig.nRefInitMutex--;
  145876. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  145877. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  145878. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  145879. sqlite3GlobalConfig.pInitMutex = 0;
  145880. }
  145881. sqlite3_mutex_leave(pMaster);
  145882. /* The following is just a sanity check to make sure SQLite has
  145883. ** been compiled correctly. It is important to run this code, but
  145884. ** we don't want to run it too often and soak up CPU cycles for no
  145885. ** reason. So we run it once during initialization.
  145886. */
  145887. #ifndef NDEBUG
  145888. #ifndef SQLITE_OMIT_FLOATING_POINT
  145889. /* This section of code's only "output" is via assert() statements. */
  145890. if( rc==SQLITE_OK ){
  145891. u64 x = (((u64)1)<<63)-1;
  145892. double y;
  145893. assert(sizeof(x)==8);
  145894. assert(sizeof(x)==sizeof(y));
  145895. memcpy(&y, &x, 8);
  145896. assert( sqlite3IsNaN(y) );
  145897. }
  145898. #endif
  145899. #endif
  145900. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  145901. ** compile-time option.
  145902. */
  145903. #ifdef SQLITE_EXTRA_INIT
  145904. if( bRunExtraInit ){
  145905. int SQLITE_EXTRA_INIT(const char*);
  145906. rc = SQLITE_EXTRA_INIT(0);
  145907. }
  145908. #endif
  145909. return rc;
  145910. }
  145911. /*
  145912. ** Undo the effects of sqlite3_initialize(). Must not be called while
  145913. ** there are outstanding database connections or memory allocations or
  145914. ** while any part of SQLite is otherwise in use in any thread. This
  145915. ** routine is not threadsafe. But it is safe to invoke this routine
  145916. ** on when SQLite is already shut down. If SQLite is already shut down
  145917. ** when this routine is invoked, then this routine is a harmless no-op.
  145918. */
  145919. SQLITE_API int sqlite3_shutdown(void){
  145920. #ifdef SQLITE_OMIT_WSD
  145921. int rc = sqlite3_wsd_init(4096, 24);
  145922. if( rc!=SQLITE_OK ){
  145923. return rc;
  145924. }
  145925. #endif
  145926. if( sqlite3GlobalConfig.isInit ){
  145927. #ifdef SQLITE_EXTRA_SHUTDOWN
  145928. void SQLITE_EXTRA_SHUTDOWN(void);
  145929. SQLITE_EXTRA_SHUTDOWN();
  145930. #endif
  145931. sqlite3_os_end();
  145932. sqlite3_reset_auto_extension();
  145933. sqlite3GlobalConfig.isInit = 0;
  145934. }
  145935. if( sqlite3GlobalConfig.isPCacheInit ){
  145936. sqlite3PcacheShutdown();
  145937. sqlite3GlobalConfig.isPCacheInit = 0;
  145938. }
  145939. if( sqlite3GlobalConfig.isMallocInit ){
  145940. sqlite3MallocEnd();
  145941. sqlite3GlobalConfig.isMallocInit = 0;
  145942. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  145943. /* The heap subsystem has now been shutdown and these values are supposed
  145944. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  145945. ** which would rely on that heap subsystem; therefore, make sure these
  145946. ** values cannot refer to heap memory that was just invalidated when the
  145947. ** heap subsystem was shutdown. This is only done if the current call to
  145948. ** this function resulted in the heap subsystem actually being shutdown.
  145949. */
  145950. sqlite3_data_directory = 0;
  145951. sqlite3_temp_directory = 0;
  145952. #endif
  145953. }
  145954. if( sqlite3GlobalConfig.isMutexInit ){
  145955. sqlite3MutexEnd();
  145956. sqlite3GlobalConfig.isMutexInit = 0;
  145957. }
  145958. return SQLITE_OK;
  145959. }
  145960. /*
  145961. ** This API allows applications to modify the global configuration of
  145962. ** the SQLite library at run-time.
  145963. **
  145964. ** This routine should only be called when there are no outstanding
  145965. ** database connections or memory allocations. This routine is not
  145966. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  145967. ** behavior.
  145968. */
  145969. SQLITE_API int sqlite3_config(int op, ...){
  145970. va_list ap;
  145971. int rc = SQLITE_OK;
  145972. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  145973. ** the SQLite library is in use. */
  145974. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  145975. va_start(ap, op);
  145976. switch( op ){
  145977. /* Mutex configuration options are only available in a threadsafe
  145978. ** compile.
  145979. */
  145980. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  145981. case SQLITE_CONFIG_SINGLETHREAD: {
  145982. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  145983. ** Single-thread. */
  145984. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  145985. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  145986. break;
  145987. }
  145988. #endif
  145989. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  145990. case SQLITE_CONFIG_MULTITHREAD: {
  145991. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  145992. ** Multi-thread. */
  145993. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  145994. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  145995. break;
  145996. }
  145997. #endif
  145998. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  145999. case SQLITE_CONFIG_SERIALIZED: {
  146000. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  146001. ** Serialized. */
  146002. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  146003. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  146004. break;
  146005. }
  146006. #endif
  146007. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  146008. case SQLITE_CONFIG_MUTEX: {
  146009. /* Specify an alternative mutex implementation */
  146010. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  146011. break;
  146012. }
  146013. #endif
  146014. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  146015. case SQLITE_CONFIG_GETMUTEX: {
  146016. /* Retrieve the current mutex implementation */
  146017. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  146018. break;
  146019. }
  146020. #endif
  146021. case SQLITE_CONFIG_MALLOC: {
  146022. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  146023. ** single argument which is a pointer to an instance of the
  146024. ** sqlite3_mem_methods structure. The argument specifies alternative
  146025. ** low-level memory allocation routines to be used in place of the memory
  146026. ** allocation routines built into SQLite. */
  146027. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  146028. break;
  146029. }
  146030. case SQLITE_CONFIG_GETMALLOC: {
  146031. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  146032. ** single argument which is a pointer to an instance of the
  146033. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  146034. ** filled with the currently defined memory allocation routines. */
  146035. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  146036. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  146037. break;
  146038. }
  146039. case SQLITE_CONFIG_MEMSTATUS: {
  146040. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  146041. ** single argument of type int, interpreted as a boolean, which enables
  146042. ** or disables the collection of memory allocation statistics. */
  146043. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  146044. break;
  146045. }
  146046. case SQLITE_CONFIG_SMALL_MALLOC: {
  146047. sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
  146048. break;
  146049. }
  146050. case SQLITE_CONFIG_PAGECACHE: {
  146051. /* EVIDENCE-OF: R-18761-36601 There are three arguments to
  146052. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
  146053. ** the size of each page cache line (sz), and the number of cache lines
  146054. ** (N). */
  146055. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  146056. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  146057. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  146058. break;
  146059. }
  146060. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  146061. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  146062. ** a single parameter which is a pointer to an integer and writes into
  146063. ** that integer the number of extra bytes per page required for each page
  146064. ** in SQLITE_CONFIG_PAGECACHE. */
  146065. *va_arg(ap, int*) =
  146066. sqlite3HeaderSizeBtree() +
  146067. sqlite3HeaderSizePcache() +
  146068. sqlite3HeaderSizePcache1();
  146069. break;
  146070. }
  146071. case SQLITE_CONFIG_PCACHE: {
  146072. /* no-op */
  146073. break;
  146074. }
  146075. case SQLITE_CONFIG_GETPCACHE: {
  146076. /* now an error */
  146077. rc = SQLITE_ERROR;
  146078. break;
  146079. }
  146080. case SQLITE_CONFIG_PCACHE2: {
  146081. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  146082. ** single argument which is a pointer to an sqlite3_pcache_methods2
  146083. ** object. This object specifies the interface to a custom page cache
  146084. ** implementation. */
  146085. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  146086. break;
  146087. }
  146088. case SQLITE_CONFIG_GETPCACHE2: {
  146089. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  146090. ** single argument which is a pointer to an sqlite3_pcache_methods2
  146091. ** object. SQLite copies of the current page cache implementation into
  146092. ** that object. */
  146093. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  146094. sqlite3PCacheSetDefault();
  146095. }
  146096. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  146097. break;
  146098. }
  146099. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  146100. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  146101. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  146102. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  146103. case SQLITE_CONFIG_HEAP: {
  146104. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  146105. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  146106. ** number of bytes in the memory buffer, and the minimum allocation size.
  146107. */
  146108. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  146109. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  146110. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  146111. if( sqlite3GlobalConfig.mnReq<1 ){
  146112. sqlite3GlobalConfig.mnReq = 1;
  146113. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  146114. /* cap min request size at 2^12 */
  146115. sqlite3GlobalConfig.mnReq = (1<<12);
  146116. }
  146117. if( sqlite3GlobalConfig.pHeap==0 ){
  146118. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  146119. ** is NULL, then SQLite reverts to using its default memory allocator
  146120. ** (the system malloc() implementation), undoing any prior invocation of
  146121. ** SQLITE_CONFIG_MALLOC.
  146122. **
  146123. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  146124. ** revert to its default implementation when sqlite3_initialize() is run
  146125. */
  146126. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  146127. }else{
  146128. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  146129. ** alternative memory allocator is engaged to handle all of SQLites
  146130. ** memory allocation needs. */
  146131. #ifdef SQLITE_ENABLE_MEMSYS3
  146132. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  146133. #endif
  146134. #ifdef SQLITE_ENABLE_MEMSYS5
  146135. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  146136. #endif
  146137. }
  146138. break;
  146139. }
  146140. #endif
  146141. case SQLITE_CONFIG_LOOKASIDE: {
  146142. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  146143. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  146144. break;
  146145. }
  146146. /* Record a pointer to the logger function and its first argument.
  146147. ** The default is NULL. Logging is disabled if the function pointer is
  146148. ** NULL.
  146149. */
  146150. case SQLITE_CONFIG_LOG: {
  146151. /* MSVC is picky about pulling func ptrs from va lists.
  146152. ** http://support.microsoft.com/kb/47961
  146153. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  146154. */
  146155. typedef void(*LOGFUNC_t)(void*,int,const char*);
  146156. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  146157. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  146158. break;
  146159. }
  146160. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  146161. ** can be changed at start-time using the
  146162. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  146163. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  146164. */
  146165. case SQLITE_CONFIG_URI: {
  146166. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  146167. ** argument of type int. If non-zero, then URI handling is globally
  146168. ** enabled. If the parameter is zero, then URI handling is globally
  146169. ** disabled. */
  146170. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  146171. break;
  146172. }
  146173. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  146174. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  146175. ** option takes a single integer argument which is interpreted as a
  146176. ** boolean in order to enable or disable the use of covering indices for
  146177. ** full table scans in the query optimizer. */
  146178. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  146179. break;
  146180. }
  146181. #ifdef SQLITE_ENABLE_SQLLOG
  146182. case SQLITE_CONFIG_SQLLOG: {
  146183. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  146184. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  146185. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  146186. break;
  146187. }
  146188. #endif
  146189. case SQLITE_CONFIG_MMAP_SIZE: {
  146190. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  146191. ** integer (sqlite3_int64) values that are the default mmap size limit
  146192. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  146193. ** mmap size limit. */
  146194. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  146195. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  146196. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  146197. ** negative, then that argument is changed to its compile-time default.
  146198. **
  146199. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  146200. ** silently truncated if necessary so that it does not exceed the
  146201. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  146202. ** compile-time option.
  146203. */
  146204. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  146205. mxMmap = SQLITE_MAX_MMAP_SIZE;
  146206. }
  146207. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  146208. if( szMmap>mxMmap) szMmap = mxMmap;
  146209. sqlite3GlobalConfig.mxMmap = mxMmap;
  146210. sqlite3GlobalConfig.szMmap = szMmap;
  146211. break;
  146212. }
  146213. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  146214. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  146215. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  146216. ** unsigned integer value that specifies the maximum size of the created
  146217. ** heap. */
  146218. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  146219. break;
  146220. }
  146221. #endif
  146222. case SQLITE_CONFIG_PMASZ: {
  146223. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  146224. break;
  146225. }
  146226. case SQLITE_CONFIG_STMTJRNL_SPILL: {
  146227. sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
  146228. break;
  146229. }
  146230. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  146231. case SQLITE_CONFIG_SORTERREF_SIZE: {
  146232. int iVal = va_arg(ap, int);
  146233. if( iVal<0 ){
  146234. iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
  146235. }
  146236. sqlite3GlobalConfig.szSorterRef = (u32)iVal;
  146237. break;
  146238. }
  146239. #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
  146240. #ifdef SQLITE_ENABLE_DESERIALIZE
  146241. case SQLITE_CONFIG_MEMDB_MAXSIZE: {
  146242. sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
  146243. break;
  146244. }
  146245. #endif /* SQLITE_ENABLE_DESERIALIZE */
  146246. default: {
  146247. rc = SQLITE_ERROR;
  146248. break;
  146249. }
  146250. }
  146251. va_end(ap);
  146252. return rc;
  146253. }
  146254. /*
  146255. ** Set up the lookaside buffers for a database connection.
  146256. ** Return SQLITE_OK on success.
  146257. ** If lookaside is already active, return SQLITE_BUSY.
  146258. **
  146259. ** The sz parameter is the number of bytes in each lookaside slot.
  146260. ** The cnt parameter is the number of slots. If pStart is NULL the
  146261. ** space for the lookaside memory is obtained from sqlite3_malloc().
  146262. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  146263. ** the lookaside memory.
  146264. */
  146265. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  146266. #ifndef SQLITE_OMIT_LOOKASIDE
  146267. void *pStart;
  146268. if( sqlite3LookasideUsed(db,0)>0 ){
  146269. return SQLITE_BUSY;
  146270. }
  146271. /* Free any existing lookaside buffer for this handle before
  146272. ** allocating a new one so we don't have to have space for
  146273. ** both at the same time.
  146274. */
  146275. if( db->lookaside.bMalloced ){
  146276. sqlite3_free(db->lookaside.pStart);
  146277. }
  146278. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  146279. ** than a pointer to be useful.
  146280. */
  146281. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  146282. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  146283. if( cnt<0 ) cnt = 0;
  146284. if( sz==0 || cnt==0 ){
  146285. sz = 0;
  146286. pStart = 0;
  146287. }else if( pBuf==0 ){
  146288. sqlite3BeginBenignMalloc();
  146289. pStart = sqlite3Malloc( sz*(sqlite3_int64)cnt ); /* IMP: R-61949-35727 */
  146290. sqlite3EndBenignMalloc();
  146291. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  146292. }else{
  146293. pStart = pBuf;
  146294. }
  146295. db->lookaside.pStart = pStart;
  146296. db->lookaside.pInit = 0;
  146297. db->lookaside.pFree = 0;
  146298. db->lookaside.sz = (u16)sz;
  146299. if( pStart ){
  146300. int i;
  146301. LookasideSlot *p;
  146302. assert( sz > (int)sizeof(LookasideSlot*) );
  146303. db->lookaside.nSlot = cnt;
  146304. p = (LookasideSlot*)pStart;
  146305. for(i=cnt-1; i>=0; i--){
  146306. p->pNext = db->lookaside.pInit;
  146307. db->lookaside.pInit = p;
  146308. p = (LookasideSlot*)&((u8*)p)[sz];
  146309. }
  146310. db->lookaside.pEnd = p;
  146311. db->lookaside.bDisable = 0;
  146312. db->lookaside.bMalloced = pBuf==0 ?1:0;
  146313. }else{
  146314. db->lookaside.pStart = db;
  146315. db->lookaside.pEnd = db;
  146316. db->lookaside.bDisable = 1;
  146317. db->lookaside.bMalloced = 0;
  146318. db->lookaside.nSlot = 0;
  146319. }
  146320. #endif /* SQLITE_OMIT_LOOKASIDE */
  146321. return SQLITE_OK;
  146322. }
  146323. /*
  146324. ** Return the mutex associated with a database connection.
  146325. */
  146326. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  146327. #ifdef SQLITE_ENABLE_API_ARMOR
  146328. if( !sqlite3SafetyCheckOk(db) ){
  146329. (void)SQLITE_MISUSE_BKPT;
  146330. return 0;
  146331. }
  146332. #endif
  146333. return db->mutex;
  146334. }
  146335. /*
  146336. ** Free up as much memory as we can from the given database
  146337. ** connection.
  146338. */
  146339. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  146340. int i;
  146341. #ifdef SQLITE_ENABLE_API_ARMOR
  146342. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  146343. #endif
  146344. sqlite3_mutex_enter(db->mutex);
  146345. sqlite3BtreeEnterAll(db);
  146346. for(i=0; i<db->nDb; i++){
  146347. Btree *pBt = db->aDb[i].pBt;
  146348. if( pBt ){
  146349. Pager *pPager = sqlite3BtreePager(pBt);
  146350. sqlite3PagerShrink(pPager);
  146351. }
  146352. }
  146353. sqlite3BtreeLeaveAll(db);
  146354. sqlite3_mutex_leave(db->mutex);
  146355. return SQLITE_OK;
  146356. }
  146357. /*
  146358. ** Flush any dirty pages in the pager-cache for any attached database
  146359. ** to disk.
  146360. */
  146361. SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
  146362. int i;
  146363. int rc = SQLITE_OK;
  146364. int bSeenBusy = 0;
  146365. #ifdef SQLITE_ENABLE_API_ARMOR
  146366. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  146367. #endif
  146368. sqlite3_mutex_enter(db->mutex);
  146369. sqlite3BtreeEnterAll(db);
  146370. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  146371. Btree *pBt = db->aDb[i].pBt;
  146372. if( pBt && sqlite3BtreeIsInTrans(pBt) ){
  146373. Pager *pPager = sqlite3BtreePager(pBt);
  146374. rc = sqlite3PagerFlush(pPager);
  146375. if( rc==SQLITE_BUSY ){
  146376. bSeenBusy = 1;
  146377. rc = SQLITE_OK;
  146378. }
  146379. }
  146380. }
  146381. sqlite3BtreeLeaveAll(db);
  146382. sqlite3_mutex_leave(db->mutex);
  146383. return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
  146384. }
  146385. /*
  146386. ** Configuration settings for an individual database connection
  146387. */
  146388. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  146389. va_list ap;
  146390. int rc;
  146391. va_start(ap, op);
  146392. switch( op ){
  146393. case SQLITE_DBCONFIG_MAINDBNAME: {
  146394. /* IMP: R-06824-28531 */
  146395. /* IMP: R-36257-52125 */
  146396. db->aDb[0].zDbSName = va_arg(ap,char*);
  146397. rc = SQLITE_OK;
  146398. break;
  146399. }
  146400. case SQLITE_DBCONFIG_LOOKASIDE: {
  146401. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  146402. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  146403. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  146404. rc = setupLookaside(db, pBuf, sz, cnt);
  146405. break;
  146406. }
  146407. default: {
  146408. static const struct {
  146409. int op; /* The opcode */
  146410. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  146411. } aFlagOp[] = {
  146412. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  146413. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  146414. { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
  146415. { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
  146416. { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
  146417. { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
  146418. { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
  146419. { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase },
  146420. { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive },
  146421. { SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_WriteSchema|
  146422. SQLITE_NoSchemaError },
  146423. };
  146424. unsigned int i;
  146425. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  146426. for(i=0; i<ArraySize(aFlagOp); i++){
  146427. if( aFlagOp[i].op==op ){
  146428. int onoff = va_arg(ap, int);
  146429. int *pRes = va_arg(ap, int*);
  146430. u64 oldFlags = db->flags;
  146431. if( onoff>0 ){
  146432. db->flags |= aFlagOp[i].mask;
  146433. }else if( onoff==0 ){
  146434. db->flags &= ~(u64)aFlagOp[i].mask;
  146435. }
  146436. if( oldFlags!=db->flags ){
  146437. sqlite3ExpirePreparedStatements(db, 0);
  146438. }
  146439. if( pRes ){
  146440. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  146441. }
  146442. rc = SQLITE_OK;
  146443. break;
  146444. }
  146445. }
  146446. break;
  146447. }
  146448. }
  146449. va_end(ap);
  146450. return rc;
  146451. }
  146452. /*
  146453. ** Return true if the buffer z[0..n-1] contains all spaces.
  146454. */
  146455. static int allSpaces(const char *z, int n){
  146456. while( n>0 && z[n-1]==' ' ){ n--; }
  146457. return n==0;
  146458. }
  146459. /*
  146460. ** This is the default collating function named "BINARY" which is always
  146461. ** available.
  146462. **
  146463. ** If the padFlag argument is not NULL then space padding at the end
  146464. ** of strings is ignored. This implements the RTRIM collation.
  146465. */
  146466. static int binCollFunc(
  146467. void *padFlag,
  146468. int nKey1, const void *pKey1,
  146469. int nKey2, const void *pKey2
  146470. ){
  146471. int rc, n;
  146472. n = nKey1<nKey2 ? nKey1 : nKey2;
  146473. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  146474. ** strings byte by byte using the memcmp() function from the standard C
  146475. ** library. */
  146476. assert( pKey1 && pKey2 );
  146477. rc = memcmp(pKey1, pKey2, n);
  146478. if( rc==0 ){
  146479. if( padFlag
  146480. && allSpaces(((char*)pKey1)+n, nKey1-n)
  146481. && allSpaces(((char*)pKey2)+n, nKey2-n)
  146482. ){
  146483. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  146484. ** spaces at the end of either string do not change the result. In other
  146485. ** words, strings will compare equal to one another as long as they
  146486. ** differ only in the number of spaces at the end.
  146487. */
  146488. }else{
  146489. rc = nKey1 - nKey2;
  146490. }
  146491. }
  146492. return rc;
  146493. }
  146494. /*
  146495. ** Return true if CollSeq is the default built-in BINARY.
  146496. */
  146497. SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq *p){
  146498. assert( p==0 || p->xCmp!=binCollFunc || p->pUser!=0
  146499. || strcmp(p->zName,"BINARY")==0 );
  146500. return p==0 || (p->xCmp==binCollFunc && p->pUser==0);
  146501. }
  146502. /*
  146503. ** Another built-in collating sequence: NOCASE.
  146504. **
  146505. ** This collating sequence is intended to be used for "case independent
  146506. ** comparison". SQLite's knowledge of upper and lower case equivalents
  146507. ** extends only to the 26 characters used in the English language.
  146508. **
  146509. ** At the moment there is only a UTF-8 implementation.
  146510. */
  146511. static int nocaseCollatingFunc(
  146512. void *NotUsed,
  146513. int nKey1, const void *pKey1,
  146514. int nKey2, const void *pKey2
  146515. ){
  146516. int r = sqlite3StrNICmp(
  146517. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  146518. UNUSED_PARAMETER(NotUsed);
  146519. if( 0==r ){
  146520. r = nKey1-nKey2;
  146521. }
  146522. return r;
  146523. }
  146524. /*
  146525. ** Return the ROWID of the most recent insert
  146526. */
  146527. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  146528. #ifdef SQLITE_ENABLE_API_ARMOR
  146529. if( !sqlite3SafetyCheckOk(db) ){
  146530. (void)SQLITE_MISUSE_BKPT;
  146531. return 0;
  146532. }
  146533. #endif
  146534. return db->lastRowid;
  146535. }
  146536. /*
  146537. ** Set the value returned by the sqlite3_last_insert_rowid() API function.
  146538. */
  146539. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
  146540. #ifdef SQLITE_ENABLE_API_ARMOR
  146541. if( !sqlite3SafetyCheckOk(db) ){
  146542. (void)SQLITE_MISUSE_BKPT;
  146543. return;
  146544. }
  146545. #endif
  146546. sqlite3_mutex_enter(db->mutex);
  146547. db->lastRowid = iRowid;
  146548. sqlite3_mutex_leave(db->mutex);
  146549. }
  146550. /*
  146551. ** Return the number of changes in the most recent call to sqlite3_exec().
  146552. */
  146553. SQLITE_API int sqlite3_changes(sqlite3 *db){
  146554. #ifdef SQLITE_ENABLE_API_ARMOR
  146555. if( !sqlite3SafetyCheckOk(db) ){
  146556. (void)SQLITE_MISUSE_BKPT;
  146557. return 0;
  146558. }
  146559. #endif
  146560. return db->nChange;
  146561. }
  146562. /*
  146563. ** Return the number of changes since the database handle was opened.
  146564. */
  146565. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  146566. #ifdef SQLITE_ENABLE_API_ARMOR
  146567. if( !sqlite3SafetyCheckOk(db) ){
  146568. (void)SQLITE_MISUSE_BKPT;
  146569. return 0;
  146570. }
  146571. #endif
  146572. return db->nTotalChange;
  146573. }
  146574. /*
  146575. ** Close all open savepoints. This function only manipulates fields of the
  146576. ** database handle object, it does not close any savepoints that may be open
  146577. ** at the b-tree/pager level.
  146578. */
  146579. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  146580. while( db->pSavepoint ){
  146581. Savepoint *pTmp = db->pSavepoint;
  146582. db->pSavepoint = pTmp->pNext;
  146583. sqlite3DbFree(db, pTmp);
  146584. }
  146585. db->nSavepoint = 0;
  146586. db->nStatement = 0;
  146587. db->isTransactionSavepoint = 0;
  146588. }
  146589. /*
  146590. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  146591. ** if this is not the last copy of the function, do not invoke it. Multiple
  146592. ** copies of a single function are created when create_function() is called
  146593. ** with SQLITE_ANY as the encoding.
  146594. */
  146595. static void functionDestroy(sqlite3 *db, FuncDef *p){
  146596. FuncDestructor *pDestructor = p->u.pDestructor;
  146597. if( pDestructor ){
  146598. pDestructor->nRef--;
  146599. if( pDestructor->nRef==0 ){
  146600. pDestructor->xDestroy(pDestructor->pUserData);
  146601. sqlite3DbFree(db, pDestructor);
  146602. }
  146603. }
  146604. }
  146605. /*
  146606. ** Disconnect all sqlite3_vtab objects that belong to database connection
  146607. ** db. This is called when db is being closed.
  146608. */
  146609. static void disconnectAllVtab(sqlite3 *db){
  146610. #ifndef SQLITE_OMIT_VIRTUALTABLE
  146611. int i;
  146612. HashElem *p;
  146613. sqlite3BtreeEnterAll(db);
  146614. for(i=0; i<db->nDb; i++){
  146615. Schema *pSchema = db->aDb[i].pSchema;
  146616. if( pSchema ){
  146617. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  146618. Table *pTab = (Table *)sqliteHashData(p);
  146619. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  146620. }
  146621. }
  146622. }
  146623. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  146624. Module *pMod = (Module *)sqliteHashData(p);
  146625. if( pMod->pEpoTab ){
  146626. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  146627. }
  146628. }
  146629. sqlite3VtabUnlockList(db);
  146630. sqlite3BtreeLeaveAll(db);
  146631. #else
  146632. UNUSED_PARAMETER(db);
  146633. #endif
  146634. }
  146635. /*
  146636. ** Return TRUE if database connection db has unfinalized prepared
  146637. ** statements or unfinished sqlite3_backup objects.
  146638. */
  146639. static int connectionIsBusy(sqlite3 *db){
  146640. int j;
  146641. assert( sqlite3_mutex_held(db->mutex) );
  146642. if( db->pVdbe ) return 1;
  146643. for(j=0; j<db->nDb; j++){
  146644. Btree *pBt = db->aDb[j].pBt;
  146645. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  146646. }
  146647. return 0;
  146648. }
  146649. /*
  146650. ** Close an existing SQLite database
  146651. */
  146652. static int sqlite3Close(sqlite3 *db, int forceZombie){
  146653. if( !db ){
  146654. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  146655. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  146656. return SQLITE_OK;
  146657. }
  146658. if( !sqlite3SafetyCheckSickOrOk(db) ){
  146659. return SQLITE_MISUSE_BKPT;
  146660. }
  146661. sqlite3_mutex_enter(db->mutex);
  146662. if( db->mTrace & SQLITE_TRACE_CLOSE ){
  146663. db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
  146664. }
  146665. /* Force xDisconnect calls on all virtual tables */
  146666. disconnectAllVtab(db);
  146667. /* If a transaction is open, the disconnectAllVtab() call above
  146668. ** will not have called the xDisconnect() method on any virtual
  146669. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  146670. ** call will do so. We need to do this before the check for active
  146671. ** SQL statements below, as the v-table implementation may be storing
  146672. ** some prepared statements internally.
  146673. */
  146674. sqlite3VtabRollback(db);
  146675. /* Legacy behavior (sqlite3_close() behavior) is to return
  146676. ** SQLITE_BUSY if the connection can not be closed immediately.
  146677. */
  146678. if( !forceZombie && connectionIsBusy(db) ){
  146679. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  146680. "statements or unfinished backups");
  146681. sqlite3_mutex_leave(db->mutex);
  146682. return SQLITE_BUSY;
  146683. }
  146684. #ifdef SQLITE_ENABLE_SQLLOG
  146685. if( sqlite3GlobalConfig.xSqllog ){
  146686. /* Closing the handle. Fourth parameter is passed the value 2. */
  146687. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  146688. }
  146689. #endif
  146690. /* Convert the connection into a zombie and then close it.
  146691. */
  146692. db->magic = SQLITE_MAGIC_ZOMBIE;
  146693. sqlite3LeaveMutexAndCloseZombie(db);
  146694. return SQLITE_OK;
  146695. }
  146696. /*
  146697. ** Two variations on the public interface for closing a database
  146698. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  146699. ** leaves the connection option if there are unfinalized prepared
  146700. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  146701. ** version forces the connection to become a zombie if there are
  146702. ** unclosed resources, and arranges for deallocation when the last
  146703. ** prepare statement or sqlite3_backup closes.
  146704. */
  146705. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  146706. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  146707. /*
  146708. ** Close the mutex on database connection db.
  146709. **
  146710. ** Furthermore, if database connection db is a zombie (meaning that there
  146711. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  146712. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  146713. ** finished, then free all resources.
  146714. */
  146715. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  146716. HashElem *i; /* Hash table iterator */
  146717. int j;
  146718. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  146719. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  146720. ** then just leave the mutex and return.
  146721. */
  146722. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  146723. sqlite3_mutex_leave(db->mutex);
  146724. return;
  146725. }
  146726. /* If we reach this point, it means that the database connection has
  146727. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  146728. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  146729. ** go ahead and free all resources.
  146730. */
  146731. /* If a transaction is open, roll it back. This also ensures that if
  146732. ** any database schemas have been modified by an uncommitted transaction
  146733. ** they are reset. And that the required b-tree mutex is held to make
  146734. ** the pager rollback and schema reset an atomic operation. */
  146735. sqlite3RollbackAll(db, SQLITE_OK);
  146736. /* Free any outstanding Savepoint structures. */
  146737. sqlite3CloseSavepoints(db);
  146738. /* Close all database connections */
  146739. for(j=0; j<db->nDb; j++){
  146740. struct Db *pDb = &db->aDb[j];
  146741. if( pDb->pBt ){
  146742. sqlite3BtreeClose(pDb->pBt);
  146743. pDb->pBt = 0;
  146744. if( j!=1 ){
  146745. pDb->pSchema = 0;
  146746. }
  146747. }
  146748. }
  146749. /* Clear the TEMP schema separately and last */
  146750. if( db->aDb[1].pSchema ){
  146751. sqlite3SchemaClear(db->aDb[1].pSchema);
  146752. }
  146753. sqlite3VtabUnlockList(db);
  146754. /* Free up the array of auxiliary databases */
  146755. sqlite3CollapseDatabaseArray(db);
  146756. assert( db->nDb<=2 );
  146757. assert( db->aDb==db->aDbStatic );
  146758. /* Tell the code in notify.c that the connection no longer holds any
  146759. ** locks and does not require any further unlock-notify callbacks.
  146760. */
  146761. sqlite3ConnectionClosed(db);
  146762. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  146763. FuncDef *pNext, *p;
  146764. p = sqliteHashData(i);
  146765. do{
  146766. functionDestroy(db, p);
  146767. pNext = p->pNext;
  146768. sqlite3DbFree(db, p);
  146769. p = pNext;
  146770. }while( p );
  146771. }
  146772. sqlite3HashClear(&db->aFunc);
  146773. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  146774. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  146775. /* Invoke any destructors registered for collation sequence user data. */
  146776. for(j=0; j<3; j++){
  146777. if( pColl[j].xDel ){
  146778. pColl[j].xDel(pColl[j].pUser);
  146779. }
  146780. }
  146781. sqlite3DbFree(db, pColl);
  146782. }
  146783. sqlite3HashClear(&db->aCollSeq);
  146784. #ifndef SQLITE_OMIT_VIRTUALTABLE
  146785. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  146786. Module *pMod = (Module *)sqliteHashData(i);
  146787. if( pMod->xDestroy ){
  146788. pMod->xDestroy(pMod->pAux);
  146789. }
  146790. sqlite3VtabEponymousTableClear(db, pMod);
  146791. sqlite3DbFree(db, pMod);
  146792. }
  146793. sqlite3HashClear(&db->aModule);
  146794. #endif
  146795. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  146796. sqlite3ValueFree(db->pErr);
  146797. sqlite3CloseExtensions(db);
  146798. #if SQLITE_USER_AUTHENTICATION
  146799. sqlite3_free(db->auth.zAuthUser);
  146800. sqlite3_free(db->auth.zAuthPW);
  146801. #endif
  146802. db->magic = SQLITE_MAGIC_ERROR;
  146803. /* The temp-database schema is allocated differently from the other schema
  146804. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  146805. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  146806. ** the same sqliteMalloc() as the one that allocates the database
  146807. ** structure?
  146808. */
  146809. sqlite3DbFree(db, db->aDb[1].pSchema);
  146810. sqlite3_mutex_leave(db->mutex);
  146811. db->magic = SQLITE_MAGIC_CLOSED;
  146812. sqlite3_mutex_free(db->mutex);
  146813. assert( sqlite3LookasideUsed(db,0)==0 );
  146814. if( db->lookaside.bMalloced ){
  146815. sqlite3_free(db->lookaside.pStart);
  146816. }
  146817. sqlite3_free(db);
  146818. }
  146819. /*
  146820. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  146821. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  146822. ** breaker") and made to return tripCode if there are any further
  146823. ** attempts to use that cursor. Read cursors remain open and valid
  146824. ** but are "saved" in case the table pages are moved around.
  146825. */
  146826. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  146827. int i;
  146828. int inTrans = 0;
  146829. int schemaChange;
  146830. assert( sqlite3_mutex_held(db->mutex) );
  146831. sqlite3BeginBenignMalloc();
  146832. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  146833. ** This is important in case the transaction being rolled back has
  146834. ** modified the database schema. If the b-tree mutexes are not taken
  146835. ** here, then another shared-cache connection might sneak in between
  146836. ** the database rollback and schema reset, which can cause false
  146837. ** corruption reports in some cases. */
  146838. sqlite3BtreeEnterAll(db);
  146839. schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
  146840. for(i=0; i<db->nDb; i++){
  146841. Btree *p = db->aDb[i].pBt;
  146842. if( p ){
  146843. if( sqlite3BtreeIsInTrans(p) ){
  146844. inTrans = 1;
  146845. }
  146846. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  146847. }
  146848. }
  146849. sqlite3VtabRollback(db);
  146850. sqlite3EndBenignMalloc();
  146851. if( schemaChange ){
  146852. sqlite3ExpirePreparedStatements(db, 0);
  146853. sqlite3ResetAllSchemasOfConnection(db);
  146854. }
  146855. sqlite3BtreeLeaveAll(db);
  146856. /* Any deferred constraint violations have now been resolved. */
  146857. db->nDeferredCons = 0;
  146858. db->nDeferredImmCons = 0;
  146859. db->flags &= ~(u64)SQLITE_DeferFKs;
  146860. /* If one has been configured, invoke the rollback-hook callback */
  146861. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  146862. db->xRollbackCallback(db->pRollbackArg);
  146863. }
  146864. }
  146865. /*
  146866. ** Return a static string containing the name corresponding to the error code
  146867. ** specified in the argument.
  146868. */
  146869. #if defined(SQLITE_NEED_ERR_NAME)
  146870. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  146871. const char *zName = 0;
  146872. int i, origRc = rc;
  146873. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  146874. switch( rc ){
  146875. case SQLITE_OK: zName = "SQLITE_OK"; break;
  146876. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  146877. case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break;
  146878. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  146879. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  146880. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  146881. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  146882. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  146883. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  146884. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  146885. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  146886. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  146887. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  146888. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  146889. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  146890. case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
  146891. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  146892. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  146893. case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
  146894. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  146895. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  146896. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  146897. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  146898. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  146899. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  146900. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  146901. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  146902. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  146903. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  146904. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  146905. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  146906. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  146907. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  146908. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  146909. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  146910. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  146911. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  146912. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  146913. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  146914. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  146915. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  146916. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  146917. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  146918. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  146919. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  146920. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  146921. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  146922. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  146923. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  146924. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  146925. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  146926. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  146927. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  146928. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  146929. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  146930. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  146931. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  146932. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  146933. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  146934. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  146935. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  146936. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  146937. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  146938. case SQLITE_CONSTRAINT_FOREIGNKEY:
  146939. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  146940. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  146941. case SQLITE_CONSTRAINT_PRIMARYKEY:
  146942. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  146943. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  146944. case SQLITE_CONSTRAINT_COMMITHOOK:
  146945. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  146946. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  146947. case SQLITE_CONSTRAINT_FUNCTION:
  146948. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  146949. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  146950. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  146951. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  146952. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  146953. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  146954. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  146955. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  146956. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  146957. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  146958. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  146959. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  146960. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  146961. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  146962. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  146963. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  146964. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  146965. }
  146966. }
  146967. if( zName==0 ){
  146968. static char zBuf[50];
  146969. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  146970. zName = zBuf;
  146971. }
  146972. return zName;
  146973. }
  146974. #endif
  146975. /*
  146976. ** Return a static string that describes the kind of error specified in the
  146977. ** argument.
  146978. */
  146979. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  146980. static const char* const aMsg[] = {
  146981. /* SQLITE_OK */ "not an error",
  146982. /* SQLITE_ERROR */ "SQL logic error",
  146983. /* SQLITE_INTERNAL */ 0,
  146984. /* SQLITE_PERM */ "access permission denied",
  146985. /* SQLITE_ABORT */ "query aborted",
  146986. /* SQLITE_BUSY */ "database is locked",
  146987. /* SQLITE_LOCKED */ "database table is locked",
  146988. /* SQLITE_NOMEM */ "out of memory",
  146989. /* SQLITE_READONLY */ "attempt to write a readonly database",
  146990. /* SQLITE_INTERRUPT */ "interrupted",
  146991. /* SQLITE_IOERR */ "disk I/O error",
  146992. /* SQLITE_CORRUPT */ "database disk image is malformed",
  146993. /* SQLITE_NOTFOUND */ "unknown operation",
  146994. /* SQLITE_FULL */ "database or disk is full",
  146995. /* SQLITE_CANTOPEN */ "unable to open database file",
  146996. /* SQLITE_PROTOCOL */ "locking protocol",
  146997. /* SQLITE_EMPTY */ 0,
  146998. /* SQLITE_SCHEMA */ "database schema has changed",
  146999. /* SQLITE_TOOBIG */ "string or blob too big",
  147000. /* SQLITE_CONSTRAINT */ "constraint failed",
  147001. /* SQLITE_MISMATCH */ "datatype mismatch",
  147002. /* SQLITE_MISUSE */ "bad parameter or other API misuse",
  147003. #ifdef SQLITE_DISABLE_LFS
  147004. /* SQLITE_NOLFS */ "large file support is disabled",
  147005. #else
  147006. /* SQLITE_NOLFS */ 0,
  147007. #endif
  147008. /* SQLITE_AUTH */ "authorization denied",
  147009. /* SQLITE_FORMAT */ 0,
  147010. /* SQLITE_RANGE */ "column index out of range",
  147011. /* SQLITE_NOTADB */ "file is not a database",
  147012. /* SQLITE_NOTICE */ "notification message",
  147013. /* SQLITE_WARNING */ "warning message",
  147014. };
  147015. const char *zErr = "unknown error";
  147016. switch( rc ){
  147017. case SQLITE_ABORT_ROLLBACK: {
  147018. zErr = "abort due to ROLLBACK";
  147019. break;
  147020. }
  147021. case SQLITE_ROW: {
  147022. zErr = "another row available";
  147023. break;
  147024. }
  147025. case SQLITE_DONE: {
  147026. zErr = "no more rows available";
  147027. break;
  147028. }
  147029. default: {
  147030. rc &= 0xff;
  147031. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  147032. zErr = aMsg[rc];
  147033. }
  147034. break;
  147035. }
  147036. }
  147037. return zErr;
  147038. }
  147039. /*
  147040. ** This routine implements a busy callback that sleeps and tries
  147041. ** again until a timeout value is reached. The timeout value is
  147042. ** an integer number of milliseconds passed in as the first
  147043. ** argument.
  147044. **
  147045. ** Return non-zero to retry the lock. Return zero to stop trying
  147046. ** and cause SQLite to return SQLITE_BUSY.
  147047. */
  147048. static int sqliteDefaultBusyCallback(
  147049. void *ptr, /* Database connection */
  147050. int count, /* Number of times table has been busy */
  147051. sqlite3_file *pFile /* The file on which the lock occurred */
  147052. ){
  147053. #if SQLITE_OS_WIN || HAVE_USLEEP
  147054. /* This case is for systems that have support for sleeping for fractions of
  147055. ** a second. Examples: All windows systems, unix systems with usleep() */
  147056. static const u8 delays[] =
  147057. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  147058. static const u8 totals[] =
  147059. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  147060. # define NDELAY ArraySize(delays)
  147061. sqlite3 *db = (sqlite3 *)ptr;
  147062. int tmout = db->busyTimeout;
  147063. int delay, prior;
  147064. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  147065. if( sqlite3OsFileControl(pFile,SQLITE_FCNTL_LOCK_TIMEOUT,&tmout)==SQLITE_OK ){
  147066. if( count ){
  147067. tmout = 0;
  147068. sqlite3OsFileControl(pFile, SQLITE_FCNTL_LOCK_TIMEOUT, &tmout);
  147069. return 0;
  147070. }else{
  147071. return 1;
  147072. }
  147073. }
  147074. #else
  147075. UNUSED_PARAMETER(pFile);
  147076. #endif
  147077. assert( count>=0 );
  147078. if( count < NDELAY ){
  147079. delay = delays[count];
  147080. prior = totals[count];
  147081. }else{
  147082. delay = delays[NDELAY-1];
  147083. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  147084. }
  147085. if( prior + delay > tmout ){
  147086. delay = tmout - prior;
  147087. if( delay<=0 ) return 0;
  147088. }
  147089. sqlite3OsSleep(db->pVfs, delay*1000);
  147090. return 1;
  147091. #else
  147092. /* This case for unix systems that lack usleep() support. Sleeping
  147093. ** must be done in increments of whole seconds */
  147094. sqlite3 *db = (sqlite3 *)ptr;
  147095. int tmout = ((sqlite3 *)ptr)->busyTimeout;
  147096. UNUSED_PARAMETER(pFile);
  147097. if( (count+1)*1000 > tmout ){
  147098. return 0;
  147099. }
  147100. sqlite3OsSleep(db->pVfs, 1000000);
  147101. return 1;
  147102. #endif
  147103. }
  147104. /*
  147105. ** Invoke the given busy handler.
  147106. **
  147107. ** This routine is called when an operation failed to acquire a
  147108. ** lock on VFS file pFile.
  147109. **
  147110. ** If this routine returns non-zero, the lock is retried. If it
  147111. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  147112. */
  147113. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p, sqlite3_file *pFile){
  147114. int rc;
  147115. if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
  147116. if( p->bExtraFileArg ){
  147117. /* Add an extra parameter with the pFile pointer to the end of the
  147118. ** callback argument list */
  147119. int (*xTra)(void*,int,sqlite3_file*);
  147120. xTra = (int(*)(void*,int,sqlite3_file*))p->xBusyHandler;
  147121. rc = xTra(p->pBusyArg, p->nBusy, pFile);
  147122. }else{
  147123. /* Legacy style busy handler callback */
  147124. rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
  147125. }
  147126. if( rc==0 ){
  147127. p->nBusy = -1;
  147128. }else{
  147129. p->nBusy++;
  147130. }
  147131. return rc;
  147132. }
  147133. /*
  147134. ** This routine sets the busy callback for an Sqlite database to the
  147135. ** given callback function with the given argument.
  147136. */
  147137. SQLITE_API int sqlite3_busy_handler(
  147138. sqlite3 *db,
  147139. int (*xBusy)(void*,int),
  147140. void *pArg
  147141. ){
  147142. #ifdef SQLITE_ENABLE_API_ARMOR
  147143. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  147144. #endif
  147145. sqlite3_mutex_enter(db->mutex);
  147146. db->busyHandler.xBusyHandler = xBusy;
  147147. db->busyHandler.pBusyArg = pArg;
  147148. db->busyHandler.nBusy = 0;
  147149. db->busyHandler.bExtraFileArg = 0;
  147150. db->busyTimeout = 0;
  147151. sqlite3_mutex_leave(db->mutex);
  147152. return SQLITE_OK;
  147153. }
  147154. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  147155. /*
  147156. ** This routine sets the progress callback for an Sqlite database to the
  147157. ** given callback function with the given argument. The progress callback will
  147158. ** be invoked every nOps opcodes.
  147159. */
  147160. SQLITE_API void sqlite3_progress_handler(
  147161. sqlite3 *db,
  147162. int nOps,
  147163. int (*xProgress)(void*),
  147164. void *pArg
  147165. ){
  147166. #ifdef SQLITE_ENABLE_API_ARMOR
  147167. if( !sqlite3SafetyCheckOk(db) ){
  147168. (void)SQLITE_MISUSE_BKPT;
  147169. return;
  147170. }
  147171. #endif
  147172. sqlite3_mutex_enter(db->mutex);
  147173. if( nOps>0 ){
  147174. db->xProgress = xProgress;
  147175. db->nProgressOps = (unsigned)nOps;
  147176. db->pProgressArg = pArg;
  147177. }else{
  147178. db->xProgress = 0;
  147179. db->nProgressOps = 0;
  147180. db->pProgressArg = 0;
  147181. }
  147182. sqlite3_mutex_leave(db->mutex);
  147183. }
  147184. #endif
  147185. /*
  147186. ** This routine installs a default busy handler that waits for the
  147187. ** specified number of milliseconds before returning 0.
  147188. */
  147189. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  147190. #ifdef SQLITE_ENABLE_API_ARMOR
  147191. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  147192. #endif
  147193. if( ms>0 ){
  147194. sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
  147195. (void*)db);
  147196. db->busyTimeout = ms;
  147197. db->busyHandler.bExtraFileArg = 1;
  147198. }else{
  147199. sqlite3_busy_handler(db, 0, 0);
  147200. }
  147201. return SQLITE_OK;
  147202. }
  147203. /*
  147204. ** Cause any pending operation to stop at its earliest opportunity.
  147205. */
  147206. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  147207. #ifdef SQLITE_ENABLE_API_ARMOR
  147208. if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
  147209. (void)SQLITE_MISUSE_BKPT;
  147210. return;
  147211. }
  147212. #endif
  147213. db->u1.isInterrupted = 1;
  147214. }
  147215. /*
  147216. ** This function is exactly the same as sqlite3_create_function(), except
  147217. ** that it is designed to be called by internal code. The difference is
  147218. ** that if a malloc() fails in sqlite3_create_function(), an error code
  147219. ** is returned and the mallocFailed flag cleared.
  147220. */
  147221. SQLITE_PRIVATE int sqlite3CreateFunc(
  147222. sqlite3 *db,
  147223. const char *zFunctionName,
  147224. int nArg,
  147225. int enc,
  147226. void *pUserData,
  147227. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  147228. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  147229. void (*xFinal)(sqlite3_context*),
  147230. void (*xValue)(sqlite3_context*),
  147231. void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
  147232. FuncDestructor *pDestructor
  147233. ){
  147234. FuncDef *p;
  147235. int nName;
  147236. int extraFlags;
  147237. assert( sqlite3_mutex_held(db->mutex) );
  147238. assert( xValue==0 || xSFunc==0 );
  147239. if( zFunctionName==0 /* Must have a valid name */
  147240. || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */
  147241. || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */
  147242. || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */
  147243. || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
  147244. || (255<(nName = sqlite3Strlen30( zFunctionName)))
  147245. ){
  147246. return SQLITE_MISUSE_BKPT;
  147247. }
  147248. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  147249. extraFlags = enc & SQLITE_DETERMINISTIC;
  147250. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  147251. #ifndef SQLITE_OMIT_UTF16
  147252. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  147253. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  147254. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  147255. **
  147256. ** If SQLITE_ANY is specified, add three versions of the function
  147257. ** to the hash table.
  147258. */
  147259. if( enc==SQLITE_UTF16 ){
  147260. enc = SQLITE_UTF16NATIVE;
  147261. }else if( enc==SQLITE_ANY ){
  147262. int rc;
  147263. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  147264. pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
  147265. if( rc==SQLITE_OK ){
  147266. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  147267. pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
  147268. }
  147269. if( rc!=SQLITE_OK ){
  147270. return rc;
  147271. }
  147272. enc = SQLITE_UTF16BE;
  147273. }
  147274. #else
  147275. enc = SQLITE_UTF8;
  147276. #endif
  147277. /* Check if an existing function is being overridden or deleted. If so,
  147278. ** and there are active VMs, then return SQLITE_BUSY. If a function
  147279. ** is being overridden/deleted but there are no active VMs, allow the
  147280. ** operation to continue but invalidate all precompiled statements.
  147281. */
  147282. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
  147283. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
  147284. if( db->nVdbeActive ){
  147285. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  147286. "unable to delete/modify user-function due to active statements");
  147287. assert( !db->mallocFailed );
  147288. return SQLITE_BUSY;
  147289. }else{
  147290. sqlite3ExpirePreparedStatements(db, 0);
  147291. }
  147292. }
  147293. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
  147294. assert(p || db->mallocFailed);
  147295. if( !p ){
  147296. return SQLITE_NOMEM_BKPT;
  147297. }
  147298. /* If an older version of the function with a configured destructor is
  147299. ** being replaced invoke the destructor function here. */
  147300. functionDestroy(db, p);
  147301. if( pDestructor ){
  147302. pDestructor->nRef++;
  147303. }
  147304. p->u.pDestructor = pDestructor;
  147305. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  147306. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  147307. p->xSFunc = xSFunc ? xSFunc : xStep;
  147308. p->xFinalize = xFinal;
  147309. p->xValue = xValue;
  147310. p->xInverse = xInverse;
  147311. p->pUserData = pUserData;
  147312. p->nArg = (u16)nArg;
  147313. return SQLITE_OK;
  147314. }
  147315. /*
  147316. ** Worker function used by utf-8 APIs that create new functions:
  147317. **
  147318. ** sqlite3_create_function()
  147319. ** sqlite3_create_function_v2()
  147320. ** sqlite3_create_window_function()
  147321. */
  147322. static int createFunctionApi(
  147323. sqlite3 *db,
  147324. const char *zFunc,
  147325. int nArg,
  147326. int enc,
  147327. void *p,
  147328. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  147329. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  147330. void (*xFinal)(sqlite3_context*),
  147331. void (*xValue)(sqlite3_context*),
  147332. void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
  147333. void(*xDestroy)(void*)
  147334. ){
  147335. int rc = SQLITE_ERROR;
  147336. FuncDestructor *pArg = 0;
  147337. #ifdef SQLITE_ENABLE_API_ARMOR
  147338. if( !sqlite3SafetyCheckOk(db) ){
  147339. return SQLITE_MISUSE_BKPT;
  147340. }
  147341. #endif
  147342. sqlite3_mutex_enter(db->mutex);
  147343. if( xDestroy ){
  147344. pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
  147345. if( !pArg ){
  147346. sqlite3OomFault(db);
  147347. xDestroy(p);
  147348. goto out;
  147349. }
  147350. pArg->nRef = 0;
  147351. pArg->xDestroy = xDestroy;
  147352. pArg->pUserData = p;
  147353. }
  147354. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
  147355. xSFunc, xStep, xFinal, xValue, xInverse, pArg
  147356. );
  147357. if( pArg && pArg->nRef==0 ){
  147358. assert( rc!=SQLITE_OK );
  147359. xDestroy(p);
  147360. sqlite3_free(pArg);
  147361. }
  147362. out:
  147363. rc = sqlite3ApiExit(db, rc);
  147364. sqlite3_mutex_leave(db->mutex);
  147365. return rc;
  147366. }
  147367. /*
  147368. ** Create new user functions.
  147369. */
  147370. SQLITE_API int sqlite3_create_function(
  147371. sqlite3 *db,
  147372. const char *zFunc,
  147373. int nArg,
  147374. int enc,
  147375. void *p,
  147376. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  147377. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  147378. void (*xFinal)(sqlite3_context*)
  147379. ){
  147380. return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
  147381. xFinal, 0, 0, 0);
  147382. }
  147383. SQLITE_API int sqlite3_create_function_v2(
  147384. sqlite3 *db,
  147385. const char *zFunc,
  147386. int nArg,
  147387. int enc,
  147388. void *p,
  147389. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  147390. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  147391. void (*xFinal)(sqlite3_context*),
  147392. void (*xDestroy)(void *)
  147393. ){
  147394. return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
  147395. xFinal, 0, 0, xDestroy);
  147396. }
  147397. SQLITE_API int sqlite3_create_window_function(
  147398. sqlite3 *db,
  147399. const char *zFunc,
  147400. int nArg,
  147401. int enc,
  147402. void *p,
  147403. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  147404. void (*xFinal)(sqlite3_context*),
  147405. void (*xValue)(sqlite3_context*),
  147406. void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
  147407. void (*xDestroy)(void *)
  147408. ){
  147409. return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
  147410. xFinal, xValue, xInverse, xDestroy);
  147411. }
  147412. #ifndef SQLITE_OMIT_UTF16
  147413. SQLITE_API int sqlite3_create_function16(
  147414. sqlite3 *db,
  147415. const void *zFunctionName,
  147416. int nArg,
  147417. int eTextRep,
  147418. void *p,
  147419. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  147420. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  147421. void (*xFinal)(sqlite3_context*)
  147422. ){
  147423. int rc;
  147424. char *zFunc8;
  147425. #ifdef SQLITE_ENABLE_API_ARMOR
  147426. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  147427. #endif
  147428. sqlite3_mutex_enter(db->mutex);
  147429. assert( !db->mallocFailed );
  147430. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  147431. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
  147432. sqlite3DbFree(db, zFunc8);
  147433. rc = sqlite3ApiExit(db, rc);
  147434. sqlite3_mutex_leave(db->mutex);
  147435. return rc;
  147436. }
  147437. #endif
  147438. /*
  147439. ** The following is the implementation of an SQL function that always
  147440. ** fails with an error message stating that the function is used in the
  147441. ** wrong context. The sqlite3_overload_function() API might construct
  147442. ** SQL function that use this routine so that the functions will exist
  147443. ** for name resolution but are actually overloaded by the xFindFunction
  147444. ** method of virtual tables.
  147445. */
  147446. static void sqlite3InvalidFunction(
  147447. sqlite3_context *context, /* The function calling context */
  147448. int NotUsed, /* Number of arguments to the function */
  147449. sqlite3_value **NotUsed2 /* Value of each argument */
  147450. ){
  147451. const char *zName = (const char*)sqlite3_user_data(context);
  147452. char *zErr;
  147453. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  147454. zErr = sqlite3_mprintf(
  147455. "unable to use function %s in the requested context", zName);
  147456. sqlite3_result_error(context, zErr, -1);
  147457. sqlite3_free(zErr);
  147458. }
  147459. /*
  147460. ** Declare that a function has been overloaded by a virtual table.
  147461. **
  147462. ** If the function already exists as a regular global function, then
  147463. ** this routine is a no-op. If the function does not exist, then create
  147464. ** a new one that always throws a run-time error.
  147465. **
  147466. ** When virtual tables intend to provide an overloaded function, they
  147467. ** should call this routine to make sure the global function exists.
  147468. ** A global function must exist in order for name resolution to work
  147469. ** properly.
  147470. */
  147471. SQLITE_API int sqlite3_overload_function(
  147472. sqlite3 *db,
  147473. const char *zName,
  147474. int nArg
  147475. ){
  147476. int rc;
  147477. char *zCopy;
  147478. #ifdef SQLITE_ENABLE_API_ARMOR
  147479. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  147480. return SQLITE_MISUSE_BKPT;
  147481. }
  147482. #endif
  147483. sqlite3_mutex_enter(db->mutex);
  147484. rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
  147485. sqlite3_mutex_leave(db->mutex);
  147486. if( rc ) return SQLITE_OK;
  147487. zCopy = sqlite3_mprintf(zName);
  147488. if( zCopy==0 ) return SQLITE_NOMEM;
  147489. return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
  147490. zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
  147491. }
  147492. #ifndef SQLITE_OMIT_TRACE
  147493. /*
  147494. ** Register a trace function. The pArg from the previously registered trace
  147495. ** is returned.
  147496. **
  147497. ** A NULL trace function means that no tracing is executes. A non-NULL
  147498. ** trace is a pointer to a function that is invoked at the start of each
  147499. ** SQL statement.
  147500. */
  147501. #ifndef SQLITE_OMIT_DEPRECATED
  147502. SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
  147503. void *pOld;
  147504. #ifdef SQLITE_ENABLE_API_ARMOR
  147505. if( !sqlite3SafetyCheckOk(db) ){
  147506. (void)SQLITE_MISUSE_BKPT;
  147507. return 0;
  147508. }
  147509. #endif
  147510. sqlite3_mutex_enter(db->mutex);
  147511. pOld = db->pTraceArg;
  147512. db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
  147513. db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
  147514. db->pTraceArg = pArg;
  147515. sqlite3_mutex_leave(db->mutex);
  147516. return pOld;
  147517. }
  147518. #endif /* SQLITE_OMIT_DEPRECATED */
  147519. /* Register a trace callback using the version-2 interface.
  147520. */
  147521. SQLITE_API int sqlite3_trace_v2(
  147522. sqlite3 *db, /* Trace this connection */
  147523. unsigned mTrace, /* Mask of events to be traced */
  147524. int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
  147525. void *pArg /* Context */
  147526. ){
  147527. #ifdef SQLITE_ENABLE_API_ARMOR
  147528. if( !sqlite3SafetyCheckOk(db) ){
  147529. return SQLITE_MISUSE_BKPT;
  147530. }
  147531. #endif
  147532. sqlite3_mutex_enter(db->mutex);
  147533. if( mTrace==0 ) xTrace = 0;
  147534. if( xTrace==0 ) mTrace = 0;
  147535. db->mTrace = mTrace;
  147536. db->xTrace = xTrace;
  147537. db->pTraceArg = pArg;
  147538. sqlite3_mutex_leave(db->mutex);
  147539. return SQLITE_OK;
  147540. }
  147541. #ifndef SQLITE_OMIT_DEPRECATED
  147542. /*
  147543. ** Register a profile function. The pArg from the previously registered
  147544. ** profile function is returned.
  147545. **
  147546. ** A NULL profile function means that no profiling is executes. A non-NULL
  147547. ** profile is a pointer to a function that is invoked at the conclusion of
  147548. ** each SQL statement that is run.
  147549. */
  147550. SQLITE_API void *sqlite3_profile(
  147551. sqlite3 *db,
  147552. void (*xProfile)(void*,const char*,sqlite_uint64),
  147553. void *pArg
  147554. ){
  147555. void *pOld;
  147556. #ifdef SQLITE_ENABLE_API_ARMOR
  147557. if( !sqlite3SafetyCheckOk(db) ){
  147558. (void)SQLITE_MISUSE_BKPT;
  147559. return 0;
  147560. }
  147561. #endif
  147562. sqlite3_mutex_enter(db->mutex);
  147563. pOld = db->pProfileArg;
  147564. db->xProfile = xProfile;
  147565. db->pProfileArg = pArg;
  147566. db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
  147567. if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
  147568. sqlite3_mutex_leave(db->mutex);
  147569. return pOld;
  147570. }
  147571. #endif /* SQLITE_OMIT_DEPRECATED */
  147572. #endif /* SQLITE_OMIT_TRACE */
  147573. /*
  147574. ** Register a function to be invoked when a transaction commits.
  147575. ** If the invoked function returns non-zero, then the commit becomes a
  147576. ** rollback.
  147577. */
  147578. SQLITE_API void *sqlite3_commit_hook(
  147579. sqlite3 *db, /* Attach the hook to this database */
  147580. int (*xCallback)(void*), /* Function to invoke on each commit */
  147581. void *pArg /* Argument to the function */
  147582. ){
  147583. void *pOld;
  147584. #ifdef SQLITE_ENABLE_API_ARMOR
  147585. if( !sqlite3SafetyCheckOk(db) ){
  147586. (void)SQLITE_MISUSE_BKPT;
  147587. return 0;
  147588. }
  147589. #endif
  147590. sqlite3_mutex_enter(db->mutex);
  147591. pOld = db->pCommitArg;
  147592. db->xCommitCallback = xCallback;
  147593. db->pCommitArg = pArg;
  147594. sqlite3_mutex_leave(db->mutex);
  147595. return pOld;
  147596. }
  147597. /*
  147598. ** Register a callback to be invoked each time a row is updated,
  147599. ** inserted or deleted using this database connection.
  147600. */
  147601. SQLITE_API void *sqlite3_update_hook(
  147602. sqlite3 *db, /* Attach the hook to this database */
  147603. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  147604. void *pArg /* Argument to the function */
  147605. ){
  147606. void *pRet;
  147607. #ifdef SQLITE_ENABLE_API_ARMOR
  147608. if( !sqlite3SafetyCheckOk(db) ){
  147609. (void)SQLITE_MISUSE_BKPT;
  147610. return 0;
  147611. }
  147612. #endif
  147613. sqlite3_mutex_enter(db->mutex);
  147614. pRet = db->pUpdateArg;
  147615. db->xUpdateCallback = xCallback;
  147616. db->pUpdateArg = pArg;
  147617. sqlite3_mutex_leave(db->mutex);
  147618. return pRet;
  147619. }
  147620. /*
  147621. ** Register a callback to be invoked each time a transaction is rolled
  147622. ** back by this database connection.
  147623. */
  147624. SQLITE_API void *sqlite3_rollback_hook(
  147625. sqlite3 *db, /* Attach the hook to this database */
  147626. void (*xCallback)(void*), /* Callback function */
  147627. void *pArg /* Argument to the function */
  147628. ){
  147629. void *pRet;
  147630. #ifdef SQLITE_ENABLE_API_ARMOR
  147631. if( !sqlite3SafetyCheckOk(db) ){
  147632. (void)SQLITE_MISUSE_BKPT;
  147633. return 0;
  147634. }
  147635. #endif
  147636. sqlite3_mutex_enter(db->mutex);
  147637. pRet = db->pRollbackArg;
  147638. db->xRollbackCallback = xCallback;
  147639. db->pRollbackArg = pArg;
  147640. sqlite3_mutex_leave(db->mutex);
  147641. return pRet;
  147642. }
  147643. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  147644. /*
  147645. ** Register a callback to be invoked each time a row is updated,
  147646. ** inserted or deleted using this database connection.
  147647. */
  147648. SQLITE_API void *sqlite3_preupdate_hook(
  147649. sqlite3 *db, /* Attach the hook to this database */
  147650. void(*xCallback)( /* Callback function */
  147651. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
  147652. void *pArg /* First callback argument */
  147653. ){
  147654. void *pRet;
  147655. sqlite3_mutex_enter(db->mutex);
  147656. pRet = db->pPreUpdateArg;
  147657. db->xPreUpdateCallback = xCallback;
  147658. db->pPreUpdateArg = pArg;
  147659. sqlite3_mutex_leave(db->mutex);
  147660. return pRet;
  147661. }
  147662. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  147663. #ifndef SQLITE_OMIT_WAL
  147664. /*
  147665. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  147666. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  147667. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  147668. ** wal_autocheckpoint()).
  147669. */
  147670. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  147671. void *pClientData, /* Argument */
  147672. sqlite3 *db, /* Connection */
  147673. const char *zDb, /* Database */
  147674. int nFrame /* Size of WAL */
  147675. ){
  147676. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  147677. sqlite3BeginBenignMalloc();
  147678. sqlite3_wal_checkpoint(db, zDb);
  147679. sqlite3EndBenignMalloc();
  147680. }
  147681. return SQLITE_OK;
  147682. }
  147683. #endif /* SQLITE_OMIT_WAL */
  147684. /*
  147685. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  147686. ** a database after committing a transaction if there are nFrame or
  147687. ** more frames in the log file. Passing zero or a negative value as the
  147688. ** nFrame parameter disables automatic checkpoints entirely.
  147689. **
  147690. ** The callback registered by this function replaces any existing callback
  147691. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  147692. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  147693. ** configured by this function.
  147694. */
  147695. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  147696. #ifdef SQLITE_OMIT_WAL
  147697. UNUSED_PARAMETER(db);
  147698. UNUSED_PARAMETER(nFrame);
  147699. #else
  147700. #ifdef SQLITE_ENABLE_API_ARMOR
  147701. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  147702. #endif
  147703. if( nFrame>0 ){
  147704. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  147705. }else{
  147706. sqlite3_wal_hook(db, 0, 0);
  147707. }
  147708. #endif
  147709. return SQLITE_OK;
  147710. }
  147711. /*
  147712. ** Register a callback to be invoked each time a transaction is written
  147713. ** into the write-ahead-log by this database connection.
  147714. */
  147715. SQLITE_API void *sqlite3_wal_hook(
  147716. sqlite3 *db, /* Attach the hook to this db handle */
  147717. int(*xCallback)(void *, sqlite3*, const char*, int),
  147718. void *pArg /* First argument passed to xCallback() */
  147719. ){
  147720. #ifndef SQLITE_OMIT_WAL
  147721. void *pRet;
  147722. #ifdef SQLITE_ENABLE_API_ARMOR
  147723. if( !sqlite3SafetyCheckOk(db) ){
  147724. (void)SQLITE_MISUSE_BKPT;
  147725. return 0;
  147726. }
  147727. #endif
  147728. sqlite3_mutex_enter(db->mutex);
  147729. pRet = db->pWalArg;
  147730. db->xWalCallback = xCallback;
  147731. db->pWalArg = pArg;
  147732. sqlite3_mutex_leave(db->mutex);
  147733. return pRet;
  147734. #else
  147735. return 0;
  147736. #endif
  147737. }
  147738. /*
  147739. ** Checkpoint database zDb.
  147740. */
  147741. SQLITE_API int sqlite3_wal_checkpoint_v2(
  147742. sqlite3 *db, /* Database handle */
  147743. const char *zDb, /* Name of attached database (or NULL) */
  147744. int eMode, /* SQLITE_CHECKPOINT_* value */
  147745. int *pnLog, /* OUT: Size of WAL log in frames */
  147746. int *pnCkpt /* OUT: Total number of frames checkpointed */
  147747. ){
  147748. #ifdef SQLITE_OMIT_WAL
  147749. return SQLITE_OK;
  147750. #else
  147751. int rc; /* Return code */
  147752. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  147753. #ifdef SQLITE_ENABLE_API_ARMOR
  147754. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  147755. #endif
  147756. /* Initialize the output variables to -1 in case an error occurs. */
  147757. if( pnLog ) *pnLog = -1;
  147758. if( pnCkpt ) *pnCkpt = -1;
  147759. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  147760. assert( SQLITE_CHECKPOINT_FULL==1 );
  147761. assert( SQLITE_CHECKPOINT_RESTART==2 );
  147762. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  147763. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  147764. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  147765. ** mode: */
  147766. return SQLITE_MISUSE;
  147767. }
  147768. sqlite3_mutex_enter(db->mutex);
  147769. if( zDb && zDb[0] ){
  147770. iDb = sqlite3FindDbName(db, zDb);
  147771. }
  147772. if( iDb<0 ){
  147773. rc = SQLITE_ERROR;
  147774. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  147775. }else{
  147776. db->busyHandler.nBusy = 0;
  147777. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  147778. sqlite3Error(db, rc);
  147779. }
  147780. rc = sqlite3ApiExit(db, rc);
  147781. /* If there are no active statements, clear the interrupt flag at this
  147782. ** point. */
  147783. if( db->nVdbeActive==0 ){
  147784. db->u1.isInterrupted = 0;
  147785. }
  147786. sqlite3_mutex_leave(db->mutex);
  147787. return rc;
  147788. #endif
  147789. }
  147790. /*
  147791. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  147792. ** to contains a zero-length string, all attached databases are
  147793. ** checkpointed.
  147794. */
  147795. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  147796. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  147797. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  147798. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  147799. }
  147800. #ifndef SQLITE_OMIT_WAL
  147801. /*
  147802. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  147803. ** not currently open in WAL mode.
  147804. **
  147805. ** If a transaction is open on the database being checkpointed, this
  147806. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  147807. ** an error occurs while running the checkpoint, an SQLite error code is
  147808. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  147809. **
  147810. ** The mutex on database handle db should be held by the caller. The mutex
  147811. ** associated with the specific b-tree being checkpointed is taken by
  147812. ** this function while the checkpoint is running.
  147813. **
  147814. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  147815. ** checkpointed. If an error is encountered it is returned immediately -
  147816. ** no attempt is made to checkpoint any remaining databases.
  147817. **
  147818. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
  147819. ** or TRUNCATE.
  147820. */
  147821. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  147822. int rc = SQLITE_OK; /* Return code */
  147823. int i; /* Used to iterate through attached dbs */
  147824. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  147825. assert( sqlite3_mutex_held(db->mutex) );
  147826. assert( !pnLog || *pnLog==-1 );
  147827. assert( !pnCkpt || *pnCkpt==-1 );
  147828. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  147829. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  147830. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  147831. pnLog = 0;
  147832. pnCkpt = 0;
  147833. if( rc==SQLITE_BUSY ){
  147834. bBusy = 1;
  147835. rc = SQLITE_OK;
  147836. }
  147837. }
  147838. }
  147839. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  147840. }
  147841. #endif /* SQLITE_OMIT_WAL */
  147842. /*
  147843. ** This function returns true if main-memory should be used instead of
  147844. ** a temporary file for transient pager files and statement journals.
  147845. ** The value returned depends on the value of db->temp_store (runtime
  147846. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  147847. ** following table describes the relationship between these two values
  147848. ** and this functions return value.
  147849. **
  147850. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  147851. ** ----------------- -------------- ------------------------------
  147852. ** 0 any file (return 0)
  147853. ** 1 1 file (return 0)
  147854. ** 1 2 memory (return 1)
  147855. ** 1 0 file (return 0)
  147856. ** 2 1 file (return 0)
  147857. ** 2 2 memory (return 1)
  147858. ** 2 0 memory (return 1)
  147859. ** 3 any memory (return 1)
  147860. */
  147861. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  147862. #if SQLITE_TEMP_STORE==1
  147863. return ( db->temp_store==2 );
  147864. #endif
  147865. #if SQLITE_TEMP_STORE==2
  147866. return ( db->temp_store!=1 );
  147867. #endif
  147868. #if SQLITE_TEMP_STORE==3
  147869. UNUSED_PARAMETER(db);
  147870. return 1;
  147871. #endif
  147872. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  147873. UNUSED_PARAMETER(db);
  147874. return 0;
  147875. #endif
  147876. }
  147877. /*
  147878. ** Return UTF-8 encoded English language explanation of the most recent
  147879. ** error.
  147880. */
  147881. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  147882. const char *z;
  147883. if( !db ){
  147884. return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  147885. }
  147886. if( !sqlite3SafetyCheckSickOrOk(db) ){
  147887. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  147888. }
  147889. sqlite3_mutex_enter(db->mutex);
  147890. if( db->mallocFailed ){
  147891. z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  147892. }else{
  147893. testcase( db->pErr==0 );
  147894. z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
  147895. assert( !db->mallocFailed );
  147896. if( z==0 ){
  147897. z = sqlite3ErrStr(db->errCode);
  147898. }
  147899. }
  147900. sqlite3_mutex_leave(db->mutex);
  147901. return z;
  147902. }
  147903. #ifndef SQLITE_OMIT_UTF16
  147904. /*
  147905. ** Return UTF-16 encoded English language explanation of the most recent
  147906. ** error.
  147907. */
  147908. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  147909. static const u16 outOfMem[] = {
  147910. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  147911. };
  147912. static const u16 misuse[] = {
  147913. 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
  147914. 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
  147915. 'm', 'i', 's', 'u', 's', 'e', 0
  147916. };
  147917. const void *z;
  147918. if( !db ){
  147919. return (void *)outOfMem;
  147920. }
  147921. if( !sqlite3SafetyCheckSickOrOk(db) ){
  147922. return (void *)misuse;
  147923. }
  147924. sqlite3_mutex_enter(db->mutex);
  147925. if( db->mallocFailed ){
  147926. z = (void *)outOfMem;
  147927. }else{
  147928. z = sqlite3_value_text16(db->pErr);
  147929. if( z==0 ){
  147930. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  147931. z = sqlite3_value_text16(db->pErr);
  147932. }
  147933. /* A malloc() may have failed within the call to sqlite3_value_text16()
  147934. ** above. If this is the case, then the db->mallocFailed flag needs to
  147935. ** be cleared before returning. Do this directly, instead of via
  147936. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  147937. */
  147938. sqlite3OomClear(db);
  147939. }
  147940. sqlite3_mutex_leave(db->mutex);
  147941. return z;
  147942. }
  147943. #endif /* SQLITE_OMIT_UTF16 */
  147944. /*
  147945. ** Return the most recent error code generated by an SQLite routine. If NULL is
  147946. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  147947. */
  147948. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  147949. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  147950. return SQLITE_MISUSE_BKPT;
  147951. }
  147952. if( !db || db->mallocFailed ){
  147953. return SQLITE_NOMEM_BKPT;
  147954. }
  147955. return db->errCode & db->errMask;
  147956. }
  147957. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  147958. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  147959. return SQLITE_MISUSE_BKPT;
  147960. }
  147961. if( !db || db->mallocFailed ){
  147962. return SQLITE_NOMEM_BKPT;
  147963. }
  147964. return db->errCode;
  147965. }
  147966. SQLITE_API int sqlite3_system_errno(sqlite3 *db){
  147967. return db ? db->iSysErrno : 0;
  147968. }
  147969. /*
  147970. ** Return a string that describes the kind of error specified in the
  147971. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  147972. ** function.
  147973. */
  147974. SQLITE_API const char *sqlite3_errstr(int rc){
  147975. return sqlite3ErrStr(rc);
  147976. }
  147977. /*
  147978. ** Create a new collating function for database "db". The name is zName
  147979. ** and the encoding is enc.
  147980. */
  147981. static int createCollation(
  147982. sqlite3* db,
  147983. const char *zName,
  147984. u8 enc,
  147985. void* pCtx,
  147986. int(*xCompare)(void*,int,const void*,int,const void*),
  147987. void(*xDel)(void*)
  147988. ){
  147989. CollSeq *pColl;
  147990. int enc2;
  147991. assert( sqlite3_mutex_held(db->mutex) );
  147992. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  147993. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  147994. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  147995. */
  147996. enc2 = enc;
  147997. testcase( enc2==SQLITE_UTF16 );
  147998. testcase( enc2==SQLITE_UTF16_ALIGNED );
  147999. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  148000. enc2 = SQLITE_UTF16NATIVE;
  148001. }
  148002. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  148003. return SQLITE_MISUSE_BKPT;
  148004. }
  148005. /* Check if this call is removing or replacing an existing collation
  148006. ** sequence. If so, and there are active VMs, return busy. If there
  148007. ** are no active VMs, invalidate any pre-compiled statements.
  148008. */
  148009. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  148010. if( pColl && pColl->xCmp ){
  148011. if( db->nVdbeActive ){
  148012. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  148013. "unable to delete/modify collation sequence due to active statements");
  148014. return SQLITE_BUSY;
  148015. }
  148016. sqlite3ExpirePreparedStatements(db, 0);
  148017. /* If collation sequence pColl was created directly by a call to
  148018. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  148019. ** then any copies made by synthCollSeq() need to be invalidated.
  148020. ** Also, collation destructor - CollSeq.xDel() - function may need
  148021. ** to be called.
  148022. */
  148023. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  148024. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  148025. int j;
  148026. for(j=0; j<3; j++){
  148027. CollSeq *p = &aColl[j];
  148028. if( p->enc==pColl->enc ){
  148029. if( p->xDel ){
  148030. p->xDel(p->pUser);
  148031. }
  148032. p->xCmp = 0;
  148033. }
  148034. }
  148035. }
  148036. }
  148037. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  148038. if( pColl==0 ) return SQLITE_NOMEM_BKPT;
  148039. pColl->xCmp = xCompare;
  148040. pColl->pUser = pCtx;
  148041. pColl->xDel = xDel;
  148042. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  148043. sqlite3Error(db, SQLITE_OK);
  148044. return SQLITE_OK;
  148045. }
  148046. /*
  148047. ** This array defines hard upper bounds on limit values. The
  148048. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  148049. ** #defines in sqlite3.h.
  148050. */
  148051. static const int aHardLimit[] = {
  148052. SQLITE_MAX_LENGTH,
  148053. SQLITE_MAX_SQL_LENGTH,
  148054. SQLITE_MAX_COLUMN,
  148055. SQLITE_MAX_EXPR_DEPTH,
  148056. SQLITE_MAX_COMPOUND_SELECT,
  148057. SQLITE_MAX_VDBE_OP,
  148058. SQLITE_MAX_FUNCTION_ARG,
  148059. SQLITE_MAX_ATTACHED,
  148060. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  148061. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  148062. SQLITE_MAX_TRIGGER_DEPTH,
  148063. SQLITE_MAX_WORKER_THREADS,
  148064. };
  148065. /*
  148066. ** Make sure the hard limits are set to reasonable values
  148067. */
  148068. #if SQLITE_MAX_LENGTH<100
  148069. # error SQLITE_MAX_LENGTH must be at least 100
  148070. #endif
  148071. #if SQLITE_MAX_SQL_LENGTH<100
  148072. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  148073. #endif
  148074. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  148075. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  148076. #endif
  148077. #if SQLITE_MAX_COMPOUND_SELECT<2
  148078. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  148079. #endif
  148080. #if SQLITE_MAX_VDBE_OP<40
  148081. # error SQLITE_MAX_VDBE_OP must be at least 40
  148082. #endif
  148083. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
  148084. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
  148085. #endif
  148086. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  148087. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  148088. #endif
  148089. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  148090. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  148091. #endif
  148092. #if SQLITE_MAX_COLUMN>32767
  148093. # error SQLITE_MAX_COLUMN must not exceed 32767
  148094. #endif
  148095. #if SQLITE_MAX_TRIGGER_DEPTH<1
  148096. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  148097. #endif
  148098. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  148099. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  148100. #endif
  148101. /*
  148102. ** Change the value of a limit. Report the old value.
  148103. ** If an invalid limit index is supplied, report -1.
  148104. ** Make no changes but still report the old value if the
  148105. ** new limit is negative.
  148106. **
  148107. ** A new lower limit does not shrink existing constructs.
  148108. ** It merely prevents new constructs that exceed the limit
  148109. ** from forming.
  148110. */
  148111. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  148112. int oldLimit;
  148113. #ifdef SQLITE_ENABLE_API_ARMOR
  148114. if( !sqlite3SafetyCheckOk(db) ){
  148115. (void)SQLITE_MISUSE_BKPT;
  148116. return -1;
  148117. }
  148118. #endif
  148119. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  148120. ** there is a hard upper bound set at compile-time by a C preprocessor
  148121. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  148122. ** "_MAX_".)
  148123. */
  148124. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  148125. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  148126. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  148127. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  148128. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  148129. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  148130. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  148131. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  148132. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  148133. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  148134. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  148135. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  148136. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  148137. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  148138. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  148139. return -1;
  148140. }
  148141. oldLimit = db->aLimit[limitId];
  148142. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  148143. if( newLimit>aHardLimit[limitId] ){
  148144. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  148145. }
  148146. db->aLimit[limitId] = newLimit;
  148147. }
  148148. return oldLimit; /* IMP: R-53341-35419 */
  148149. }
  148150. /*
  148151. ** This function is used to parse both URIs and non-URI filenames passed by the
  148152. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  148153. ** URIs specified as part of ATTACH statements.
  148154. **
  148155. ** The first argument to this function is the name of the VFS to use (or
  148156. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  148157. ** query parameter. The second argument contains the URI (or non-URI filename)
  148158. ** itself. When this function is called the *pFlags variable should contain
  148159. ** the default flags to open the database handle with. The value stored in
  148160. ** *pFlags may be updated before returning if the URI filename contains
  148161. ** "cache=xxx" or "mode=xxx" query parameters.
  148162. **
  148163. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  148164. ** the VFS that should be used to open the database file. *pzFile is set to
  148165. ** point to a buffer containing the name of the file to open. It is the
  148166. ** responsibility of the caller to eventually call sqlite3_free() to release
  148167. ** this buffer.
  148168. **
  148169. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  148170. ** may be set to point to a buffer containing an English language error
  148171. ** message. It is the responsibility of the caller to eventually release
  148172. ** this buffer by calling sqlite3_free().
  148173. */
  148174. SQLITE_PRIVATE int sqlite3ParseUri(
  148175. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  148176. const char *zUri, /* Nul-terminated URI to parse */
  148177. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  148178. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  148179. char **pzFile, /* OUT: Filename component of URI */
  148180. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  148181. ){
  148182. int rc = SQLITE_OK;
  148183. unsigned int flags = *pFlags;
  148184. const char *zVfs = zDefaultVfs;
  148185. char *zFile;
  148186. char c;
  148187. int nUri = sqlite3Strlen30(zUri);
  148188. assert( *pzErrMsg==0 );
  148189. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  148190. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  148191. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  148192. ){
  148193. char *zOpt;
  148194. int eState; /* Parser state when parsing URI */
  148195. int iIn; /* Input character index */
  148196. int iOut = 0; /* Output character index */
  148197. u64 nByte = nUri+2; /* Bytes of space to allocate */
  148198. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  148199. ** method that there may be extra parameters following the file-name. */
  148200. flags |= SQLITE_OPEN_URI;
  148201. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  148202. zFile = sqlite3_malloc64(nByte);
  148203. if( !zFile ) return SQLITE_NOMEM_BKPT;
  148204. iIn = 5;
  148205. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  148206. if( strncmp(zUri+5, "///", 3)==0 ){
  148207. iIn = 7;
  148208. /* The following condition causes URIs with five leading / characters
  148209. ** like file://///host/path to be converted into UNCs like //host/path.
  148210. ** The correct URI for that UNC has only two or four leading / characters
  148211. ** file://host/path or file:////host/path. But 5 leading slashes is a
  148212. ** common error, we are told, so we handle it as a special case. */
  148213. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  148214. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  148215. iIn = 16;
  148216. }
  148217. #else
  148218. /* Discard the scheme and authority segments of the URI. */
  148219. if( zUri[5]=='/' && zUri[6]=='/' ){
  148220. iIn = 7;
  148221. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  148222. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  148223. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  148224. iIn-7, &zUri[7]);
  148225. rc = SQLITE_ERROR;
  148226. goto parse_uri_out;
  148227. }
  148228. }
  148229. #endif
  148230. /* Copy the filename and any query parameters into the zFile buffer.
  148231. ** Decode %HH escape codes along the way.
  148232. **
  148233. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  148234. ** on the parsing context. As follows:
  148235. **
  148236. ** 0: Parsing file-name.
  148237. ** 1: Parsing name section of a name=value query parameter.
  148238. ** 2: Parsing value section of a name=value query parameter.
  148239. */
  148240. eState = 0;
  148241. while( (c = zUri[iIn])!=0 && c!='#' ){
  148242. iIn++;
  148243. if( c=='%'
  148244. && sqlite3Isxdigit(zUri[iIn])
  148245. && sqlite3Isxdigit(zUri[iIn+1])
  148246. ){
  148247. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  148248. octet += sqlite3HexToInt(zUri[iIn++]);
  148249. assert( octet>=0 && octet<256 );
  148250. if( octet==0 ){
  148251. #ifndef SQLITE_ENABLE_URI_00_ERROR
  148252. /* This branch is taken when "%00" appears within the URI. In this
  148253. ** case we ignore all text in the remainder of the path, name or
  148254. ** value currently being parsed. So ignore the current character
  148255. ** and skip to the next "?", "=" or "&", as appropriate. */
  148256. while( (c = zUri[iIn])!=0 && c!='#'
  148257. && (eState!=0 || c!='?')
  148258. && (eState!=1 || (c!='=' && c!='&'))
  148259. && (eState!=2 || c!='&')
  148260. ){
  148261. iIn++;
  148262. }
  148263. continue;
  148264. #else
  148265. /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
  148266. *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
  148267. rc = SQLITE_ERROR;
  148268. goto parse_uri_out;
  148269. #endif
  148270. }
  148271. c = octet;
  148272. }else if( eState==1 && (c=='&' || c=='=') ){
  148273. if( zFile[iOut-1]==0 ){
  148274. /* An empty option name. Ignore this option altogether. */
  148275. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  148276. continue;
  148277. }
  148278. if( c=='&' ){
  148279. zFile[iOut++] = '\0';
  148280. }else{
  148281. eState = 2;
  148282. }
  148283. c = 0;
  148284. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  148285. c = 0;
  148286. eState = 1;
  148287. }
  148288. zFile[iOut++] = c;
  148289. }
  148290. if( eState==1 ) zFile[iOut++] = '\0';
  148291. zFile[iOut++] = '\0';
  148292. zFile[iOut++] = '\0';
  148293. /* Check if there were any options specified that should be interpreted
  148294. ** here. Options that are interpreted here include "vfs" and those that
  148295. ** correspond to flags that may be passed to the sqlite3_open_v2()
  148296. ** method. */
  148297. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  148298. while( zOpt[0] ){
  148299. int nOpt = sqlite3Strlen30(zOpt);
  148300. char *zVal = &zOpt[nOpt+1];
  148301. int nVal = sqlite3Strlen30(zVal);
  148302. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  148303. zVfs = zVal;
  148304. }else{
  148305. struct OpenMode {
  148306. const char *z;
  148307. int mode;
  148308. } *aMode = 0;
  148309. char *zModeType = 0;
  148310. int mask = 0;
  148311. int limit = 0;
  148312. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  148313. static struct OpenMode aCacheMode[] = {
  148314. { "shared", SQLITE_OPEN_SHAREDCACHE },
  148315. { "private", SQLITE_OPEN_PRIVATECACHE },
  148316. { 0, 0 }
  148317. };
  148318. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  148319. aMode = aCacheMode;
  148320. limit = mask;
  148321. zModeType = "cache";
  148322. }
  148323. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  148324. static struct OpenMode aOpenMode[] = {
  148325. { "ro", SQLITE_OPEN_READONLY },
  148326. { "rw", SQLITE_OPEN_READWRITE },
  148327. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  148328. { "memory", SQLITE_OPEN_MEMORY },
  148329. { 0, 0 }
  148330. };
  148331. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  148332. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  148333. aMode = aOpenMode;
  148334. limit = mask & flags;
  148335. zModeType = "access";
  148336. }
  148337. if( aMode ){
  148338. int i;
  148339. int mode = 0;
  148340. for(i=0; aMode[i].z; i++){
  148341. const char *z = aMode[i].z;
  148342. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  148343. mode = aMode[i].mode;
  148344. break;
  148345. }
  148346. }
  148347. if( mode==0 ){
  148348. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  148349. rc = SQLITE_ERROR;
  148350. goto parse_uri_out;
  148351. }
  148352. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  148353. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  148354. zModeType, zVal);
  148355. rc = SQLITE_PERM;
  148356. goto parse_uri_out;
  148357. }
  148358. flags = (flags & ~mask) | mode;
  148359. }
  148360. }
  148361. zOpt = &zVal[nVal+1];
  148362. }
  148363. }else{
  148364. zFile = sqlite3_malloc64(nUri+2);
  148365. if( !zFile ) return SQLITE_NOMEM_BKPT;
  148366. if( nUri ){
  148367. memcpy(zFile, zUri, nUri);
  148368. }
  148369. zFile[nUri] = '\0';
  148370. zFile[nUri+1] = '\0';
  148371. flags &= ~SQLITE_OPEN_URI;
  148372. }
  148373. *ppVfs = sqlite3_vfs_find(zVfs);
  148374. if( *ppVfs==0 ){
  148375. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  148376. rc = SQLITE_ERROR;
  148377. }
  148378. parse_uri_out:
  148379. if( rc!=SQLITE_OK ){
  148380. sqlite3_free(zFile);
  148381. zFile = 0;
  148382. }
  148383. *pFlags = flags;
  148384. *pzFile = zFile;
  148385. return rc;
  148386. }
  148387. #if defined(SQLITE_HAS_CODEC)
  148388. /*
  148389. ** Process URI filename query parameters relevant to the SQLite Encryption
  148390. ** Extension. Return true if any of the relevant query parameters are
  148391. ** seen and return false if not.
  148392. */
  148393. SQLITE_PRIVATE int sqlite3CodecQueryParameters(
  148394. sqlite3 *db, /* Database connection */
  148395. const char *zDb, /* Which schema is being created/attached */
  148396. const char *zUri /* URI filename */
  148397. ){
  148398. const char *zKey;
  148399. if( (zKey = sqlite3_uri_parameter(zUri, "hexkey"))!=0 && zKey[0] ){
  148400. u8 iByte;
  148401. int i;
  148402. char zDecoded[40];
  148403. for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
  148404. iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
  148405. if( (i&1)!=0 ) zDecoded[i/2] = iByte;
  148406. }
  148407. sqlite3_key_v2(db, zDb, zDecoded, i/2);
  148408. return 1;
  148409. }else if( (zKey = sqlite3_uri_parameter(zUri, "key"))!=0 ){
  148410. sqlite3_key_v2(db, zDb, zKey, sqlite3Strlen30(zKey));
  148411. return 1;
  148412. }else if( (zKey = sqlite3_uri_parameter(zUri, "textkey"))!=0 ){
  148413. sqlite3_key_v2(db, zDb, zKey, -1);
  148414. return 1;
  148415. }else{
  148416. return 0;
  148417. }
  148418. }
  148419. #endif
  148420. /*
  148421. ** This routine does the work of opening a database on behalf of
  148422. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  148423. ** is UTF-8 encoded.
  148424. */
  148425. static int openDatabase(
  148426. const char *zFilename, /* Database filename UTF-8 encoded */
  148427. sqlite3 **ppDb, /* OUT: Returned database handle */
  148428. unsigned int flags, /* Operational flags */
  148429. const char *zVfs /* Name of the VFS to use */
  148430. ){
  148431. sqlite3 *db; /* Store allocated handle here */
  148432. int rc; /* Return code */
  148433. int isThreadsafe; /* True for threadsafe connections */
  148434. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  148435. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  148436. #ifdef SQLITE_ENABLE_API_ARMOR
  148437. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  148438. #endif
  148439. *ppDb = 0;
  148440. #ifndef SQLITE_OMIT_AUTOINIT
  148441. rc = sqlite3_initialize();
  148442. if( rc ) return rc;
  148443. #endif
  148444. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  148445. isThreadsafe = 0;
  148446. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  148447. isThreadsafe = 0;
  148448. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  148449. isThreadsafe = 1;
  148450. }else{
  148451. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  148452. }
  148453. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  148454. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  148455. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  148456. flags |= SQLITE_OPEN_SHAREDCACHE;
  148457. }
  148458. /* Remove harmful bits from the flags parameter
  148459. **
  148460. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  148461. ** dealt with in the previous code block. Besides these, the only
  148462. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  148463. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  148464. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  148465. ** off all other flags.
  148466. */
  148467. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  148468. SQLITE_OPEN_EXCLUSIVE |
  148469. SQLITE_OPEN_MAIN_DB |
  148470. SQLITE_OPEN_TEMP_DB |
  148471. SQLITE_OPEN_TRANSIENT_DB |
  148472. SQLITE_OPEN_MAIN_JOURNAL |
  148473. SQLITE_OPEN_TEMP_JOURNAL |
  148474. SQLITE_OPEN_SUBJOURNAL |
  148475. SQLITE_OPEN_MASTER_JOURNAL |
  148476. SQLITE_OPEN_NOMUTEX |
  148477. SQLITE_OPEN_FULLMUTEX |
  148478. SQLITE_OPEN_WAL
  148479. );
  148480. /* Allocate the sqlite data structure */
  148481. db = sqlite3MallocZero( sizeof(sqlite3) );
  148482. if( db==0 ) goto opendb_out;
  148483. if( isThreadsafe
  148484. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  148485. || sqlite3GlobalConfig.bCoreMutex
  148486. #endif
  148487. ){
  148488. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  148489. if( db->mutex==0 ){
  148490. sqlite3_free(db);
  148491. db = 0;
  148492. goto opendb_out;
  148493. }
  148494. if( isThreadsafe==0 ){
  148495. sqlite3MutexWarnOnContention(db->mutex);
  148496. }
  148497. }
  148498. sqlite3_mutex_enter(db->mutex);
  148499. db->errMask = 0xff;
  148500. db->nDb = 2;
  148501. db->magic = SQLITE_MAGIC_BUSY;
  148502. db->aDb = db->aDbStatic;
  148503. db->lookaside.bDisable = 1;
  148504. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  148505. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  148506. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  148507. db->autoCommit = 1;
  148508. db->nextAutovac = -1;
  148509. db->szMmap = sqlite3GlobalConfig.szMmap;
  148510. db->nextPagesize = 0;
  148511. db->nMaxSorterMmap = 0x7FFFFFFF;
  148512. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  148513. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  148514. | SQLITE_AutoIndex
  148515. #endif
  148516. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  148517. | SQLITE_CkptFullFSync
  148518. #endif
  148519. #if SQLITE_DEFAULT_FILE_FORMAT<4
  148520. | SQLITE_LegacyFileFmt
  148521. #endif
  148522. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  148523. | SQLITE_LoadExtension
  148524. #endif
  148525. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  148526. | SQLITE_RecTriggers
  148527. #endif
  148528. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  148529. | SQLITE_ForeignKeys
  148530. #endif
  148531. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  148532. | SQLITE_ReverseOrder
  148533. #endif
  148534. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  148535. | SQLITE_CellSizeCk
  148536. #endif
  148537. #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
  148538. | SQLITE_Fts3Tokenizer
  148539. #endif
  148540. #if defined(SQLITE_ENABLE_QPSG)
  148541. | SQLITE_EnableQPSG
  148542. #endif
  148543. #if defined(SQLITE_DEFAULT_DEFENSIVE)
  148544. | SQLITE_Defensive
  148545. #endif
  148546. ;
  148547. sqlite3HashInit(&db->aCollSeq);
  148548. #ifndef SQLITE_OMIT_VIRTUALTABLE
  148549. sqlite3HashInit(&db->aModule);
  148550. #endif
  148551. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  148552. ** and UTF-16, so add a version for each to avoid any unnecessary
  148553. ** conversions. The only error that can occur here is a malloc() failure.
  148554. **
  148555. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  148556. ** functions:
  148557. */
  148558. createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
  148559. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
  148560. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
  148561. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  148562. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  148563. if( db->mallocFailed ){
  148564. goto opendb_out;
  148565. }
  148566. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  148567. ** strings is BINARY.
  148568. */
  148569. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
  148570. assert( db->pDfltColl!=0 );
  148571. /* Parse the filename/URI argument
  148572. **
  148573. ** Only allow sensible combinations of bits in the flags argument.
  148574. ** Throw an error if any non-sense combination is used. If we
  148575. ** do not block illegal combinations here, it could trigger
  148576. ** assert() statements in deeper layers. Sensible combinations
  148577. ** are:
  148578. **
  148579. ** 1: SQLITE_OPEN_READONLY
  148580. ** 2: SQLITE_OPEN_READWRITE
  148581. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  148582. */
  148583. db->openFlags = flags;
  148584. assert( SQLITE_OPEN_READONLY == 0x01 );
  148585. assert( SQLITE_OPEN_READWRITE == 0x02 );
  148586. assert( SQLITE_OPEN_CREATE == 0x04 );
  148587. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  148588. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  148589. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  148590. if( ((1<<(flags&7)) & 0x46)==0 ){
  148591. rc = SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  148592. }else{
  148593. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  148594. }
  148595. if( rc!=SQLITE_OK ){
  148596. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  148597. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  148598. sqlite3_free(zErrMsg);
  148599. goto opendb_out;
  148600. }
  148601. /* Open the backend database driver */
  148602. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  148603. flags | SQLITE_OPEN_MAIN_DB);
  148604. if( rc!=SQLITE_OK ){
  148605. if( rc==SQLITE_IOERR_NOMEM ){
  148606. rc = SQLITE_NOMEM_BKPT;
  148607. }
  148608. sqlite3Error(db, rc);
  148609. goto opendb_out;
  148610. }
  148611. sqlite3BtreeEnter(db->aDb[0].pBt);
  148612. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  148613. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  148614. sqlite3BtreeLeave(db->aDb[0].pBt);
  148615. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  148616. /* The default safety_level for the main database is FULL; for the temp
  148617. ** database it is OFF. This matches the pager layer defaults.
  148618. */
  148619. db->aDb[0].zDbSName = "main";
  148620. db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  148621. db->aDb[1].zDbSName = "temp";
  148622. db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
  148623. db->magic = SQLITE_MAGIC_OPEN;
  148624. if( db->mallocFailed ){
  148625. goto opendb_out;
  148626. }
  148627. /* Register all built-in functions, but do not attempt to read the
  148628. ** database schema yet. This is delayed until the first time the database
  148629. ** is accessed.
  148630. */
  148631. sqlite3Error(db, SQLITE_OK);
  148632. sqlite3RegisterPerConnectionBuiltinFunctions(db);
  148633. rc = sqlite3_errcode(db);
  148634. #ifdef SQLITE_ENABLE_FTS5
  148635. /* Register any built-in FTS5 module before loading the automatic
  148636. ** extensions. This allows automatic extensions to register FTS5
  148637. ** tokenizers and auxiliary functions. */
  148638. if( !db->mallocFailed && rc==SQLITE_OK ){
  148639. rc = sqlite3Fts5Init(db);
  148640. }
  148641. #endif
  148642. /* Load automatic extensions - extensions that have been registered
  148643. ** using the sqlite3_automatic_extension() API.
  148644. */
  148645. if( rc==SQLITE_OK ){
  148646. sqlite3AutoLoadExtensions(db);
  148647. rc = sqlite3_errcode(db);
  148648. if( rc!=SQLITE_OK ){
  148649. goto opendb_out;
  148650. }
  148651. }
  148652. #ifdef SQLITE_ENABLE_FTS1
  148653. if( !db->mallocFailed ){
  148654. extern int sqlite3Fts1Init(sqlite3*);
  148655. rc = sqlite3Fts1Init(db);
  148656. }
  148657. #endif
  148658. #ifdef SQLITE_ENABLE_FTS2
  148659. if( !db->mallocFailed && rc==SQLITE_OK ){
  148660. extern int sqlite3Fts2Init(sqlite3*);
  148661. rc = sqlite3Fts2Init(db);
  148662. }
  148663. #endif
  148664. #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  148665. if( !db->mallocFailed && rc==SQLITE_OK ){
  148666. rc = sqlite3Fts3Init(db);
  148667. }
  148668. #endif
  148669. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  148670. if( !db->mallocFailed && rc==SQLITE_OK ){
  148671. rc = sqlite3IcuInit(db);
  148672. }
  148673. #endif
  148674. #ifdef SQLITE_ENABLE_RTREE
  148675. if( !db->mallocFailed && rc==SQLITE_OK){
  148676. rc = sqlite3RtreeInit(db);
  148677. }
  148678. #endif
  148679. #ifdef SQLITE_ENABLE_DBPAGE_VTAB
  148680. if( !db->mallocFailed && rc==SQLITE_OK){
  148681. rc = sqlite3DbpageRegister(db);
  148682. }
  148683. #endif
  148684. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  148685. if( !db->mallocFailed && rc==SQLITE_OK){
  148686. rc = sqlite3DbstatRegister(db);
  148687. }
  148688. #endif
  148689. #ifdef SQLITE_ENABLE_JSON1
  148690. if( !db->mallocFailed && rc==SQLITE_OK){
  148691. rc = sqlite3Json1Init(db);
  148692. }
  148693. #endif
  148694. #ifdef SQLITE_ENABLE_STMTVTAB
  148695. if( !db->mallocFailed && rc==SQLITE_OK){
  148696. rc = sqlite3StmtVtabInit(db);
  148697. }
  148698. #endif
  148699. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  148700. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  148701. ** mode. Doing nothing at all also makes NORMAL the default.
  148702. */
  148703. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  148704. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  148705. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  148706. SQLITE_DEFAULT_LOCKING_MODE);
  148707. #endif
  148708. if( rc ) sqlite3Error(db, rc);
  148709. /* Enable the lookaside-malloc subsystem */
  148710. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  148711. sqlite3GlobalConfig.nLookaside);
  148712. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  148713. opendb_out:
  148714. if( db ){
  148715. assert( db->mutex!=0 || isThreadsafe==0
  148716. || sqlite3GlobalConfig.bFullMutex==0 );
  148717. sqlite3_mutex_leave(db->mutex);
  148718. }
  148719. rc = sqlite3_errcode(db);
  148720. assert( db!=0 || rc==SQLITE_NOMEM );
  148721. if( rc==SQLITE_NOMEM ){
  148722. sqlite3_close(db);
  148723. db = 0;
  148724. }else if( rc!=SQLITE_OK ){
  148725. db->magic = SQLITE_MAGIC_SICK;
  148726. }
  148727. *ppDb = db;
  148728. #ifdef SQLITE_ENABLE_SQLLOG
  148729. if( sqlite3GlobalConfig.xSqllog ){
  148730. /* Opening a db handle. Fourth parameter is passed 0. */
  148731. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  148732. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  148733. }
  148734. #endif
  148735. #if defined(SQLITE_HAS_CODEC)
  148736. if( rc==SQLITE_OK ) sqlite3CodecQueryParameters(db, 0, zOpen);
  148737. #endif
  148738. sqlite3_free(zOpen);
  148739. return rc & 0xff;
  148740. }
  148741. /*
  148742. ** Open a new database handle.
  148743. */
  148744. SQLITE_API int sqlite3_open(
  148745. const char *zFilename,
  148746. sqlite3 **ppDb
  148747. ){
  148748. return openDatabase(zFilename, ppDb,
  148749. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  148750. }
  148751. SQLITE_API int sqlite3_open_v2(
  148752. const char *filename, /* Database filename (UTF-8) */
  148753. sqlite3 **ppDb, /* OUT: SQLite db handle */
  148754. int flags, /* Flags */
  148755. const char *zVfs /* Name of VFS module to use */
  148756. ){
  148757. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  148758. }
  148759. #ifndef SQLITE_OMIT_UTF16
  148760. /*
  148761. ** Open a new database handle.
  148762. */
  148763. SQLITE_API int sqlite3_open16(
  148764. const void *zFilename,
  148765. sqlite3 **ppDb
  148766. ){
  148767. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  148768. sqlite3_value *pVal;
  148769. int rc;
  148770. #ifdef SQLITE_ENABLE_API_ARMOR
  148771. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  148772. #endif
  148773. *ppDb = 0;
  148774. #ifndef SQLITE_OMIT_AUTOINIT
  148775. rc = sqlite3_initialize();
  148776. if( rc ) return rc;
  148777. #endif
  148778. if( zFilename==0 ) zFilename = "\000\000";
  148779. pVal = sqlite3ValueNew(0);
  148780. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  148781. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  148782. if( zFilename8 ){
  148783. rc = openDatabase(zFilename8, ppDb,
  148784. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  148785. assert( *ppDb || rc==SQLITE_NOMEM );
  148786. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  148787. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  148788. }
  148789. }else{
  148790. rc = SQLITE_NOMEM_BKPT;
  148791. }
  148792. sqlite3ValueFree(pVal);
  148793. return rc & 0xff;
  148794. }
  148795. #endif /* SQLITE_OMIT_UTF16 */
  148796. /*
  148797. ** Register a new collation sequence with the database handle db.
  148798. */
  148799. SQLITE_API int sqlite3_create_collation(
  148800. sqlite3* db,
  148801. const char *zName,
  148802. int enc,
  148803. void* pCtx,
  148804. int(*xCompare)(void*,int,const void*,int,const void*)
  148805. ){
  148806. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  148807. }
  148808. /*
  148809. ** Register a new collation sequence with the database handle db.
  148810. */
  148811. SQLITE_API int sqlite3_create_collation_v2(
  148812. sqlite3* db,
  148813. const char *zName,
  148814. int enc,
  148815. void* pCtx,
  148816. int(*xCompare)(void*,int,const void*,int,const void*),
  148817. void(*xDel)(void*)
  148818. ){
  148819. int rc;
  148820. #ifdef SQLITE_ENABLE_API_ARMOR
  148821. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  148822. #endif
  148823. sqlite3_mutex_enter(db->mutex);
  148824. assert( !db->mallocFailed );
  148825. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  148826. rc = sqlite3ApiExit(db, rc);
  148827. sqlite3_mutex_leave(db->mutex);
  148828. return rc;
  148829. }
  148830. #ifndef SQLITE_OMIT_UTF16
  148831. /*
  148832. ** Register a new collation sequence with the database handle db.
  148833. */
  148834. SQLITE_API int sqlite3_create_collation16(
  148835. sqlite3* db,
  148836. const void *zName,
  148837. int enc,
  148838. void* pCtx,
  148839. int(*xCompare)(void*,int,const void*,int,const void*)
  148840. ){
  148841. int rc = SQLITE_OK;
  148842. char *zName8;
  148843. #ifdef SQLITE_ENABLE_API_ARMOR
  148844. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  148845. #endif
  148846. sqlite3_mutex_enter(db->mutex);
  148847. assert( !db->mallocFailed );
  148848. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  148849. if( zName8 ){
  148850. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  148851. sqlite3DbFree(db, zName8);
  148852. }
  148853. rc = sqlite3ApiExit(db, rc);
  148854. sqlite3_mutex_leave(db->mutex);
  148855. return rc;
  148856. }
  148857. #endif /* SQLITE_OMIT_UTF16 */
  148858. /*
  148859. ** Register a collation sequence factory callback with the database handle
  148860. ** db. Replace any previously installed collation sequence factory.
  148861. */
  148862. SQLITE_API int sqlite3_collation_needed(
  148863. sqlite3 *db,
  148864. void *pCollNeededArg,
  148865. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  148866. ){
  148867. #ifdef SQLITE_ENABLE_API_ARMOR
  148868. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  148869. #endif
  148870. sqlite3_mutex_enter(db->mutex);
  148871. db->xCollNeeded = xCollNeeded;
  148872. db->xCollNeeded16 = 0;
  148873. db->pCollNeededArg = pCollNeededArg;
  148874. sqlite3_mutex_leave(db->mutex);
  148875. return SQLITE_OK;
  148876. }
  148877. #ifndef SQLITE_OMIT_UTF16
  148878. /*
  148879. ** Register a collation sequence factory callback with the database handle
  148880. ** db. Replace any previously installed collation sequence factory.
  148881. */
  148882. SQLITE_API int sqlite3_collation_needed16(
  148883. sqlite3 *db,
  148884. void *pCollNeededArg,
  148885. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  148886. ){
  148887. #ifdef SQLITE_ENABLE_API_ARMOR
  148888. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  148889. #endif
  148890. sqlite3_mutex_enter(db->mutex);
  148891. db->xCollNeeded = 0;
  148892. db->xCollNeeded16 = xCollNeeded16;
  148893. db->pCollNeededArg = pCollNeededArg;
  148894. sqlite3_mutex_leave(db->mutex);
  148895. return SQLITE_OK;
  148896. }
  148897. #endif /* SQLITE_OMIT_UTF16 */
  148898. #ifndef SQLITE_OMIT_DEPRECATED
  148899. /*
  148900. ** This function is now an anachronism. It used to be used to recover from a
  148901. ** malloc() failure, but SQLite now does this automatically.
  148902. */
  148903. SQLITE_API int sqlite3_global_recover(void){
  148904. return SQLITE_OK;
  148905. }
  148906. #endif
  148907. /*
  148908. ** Test to see whether or not the database connection is in autocommit
  148909. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  148910. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  148911. ** by the next COMMIT or ROLLBACK.
  148912. */
  148913. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  148914. #ifdef SQLITE_ENABLE_API_ARMOR
  148915. if( !sqlite3SafetyCheckOk(db) ){
  148916. (void)SQLITE_MISUSE_BKPT;
  148917. return 0;
  148918. }
  148919. #endif
  148920. return db->autoCommit;
  148921. }
  148922. /*
  148923. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  148924. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
  148925. ** constants. They serve two purposes:
  148926. **
  148927. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  148928. ** to detect when version error conditions occurs.
  148929. **
  148930. ** 2. Invoke sqlite3_log() to provide the source code location where
  148931. ** a low-level error is first detected.
  148932. */
  148933. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){
  148934. sqlite3_log(iErr, "%s at line %d of [%.10s]",
  148935. zType, lineno, 20+sqlite3_sourceid());
  148936. return iErr;
  148937. }
  148938. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  148939. testcase( sqlite3GlobalConfig.xLog!=0 );
  148940. return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
  148941. }
  148942. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  148943. testcase( sqlite3GlobalConfig.xLog!=0 );
  148944. return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
  148945. }
  148946. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  148947. testcase( sqlite3GlobalConfig.xLog!=0 );
  148948. return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
  148949. }
  148950. #ifdef SQLITE_DEBUG
  148951. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
  148952. char zMsg[100];
  148953. sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
  148954. testcase( sqlite3GlobalConfig.xLog!=0 );
  148955. return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  148956. }
  148957. SQLITE_PRIVATE int sqlite3NomemError(int lineno){
  148958. testcase( sqlite3GlobalConfig.xLog!=0 );
  148959. return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
  148960. }
  148961. SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
  148962. testcase( sqlite3GlobalConfig.xLog!=0 );
  148963. return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
  148964. }
  148965. #endif
  148966. #ifndef SQLITE_OMIT_DEPRECATED
  148967. /*
  148968. ** This is a convenience routine that makes sure that all thread-specific
  148969. ** data for this thread has been deallocated.
  148970. **
  148971. ** SQLite no longer uses thread-specific data so this routine is now a
  148972. ** no-op. It is retained for historical compatibility.
  148973. */
  148974. SQLITE_API void sqlite3_thread_cleanup(void){
  148975. }
  148976. #endif
  148977. /*
  148978. ** Return meta information about a specific column of a database table.
  148979. ** See comment in sqlite3.h (sqlite.h.in) for details.
  148980. */
  148981. SQLITE_API int sqlite3_table_column_metadata(
  148982. sqlite3 *db, /* Connection handle */
  148983. const char *zDbName, /* Database name or NULL */
  148984. const char *zTableName, /* Table name */
  148985. const char *zColumnName, /* Column name */
  148986. char const **pzDataType, /* OUTPUT: Declared data type */
  148987. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  148988. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  148989. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  148990. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  148991. ){
  148992. int rc;
  148993. char *zErrMsg = 0;
  148994. Table *pTab = 0;
  148995. Column *pCol = 0;
  148996. int iCol = 0;
  148997. char const *zDataType = 0;
  148998. char const *zCollSeq = 0;
  148999. int notnull = 0;
  149000. int primarykey = 0;
  149001. int autoinc = 0;
  149002. #ifdef SQLITE_ENABLE_API_ARMOR
  149003. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  149004. return SQLITE_MISUSE_BKPT;
  149005. }
  149006. #endif
  149007. /* Ensure the database schema has been loaded */
  149008. sqlite3_mutex_enter(db->mutex);
  149009. sqlite3BtreeEnterAll(db);
  149010. rc = sqlite3Init(db, &zErrMsg);
  149011. if( SQLITE_OK!=rc ){
  149012. goto error_out;
  149013. }
  149014. /* Locate the table in question */
  149015. pTab = sqlite3FindTable(db, zTableName, zDbName);
  149016. if( !pTab || pTab->pSelect ){
  149017. pTab = 0;
  149018. goto error_out;
  149019. }
  149020. /* Find the column for which info is requested */
  149021. if( zColumnName==0 ){
  149022. /* Query for existance of table only */
  149023. }else{
  149024. for(iCol=0; iCol<pTab->nCol; iCol++){
  149025. pCol = &pTab->aCol[iCol];
  149026. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  149027. break;
  149028. }
  149029. }
  149030. if( iCol==pTab->nCol ){
  149031. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  149032. iCol = pTab->iPKey;
  149033. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  149034. }else{
  149035. pTab = 0;
  149036. goto error_out;
  149037. }
  149038. }
  149039. }
  149040. /* The following block stores the meta information that will be returned
  149041. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  149042. ** and autoinc. At this point there are two possibilities:
  149043. **
  149044. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  149045. ** and there is no explicitly declared IPK column.
  149046. **
  149047. ** 2. The table is not a view and the column name identified an
  149048. ** explicitly declared column. Copy meta information from *pCol.
  149049. */
  149050. if( pCol ){
  149051. zDataType = sqlite3ColumnType(pCol,0);
  149052. zCollSeq = pCol->zColl;
  149053. notnull = pCol->notNull!=0;
  149054. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  149055. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  149056. }else{
  149057. zDataType = "INTEGER";
  149058. primarykey = 1;
  149059. }
  149060. if( !zCollSeq ){
  149061. zCollSeq = sqlite3StrBINARY;
  149062. }
  149063. error_out:
  149064. sqlite3BtreeLeaveAll(db);
  149065. /* Whether the function call succeeded or failed, set the output parameters
  149066. ** to whatever their local counterparts contain. If an error did occur,
  149067. ** this has the effect of zeroing all output parameters.
  149068. */
  149069. if( pzDataType ) *pzDataType = zDataType;
  149070. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  149071. if( pNotNull ) *pNotNull = notnull;
  149072. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  149073. if( pAutoinc ) *pAutoinc = autoinc;
  149074. if( SQLITE_OK==rc && !pTab ){
  149075. sqlite3DbFree(db, zErrMsg);
  149076. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  149077. zColumnName);
  149078. rc = SQLITE_ERROR;
  149079. }
  149080. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  149081. sqlite3DbFree(db, zErrMsg);
  149082. rc = sqlite3ApiExit(db, rc);
  149083. sqlite3_mutex_leave(db->mutex);
  149084. return rc;
  149085. }
  149086. /*
  149087. ** Sleep for a little while. Return the amount of time slept.
  149088. */
  149089. SQLITE_API int sqlite3_sleep(int ms){
  149090. sqlite3_vfs *pVfs;
  149091. int rc;
  149092. pVfs = sqlite3_vfs_find(0);
  149093. if( pVfs==0 ) return 0;
  149094. /* This function works in milliseconds, but the underlying OsSleep()
  149095. ** API uses microseconds. Hence the 1000's.
  149096. */
  149097. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  149098. return rc;
  149099. }
  149100. /*
  149101. ** Enable or disable the extended result codes.
  149102. */
  149103. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  149104. #ifdef SQLITE_ENABLE_API_ARMOR
  149105. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  149106. #endif
  149107. sqlite3_mutex_enter(db->mutex);
  149108. db->errMask = onoff ? 0xffffffff : 0xff;
  149109. sqlite3_mutex_leave(db->mutex);
  149110. return SQLITE_OK;
  149111. }
  149112. /*
  149113. ** Invoke the xFileControl method on a particular database.
  149114. */
  149115. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  149116. int rc = SQLITE_ERROR;
  149117. Btree *pBtree;
  149118. #ifdef SQLITE_ENABLE_API_ARMOR
  149119. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  149120. #endif
  149121. sqlite3_mutex_enter(db->mutex);
  149122. pBtree = sqlite3DbNameToBtree(db, zDbName);
  149123. if( pBtree ){
  149124. Pager *pPager;
  149125. sqlite3_file *fd;
  149126. sqlite3BtreeEnter(pBtree);
  149127. pPager = sqlite3BtreePager(pBtree);
  149128. assert( pPager!=0 );
  149129. fd = sqlite3PagerFile(pPager);
  149130. assert( fd!=0 );
  149131. if( op==SQLITE_FCNTL_FILE_POINTER ){
  149132. *(sqlite3_file**)pArg = fd;
  149133. rc = SQLITE_OK;
  149134. }else if( op==SQLITE_FCNTL_VFS_POINTER ){
  149135. *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
  149136. rc = SQLITE_OK;
  149137. }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
  149138. *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
  149139. rc = SQLITE_OK;
  149140. }else if( op==SQLITE_FCNTL_DATA_VERSION ){
  149141. *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
  149142. rc = SQLITE_OK;
  149143. }else{
  149144. rc = sqlite3OsFileControl(fd, op, pArg);
  149145. }
  149146. sqlite3BtreeLeave(pBtree);
  149147. }
  149148. sqlite3_mutex_leave(db->mutex);
  149149. return rc;
  149150. }
  149151. /*
  149152. ** Interface to the testing logic.
  149153. */
  149154. SQLITE_API int sqlite3_test_control(int op, ...){
  149155. int rc = 0;
  149156. #ifdef SQLITE_UNTESTABLE
  149157. UNUSED_PARAMETER(op);
  149158. #else
  149159. va_list ap;
  149160. va_start(ap, op);
  149161. switch( op ){
  149162. /*
  149163. ** Save the current state of the PRNG.
  149164. */
  149165. case SQLITE_TESTCTRL_PRNG_SAVE: {
  149166. sqlite3PrngSaveState();
  149167. break;
  149168. }
  149169. /*
  149170. ** Restore the state of the PRNG to the last state saved using
  149171. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  149172. ** this verb acts like PRNG_RESET.
  149173. */
  149174. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  149175. sqlite3PrngRestoreState();
  149176. break;
  149177. }
  149178. /*
  149179. ** Reset the PRNG back to its uninitialized state. The next call
  149180. ** to sqlite3_randomness() will reseed the PRNG using a single call
  149181. ** to the xRandomness method of the default VFS.
  149182. */
  149183. case SQLITE_TESTCTRL_PRNG_RESET: {
  149184. sqlite3_randomness(0,0);
  149185. break;
  149186. }
  149187. /*
  149188. ** sqlite3_test_control(BITVEC_TEST, size, program)
  149189. **
  149190. ** Run a test against a Bitvec object of size. The program argument
  149191. ** is an array of integers that defines the test. Return -1 on a
  149192. ** memory allocation error, 0 on success, or non-zero for an error.
  149193. ** See the sqlite3BitvecBuiltinTest() for additional information.
  149194. */
  149195. case SQLITE_TESTCTRL_BITVEC_TEST: {
  149196. int sz = va_arg(ap, int);
  149197. int *aProg = va_arg(ap, int*);
  149198. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  149199. break;
  149200. }
  149201. /*
  149202. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  149203. **
  149204. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  149205. ** if xCallback is not NULL.
  149206. **
  149207. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  149208. ** is called immediately after installing the new callback and the return
  149209. ** value from sqlite3FaultSim(0) becomes the return from
  149210. ** sqlite3_test_control().
  149211. */
  149212. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  149213. /* MSVC is picky about pulling func ptrs from va lists.
  149214. ** http://support.microsoft.com/kb/47961
  149215. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  149216. */
  149217. typedef int(*TESTCALLBACKFUNC_t)(int);
  149218. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  149219. rc = sqlite3FaultSim(0);
  149220. break;
  149221. }
  149222. /*
  149223. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  149224. **
  149225. ** Register hooks to call to indicate which malloc() failures
  149226. ** are benign.
  149227. */
  149228. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  149229. typedef void (*void_function)(void);
  149230. void_function xBenignBegin;
  149231. void_function xBenignEnd;
  149232. xBenignBegin = va_arg(ap, void_function);
  149233. xBenignEnd = va_arg(ap, void_function);
  149234. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  149235. break;
  149236. }
  149237. /*
  149238. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  149239. **
  149240. ** Set the PENDING byte to the value in the argument, if X>0.
  149241. ** Make no changes if X==0. Return the value of the pending byte
  149242. ** as it existing before this routine was called.
  149243. **
  149244. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  149245. ** an incompatible database file format. Changing the PENDING byte
  149246. ** while any database connection is open results in undefined and
  149247. ** deleterious behavior.
  149248. */
  149249. case SQLITE_TESTCTRL_PENDING_BYTE: {
  149250. rc = PENDING_BYTE;
  149251. #ifndef SQLITE_OMIT_WSD
  149252. {
  149253. unsigned int newVal = va_arg(ap, unsigned int);
  149254. if( newVal ) sqlite3PendingByte = newVal;
  149255. }
  149256. #endif
  149257. break;
  149258. }
  149259. /*
  149260. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  149261. **
  149262. ** This action provides a run-time test to see whether or not
  149263. ** assert() was enabled at compile-time. If X is true and assert()
  149264. ** is enabled, then the return value is true. If X is true and
  149265. ** assert() is disabled, then the return value is zero. If X is
  149266. ** false and assert() is enabled, then the assertion fires and the
  149267. ** process aborts. If X is false and assert() is disabled, then the
  149268. ** return value is zero.
  149269. */
  149270. case SQLITE_TESTCTRL_ASSERT: {
  149271. volatile int x = 0;
  149272. assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
  149273. rc = x;
  149274. break;
  149275. }
  149276. /*
  149277. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  149278. **
  149279. ** This action provides a run-time test to see how the ALWAYS and
  149280. ** NEVER macros were defined at compile-time.
  149281. **
  149282. ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
  149283. **
  149284. ** The recommended test is X==2. If the return value is 2, that means
  149285. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  149286. ** default setting. If the return value is 1, then ALWAYS() is either
  149287. ** hard-coded to true or else it asserts if its argument is false.
  149288. ** The first behavior (hard-coded to true) is the case if
  149289. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  149290. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  149291. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  149292. **
  149293. ** The run-time test procedure might look something like this:
  149294. **
  149295. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  149296. ** // ALWAYS() and NEVER() are no-op pass-through macros
  149297. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  149298. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  149299. ** }else{
  149300. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  149301. ** }
  149302. */
  149303. case SQLITE_TESTCTRL_ALWAYS: {
  149304. int x = va_arg(ap,int);
  149305. rc = x ? ALWAYS(x) : 0;
  149306. break;
  149307. }
  149308. /*
  149309. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  149310. **
  149311. ** The integer returned reveals the byte-order of the computer on which
  149312. ** SQLite is running:
  149313. **
  149314. ** 1 big-endian, determined at run-time
  149315. ** 10 little-endian, determined at run-time
  149316. ** 432101 big-endian, determined at compile-time
  149317. ** 123410 little-endian, determined at compile-time
  149318. */
  149319. case SQLITE_TESTCTRL_BYTEORDER: {
  149320. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  149321. break;
  149322. }
  149323. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  149324. **
  149325. ** Set the nReserve size to N for the main database on the database
  149326. ** connection db.
  149327. */
  149328. case SQLITE_TESTCTRL_RESERVE: {
  149329. sqlite3 *db = va_arg(ap, sqlite3*);
  149330. int x = va_arg(ap,int);
  149331. sqlite3_mutex_enter(db->mutex);
  149332. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  149333. sqlite3_mutex_leave(db->mutex);
  149334. break;
  149335. }
  149336. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  149337. **
  149338. ** Enable or disable various optimizations for testing purposes. The
  149339. ** argument N is a bitmask of optimizations to be disabled. For normal
  149340. ** operation N should be 0. The idea is that a test program (like the
  149341. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  149342. ** with various optimizations disabled to verify that the same answer
  149343. ** is obtained in every case.
  149344. */
  149345. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  149346. sqlite3 *db = va_arg(ap, sqlite3*);
  149347. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  149348. break;
  149349. }
  149350. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  149351. **
  149352. ** If parameter onoff is non-zero, subsequent calls to localtime()
  149353. ** and its variants fail. If onoff is zero, undo this setting.
  149354. */
  149355. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  149356. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  149357. break;
  149358. }
  149359. /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCS, int onoff);
  149360. **
  149361. ** If parameter onoff is non-zero, internal-use-only SQL functions
  149362. ** are visible to ordinary SQL. This is useful for testing but is
  149363. ** unsafe because invalid parameters to those internal-use-only functions
  149364. ** can result in crashes or segfaults.
  149365. */
  149366. case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
  149367. sqlite3GlobalConfig.bInternalFunctions = va_arg(ap, int);
  149368. break;
  149369. }
  149370. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  149371. **
  149372. ** Set or clear a flag that indicates that the database file is always well-
  149373. ** formed and never corrupt. This flag is clear by default, indicating that
  149374. ** database files might have arbitrary corruption. Setting the flag during
  149375. ** testing causes certain assert() statements in the code to be activated
  149376. ** that demonstrat invariants on well-formed database files.
  149377. */
  149378. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  149379. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  149380. break;
  149381. }
  149382. /* Set the threshold at which OP_Once counters reset back to zero.
  149383. ** By default this is 0x7ffffffe (over 2 billion), but that value is
  149384. ** too big to test in a reasonable amount of time, so this control is
  149385. ** provided to set a small and easily reachable reset value.
  149386. */
  149387. case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
  149388. sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
  149389. break;
  149390. }
  149391. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  149392. **
  149393. ** Set the VDBE coverage callback function to xCallback with context
  149394. ** pointer ptr.
  149395. */
  149396. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  149397. #ifdef SQLITE_VDBE_COVERAGE
  149398. typedef void (*branch_callback)(void*,unsigned int,
  149399. unsigned char,unsigned char);
  149400. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  149401. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  149402. #endif
  149403. break;
  149404. }
  149405. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  149406. case SQLITE_TESTCTRL_SORTER_MMAP: {
  149407. sqlite3 *db = va_arg(ap, sqlite3*);
  149408. db->nMaxSorterMmap = va_arg(ap, int);
  149409. break;
  149410. }
  149411. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  149412. **
  149413. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  149414. ** not.
  149415. */
  149416. case SQLITE_TESTCTRL_ISINIT: {
  149417. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  149418. break;
  149419. }
  149420. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  149421. **
  149422. ** This test control is used to create imposter tables. "db" is a pointer
  149423. ** to the database connection. dbName is the database name (ex: "main" or
  149424. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  149425. ** or off. "tnum" is the root page of the b-tree to which the imposter
  149426. ** table should connect.
  149427. **
  149428. ** Enable imposter mode only when the schema has already been parsed. Then
  149429. ** run a single CREATE TABLE statement to construct the imposter table in
  149430. ** the parsed schema. Then turn imposter mode back off again.
  149431. **
  149432. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  149433. ** the schema to be reparsed the next time it is needed. This has the
  149434. ** effect of erasing all imposter tables.
  149435. */
  149436. case SQLITE_TESTCTRL_IMPOSTER: {
  149437. sqlite3 *db = va_arg(ap, sqlite3*);
  149438. sqlite3_mutex_enter(db->mutex);
  149439. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  149440. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  149441. db->init.newTnum = va_arg(ap,int);
  149442. if( db->init.busy==0 && db->init.newTnum>0 ){
  149443. sqlite3ResetAllSchemasOfConnection(db);
  149444. }
  149445. sqlite3_mutex_leave(db->mutex);
  149446. break;
  149447. }
  149448. #if defined(YYCOVERAGE)
  149449. /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
  149450. **
  149451. ** This test control (only available when SQLite is compiled with
  149452. ** -DYYCOVERAGE) writes a report onto "out" that shows all
  149453. ** state/lookahead combinations in the parser state machine
  149454. ** which are never exercised. If any state is missed, make the
  149455. ** return code SQLITE_ERROR.
  149456. */
  149457. case SQLITE_TESTCTRL_PARSER_COVERAGE: {
  149458. FILE *out = va_arg(ap, FILE*);
  149459. if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
  149460. break;
  149461. }
  149462. #endif /* defined(YYCOVERAGE) */
  149463. }
  149464. va_end(ap);
  149465. #endif /* SQLITE_UNTESTABLE */
  149466. return rc;
  149467. }
  149468. /*
  149469. ** This is a utility routine, useful to VFS implementations, that checks
  149470. ** to see if a database file was a URI that contained a specific query
  149471. ** parameter, and if so obtains the value of the query parameter.
  149472. **
  149473. ** The zFilename argument is the filename pointer passed into the xOpen()
  149474. ** method of a VFS implementation. The zParam argument is the name of the
  149475. ** query parameter we seek. This routine returns the value of the zParam
  149476. ** parameter if it exists. If the parameter does not exist, this routine
  149477. ** returns a NULL pointer.
  149478. */
  149479. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  149480. if( zFilename==0 || zParam==0 ) return 0;
  149481. zFilename += sqlite3Strlen30(zFilename) + 1;
  149482. while( zFilename[0] ){
  149483. int x = strcmp(zFilename, zParam);
  149484. zFilename += sqlite3Strlen30(zFilename) + 1;
  149485. if( x==0 ) return zFilename;
  149486. zFilename += sqlite3Strlen30(zFilename) + 1;
  149487. }
  149488. return 0;
  149489. }
  149490. /*
  149491. ** Return a boolean value for a query parameter.
  149492. */
  149493. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  149494. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  149495. bDflt = bDflt!=0;
  149496. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  149497. }
  149498. /*
  149499. ** Return a 64-bit integer value for a query parameter.
  149500. */
  149501. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  149502. const char *zFilename, /* Filename as passed to xOpen */
  149503. const char *zParam, /* URI parameter sought */
  149504. sqlite3_int64 bDflt /* return if parameter is missing */
  149505. ){
  149506. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  149507. sqlite3_int64 v;
  149508. if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
  149509. bDflt = v;
  149510. }
  149511. return bDflt;
  149512. }
  149513. /*
  149514. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  149515. */
  149516. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  149517. int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
  149518. return iDb<0 ? 0 : db->aDb[iDb].pBt;
  149519. }
  149520. /*
  149521. ** Return the filename of the database associated with a database
  149522. ** connection.
  149523. */
  149524. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  149525. Btree *pBt;
  149526. #ifdef SQLITE_ENABLE_API_ARMOR
  149527. if( !sqlite3SafetyCheckOk(db) ){
  149528. (void)SQLITE_MISUSE_BKPT;
  149529. return 0;
  149530. }
  149531. #endif
  149532. pBt = sqlite3DbNameToBtree(db, zDbName);
  149533. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  149534. }
  149535. /*
  149536. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  149537. ** no such database exists.
  149538. */
  149539. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  149540. Btree *pBt;
  149541. #ifdef SQLITE_ENABLE_API_ARMOR
  149542. if( !sqlite3SafetyCheckOk(db) ){
  149543. (void)SQLITE_MISUSE_BKPT;
  149544. return -1;
  149545. }
  149546. #endif
  149547. pBt = sqlite3DbNameToBtree(db, zDbName);
  149548. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  149549. }
  149550. #ifdef SQLITE_ENABLE_SNAPSHOT
  149551. /*
  149552. ** Obtain a snapshot handle for the snapshot of database zDb currently
  149553. ** being read by handle db.
  149554. */
  149555. SQLITE_API int sqlite3_snapshot_get(
  149556. sqlite3 *db,
  149557. const char *zDb,
  149558. sqlite3_snapshot **ppSnapshot
  149559. ){
  149560. int rc = SQLITE_ERROR;
  149561. #ifndef SQLITE_OMIT_WAL
  149562. #ifdef SQLITE_ENABLE_API_ARMOR
  149563. if( !sqlite3SafetyCheckOk(db) ){
  149564. return SQLITE_MISUSE_BKPT;
  149565. }
  149566. #endif
  149567. sqlite3_mutex_enter(db->mutex);
  149568. if( db->autoCommit==0 ){
  149569. int iDb = sqlite3FindDbName(db, zDb);
  149570. if( iDb==0 || iDb>1 ){
  149571. Btree *pBt = db->aDb[iDb].pBt;
  149572. if( 0==sqlite3BtreeIsInTrans(pBt) ){
  149573. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  149574. if( rc==SQLITE_OK ){
  149575. rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
  149576. }
  149577. }
  149578. }
  149579. }
  149580. sqlite3_mutex_leave(db->mutex);
  149581. #endif /* SQLITE_OMIT_WAL */
  149582. return rc;
  149583. }
  149584. /*
  149585. ** Open a read-transaction on the snapshot idendified by pSnapshot.
  149586. */
  149587. SQLITE_API int sqlite3_snapshot_open(
  149588. sqlite3 *db,
  149589. const char *zDb,
  149590. sqlite3_snapshot *pSnapshot
  149591. ){
  149592. int rc = SQLITE_ERROR;
  149593. #ifndef SQLITE_OMIT_WAL
  149594. #ifdef SQLITE_ENABLE_API_ARMOR
  149595. if( !sqlite3SafetyCheckOk(db) ){
  149596. return SQLITE_MISUSE_BKPT;
  149597. }
  149598. #endif
  149599. sqlite3_mutex_enter(db->mutex);
  149600. if( db->autoCommit==0 ){
  149601. int iDb;
  149602. iDb = sqlite3FindDbName(db, zDb);
  149603. if( iDb==0 || iDb>1 ){
  149604. Btree *pBt = db->aDb[iDb].pBt;
  149605. if( sqlite3BtreeIsInTrans(pBt)==0 ){
  149606. Pager *pPager = sqlite3BtreePager(pBt);
  149607. int bUnlock = 0;
  149608. if( sqlite3BtreeIsInReadTrans(pBt) ){
  149609. if( db->nVdbeActive==0 ){
  149610. rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
  149611. if( rc==SQLITE_OK ){
  149612. bUnlock = 1;
  149613. rc = sqlite3BtreeCommit(pBt);
  149614. }
  149615. }
  149616. }else{
  149617. rc = SQLITE_OK;
  149618. }
  149619. if( rc==SQLITE_OK ){
  149620. rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
  149621. }
  149622. if( rc==SQLITE_OK ){
  149623. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  149624. sqlite3PagerSnapshotOpen(pPager, 0);
  149625. }
  149626. if( bUnlock ){
  149627. sqlite3PagerSnapshotUnlock(pPager);
  149628. }
  149629. }
  149630. }
  149631. }
  149632. sqlite3_mutex_leave(db->mutex);
  149633. #endif /* SQLITE_OMIT_WAL */
  149634. return rc;
  149635. }
  149636. /*
  149637. ** Recover as many snapshots as possible from the wal file associated with
  149638. ** schema zDb of database db.
  149639. */
  149640. SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
  149641. int rc = SQLITE_ERROR;
  149642. int iDb;
  149643. #ifndef SQLITE_OMIT_WAL
  149644. #ifdef SQLITE_ENABLE_API_ARMOR
  149645. if( !sqlite3SafetyCheckOk(db) ){
  149646. return SQLITE_MISUSE_BKPT;
  149647. }
  149648. #endif
  149649. sqlite3_mutex_enter(db->mutex);
  149650. iDb = sqlite3FindDbName(db, zDb);
  149651. if( iDb==0 || iDb>1 ){
  149652. Btree *pBt = db->aDb[iDb].pBt;
  149653. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  149654. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  149655. if( rc==SQLITE_OK ){
  149656. rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
  149657. sqlite3BtreeCommit(pBt);
  149658. }
  149659. }
  149660. }
  149661. sqlite3_mutex_leave(db->mutex);
  149662. #endif /* SQLITE_OMIT_WAL */
  149663. return rc;
  149664. }
  149665. /*
  149666. ** Free a snapshot handle obtained from sqlite3_snapshot_get().
  149667. */
  149668. SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
  149669. sqlite3_free(pSnapshot);
  149670. }
  149671. #endif /* SQLITE_ENABLE_SNAPSHOT */
  149672. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  149673. /*
  149674. ** Given the name of a compile-time option, return true if that option
  149675. ** was used and false if not.
  149676. **
  149677. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  149678. ** is not required for a match.
  149679. */
  149680. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  149681. int i, n;
  149682. int nOpt;
  149683. const char **azCompileOpt;
  149684. #if SQLITE_ENABLE_API_ARMOR
  149685. if( zOptName==0 ){
  149686. (void)SQLITE_MISUSE_BKPT;
  149687. return 0;
  149688. }
  149689. #endif
  149690. azCompileOpt = sqlite3CompileOptions(&nOpt);
  149691. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  149692. n = sqlite3Strlen30(zOptName);
  149693. /* Since nOpt is normally in single digits, a linear search is
  149694. ** adequate. No need for a binary search. */
  149695. for(i=0; i<nOpt; i++){
  149696. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  149697. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  149698. ){
  149699. return 1;
  149700. }
  149701. }
  149702. return 0;
  149703. }
  149704. /*
  149705. ** Return the N-th compile-time option string. If N is out of range,
  149706. ** return a NULL pointer.
  149707. */
  149708. SQLITE_API const char *sqlite3_compileoption_get(int N){
  149709. int nOpt;
  149710. const char **azCompileOpt;
  149711. azCompileOpt = sqlite3CompileOptions(&nOpt);
  149712. if( N>=0 && N<nOpt ){
  149713. return azCompileOpt[N];
  149714. }
  149715. return 0;
  149716. }
  149717. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  149718. /************** End of main.c ************************************************/
  149719. /************** Begin file notify.c ******************************************/
  149720. /*
  149721. ** 2009 March 3
  149722. **
  149723. ** The author disclaims copyright to this source code. In place of
  149724. ** a legal notice, here is a blessing:
  149725. **
  149726. ** May you do good and not evil.
  149727. ** May you find forgiveness for yourself and forgive others.
  149728. ** May you share freely, never taking more than you give.
  149729. **
  149730. *************************************************************************
  149731. **
  149732. ** This file contains the implementation of the sqlite3_unlock_notify()
  149733. ** API method and its associated functionality.
  149734. */
  149735. /* #include "sqliteInt.h" */
  149736. /* #include "btreeInt.h" */
  149737. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  149738. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  149739. /*
  149740. ** Public interfaces:
  149741. **
  149742. ** sqlite3ConnectionBlocked()
  149743. ** sqlite3ConnectionUnlocked()
  149744. ** sqlite3ConnectionClosed()
  149745. ** sqlite3_unlock_notify()
  149746. */
  149747. #define assertMutexHeld() \
  149748. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  149749. /*
  149750. ** Head of a linked list of all sqlite3 objects created by this process
  149751. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  149752. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  149753. ** mutex is held.
  149754. */
  149755. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  149756. #ifndef NDEBUG
  149757. /*
  149758. ** This function is a complex assert() that verifies the following
  149759. ** properties of the blocked connections list:
  149760. **
  149761. ** 1) Each entry in the list has a non-NULL value for either
  149762. ** pUnlockConnection or pBlockingConnection, or both.
  149763. **
  149764. ** 2) All entries in the list that share a common value for
  149765. ** xUnlockNotify are grouped together.
  149766. **
  149767. ** 3) If the argument db is not NULL, then none of the entries in the
  149768. ** blocked connections list have pUnlockConnection or pBlockingConnection
  149769. ** set to db. This is used when closing connection db.
  149770. */
  149771. static void checkListProperties(sqlite3 *db){
  149772. sqlite3 *p;
  149773. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  149774. int seen = 0;
  149775. sqlite3 *p2;
  149776. /* Verify property (1) */
  149777. assert( p->pUnlockConnection || p->pBlockingConnection );
  149778. /* Verify property (2) */
  149779. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  149780. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  149781. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  149782. assert( db==0 || p->pUnlockConnection!=db );
  149783. assert( db==0 || p->pBlockingConnection!=db );
  149784. }
  149785. }
  149786. }
  149787. #else
  149788. # define checkListProperties(x)
  149789. #endif
  149790. /*
  149791. ** Remove connection db from the blocked connections list. If connection
  149792. ** db is not currently a part of the list, this function is a no-op.
  149793. */
  149794. static void removeFromBlockedList(sqlite3 *db){
  149795. sqlite3 **pp;
  149796. assertMutexHeld();
  149797. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  149798. if( *pp==db ){
  149799. *pp = (*pp)->pNextBlocked;
  149800. break;
  149801. }
  149802. }
  149803. }
  149804. /*
  149805. ** Add connection db to the blocked connections list. It is assumed
  149806. ** that it is not already a part of the list.
  149807. */
  149808. static void addToBlockedList(sqlite3 *db){
  149809. sqlite3 **pp;
  149810. assertMutexHeld();
  149811. for(
  149812. pp=&sqlite3BlockedList;
  149813. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  149814. pp=&(*pp)->pNextBlocked
  149815. );
  149816. db->pNextBlocked = *pp;
  149817. *pp = db;
  149818. }
  149819. /*
  149820. ** Obtain the STATIC_MASTER mutex.
  149821. */
  149822. static void enterMutex(void){
  149823. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  149824. checkListProperties(0);
  149825. }
  149826. /*
  149827. ** Release the STATIC_MASTER mutex.
  149828. */
  149829. static void leaveMutex(void){
  149830. assertMutexHeld();
  149831. checkListProperties(0);
  149832. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  149833. }
  149834. /*
  149835. ** Register an unlock-notify callback.
  149836. **
  149837. ** This is called after connection "db" has attempted some operation
  149838. ** but has received an SQLITE_LOCKED error because another connection
  149839. ** (call it pOther) in the same process was busy using the same shared
  149840. ** cache. pOther is found by looking at db->pBlockingConnection.
  149841. **
  149842. ** If there is no blocking connection, the callback is invoked immediately,
  149843. ** before this routine returns.
  149844. **
  149845. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  149846. ** a deadlock.
  149847. **
  149848. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  149849. ** its locks.
  149850. **
  149851. ** Each call to this routine overrides any prior callbacks registered
  149852. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  149853. ** cancelled.
  149854. */
  149855. SQLITE_API int sqlite3_unlock_notify(
  149856. sqlite3 *db,
  149857. void (*xNotify)(void **, int),
  149858. void *pArg
  149859. ){
  149860. int rc = SQLITE_OK;
  149861. sqlite3_mutex_enter(db->mutex);
  149862. enterMutex();
  149863. if( xNotify==0 ){
  149864. removeFromBlockedList(db);
  149865. db->pBlockingConnection = 0;
  149866. db->pUnlockConnection = 0;
  149867. db->xUnlockNotify = 0;
  149868. db->pUnlockArg = 0;
  149869. }else if( 0==db->pBlockingConnection ){
  149870. /* The blocking transaction has been concluded. Or there never was a
  149871. ** blocking transaction. In either case, invoke the notify callback
  149872. ** immediately.
  149873. */
  149874. xNotify(&pArg, 1);
  149875. }else{
  149876. sqlite3 *p;
  149877. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  149878. if( p ){
  149879. rc = SQLITE_LOCKED; /* Deadlock detected. */
  149880. }else{
  149881. db->pUnlockConnection = db->pBlockingConnection;
  149882. db->xUnlockNotify = xNotify;
  149883. db->pUnlockArg = pArg;
  149884. removeFromBlockedList(db);
  149885. addToBlockedList(db);
  149886. }
  149887. }
  149888. leaveMutex();
  149889. assert( !db->mallocFailed );
  149890. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  149891. sqlite3_mutex_leave(db->mutex);
  149892. return rc;
  149893. }
  149894. /*
  149895. ** This function is called while stepping or preparing a statement
  149896. ** associated with connection db. The operation will return SQLITE_LOCKED
  149897. ** to the user because it requires a lock that will not be available
  149898. ** until connection pBlocker concludes its current transaction.
  149899. */
  149900. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  149901. enterMutex();
  149902. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  149903. addToBlockedList(db);
  149904. }
  149905. db->pBlockingConnection = pBlocker;
  149906. leaveMutex();
  149907. }
  149908. /*
  149909. ** This function is called when
  149910. ** the transaction opened by database db has just finished. Locks held
  149911. ** by database connection db have been released.
  149912. **
  149913. ** This function loops through each entry in the blocked connections
  149914. ** list and does the following:
  149915. **
  149916. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  149917. ** set to db, then set pBlockingConnection=0.
  149918. **
  149919. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  149920. ** set to db, then invoke the configured unlock-notify callback and
  149921. ** set pUnlockConnection=0.
  149922. **
  149923. ** 3) If the two steps above mean that pBlockingConnection==0 and
  149924. ** pUnlockConnection==0, remove the entry from the blocked connections
  149925. ** list.
  149926. */
  149927. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  149928. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  149929. int nArg = 0; /* Number of entries in aArg[] */
  149930. sqlite3 **pp; /* Iterator variable */
  149931. void **aArg; /* Arguments to the unlock callback */
  149932. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  149933. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  149934. aArg = aStatic;
  149935. enterMutex(); /* Enter STATIC_MASTER mutex */
  149936. /* This loop runs once for each entry in the blocked-connections list. */
  149937. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  149938. sqlite3 *p = *pp;
  149939. /* Step 1. */
  149940. if( p->pBlockingConnection==db ){
  149941. p->pBlockingConnection = 0;
  149942. }
  149943. /* Step 2. */
  149944. if( p->pUnlockConnection==db ){
  149945. assert( p->xUnlockNotify );
  149946. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  149947. xUnlockNotify(aArg, nArg);
  149948. nArg = 0;
  149949. }
  149950. sqlite3BeginBenignMalloc();
  149951. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  149952. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  149953. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  149954. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  149955. ){
  149956. /* The aArg[] array needs to grow. */
  149957. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  149958. if( pNew ){
  149959. memcpy(pNew, aArg, nArg*sizeof(void *));
  149960. sqlite3_free(aDyn);
  149961. aDyn = aArg = pNew;
  149962. }else{
  149963. /* This occurs when the array of context pointers that need to
  149964. ** be passed to the unlock-notify callback is larger than the
  149965. ** aStatic[] array allocated on the stack and the attempt to
  149966. ** allocate a larger array from the heap has failed.
  149967. **
  149968. ** This is a difficult situation to handle. Returning an error
  149969. ** code to the caller is insufficient, as even if an error code
  149970. ** is returned the transaction on connection db will still be
  149971. ** closed and the unlock-notify callbacks on blocked connections
  149972. ** will go unissued. This might cause the application to wait
  149973. ** indefinitely for an unlock-notify callback that will never
  149974. ** arrive.
  149975. **
  149976. ** Instead, invoke the unlock-notify callback with the context
  149977. ** array already accumulated. We can then clear the array and
  149978. ** begin accumulating any further context pointers without
  149979. ** requiring any dynamic allocation. This is sub-optimal because
  149980. ** it means that instead of one callback with a large array of
  149981. ** context pointers the application will receive two or more
  149982. ** callbacks with smaller arrays of context pointers, which will
  149983. ** reduce the applications ability to prioritize multiple
  149984. ** connections. But it is the best that can be done under the
  149985. ** circumstances.
  149986. */
  149987. xUnlockNotify(aArg, nArg);
  149988. nArg = 0;
  149989. }
  149990. }
  149991. sqlite3EndBenignMalloc();
  149992. aArg[nArg++] = p->pUnlockArg;
  149993. xUnlockNotify = p->xUnlockNotify;
  149994. p->pUnlockConnection = 0;
  149995. p->xUnlockNotify = 0;
  149996. p->pUnlockArg = 0;
  149997. }
  149998. /* Step 3. */
  149999. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  150000. /* Remove connection p from the blocked connections list. */
  150001. *pp = p->pNextBlocked;
  150002. p->pNextBlocked = 0;
  150003. }else{
  150004. pp = &p->pNextBlocked;
  150005. }
  150006. }
  150007. if( nArg!=0 ){
  150008. xUnlockNotify(aArg, nArg);
  150009. }
  150010. sqlite3_free(aDyn);
  150011. leaveMutex(); /* Leave STATIC_MASTER mutex */
  150012. }
  150013. /*
  150014. ** This is called when the database connection passed as an argument is
  150015. ** being closed. The connection is removed from the blocked list.
  150016. */
  150017. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  150018. sqlite3ConnectionUnlocked(db);
  150019. enterMutex();
  150020. removeFromBlockedList(db);
  150021. checkListProperties(db);
  150022. leaveMutex();
  150023. }
  150024. #endif
  150025. /************** End of notify.c **********************************************/
  150026. /************** Begin file fts3.c ********************************************/
  150027. /*
  150028. ** 2006 Oct 10
  150029. **
  150030. ** The author disclaims copyright to this source code. In place of
  150031. ** a legal notice, here is a blessing:
  150032. **
  150033. ** May you do good and not evil.
  150034. ** May you find forgiveness for yourself and forgive others.
  150035. ** May you share freely, never taking more than you give.
  150036. **
  150037. ******************************************************************************
  150038. **
  150039. ** This is an SQLite module implementing full-text search.
  150040. */
  150041. /*
  150042. ** The code in this file is only compiled if:
  150043. **
  150044. ** * The FTS3 module is being built as an extension
  150045. ** (in which case SQLITE_CORE is not defined), or
  150046. **
  150047. ** * The FTS3 module is being built into the core of
  150048. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  150049. */
  150050. /* The full-text index is stored in a series of b+tree (-like)
  150051. ** structures called segments which map terms to doclists. The
  150052. ** structures are like b+trees in layout, but are constructed from the
  150053. ** bottom up in optimal fashion and are not updatable. Since trees
  150054. ** are built from the bottom up, things will be described from the
  150055. ** bottom up.
  150056. **
  150057. **
  150058. **** Varints ****
  150059. ** The basic unit of encoding is a variable-length integer called a
  150060. ** varint. We encode variable-length integers in little-endian order
  150061. ** using seven bits * per byte as follows:
  150062. **
  150063. ** KEY:
  150064. ** A = 0xxxxxxx 7 bits of data and one flag bit
  150065. ** B = 1xxxxxxx 7 bits of data and one flag bit
  150066. **
  150067. ** 7 bits - A
  150068. ** 14 bits - BA
  150069. ** 21 bits - BBA
  150070. ** and so on.
  150071. **
  150072. ** This is similar in concept to how sqlite encodes "varints" but
  150073. ** the encoding is not the same. SQLite varints are big-endian
  150074. ** are are limited to 9 bytes in length whereas FTS3 varints are
  150075. ** little-endian and can be up to 10 bytes in length (in theory).
  150076. **
  150077. ** Example encodings:
  150078. **
  150079. ** 1: 0x01
  150080. ** 127: 0x7f
  150081. ** 128: 0x81 0x00
  150082. **
  150083. **
  150084. **** Document lists ****
  150085. ** A doclist (document list) holds a docid-sorted list of hits for a
  150086. ** given term. Doclists hold docids and associated token positions.
  150087. ** A docid is the unique integer identifier for a single document.
  150088. ** A position is the index of a word within the document. The first
  150089. ** word of the document has a position of 0.
  150090. **
  150091. ** FTS3 used to optionally store character offsets using a compile-time
  150092. ** option. But that functionality is no longer supported.
  150093. **
  150094. ** A doclist is stored like this:
  150095. **
  150096. ** array {
  150097. ** varint docid; (delta from previous doclist)
  150098. ** array { (position list for column 0)
  150099. ** varint position; (2 more than the delta from previous position)
  150100. ** }
  150101. ** array {
  150102. ** varint POS_COLUMN; (marks start of position list for new column)
  150103. ** varint column; (index of new column)
  150104. ** array {
  150105. ** varint position; (2 more than the delta from previous position)
  150106. ** }
  150107. ** }
  150108. ** varint POS_END; (marks end of positions for this document.
  150109. ** }
  150110. **
  150111. ** Here, array { X } means zero or more occurrences of X, adjacent in
  150112. ** memory. A "position" is an index of a token in the token stream
  150113. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  150114. ** in the same logical place as the position element, and act as sentinals
  150115. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  150116. ** The positions numbers are not stored literally but rather as two more
  150117. ** than the difference from the prior position, or the just the position plus
  150118. ** 2 for the first position. Example:
  150119. **
  150120. ** label: A B C D E F G H I J K
  150121. ** value: 123 5 9 1 1 14 35 0 234 72 0
  150122. **
  150123. ** The 123 value is the first docid. For column zero in this document
  150124. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  150125. ** at D signals the start of a new column; the 1 at E indicates that the
  150126. ** new column is column number 1. There are two positions at 12 and 45
  150127. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  150128. ** 234 at I is the delta to next docid (357). It has one position 70
  150129. ** (72-2) and then terminates with the 0 at K.
  150130. **
  150131. ** A "position-list" is the list of positions for multiple columns for
  150132. ** a single docid. A "column-list" is the set of positions for a single
  150133. ** column. Hence, a position-list consists of one or more column-lists,
  150134. ** a document record consists of a docid followed by a position-list and
  150135. ** a doclist consists of one or more document records.
  150136. **
  150137. ** A bare doclist omits the position information, becoming an
  150138. ** array of varint-encoded docids.
  150139. **
  150140. **** Segment leaf nodes ****
  150141. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  150142. ** nodes are written using LeafWriter, and read using LeafReader (to
  150143. ** iterate through a single leaf node's data) and LeavesReader (to
  150144. ** iterate through a segment's entire leaf layer). Leaf nodes have
  150145. ** the format:
  150146. **
  150147. ** varint iHeight; (height from leaf level, always 0)
  150148. ** varint nTerm; (length of first term)
  150149. ** char pTerm[nTerm]; (content of first term)
  150150. ** varint nDoclist; (length of term's associated doclist)
  150151. ** char pDoclist[nDoclist]; (content of doclist)
  150152. ** array {
  150153. ** (further terms are delta-encoded)
  150154. ** varint nPrefix; (length of prefix shared with previous term)
  150155. ** varint nSuffix; (length of unshared suffix)
  150156. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  150157. ** varint nDoclist; (length of term's associated doclist)
  150158. ** char pDoclist[nDoclist]; (content of doclist)
  150159. ** }
  150160. **
  150161. ** Here, array { X } means zero or more occurrences of X, adjacent in
  150162. ** memory.
  150163. **
  150164. ** Leaf nodes are broken into blocks which are stored contiguously in
  150165. ** the %_segments table in sorted order. This means that when the end
  150166. ** of a node is reached, the next term is in the node with the next
  150167. ** greater node id.
  150168. **
  150169. ** New data is spilled to a new leaf node when the current node
  150170. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  150171. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  150172. ** node (a leaf node with a single term and doclist). The goal of
  150173. ** these settings is to pack together groups of small doclists while
  150174. ** making it efficient to directly access large doclists. The
  150175. ** assumption is that large doclists represent terms which are more
  150176. ** likely to be query targets.
  150177. **
  150178. ** TODO(shess) It may be useful for blocking decisions to be more
  150179. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  150180. ** node rather than splitting into 2k and .5k nodes. My intuition is
  150181. ** that this might extend through 2x or 4x the pagesize.
  150182. **
  150183. **
  150184. **** Segment interior nodes ****
  150185. ** Segment interior nodes store blockids for subtree nodes and terms
  150186. ** to describe what data is stored by the each subtree. Interior
  150187. ** nodes are written using InteriorWriter, and read using
  150188. ** InteriorReader. InteriorWriters are created as needed when
  150189. ** SegmentWriter creates new leaf nodes, or when an interior node
  150190. ** itself grows too big and must be split. The format of interior
  150191. ** nodes:
  150192. **
  150193. ** varint iHeight; (height from leaf level, always >0)
  150194. ** varint iBlockid; (block id of node's leftmost subtree)
  150195. ** optional {
  150196. ** varint nTerm; (length of first term)
  150197. ** char pTerm[nTerm]; (content of first term)
  150198. ** array {
  150199. ** (further terms are delta-encoded)
  150200. ** varint nPrefix; (length of shared prefix with previous term)
  150201. ** varint nSuffix; (length of unshared suffix)
  150202. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  150203. ** }
  150204. ** }
  150205. **
  150206. ** Here, optional { X } means an optional element, while array { X }
  150207. ** means zero or more occurrences of X, adjacent in memory.
  150208. **
  150209. ** An interior node encodes n terms separating n+1 subtrees. The
  150210. ** subtree blocks are contiguous, so only the first subtree's blockid
  150211. ** is encoded. The subtree at iBlockid will contain all terms less
  150212. ** than the first term encoded (or all terms if no term is encoded).
  150213. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  150214. ** than pTerm[i+1], the subtree for that term will be rooted at
  150215. ** iBlockid+i. Interior nodes only store enough term data to
  150216. ** distinguish adjacent children (if the rightmost term of the left
  150217. ** child is "something", and the leftmost term of the right child is
  150218. ** "wicked", only "w" is stored).
  150219. **
  150220. ** New data is spilled to a new interior node at the same height when
  150221. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  150222. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  150223. ** interior nodes and making the tree too skinny. The interior nodes
  150224. ** at a given height are naturally tracked by interior nodes at
  150225. ** height+1, and so on.
  150226. **
  150227. **
  150228. **** Segment directory ****
  150229. ** The segment directory in table %_segdir stores meta-information for
  150230. ** merging and deleting segments, and also the root node of the
  150231. ** segment's tree.
  150232. **
  150233. ** The root node is the top node of the segment's tree after encoding
  150234. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  150235. ** This could be either a leaf node or an interior node. If the top
  150236. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  150237. ** and a new root interior node is generated (which should always fit
  150238. ** within ROOT_MAX because it only needs space for 2 varints, the
  150239. ** height and the blockid of the previous root).
  150240. **
  150241. ** The meta-information in the segment directory is:
  150242. ** level - segment level (see below)
  150243. ** idx - index within level
  150244. ** - (level,idx uniquely identify a segment)
  150245. ** start_block - first leaf node
  150246. ** leaves_end_block - last leaf node
  150247. ** end_block - last block (including interior nodes)
  150248. ** root - contents of root node
  150249. **
  150250. ** If the root node is a leaf node, then start_block,
  150251. ** leaves_end_block, and end_block are all 0.
  150252. **
  150253. **
  150254. **** Segment merging ****
  150255. ** To amortize update costs, segments are grouped into levels and
  150256. ** merged in batches. Each increase in level represents exponentially
  150257. ** more documents.
  150258. **
  150259. ** New documents (actually, document updates) are tokenized and
  150260. ** written individually (using LeafWriter) to a level 0 segment, with
  150261. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  150262. ** level 0 segments are merged into a single level 1 segment. Level 1
  150263. ** is populated like level 0, and eventually MERGE_COUNT level 1
  150264. ** segments are merged to a single level 2 segment (representing
  150265. ** MERGE_COUNT^2 updates), and so on.
  150266. **
  150267. ** A segment merge traverses all segments at a given level in
  150268. ** parallel, performing a straightforward sorted merge. Since segment
  150269. ** leaf nodes are written in to the %_segments table in order, this
  150270. ** merge traverses the underlying sqlite disk structures efficiently.
  150271. ** After the merge, all segment blocks from the merged level are
  150272. ** deleted.
  150273. **
  150274. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  150275. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  150276. ** very similar performance numbers to 16 on insertion, though they're
  150277. ** a tiny bit slower (perhaps due to more overhead in merge-time
  150278. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  150279. ** 16, 2 about 66% slower than 16.
  150280. **
  150281. ** At query time, high MERGE_COUNT increases the number of segments
  150282. ** which need to be scanned and merged. For instance, with 100k docs
  150283. ** inserted:
  150284. **
  150285. ** MERGE_COUNT segments
  150286. ** 16 25
  150287. ** 8 12
  150288. ** 4 10
  150289. ** 2 6
  150290. **
  150291. ** This appears to have only a moderate impact on queries for very
  150292. ** frequent terms (which are somewhat dominated by segment merge
  150293. ** costs), and infrequent and non-existent terms still seem to be fast
  150294. ** even with many segments.
  150295. **
  150296. ** TODO(shess) That said, it would be nice to have a better query-side
  150297. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  150298. ** optimizations to things like doclist merging will swing the sweet
  150299. ** spot around.
  150300. **
  150301. **
  150302. **
  150303. **** Handling of deletions and updates ****
  150304. ** Since we're using a segmented structure, with no docid-oriented
  150305. ** index into the term index, we clearly cannot simply update the term
  150306. ** index when a document is deleted or updated. For deletions, we
  150307. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  150308. ** we simply write the new doclist. Segment merges overwrite older
  150309. ** data for a particular docid with newer data, so deletes or updates
  150310. ** will eventually overtake the earlier data and knock it out. The
  150311. ** query logic likewise merges doclists so that newer data knocks out
  150312. ** older data.
  150313. */
  150314. /************** Include fts3Int.h in the middle of fts3.c ********************/
  150315. /************** Begin file fts3Int.h *****************************************/
  150316. /*
  150317. ** 2009 Nov 12
  150318. **
  150319. ** The author disclaims copyright to this source code. In place of
  150320. ** a legal notice, here is a blessing:
  150321. **
  150322. ** May you do good and not evil.
  150323. ** May you find forgiveness for yourself and forgive others.
  150324. ** May you share freely, never taking more than you give.
  150325. **
  150326. ******************************************************************************
  150327. **
  150328. */
  150329. #ifndef _FTSINT_H
  150330. #define _FTSINT_H
  150331. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  150332. # define NDEBUG 1
  150333. #endif
  150334. /* FTS3/FTS4 require virtual tables */
  150335. #ifdef SQLITE_OMIT_VIRTUALTABLE
  150336. # undef SQLITE_ENABLE_FTS3
  150337. # undef SQLITE_ENABLE_FTS4
  150338. #endif
  150339. /*
  150340. ** FTS4 is really an extension for FTS3. It is enabled using the
  150341. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  150342. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  150343. */
  150344. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  150345. # define SQLITE_ENABLE_FTS3
  150346. #endif
  150347. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  150348. /* If not building as part of the core, include sqlite3ext.h. */
  150349. #ifndef SQLITE_CORE
  150350. /* # include "sqlite3ext.h" */
  150351. SQLITE_EXTENSION_INIT3
  150352. #endif
  150353. /* #include "sqlite3.h" */
  150354. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  150355. /************** Begin file fts3_tokenizer.h **********************************/
  150356. /*
  150357. ** 2006 July 10
  150358. **
  150359. ** The author disclaims copyright to this source code.
  150360. **
  150361. *************************************************************************
  150362. ** Defines the interface to tokenizers used by fulltext-search. There
  150363. ** are three basic components:
  150364. **
  150365. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  150366. ** interface functions. This is essentially the class structure for
  150367. ** tokenizers.
  150368. **
  150369. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  150370. ** including customization information defined at creation time.
  150371. **
  150372. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  150373. ** tokens from a particular input.
  150374. */
  150375. #ifndef _FTS3_TOKENIZER_H_
  150376. #define _FTS3_TOKENIZER_H_
  150377. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  150378. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  150379. ** we will need a way to register the API consistently.
  150380. */
  150381. /* #include "sqlite3.h" */
  150382. /*
  150383. ** Structures used by the tokenizer interface. When a new tokenizer
  150384. ** implementation is registered, the caller provides a pointer to
  150385. ** an sqlite3_tokenizer_module containing pointers to the callback
  150386. ** functions that make up an implementation.
  150387. **
  150388. ** When an fts3 table is created, it passes any arguments passed to
  150389. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  150390. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  150391. ** implementation. The xCreate() function in turn returns an
  150392. ** sqlite3_tokenizer structure representing the specific tokenizer to
  150393. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  150394. **
  150395. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  150396. ** method is called. It returns an sqlite3_tokenizer_cursor object
  150397. ** that may be used to tokenize a specific input buffer based on
  150398. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  150399. ** object.
  150400. */
  150401. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  150402. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  150403. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  150404. struct sqlite3_tokenizer_module {
  150405. /*
  150406. ** Structure version. Should always be set to 0 or 1.
  150407. */
  150408. int iVersion;
  150409. /*
  150410. ** Create a new tokenizer. The values in the argv[] array are the
  150411. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  150412. ** TABLE statement that created the fts3 table. For example, if
  150413. ** the following SQL is executed:
  150414. **
  150415. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  150416. **
  150417. ** then argc is set to 2, and the argv[] array contains pointers
  150418. ** to the strings "arg1" and "arg2".
  150419. **
  150420. ** This method should return either SQLITE_OK (0), or an SQLite error
  150421. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  150422. ** to point at the newly created tokenizer structure. The generic
  150423. ** sqlite3_tokenizer.pModule variable should not be initialized by
  150424. ** this callback. The caller will do so.
  150425. */
  150426. int (*xCreate)(
  150427. int argc, /* Size of argv array */
  150428. const char *const*argv, /* Tokenizer argument strings */
  150429. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  150430. );
  150431. /*
  150432. ** Destroy an existing tokenizer. The fts3 module calls this method
  150433. ** exactly once for each successful call to xCreate().
  150434. */
  150435. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  150436. /*
  150437. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  150438. ** is responsible for ensuring that the input buffer remains valid
  150439. ** until the cursor is closed (using the xClose() method).
  150440. */
  150441. int (*xOpen)(
  150442. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  150443. const char *pInput, int nBytes, /* Input buffer */
  150444. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  150445. );
  150446. /*
  150447. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  150448. ** method exactly once for each successful call to xOpen().
  150449. */
  150450. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  150451. /*
  150452. ** Retrieve the next token from the tokenizer cursor pCursor. This
  150453. ** method should either return SQLITE_OK and set the values of the
  150454. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  150455. ** the end of the buffer has been reached, or an SQLite error code.
  150456. **
  150457. ** *ppToken should be set to point at a buffer containing the
  150458. ** normalized version of the token (i.e. after any case-folding and/or
  150459. ** stemming has been performed). *pnBytes should be set to the length
  150460. ** of this buffer in bytes. The input text that generated the token is
  150461. ** identified by the byte offsets returned in *piStartOffset and
  150462. ** *piEndOffset. *piStartOffset should be set to the index of the first
  150463. ** byte of the token in the input buffer. *piEndOffset should be set
  150464. ** to the index of the first byte just past the end of the token in
  150465. ** the input buffer.
  150466. **
  150467. ** The buffer *ppToken is set to point at is managed by the tokenizer
  150468. ** implementation. It is only required to be valid until the next call
  150469. ** to xNext() or xClose().
  150470. */
  150471. /* TODO(shess) current implementation requires pInput to be
  150472. ** nul-terminated. This should either be fixed, or pInput/nBytes
  150473. ** should be converted to zInput.
  150474. */
  150475. int (*xNext)(
  150476. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  150477. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  150478. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  150479. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  150480. int *piPosition /* OUT: Number of tokens returned before this one */
  150481. );
  150482. /***********************************************************************
  150483. ** Methods below this point are only available if iVersion>=1.
  150484. */
  150485. /*
  150486. ** Configure the language id of a tokenizer cursor.
  150487. */
  150488. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  150489. };
  150490. struct sqlite3_tokenizer {
  150491. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  150492. /* Tokenizer implementations will typically add additional fields */
  150493. };
  150494. struct sqlite3_tokenizer_cursor {
  150495. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  150496. /* Tokenizer implementations will typically add additional fields */
  150497. };
  150498. int fts3_global_term_cnt(int iTerm, int iCol);
  150499. int fts3_term_cnt(int iTerm, int iCol);
  150500. #endif /* _FTS3_TOKENIZER_H_ */
  150501. /************** End of fts3_tokenizer.h **************************************/
  150502. /************** Continuing where we left off in fts3Int.h ********************/
  150503. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  150504. /************** Begin file fts3_hash.h ***************************************/
  150505. /*
  150506. ** 2001 September 22
  150507. **
  150508. ** The author disclaims copyright to this source code. In place of
  150509. ** a legal notice, here is a blessing:
  150510. **
  150511. ** May you do good and not evil.
  150512. ** May you find forgiveness for yourself and forgive others.
  150513. ** May you share freely, never taking more than you give.
  150514. **
  150515. *************************************************************************
  150516. ** This is the header file for the generic hash-table implementation
  150517. ** used in SQLite. We've modified it slightly to serve as a standalone
  150518. ** hash table implementation for the full-text indexing module.
  150519. **
  150520. */
  150521. #ifndef _FTS3_HASH_H_
  150522. #define _FTS3_HASH_H_
  150523. /* Forward declarations of structures. */
  150524. typedef struct Fts3Hash Fts3Hash;
  150525. typedef struct Fts3HashElem Fts3HashElem;
  150526. /* A complete hash table is an instance of the following structure.
  150527. ** The internals of this structure are intended to be opaque -- client
  150528. ** code should not attempt to access or modify the fields of this structure
  150529. ** directly. Change this structure only by using the routines below.
  150530. ** However, many of the "procedures" and "functions" for modifying and
  150531. ** accessing this structure are really macros, so we can't really make
  150532. ** this structure opaque.
  150533. */
  150534. struct Fts3Hash {
  150535. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  150536. char copyKey; /* True if copy of key made on insert */
  150537. int count; /* Number of entries in this table */
  150538. Fts3HashElem *first; /* The first element of the array */
  150539. int htsize; /* Number of buckets in the hash table */
  150540. struct _fts3ht { /* the hash table */
  150541. int count; /* Number of entries with this hash */
  150542. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  150543. } *ht;
  150544. };
  150545. /* Each element in the hash table is an instance of the following
  150546. ** structure. All elements are stored on a single doubly-linked list.
  150547. **
  150548. ** Again, this structure is intended to be opaque, but it can't really
  150549. ** be opaque because it is used by macros.
  150550. */
  150551. struct Fts3HashElem {
  150552. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  150553. void *data; /* Data associated with this element */
  150554. void *pKey; int nKey; /* Key associated with this element */
  150555. };
  150556. /*
  150557. ** There are 2 different modes of operation for a hash table:
  150558. **
  150559. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  150560. ** (including the null-terminator, if any). Case
  150561. ** is respected in comparisons.
  150562. **
  150563. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  150564. ** memcmp() is used to compare keys.
  150565. **
  150566. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  150567. */
  150568. #define FTS3_HASH_STRING 1
  150569. #define FTS3_HASH_BINARY 2
  150570. /*
  150571. ** Access routines. To delete, insert a NULL pointer.
  150572. */
  150573. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  150574. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  150575. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  150576. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  150577. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  150578. /*
  150579. ** Shorthand for the functions above
  150580. */
  150581. #define fts3HashInit sqlite3Fts3HashInit
  150582. #define fts3HashInsert sqlite3Fts3HashInsert
  150583. #define fts3HashFind sqlite3Fts3HashFind
  150584. #define fts3HashClear sqlite3Fts3HashClear
  150585. #define fts3HashFindElem sqlite3Fts3HashFindElem
  150586. /*
  150587. ** Macros for looping over all elements of a hash table. The idiom is
  150588. ** like this:
  150589. **
  150590. ** Fts3Hash h;
  150591. ** Fts3HashElem *p;
  150592. ** ...
  150593. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  150594. ** SomeStructure *pData = fts3HashData(p);
  150595. ** // do something with pData
  150596. ** }
  150597. */
  150598. #define fts3HashFirst(H) ((H)->first)
  150599. #define fts3HashNext(E) ((E)->next)
  150600. #define fts3HashData(E) ((E)->data)
  150601. #define fts3HashKey(E) ((E)->pKey)
  150602. #define fts3HashKeysize(E) ((E)->nKey)
  150603. /*
  150604. ** Number of entries in a hash table
  150605. */
  150606. #define fts3HashCount(H) ((H)->count)
  150607. #endif /* _FTS3_HASH_H_ */
  150608. /************** End of fts3_hash.h *******************************************/
  150609. /************** Continuing where we left off in fts3Int.h ********************/
  150610. /*
  150611. ** This constant determines the maximum depth of an FTS expression tree
  150612. ** that the library will create and use. FTS uses recursion to perform
  150613. ** various operations on the query tree, so the disadvantage of a large
  150614. ** limit is that it may allow very large queries to use large amounts
  150615. ** of stack space (perhaps causing a stack overflow).
  150616. */
  150617. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  150618. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  150619. #endif
  150620. /*
  150621. ** This constant controls how often segments are merged. Once there are
  150622. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  150623. ** segment of level N+1.
  150624. */
  150625. #define FTS3_MERGE_COUNT 16
  150626. /*
  150627. ** This is the maximum amount of data (in bytes) to store in the
  150628. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  150629. ** populated as documents are inserted/updated/deleted in a transaction
  150630. ** and used to create a new segment when the transaction is committed.
  150631. ** However if this limit is reached midway through a transaction, a new
  150632. ** segment is created and the hash table cleared immediately.
  150633. */
  150634. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  150635. /*
  150636. ** Macro to return the number of elements in an array. SQLite has a
  150637. ** similar macro called ArraySize(). Use a different name to avoid
  150638. ** a collision when building an amalgamation with built-in FTS3.
  150639. */
  150640. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  150641. #ifndef MIN
  150642. # define MIN(x,y) ((x)<(y)?(x):(y))
  150643. #endif
  150644. #ifndef MAX
  150645. # define MAX(x,y) ((x)>(y)?(x):(y))
  150646. #endif
  150647. /*
  150648. ** Maximum length of a varint encoded integer. The varint format is different
  150649. ** from that used by SQLite, so the maximum length is 10, not 9.
  150650. */
  150651. #define FTS3_VARINT_MAX 10
  150652. #define FTS3_BUFFER_PADDING 8
  150653. /*
  150654. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  150655. ** in the document set and zero or more prefix indexes. All indexes are stored
  150656. ** as one or more b+-trees in the %_segments and %_segdir tables.
  150657. **
  150658. ** It is possible to determine which index a b+-tree belongs to based on the
  150659. ** value stored in the "%_segdir.level" column. Given this value L, the index
  150660. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  150661. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  150662. ** between 1024 and 2047 to index 1, and so on.
  150663. **
  150664. ** It is considered impossible for an index to use more than 1024 levels. In
  150665. ** theory though this may happen, but only after at least
  150666. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  150667. */
  150668. #define FTS3_SEGDIR_MAXLEVEL 1024
  150669. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  150670. /*
  150671. ** The testcase() macro is only used by the amalgamation. If undefined,
  150672. ** make it a no-op.
  150673. */
  150674. #ifndef testcase
  150675. # define testcase(X)
  150676. #endif
  150677. /*
  150678. ** Terminator values for position-lists and column-lists.
  150679. */
  150680. #define POS_COLUMN (1) /* Column-list terminator */
  150681. #define POS_END (0) /* Position-list terminator */
  150682. /*
  150683. ** The assert_fts3_nc() macro is similar to the assert() macro, except that it
  150684. ** is used for assert() conditions that are true only if it can be
  150685. ** guranteed that the database is not corrupt.
  150686. */
  150687. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  150688. SQLITE_API extern int sqlite3_fts3_may_be_corrupt;
  150689. # define assert_fts3_nc(x) assert(sqlite3_fts3_may_be_corrupt || (x))
  150690. #else
  150691. # define assert_fts3_nc(x) assert(x)
  150692. #endif
  150693. /*
  150694. ** This section provides definitions to allow the
  150695. ** FTS3 extension to be compiled outside of the
  150696. ** amalgamation.
  150697. */
  150698. #ifndef SQLITE_AMALGAMATION
  150699. /*
  150700. ** Macros indicating that conditional expressions are always true or
  150701. ** false.
  150702. */
  150703. #ifdef SQLITE_COVERAGE_TEST
  150704. # define ALWAYS(x) (1)
  150705. # define NEVER(X) (0)
  150706. #elif defined(SQLITE_DEBUG)
  150707. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  150708. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  150709. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  150710. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  150711. #else
  150712. # define ALWAYS(x) (x)
  150713. # define NEVER(x) (x)
  150714. #endif
  150715. /*
  150716. ** Internal types used by SQLite.
  150717. */
  150718. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  150719. typedef short int i16; /* 2-byte (or larger) signed integer */
  150720. typedef unsigned int u32; /* 4-byte unsigned integer */
  150721. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  150722. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  150723. /*
  150724. ** Macro used to suppress compiler warnings for unused parameters.
  150725. */
  150726. #define UNUSED_PARAMETER(x) (void)(x)
  150727. /*
  150728. ** Activate assert() only if SQLITE_TEST is enabled.
  150729. */
  150730. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  150731. # define NDEBUG 1
  150732. #endif
  150733. /*
  150734. ** The TESTONLY macro is used to enclose variable declarations or
  150735. ** other bits of code that are needed to support the arguments
  150736. ** within testcase() and assert() macros.
  150737. */
  150738. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  150739. # define TESTONLY(X) X
  150740. #else
  150741. # define TESTONLY(X)
  150742. #endif
  150743. #endif /* SQLITE_AMALGAMATION */
  150744. #ifdef SQLITE_DEBUG
  150745. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  150746. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  150747. #else
  150748. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  150749. #endif
  150750. typedef struct Fts3Table Fts3Table;
  150751. typedef struct Fts3Cursor Fts3Cursor;
  150752. typedef struct Fts3Expr Fts3Expr;
  150753. typedef struct Fts3Phrase Fts3Phrase;
  150754. typedef struct Fts3PhraseToken Fts3PhraseToken;
  150755. typedef struct Fts3Doclist Fts3Doclist;
  150756. typedef struct Fts3SegFilter Fts3SegFilter;
  150757. typedef struct Fts3DeferredToken Fts3DeferredToken;
  150758. typedef struct Fts3SegReader Fts3SegReader;
  150759. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  150760. typedef struct MatchinfoBuffer MatchinfoBuffer;
  150761. /*
  150762. ** A connection to a fulltext index is an instance of the following
  150763. ** structure. The xCreate and xConnect methods create an instance
  150764. ** of this structure and xDestroy and xDisconnect free that instance.
  150765. ** All other methods receive a pointer to the structure as one of their
  150766. ** arguments.
  150767. */
  150768. struct Fts3Table {
  150769. sqlite3_vtab base; /* Base class used by SQLite core */
  150770. sqlite3 *db; /* The database connection */
  150771. const char *zDb; /* logical database name */
  150772. const char *zName; /* virtual table name */
  150773. int nColumn; /* number of named columns in virtual table */
  150774. char **azColumn; /* column names. malloced */
  150775. u8 *abNotindexed; /* True for 'notindexed' columns */
  150776. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  150777. char *zContentTbl; /* content=xxx option, or NULL */
  150778. char *zLanguageid; /* languageid=xxx option, or NULL */
  150779. int nAutoincrmerge; /* Value configured by 'automerge' */
  150780. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  150781. /* Precompiled statements used by the implementation. Each of these
  150782. ** statements is run and reset within a single virtual table API call.
  150783. */
  150784. sqlite3_stmt *aStmt[40];
  150785. sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */
  150786. char *zReadExprlist;
  150787. char *zWriteExprlist;
  150788. int nNodeSize; /* Soft limit for node size */
  150789. u8 bFts4; /* True for FTS4, false for FTS3 */
  150790. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  150791. u8 bHasDocsize; /* True if %_docsize table exists */
  150792. u8 bDescIdx; /* True if doclists are in reverse order */
  150793. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  150794. int nPgsz; /* Page size for host database */
  150795. char *zSegmentsTbl; /* Name of %_segments table */
  150796. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  150797. /*
  150798. ** The following array of hash tables is used to buffer pending index
  150799. ** updates during transactions. All pending updates buffered at any one
  150800. ** time must share a common language-id (see the FTS4 langid= feature).
  150801. ** The current language id is stored in variable iPrevLangid.
  150802. **
  150803. ** A single FTS4 table may have multiple full-text indexes. For each index
  150804. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  150805. ** terms that appear in the document set. Each subsequent index in aIndex[]
  150806. ** is an index of prefixes of a specific length.
  150807. **
  150808. ** Variable nPendingData contains an estimate the memory consumed by the
  150809. ** pending data structures, including hash table overhead, but not including
  150810. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  150811. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  150812. ** recently inserted record.
  150813. */
  150814. int nIndex; /* Size of aIndex[] */
  150815. struct Fts3Index {
  150816. int nPrefix; /* Prefix length (0 for main terms index) */
  150817. Fts3Hash hPending; /* Pending terms table for this index */
  150818. } *aIndex;
  150819. int nMaxPendingData; /* Max pending data before flush to disk */
  150820. int nPendingData; /* Current bytes of pending data */
  150821. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  150822. int iPrevLangid; /* Langid of recently inserted document */
  150823. int bPrevDelete; /* True if last operation was a delete */
  150824. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  150825. /* State variables used for validating that the transaction control
  150826. ** methods of the virtual table are called at appropriate times. These
  150827. ** values do not contribute to FTS functionality; they are used for
  150828. ** verifying the operation of the SQLite core.
  150829. */
  150830. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  150831. int mxSavepoint; /* Largest valid xSavepoint integer */
  150832. #endif
  150833. #ifdef SQLITE_TEST
  150834. /* True to disable the incremental doclist optimization. This is controled
  150835. ** by special insert command 'test-no-incr-doclist'. */
  150836. int bNoIncrDoclist;
  150837. #endif
  150838. };
  150839. /*
  150840. ** When the core wants to read from the virtual table, it creates a
  150841. ** virtual table cursor (an instance of the following structure) using
  150842. ** the xOpen method. Cursors are destroyed using the xClose method.
  150843. */
  150844. struct Fts3Cursor {
  150845. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  150846. i16 eSearch; /* Search strategy (see below) */
  150847. u8 isEof; /* True if at End Of Results */
  150848. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  150849. u8 bSeekStmt; /* True if pStmt is a seek */
  150850. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  150851. Fts3Expr *pExpr; /* Parsed MATCH query string */
  150852. int iLangid; /* Language being queried for */
  150853. int nPhrase; /* Number of matchable phrases in query */
  150854. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  150855. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  150856. char *pNextId; /* Pointer into the body of aDoclist */
  150857. char *aDoclist; /* List of docids for full-text queries */
  150858. int nDoclist; /* Size of buffer at aDoclist */
  150859. u8 bDesc; /* True to sort in descending order */
  150860. int eEvalmode; /* An FTS3_EVAL_XX constant */
  150861. int nRowAvg; /* Average size of database rows, in pages */
  150862. sqlite3_int64 nDoc; /* Documents in table */
  150863. i64 iMinDocid; /* Minimum docid to return */
  150864. i64 iMaxDocid; /* Maximum docid to return */
  150865. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  150866. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  150867. };
  150868. #define FTS3_EVAL_FILTER 0
  150869. #define FTS3_EVAL_NEXT 1
  150870. #define FTS3_EVAL_MATCHINFO 2
  150871. /*
  150872. ** The Fts3Cursor.eSearch member is always set to one of the following.
  150873. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  150874. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  150875. ** of the column to be searched. For example, in
  150876. **
  150877. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  150878. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  150879. **
  150880. ** Because the LHS of the MATCH operator is 2nd column "b",
  150881. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  150882. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  150883. ** indicating that all columns should be searched,
  150884. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  150885. */
  150886. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  150887. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  150888. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  150889. /*
  150890. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  150891. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  150892. ** above. The upper 16-bits contain a combination of the following
  150893. ** bits, used to describe extra constraints on full-text searches.
  150894. */
  150895. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  150896. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  150897. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  150898. struct Fts3Doclist {
  150899. char *aAll; /* Array containing doclist (or NULL) */
  150900. int nAll; /* Size of a[] in bytes */
  150901. char *pNextDocid; /* Pointer to next docid */
  150902. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  150903. int bFreeList; /* True if pList should be sqlite3_free()d */
  150904. char *pList; /* Pointer to position list following iDocid */
  150905. int nList; /* Length of position list */
  150906. };
  150907. /*
  150908. ** A "phrase" is a sequence of one or more tokens that must match in
  150909. ** sequence. A single token is the base case and the most common case.
  150910. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  150911. ** nToken will be the number of tokens in the string.
  150912. */
  150913. struct Fts3PhraseToken {
  150914. char *z; /* Text of the token */
  150915. int n; /* Number of bytes in buffer z */
  150916. int isPrefix; /* True if token ends with a "*" character */
  150917. int bFirst; /* True if token must appear at position 0 */
  150918. /* Variables above this point are populated when the expression is
  150919. ** parsed (by code in fts3_expr.c). Below this point the variables are
  150920. ** used when evaluating the expression. */
  150921. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  150922. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  150923. };
  150924. struct Fts3Phrase {
  150925. /* Cache of doclist for this phrase. */
  150926. Fts3Doclist doclist;
  150927. int bIncr; /* True if doclist is loaded incrementally */
  150928. int iDoclistToken;
  150929. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  150930. ** OR condition. */
  150931. char *pOrPoslist;
  150932. i64 iOrDocid;
  150933. /* Variables below this point are populated by fts3_expr.c when parsing
  150934. ** a MATCH expression. Everything above is part of the evaluation phase.
  150935. */
  150936. int nToken; /* Number of tokens in the phrase */
  150937. int iColumn; /* Index of column this phrase must match */
  150938. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  150939. };
  150940. /*
  150941. ** A tree of these objects forms the RHS of a MATCH operator.
  150942. **
  150943. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  150944. ** points to a malloced buffer, size nDoclist bytes, containing the results
  150945. ** of this phrase query in FTS3 doclist format. As usual, the initial
  150946. ** "Length" field found in doclists stored on disk is omitted from this
  150947. ** buffer.
  150948. **
  150949. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  150950. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  150951. ** where nCol is the number of columns in the queried FTS table. The array
  150952. ** is populated as follows:
  150953. **
  150954. ** aMI[iCol*3 + 0] = Undefined
  150955. ** aMI[iCol*3 + 1] = Number of occurrences
  150956. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  150957. **
  150958. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  150959. ** when the expression node is.
  150960. */
  150961. struct Fts3Expr {
  150962. int eType; /* One of the FTSQUERY_XXX values defined below */
  150963. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  150964. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  150965. Fts3Expr *pLeft; /* Left operand */
  150966. Fts3Expr *pRight; /* Right operand */
  150967. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  150968. /* The following are used by the fts3_eval.c module. */
  150969. sqlite3_int64 iDocid; /* Current docid */
  150970. u8 bEof; /* True this expression is at EOF already */
  150971. u8 bStart; /* True if iDocid is valid */
  150972. u8 bDeferred; /* True if this expression is entirely deferred */
  150973. /* The following are used by the fts3_snippet.c module. */
  150974. int iPhrase; /* Index of this phrase in matchinfo() results */
  150975. u32 *aMI; /* See above */
  150976. };
  150977. /*
  150978. ** Candidate values for Fts3Query.eType. Note that the order of the first
  150979. ** four values is in order of precedence when parsing expressions. For
  150980. ** example, the following:
  150981. **
  150982. ** "a OR b AND c NOT d NEAR e"
  150983. **
  150984. ** is equivalent to:
  150985. **
  150986. ** "a OR (b AND (c NOT (d NEAR e)))"
  150987. */
  150988. #define FTSQUERY_NEAR 1
  150989. #define FTSQUERY_NOT 2
  150990. #define FTSQUERY_AND 3
  150991. #define FTSQUERY_OR 4
  150992. #define FTSQUERY_PHRASE 5
  150993. /* fts3_write.c */
  150994. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  150995. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  150996. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  150997. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  150998. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  150999. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  151000. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  151001. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  151002. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  151003. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  151004. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  151005. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  151006. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  151007. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  151008. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  151009. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  151010. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  151011. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  151012. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  151013. #else
  151014. # define sqlite3Fts3FreeDeferredTokens(x)
  151015. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  151016. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  151017. # define sqlite3Fts3FreeDeferredDoclists(x)
  151018. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  151019. #endif
  151020. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  151021. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  151022. /* Special values interpreted by sqlite3SegReaderCursor() */
  151023. #define FTS3_SEGCURSOR_PENDING -1
  151024. #define FTS3_SEGCURSOR_ALL -2
  151025. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  151026. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  151027. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  151028. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  151029. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  151030. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  151031. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  151032. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  151033. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  151034. #define FTS3_SEGMENT_PREFIX 0x00000008
  151035. #define FTS3_SEGMENT_SCAN 0x00000010
  151036. #define FTS3_SEGMENT_FIRST 0x00000020
  151037. /* Type passed as 4th argument to SegmentReaderIterate() */
  151038. struct Fts3SegFilter {
  151039. const char *zTerm;
  151040. int nTerm;
  151041. int iCol;
  151042. int flags;
  151043. };
  151044. struct Fts3MultiSegReader {
  151045. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  151046. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  151047. int nSegment; /* Size of apSegment array */
  151048. int nAdvance; /* How many seg-readers to advance */
  151049. Fts3SegFilter *pFilter; /* Pointer to filter object */
  151050. char *aBuffer; /* Buffer to merge doclists in */
  151051. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  151052. int iColFilter; /* If >=0, filter for this column */
  151053. int bRestart;
  151054. /* Used by fts3.c only. */
  151055. int nCost; /* Cost of running iterator */
  151056. int bLookup; /* True if a lookup of a single entry. */
  151057. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  151058. char *zTerm; /* Pointer to term buffer */
  151059. int nTerm; /* Size of zTerm in bytes */
  151060. char *aDoclist; /* Pointer to doclist buffer */
  151061. int nDoclist; /* Size of aDoclist[] in bytes */
  151062. };
  151063. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  151064. #define fts3GetVarint32(p, piVal) ( \
  151065. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  151066. )
  151067. /* fts3.c */
  151068. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  151069. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  151070. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  151071. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  151072. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  151073. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  151074. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  151075. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  151076. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  151077. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  151078. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  151079. /* fts3_tokenizer.c */
  151080. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  151081. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  151082. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  151083. sqlite3_tokenizer **, char **
  151084. );
  151085. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  151086. /* fts3_snippet.c */
  151087. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  151088. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  151089. const char *, const char *, int, int
  151090. );
  151091. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  151092. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  151093. /* fts3_expr.c */
  151094. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  151095. char **, int, int, int, const char *, int, Fts3Expr **, char **
  151096. );
  151097. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  151098. #ifdef SQLITE_TEST
  151099. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*);
  151100. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  151101. #endif
  151102. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  151103. sqlite3_tokenizer_cursor **
  151104. );
  151105. /* fts3_aux.c */
  151106. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  151107. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  151108. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  151109. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  151110. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  151111. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  151112. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  151113. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  151114. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  151115. /* fts3_tokenize_vtab.c */
  151116. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  151117. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  151118. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  151119. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  151120. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  151121. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  151122. #endif
  151123. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  151124. #endif /* _FTSINT_H */
  151125. /************** End of fts3Int.h *********************************************/
  151126. /************** Continuing where we left off in fts3.c ***********************/
  151127. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  151128. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  151129. # define SQLITE_CORE 1
  151130. #endif
  151131. /* #include <assert.h> */
  151132. /* #include <stdlib.h> */
  151133. /* #include <stddef.h> */
  151134. /* #include <stdio.h> */
  151135. /* #include <string.h> */
  151136. /* #include <stdarg.h> */
  151137. /* #include "fts3.h" */
  151138. #ifndef SQLITE_CORE
  151139. /* # include "sqlite3ext.h" */
  151140. SQLITE_EXTENSION_INIT1
  151141. #endif
  151142. static int fts3EvalNext(Fts3Cursor *pCsr);
  151143. static int fts3EvalStart(Fts3Cursor *pCsr);
  151144. static int fts3TermSegReaderCursor(
  151145. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  151146. #ifndef SQLITE_AMALGAMATION
  151147. # if defined(SQLITE_DEBUG)
  151148. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  151149. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  151150. # endif
  151151. #endif
  151152. /*
  151153. ** This variable is set to false when running tests for which the on disk
  151154. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  151155. ** assert() conditions in the fts3 code are activated - conditions that are
  151156. ** only true if it is guaranteed that the fts3 database is not corrupt.
  151157. */
  151158. SQLITE_API int sqlite3_fts3_may_be_corrupt = 1;
  151159. /*
  151160. ** Write a 64-bit variable-length integer to memory starting at p[0].
  151161. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  151162. ** The number of bytes written is returned.
  151163. */
  151164. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  151165. unsigned char *q = (unsigned char *) p;
  151166. sqlite_uint64 vu = v;
  151167. do{
  151168. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  151169. vu >>= 7;
  151170. }while( vu!=0 );
  151171. q[-1] &= 0x7f; /* turn off high bit in final byte */
  151172. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  151173. return (int) (q - (unsigned char *)p);
  151174. }
  151175. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  151176. v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift ); \
  151177. if( (v & mask2)==0 ){ var = v; return ret; }
  151178. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  151179. v = (*ptr++); \
  151180. if( (v & mask2)==0 ){ var = v; return ret; }
  151181. /*
  151182. ** Read a 64-bit variable-length integer from memory starting at p[0].
  151183. ** Return the number of bytes read, or 0 on error.
  151184. ** The value is stored in *v.
  151185. */
  151186. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
  151187. const unsigned char *p = (const unsigned char*)pBuf;
  151188. const unsigned char *pStart = p;
  151189. u32 a;
  151190. u64 b;
  151191. int shift;
  151192. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  151193. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  151194. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  151195. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  151196. b = (a & 0x0FFFFFFF );
  151197. for(shift=28; shift<=63; shift+=7){
  151198. u64 c = *p++;
  151199. b += (c&0x7F) << shift;
  151200. if( (c & 0x80)==0 ) break;
  151201. }
  151202. *v = b;
  151203. return (int)(p - pStart);
  151204. }
  151205. /*
  151206. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
  151207. ** a non-negative 32-bit integer before it is returned.
  151208. */
  151209. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  151210. const unsigned char *ptr = (const unsigned char*)p;
  151211. u32 a;
  151212. #ifndef fts3GetVarint32
  151213. GETVARINT_INIT(a, ptr, 0, 0x00, 0x80, *pi, 1);
  151214. #else
  151215. a = (*ptr++);
  151216. assert( a & 0x80 );
  151217. #endif
  151218. GETVARINT_STEP(a, ptr, 7, 0x7F, 0x4000, *pi, 2);
  151219. GETVARINT_STEP(a, ptr, 14, 0x3FFF, 0x200000, *pi, 3);
  151220. GETVARINT_STEP(a, ptr, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  151221. a = (a & 0x0FFFFFFF );
  151222. *pi = (int)(a | ((u32)(*ptr & 0x07) << 28));
  151223. assert( 0==(a & 0x80000000) );
  151224. assert( *pi>=0 );
  151225. return 5;
  151226. }
  151227. /*
  151228. ** Return the number of bytes required to encode v as a varint
  151229. */
  151230. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  151231. int i = 0;
  151232. do{
  151233. i++;
  151234. v >>= 7;
  151235. }while( v!=0 );
  151236. return i;
  151237. }
  151238. /*
  151239. ** Convert an SQL-style quoted string into a normal string by removing
  151240. ** the quote characters. The conversion is done in-place. If the
  151241. ** input does not begin with a quote character, then this routine
  151242. ** is a no-op.
  151243. **
  151244. ** Examples:
  151245. **
  151246. ** "abc" becomes abc
  151247. ** 'xyz' becomes xyz
  151248. ** [pqr] becomes pqr
  151249. ** `mno` becomes mno
  151250. **
  151251. */
  151252. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  151253. char quote; /* Quote character (if any ) */
  151254. quote = z[0];
  151255. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  151256. int iIn = 1; /* Index of next byte to read from input */
  151257. int iOut = 0; /* Index of next byte to write to output */
  151258. /* If the first byte was a '[', then the close-quote character is a ']' */
  151259. if( quote=='[' ) quote = ']';
  151260. while( z[iIn] ){
  151261. if( z[iIn]==quote ){
  151262. if( z[iIn+1]!=quote ) break;
  151263. z[iOut++] = quote;
  151264. iIn += 2;
  151265. }else{
  151266. z[iOut++] = z[iIn++];
  151267. }
  151268. }
  151269. z[iOut] = '\0';
  151270. }
  151271. }
  151272. /*
  151273. ** Read a single varint from the doclist at *pp and advance *pp to point
  151274. ** to the first byte past the end of the varint. Add the value of the varint
  151275. ** to *pVal.
  151276. */
  151277. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  151278. sqlite3_int64 iVal;
  151279. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  151280. *pVal += iVal;
  151281. }
  151282. /*
  151283. ** When this function is called, *pp points to the first byte following a
  151284. ** varint that is part of a doclist (or position-list, or any other list
  151285. ** of varints). This function moves *pp to point to the start of that varint,
  151286. ** and sets *pVal by the varint value.
  151287. **
  151288. ** Argument pStart points to the first byte of the doclist that the
  151289. ** varint is part of.
  151290. */
  151291. static void fts3GetReverseVarint(
  151292. char **pp,
  151293. char *pStart,
  151294. sqlite3_int64 *pVal
  151295. ){
  151296. sqlite3_int64 iVal;
  151297. char *p;
  151298. /* Pointer p now points at the first byte past the varint we are
  151299. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  151300. ** clear on character p[-1]. */
  151301. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  151302. p++;
  151303. *pp = p;
  151304. sqlite3Fts3GetVarint(p, &iVal);
  151305. *pVal = iVal;
  151306. }
  151307. /*
  151308. ** The xDisconnect() virtual table method.
  151309. */
  151310. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  151311. Fts3Table *p = (Fts3Table *)pVtab;
  151312. int i;
  151313. assert( p->nPendingData==0 );
  151314. assert( p->pSegments==0 );
  151315. /* Free any prepared statements held */
  151316. sqlite3_finalize(p->pSeekStmt);
  151317. for(i=0; i<SizeofArray(p->aStmt); i++){
  151318. sqlite3_finalize(p->aStmt[i]);
  151319. }
  151320. sqlite3_free(p->zSegmentsTbl);
  151321. sqlite3_free(p->zReadExprlist);
  151322. sqlite3_free(p->zWriteExprlist);
  151323. sqlite3_free(p->zContentTbl);
  151324. sqlite3_free(p->zLanguageid);
  151325. /* Invoke the tokenizer destructor to free the tokenizer. */
  151326. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  151327. sqlite3_free(p);
  151328. return SQLITE_OK;
  151329. }
  151330. /*
  151331. ** Write an error message into *pzErr
  151332. */
  151333. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  151334. va_list ap;
  151335. sqlite3_free(*pzErr);
  151336. va_start(ap, zFormat);
  151337. *pzErr = sqlite3_vmprintf(zFormat, ap);
  151338. va_end(ap);
  151339. }
  151340. /*
  151341. ** Construct one or more SQL statements from the format string given
  151342. ** and then evaluate those statements. The success code is written
  151343. ** into *pRc.
  151344. **
  151345. ** If *pRc is initially non-zero then this routine is a no-op.
  151346. */
  151347. static void fts3DbExec(
  151348. int *pRc, /* Success code */
  151349. sqlite3 *db, /* Database in which to run SQL */
  151350. const char *zFormat, /* Format string for SQL */
  151351. ... /* Arguments to the format string */
  151352. ){
  151353. va_list ap;
  151354. char *zSql;
  151355. if( *pRc ) return;
  151356. va_start(ap, zFormat);
  151357. zSql = sqlite3_vmprintf(zFormat, ap);
  151358. va_end(ap);
  151359. if( zSql==0 ){
  151360. *pRc = SQLITE_NOMEM;
  151361. }else{
  151362. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  151363. sqlite3_free(zSql);
  151364. }
  151365. }
  151366. /*
  151367. ** The xDestroy() virtual table method.
  151368. */
  151369. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  151370. Fts3Table *p = (Fts3Table *)pVtab;
  151371. int rc = SQLITE_OK; /* Return code */
  151372. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  151373. sqlite3 *db = p->db; /* Database handle */
  151374. /* Drop the shadow tables */
  151375. fts3DbExec(&rc, db,
  151376. "DROP TABLE IF EXISTS %Q.'%q_segments';"
  151377. "DROP TABLE IF EXISTS %Q.'%q_segdir';"
  151378. "DROP TABLE IF EXISTS %Q.'%q_docsize';"
  151379. "DROP TABLE IF EXISTS %Q.'%q_stat';"
  151380. "%s DROP TABLE IF EXISTS %Q.'%q_content';",
  151381. zDb, p->zName,
  151382. zDb, p->zName,
  151383. zDb, p->zName,
  151384. zDb, p->zName,
  151385. (p->zContentTbl ? "--" : ""), zDb,p->zName
  151386. );
  151387. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  151388. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  151389. ** Otherwise, return an SQLite error code.
  151390. */
  151391. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  151392. }
  151393. /*
  151394. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  151395. ** passed as the first argument. This is done as part of the xConnect()
  151396. ** and xCreate() methods.
  151397. **
  151398. ** If *pRc is non-zero when this function is called, it is a no-op.
  151399. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  151400. ** before returning.
  151401. */
  151402. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  151403. if( *pRc==SQLITE_OK ){
  151404. int i; /* Iterator variable */
  151405. int rc; /* Return code */
  151406. char *zSql; /* SQL statement passed to declare_vtab() */
  151407. char *zCols; /* List of user defined columns */
  151408. const char *zLanguageid;
  151409. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  151410. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  151411. /* Create a list of user columns for the virtual table */
  151412. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  151413. for(i=1; zCols && i<p->nColumn; i++){
  151414. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  151415. }
  151416. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  151417. zSql = sqlite3_mprintf(
  151418. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  151419. zCols, p->zName, zLanguageid
  151420. );
  151421. if( !zCols || !zSql ){
  151422. rc = SQLITE_NOMEM;
  151423. }else{
  151424. rc = sqlite3_declare_vtab(p->db, zSql);
  151425. }
  151426. sqlite3_free(zSql);
  151427. sqlite3_free(zCols);
  151428. *pRc = rc;
  151429. }
  151430. }
  151431. /*
  151432. ** Create the %_stat table if it does not already exist.
  151433. */
  151434. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  151435. fts3DbExec(pRc, p->db,
  151436. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  151437. "(id INTEGER PRIMARY KEY, value BLOB);",
  151438. p->zDb, p->zName
  151439. );
  151440. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  151441. }
  151442. /*
  151443. ** Create the backing store tables (%_content, %_segments and %_segdir)
  151444. ** required by the FTS3 table passed as the only argument. This is done
  151445. ** as part of the vtab xCreate() method.
  151446. **
  151447. ** If the p->bHasDocsize boolean is true (indicating that this is an
  151448. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  151449. ** %_stat tables required by FTS4.
  151450. */
  151451. static int fts3CreateTables(Fts3Table *p){
  151452. int rc = SQLITE_OK; /* Return code */
  151453. int i; /* Iterator variable */
  151454. sqlite3 *db = p->db; /* The database connection */
  151455. if( p->zContentTbl==0 ){
  151456. const char *zLanguageid = p->zLanguageid;
  151457. char *zContentCols; /* Columns of %_content table */
  151458. /* Create a list of user columns for the content table */
  151459. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  151460. for(i=0; zContentCols && i<p->nColumn; i++){
  151461. char *z = p->azColumn[i];
  151462. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  151463. }
  151464. if( zLanguageid && zContentCols ){
  151465. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  151466. }
  151467. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  151468. /* Create the content table */
  151469. fts3DbExec(&rc, db,
  151470. "CREATE TABLE %Q.'%q_content'(%s)",
  151471. p->zDb, p->zName, zContentCols
  151472. );
  151473. sqlite3_free(zContentCols);
  151474. }
  151475. /* Create other tables */
  151476. fts3DbExec(&rc, db,
  151477. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  151478. p->zDb, p->zName
  151479. );
  151480. fts3DbExec(&rc, db,
  151481. "CREATE TABLE %Q.'%q_segdir'("
  151482. "level INTEGER,"
  151483. "idx INTEGER,"
  151484. "start_block INTEGER,"
  151485. "leaves_end_block INTEGER,"
  151486. "end_block INTEGER,"
  151487. "root BLOB,"
  151488. "PRIMARY KEY(level, idx)"
  151489. ");",
  151490. p->zDb, p->zName
  151491. );
  151492. if( p->bHasDocsize ){
  151493. fts3DbExec(&rc, db,
  151494. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  151495. p->zDb, p->zName
  151496. );
  151497. }
  151498. assert( p->bHasStat==p->bFts4 );
  151499. if( p->bHasStat ){
  151500. sqlite3Fts3CreateStatTable(&rc, p);
  151501. }
  151502. return rc;
  151503. }
  151504. /*
  151505. ** Store the current database page-size in bytes in p->nPgsz.
  151506. **
  151507. ** If *pRc is non-zero when this function is called, it is a no-op.
  151508. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  151509. ** before returning.
  151510. */
  151511. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  151512. if( *pRc==SQLITE_OK ){
  151513. int rc; /* Return code */
  151514. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  151515. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  151516. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  151517. if( !zSql ){
  151518. rc = SQLITE_NOMEM;
  151519. }else{
  151520. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  151521. if( rc==SQLITE_OK ){
  151522. sqlite3_step(pStmt);
  151523. p->nPgsz = sqlite3_column_int(pStmt, 0);
  151524. rc = sqlite3_finalize(pStmt);
  151525. }else if( rc==SQLITE_AUTH ){
  151526. p->nPgsz = 1024;
  151527. rc = SQLITE_OK;
  151528. }
  151529. }
  151530. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  151531. sqlite3_free(zSql);
  151532. *pRc = rc;
  151533. }
  151534. }
  151535. /*
  151536. ** "Special" FTS4 arguments are column specifications of the following form:
  151537. **
  151538. ** <key> = <value>
  151539. **
  151540. ** There may not be whitespace surrounding the "=" character. The <value>
  151541. ** term may be quoted, but the <key> may not.
  151542. */
  151543. static int fts3IsSpecialColumn(
  151544. const char *z,
  151545. int *pnKey,
  151546. char **pzValue
  151547. ){
  151548. char *zValue;
  151549. const char *zCsr = z;
  151550. while( *zCsr!='=' ){
  151551. if( *zCsr=='\0' ) return 0;
  151552. zCsr++;
  151553. }
  151554. *pnKey = (int)(zCsr-z);
  151555. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  151556. if( zValue ){
  151557. sqlite3Fts3Dequote(zValue);
  151558. }
  151559. *pzValue = zValue;
  151560. return 1;
  151561. }
  151562. /*
  151563. ** Append the output of a printf() style formatting to an existing string.
  151564. */
  151565. static void fts3Appendf(
  151566. int *pRc, /* IN/OUT: Error code */
  151567. char **pz, /* IN/OUT: Pointer to string buffer */
  151568. const char *zFormat, /* Printf format string to append */
  151569. ... /* Arguments for printf format string */
  151570. ){
  151571. if( *pRc==SQLITE_OK ){
  151572. va_list ap;
  151573. char *z;
  151574. va_start(ap, zFormat);
  151575. z = sqlite3_vmprintf(zFormat, ap);
  151576. va_end(ap);
  151577. if( z && *pz ){
  151578. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  151579. sqlite3_free(z);
  151580. z = z2;
  151581. }
  151582. if( z==0 ) *pRc = SQLITE_NOMEM;
  151583. sqlite3_free(*pz);
  151584. *pz = z;
  151585. }
  151586. }
  151587. /*
  151588. ** Return a copy of input string zInput enclosed in double-quotes (") and
  151589. ** with all double quote characters escaped. For example:
  151590. **
  151591. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  151592. **
  151593. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  151594. ** is the callers responsibility to call sqlite3_free() to release this
  151595. ** memory.
  151596. */
  151597. static char *fts3QuoteId(char const *zInput){
  151598. sqlite3_int64 nRet;
  151599. char *zRet;
  151600. nRet = 2 + (int)strlen(zInput)*2 + 1;
  151601. zRet = sqlite3_malloc64(nRet);
  151602. if( zRet ){
  151603. int i;
  151604. char *z = zRet;
  151605. *(z++) = '"';
  151606. for(i=0; zInput[i]; i++){
  151607. if( zInput[i]=='"' ) *(z++) = '"';
  151608. *(z++) = zInput[i];
  151609. }
  151610. *(z++) = '"';
  151611. *(z++) = '\0';
  151612. }
  151613. return zRet;
  151614. }
  151615. /*
  151616. ** Return a list of comma separated SQL expressions and a FROM clause that
  151617. ** could be used in a SELECT statement such as the following:
  151618. **
  151619. ** SELECT <list of expressions> FROM %_content AS x ...
  151620. **
  151621. ** to return the docid, followed by each column of text data in order
  151622. ** from left to write. If parameter zFunc is not NULL, then instead of
  151623. ** being returned directly each column of text data is passed to an SQL
  151624. ** function named zFunc first. For example, if zFunc is "unzip" and the
  151625. ** table has the three user-defined columns "a", "b", and "c", the following
  151626. ** string is returned:
  151627. **
  151628. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  151629. **
  151630. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  151631. ** is the responsibility of the caller to eventually free it.
  151632. **
  151633. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  151634. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  151635. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  151636. ** no error occurs, *pRc is left unmodified.
  151637. */
  151638. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  151639. char *zRet = 0;
  151640. char *zFree = 0;
  151641. char *zFunction;
  151642. int i;
  151643. if( p->zContentTbl==0 ){
  151644. if( !zFunc ){
  151645. zFunction = "";
  151646. }else{
  151647. zFree = zFunction = fts3QuoteId(zFunc);
  151648. }
  151649. fts3Appendf(pRc, &zRet, "docid");
  151650. for(i=0; i<p->nColumn; i++){
  151651. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  151652. }
  151653. if( p->zLanguageid ){
  151654. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  151655. }
  151656. sqlite3_free(zFree);
  151657. }else{
  151658. fts3Appendf(pRc, &zRet, "rowid");
  151659. for(i=0; i<p->nColumn; i++){
  151660. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  151661. }
  151662. if( p->zLanguageid ){
  151663. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  151664. }
  151665. }
  151666. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  151667. p->zDb,
  151668. (p->zContentTbl ? p->zContentTbl : p->zName),
  151669. (p->zContentTbl ? "" : "_content")
  151670. );
  151671. return zRet;
  151672. }
  151673. /*
  151674. ** Return a list of N comma separated question marks, where N is the number
  151675. ** of columns in the %_content table (one for the docid plus one for each
  151676. ** user-defined text column).
  151677. **
  151678. ** If argument zFunc is not NULL, then all but the first question mark
  151679. ** is preceded by zFunc and an open bracket, and followed by a closed
  151680. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  151681. ** user-defined text columns, the following string is returned:
  151682. **
  151683. ** "?, zip(?), zip(?), zip(?)"
  151684. **
  151685. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  151686. ** is the responsibility of the caller to eventually free it.
  151687. **
  151688. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  151689. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  151690. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  151691. ** no error occurs, *pRc is left unmodified.
  151692. */
  151693. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  151694. char *zRet = 0;
  151695. char *zFree = 0;
  151696. char *zFunction;
  151697. int i;
  151698. if( !zFunc ){
  151699. zFunction = "";
  151700. }else{
  151701. zFree = zFunction = fts3QuoteId(zFunc);
  151702. }
  151703. fts3Appendf(pRc, &zRet, "?");
  151704. for(i=0; i<p->nColumn; i++){
  151705. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  151706. }
  151707. if( p->zLanguageid ){
  151708. fts3Appendf(pRc, &zRet, ", ?");
  151709. }
  151710. sqlite3_free(zFree);
  151711. return zRet;
  151712. }
  151713. /*
  151714. ** This function interprets the string at (*pp) as a non-negative integer
  151715. ** value. It reads the integer and sets *pnOut to the value read, then
  151716. ** sets *pp to point to the byte immediately following the last byte of
  151717. ** the integer value.
  151718. **
  151719. ** Only decimal digits ('0'..'9') may be part of an integer value.
  151720. **
  151721. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  151722. ** the output value undefined. Otherwise SQLITE_OK is returned.
  151723. **
  151724. ** This function is used when parsing the "prefix=" FTS4 parameter.
  151725. */
  151726. static int fts3GobbleInt(const char **pp, int *pnOut){
  151727. const int MAX_NPREFIX = 10000000;
  151728. const char *p; /* Iterator pointer */
  151729. int nInt = 0; /* Output value */
  151730. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  151731. nInt = nInt * 10 + (p[0] - '0');
  151732. if( nInt>MAX_NPREFIX ){
  151733. nInt = 0;
  151734. break;
  151735. }
  151736. }
  151737. if( p==*pp ) return SQLITE_ERROR;
  151738. *pnOut = nInt;
  151739. *pp = p;
  151740. return SQLITE_OK;
  151741. }
  151742. /*
  151743. ** This function is called to allocate an array of Fts3Index structures
  151744. ** representing the indexes maintained by the current FTS table. FTS tables
  151745. ** always maintain the main "terms" index, but may also maintain one or
  151746. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  151747. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  151748. **
  151749. ** Argument zParam is passed the value of the "prefix=" option if one was
  151750. ** specified, or NULL otherwise.
  151751. **
  151752. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  151753. ** the allocated array. *pnIndex is set to the number of elements in the
  151754. ** array. If an error does occur, an SQLite error code is returned.
  151755. **
  151756. ** Regardless of whether or not an error is returned, it is the responsibility
  151757. ** of the caller to call sqlite3_free() on the output array to free it.
  151758. */
  151759. static int fts3PrefixParameter(
  151760. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  151761. int *pnIndex, /* OUT: size of *apIndex[] array */
  151762. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  151763. ){
  151764. struct Fts3Index *aIndex; /* Allocated array */
  151765. int nIndex = 1; /* Number of entries in array */
  151766. if( zParam && zParam[0] ){
  151767. const char *p;
  151768. nIndex++;
  151769. for(p=zParam; *p; p++){
  151770. if( *p==',' ) nIndex++;
  151771. }
  151772. }
  151773. aIndex = sqlite3_malloc64(sizeof(struct Fts3Index) * nIndex);
  151774. *apIndex = aIndex;
  151775. if( !aIndex ){
  151776. return SQLITE_NOMEM;
  151777. }
  151778. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  151779. if( zParam ){
  151780. const char *p = zParam;
  151781. int i;
  151782. for(i=1; i<nIndex; i++){
  151783. int nPrefix = 0;
  151784. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  151785. assert( nPrefix>=0 );
  151786. if( nPrefix==0 ){
  151787. nIndex--;
  151788. i--;
  151789. }else{
  151790. aIndex[i].nPrefix = nPrefix;
  151791. }
  151792. p++;
  151793. }
  151794. }
  151795. *pnIndex = nIndex;
  151796. return SQLITE_OK;
  151797. }
  151798. /*
  151799. ** This function is called when initializing an FTS4 table that uses the
  151800. ** content=xxx option. It determines the number of and names of the columns
  151801. ** of the new FTS4 table.
  151802. **
  151803. ** The third argument passed to this function is the value passed to the
  151804. ** config=xxx option (i.e. "xxx"). This function queries the database for
  151805. ** a table of that name. If found, the output variables are populated
  151806. ** as follows:
  151807. **
  151808. ** *pnCol: Set to the number of columns table xxx has,
  151809. **
  151810. ** *pnStr: Set to the total amount of space required to store a copy
  151811. ** of each columns name, including the nul-terminator.
  151812. **
  151813. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  151814. ** the name of the corresponding column in table xxx. The array
  151815. ** and its contents are allocated using a single allocation. It
  151816. ** is the responsibility of the caller to free this allocation
  151817. ** by eventually passing the *pazCol value to sqlite3_free().
  151818. **
  151819. ** If the table cannot be found, an error code is returned and the output
  151820. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  151821. ** returned (and the output variables are undefined).
  151822. */
  151823. static int fts3ContentColumns(
  151824. sqlite3 *db, /* Database handle */
  151825. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  151826. const char *zTbl, /* Name of content table */
  151827. const char ***pazCol, /* OUT: Malloc'd array of column names */
  151828. int *pnCol, /* OUT: Size of array *pazCol */
  151829. int *pnStr, /* OUT: Bytes of string content */
  151830. char **pzErr /* OUT: error message */
  151831. ){
  151832. int rc = SQLITE_OK; /* Return code */
  151833. char *zSql; /* "SELECT *" statement on zTbl */
  151834. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  151835. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  151836. if( !zSql ){
  151837. rc = SQLITE_NOMEM;
  151838. }else{
  151839. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  151840. if( rc!=SQLITE_OK ){
  151841. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  151842. }
  151843. }
  151844. sqlite3_free(zSql);
  151845. if( rc==SQLITE_OK ){
  151846. const char **azCol; /* Output array */
  151847. sqlite3_int64 nStr = 0; /* Size of all column names (incl. 0x00) */
  151848. int nCol; /* Number of table columns */
  151849. int i; /* Used to iterate through columns */
  151850. /* Loop through the returned columns. Set nStr to the number of bytes of
  151851. ** space required to store a copy of each column name, including the
  151852. ** nul-terminator byte. */
  151853. nCol = sqlite3_column_count(pStmt);
  151854. for(i=0; i<nCol; i++){
  151855. const char *zCol = sqlite3_column_name(pStmt, i);
  151856. nStr += strlen(zCol) + 1;
  151857. }
  151858. /* Allocate and populate the array to return. */
  151859. azCol = (const char **)sqlite3_malloc64(sizeof(char *) * nCol + nStr);
  151860. if( azCol==0 ){
  151861. rc = SQLITE_NOMEM;
  151862. }else{
  151863. char *p = (char *)&azCol[nCol];
  151864. for(i=0; i<nCol; i++){
  151865. const char *zCol = sqlite3_column_name(pStmt, i);
  151866. int n = (int)strlen(zCol)+1;
  151867. memcpy(p, zCol, n);
  151868. azCol[i] = p;
  151869. p += n;
  151870. }
  151871. }
  151872. sqlite3_finalize(pStmt);
  151873. /* Set the output variables. */
  151874. *pnCol = nCol;
  151875. *pnStr = nStr;
  151876. *pazCol = azCol;
  151877. }
  151878. return rc;
  151879. }
  151880. /*
  151881. ** This function is the implementation of both the xConnect and xCreate
  151882. ** methods of the FTS3 virtual table.
  151883. **
  151884. ** The argv[] array contains the following:
  151885. **
  151886. ** argv[0] -> module name ("fts3" or "fts4")
  151887. ** argv[1] -> database name
  151888. ** argv[2] -> table name
  151889. ** argv[...] -> "column name" and other module argument fields.
  151890. */
  151891. static int fts3InitVtab(
  151892. int isCreate, /* True for xCreate, false for xConnect */
  151893. sqlite3 *db, /* The SQLite database connection */
  151894. void *pAux, /* Hash table containing tokenizers */
  151895. int argc, /* Number of elements in argv array */
  151896. const char * const *argv, /* xCreate/xConnect argument array */
  151897. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  151898. char **pzErr /* Write any error message here */
  151899. ){
  151900. Fts3Hash *pHash = (Fts3Hash *)pAux;
  151901. Fts3Table *p = 0; /* Pointer to allocated vtab */
  151902. int rc = SQLITE_OK; /* Return code */
  151903. int i; /* Iterator variable */
  151904. sqlite3_int64 nByte; /* Size of allocation used for *p */
  151905. int iCol; /* Column index */
  151906. int nString = 0; /* Bytes required to hold all column names */
  151907. int nCol = 0; /* Number of columns in the FTS table */
  151908. char *zCsr; /* Space for holding column names */
  151909. int nDb; /* Bytes required to hold database name */
  151910. int nName; /* Bytes required to hold table name */
  151911. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  151912. const char **aCol; /* Array of column names */
  151913. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  151914. int nIndex = 0; /* Size of aIndex[] array */
  151915. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  151916. /* The results of parsing supported FTS4 key=value options: */
  151917. int bNoDocsize = 0; /* True to omit %_docsize table */
  151918. int bDescIdx = 0; /* True to store descending indexes */
  151919. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  151920. char *zCompress = 0; /* compress=? parameter (or NULL) */
  151921. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  151922. char *zContent = 0; /* content=? parameter (or NULL) */
  151923. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  151924. char **azNotindexed = 0; /* The set of notindexed= columns */
  151925. int nNotindexed = 0; /* Size of azNotindexed[] array */
  151926. assert( strlen(argv[0])==4 );
  151927. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  151928. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  151929. );
  151930. nDb = (int)strlen(argv[1]) + 1;
  151931. nName = (int)strlen(argv[2]) + 1;
  151932. nByte = sizeof(const char *) * (argc-2);
  151933. aCol = (const char **)sqlite3_malloc64(nByte);
  151934. if( aCol ){
  151935. memset((void*)aCol, 0, nByte);
  151936. azNotindexed = (char **)sqlite3_malloc64(nByte);
  151937. }
  151938. if( azNotindexed ){
  151939. memset(azNotindexed, 0, nByte);
  151940. }
  151941. if( !aCol || !azNotindexed ){
  151942. rc = SQLITE_NOMEM;
  151943. goto fts3_init_out;
  151944. }
  151945. /* Loop through all of the arguments passed by the user to the FTS3/4
  151946. ** module (i.e. all the column names and special arguments). This loop
  151947. ** does the following:
  151948. **
  151949. ** + Figures out the number of columns the FTSX table will have, and
  151950. ** the number of bytes of space that must be allocated to store copies
  151951. ** of the column names.
  151952. **
  151953. ** + If there is a tokenizer specification included in the arguments,
  151954. ** initializes the tokenizer pTokenizer.
  151955. */
  151956. for(i=3; rc==SQLITE_OK && i<argc; i++){
  151957. char const *z = argv[i];
  151958. int nKey;
  151959. char *zVal;
  151960. /* Check if this is a tokenizer specification */
  151961. if( !pTokenizer
  151962. && strlen(z)>8
  151963. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  151964. && 0==sqlite3Fts3IsIdChar(z[8])
  151965. ){
  151966. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  151967. }
  151968. /* Check if it is an FTS4 special argument. */
  151969. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  151970. struct Fts4Option {
  151971. const char *zOpt;
  151972. int nOpt;
  151973. } aFts4Opt[] = {
  151974. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  151975. { "prefix", 6 }, /* 1 -> PREFIX */
  151976. { "compress", 8 }, /* 2 -> COMPRESS */
  151977. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  151978. { "order", 5 }, /* 4 -> ORDER */
  151979. { "content", 7 }, /* 5 -> CONTENT */
  151980. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  151981. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  151982. };
  151983. int iOpt;
  151984. if( !zVal ){
  151985. rc = SQLITE_NOMEM;
  151986. }else{
  151987. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  151988. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  151989. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  151990. break;
  151991. }
  151992. }
  151993. switch( iOpt ){
  151994. case 0: /* MATCHINFO */
  151995. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  151996. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  151997. rc = SQLITE_ERROR;
  151998. }
  151999. bNoDocsize = 1;
  152000. break;
  152001. case 1: /* PREFIX */
  152002. sqlite3_free(zPrefix);
  152003. zPrefix = zVal;
  152004. zVal = 0;
  152005. break;
  152006. case 2: /* COMPRESS */
  152007. sqlite3_free(zCompress);
  152008. zCompress = zVal;
  152009. zVal = 0;
  152010. break;
  152011. case 3: /* UNCOMPRESS */
  152012. sqlite3_free(zUncompress);
  152013. zUncompress = zVal;
  152014. zVal = 0;
  152015. break;
  152016. case 4: /* ORDER */
  152017. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  152018. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  152019. ){
  152020. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  152021. rc = SQLITE_ERROR;
  152022. }
  152023. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  152024. break;
  152025. case 5: /* CONTENT */
  152026. sqlite3_free(zContent);
  152027. zContent = zVal;
  152028. zVal = 0;
  152029. break;
  152030. case 6: /* LANGUAGEID */
  152031. assert( iOpt==6 );
  152032. sqlite3_free(zLanguageid);
  152033. zLanguageid = zVal;
  152034. zVal = 0;
  152035. break;
  152036. case 7: /* NOTINDEXED */
  152037. azNotindexed[nNotindexed++] = zVal;
  152038. zVal = 0;
  152039. break;
  152040. default:
  152041. assert( iOpt==SizeofArray(aFts4Opt) );
  152042. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  152043. rc = SQLITE_ERROR;
  152044. break;
  152045. }
  152046. sqlite3_free(zVal);
  152047. }
  152048. }
  152049. /* Otherwise, the argument is a column name. */
  152050. else {
  152051. nString += (int)(strlen(z) + 1);
  152052. aCol[nCol++] = z;
  152053. }
  152054. }
  152055. /* If a content=xxx option was specified, the following:
  152056. **
  152057. ** 1. Ignore any compress= and uncompress= options.
  152058. **
  152059. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  152060. ** TABLE statement, use all columns from the content table.
  152061. */
  152062. if( rc==SQLITE_OK && zContent ){
  152063. sqlite3_free(zCompress);
  152064. sqlite3_free(zUncompress);
  152065. zCompress = 0;
  152066. zUncompress = 0;
  152067. if( nCol==0 ){
  152068. sqlite3_free((void*)aCol);
  152069. aCol = 0;
  152070. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  152071. /* If a languageid= option was specified, remove the language id
  152072. ** column from the aCol[] array. */
  152073. if( rc==SQLITE_OK && zLanguageid ){
  152074. int j;
  152075. for(j=0; j<nCol; j++){
  152076. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  152077. int k;
  152078. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  152079. nCol--;
  152080. break;
  152081. }
  152082. }
  152083. }
  152084. }
  152085. }
  152086. if( rc!=SQLITE_OK ) goto fts3_init_out;
  152087. if( nCol==0 ){
  152088. assert( nString==0 );
  152089. aCol[0] = "content";
  152090. nString = 8;
  152091. nCol = 1;
  152092. }
  152093. if( pTokenizer==0 ){
  152094. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  152095. if( rc!=SQLITE_OK ) goto fts3_init_out;
  152096. }
  152097. assert( pTokenizer );
  152098. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  152099. if( rc==SQLITE_ERROR ){
  152100. assert( zPrefix );
  152101. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  152102. }
  152103. if( rc!=SQLITE_OK ) goto fts3_init_out;
  152104. /* Allocate and populate the Fts3Table structure. */
  152105. nByte = sizeof(Fts3Table) + /* Fts3Table */
  152106. nCol * sizeof(char *) + /* azColumn */
  152107. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  152108. nCol * sizeof(u8) + /* abNotindexed */
  152109. nName + /* zName */
  152110. nDb + /* zDb */
  152111. nString; /* Space for azColumn strings */
  152112. p = (Fts3Table*)sqlite3_malloc64(nByte);
  152113. if( p==0 ){
  152114. rc = SQLITE_NOMEM;
  152115. goto fts3_init_out;
  152116. }
  152117. memset(p, 0, nByte);
  152118. p->db = db;
  152119. p->nColumn = nCol;
  152120. p->nPendingData = 0;
  152121. p->azColumn = (char **)&p[1];
  152122. p->pTokenizer = pTokenizer;
  152123. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  152124. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  152125. p->bHasStat = (u8)isFts4;
  152126. p->bFts4 = (u8)isFts4;
  152127. p->bDescIdx = (u8)bDescIdx;
  152128. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  152129. p->zContentTbl = zContent;
  152130. p->zLanguageid = zLanguageid;
  152131. zContent = 0;
  152132. zLanguageid = 0;
  152133. TESTONLY( p->inTransaction = -1 );
  152134. TESTONLY( p->mxSavepoint = -1 );
  152135. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  152136. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  152137. p->nIndex = nIndex;
  152138. for(i=0; i<nIndex; i++){
  152139. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  152140. }
  152141. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  152142. /* Fill in the zName and zDb fields of the vtab structure. */
  152143. zCsr = (char *)&p->abNotindexed[nCol];
  152144. p->zName = zCsr;
  152145. memcpy(zCsr, argv[2], nName);
  152146. zCsr += nName;
  152147. p->zDb = zCsr;
  152148. memcpy(zCsr, argv[1], nDb);
  152149. zCsr += nDb;
  152150. /* Fill in the azColumn array */
  152151. for(iCol=0; iCol<nCol; iCol++){
  152152. char *z;
  152153. int n = 0;
  152154. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  152155. if( n>0 ){
  152156. memcpy(zCsr, z, n);
  152157. }
  152158. zCsr[n] = '\0';
  152159. sqlite3Fts3Dequote(zCsr);
  152160. p->azColumn[iCol] = zCsr;
  152161. zCsr += n+1;
  152162. assert( zCsr <= &((char *)p)[nByte] );
  152163. }
  152164. /* Fill in the abNotindexed array */
  152165. for(iCol=0; iCol<nCol; iCol++){
  152166. int n = (int)strlen(p->azColumn[iCol]);
  152167. for(i=0; i<nNotindexed; i++){
  152168. char *zNot = azNotindexed[i];
  152169. if( zNot && n==(int)strlen(zNot)
  152170. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  152171. ){
  152172. p->abNotindexed[iCol] = 1;
  152173. sqlite3_free(zNot);
  152174. azNotindexed[i] = 0;
  152175. }
  152176. }
  152177. }
  152178. for(i=0; i<nNotindexed; i++){
  152179. if( azNotindexed[i] ){
  152180. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  152181. rc = SQLITE_ERROR;
  152182. }
  152183. }
  152184. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  152185. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  152186. rc = SQLITE_ERROR;
  152187. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  152188. }
  152189. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  152190. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  152191. if( rc!=SQLITE_OK ) goto fts3_init_out;
  152192. /* If this is an xCreate call, create the underlying tables in the
  152193. ** database. TODO: For xConnect(), it could verify that said tables exist.
  152194. */
  152195. if( isCreate ){
  152196. rc = fts3CreateTables(p);
  152197. }
  152198. /* Check to see if a legacy fts3 table has been "upgraded" by the
  152199. ** addition of a %_stat table so that it can use incremental merge.
  152200. */
  152201. if( !isFts4 && !isCreate ){
  152202. p->bHasStat = 2;
  152203. }
  152204. /* Figure out the page-size for the database. This is required in order to
  152205. ** estimate the cost of loading large doclists from the database. */
  152206. fts3DatabasePageSize(&rc, p);
  152207. p->nNodeSize = p->nPgsz-35;
  152208. /* Declare the table schema to SQLite. */
  152209. fts3DeclareVtab(&rc, p);
  152210. fts3_init_out:
  152211. sqlite3_free(zPrefix);
  152212. sqlite3_free(aIndex);
  152213. sqlite3_free(zCompress);
  152214. sqlite3_free(zUncompress);
  152215. sqlite3_free(zContent);
  152216. sqlite3_free(zLanguageid);
  152217. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  152218. sqlite3_free((void *)aCol);
  152219. sqlite3_free((void *)azNotindexed);
  152220. if( rc!=SQLITE_OK ){
  152221. if( p ){
  152222. fts3DisconnectMethod((sqlite3_vtab *)p);
  152223. }else if( pTokenizer ){
  152224. pTokenizer->pModule->xDestroy(pTokenizer);
  152225. }
  152226. }else{
  152227. assert( p->pSegments==0 );
  152228. *ppVTab = &p->base;
  152229. }
  152230. return rc;
  152231. }
  152232. /*
  152233. ** The xConnect() and xCreate() methods for the virtual table. All the
  152234. ** work is done in function fts3InitVtab().
  152235. */
  152236. static int fts3ConnectMethod(
  152237. sqlite3 *db, /* Database connection */
  152238. void *pAux, /* Pointer to tokenizer hash table */
  152239. int argc, /* Number of elements in argv array */
  152240. const char * const *argv, /* xCreate/xConnect argument array */
  152241. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  152242. char **pzErr /* OUT: sqlite3_malloc'd error message */
  152243. ){
  152244. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  152245. }
  152246. static int fts3CreateMethod(
  152247. sqlite3 *db, /* Database connection */
  152248. void *pAux, /* Pointer to tokenizer hash table */
  152249. int argc, /* Number of elements in argv array */
  152250. const char * const *argv, /* xCreate/xConnect argument array */
  152251. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  152252. char **pzErr /* OUT: sqlite3_malloc'd error message */
  152253. ){
  152254. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  152255. }
  152256. /*
  152257. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  152258. ** extension is currently being used by a version of SQLite too old to
  152259. ** support estimatedRows. In that case this function is a no-op.
  152260. */
  152261. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  152262. #if SQLITE_VERSION_NUMBER>=3008002
  152263. if( sqlite3_libversion_number()>=3008002 ){
  152264. pIdxInfo->estimatedRows = nRow;
  152265. }
  152266. #endif
  152267. }
  152268. /*
  152269. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  152270. ** extension is currently being used by a version of SQLite too old to
  152271. ** support index-info flags. In that case this function is a no-op.
  152272. */
  152273. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  152274. #if SQLITE_VERSION_NUMBER>=3008012
  152275. if( sqlite3_libversion_number()>=3008012 ){
  152276. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  152277. }
  152278. #endif
  152279. }
  152280. /*
  152281. ** Implementation of the xBestIndex method for FTS3 tables. There
  152282. ** are three possible strategies, in order of preference:
  152283. **
  152284. ** 1. Direct lookup by rowid or docid.
  152285. ** 2. Full-text search using a MATCH operator on a non-docid column.
  152286. ** 3. Linear scan of %_content table.
  152287. */
  152288. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  152289. Fts3Table *p = (Fts3Table *)pVTab;
  152290. int i; /* Iterator variable */
  152291. int iCons = -1; /* Index of constraint to use */
  152292. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  152293. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  152294. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  152295. int iIdx;
  152296. /* By default use a full table scan. This is an expensive option,
  152297. ** so search through the constraints to see if a more efficient
  152298. ** strategy is possible.
  152299. */
  152300. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  152301. pInfo->estimatedCost = 5000000;
  152302. for(i=0; i<pInfo->nConstraint; i++){
  152303. int bDocid; /* True if this constraint is on docid */
  152304. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  152305. if( pCons->usable==0 ){
  152306. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  152307. /* There exists an unusable MATCH constraint. This means that if
  152308. ** the planner does elect to use the results of this call as part
  152309. ** of the overall query plan the user will see an "unable to use
  152310. ** function MATCH in the requested context" error. To discourage
  152311. ** this, return a very high cost here. */
  152312. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  152313. pInfo->estimatedCost = 1e50;
  152314. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  152315. return SQLITE_OK;
  152316. }
  152317. continue;
  152318. }
  152319. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  152320. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  152321. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  152322. pInfo->idxNum = FTS3_DOCID_SEARCH;
  152323. pInfo->estimatedCost = 1.0;
  152324. iCons = i;
  152325. }
  152326. /* A MATCH constraint. Use a full-text search.
  152327. **
  152328. ** If there is more than one MATCH constraint available, use the first
  152329. ** one encountered. If there is both a MATCH constraint and a direct
  152330. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  152331. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  152332. ** it would lead to an "unable to use function MATCH in the requested
  152333. ** context" error.
  152334. */
  152335. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  152336. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  152337. ){
  152338. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  152339. pInfo->estimatedCost = 2.0;
  152340. iCons = i;
  152341. }
  152342. /* Equality constraint on the langid column */
  152343. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  152344. && pCons->iColumn==p->nColumn + 2
  152345. ){
  152346. iLangidCons = i;
  152347. }
  152348. if( bDocid ){
  152349. switch( pCons->op ){
  152350. case SQLITE_INDEX_CONSTRAINT_GE:
  152351. case SQLITE_INDEX_CONSTRAINT_GT:
  152352. iDocidGe = i;
  152353. break;
  152354. case SQLITE_INDEX_CONSTRAINT_LE:
  152355. case SQLITE_INDEX_CONSTRAINT_LT:
  152356. iDocidLe = i;
  152357. break;
  152358. }
  152359. }
  152360. }
  152361. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  152362. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  152363. iIdx = 1;
  152364. if( iCons>=0 ){
  152365. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  152366. pInfo->aConstraintUsage[iCons].omit = 1;
  152367. }
  152368. if( iLangidCons>=0 ){
  152369. pInfo->idxNum |= FTS3_HAVE_LANGID;
  152370. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  152371. }
  152372. if( iDocidGe>=0 ){
  152373. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  152374. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  152375. }
  152376. if( iDocidLe>=0 ){
  152377. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  152378. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  152379. }
  152380. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  152381. ** docid) order. Both ascending and descending are possible.
  152382. */
  152383. if( pInfo->nOrderBy==1 ){
  152384. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  152385. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  152386. if( pOrder->desc ){
  152387. pInfo->idxStr = "DESC";
  152388. }else{
  152389. pInfo->idxStr = "ASC";
  152390. }
  152391. pInfo->orderByConsumed = 1;
  152392. }
  152393. }
  152394. assert( p->pSegments==0 );
  152395. return SQLITE_OK;
  152396. }
  152397. /*
  152398. ** Implementation of xOpen method.
  152399. */
  152400. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  152401. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  152402. UNUSED_PARAMETER(pVTab);
  152403. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  152404. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  152405. ** if the allocation fails, return SQLITE_NOMEM.
  152406. */
  152407. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  152408. if( !pCsr ){
  152409. return SQLITE_NOMEM;
  152410. }
  152411. memset(pCsr, 0, sizeof(Fts3Cursor));
  152412. return SQLITE_OK;
  152413. }
  152414. /*
  152415. ** Finalize the statement handle at pCsr->pStmt.
  152416. **
  152417. ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
  152418. ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
  152419. ** pointer there instead of finalizing it.
  152420. */
  152421. static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
  152422. if( pCsr->bSeekStmt ){
  152423. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  152424. if( p->pSeekStmt==0 ){
  152425. p->pSeekStmt = pCsr->pStmt;
  152426. sqlite3_reset(pCsr->pStmt);
  152427. pCsr->pStmt = 0;
  152428. }
  152429. pCsr->bSeekStmt = 0;
  152430. }
  152431. sqlite3_finalize(pCsr->pStmt);
  152432. }
  152433. /*
  152434. ** Free all resources currently held by the cursor passed as the only
  152435. ** argument.
  152436. */
  152437. static void fts3ClearCursor(Fts3Cursor *pCsr){
  152438. fts3CursorFinalizeStmt(pCsr);
  152439. sqlite3Fts3FreeDeferredTokens(pCsr);
  152440. sqlite3_free(pCsr->aDoclist);
  152441. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  152442. sqlite3Fts3ExprFree(pCsr->pExpr);
  152443. memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  152444. }
  152445. /*
  152446. ** Close the cursor. For additional information see the documentation
  152447. ** on the xClose method of the virtual table interface.
  152448. */
  152449. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  152450. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  152451. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  152452. fts3ClearCursor(pCsr);
  152453. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  152454. sqlite3_free(pCsr);
  152455. return SQLITE_OK;
  152456. }
  152457. /*
  152458. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  152459. ** compose and prepare an SQL statement of the form:
  152460. **
  152461. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  152462. **
  152463. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  152464. ** it. If an error occurs, return an SQLite error code.
  152465. */
  152466. static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
  152467. int rc = SQLITE_OK;
  152468. if( pCsr->pStmt==0 ){
  152469. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  152470. char *zSql;
  152471. if( p->pSeekStmt ){
  152472. pCsr->pStmt = p->pSeekStmt;
  152473. p->pSeekStmt = 0;
  152474. }else{
  152475. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  152476. if( !zSql ) return SQLITE_NOMEM;
  152477. rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  152478. sqlite3_free(zSql);
  152479. }
  152480. if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
  152481. }
  152482. return rc;
  152483. }
  152484. /*
  152485. ** Position the pCsr->pStmt statement so that it is on the row
  152486. ** of the %_content table that contains the last match. Return
  152487. ** SQLITE_OK on success.
  152488. */
  152489. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  152490. int rc = SQLITE_OK;
  152491. if( pCsr->isRequireSeek ){
  152492. rc = fts3CursorSeekStmt(pCsr);
  152493. if( rc==SQLITE_OK ){
  152494. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  152495. pCsr->isRequireSeek = 0;
  152496. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  152497. return SQLITE_OK;
  152498. }else{
  152499. rc = sqlite3_reset(pCsr->pStmt);
  152500. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  152501. /* If no row was found and no error has occurred, then the %_content
  152502. ** table is missing a row that is present in the full-text index.
  152503. ** The data structures are corrupt. */
  152504. rc = FTS_CORRUPT_VTAB;
  152505. pCsr->isEof = 1;
  152506. }
  152507. }
  152508. }
  152509. }
  152510. if( rc!=SQLITE_OK && pContext ){
  152511. sqlite3_result_error_code(pContext, rc);
  152512. }
  152513. return rc;
  152514. }
  152515. /*
  152516. ** This function is used to process a single interior node when searching
  152517. ** a b-tree for a term or term prefix. The node data is passed to this
  152518. ** function via the zNode/nNode parameters. The term to search for is
  152519. ** passed in zTerm/nTerm.
  152520. **
  152521. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  152522. ** of the child node that heads the sub-tree that may contain the term.
  152523. **
  152524. ** If piLast is not NULL, then *piLast is set to the right-most child node
  152525. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  152526. ** a prefix.
  152527. **
  152528. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  152529. */
  152530. static int fts3ScanInteriorNode(
  152531. const char *zTerm, /* Term to select leaves for */
  152532. int nTerm, /* Size of term zTerm in bytes */
  152533. const char *zNode, /* Buffer containing segment interior node */
  152534. int nNode, /* Size of buffer at zNode */
  152535. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  152536. sqlite3_int64 *piLast /* OUT: Selected child node */
  152537. ){
  152538. int rc = SQLITE_OK; /* Return code */
  152539. const char *zCsr = zNode; /* Cursor to iterate through node */
  152540. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  152541. char *zBuffer = 0; /* Buffer to load terms into */
  152542. i64 nAlloc = 0; /* Size of allocated buffer */
  152543. int isFirstTerm = 1; /* True when processing first term on page */
  152544. sqlite3_int64 iChild; /* Block id of child node to descend to */
  152545. /* Skip over the 'height' varint that occurs at the start of every
  152546. ** interior node. Then load the blockid of the left-child of the b-tree
  152547. ** node into variable iChild.
  152548. **
  152549. ** Even if the data structure on disk is corrupted, this (reading two
  152550. ** varints from the buffer) does not risk an overread. If zNode is a
  152551. ** root node, then the buffer comes from a SELECT statement. SQLite does
  152552. ** not make this guarantee explicitly, but in practice there are always
  152553. ** either more than 20 bytes of allocated space following the nNode bytes of
  152554. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  152555. ** table, then there are always 20 bytes of zeroed padding following the
  152556. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  152557. */
  152558. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  152559. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  152560. if( zCsr>zEnd ){
  152561. return FTS_CORRUPT_VTAB;
  152562. }
  152563. while( zCsr<zEnd && (piFirst || piLast) ){
  152564. int cmp; /* memcmp() result */
  152565. int nSuffix; /* Size of term suffix */
  152566. int nPrefix = 0; /* Size of term prefix */
  152567. int nBuffer; /* Total term size */
  152568. /* Load the next term on the node into zBuffer. Use realloc() to expand
  152569. ** the size of zBuffer if required. */
  152570. if( !isFirstTerm ){
  152571. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  152572. }
  152573. isFirstTerm = 0;
  152574. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  152575. assert( nPrefix>=0 && nSuffix>=0 );
  152576. if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){
  152577. rc = FTS_CORRUPT_VTAB;
  152578. goto finish_scan;
  152579. }
  152580. if( (i64)nPrefix+nSuffix>nAlloc ){
  152581. char *zNew;
  152582. nAlloc = ((i64)nPrefix+nSuffix) * 2;
  152583. zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc);
  152584. if( !zNew ){
  152585. rc = SQLITE_NOMEM;
  152586. goto finish_scan;
  152587. }
  152588. zBuffer = zNew;
  152589. }
  152590. assert( zBuffer );
  152591. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  152592. nBuffer = nPrefix + nSuffix;
  152593. zCsr += nSuffix;
  152594. /* Compare the term we are searching for with the term just loaded from
  152595. ** the interior node. If the specified term is greater than or equal
  152596. ** to the term from the interior node, then all terms on the sub-tree
  152597. ** headed by node iChild are smaller than zTerm. No need to search
  152598. ** iChild.
  152599. **
  152600. ** If the interior node term is larger than the specified term, then
  152601. ** the tree headed by iChild may contain the specified term.
  152602. */
  152603. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  152604. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  152605. *piFirst = iChild;
  152606. piFirst = 0;
  152607. }
  152608. if( piLast && cmp<0 ){
  152609. *piLast = iChild;
  152610. piLast = 0;
  152611. }
  152612. iChild++;
  152613. };
  152614. if( piFirst ) *piFirst = iChild;
  152615. if( piLast ) *piLast = iChild;
  152616. finish_scan:
  152617. sqlite3_free(zBuffer);
  152618. return rc;
  152619. }
  152620. /*
  152621. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  152622. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  152623. ** contains a term. This function searches the sub-tree headed by the zNode
  152624. ** node for the range of leaf nodes that may contain the specified term
  152625. ** or terms for which the specified term is a prefix.
  152626. **
  152627. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  152628. ** left-most leaf node in the tree that may contain the specified term.
  152629. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  152630. ** right-most leaf node that may contain a term for which the specified
  152631. ** term is a prefix.
  152632. **
  152633. ** It is possible that the range of returned leaf nodes does not contain
  152634. ** the specified term or any terms for which it is a prefix. However, if the
  152635. ** segment does contain any such terms, they are stored within the identified
  152636. ** range. Because this function only inspects interior segment nodes (and
  152637. ** never loads leaf nodes into memory), it is not possible to be sure.
  152638. **
  152639. ** If an error occurs, an error code other than SQLITE_OK is returned.
  152640. */
  152641. static int fts3SelectLeaf(
  152642. Fts3Table *p, /* Virtual table handle */
  152643. const char *zTerm, /* Term to select leaves for */
  152644. int nTerm, /* Size of term zTerm in bytes */
  152645. const char *zNode, /* Buffer containing segment interior node */
  152646. int nNode, /* Size of buffer at zNode */
  152647. sqlite3_int64 *piLeaf, /* Selected leaf node */
  152648. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  152649. ){
  152650. int rc = SQLITE_OK; /* Return code */
  152651. int iHeight; /* Height of this node in tree */
  152652. assert( piLeaf || piLeaf2 );
  152653. fts3GetVarint32(zNode, &iHeight);
  152654. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  152655. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  152656. if( rc==SQLITE_OK && iHeight>1 ){
  152657. char *zBlob = 0; /* Blob read from %_segments table */
  152658. int nBlob = 0; /* Size of zBlob in bytes */
  152659. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  152660. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  152661. if( rc==SQLITE_OK ){
  152662. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  152663. }
  152664. sqlite3_free(zBlob);
  152665. piLeaf = 0;
  152666. zBlob = 0;
  152667. }
  152668. if( rc==SQLITE_OK ){
  152669. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  152670. }
  152671. if( rc==SQLITE_OK ){
  152672. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  152673. }
  152674. sqlite3_free(zBlob);
  152675. }
  152676. return rc;
  152677. }
  152678. /*
  152679. ** This function is used to create delta-encoded serialized lists of FTS3
  152680. ** varints. Each call to this function appends a single varint to a list.
  152681. */
  152682. static void fts3PutDeltaVarint(
  152683. char **pp, /* IN/OUT: Output pointer */
  152684. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  152685. sqlite3_int64 iVal /* Write this value to the list */
  152686. ){
  152687. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  152688. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  152689. *piPrev = iVal;
  152690. }
  152691. /*
  152692. ** When this function is called, *ppPoslist is assumed to point to the
  152693. ** start of a position-list. After it returns, *ppPoslist points to the
  152694. ** first byte after the position-list.
  152695. **
  152696. ** A position list is list of positions (delta encoded) and columns for
  152697. ** a single document record of a doclist. So, in other words, this
  152698. ** routine advances *ppPoslist so that it points to the next docid in
  152699. ** the doclist, or to the first byte past the end of the doclist.
  152700. **
  152701. ** If pp is not NULL, then the contents of the position list are copied
  152702. ** to *pp. *pp is set to point to the first byte past the last byte copied
  152703. ** before this function returns.
  152704. */
  152705. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  152706. char *pEnd = *ppPoslist;
  152707. char c = 0;
  152708. /* The end of a position list is marked by a zero encoded as an FTS3
  152709. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  152710. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  152711. ** of some other, multi-byte, value.
  152712. **
  152713. ** The following while-loop moves pEnd to point to the first byte that is not
  152714. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  152715. ** pEnd once more so that it points to the byte immediately following the
  152716. ** last byte in the position-list.
  152717. */
  152718. while( *pEnd | c ){
  152719. c = *pEnd++ & 0x80;
  152720. testcase( c!=0 && (*pEnd)==0 );
  152721. }
  152722. pEnd++; /* Advance past the POS_END terminator byte */
  152723. if( pp ){
  152724. int n = (int)(pEnd - *ppPoslist);
  152725. char *p = *pp;
  152726. memcpy(p, *ppPoslist, n);
  152727. p += n;
  152728. *pp = p;
  152729. }
  152730. *ppPoslist = pEnd;
  152731. }
  152732. /*
  152733. ** When this function is called, *ppPoslist is assumed to point to the
  152734. ** start of a column-list. After it returns, *ppPoslist points to the
  152735. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  152736. **
  152737. ** A column-list is list of delta-encoded positions for a single column
  152738. ** within a single document within a doclist.
  152739. **
  152740. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  152741. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  152742. ** the POS_COLUMN or POS_END that terminates the column-list.
  152743. **
  152744. ** If pp is not NULL, then the contents of the column-list are copied
  152745. ** to *pp. *pp is set to point to the first byte past the last byte copied
  152746. ** before this function returns. The POS_COLUMN or POS_END terminator
  152747. ** is not copied into *pp.
  152748. */
  152749. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  152750. char *pEnd = *ppPoslist;
  152751. char c = 0;
  152752. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  152753. ** not part of a multi-byte varint.
  152754. */
  152755. while( 0xFE & (*pEnd | c) ){
  152756. c = *pEnd++ & 0x80;
  152757. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  152758. }
  152759. if( pp ){
  152760. int n = (int)(pEnd - *ppPoslist);
  152761. char *p = *pp;
  152762. memcpy(p, *ppPoslist, n);
  152763. p += n;
  152764. *pp = p;
  152765. }
  152766. *ppPoslist = pEnd;
  152767. }
  152768. /*
  152769. ** Value used to signify the end of an position-list. This is safe because
  152770. ** it is not possible to have a document with 2^31 terms.
  152771. */
  152772. #define POSITION_LIST_END 0x7fffffff
  152773. /*
  152774. ** This function is used to help parse position-lists. When this function is
  152775. ** called, *pp may point to the start of the next varint in the position-list
  152776. ** being parsed, or it may point to 1 byte past the end of the position-list
  152777. ** (in which case **pp will be a terminator bytes POS_END (0) or
  152778. ** (1)).
  152779. **
  152780. ** If *pp points past the end of the current position-list, set *pi to
  152781. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  152782. ** increment the current value of *pi by the value read, and set *pp to
  152783. ** point to the next value before returning.
  152784. **
  152785. ** Before calling this routine *pi must be initialized to the value of
  152786. ** the previous position, or zero if we are reading the first position
  152787. ** in the position-list. Because positions are delta-encoded, the value
  152788. ** of the previous position is needed in order to compute the value of
  152789. ** the next position.
  152790. */
  152791. static void fts3ReadNextPos(
  152792. char **pp, /* IN/OUT: Pointer into position-list buffer */
  152793. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  152794. ){
  152795. if( (**pp)&0xFE ){
  152796. fts3GetDeltaVarint(pp, pi);
  152797. *pi -= 2;
  152798. }else{
  152799. *pi = POSITION_LIST_END;
  152800. }
  152801. }
  152802. /*
  152803. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  152804. ** the value of iCol encoded as a varint to *pp. This will start a new
  152805. ** column list.
  152806. **
  152807. ** Set *pp to point to the byte just after the last byte written before
  152808. ** returning (do not modify it if iCol==0). Return the total number of bytes
  152809. ** written (0 if iCol==0).
  152810. */
  152811. static int fts3PutColNumber(char **pp, int iCol){
  152812. int n = 0; /* Number of bytes written */
  152813. if( iCol ){
  152814. char *p = *pp; /* Output pointer */
  152815. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  152816. *p = 0x01;
  152817. *pp = &p[n];
  152818. }
  152819. return n;
  152820. }
  152821. /*
  152822. ** Compute the union of two position lists. The output written
  152823. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  152824. ** order and with any duplicates removed. All pointers are
  152825. ** updated appropriately. The caller is responsible for insuring
  152826. ** that there is enough space in *pp to hold the complete output.
  152827. */
  152828. static int fts3PoslistMerge(
  152829. char **pp, /* Output buffer */
  152830. char **pp1, /* Left input list */
  152831. char **pp2 /* Right input list */
  152832. ){
  152833. char *p = *pp;
  152834. char *p1 = *pp1;
  152835. char *p2 = *pp2;
  152836. while( *p1 || *p2 ){
  152837. int iCol1; /* The current column index in pp1 */
  152838. int iCol2; /* The current column index in pp2 */
  152839. if( *p1==POS_COLUMN ){
  152840. fts3GetVarint32(&p1[1], &iCol1);
  152841. if( iCol1==0 ) return FTS_CORRUPT_VTAB;
  152842. }
  152843. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  152844. else iCol1 = 0;
  152845. if( *p2==POS_COLUMN ){
  152846. fts3GetVarint32(&p2[1], &iCol2);
  152847. if( iCol2==0 ) return FTS_CORRUPT_VTAB;
  152848. }
  152849. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  152850. else iCol2 = 0;
  152851. if( iCol1==iCol2 ){
  152852. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  152853. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  152854. sqlite3_int64 iPrev = 0;
  152855. int n = fts3PutColNumber(&p, iCol1);
  152856. p1 += n;
  152857. p2 += n;
  152858. /* At this point, both p1 and p2 point to the start of column-lists
  152859. ** for the same column (the column with index iCol1 and iCol2).
  152860. ** A column-list is a list of non-negative delta-encoded varints, each
  152861. ** incremented by 2 before being stored. Each list is terminated by a
  152862. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  152863. ** and writes the results to buffer p. p is left pointing to the byte
  152864. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  152865. ** written to the output.
  152866. */
  152867. fts3GetDeltaVarint(&p1, &i1);
  152868. fts3GetDeltaVarint(&p2, &i2);
  152869. do {
  152870. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  152871. iPrev -= 2;
  152872. if( i1==i2 ){
  152873. fts3ReadNextPos(&p1, &i1);
  152874. fts3ReadNextPos(&p2, &i2);
  152875. }else if( i1<i2 ){
  152876. fts3ReadNextPos(&p1, &i1);
  152877. }else{
  152878. fts3ReadNextPos(&p2, &i2);
  152879. }
  152880. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  152881. }else if( iCol1<iCol2 ){
  152882. p1 += fts3PutColNumber(&p, iCol1);
  152883. fts3ColumnlistCopy(&p, &p1);
  152884. }else{
  152885. p2 += fts3PutColNumber(&p, iCol2);
  152886. fts3ColumnlistCopy(&p, &p2);
  152887. }
  152888. }
  152889. *p++ = POS_END;
  152890. *pp = p;
  152891. *pp1 = p1 + 1;
  152892. *pp2 = p2 + 1;
  152893. return SQLITE_OK;
  152894. }
  152895. /*
  152896. ** This function is used to merge two position lists into one. When it is
  152897. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  152898. ** the part of a doclist that follows each document id. For example, if a row
  152899. ** contains:
  152900. **
  152901. ** 'a b c'|'x y z'|'a b b a'
  152902. **
  152903. ** Then the position list for this row for token 'b' would consist of:
  152904. **
  152905. ** 0x02 0x01 0x02 0x03 0x03 0x00
  152906. **
  152907. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  152908. ** byte following the 0x00 terminator of their respective position lists.
  152909. **
  152910. ** If isSaveLeft is 0, an entry is added to the output position list for
  152911. ** each position in *pp2 for which there exists one or more positions in
  152912. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  152913. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  152914. ** slots before it.
  152915. **
  152916. ** e.g. nToken==1 searches for adjacent positions.
  152917. */
  152918. static int fts3PoslistPhraseMerge(
  152919. char **pp, /* IN/OUT: Preallocated output buffer */
  152920. int nToken, /* Maximum difference in token positions */
  152921. int isSaveLeft, /* Save the left position */
  152922. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  152923. char **pp1, /* IN/OUT: Left input list */
  152924. char **pp2 /* IN/OUT: Right input list */
  152925. ){
  152926. char *p = *pp;
  152927. char *p1 = *pp1;
  152928. char *p2 = *pp2;
  152929. int iCol1 = 0;
  152930. int iCol2 = 0;
  152931. /* Never set both isSaveLeft and isExact for the same invocation. */
  152932. assert( isSaveLeft==0 || isExact==0 );
  152933. assert( p!=0 && *p1!=0 && *p2!=0 );
  152934. if( *p1==POS_COLUMN ){
  152935. p1++;
  152936. p1 += fts3GetVarint32(p1, &iCol1);
  152937. }
  152938. if( *p2==POS_COLUMN ){
  152939. p2++;
  152940. p2 += fts3GetVarint32(p2, &iCol2);
  152941. }
  152942. while( 1 ){
  152943. if( iCol1==iCol2 ){
  152944. char *pSave = p;
  152945. sqlite3_int64 iPrev = 0;
  152946. sqlite3_int64 iPos1 = 0;
  152947. sqlite3_int64 iPos2 = 0;
  152948. if( iCol1 ){
  152949. *p++ = POS_COLUMN;
  152950. p += sqlite3Fts3PutVarint(p, iCol1);
  152951. }
  152952. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  152953. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  152954. if( iPos1<0 || iPos2<0 ) break;
  152955. while( 1 ){
  152956. if( iPos2==iPos1+nToken
  152957. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  152958. ){
  152959. sqlite3_int64 iSave;
  152960. iSave = isSaveLeft ? iPos1 : iPos2;
  152961. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  152962. pSave = 0;
  152963. assert( p );
  152964. }
  152965. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  152966. if( (*p2&0xFE)==0 ) break;
  152967. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  152968. }else{
  152969. if( (*p1&0xFE)==0 ) break;
  152970. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  152971. }
  152972. }
  152973. if( pSave ){
  152974. assert( pp && p );
  152975. p = pSave;
  152976. }
  152977. fts3ColumnlistCopy(0, &p1);
  152978. fts3ColumnlistCopy(0, &p2);
  152979. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  152980. if( 0==*p1 || 0==*p2 ) break;
  152981. p1++;
  152982. p1 += fts3GetVarint32(p1, &iCol1);
  152983. p2++;
  152984. p2 += fts3GetVarint32(p2, &iCol2);
  152985. }
  152986. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  152987. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  152988. ** end of the position list, or the 0x01 that precedes the next
  152989. ** column-number in the position list.
  152990. */
  152991. else if( iCol1<iCol2 ){
  152992. fts3ColumnlistCopy(0, &p1);
  152993. if( 0==*p1 ) break;
  152994. p1++;
  152995. p1 += fts3GetVarint32(p1, &iCol1);
  152996. }else{
  152997. fts3ColumnlistCopy(0, &p2);
  152998. if( 0==*p2 ) break;
  152999. p2++;
  153000. p2 += fts3GetVarint32(p2, &iCol2);
  153001. }
  153002. }
  153003. fts3PoslistCopy(0, &p2);
  153004. fts3PoslistCopy(0, &p1);
  153005. *pp1 = p1;
  153006. *pp2 = p2;
  153007. if( *pp==p ){
  153008. return 0;
  153009. }
  153010. *p++ = 0x00;
  153011. *pp = p;
  153012. return 1;
  153013. }
  153014. /*
  153015. ** Merge two position-lists as required by the NEAR operator. The argument
  153016. ** position lists correspond to the left and right phrases of an expression
  153017. ** like:
  153018. **
  153019. ** "phrase 1" NEAR "phrase number 2"
  153020. **
  153021. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  153022. ** expression and *pp2 to the right. As usual, the indexes in the position
  153023. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  153024. ** in the example above).
  153025. **
  153026. ** The output position list - written to *pp - is a copy of *pp2 with those
  153027. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  153028. */
  153029. static int fts3PoslistNearMerge(
  153030. char **pp, /* Output buffer */
  153031. char *aTmp, /* Temporary buffer space */
  153032. int nRight, /* Maximum difference in token positions */
  153033. int nLeft, /* Maximum difference in token positions */
  153034. char **pp1, /* IN/OUT: Left input list */
  153035. char **pp2 /* IN/OUT: Right input list */
  153036. ){
  153037. char *p1 = *pp1;
  153038. char *p2 = *pp2;
  153039. char *pTmp1 = aTmp;
  153040. char *pTmp2;
  153041. char *aTmp2;
  153042. int res = 1;
  153043. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  153044. aTmp2 = pTmp2 = pTmp1;
  153045. *pp1 = p1;
  153046. *pp2 = p2;
  153047. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  153048. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  153049. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  153050. }else if( pTmp1!=aTmp ){
  153051. fts3PoslistCopy(pp, &aTmp);
  153052. }else if( pTmp2!=aTmp2 ){
  153053. fts3PoslistCopy(pp, &aTmp2);
  153054. }else{
  153055. res = 0;
  153056. }
  153057. return res;
  153058. }
  153059. /*
  153060. ** An instance of this function is used to merge together the (potentially
  153061. ** large number of) doclists for each term that matches a prefix query.
  153062. ** See function fts3TermSelectMerge() for details.
  153063. */
  153064. typedef struct TermSelect TermSelect;
  153065. struct TermSelect {
  153066. char *aaOutput[16]; /* Malloc'd output buffers */
  153067. int anOutput[16]; /* Size each output buffer in bytes */
  153068. };
  153069. /*
  153070. ** This function is used to read a single varint from a buffer. Parameter
  153071. ** pEnd points 1 byte past the end of the buffer. When this function is
  153072. ** called, if *pp points to pEnd or greater, then the end of the buffer
  153073. ** has been reached. In this case *pp is set to 0 and the function returns.
  153074. **
  153075. ** If *pp does not point to or past pEnd, then a single varint is read
  153076. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  153077. **
  153078. ** If bDescIdx is false, the value read is added to *pVal before returning.
  153079. ** If it is true, the value read is subtracted from *pVal before this
  153080. ** function returns.
  153081. */
  153082. static void fts3GetDeltaVarint3(
  153083. char **pp, /* IN/OUT: Point to read varint from */
  153084. char *pEnd, /* End of buffer */
  153085. int bDescIdx, /* True if docids are descending */
  153086. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  153087. ){
  153088. if( *pp>=pEnd ){
  153089. *pp = 0;
  153090. }else{
  153091. sqlite3_int64 iVal;
  153092. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  153093. if( bDescIdx ){
  153094. *pVal -= iVal;
  153095. }else{
  153096. *pVal += iVal;
  153097. }
  153098. }
  153099. }
  153100. /*
  153101. ** This function is used to write a single varint to a buffer. The varint
  153102. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  153103. ** end of the value written.
  153104. **
  153105. ** If *pbFirst is zero when this function is called, the value written to
  153106. ** the buffer is that of parameter iVal.
  153107. **
  153108. ** If *pbFirst is non-zero when this function is called, then the value
  153109. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  153110. ** (if bDescIdx is non-zero).
  153111. **
  153112. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  153113. ** to the value of parameter iVal.
  153114. */
  153115. static void fts3PutDeltaVarint3(
  153116. char **pp, /* IN/OUT: Output pointer */
  153117. int bDescIdx, /* True for descending docids */
  153118. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  153119. int *pbFirst, /* IN/OUT: True after first int written */
  153120. sqlite3_int64 iVal /* Write this value to the list */
  153121. ){
  153122. sqlite3_int64 iWrite;
  153123. if( bDescIdx==0 || *pbFirst==0 ){
  153124. iWrite = iVal - *piPrev;
  153125. }else{
  153126. iWrite = *piPrev - iVal;
  153127. }
  153128. assert( *pbFirst || *piPrev==0 );
  153129. assert( *pbFirst==0 || iWrite>0 );
  153130. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  153131. *piPrev = iVal;
  153132. *pbFirst = 1;
  153133. }
  153134. /*
  153135. ** This macro is used by various functions that merge doclists. The two
  153136. ** arguments are 64-bit docid values. If the value of the stack variable
  153137. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  153138. ** Otherwise, (i2-i1).
  153139. **
  153140. ** Using this makes it easier to write code that can merge doclists that are
  153141. ** sorted in either ascending or descending order.
  153142. */
  153143. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  153144. /*
  153145. ** This function does an "OR" merge of two doclists (output contains all
  153146. ** positions contained in either argument doclist). If the docids in the
  153147. ** input doclists are sorted in ascending order, parameter bDescDoclist
  153148. ** should be false. If they are sorted in ascending order, it should be
  153149. ** passed a non-zero value.
  153150. **
  153151. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  153152. ** containing the output doclist and SQLITE_OK is returned. In this case
  153153. ** *pnOut is set to the number of bytes in the output doclist.
  153154. **
  153155. ** If an error occurs, an SQLite error code is returned. The output values
  153156. ** are undefined in this case.
  153157. */
  153158. static int fts3DoclistOrMerge(
  153159. int bDescDoclist, /* True if arguments are desc */
  153160. char *a1, int n1, /* First doclist */
  153161. char *a2, int n2, /* Second doclist */
  153162. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  153163. ){
  153164. int rc = SQLITE_OK;
  153165. sqlite3_int64 i1 = 0;
  153166. sqlite3_int64 i2 = 0;
  153167. sqlite3_int64 iPrev = 0;
  153168. char *pEnd1 = &a1[n1];
  153169. char *pEnd2 = &a2[n2];
  153170. char *p1 = a1;
  153171. char *p2 = a2;
  153172. char *p;
  153173. char *aOut;
  153174. int bFirstOut = 0;
  153175. *paOut = 0;
  153176. *pnOut = 0;
  153177. /* Allocate space for the output. Both the input and output doclists
  153178. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  153179. ** then the first docid in each list is simply encoded as a varint. For
  153180. ** each subsequent docid, the varint stored is the difference between the
  153181. ** current and previous docid (a positive number - since the list is in
  153182. ** ascending order).
  153183. **
  153184. ** The first docid written to the output is therefore encoded using the
  153185. ** same number of bytes as it is in whichever of the input lists it is
  153186. ** read from. And each subsequent docid read from the same input list
  153187. ** consumes either the same or less bytes as it did in the input (since
  153188. ** the difference between it and the previous value in the output must
  153189. ** be a positive value less than or equal to the delta value read from
  153190. ** the input list). The same argument applies to all but the first docid
  153191. ** read from the 'other' list. And to the contents of all position lists
  153192. ** that will be copied and merged from the input to the output.
  153193. **
  153194. ** However, if the first docid copied to the output is a negative number,
  153195. ** then the encoding of the first docid from the 'other' input list may
  153196. ** be larger in the output than it was in the input (since the delta value
  153197. ** may be a larger positive integer than the actual docid).
  153198. **
  153199. ** The space required to store the output is therefore the sum of the
  153200. ** sizes of the two inputs, plus enough space for exactly one of the input
  153201. ** docids to grow.
  153202. **
  153203. ** A symetric argument may be made if the doclists are in descending
  153204. ** order.
  153205. */
  153206. aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING);
  153207. if( !aOut ) return SQLITE_NOMEM;
  153208. p = aOut;
  153209. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  153210. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  153211. while( p1 || p2 ){
  153212. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  153213. if( p2 && p1 && iDiff==0 ){
  153214. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  153215. rc = fts3PoslistMerge(&p, &p1, &p2);
  153216. if( rc ) break;
  153217. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  153218. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  153219. }else if( !p2 || (p1 && iDiff<0) ){
  153220. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  153221. fts3PoslistCopy(&p, &p1);
  153222. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  153223. }else{
  153224. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  153225. fts3PoslistCopy(&p, &p2);
  153226. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  153227. }
  153228. }
  153229. if( rc!=SQLITE_OK ){
  153230. sqlite3_free(aOut);
  153231. p = aOut = 0;
  153232. }else{
  153233. assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 );
  153234. memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING);
  153235. }
  153236. *paOut = aOut;
  153237. *pnOut = (int)(p-aOut);
  153238. return rc;
  153239. }
  153240. /*
  153241. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  153242. ** the output contains a copy of each position from the right-hand input
  153243. ** doclist for which there is a position in the left-hand input doclist
  153244. ** exactly nDist tokens before it.
  153245. **
  153246. ** If the docids in the input doclists are sorted in ascending order,
  153247. ** parameter bDescDoclist should be false. If they are sorted in ascending
  153248. ** order, it should be passed a non-zero value.
  153249. **
  153250. ** The right-hand input doclist is overwritten by this function.
  153251. */
  153252. static int fts3DoclistPhraseMerge(
  153253. int bDescDoclist, /* True if arguments are desc */
  153254. int nDist, /* Distance from left to right (1=adjacent) */
  153255. char *aLeft, int nLeft, /* Left doclist */
  153256. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  153257. ){
  153258. sqlite3_int64 i1 = 0;
  153259. sqlite3_int64 i2 = 0;
  153260. sqlite3_int64 iPrev = 0;
  153261. char *aRight = *paRight;
  153262. char *pEnd1 = &aLeft[nLeft];
  153263. char *pEnd2 = &aRight[*pnRight];
  153264. char *p1 = aLeft;
  153265. char *p2 = aRight;
  153266. char *p;
  153267. int bFirstOut = 0;
  153268. char *aOut;
  153269. assert( nDist>0 );
  153270. if( bDescDoclist ){
  153271. aOut = sqlite3_malloc64((sqlite3_int64)*pnRight + FTS3_VARINT_MAX);
  153272. if( aOut==0 ) return SQLITE_NOMEM;
  153273. }else{
  153274. aOut = aRight;
  153275. }
  153276. p = aOut;
  153277. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  153278. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  153279. while( p1 && p2 ){
  153280. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  153281. if( iDiff==0 ){
  153282. char *pSave = p;
  153283. sqlite3_int64 iPrevSave = iPrev;
  153284. int bFirstOutSave = bFirstOut;
  153285. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  153286. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  153287. p = pSave;
  153288. iPrev = iPrevSave;
  153289. bFirstOut = bFirstOutSave;
  153290. }
  153291. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  153292. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  153293. }else if( iDiff<0 ){
  153294. fts3PoslistCopy(0, &p1);
  153295. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  153296. }else{
  153297. fts3PoslistCopy(0, &p2);
  153298. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  153299. }
  153300. }
  153301. *pnRight = (int)(p - aOut);
  153302. if( bDescDoclist ){
  153303. sqlite3_free(aRight);
  153304. *paRight = aOut;
  153305. }
  153306. return SQLITE_OK;
  153307. }
  153308. /*
  153309. ** Argument pList points to a position list nList bytes in size. This
  153310. ** function checks to see if the position list contains any entries for
  153311. ** a token in position 0 (of any column). If so, it writes argument iDelta
  153312. ** to the output buffer pOut, followed by a position list consisting only
  153313. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  153314. ** The value returned is the number of bytes written to pOut (if any).
  153315. */
  153316. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  153317. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  153318. char *pList, /* Position list (no 0x00 term) */
  153319. int nList, /* Size of pList in bytes */
  153320. char *pOut /* Write output here */
  153321. ){
  153322. int nOut = 0;
  153323. int bWritten = 0; /* True once iDelta has been written */
  153324. char *p = pList;
  153325. char *pEnd = &pList[nList];
  153326. if( *p!=0x01 ){
  153327. if( *p==0x02 ){
  153328. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  153329. pOut[nOut++] = 0x02;
  153330. bWritten = 1;
  153331. }
  153332. fts3ColumnlistCopy(0, &p);
  153333. }
  153334. while( p<pEnd ){
  153335. sqlite3_int64 iCol;
  153336. p++;
  153337. p += sqlite3Fts3GetVarint(p, &iCol);
  153338. if( *p==0x02 ){
  153339. if( bWritten==0 ){
  153340. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  153341. bWritten = 1;
  153342. }
  153343. pOut[nOut++] = 0x01;
  153344. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  153345. pOut[nOut++] = 0x02;
  153346. }
  153347. fts3ColumnlistCopy(0, &p);
  153348. }
  153349. if( bWritten ){
  153350. pOut[nOut++] = 0x00;
  153351. }
  153352. return nOut;
  153353. }
  153354. /*
  153355. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  153356. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  153357. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  153358. **
  153359. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  153360. ** the responsibility of the caller to free any doclists left in the
  153361. ** TermSelect.aaOutput[] array.
  153362. */
  153363. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  153364. char *aOut = 0;
  153365. int nOut = 0;
  153366. int i;
  153367. /* Loop through the doclists in the aaOutput[] array. Merge them all
  153368. ** into a single doclist.
  153369. */
  153370. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  153371. if( pTS->aaOutput[i] ){
  153372. if( !aOut ){
  153373. aOut = pTS->aaOutput[i];
  153374. nOut = pTS->anOutput[i];
  153375. pTS->aaOutput[i] = 0;
  153376. }else{
  153377. int nNew;
  153378. char *aNew;
  153379. int rc = fts3DoclistOrMerge(p->bDescIdx,
  153380. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  153381. );
  153382. if( rc!=SQLITE_OK ){
  153383. sqlite3_free(aOut);
  153384. return rc;
  153385. }
  153386. sqlite3_free(pTS->aaOutput[i]);
  153387. sqlite3_free(aOut);
  153388. pTS->aaOutput[i] = 0;
  153389. aOut = aNew;
  153390. nOut = nNew;
  153391. }
  153392. }
  153393. }
  153394. pTS->aaOutput[0] = aOut;
  153395. pTS->anOutput[0] = nOut;
  153396. return SQLITE_OK;
  153397. }
  153398. /*
  153399. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  153400. ** as the first argument. The merge is an "OR" merge (see function
  153401. ** fts3DoclistOrMerge() for details).
  153402. **
  153403. ** This function is called with the doclist for each term that matches
  153404. ** a queried prefix. It merges all these doclists into one, the doclist
  153405. ** for the specified prefix. Since there can be a very large number of
  153406. ** doclists to merge, the merging is done pair-wise using the TermSelect
  153407. ** object.
  153408. **
  153409. ** This function returns SQLITE_OK if the merge is successful, or an
  153410. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  153411. */
  153412. static int fts3TermSelectMerge(
  153413. Fts3Table *p, /* FTS table handle */
  153414. TermSelect *pTS, /* TermSelect object to merge into */
  153415. char *aDoclist, /* Pointer to doclist */
  153416. int nDoclist /* Size of aDoclist in bytes */
  153417. ){
  153418. if( pTS->aaOutput[0]==0 ){
  153419. /* If this is the first term selected, copy the doclist to the output
  153420. ** buffer using memcpy().
  153421. **
  153422. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  153423. ** allocation. This is so as to ensure that the buffer is big enough
  153424. ** to hold the current doclist AND'd with any other doclist. If the
  153425. ** doclists are stored in order=ASC order, this padding would not be
  153426. ** required (since the size of [doclistA AND doclistB] is always less
  153427. ** than or equal to the size of [doclistA] in that case). But this is
  153428. ** not true for order=DESC. For example, a doclist containing (1, -1)
  153429. ** may be smaller than (-1), as in the first example the -1 may be stored
  153430. ** as a single-byte delta, whereas in the second it must be stored as a
  153431. ** FTS3_VARINT_MAX byte varint.
  153432. **
  153433. ** Similar padding is added in the fts3DoclistOrMerge() function.
  153434. */
  153435. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  153436. pTS->anOutput[0] = nDoclist;
  153437. if( pTS->aaOutput[0] ){
  153438. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  153439. memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX);
  153440. }else{
  153441. return SQLITE_NOMEM;
  153442. }
  153443. }else{
  153444. char *aMerge = aDoclist;
  153445. int nMerge = nDoclist;
  153446. int iOut;
  153447. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  153448. if( pTS->aaOutput[iOut]==0 ){
  153449. assert( iOut>0 );
  153450. pTS->aaOutput[iOut] = aMerge;
  153451. pTS->anOutput[iOut] = nMerge;
  153452. break;
  153453. }else{
  153454. char *aNew;
  153455. int nNew;
  153456. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  153457. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  153458. );
  153459. if( rc!=SQLITE_OK ){
  153460. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  153461. return rc;
  153462. }
  153463. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  153464. sqlite3_free(pTS->aaOutput[iOut]);
  153465. pTS->aaOutput[iOut] = 0;
  153466. aMerge = aNew;
  153467. nMerge = nNew;
  153468. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  153469. pTS->aaOutput[iOut] = aMerge;
  153470. pTS->anOutput[iOut] = nMerge;
  153471. }
  153472. }
  153473. }
  153474. }
  153475. return SQLITE_OK;
  153476. }
  153477. /*
  153478. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  153479. */
  153480. static int fts3SegReaderCursorAppend(
  153481. Fts3MultiSegReader *pCsr,
  153482. Fts3SegReader *pNew
  153483. ){
  153484. if( (pCsr->nSegment%16)==0 ){
  153485. Fts3SegReader **apNew;
  153486. sqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  153487. apNew = (Fts3SegReader **)sqlite3_realloc64(pCsr->apSegment, nByte);
  153488. if( !apNew ){
  153489. sqlite3Fts3SegReaderFree(pNew);
  153490. return SQLITE_NOMEM;
  153491. }
  153492. pCsr->apSegment = apNew;
  153493. }
  153494. pCsr->apSegment[pCsr->nSegment++] = pNew;
  153495. return SQLITE_OK;
  153496. }
  153497. /*
  153498. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  153499. ** 8th argument.
  153500. **
  153501. ** This function returns SQLITE_OK if successful, or an SQLite error code
  153502. ** otherwise.
  153503. */
  153504. static int fts3SegReaderCursor(
  153505. Fts3Table *p, /* FTS3 table handle */
  153506. int iLangid, /* Language id */
  153507. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  153508. int iLevel, /* Level of segments to scan */
  153509. const char *zTerm, /* Term to query for */
  153510. int nTerm, /* Size of zTerm in bytes */
  153511. int isPrefix, /* True for a prefix search */
  153512. int isScan, /* True to scan from zTerm to EOF */
  153513. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  153514. ){
  153515. int rc = SQLITE_OK; /* Error code */
  153516. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  153517. int rc2; /* Result of sqlite3_reset() */
  153518. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  153519. ** for the pending-terms. If this is a scan, then this call must be being
  153520. ** made by an fts4aux module, not an FTS table. In this case calling
  153521. ** Fts3SegReaderPending might segfault, as the data structures used by
  153522. ** fts4aux are not completely populated. So it's easiest to filter these
  153523. ** calls out here. */
  153524. if( iLevel<0 && p->aIndex ){
  153525. Fts3SegReader *pSeg = 0;
  153526. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  153527. if( rc==SQLITE_OK && pSeg ){
  153528. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  153529. }
  153530. }
  153531. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  153532. if( rc==SQLITE_OK ){
  153533. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  153534. }
  153535. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  153536. Fts3SegReader *pSeg = 0;
  153537. /* Read the values returned by the SELECT into local variables. */
  153538. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  153539. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  153540. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  153541. int nRoot = sqlite3_column_bytes(pStmt, 4);
  153542. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  153543. /* If zTerm is not NULL, and this segment is not stored entirely on its
  153544. ** root node, the range of leaves scanned can be reduced. Do this. */
  153545. if( iStartBlock && zTerm && zRoot ){
  153546. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  153547. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  153548. if( rc!=SQLITE_OK ) goto finished;
  153549. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  153550. }
  153551. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  153552. (isPrefix==0 && isScan==0),
  153553. iStartBlock, iLeavesEndBlock,
  153554. iEndBlock, zRoot, nRoot, &pSeg
  153555. );
  153556. if( rc!=SQLITE_OK ) goto finished;
  153557. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  153558. }
  153559. }
  153560. finished:
  153561. rc2 = sqlite3_reset(pStmt);
  153562. if( rc==SQLITE_DONE ) rc = rc2;
  153563. return rc;
  153564. }
  153565. /*
  153566. ** Set up a cursor object for iterating through a full-text index or a
  153567. ** single level therein.
  153568. */
  153569. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  153570. Fts3Table *p, /* FTS3 table handle */
  153571. int iLangid, /* Language-id to search */
  153572. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  153573. int iLevel, /* Level of segments to scan */
  153574. const char *zTerm, /* Term to query for */
  153575. int nTerm, /* Size of zTerm in bytes */
  153576. int isPrefix, /* True for a prefix search */
  153577. int isScan, /* True to scan from zTerm to EOF */
  153578. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  153579. ){
  153580. assert( iIndex>=0 && iIndex<p->nIndex );
  153581. assert( iLevel==FTS3_SEGCURSOR_ALL
  153582. || iLevel==FTS3_SEGCURSOR_PENDING
  153583. || iLevel>=0
  153584. );
  153585. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  153586. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  153587. assert( isPrefix==0 || isScan==0 );
  153588. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  153589. return fts3SegReaderCursor(
  153590. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  153591. );
  153592. }
  153593. /*
  153594. ** In addition to its current configuration, have the Fts3MultiSegReader
  153595. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  153596. **
  153597. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  153598. */
  153599. static int fts3SegReaderCursorAddZero(
  153600. Fts3Table *p, /* FTS virtual table handle */
  153601. int iLangid,
  153602. const char *zTerm, /* Term to scan doclist of */
  153603. int nTerm, /* Number of bytes in zTerm */
  153604. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  153605. ){
  153606. return fts3SegReaderCursor(p,
  153607. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  153608. );
  153609. }
  153610. /*
  153611. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  153612. ** if isPrefix is true, to scan the doclist for all terms for which
  153613. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  153614. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  153615. ** an SQLite error code.
  153616. **
  153617. ** It is the responsibility of the caller to free this object by eventually
  153618. ** passing it to fts3SegReaderCursorFree()
  153619. **
  153620. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  153621. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  153622. */
  153623. static int fts3TermSegReaderCursor(
  153624. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  153625. const char *zTerm, /* Term to query for */
  153626. int nTerm, /* Size of zTerm in bytes */
  153627. int isPrefix, /* True for a prefix search */
  153628. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  153629. ){
  153630. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  153631. int rc = SQLITE_NOMEM; /* Return code */
  153632. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  153633. if( pSegcsr ){
  153634. int i;
  153635. int bFound = 0; /* True once an index has been found */
  153636. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  153637. if( isPrefix ){
  153638. for(i=1; bFound==0 && i<p->nIndex; i++){
  153639. if( p->aIndex[i].nPrefix==nTerm ){
  153640. bFound = 1;
  153641. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  153642. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  153643. );
  153644. pSegcsr->bLookup = 1;
  153645. }
  153646. }
  153647. for(i=1; bFound==0 && i<p->nIndex; i++){
  153648. if( p->aIndex[i].nPrefix==nTerm+1 ){
  153649. bFound = 1;
  153650. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  153651. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  153652. );
  153653. if( rc==SQLITE_OK ){
  153654. rc = fts3SegReaderCursorAddZero(
  153655. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  153656. );
  153657. }
  153658. }
  153659. }
  153660. }
  153661. if( bFound==0 ){
  153662. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  153663. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  153664. );
  153665. pSegcsr->bLookup = !isPrefix;
  153666. }
  153667. }
  153668. *ppSegcsr = pSegcsr;
  153669. return rc;
  153670. }
  153671. /*
  153672. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  153673. */
  153674. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  153675. sqlite3Fts3SegReaderFinish(pSegcsr);
  153676. sqlite3_free(pSegcsr);
  153677. }
  153678. /*
  153679. ** This function retrieves the doclist for the specified term (or term
  153680. ** prefix) from the database.
  153681. */
  153682. static int fts3TermSelect(
  153683. Fts3Table *p, /* Virtual table handle */
  153684. Fts3PhraseToken *pTok, /* Token to query for */
  153685. int iColumn, /* Column to query (or -ve for all columns) */
  153686. int *pnOut, /* OUT: Size of buffer at *ppOut */
  153687. char **ppOut /* OUT: Malloced result buffer */
  153688. ){
  153689. int rc; /* Return code */
  153690. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  153691. TermSelect tsc; /* Object for pair-wise doclist merging */
  153692. Fts3SegFilter filter; /* Segment term filter configuration */
  153693. pSegcsr = pTok->pSegcsr;
  153694. memset(&tsc, 0, sizeof(TermSelect));
  153695. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  153696. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  153697. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  153698. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  153699. filter.iCol = iColumn;
  153700. filter.zTerm = pTok->z;
  153701. filter.nTerm = pTok->n;
  153702. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  153703. while( SQLITE_OK==rc
  153704. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  153705. ){
  153706. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  153707. }
  153708. if( rc==SQLITE_OK ){
  153709. rc = fts3TermSelectFinishMerge(p, &tsc);
  153710. }
  153711. if( rc==SQLITE_OK ){
  153712. *ppOut = tsc.aaOutput[0];
  153713. *pnOut = tsc.anOutput[0];
  153714. }else{
  153715. int i;
  153716. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  153717. sqlite3_free(tsc.aaOutput[i]);
  153718. }
  153719. }
  153720. fts3SegReaderCursorFree(pSegcsr);
  153721. pTok->pSegcsr = 0;
  153722. return rc;
  153723. }
  153724. /*
  153725. ** This function counts the total number of docids in the doclist stored
  153726. ** in buffer aList[], size nList bytes.
  153727. **
  153728. ** If the isPoslist argument is true, then it is assumed that the doclist
  153729. ** contains a position-list following each docid. Otherwise, it is assumed
  153730. ** that the doclist is simply a list of docids stored as delta encoded
  153731. ** varints.
  153732. */
  153733. static int fts3DoclistCountDocids(char *aList, int nList){
  153734. int nDoc = 0; /* Return value */
  153735. if( aList ){
  153736. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  153737. char *p = aList; /* Cursor */
  153738. while( p<aEnd ){
  153739. nDoc++;
  153740. while( (*p++)&0x80 ); /* Skip docid varint */
  153741. fts3PoslistCopy(0, &p); /* Skip over position list */
  153742. }
  153743. }
  153744. return nDoc;
  153745. }
  153746. /*
  153747. ** Advance the cursor to the next row in the %_content table that
  153748. ** matches the search criteria. For a MATCH search, this will be
  153749. ** the next row that matches. For a full-table scan, this will be
  153750. ** simply the next row in the %_content table. For a docid lookup,
  153751. ** this routine simply sets the EOF flag.
  153752. **
  153753. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  153754. ** even if we reach end-of-file. The fts3EofMethod() will be called
  153755. ** subsequently to determine whether or not an EOF was hit.
  153756. */
  153757. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  153758. int rc;
  153759. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  153760. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  153761. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  153762. pCsr->isEof = 1;
  153763. rc = sqlite3_reset(pCsr->pStmt);
  153764. }else{
  153765. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  153766. rc = SQLITE_OK;
  153767. }
  153768. }else{
  153769. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  153770. }
  153771. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  153772. return rc;
  153773. }
  153774. /*
  153775. ** The following are copied from sqliteInt.h.
  153776. **
  153777. ** Constants for the largest and smallest possible 64-bit signed integers.
  153778. ** These macros are designed to work correctly on both 32-bit and 64-bit
  153779. ** compilers.
  153780. */
  153781. #ifndef SQLITE_AMALGAMATION
  153782. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  153783. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  153784. #endif
  153785. /*
  153786. ** If the numeric type of argument pVal is "integer", then return it
  153787. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  153788. ** the second parameter, iDefault.
  153789. */
  153790. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  153791. if( pVal ){
  153792. int eType = sqlite3_value_numeric_type(pVal);
  153793. if( eType==SQLITE_INTEGER ){
  153794. return sqlite3_value_int64(pVal);
  153795. }
  153796. }
  153797. return iDefault;
  153798. }
  153799. /*
  153800. ** This is the xFilter interface for the virtual table. See
  153801. ** the virtual table xFilter method documentation for additional
  153802. ** information.
  153803. **
  153804. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  153805. ** the %_content table.
  153806. **
  153807. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  153808. ** in the %_content table.
  153809. **
  153810. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  153811. ** column on the left-hand side of the MATCH operator is column
  153812. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  153813. ** side of the MATCH operator.
  153814. */
  153815. static int fts3FilterMethod(
  153816. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  153817. int idxNum, /* Strategy index */
  153818. const char *idxStr, /* Unused */
  153819. int nVal, /* Number of elements in apVal */
  153820. sqlite3_value **apVal /* Arguments for the indexing scheme */
  153821. ){
  153822. int rc = SQLITE_OK;
  153823. char *zSql; /* SQL statement used to access %_content */
  153824. int eSearch;
  153825. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  153826. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  153827. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  153828. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  153829. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  153830. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  153831. int iIdx;
  153832. UNUSED_PARAMETER(idxStr);
  153833. UNUSED_PARAMETER(nVal);
  153834. eSearch = (idxNum & 0x0000FFFF);
  153835. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  153836. assert( p->pSegments==0 );
  153837. /* Collect arguments into local variables */
  153838. iIdx = 0;
  153839. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  153840. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  153841. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  153842. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  153843. assert( iIdx==nVal );
  153844. /* In case the cursor has been used before, clear it now. */
  153845. fts3ClearCursor(pCsr);
  153846. /* Set the lower and upper bounds on docids to return */
  153847. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  153848. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  153849. if( idxStr ){
  153850. pCsr->bDesc = (idxStr[0]=='D');
  153851. }else{
  153852. pCsr->bDesc = p->bDescIdx;
  153853. }
  153854. pCsr->eSearch = (i16)eSearch;
  153855. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  153856. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  153857. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  153858. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  153859. return SQLITE_NOMEM;
  153860. }
  153861. pCsr->iLangid = 0;
  153862. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  153863. assert( p->base.zErrMsg==0 );
  153864. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  153865. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  153866. &p->base.zErrMsg
  153867. );
  153868. if( rc!=SQLITE_OK ){
  153869. return rc;
  153870. }
  153871. rc = fts3EvalStart(pCsr);
  153872. sqlite3Fts3SegmentsClose(p);
  153873. if( rc!=SQLITE_OK ) return rc;
  153874. pCsr->pNextId = pCsr->aDoclist;
  153875. pCsr->iPrevId = 0;
  153876. }
  153877. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  153878. ** statement loops through all rows of the %_content table. For a
  153879. ** full-text query or docid lookup, the statement retrieves a single
  153880. ** row by docid.
  153881. */
  153882. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  153883. if( pDocidGe || pDocidLe ){
  153884. zSql = sqlite3_mprintf(
  153885. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  153886. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  153887. (pCsr->bDesc ? "DESC" : "ASC")
  153888. );
  153889. }else{
  153890. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  153891. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  153892. );
  153893. }
  153894. if( zSql ){
  153895. rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  153896. sqlite3_free(zSql);
  153897. }else{
  153898. rc = SQLITE_NOMEM;
  153899. }
  153900. }else if( eSearch==FTS3_DOCID_SEARCH ){
  153901. rc = fts3CursorSeekStmt(pCsr);
  153902. if( rc==SQLITE_OK ){
  153903. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  153904. }
  153905. }
  153906. if( rc!=SQLITE_OK ) return rc;
  153907. return fts3NextMethod(pCursor);
  153908. }
  153909. /*
  153910. ** This is the xEof method of the virtual table. SQLite calls this
  153911. ** routine to find out if it has reached the end of a result set.
  153912. */
  153913. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  153914. Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
  153915. if( pCsr->isEof ){
  153916. fts3ClearCursor(pCsr);
  153917. pCsr->isEof = 1;
  153918. }
  153919. return pCsr->isEof;
  153920. }
  153921. /*
  153922. ** This is the xRowid method. The SQLite core calls this routine to
  153923. ** retrieve the rowid for the current row of the result set. fts3
  153924. ** exposes %_content.docid as the rowid for the virtual table. The
  153925. ** rowid should be written to *pRowid.
  153926. */
  153927. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  153928. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  153929. *pRowid = pCsr->iPrevId;
  153930. return SQLITE_OK;
  153931. }
  153932. /*
  153933. ** This is the xColumn method, called by SQLite to request a value from
  153934. ** the row that the supplied cursor currently points to.
  153935. **
  153936. ** If:
  153937. **
  153938. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  153939. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  153940. ** (iCol == p->nColumn+1) -> Docid column
  153941. ** (iCol == p->nColumn+2) -> Langid column
  153942. */
  153943. static int fts3ColumnMethod(
  153944. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  153945. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  153946. int iCol /* Index of column to read value from */
  153947. ){
  153948. int rc = SQLITE_OK; /* Return Code */
  153949. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  153950. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  153951. /* The column value supplied by SQLite must be in range. */
  153952. assert( iCol>=0 && iCol<=p->nColumn+2 );
  153953. switch( iCol-p->nColumn ){
  153954. case 0:
  153955. /* The special 'table-name' column */
  153956. sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
  153957. break;
  153958. case 1:
  153959. /* The docid column */
  153960. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  153961. break;
  153962. case 2:
  153963. if( pCsr->pExpr ){
  153964. sqlite3_result_int64(pCtx, pCsr->iLangid);
  153965. break;
  153966. }else if( p->zLanguageid==0 ){
  153967. sqlite3_result_int(pCtx, 0);
  153968. break;
  153969. }else{
  153970. iCol = p->nColumn;
  153971. /* fall-through */
  153972. }
  153973. default:
  153974. /* A user column. Or, if this is a full-table scan, possibly the
  153975. ** language-id column. Seek the cursor. */
  153976. rc = fts3CursorSeek(0, pCsr);
  153977. if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
  153978. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  153979. }
  153980. break;
  153981. }
  153982. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  153983. return rc;
  153984. }
  153985. /*
  153986. ** This function is the implementation of the xUpdate callback used by
  153987. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  153988. ** inserted, updated or deleted.
  153989. */
  153990. static int fts3UpdateMethod(
  153991. sqlite3_vtab *pVtab, /* Virtual table handle */
  153992. int nArg, /* Size of argument array */
  153993. sqlite3_value **apVal, /* Array of arguments */
  153994. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  153995. ){
  153996. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  153997. }
  153998. /*
  153999. ** Implementation of xSync() method. Flush the contents of the pending-terms
  154000. ** hash-table to the database.
  154001. */
  154002. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  154003. /* Following an incremental-merge operation, assuming that the input
  154004. ** segments are not completely consumed (the usual case), they are updated
  154005. ** in place to remove the entries that have already been merged. This
  154006. ** involves updating the leaf block that contains the smallest unmerged
  154007. ** entry and each block (if any) between the leaf and the root node. So
  154008. ** if the height of the input segment b-trees is N, and input segments
  154009. ** are merged eight at a time, updating the input segments at the end
  154010. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  154011. ** small - often between 0 and 2. So the overhead of the incremental
  154012. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  154013. ** dwarfing the actual productive work accomplished, the incremental merge
  154014. ** is only attempted if it will write at least 64 leaf blocks. Hence
  154015. ** nMinMerge.
  154016. **
  154017. ** Of course, updating the input segments also involves deleting a bunch
  154018. ** of blocks from the segments table. But this is not considered overhead
  154019. ** as it would also be required by a crisis-merge that used the same input
  154020. ** segments.
  154021. */
  154022. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  154023. Fts3Table *p = (Fts3Table*)pVtab;
  154024. int rc;
  154025. i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
  154026. rc = sqlite3Fts3PendingTermsFlush(p);
  154027. if( rc==SQLITE_OK
  154028. && p->nLeafAdd>(nMinMerge/16)
  154029. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  154030. ){
  154031. int mxLevel = 0; /* Maximum relative level value in db */
  154032. int A; /* Incr-merge parameter A */
  154033. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  154034. assert( rc==SQLITE_OK || mxLevel==0 );
  154035. A = p->nLeafAdd * mxLevel;
  154036. A += (A/2);
  154037. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  154038. }
  154039. sqlite3Fts3SegmentsClose(p);
  154040. sqlite3_set_last_insert_rowid(p->db, iLastRowid);
  154041. return rc;
  154042. }
  154043. /*
  154044. ** If it is currently unknown whether or not the FTS table has an %_stat
  154045. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  154046. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  154047. ** if an error occurs.
  154048. */
  154049. static int fts3SetHasStat(Fts3Table *p){
  154050. int rc = SQLITE_OK;
  154051. if( p->bHasStat==2 ){
  154052. char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
  154053. if( zTbl ){
  154054. int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
  154055. sqlite3_free(zTbl);
  154056. p->bHasStat = (res==SQLITE_OK);
  154057. }else{
  154058. rc = SQLITE_NOMEM;
  154059. }
  154060. }
  154061. return rc;
  154062. }
  154063. /*
  154064. ** Implementation of xBegin() method.
  154065. */
  154066. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  154067. Fts3Table *p = (Fts3Table*)pVtab;
  154068. UNUSED_PARAMETER(pVtab);
  154069. assert( p->pSegments==0 );
  154070. assert( p->nPendingData==0 );
  154071. assert( p->inTransaction!=1 );
  154072. TESTONLY( p->inTransaction = 1 );
  154073. TESTONLY( p->mxSavepoint = -1; );
  154074. p->nLeafAdd = 0;
  154075. return fts3SetHasStat(p);
  154076. }
  154077. /*
  154078. ** Implementation of xCommit() method. This is a no-op. The contents of
  154079. ** the pending-terms hash-table have already been flushed into the database
  154080. ** by fts3SyncMethod().
  154081. */
  154082. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  154083. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  154084. UNUSED_PARAMETER(pVtab);
  154085. assert( p->nPendingData==0 );
  154086. assert( p->inTransaction!=0 );
  154087. assert( p->pSegments==0 );
  154088. TESTONLY( p->inTransaction = 0 );
  154089. TESTONLY( p->mxSavepoint = -1; );
  154090. return SQLITE_OK;
  154091. }
  154092. /*
  154093. ** Implementation of xRollback(). Discard the contents of the pending-terms
  154094. ** hash-table. Any changes made to the database are reverted by SQLite.
  154095. */
  154096. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  154097. Fts3Table *p = (Fts3Table*)pVtab;
  154098. sqlite3Fts3PendingTermsClear(p);
  154099. assert( p->inTransaction!=0 );
  154100. TESTONLY( p->inTransaction = 0 );
  154101. TESTONLY( p->mxSavepoint = -1; );
  154102. return SQLITE_OK;
  154103. }
  154104. /*
  154105. ** When called, *ppPoslist must point to the byte immediately following the
  154106. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  154107. ** moves *ppPoslist so that it instead points to the first byte of the
  154108. ** same position list.
  154109. */
  154110. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  154111. char *p = &(*ppPoslist)[-2];
  154112. char c = 0;
  154113. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  154114. while( p>pStart && (c=*p--)==0 );
  154115. /* Search backwards for a varint with value zero (the end of the previous
  154116. ** poslist). This is an 0x00 byte preceded by some byte that does not
  154117. ** have the 0x80 bit set. */
  154118. while( p>pStart && (*p & 0x80) | c ){
  154119. c = *p--;
  154120. }
  154121. assert( p==pStart || c==0 );
  154122. /* At this point p points to that preceding byte without the 0x80 bit
  154123. ** set. So to find the start of the poslist, skip forward 2 bytes then
  154124. ** over a varint.
  154125. **
  154126. ** Normally. The other case is that p==pStart and the poslist to return
  154127. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  154128. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  154129. ** is required for cases where the first byte of a doclist and the
  154130. ** doclist is empty. For example, if the first docid is 10, a doclist
  154131. ** that begins with:
  154132. **
  154133. ** 0x0A 0x00 <next docid delta varint>
  154134. */
  154135. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  154136. while( *p++&0x80 );
  154137. *ppPoslist = p;
  154138. }
  154139. /*
  154140. ** Helper function used by the implementation of the overloaded snippet(),
  154141. ** offsets() and optimize() SQL functions.
  154142. **
  154143. ** If the value passed as the third argument is a blob of size
  154144. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  154145. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  154146. ** message is written to context pContext and SQLITE_ERROR returned. The
  154147. ** string passed via zFunc is used as part of the error message.
  154148. */
  154149. static int fts3FunctionArg(
  154150. sqlite3_context *pContext, /* SQL function call context */
  154151. const char *zFunc, /* Function name */
  154152. sqlite3_value *pVal, /* argv[0] passed to function */
  154153. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  154154. ){
  154155. int rc;
  154156. *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
  154157. if( (*ppCsr)!=0 ){
  154158. rc = SQLITE_OK;
  154159. }else{
  154160. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  154161. sqlite3_result_error(pContext, zErr, -1);
  154162. sqlite3_free(zErr);
  154163. rc = SQLITE_ERROR;
  154164. }
  154165. return rc;
  154166. }
  154167. /*
  154168. ** Implementation of the snippet() function for FTS3
  154169. */
  154170. static void fts3SnippetFunc(
  154171. sqlite3_context *pContext, /* SQLite function call context */
  154172. int nVal, /* Size of apVal[] array */
  154173. sqlite3_value **apVal /* Array of arguments */
  154174. ){
  154175. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  154176. const char *zStart = "<b>";
  154177. const char *zEnd = "</b>";
  154178. const char *zEllipsis = "<b>...</b>";
  154179. int iCol = -1;
  154180. int nToken = 15; /* Default number of tokens in snippet */
  154181. /* There must be at least one argument passed to this function (otherwise
  154182. ** the non-overloaded version would have been called instead of this one).
  154183. */
  154184. assert( nVal>=1 );
  154185. if( nVal>6 ){
  154186. sqlite3_result_error(pContext,
  154187. "wrong number of arguments to function snippet()", -1);
  154188. return;
  154189. }
  154190. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  154191. switch( nVal ){
  154192. case 6: nToken = sqlite3_value_int(apVal[5]);
  154193. case 5: iCol = sqlite3_value_int(apVal[4]);
  154194. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  154195. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  154196. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  154197. }
  154198. if( !zEllipsis || !zEnd || !zStart ){
  154199. sqlite3_result_error_nomem(pContext);
  154200. }else if( nToken==0 ){
  154201. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  154202. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  154203. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  154204. }
  154205. }
  154206. /*
  154207. ** Implementation of the offsets() function for FTS3
  154208. */
  154209. static void fts3OffsetsFunc(
  154210. sqlite3_context *pContext, /* SQLite function call context */
  154211. int nVal, /* Size of argument array */
  154212. sqlite3_value **apVal /* Array of arguments */
  154213. ){
  154214. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  154215. UNUSED_PARAMETER(nVal);
  154216. assert( nVal==1 );
  154217. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  154218. assert( pCsr );
  154219. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  154220. sqlite3Fts3Offsets(pContext, pCsr);
  154221. }
  154222. }
  154223. /*
  154224. ** Implementation of the special optimize() function for FTS3. This
  154225. ** function merges all segments in the database to a single segment.
  154226. ** Example usage is:
  154227. **
  154228. ** SELECT optimize(t) FROM t LIMIT 1;
  154229. **
  154230. ** where 't' is the name of an FTS3 table.
  154231. */
  154232. static void fts3OptimizeFunc(
  154233. sqlite3_context *pContext, /* SQLite function call context */
  154234. int nVal, /* Size of argument array */
  154235. sqlite3_value **apVal /* Array of arguments */
  154236. ){
  154237. int rc; /* Return code */
  154238. Fts3Table *p; /* Virtual table handle */
  154239. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  154240. UNUSED_PARAMETER(nVal);
  154241. assert( nVal==1 );
  154242. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  154243. p = (Fts3Table *)pCursor->base.pVtab;
  154244. assert( p );
  154245. rc = sqlite3Fts3Optimize(p);
  154246. switch( rc ){
  154247. case SQLITE_OK:
  154248. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  154249. break;
  154250. case SQLITE_DONE:
  154251. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  154252. break;
  154253. default:
  154254. sqlite3_result_error_code(pContext, rc);
  154255. break;
  154256. }
  154257. }
  154258. /*
  154259. ** Implementation of the matchinfo() function for FTS3
  154260. */
  154261. static void fts3MatchinfoFunc(
  154262. sqlite3_context *pContext, /* SQLite function call context */
  154263. int nVal, /* Size of argument array */
  154264. sqlite3_value **apVal /* Array of arguments */
  154265. ){
  154266. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  154267. assert( nVal==1 || nVal==2 );
  154268. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  154269. const char *zArg = 0;
  154270. if( nVal>1 ){
  154271. zArg = (const char *)sqlite3_value_text(apVal[1]);
  154272. }
  154273. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  154274. }
  154275. }
  154276. /*
  154277. ** This routine implements the xFindFunction method for the FTS3
  154278. ** virtual table.
  154279. */
  154280. static int fts3FindFunctionMethod(
  154281. sqlite3_vtab *pVtab, /* Virtual table handle */
  154282. int nArg, /* Number of SQL function arguments */
  154283. const char *zName, /* Name of SQL function */
  154284. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  154285. void **ppArg /* Unused */
  154286. ){
  154287. struct Overloaded {
  154288. const char *zName;
  154289. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  154290. } aOverload[] = {
  154291. { "snippet", fts3SnippetFunc },
  154292. { "offsets", fts3OffsetsFunc },
  154293. { "optimize", fts3OptimizeFunc },
  154294. { "matchinfo", fts3MatchinfoFunc },
  154295. };
  154296. int i; /* Iterator variable */
  154297. UNUSED_PARAMETER(pVtab);
  154298. UNUSED_PARAMETER(nArg);
  154299. UNUSED_PARAMETER(ppArg);
  154300. for(i=0; i<SizeofArray(aOverload); i++){
  154301. if( strcmp(zName, aOverload[i].zName)==0 ){
  154302. *pxFunc = aOverload[i].xFunc;
  154303. return 1;
  154304. }
  154305. }
  154306. /* No function of the specified name was found. Return 0. */
  154307. return 0;
  154308. }
  154309. /*
  154310. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  154311. */
  154312. static int fts3RenameMethod(
  154313. sqlite3_vtab *pVtab, /* Virtual table handle */
  154314. const char *zName /* New name of table */
  154315. ){
  154316. Fts3Table *p = (Fts3Table *)pVtab;
  154317. sqlite3 *db = p->db; /* Database connection */
  154318. int rc; /* Return Code */
  154319. /* At this point it must be known if the %_stat table exists or not.
  154320. ** So bHasStat may not be 2. */
  154321. rc = fts3SetHasStat(p);
  154322. /* As it happens, the pending terms table is always empty here. This is
  154323. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  154324. ** always opens a savepoint transaction. And the xSavepoint() method
  154325. ** flushes the pending terms table. But leave the (no-op) call to
  154326. ** PendingTermsFlush() in in case that changes.
  154327. */
  154328. assert( p->nPendingData==0 );
  154329. if( rc==SQLITE_OK ){
  154330. rc = sqlite3Fts3PendingTermsFlush(p);
  154331. }
  154332. if( p->zContentTbl==0 ){
  154333. fts3DbExec(&rc, db,
  154334. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  154335. p->zDb, p->zName, zName
  154336. );
  154337. }
  154338. if( p->bHasDocsize ){
  154339. fts3DbExec(&rc, db,
  154340. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  154341. p->zDb, p->zName, zName
  154342. );
  154343. }
  154344. if( p->bHasStat ){
  154345. fts3DbExec(&rc, db,
  154346. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  154347. p->zDb, p->zName, zName
  154348. );
  154349. }
  154350. fts3DbExec(&rc, db,
  154351. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  154352. p->zDb, p->zName, zName
  154353. );
  154354. fts3DbExec(&rc, db,
  154355. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  154356. p->zDb, p->zName, zName
  154357. );
  154358. return rc;
  154359. }
  154360. /*
  154361. ** The xSavepoint() method.
  154362. **
  154363. ** Flush the contents of the pending-terms table to disk.
  154364. */
  154365. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  154366. int rc = SQLITE_OK;
  154367. UNUSED_PARAMETER(iSavepoint);
  154368. assert( ((Fts3Table *)pVtab)->inTransaction );
  154369. assert( ((Fts3Table *)pVtab)->mxSavepoint <= iSavepoint );
  154370. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  154371. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  154372. rc = fts3SyncMethod(pVtab);
  154373. }
  154374. return rc;
  154375. }
  154376. /*
  154377. ** The xRelease() method.
  154378. **
  154379. ** This is a no-op.
  154380. */
  154381. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  154382. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  154383. UNUSED_PARAMETER(iSavepoint);
  154384. UNUSED_PARAMETER(pVtab);
  154385. assert( p->inTransaction );
  154386. assert( p->mxSavepoint >= iSavepoint );
  154387. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  154388. return SQLITE_OK;
  154389. }
  154390. /*
  154391. ** The xRollbackTo() method.
  154392. **
  154393. ** Discard the contents of the pending terms table.
  154394. */
  154395. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  154396. Fts3Table *p = (Fts3Table*)pVtab;
  154397. UNUSED_PARAMETER(iSavepoint);
  154398. assert( p->inTransaction );
  154399. TESTONLY( p->mxSavepoint = iSavepoint );
  154400. sqlite3Fts3PendingTermsClear(p);
  154401. return SQLITE_OK;
  154402. }
  154403. /*
  154404. ** Return true if zName is the extension on one of the shadow tables used
  154405. ** by this module.
  154406. */
  154407. static int fts3ShadowName(const char *zName){
  154408. static const char *azName[] = {
  154409. "content", "docsize", "segdir", "segments", "stat",
  154410. };
  154411. unsigned int i;
  154412. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  154413. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  154414. }
  154415. return 0;
  154416. }
  154417. static const sqlite3_module fts3Module = {
  154418. /* iVersion */ 3,
  154419. /* xCreate */ fts3CreateMethod,
  154420. /* xConnect */ fts3ConnectMethod,
  154421. /* xBestIndex */ fts3BestIndexMethod,
  154422. /* xDisconnect */ fts3DisconnectMethod,
  154423. /* xDestroy */ fts3DestroyMethod,
  154424. /* xOpen */ fts3OpenMethod,
  154425. /* xClose */ fts3CloseMethod,
  154426. /* xFilter */ fts3FilterMethod,
  154427. /* xNext */ fts3NextMethod,
  154428. /* xEof */ fts3EofMethod,
  154429. /* xColumn */ fts3ColumnMethod,
  154430. /* xRowid */ fts3RowidMethod,
  154431. /* xUpdate */ fts3UpdateMethod,
  154432. /* xBegin */ fts3BeginMethod,
  154433. /* xSync */ fts3SyncMethod,
  154434. /* xCommit */ fts3CommitMethod,
  154435. /* xRollback */ fts3RollbackMethod,
  154436. /* xFindFunction */ fts3FindFunctionMethod,
  154437. /* xRename */ fts3RenameMethod,
  154438. /* xSavepoint */ fts3SavepointMethod,
  154439. /* xRelease */ fts3ReleaseMethod,
  154440. /* xRollbackTo */ fts3RollbackToMethod,
  154441. /* xShadowName */ fts3ShadowName,
  154442. };
  154443. /*
  154444. ** This function is registered as the module destructor (called when an
  154445. ** FTS3 enabled database connection is closed). It frees the memory
  154446. ** allocated for the tokenizer hash table.
  154447. */
  154448. static void hashDestroy(void *p){
  154449. Fts3Hash *pHash = (Fts3Hash *)p;
  154450. sqlite3Fts3HashClear(pHash);
  154451. sqlite3_free(pHash);
  154452. }
  154453. /*
  154454. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  154455. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  154456. ** respectively. The following three forward declarations are for functions
  154457. ** declared in these files used to retrieve the respective implementations.
  154458. **
  154459. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  154460. ** to by the argument to point to the "simple" tokenizer implementation.
  154461. ** And so on.
  154462. */
  154463. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  154464. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  154465. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  154466. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  154467. #endif
  154468. #ifdef SQLITE_ENABLE_ICU
  154469. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  154470. #endif
  154471. /*
  154472. ** Initialize the fts3 extension. If this extension is built as part
  154473. ** of the sqlite library, then this function is called directly by
  154474. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  154475. ** function is called by the sqlite3_extension_init() entry point.
  154476. */
  154477. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  154478. int rc = SQLITE_OK;
  154479. Fts3Hash *pHash = 0;
  154480. const sqlite3_tokenizer_module *pSimple = 0;
  154481. const sqlite3_tokenizer_module *pPorter = 0;
  154482. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  154483. const sqlite3_tokenizer_module *pUnicode = 0;
  154484. #endif
  154485. #ifdef SQLITE_ENABLE_ICU
  154486. const sqlite3_tokenizer_module *pIcu = 0;
  154487. sqlite3Fts3IcuTokenizerModule(&pIcu);
  154488. #endif
  154489. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  154490. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  154491. #endif
  154492. #ifdef SQLITE_TEST
  154493. rc = sqlite3Fts3InitTerm(db);
  154494. if( rc!=SQLITE_OK ) return rc;
  154495. #endif
  154496. rc = sqlite3Fts3InitAux(db);
  154497. if( rc!=SQLITE_OK ) return rc;
  154498. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  154499. sqlite3Fts3PorterTokenizerModule(&pPorter);
  154500. /* Allocate and initialize the hash-table used to store tokenizers. */
  154501. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  154502. if( !pHash ){
  154503. rc = SQLITE_NOMEM;
  154504. }else{
  154505. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  154506. }
  154507. /* Load the built-in tokenizers into the hash table */
  154508. if( rc==SQLITE_OK ){
  154509. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  154510. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  154511. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  154512. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  154513. #endif
  154514. #ifdef SQLITE_ENABLE_ICU
  154515. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  154516. #endif
  154517. ){
  154518. rc = SQLITE_NOMEM;
  154519. }
  154520. }
  154521. #ifdef SQLITE_TEST
  154522. if( rc==SQLITE_OK ){
  154523. rc = sqlite3Fts3ExprInitTestInterface(db, pHash);
  154524. }
  154525. #endif
  154526. /* Create the virtual table wrapper around the hash-table and overload
  154527. ** the four scalar functions. If this is successful, register the
  154528. ** module with sqlite.
  154529. */
  154530. if( SQLITE_OK==rc
  154531. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  154532. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  154533. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  154534. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  154535. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  154536. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  154537. ){
  154538. rc = sqlite3_create_module_v2(
  154539. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  154540. );
  154541. if( rc==SQLITE_OK ){
  154542. rc = sqlite3_create_module_v2(
  154543. db, "fts4", &fts3Module, (void *)pHash, 0
  154544. );
  154545. }
  154546. if( rc==SQLITE_OK ){
  154547. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  154548. }
  154549. return rc;
  154550. }
  154551. /* An error has occurred. Delete the hash table and return the error code. */
  154552. assert( rc!=SQLITE_OK );
  154553. if( pHash ){
  154554. sqlite3Fts3HashClear(pHash);
  154555. sqlite3_free(pHash);
  154556. }
  154557. return rc;
  154558. }
  154559. /*
  154560. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  154561. ** by pExpr.
  154562. **
  154563. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  154564. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  154565. ** Fts3SegReader objects internally to provide an interface to seek or scan
  154566. ** within the union of all segments of a b-tree. Hence the name.
  154567. **
  154568. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  154569. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  154570. ** there exists prefix b-tree of the right length) then it may be traversed
  154571. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  154572. ** doclist and then traversed.
  154573. */
  154574. static void fts3EvalAllocateReaders(
  154575. Fts3Cursor *pCsr, /* FTS cursor handle */
  154576. Fts3Expr *pExpr, /* Allocate readers for this expression */
  154577. int *pnToken, /* OUT: Total number of tokens in phrase. */
  154578. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  154579. int *pRc /* IN/OUT: Error code */
  154580. ){
  154581. if( pExpr && SQLITE_OK==*pRc ){
  154582. if( pExpr->eType==FTSQUERY_PHRASE ){
  154583. int i;
  154584. int nToken = pExpr->pPhrase->nToken;
  154585. *pnToken += nToken;
  154586. for(i=0; i<nToken; i++){
  154587. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  154588. int rc = fts3TermSegReaderCursor(pCsr,
  154589. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  154590. );
  154591. if( rc!=SQLITE_OK ){
  154592. *pRc = rc;
  154593. return;
  154594. }
  154595. }
  154596. assert( pExpr->pPhrase->iDoclistToken==0 );
  154597. pExpr->pPhrase->iDoclistToken = -1;
  154598. }else{
  154599. *pnOr += (pExpr->eType==FTSQUERY_OR);
  154600. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  154601. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  154602. }
  154603. }
  154604. }
  154605. /*
  154606. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  154607. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  154608. **
  154609. ** This function assumes that pList points to a buffer allocated using
  154610. ** sqlite3_malloc(). This function takes responsibility for eventually
  154611. ** freeing the buffer.
  154612. **
  154613. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  154614. */
  154615. static int fts3EvalPhraseMergeToken(
  154616. Fts3Table *pTab, /* FTS Table pointer */
  154617. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  154618. int iToken, /* Token pList/nList corresponds to */
  154619. char *pList, /* Pointer to doclist */
  154620. int nList /* Number of bytes in pList */
  154621. ){
  154622. int rc = SQLITE_OK;
  154623. assert( iToken!=p->iDoclistToken );
  154624. if( pList==0 ){
  154625. sqlite3_free(p->doclist.aAll);
  154626. p->doclist.aAll = 0;
  154627. p->doclist.nAll = 0;
  154628. }
  154629. else if( p->iDoclistToken<0 ){
  154630. p->doclist.aAll = pList;
  154631. p->doclist.nAll = nList;
  154632. }
  154633. else if( p->doclist.aAll==0 ){
  154634. sqlite3_free(pList);
  154635. }
  154636. else {
  154637. char *pLeft;
  154638. char *pRight;
  154639. int nLeft;
  154640. int nRight;
  154641. int nDiff;
  154642. if( p->iDoclistToken<iToken ){
  154643. pLeft = p->doclist.aAll;
  154644. nLeft = p->doclist.nAll;
  154645. pRight = pList;
  154646. nRight = nList;
  154647. nDiff = iToken - p->iDoclistToken;
  154648. }else{
  154649. pRight = p->doclist.aAll;
  154650. nRight = p->doclist.nAll;
  154651. pLeft = pList;
  154652. nLeft = nList;
  154653. nDiff = p->iDoclistToken - iToken;
  154654. }
  154655. rc = fts3DoclistPhraseMerge(
  154656. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  154657. );
  154658. sqlite3_free(pLeft);
  154659. p->doclist.aAll = pRight;
  154660. p->doclist.nAll = nRight;
  154661. }
  154662. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  154663. return rc;
  154664. }
  154665. /*
  154666. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  154667. ** does not take deferred tokens into account.
  154668. **
  154669. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  154670. */
  154671. static int fts3EvalPhraseLoad(
  154672. Fts3Cursor *pCsr, /* FTS Cursor handle */
  154673. Fts3Phrase *p /* Phrase object */
  154674. ){
  154675. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  154676. int iToken;
  154677. int rc = SQLITE_OK;
  154678. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  154679. Fts3PhraseToken *pToken = &p->aToken[iToken];
  154680. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  154681. if( pToken->pSegcsr ){
  154682. int nThis = 0;
  154683. char *pThis = 0;
  154684. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  154685. if( rc==SQLITE_OK ){
  154686. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  154687. }
  154688. }
  154689. assert( pToken->pSegcsr==0 );
  154690. }
  154691. return rc;
  154692. }
  154693. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  154694. /*
  154695. ** This function is called on each phrase after the position lists for
  154696. ** any deferred tokens have been loaded into memory. It updates the phrases
  154697. ** current position list to include only those positions that are really
  154698. ** instances of the phrase (after considering deferred tokens). If this
  154699. ** means that the phrase does not appear in the current row, doclist.pList
  154700. ** and doclist.nList are both zeroed.
  154701. **
  154702. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  154703. */
  154704. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  154705. int iToken; /* Used to iterate through phrase tokens */
  154706. char *aPoslist = 0; /* Position list for deferred tokens */
  154707. int nPoslist = 0; /* Number of bytes in aPoslist */
  154708. int iPrev = -1; /* Token number of previous deferred token */
  154709. assert( pPhrase->doclist.bFreeList==0 );
  154710. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  154711. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  154712. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  154713. if( pDeferred ){
  154714. char *pList;
  154715. int nList;
  154716. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  154717. if( rc!=SQLITE_OK ) return rc;
  154718. if( pList==0 ){
  154719. sqlite3_free(aPoslist);
  154720. pPhrase->doclist.pList = 0;
  154721. pPhrase->doclist.nList = 0;
  154722. return SQLITE_OK;
  154723. }else if( aPoslist==0 ){
  154724. aPoslist = pList;
  154725. nPoslist = nList;
  154726. }else{
  154727. char *aOut = pList;
  154728. char *p1 = aPoslist;
  154729. char *p2 = aOut;
  154730. assert( iPrev>=0 );
  154731. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  154732. sqlite3_free(aPoslist);
  154733. aPoslist = pList;
  154734. nPoslist = (int)(aOut - aPoslist);
  154735. if( nPoslist==0 ){
  154736. sqlite3_free(aPoslist);
  154737. pPhrase->doclist.pList = 0;
  154738. pPhrase->doclist.nList = 0;
  154739. return SQLITE_OK;
  154740. }
  154741. }
  154742. iPrev = iToken;
  154743. }
  154744. }
  154745. if( iPrev>=0 ){
  154746. int nMaxUndeferred = pPhrase->iDoclistToken;
  154747. if( nMaxUndeferred<0 ){
  154748. pPhrase->doclist.pList = aPoslist;
  154749. pPhrase->doclist.nList = nPoslist;
  154750. pPhrase->doclist.iDocid = pCsr->iPrevId;
  154751. pPhrase->doclist.bFreeList = 1;
  154752. }else{
  154753. int nDistance;
  154754. char *p1;
  154755. char *p2;
  154756. char *aOut;
  154757. if( nMaxUndeferred>iPrev ){
  154758. p1 = aPoslist;
  154759. p2 = pPhrase->doclist.pList;
  154760. nDistance = nMaxUndeferred - iPrev;
  154761. }else{
  154762. p1 = pPhrase->doclist.pList;
  154763. p2 = aPoslist;
  154764. nDistance = iPrev - nMaxUndeferred;
  154765. }
  154766. aOut = (char *)sqlite3_malloc(nPoslist+8);
  154767. if( !aOut ){
  154768. sqlite3_free(aPoslist);
  154769. return SQLITE_NOMEM;
  154770. }
  154771. pPhrase->doclist.pList = aOut;
  154772. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  154773. pPhrase->doclist.bFreeList = 1;
  154774. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  154775. }else{
  154776. sqlite3_free(aOut);
  154777. pPhrase->doclist.pList = 0;
  154778. pPhrase->doclist.nList = 0;
  154779. }
  154780. sqlite3_free(aPoslist);
  154781. }
  154782. }
  154783. return SQLITE_OK;
  154784. }
  154785. #endif /* SQLITE_DISABLE_FTS4_DEFERRED */
  154786. /*
  154787. ** Maximum number of tokens a phrase may have to be considered for the
  154788. ** incremental doclists strategy.
  154789. */
  154790. #define MAX_INCR_PHRASE_TOKENS 4
  154791. /*
  154792. ** This function is called for each Fts3Phrase in a full-text query
  154793. ** expression to initialize the mechanism for returning rows. Once this
  154794. ** function has been called successfully on an Fts3Phrase, it may be
  154795. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  154796. **
  154797. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  154798. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  154799. ** memory within this call.
  154800. **
  154801. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  154802. */
  154803. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  154804. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  154805. int rc = SQLITE_OK; /* Error code */
  154806. int i;
  154807. /* Determine if doclists may be loaded from disk incrementally. This is
  154808. ** possible if the bOptOk argument is true, the FTS doclists will be
  154809. ** scanned in forward order, and the phrase consists of
  154810. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  154811. ** tokens or prefix tokens that cannot use a prefix-index. */
  154812. int bHaveIncr = 0;
  154813. int bIncrOk = (bOptOk
  154814. && pCsr->bDesc==pTab->bDescIdx
  154815. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  154816. #ifdef SQLITE_TEST
  154817. && pTab->bNoIncrDoclist==0
  154818. #endif
  154819. );
  154820. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  154821. Fts3PhraseToken *pToken = &p->aToken[i];
  154822. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  154823. bIncrOk = 0;
  154824. }
  154825. if( pToken->pSegcsr ) bHaveIncr = 1;
  154826. }
  154827. if( bIncrOk && bHaveIncr ){
  154828. /* Use the incremental approach. */
  154829. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  154830. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  154831. Fts3PhraseToken *pToken = &p->aToken[i];
  154832. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  154833. if( pSegcsr ){
  154834. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  154835. }
  154836. }
  154837. p->bIncr = 1;
  154838. }else{
  154839. /* Load the full doclist for the phrase into memory. */
  154840. rc = fts3EvalPhraseLoad(pCsr, p);
  154841. p->bIncr = 0;
  154842. }
  154843. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  154844. return rc;
  154845. }
  154846. /*
  154847. ** This function is used to iterate backwards (from the end to start)
  154848. ** through doclists. It is used by this module to iterate through phrase
  154849. ** doclists in reverse and by the fts3_write.c module to iterate through
  154850. ** pending-terms lists when writing to databases with "order=desc".
  154851. **
  154852. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  154853. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  154854. ** function iterates from the end of the doclist to the beginning.
  154855. */
  154856. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  154857. int bDescIdx, /* True if the doclist is desc */
  154858. char *aDoclist, /* Pointer to entire doclist */
  154859. int nDoclist, /* Length of aDoclist in bytes */
  154860. char **ppIter, /* IN/OUT: Iterator pointer */
  154861. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  154862. int *pnList, /* OUT: List length pointer */
  154863. u8 *pbEof /* OUT: End-of-file flag */
  154864. ){
  154865. char *p = *ppIter;
  154866. assert( nDoclist>0 );
  154867. assert( *pbEof==0 );
  154868. assert( p || *piDocid==0 );
  154869. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  154870. if( p==0 ){
  154871. sqlite3_int64 iDocid = 0;
  154872. char *pNext = 0;
  154873. char *pDocid = aDoclist;
  154874. char *pEnd = &aDoclist[nDoclist];
  154875. int iMul = 1;
  154876. while( pDocid<pEnd ){
  154877. sqlite3_int64 iDelta;
  154878. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  154879. iDocid += (iMul * iDelta);
  154880. pNext = pDocid;
  154881. fts3PoslistCopy(0, &pDocid);
  154882. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  154883. iMul = (bDescIdx ? -1 : 1);
  154884. }
  154885. *pnList = (int)(pEnd - pNext);
  154886. *ppIter = pNext;
  154887. *piDocid = iDocid;
  154888. }else{
  154889. int iMul = (bDescIdx ? -1 : 1);
  154890. sqlite3_int64 iDelta;
  154891. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  154892. *piDocid -= (iMul * iDelta);
  154893. if( p==aDoclist ){
  154894. *pbEof = 1;
  154895. }else{
  154896. char *pSave = p;
  154897. fts3ReversePoslist(aDoclist, &p);
  154898. *pnList = (int)(pSave - p);
  154899. }
  154900. *ppIter = p;
  154901. }
  154902. }
  154903. /*
  154904. ** Iterate forwards through a doclist.
  154905. */
  154906. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  154907. int bDescIdx, /* True if the doclist is desc */
  154908. char *aDoclist, /* Pointer to entire doclist */
  154909. int nDoclist, /* Length of aDoclist in bytes */
  154910. char **ppIter, /* IN/OUT: Iterator pointer */
  154911. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  154912. u8 *pbEof /* OUT: End-of-file flag */
  154913. ){
  154914. char *p = *ppIter;
  154915. assert( nDoclist>0 );
  154916. assert( *pbEof==0 );
  154917. assert( p || *piDocid==0 );
  154918. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  154919. if( p==0 ){
  154920. p = aDoclist;
  154921. p += sqlite3Fts3GetVarint(p, piDocid);
  154922. }else{
  154923. fts3PoslistCopy(0, &p);
  154924. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  154925. if( p>=&aDoclist[nDoclist] ){
  154926. *pbEof = 1;
  154927. }else{
  154928. sqlite3_int64 iVar;
  154929. p += sqlite3Fts3GetVarint(p, &iVar);
  154930. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  154931. }
  154932. }
  154933. *ppIter = p;
  154934. }
  154935. /*
  154936. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  154937. ** to true if EOF is reached.
  154938. */
  154939. static void fts3EvalDlPhraseNext(
  154940. Fts3Table *pTab,
  154941. Fts3Doclist *pDL,
  154942. u8 *pbEof
  154943. ){
  154944. char *pIter; /* Used to iterate through aAll */
  154945. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  154946. if( pDL->pNextDocid ){
  154947. pIter = pDL->pNextDocid;
  154948. }else{
  154949. pIter = pDL->aAll;
  154950. }
  154951. if( pIter>=pEnd ){
  154952. /* We have already reached the end of this doclist. EOF. */
  154953. *pbEof = 1;
  154954. }else{
  154955. sqlite3_int64 iDelta;
  154956. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  154957. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  154958. pDL->iDocid += iDelta;
  154959. }else{
  154960. pDL->iDocid -= iDelta;
  154961. }
  154962. pDL->pList = pIter;
  154963. fts3PoslistCopy(0, &pIter);
  154964. pDL->nList = (int)(pIter - pDL->pList);
  154965. /* pIter now points just past the 0x00 that terminates the position-
  154966. ** list for document pDL->iDocid. However, if this position-list was
  154967. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  154968. ** point to the start of the next docid value. The following line deals
  154969. ** with this case by advancing pIter past the zero-padding added by
  154970. ** fts3EvalNearTrim(). */
  154971. while( pIter<pEnd && *pIter==0 ) pIter++;
  154972. pDL->pNextDocid = pIter;
  154973. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  154974. *pbEof = 0;
  154975. }
  154976. }
  154977. /*
  154978. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  154979. */
  154980. typedef struct TokenDoclist TokenDoclist;
  154981. struct TokenDoclist {
  154982. int bIgnore;
  154983. sqlite3_int64 iDocid;
  154984. char *pList;
  154985. int nList;
  154986. };
  154987. /*
  154988. ** Token pToken is an incrementally loaded token that is part of a
  154989. ** multi-token phrase. Advance it to the next matching document in the
  154990. ** database and populate output variable *p with the details of the new
  154991. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  154992. **
  154993. ** If an error occurs, return an SQLite error code. Otherwise, return
  154994. ** SQLITE_OK.
  154995. */
  154996. static int incrPhraseTokenNext(
  154997. Fts3Table *pTab, /* Virtual table handle */
  154998. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  154999. int iToken, /* Specific token to advance */
  155000. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  155001. u8 *pbEof /* OUT: True if iterator is at EOF */
  155002. ){
  155003. int rc = SQLITE_OK;
  155004. if( pPhrase->iDoclistToken==iToken ){
  155005. assert( p->bIgnore==0 );
  155006. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  155007. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  155008. p->pList = pPhrase->doclist.pList;
  155009. p->nList = pPhrase->doclist.nList;
  155010. p->iDocid = pPhrase->doclist.iDocid;
  155011. }else{
  155012. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  155013. assert( pToken->pDeferred==0 );
  155014. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  155015. if( pToken->pSegcsr ){
  155016. assert( p->bIgnore==0 );
  155017. rc = sqlite3Fts3MsrIncrNext(
  155018. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  155019. );
  155020. if( p->pList==0 ) *pbEof = 1;
  155021. }else{
  155022. p->bIgnore = 1;
  155023. }
  155024. }
  155025. return rc;
  155026. }
  155027. /*
  155028. ** The phrase iterator passed as the second argument:
  155029. **
  155030. ** * features at least one token that uses an incremental doclist, and
  155031. **
  155032. ** * does not contain any deferred tokens.
  155033. **
  155034. ** Advance it to the next matching documnent in the database and populate
  155035. ** the Fts3Doclist.pList and nList fields.
  155036. **
  155037. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  155038. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  155039. ** successfully advanced, *pbEof is set to 0.
  155040. **
  155041. ** If an error occurs, return an SQLite error code. Otherwise, return
  155042. ** SQLITE_OK.
  155043. */
  155044. static int fts3EvalIncrPhraseNext(
  155045. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155046. Fts3Phrase *p, /* Phrase object to advance to next docid */
  155047. u8 *pbEof /* OUT: Set to 1 if EOF */
  155048. ){
  155049. int rc = SQLITE_OK;
  155050. Fts3Doclist *pDL = &p->doclist;
  155051. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  155052. u8 bEof = 0;
  155053. /* This is only called if it is guaranteed that the phrase has at least
  155054. ** one incremental token. In which case the bIncr flag is set. */
  155055. assert( p->bIncr==1 );
  155056. if( p->nToken==1 ){
  155057. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  155058. &pDL->iDocid, &pDL->pList, &pDL->nList
  155059. );
  155060. if( pDL->pList==0 ) bEof = 1;
  155061. }else{
  155062. int bDescDoclist = pCsr->bDesc;
  155063. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  155064. memset(a, 0, sizeof(a));
  155065. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  155066. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  155067. while( bEof==0 ){
  155068. int bMaxSet = 0;
  155069. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  155070. int i; /* Used to iterate through tokens */
  155071. /* Advance the iterator for each token in the phrase once. */
  155072. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  155073. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  155074. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  155075. iMax = a[i].iDocid;
  155076. bMaxSet = 1;
  155077. }
  155078. }
  155079. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  155080. assert( rc!=SQLITE_OK || bMaxSet );
  155081. /* Keep advancing iterators until they all point to the same document */
  155082. for(i=0; i<p->nToken; i++){
  155083. while( rc==SQLITE_OK && bEof==0
  155084. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  155085. ){
  155086. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  155087. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  155088. iMax = a[i].iDocid;
  155089. i = 0;
  155090. }
  155091. }
  155092. }
  155093. /* Check if the current entries really are a phrase match */
  155094. if( bEof==0 ){
  155095. int nList = 0;
  155096. int nByte = a[p->nToken-1].nList;
  155097. char *aDoclist = sqlite3_malloc(nByte+FTS3_BUFFER_PADDING);
  155098. if( !aDoclist ) return SQLITE_NOMEM;
  155099. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  155100. memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING);
  155101. for(i=0; i<(p->nToken-1); i++){
  155102. if( a[i].bIgnore==0 ){
  155103. char *pL = a[i].pList;
  155104. char *pR = aDoclist;
  155105. char *pOut = aDoclist;
  155106. int nDist = p->nToken-1-i;
  155107. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  155108. if( res==0 ) break;
  155109. nList = (int)(pOut - aDoclist);
  155110. }
  155111. }
  155112. if( i==(p->nToken-1) ){
  155113. pDL->iDocid = iMax;
  155114. pDL->pList = aDoclist;
  155115. pDL->nList = nList;
  155116. pDL->bFreeList = 1;
  155117. break;
  155118. }
  155119. sqlite3_free(aDoclist);
  155120. }
  155121. }
  155122. }
  155123. *pbEof = bEof;
  155124. return rc;
  155125. }
  155126. /*
  155127. ** Attempt to move the phrase iterator to point to the next matching docid.
  155128. ** If an error occurs, return an SQLite error code. Otherwise, return
  155129. ** SQLITE_OK.
  155130. **
  155131. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  155132. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  155133. ** successfully advanced, *pbEof is set to 0.
  155134. */
  155135. static int fts3EvalPhraseNext(
  155136. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155137. Fts3Phrase *p, /* Phrase object to advance to next docid */
  155138. u8 *pbEof /* OUT: Set to 1 if EOF */
  155139. ){
  155140. int rc = SQLITE_OK;
  155141. Fts3Doclist *pDL = &p->doclist;
  155142. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  155143. if( p->bIncr ){
  155144. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  155145. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  155146. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  155147. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  155148. );
  155149. pDL->pList = pDL->pNextDocid;
  155150. }else{
  155151. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  155152. }
  155153. return rc;
  155154. }
  155155. /*
  155156. **
  155157. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  155158. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  155159. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  155160. ** expressions for which all descendent tokens are deferred.
  155161. **
  155162. ** If parameter bOptOk is zero, then it is guaranteed that the
  155163. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  155164. ** each phrase in the expression (subject to deferred token processing).
  155165. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  155166. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  155167. **
  155168. ** If an error occurs within this function, *pRc is set to an SQLite error
  155169. ** code before returning.
  155170. */
  155171. static void fts3EvalStartReaders(
  155172. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155173. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  155174. int *pRc /* IN/OUT: Error code */
  155175. ){
  155176. if( pExpr && SQLITE_OK==*pRc ){
  155177. if( pExpr->eType==FTSQUERY_PHRASE ){
  155178. int nToken = pExpr->pPhrase->nToken;
  155179. if( nToken ){
  155180. int i;
  155181. for(i=0; i<nToken; i++){
  155182. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  155183. }
  155184. pExpr->bDeferred = (i==nToken);
  155185. }
  155186. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  155187. }else{
  155188. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  155189. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  155190. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  155191. }
  155192. }
  155193. }
  155194. /*
  155195. ** An array of the following structures is assembled as part of the process
  155196. ** of selecting tokens to defer before the query starts executing (as part
  155197. ** of the xFilter() method). There is one element in the array for each
  155198. ** token in the FTS expression.
  155199. **
  155200. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  155201. ** to phrases that are connected only by AND and NEAR operators (not OR or
  155202. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  155203. ** separately. The root of a tokens AND/NEAR cluster is stored in
  155204. ** Fts3TokenAndCost.pRoot.
  155205. */
  155206. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  155207. struct Fts3TokenAndCost {
  155208. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  155209. int iToken; /* Position of token in phrase */
  155210. Fts3PhraseToken *pToken; /* The token itself */
  155211. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  155212. int nOvfl; /* Number of overflow pages to load doclist */
  155213. int iCol; /* The column the token must match */
  155214. };
  155215. /*
  155216. ** This function is used to populate an allocated Fts3TokenAndCost array.
  155217. **
  155218. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  155219. ** Otherwise, if an error occurs during execution, *pRc is set to an
  155220. ** SQLite error code.
  155221. */
  155222. static void fts3EvalTokenCosts(
  155223. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155224. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  155225. Fts3Expr *pExpr, /* Expression to consider */
  155226. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  155227. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  155228. int *pRc /* IN/OUT: Error code */
  155229. ){
  155230. if( *pRc==SQLITE_OK ){
  155231. if( pExpr->eType==FTSQUERY_PHRASE ){
  155232. Fts3Phrase *pPhrase = pExpr->pPhrase;
  155233. int i;
  155234. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  155235. Fts3TokenAndCost *pTC = (*ppTC)++;
  155236. pTC->pPhrase = pPhrase;
  155237. pTC->iToken = i;
  155238. pTC->pRoot = pRoot;
  155239. pTC->pToken = &pPhrase->aToken[i];
  155240. pTC->iCol = pPhrase->iColumn;
  155241. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  155242. }
  155243. }else if( pExpr->eType!=FTSQUERY_NOT ){
  155244. assert( pExpr->eType==FTSQUERY_OR
  155245. || pExpr->eType==FTSQUERY_AND
  155246. || pExpr->eType==FTSQUERY_NEAR
  155247. );
  155248. assert( pExpr->pLeft && pExpr->pRight );
  155249. if( pExpr->eType==FTSQUERY_OR ){
  155250. pRoot = pExpr->pLeft;
  155251. **ppOr = pRoot;
  155252. (*ppOr)++;
  155253. }
  155254. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  155255. if( pExpr->eType==FTSQUERY_OR ){
  155256. pRoot = pExpr->pRight;
  155257. **ppOr = pRoot;
  155258. (*ppOr)++;
  155259. }
  155260. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  155261. }
  155262. }
  155263. }
  155264. /*
  155265. ** Determine the average document (row) size in pages. If successful,
  155266. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  155267. ** an SQLite error code.
  155268. **
  155269. ** The average document size in pages is calculated by first calculating
  155270. ** determining the average size in bytes, B. If B is less than the amount
  155271. ** of data that will fit on a single leaf page of an intkey table in
  155272. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  155273. ** the number of overflow pages consumed by a record B bytes in size.
  155274. */
  155275. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  155276. int rc = SQLITE_OK;
  155277. if( pCsr->nRowAvg==0 ){
  155278. /* The average document size, which is required to calculate the cost
  155279. ** of each doclist, has not yet been determined. Read the required
  155280. ** data from the %_stat table to calculate it.
  155281. **
  155282. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  155283. ** varints, where nCol is the number of columns in the FTS3 table.
  155284. ** The first varint is the number of documents currently stored in
  155285. ** the table. The following nCol varints contain the total amount of
  155286. ** data stored in all rows of each column of the table, from left
  155287. ** to right.
  155288. */
  155289. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  155290. sqlite3_stmt *pStmt;
  155291. sqlite3_int64 nDoc = 0;
  155292. sqlite3_int64 nByte = 0;
  155293. const char *pEnd;
  155294. const char *a;
  155295. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  155296. if( rc!=SQLITE_OK ) return rc;
  155297. a = sqlite3_column_blob(pStmt, 0);
  155298. assert( a );
  155299. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  155300. a += sqlite3Fts3GetVarint(a, &nDoc);
  155301. while( a<pEnd ){
  155302. a += sqlite3Fts3GetVarint(a, &nByte);
  155303. }
  155304. if( nDoc==0 || nByte==0 ){
  155305. sqlite3_reset(pStmt);
  155306. return FTS_CORRUPT_VTAB;
  155307. }
  155308. pCsr->nDoc = nDoc;
  155309. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  155310. assert( pCsr->nRowAvg>0 );
  155311. rc = sqlite3_reset(pStmt);
  155312. }
  155313. *pnPage = pCsr->nRowAvg;
  155314. return rc;
  155315. }
  155316. /*
  155317. ** This function is called to select the tokens (if any) that will be
  155318. ** deferred. The array aTC[] has already been populated when this is
  155319. ** called.
  155320. **
  155321. ** This function is called once for each AND/NEAR cluster in the
  155322. ** expression. Each invocation determines which tokens to defer within
  155323. ** the cluster with root node pRoot. See comments above the definition
  155324. ** of struct Fts3TokenAndCost for more details.
  155325. **
  155326. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  155327. ** called on each token to defer. Otherwise, an SQLite error code is
  155328. ** returned.
  155329. */
  155330. static int fts3EvalSelectDeferred(
  155331. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155332. Fts3Expr *pRoot, /* Consider tokens with this root node */
  155333. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  155334. int nTC /* Number of entries in aTC[] */
  155335. ){
  155336. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  155337. int nDocSize = 0; /* Number of pages per doc loaded */
  155338. int rc = SQLITE_OK; /* Return code */
  155339. int ii; /* Iterator variable for various purposes */
  155340. int nOvfl = 0; /* Total overflow pages used by doclists */
  155341. int nToken = 0; /* Total number of tokens in cluster */
  155342. int nMinEst = 0; /* The minimum count for any phrase so far. */
  155343. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  155344. /* Tokens are never deferred for FTS tables created using the content=xxx
  155345. ** option. The reason being that it is not guaranteed that the content
  155346. ** table actually contains the same data as the index. To prevent this from
  155347. ** causing any problems, the deferred token optimization is completely
  155348. ** disabled for content=xxx tables. */
  155349. if( pTab->zContentTbl ){
  155350. return SQLITE_OK;
  155351. }
  155352. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  155353. ** associated with the tokens spill onto overflow pages, or if there is
  155354. ** only 1 token, exit early. No tokens to defer in this case. */
  155355. for(ii=0; ii<nTC; ii++){
  155356. if( aTC[ii].pRoot==pRoot ){
  155357. nOvfl += aTC[ii].nOvfl;
  155358. nToken++;
  155359. }
  155360. }
  155361. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  155362. /* Obtain the average docsize (in pages). */
  155363. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  155364. assert( rc!=SQLITE_OK || nDocSize>0 );
  155365. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  155366. ** of the number of overflow pages that will be loaded by the pager layer
  155367. ** to retrieve the entire doclist for the token from the full-text index.
  155368. ** Load the doclists for tokens that are either:
  155369. **
  155370. ** a. The cheapest token in the entire query (i.e. the one visited by the
  155371. ** first iteration of this loop), or
  155372. **
  155373. ** b. Part of a multi-token phrase.
  155374. **
  155375. ** After each token doclist is loaded, merge it with the others from the
  155376. ** same phrase and count the number of documents that the merged doclist
  155377. ** contains. Set variable "nMinEst" to the smallest number of documents in
  155378. ** any phrase doclist for which 1 or more token doclists have been loaded.
  155379. ** Let nOther be the number of other phrases for which it is certain that
  155380. ** one or more tokens will not be deferred.
  155381. **
  155382. ** Then, for each token, defer it if loading the doclist would result in
  155383. ** loading N or more overflow pages into memory, where N is computed as:
  155384. **
  155385. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  155386. */
  155387. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  155388. int iTC; /* Used to iterate through aTC[] array. */
  155389. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  155390. /* Set pTC to point to the cheapest remaining token. */
  155391. for(iTC=0; iTC<nTC; iTC++){
  155392. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  155393. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  155394. ){
  155395. pTC = &aTC[iTC];
  155396. }
  155397. }
  155398. assert( pTC );
  155399. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  155400. /* The number of overflow pages to load for this (and therefore all
  155401. ** subsequent) tokens is greater than the estimated number of pages
  155402. ** that will be loaded if all subsequent tokens are deferred.
  155403. */
  155404. Fts3PhraseToken *pToken = pTC->pToken;
  155405. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  155406. fts3SegReaderCursorFree(pToken->pSegcsr);
  155407. pToken->pSegcsr = 0;
  155408. }else{
  155409. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  155410. ** for-loop. Except, limit the value to 2^24 to prevent it from
  155411. ** overflowing the 32-bit integer it is stored in. */
  155412. if( ii<12 ) nLoad4 = nLoad4*4;
  155413. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  155414. /* Either this is the cheapest token in the entire query, or it is
  155415. ** part of a multi-token phrase. Either way, the entire doclist will
  155416. ** (eventually) be loaded into memory. It may as well be now. */
  155417. Fts3PhraseToken *pToken = pTC->pToken;
  155418. int nList = 0;
  155419. char *pList = 0;
  155420. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  155421. assert( rc==SQLITE_OK || pList==0 );
  155422. if( rc==SQLITE_OK ){
  155423. rc = fts3EvalPhraseMergeToken(
  155424. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  155425. );
  155426. }
  155427. if( rc==SQLITE_OK ){
  155428. int nCount;
  155429. nCount = fts3DoclistCountDocids(
  155430. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  155431. );
  155432. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  155433. }
  155434. }
  155435. }
  155436. pTC->pToken = 0;
  155437. }
  155438. return rc;
  155439. }
  155440. /*
  155441. ** This function is called from within the xFilter method. It initializes
  155442. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  155443. ** the results of a query, the caller does:
  155444. **
  155445. ** fts3EvalStart(pCsr);
  155446. ** while( 1 ){
  155447. ** fts3EvalNext(pCsr);
  155448. ** if( pCsr->bEof ) break;
  155449. ** ... return row pCsr->iPrevId to the caller ...
  155450. ** }
  155451. */
  155452. static int fts3EvalStart(Fts3Cursor *pCsr){
  155453. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  155454. int rc = SQLITE_OK;
  155455. int nToken = 0;
  155456. int nOr = 0;
  155457. /* Allocate a MultiSegReader for each token in the expression. */
  155458. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  155459. /* Determine which, if any, tokens in the expression should be deferred. */
  155460. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  155461. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  155462. Fts3TokenAndCost *aTC;
  155463. Fts3Expr **apOr;
  155464. aTC = (Fts3TokenAndCost *)sqlite3_malloc64(
  155465. sizeof(Fts3TokenAndCost) * nToken
  155466. + sizeof(Fts3Expr *) * nOr * 2
  155467. );
  155468. apOr = (Fts3Expr **)&aTC[nToken];
  155469. if( !aTC ){
  155470. rc = SQLITE_NOMEM;
  155471. }else{
  155472. int ii;
  155473. Fts3TokenAndCost *pTC = aTC;
  155474. Fts3Expr **ppOr = apOr;
  155475. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  155476. nToken = (int)(pTC-aTC);
  155477. nOr = (int)(ppOr-apOr);
  155478. if( rc==SQLITE_OK ){
  155479. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  155480. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  155481. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  155482. }
  155483. }
  155484. sqlite3_free(aTC);
  155485. }
  155486. }
  155487. #endif
  155488. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  155489. return rc;
  155490. }
  155491. /*
  155492. ** Invalidate the current position list for phrase pPhrase.
  155493. */
  155494. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  155495. if( pPhrase->doclist.bFreeList ){
  155496. sqlite3_free(pPhrase->doclist.pList);
  155497. }
  155498. pPhrase->doclist.pList = 0;
  155499. pPhrase->doclist.nList = 0;
  155500. pPhrase->doclist.bFreeList = 0;
  155501. }
  155502. /*
  155503. ** This function is called to edit the position list associated with
  155504. ** the phrase object passed as the fifth argument according to a NEAR
  155505. ** condition. For example:
  155506. **
  155507. ** abc NEAR/5 "def ghi"
  155508. **
  155509. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  155510. ** the example above). When this function is called, *paPoslist points to
  155511. ** the position list, and *pnToken is the number of phrase tokens in, the
  155512. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  155513. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  155514. ** the position list associated with phrase "abc".
  155515. **
  155516. ** All positions in the pPhrase position list that are not sufficiently
  155517. ** close to a position in the *paPoslist position list are removed. If this
  155518. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  155519. **
  155520. ** Before returning, *paPoslist is set to point to the position lsit
  155521. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  155522. ** pPhrase.
  155523. */
  155524. static int fts3EvalNearTrim(
  155525. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  155526. char *aTmp, /* Temporary space to use */
  155527. char **paPoslist, /* IN/OUT: Position list */
  155528. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  155529. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  155530. ){
  155531. int nParam1 = nNear + pPhrase->nToken;
  155532. int nParam2 = nNear + *pnToken;
  155533. int nNew;
  155534. char *p2;
  155535. char *pOut;
  155536. int res;
  155537. assert( pPhrase->doclist.pList );
  155538. p2 = pOut = pPhrase->doclist.pList;
  155539. res = fts3PoslistNearMerge(
  155540. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  155541. );
  155542. if( res ){
  155543. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  155544. assert( pPhrase->doclist.pList[nNew]=='\0' );
  155545. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  155546. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  155547. pPhrase->doclist.nList = nNew;
  155548. *paPoslist = pPhrase->doclist.pList;
  155549. *pnToken = pPhrase->nToken;
  155550. }
  155551. return res;
  155552. }
  155553. /*
  155554. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  155555. ** Otherwise, it advances the expression passed as the second argument to
  155556. ** point to the next matching row in the database. Expressions iterate through
  155557. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  155558. ** or descending if it is non-zero.
  155559. **
  155560. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  155561. ** successful, the following variables in pExpr are set:
  155562. **
  155563. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  155564. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  155565. **
  155566. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  155567. ** at EOF, then the following variables are populated with the position list
  155568. ** for the phrase for the visited row:
  155569. **
  155570. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  155571. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  155572. **
  155573. ** It says above that this function advances the expression to the next
  155574. ** matching row. This is usually true, but there are the following exceptions:
  155575. **
  155576. ** 1. Deferred tokens are not taken into account. If a phrase consists
  155577. ** entirely of deferred tokens, it is assumed to match every row in
  155578. ** the db. In this case the position-list is not populated at all.
  155579. **
  155580. ** Or, if a phrase contains one or more deferred tokens and one or
  155581. ** more non-deferred tokens, then the expression is advanced to the
  155582. ** next possible match, considering only non-deferred tokens. In other
  155583. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  155584. ** is advanced to the next row that contains an instance of "A * C",
  155585. ** where "*" may match any single token. The position list in this case
  155586. ** is populated as for "A * C" before returning.
  155587. **
  155588. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  155589. ** advanced to point to the next row that matches "x AND y".
  155590. **
  155591. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  155592. ** really a match, taking into account deferred tokens and NEAR operators.
  155593. */
  155594. static void fts3EvalNextRow(
  155595. Fts3Cursor *pCsr, /* FTS Cursor handle */
  155596. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  155597. int *pRc /* IN/OUT: Error code */
  155598. ){
  155599. if( *pRc==SQLITE_OK ){
  155600. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  155601. assert( pExpr->bEof==0 );
  155602. pExpr->bStart = 1;
  155603. switch( pExpr->eType ){
  155604. case FTSQUERY_NEAR:
  155605. case FTSQUERY_AND: {
  155606. Fts3Expr *pLeft = pExpr->pLeft;
  155607. Fts3Expr *pRight = pExpr->pRight;
  155608. assert( !pLeft->bDeferred || !pRight->bDeferred );
  155609. if( pLeft->bDeferred ){
  155610. /* LHS is entirely deferred. So we assume it matches every row.
  155611. ** Advance the RHS iterator to find the next row visited. */
  155612. fts3EvalNextRow(pCsr, pRight, pRc);
  155613. pExpr->iDocid = pRight->iDocid;
  155614. pExpr->bEof = pRight->bEof;
  155615. }else if( pRight->bDeferred ){
  155616. /* RHS is entirely deferred. So we assume it matches every row.
  155617. ** Advance the LHS iterator to find the next row visited. */
  155618. fts3EvalNextRow(pCsr, pLeft, pRc);
  155619. pExpr->iDocid = pLeft->iDocid;
  155620. pExpr->bEof = pLeft->bEof;
  155621. }else{
  155622. /* Neither the RHS or LHS are deferred. */
  155623. fts3EvalNextRow(pCsr, pLeft, pRc);
  155624. fts3EvalNextRow(pCsr, pRight, pRc);
  155625. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  155626. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  155627. if( iDiff==0 ) break;
  155628. if( iDiff<0 ){
  155629. fts3EvalNextRow(pCsr, pLeft, pRc);
  155630. }else{
  155631. fts3EvalNextRow(pCsr, pRight, pRc);
  155632. }
  155633. }
  155634. pExpr->iDocid = pLeft->iDocid;
  155635. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  155636. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  155637. assert( pRight->eType==FTSQUERY_PHRASE );
  155638. if( pRight->pPhrase->doclist.aAll ){
  155639. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  155640. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  155641. memset(pDl->pList, 0, pDl->nList);
  155642. fts3EvalNextRow(pCsr, pRight, pRc);
  155643. }
  155644. }
  155645. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  155646. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  155647. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  155648. memset(pDl->pList, 0, pDl->nList);
  155649. fts3EvalNextRow(pCsr, pLeft, pRc);
  155650. }
  155651. }
  155652. }
  155653. }
  155654. break;
  155655. }
  155656. case FTSQUERY_OR: {
  155657. Fts3Expr *pLeft = pExpr->pLeft;
  155658. Fts3Expr *pRight = pExpr->pRight;
  155659. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  155660. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  155661. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  155662. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  155663. fts3EvalNextRow(pCsr, pLeft, pRc);
  155664. }else if( pLeft->bEof || iCmp>0 ){
  155665. fts3EvalNextRow(pCsr, pRight, pRc);
  155666. }else{
  155667. fts3EvalNextRow(pCsr, pLeft, pRc);
  155668. fts3EvalNextRow(pCsr, pRight, pRc);
  155669. }
  155670. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  155671. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  155672. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  155673. pExpr->iDocid = pLeft->iDocid;
  155674. }else{
  155675. pExpr->iDocid = pRight->iDocid;
  155676. }
  155677. break;
  155678. }
  155679. case FTSQUERY_NOT: {
  155680. Fts3Expr *pLeft = pExpr->pLeft;
  155681. Fts3Expr *pRight = pExpr->pRight;
  155682. if( pRight->bStart==0 ){
  155683. fts3EvalNextRow(pCsr, pRight, pRc);
  155684. assert( *pRc!=SQLITE_OK || pRight->bStart );
  155685. }
  155686. fts3EvalNextRow(pCsr, pLeft, pRc);
  155687. if( pLeft->bEof==0 ){
  155688. while( !*pRc
  155689. && !pRight->bEof
  155690. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  155691. ){
  155692. fts3EvalNextRow(pCsr, pRight, pRc);
  155693. }
  155694. }
  155695. pExpr->iDocid = pLeft->iDocid;
  155696. pExpr->bEof = pLeft->bEof;
  155697. break;
  155698. }
  155699. default: {
  155700. Fts3Phrase *pPhrase = pExpr->pPhrase;
  155701. fts3EvalInvalidatePoslist(pPhrase);
  155702. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  155703. pExpr->iDocid = pPhrase->doclist.iDocid;
  155704. break;
  155705. }
  155706. }
  155707. }
  155708. }
  155709. /*
  155710. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  155711. ** cluster, then this function returns 1 immediately.
  155712. **
  155713. ** Otherwise, it checks if the current row really does match the NEAR
  155714. ** expression, using the data currently stored in the position lists
  155715. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  155716. **
  155717. ** If the current row is a match, the position list associated with each
  155718. ** phrase in the NEAR expression is edited in place to contain only those
  155719. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  155720. ** constraints. In this case it returns 1. If the NEAR expression does not
  155721. ** match the current row, 0 is returned. The position lists may or may not
  155722. ** be edited if 0 is returned.
  155723. */
  155724. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  155725. int res = 1;
  155726. /* The following block runs if pExpr is the root of a NEAR query.
  155727. ** For example, the query:
  155728. **
  155729. ** "w" NEAR "x" NEAR "y" NEAR "z"
  155730. **
  155731. ** which is represented in tree form as:
  155732. **
  155733. ** |
  155734. ** +--NEAR--+ <-- root of NEAR query
  155735. ** | |
  155736. ** +--NEAR--+ "z"
  155737. ** | |
  155738. ** +--NEAR--+ "y"
  155739. ** | |
  155740. ** "w" "x"
  155741. **
  155742. ** The right-hand child of a NEAR node is always a phrase. The
  155743. ** left-hand child may be either a phrase or a NEAR node. There are
  155744. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  155745. */
  155746. if( *pRc==SQLITE_OK
  155747. && pExpr->eType==FTSQUERY_NEAR
  155748. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  155749. ){
  155750. Fts3Expr *p;
  155751. sqlite3_int64 nTmp = 0; /* Bytes of temp space */
  155752. char *aTmp; /* Temp space for PoslistNearMerge() */
  155753. /* Allocate temporary working space. */
  155754. for(p=pExpr; p->pLeft; p=p->pLeft){
  155755. assert( p->pRight->pPhrase->doclist.nList>0 );
  155756. nTmp += p->pRight->pPhrase->doclist.nList;
  155757. }
  155758. nTmp += p->pPhrase->doclist.nList;
  155759. aTmp = sqlite3_malloc64(nTmp*2);
  155760. if( !aTmp ){
  155761. *pRc = SQLITE_NOMEM;
  155762. res = 0;
  155763. }else{
  155764. char *aPoslist = p->pPhrase->doclist.pList;
  155765. int nToken = p->pPhrase->nToken;
  155766. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  155767. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  155768. int nNear = p->nNear;
  155769. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  155770. }
  155771. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  155772. nToken = pExpr->pRight->pPhrase->nToken;
  155773. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  155774. int nNear;
  155775. Fts3Phrase *pPhrase;
  155776. assert( p->pParent && p->pParent->pLeft==p );
  155777. nNear = p->pParent->nNear;
  155778. pPhrase = (
  155779. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  155780. );
  155781. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  155782. }
  155783. }
  155784. sqlite3_free(aTmp);
  155785. }
  155786. return res;
  155787. }
  155788. /*
  155789. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  155790. ** Assuming no error occurs or has occurred, It returns non-zero if the
  155791. ** expression passed as the second argument matches the row that pCsr
  155792. ** currently points to, or zero if it does not.
  155793. **
  155794. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  155795. ** If an error occurs during execution of this function, *pRc is set to
  155796. ** the appropriate SQLite error code. In this case the returned value is
  155797. ** undefined.
  155798. */
  155799. static int fts3EvalTestExpr(
  155800. Fts3Cursor *pCsr, /* FTS cursor handle */
  155801. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  155802. int *pRc /* IN/OUT: Error code */
  155803. ){
  155804. int bHit = 1; /* Return value */
  155805. if( *pRc==SQLITE_OK ){
  155806. switch( pExpr->eType ){
  155807. case FTSQUERY_NEAR:
  155808. case FTSQUERY_AND:
  155809. bHit = (
  155810. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  155811. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  155812. && fts3EvalNearTest(pExpr, pRc)
  155813. );
  155814. /* If the NEAR expression does not match any rows, zero the doclist for
  155815. ** all phrases involved in the NEAR. This is because the snippet(),
  155816. ** offsets() and matchinfo() functions are not supposed to recognize
  155817. ** any instances of phrases that are part of unmatched NEAR queries.
  155818. ** For example if this expression:
  155819. **
  155820. ** ... MATCH 'a OR (b NEAR c)'
  155821. **
  155822. ** is matched against a row containing:
  155823. **
  155824. ** 'a b d e'
  155825. **
  155826. ** then any snippet() should ony highlight the "a" term, not the "b"
  155827. ** (as "b" is part of a non-matching NEAR clause).
  155828. */
  155829. if( bHit==0
  155830. && pExpr->eType==FTSQUERY_NEAR
  155831. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  155832. ){
  155833. Fts3Expr *p;
  155834. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  155835. if( p->pRight->iDocid==pCsr->iPrevId ){
  155836. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  155837. }
  155838. }
  155839. if( p->iDocid==pCsr->iPrevId ){
  155840. fts3EvalInvalidatePoslist(p->pPhrase);
  155841. }
  155842. }
  155843. break;
  155844. case FTSQUERY_OR: {
  155845. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  155846. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  155847. bHit = bHit1 || bHit2;
  155848. break;
  155849. }
  155850. case FTSQUERY_NOT:
  155851. bHit = (
  155852. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  155853. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  155854. );
  155855. break;
  155856. default: {
  155857. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  155858. if( pCsr->pDeferred
  155859. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  155860. ){
  155861. Fts3Phrase *pPhrase = pExpr->pPhrase;
  155862. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  155863. if( pExpr->bDeferred ){
  155864. fts3EvalInvalidatePoslist(pPhrase);
  155865. }
  155866. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  155867. bHit = (pPhrase->doclist.pList!=0);
  155868. pExpr->iDocid = pCsr->iPrevId;
  155869. }else
  155870. #endif
  155871. {
  155872. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  155873. }
  155874. break;
  155875. }
  155876. }
  155877. }
  155878. return bHit;
  155879. }
  155880. /*
  155881. ** This function is called as the second part of each xNext operation when
  155882. ** iterating through the results of a full-text query. At this point the
  155883. ** cursor points to a row that matches the query expression, with the
  155884. ** following caveats:
  155885. **
  155886. ** * Up until this point, "NEAR" operators in the expression have been
  155887. ** treated as "AND".
  155888. **
  155889. ** * Deferred tokens have not yet been considered.
  155890. **
  155891. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  155892. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  155893. ** operators and deferred tokens the current row is still a match for the
  155894. ** expression. It returns 1 if both of the following are true:
  155895. **
  155896. ** 1. *pRc is SQLITE_OK when this function returns, and
  155897. **
  155898. ** 2. After scanning the current FTS table row for the deferred tokens,
  155899. ** it is determined that the row does *not* match the query.
  155900. **
  155901. ** Or, if no error occurs and it seems the current row does match the FTS
  155902. ** query, return 0.
  155903. */
  155904. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  155905. int rc = *pRc;
  155906. int bMiss = 0;
  155907. if( rc==SQLITE_OK ){
  155908. /* If there are one or more deferred tokens, load the current row into
  155909. ** memory and scan it to determine the position list for each deferred
  155910. ** token. Then, see if this row is really a match, considering deferred
  155911. ** tokens and NEAR operators (neither of which were taken into account
  155912. ** earlier, by fts3EvalNextRow()).
  155913. */
  155914. if( pCsr->pDeferred ){
  155915. rc = fts3CursorSeek(0, pCsr);
  155916. if( rc==SQLITE_OK ){
  155917. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  155918. }
  155919. }
  155920. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  155921. /* Free the position-lists accumulated for each deferred token above. */
  155922. sqlite3Fts3FreeDeferredDoclists(pCsr);
  155923. *pRc = rc;
  155924. }
  155925. return (rc==SQLITE_OK && bMiss);
  155926. }
  155927. /*
  155928. ** Advance to the next document that matches the FTS expression in
  155929. ** Fts3Cursor.pExpr.
  155930. */
  155931. static int fts3EvalNext(Fts3Cursor *pCsr){
  155932. int rc = SQLITE_OK; /* Return Code */
  155933. Fts3Expr *pExpr = pCsr->pExpr;
  155934. assert( pCsr->isEof==0 );
  155935. if( pExpr==0 ){
  155936. pCsr->isEof = 1;
  155937. }else{
  155938. do {
  155939. if( pCsr->isRequireSeek==0 ){
  155940. sqlite3_reset(pCsr->pStmt);
  155941. }
  155942. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  155943. fts3EvalNextRow(pCsr, pExpr, &rc);
  155944. pCsr->isEof = pExpr->bEof;
  155945. pCsr->isRequireSeek = 1;
  155946. pCsr->isMatchinfoNeeded = 1;
  155947. pCsr->iPrevId = pExpr->iDocid;
  155948. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  155949. }
  155950. /* Check if the cursor is past the end of the docid range specified
  155951. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  155952. if( rc==SQLITE_OK && (
  155953. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  155954. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  155955. )){
  155956. pCsr->isEof = 1;
  155957. }
  155958. return rc;
  155959. }
  155960. /*
  155961. ** Restart interation for expression pExpr so that the next call to
  155962. ** fts3EvalNext() visits the first row. Do not allow incremental
  155963. ** loading or merging of phrase doclists for this iteration.
  155964. **
  155965. ** If *pRc is other than SQLITE_OK when this function is called, it is
  155966. ** a no-op. If an error occurs within this function, *pRc is set to an
  155967. ** SQLite error code before returning.
  155968. */
  155969. static void fts3EvalRestart(
  155970. Fts3Cursor *pCsr,
  155971. Fts3Expr *pExpr,
  155972. int *pRc
  155973. ){
  155974. if( pExpr && *pRc==SQLITE_OK ){
  155975. Fts3Phrase *pPhrase = pExpr->pPhrase;
  155976. if( pPhrase ){
  155977. fts3EvalInvalidatePoslist(pPhrase);
  155978. if( pPhrase->bIncr ){
  155979. int i;
  155980. for(i=0; i<pPhrase->nToken; i++){
  155981. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  155982. assert( pToken->pDeferred==0 );
  155983. if( pToken->pSegcsr ){
  155984. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  155985. }
  155986. }
  155987. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  155988. }
  155989. pPhrase->doclist.pNextDocid = 0;
  155990. pPhrase->doclist.iDocid = 0;
  155991. pPhrase->pOrPoslist = 0;
  155992. }
  155993. pExpr->iDocid = 0;
  155994. pExpr->bEof = 0;
  155995. pExpr->bStart = 0;
  155996. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  155997. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  155998. }
  155999. }
  156000. /*
  156001. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  156002. ** expression rooted at pExpr, the cursor iterates through all rows matched
  156003. ** by pExpr, calling this function for each row. This function increments
  156004. ** the values in Fts3Expr.aMI[] according to the position-list currently
  156005. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  156006. ** expression nodes.
  156007. */
  156008. static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){
  156009. if( pExpr ){
  156010. Fts3Phrase *pPhrase = pExpr->pPhrase;
  156011. if( pPhrase && pPhrase->doclist.pList ){
  156012. int iCol = 0;
  156013. char *p = pPhrase->doclist.pList;
  156014. do{
  156015. u8 c = 0;
  156016. int iCnt = 0;
  156017. while( 0xFE & (*p | c) ){
  156018. if( (c&0x80)==0 ) iCnt++;
  156019. c = *p++ & 0x80;
  156020. }
  156021. /* aMI[iCol*3 + 1] = Number of occurrences
  156022. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  156023. */
  156024. pExpr->aMI[iCol*3 + 1] += iCnt;
  156025. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  156026. if( *p==0x00 ) break;
  156027. p++;
  156028. p += fts3GetVarint32(p, &iCol);
  156029. }while( iCol<nCol );
  156030. }
  156031. fts3EvalUpdateCounts(pExpr->pLeft, nCol);
  156032. fts3EvalUpdateCounts(pExpr->pRight, nCol);
  156033. }
  156034. }
  156035. /*
  156036. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  156037. **
  156038. ** If it is not already allocated and populated, this function allocates and
  156039. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  156040. ** of a NEAR expression, then it also allocates and populates the same array
  156041. ** for all other phrases that are part of the NEAR expression.
  156042. **
  156043. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  156044. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  156045. */
  156046. static int fts3EvalGatherStats(
  156047. Fts3Cursor *pCsr, /* Cursor object */
  156048. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  156049. ){
  156050. int rc = SQLITE_OK; /* Return code */
  156051. assert( pExpr->eType==FTSQUERY_PHRASE );
  156052. if( pExpr->aMI==0 ){
  156053. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  156054. Fts3Expr *pRoot; /* Root of NEAR expression */
  156055. Fts3Expr *p; /* Iterator used for several purposes */
  156056. sqlite3_int64 iPrevId = pCsr->iPrevId;
  156057. sqlite3_int64 iDocid;
  156058. u8 bEof;
  156059. /* Find the root of the NEAR expression */
  156060. pRoot = pExpr;
  156061. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  156062. pRoot = pRoot->pParent;
  156063. }
  156064. iDocid = pRoot->iDocid;
  156065. bEof = pRoot->bEof;
  156066. assert( pRoot->bStart );
  156067. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  156068. for(p=pRoot; p; p=p->pLeft){
  156069. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  156070. assert( pE->aMI==0 );
  156071. pE->aMI = (u32 *)sqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32));
  156072. if( !pE->aMI ) return SQLITE_NOMEM;
  156073. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  156074. }
  156075. fts3EvalRestart(pCsr, pRoot, &rc);
  156076. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  156077. do {
  156078. /* Ensure the %_content statement is reset. */
  156079. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  156080. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  156081. /* Advance to the next document */
  156082. fts3EvalNextRow(pCsr, pRoot, &rc);
  156083. pCsr->isEof = pRoot->bEof;
  156084. pCsr->isRequireSeek = 1;
  156085. pCsr->isMatchinfoNeeded = 1;
  156086. pCsr->iPrevId = pRoot->iDocid;
  156087. }while( pCsr->isEof==0
  156088. && pRoot->eType==FTSQUERY_NEAR
  156089. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  156090. );
  156091. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  156092. fts3EvalUpdateCounts(pRoot, pTab->nColumn);
  156093. }
  156094. }
  156095. pCsr->isEof = 0;
  156096. pCsr->iPrevId = iPrevId;
  156097. if( bEof ){
  156098. pRoot->bEof = bEof;
  156099. }else{
  156100. /* Caution: pRoot may iterate through docids in ascending or descending
  156101. ** order. For this reason, even though it seems more defensive, the
  156102. ** do loop can not be written:
  156103. **
  156104. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  156105. */
  156106. fts3EvalRestart(pCsr, pRoot, &rc);
  156107. do {
  156108. fts3EvalNextRow(pCsr, pRoot, &rc);
  156109. assert( pRoot->bEof==0 );
  156110. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  156111. }
  156112. }
  156113. return rc;
  156114. }
  156115. /*
  156116. ** This function is used by the matchinfo() module to query a phrase
  156117. ** expression node for the following information:
  156118. **
  156119. ** 1. The total number of occurrences of the phrase in each column of
  156120. ** the FTS table (considering all rows), and
  156121. **
  156122. ** 2. For each column, the number of rows in the table for which the
  156123. ** column contains at least one instance of the phrase.
  156124. **
  156125. ** If no error occurs, SQLITE_OK is returned and the values for each column
  156126. ** written into the array aiOut as follows:
  156127. **
  156128. ** aiOut[iCol*3 + 1] = Number of occurrences
  156129. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  156130. **
  156131. ** Caveats:
  156132. **
  156133. ** * If a phrase consists entirely of deferred tokens, then all output
  156134. ** values are set to the number of documents in the table. In other
  156135. ** words we assume that very common tokens occur exactly once in each
  156136. ** column of each row of the table.
  156137. **
  156138. ** * If a phrase contains some deferred tokens (and some non-deferred
  156139. ** tokens), count the potential occurrence identified by considering
  156140. ** the non-deferred tokens instead of actual phrase occurrences.
  156141. **
  156142. ** * If the phrase is part of a NEAR expression, then only phrase instances
  156143. ** that meet the NEAR constraint are included in the counts.
  156144. */
  156145. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  156146. Fts3Cursor *pCsr, /* FTS cursor handle */
  156147. Fts3Expr *pExpr, /* Phrase expression */
  156148. u32 *aiOut /* Array to write results into (see above) */
  156149. ){
  156150. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  156151. int rc = SQLITE_OK;
  156152. int iCol;
  156153. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  156154. assert( pCsr->nDoc>0 );
  156155. for(iCol=0; iCol<pTab->nColumn; iCol++){
  156156. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  156157. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  156158. }
  156159. }else{
  156160. rc = fts3EvalGatherStats(pCsr, pExpr);
  156161. if( rc==SQLITE_OK ){
  156162. assert( pExpr->aMI );
  156163. for(iCol=0; iCol<pTab->nColumn; iCol++){
  156164. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  156165. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  156166. }
  156167. }
  156168. }
  156169. return rc;
  156170. }
  156171. /*
  156172. ** The expression pExpr passed as the second argument to this function
  156173. ** must be of type FTSQUERY_PHRASE.
  156174. **
  156175. ** The returned value is either NULL or a pointer to a buffer containing
  156176. ** a position-list indicating the occurrences of the phrase in column iCol
  156177. ** of the current row.
  156178. **
  156179. ** More specifically, the returned buffer contains 1 varint for each
  156180. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  156181. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  156182. ** if the requested column contains "a b X c d X X" and the position-list
  156183. ** for 'X' is requested, the buffer returned may contain:
  156184. **
  156185. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  156186. **
  156187. ** This function works regardless of whether or not the phrase is deferred,
  156188. ** incremental, or neither.
  156189. */
  156190. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  156191. Fts3Cursor *pCsr, /* FTS3 cursor object */
  156192. Fts3Expr *pExpr, /* Phrase to return doclist for */
  156193. int iCol, /* Column to return position list for */
  156194. char **ppOut /* OUT: Pointer to position list */
  156195. ){
  156196. Fts3Phrase *pPhrase = pExpr->pPhrase;
  156197. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  156198. char *pIter;
  156199. int iThis;
  156200. sqlite3_int64 iDocid;
  156201. /* If this phrase is applies specifically to some column other than
  156202. ** column iCol, return a NULL pointer. */
  156203. *ppOut = 0;
  156204. assert( iCol>=0 && iCol<pTab->nColumn );
  156205. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  156206. return SQLITE_OK;
  156207. }
  156208. iDocid = pExpr->iDocid;
  156209. pIter = pPhrase->doclist.pList;
  156210. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  156211. int rc = SQLITE_OK;
  156212. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  156213. int bOr = 0;
  156214. u8 bTreeEof = 0;
  156215. Fts3Expr *p; /* Used to iterate from pExpr to root */
  156216. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  156217. int bMatch;
  156218. /* Check if this phrase descends from an OR expression node. If not,
  156219. ** return NULL. Otherwise, the entry that corresponds to docid
  156220. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  156221. ** tree that the node is part of has been marked as EOF, but the node
  156222. ** itself is not EOF, then it may point to an earlier entry. */
  156223. pNear = pExpr;
  156224. for(p=pExpr->pParent; p; p=p->pParent){
  156225. if( p->eType==FTSQUERY_OR ) bOr = 1;
  156226. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  156227. if( p->bEof ) bTreeEof = 1;
  156228. }
  156229. if( bOr==0 ) return SQLITE_OK;
  156230. /* This is the descendent of an OR node. In this case we cannot use
  156231. ** an incremental phrase. Load the entire doclist for the phrase
  156232. ** into memory in this case. */
  156233. if( pPhrase->bIncr ){
  156234. int bEofSave = pNear->bEof;
  156235. fts3EvalRestart(pCsr, pNear, &rc);
  156236. while( rc==SQLITE_OK && !pNear->bEof ){
  156237. fts3EvalNextRow(pCsr, pNear, &rc);
  156238. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  156239. }
  156240. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  156241. }
  156242. if( bTreeEof ){
  156243. while( rc==SQLITE_OK && !pNear->bEof ){
  156244. fts3EvalNextRow(pCsr, pNear, &rc);
  156245. }
  156246. }
  156247. if( rc!=SQLITE_OK ) return rc;
  156248. bMatch = 1;
  156249. for(p=pNear; p; p=p->pLeft){
  156250. u8 bEof = 0;
  156251. Fts3Expr *pTest = p;
  156252. Fts3Phrase *pPh;
  156253. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  156254. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  156255. assert( pTest->eType==FTSQUERY_PHRASE );
  156256. pPh = pTest->pPhrase;
  156257. pIter = pPh->pOrPoslist;
  156258. iDocid = pPh->iOrDocid;
  156259. if( pCsr->bDesc==bDescDoclist ){
  156260. bEof = !pPh->doclist.nAll ||
  156261. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  156262. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  156263. sqlite3Fts3DoclistNext(
  156264. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  156265. &pIter, &iDocid, &bEof
  156266. );
  156267. }
  156268. }else{
  156269. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  156270. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  156271. int dummy;
  156272. sqlite3Fts3DoclistPrev(
  156273. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  156274. &pIter, &iDocid, &dummy, &bEof
  156275. );
  156276. }
  156277. }
  156278. pPh->pOrPoslist = pIter;
  156279. pPh->iOrDocid = iDocid;
  156280. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  156281. }
  156282. if( bMatch ){
  156283. pIter = pPhrase->pOrPoslist;
  156284. }else{
  156285. pIter = 0;
  156286. }
  156287. }
  156288. if( pIter==0 ) return SQLITE_OK;
  156289. if( *pIter==0x01 ){
  156290. pIter++;
  156291. pIter += fts3GetVarint32(pIter, &iThis);
  156292. }else{
  156293. iThis = 0;
  156294. }
  156295. while( iThis<iCol ){
  156296. fts3ColumnlistCopy(0, &pIter);
  156297. if( *pIter==0x00 ) return SQLITE_OK;
  156298. pIter++;
  156299. pIter += fts3GetVarint32(pIter, &iThis);
  156300. }
  156301. if( *pIter==0x00 ){
  156302. pIter = 0;
  156303. }
  156304. *ppOut = ((iCol==iThis)?pIter:0);
  156305. return SQLITE_OK;
  156306. }
  156307. /*
  156308. ** Free all components of the Fts3Phrase structure that were allocated by
  156309. ** the eval module. Specifically, this means to free:
  156310. **
  156311. ** * the contents of pPhrase->doclist, and
  156312. ** * any Fts3MultiSegReader objects held by phrase tokens.
  156313. */
  156314. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  156315. if( pPhrase ){
  156316. int i;
  156317. sqlite3_free(pPhrase->doclist.aAll);
  156318. fts3EvalInvalidatePoslist(pPhrase);
  156319. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  156320. for(i=0; i<pPhrase->nToken; i++){
  156321. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  156322. pPhrase->aToken[i].pSegcsr = 0;
  156323. }
  156324. }
  156325. }
  156326. /*
  156327. ** Return SQLITE_CORRUPT_VTAB.
  156328. */
  156329. #ifdef SQLITE_DEBUG
  156330. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  156331. return SQLITE_CORRUPT_VTAB;
  156332. }
  156333. #endif
  156334. #if !SQLITE_CORE
  156335. /*
  156336. ** Initialize API pointer table, if required.
  156337. */
  156338. #ifdef _WIN32
  156339. __declspec(dllexport)
  156340. #endif
  156341. SQLITE_API int sqlite3_fts3_init(
  156342. sqlite3 *db,
  156343. char **pzErrMsg,
  156344. const sqlite3_api_routines *pApi
  156345. ){
  156346. SQLITE_EXTENSION_INIT2(pApi)
  156347. return sqlite3Fts3Init(db);
  156348. }
  156349. #endif
  156350. #endif
  156351. /************** End of fts3.c ************************************************/
  156352. /************** Begin file fts3_aux.c ****************************************/
  156353. /*
  156354. ** 2011 Jan 27
  156355. **
  156356. ** The author disclaims copyright to this source code. In place of
  156357. ** a legal notice, here is a blessing:
  156358. **
  156359. ** May you do good and not evil.
  156360. ** May you find forgiveness for yourself and forgive others.
  156361. ** May you share freely, never taking more than you give.
  156362. **
  156363. ******************************************************************************
  156364. **
  156365. */
  156366. /* #include "fts3Int.h" */
  156367. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  156368. /* #include <string.h> */
  156369. /* #include <assert.h> */
  156370. typedef struct Fts3auxTable Fts3auxTable;
  156371. typedef struct Fts3auxCursor Fts3auxCursor;
  156372. struct Fts3auxTable {
  156373. sqlite3_vtab base; /* Base class used by SQLite core */
  156374. Fts3Table *pFts3Tab;
  156375. };
  156376. struct Fts3auxCursor {
  156377. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  156378. Fts3MultiSegReader csr; /* Must be right after "base" */
  156379. Fts3SegFilter filter;
  156380. char *zStop;
  156381. int nStop; /* Byte-length of string zStop */
  156382. int iLangid; /* Language id to query */
  156383. int isEof; /* True if cursor is at EOF */
  156384. sqlite3_int64 iRowid; /* Current rowid */
  156385. int iCol; /* Current value of 'col' column */
  156386. int nStat; /* Size of aStat[] array */
  156387. struct Fts3auxColstats {
  156388. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  156389. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  156390. } *aStat;
  156391. };
  156392. /*
  156393. ** Schema of the terms table.
  156394. */
  156395. #define FTS3_AUX_SCHEMA \
  156396. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  156397. /*
  156398. ** This function does all the work for both the xConnect and xCreate methods.
  156399. ** These tables have no persistent representation of their own, so xConnect
  156400. ** and xCreate are identical operations.
  156401. */
  156402. static int fts3auxConnectMethod(
  156403. sqlite3 *db, /* Database connection */
  156404. void *pUnused, /* Unused */
  156405. int argc, /* Number of elements in argv array */
  156406. const char * const *argv, /* xCreate/xConnect argument array */
  156407. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  156408. char **pzErr /* OUT: sqlite3_malloc'd error message */
  156409. ){
  156410. char const *zDb; /* Name of database (e.g. "main") */
  156411. char const *zFts3; /* Name of fts3 table */
  156412. int nDb; /* Result of strlen(zDb) */
  156413. int nFts3; /* Result of strlen(zFts3) */
  156414. sqlite3_int64 nByte; /* Bytes of space to allocate here */
  156415. int rc; /* value returned by declare_vtab() */
  156416. Fts3auxTable *p; /* Virtual table object to return */
  156417. UNUSED_PARAMETER(pUnused);
  156418. /* The user should invoke this in one of two forms:
  156419. **
  156420. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  156421. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  156422. */
  156423. if( argc!=4 && argc!=5 ) goto bad_args;
  156424. zDb = argv[1];
  156425. nDb = (int)strlen(zDb);
  156426. if( argc==5 ){
  156427. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  156428. zDb = argv[3];
  156429. nDb = (int)strlen(zDb);
  156430. zFts3 = argv[4];
  156431. }else{
  156432. goto bad_args;
  156433. }
  156434. }else{
  156435. zFts3 = argv[3];
  156436. }
  156437. nFts3 = (int)strlen(zFts3);
  156438. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  156439. if( rc!=SQLITE_OK ) return rc;
  156440. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  156441. p = (Fts3auxTable *)sqlite3_malloc64(nByte);
  156442. if( !p ) return SQLITE_NOMEM;
  156443. memset(p, 0, nByte);
  156444. p->pFts3Tab = (Fts3Table *)&p[1];
  156445. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  156446. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  156447. p->pFts3Tab->db = db;
  156448. p->pFts3Tab->nIndex = 1;
  156449. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  156450. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  156451. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  156452. *ppVtab = (sqlite3_vtab *)p;
  156453. return SQLITE_OK;
  156454. bad_args:
  156455. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  156456. return SQLITE_ERROR;
  156457. }
  156458. /*
  156459. ** This function does the work for both the xDisconnect and xDestroy methods.
  156460. ** These tables have no persistent representation of their own, so xDisconnect
  156461. ** and xDestroy are identical operations.
  156462. */
  156463. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  156464. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  156465. Fts3Table *pFts3 = p->pFts3Tab;
  156466. int i;
  156467. /* Free any prepared statements held */
  156468. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  156469. sqlite3_finalize(pFts3->aStmt[i]);
  156470. }
  156471. sqlite3_free(pFts3->zSegmentsTbl);
  156472. sqlite3_free(p);
  156473. return SQLITE_OK;
  156474. }
  156475. #define FTS4AUX_EQ_CONSTRAINT 1
  156476. #define FTS4AUX_GE_CONSTRAINT 2
  156477. #define FTS4AUX_LE_CONSTRAINT 4
  156478. /*
  156479. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  156480. */
  156481. static int fts3auxBestIndexMethod(
  156482. sqlite3_vtab *pVTab,
  156483. sqlite3_index_info *pInfo
  156484. ){
  156485. int i;
  156486. int iEq = -1;
  156487. int iGe = -1;
  156488. int iLe = -1;
  156489. int iLangid = -1;
  156490. int iNext = 1; /* Next free argvIndex value */
  156491. UNUSED_PARAMETER(pVTab);
  156492. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  156493. if( pInfo->nOrderBy==1
  156494. && pInfo->aOrderBy[0].iColumn==0
  156495. && pInfo->aOrderBy[0].desc==0
  156496. ){
  156497. pInfo->orderByConsumed = 1;
  156498. }
  156499. /* Search for equality and range constraints on the "term" column.
  156500. ** And equality constraints on the hidden "languageid" column. */
  156501. for(i=0; i<pInfo->nConstraint; i++){
  156502. if( pInfo->aConstraint[i].usable ){
  156503. int op = pInfo->aConstraint[i].op;
  156504. int iCol = pInfo->aConstraint[i].iColumn;
  156505. if( iCol==0 ){
  156506. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  156507. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  156508. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  156509. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  156510. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  156511. }
  156512. if( iCol==4 ){
  156513. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  156514. }
  156515. }
  156516. }
  156517. if( iEq>=0 ){
  156518. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  156519. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  156520. pInfo->estimatedCost = 5;
  156521. }else{
  156522. pInfo->idxNum = 0;
  156523. pInfo->estimatedCost = 20000;
  156524. if( iGe>=0 ){
  156525. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  156526. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  156527. pInfo->estimatedCost /= 2;
  156528. }
  156529. if( iLe>=0 ){
  156530. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  156531. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  156532. pInfo->estimatedCost /= 2;
  156533. }
  156534. }
  156535. if( iLangid>=0 ){
  156536. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  156537. pInfo->estimatedCost--;
  156538. }
  156539. return SQLITE_OK;
  156540. }
  156541. /*
  156542. ** xOpen - Open a cursor.
  156543. */
  156544. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  156545. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  156546. UNUSED_PARAMETER(pVTab);
  156547. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  156548. if( !pCsr ) return SQLITE_NOMEM;
  156549. memset(pCsr, 0, sizeof(Fts3auxCursor));
  156550. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  156551. return SQLITE_OK;
  156552. }
  156553. /*
  156554. ** xClose - Close a cursor.
  156555. */
  156556. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  156557. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  156558. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  156559. sqlite3Fts3SegmentsClose(pFts3);
  156560. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  156561. sqlite3_free((void *)pCsr->filter.zTerm);
  156562. sqlite3_free(pCsr->zStop);
  156563. sqlite3_free(pCsr->aStat);
  156564. sqlite3_free(pCsr);
  156565. return SQLITE_OK;
  156566. }
  156567. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  156568. if( nSize>pCsr->nStat ){
  156569. struct Fts3auxColstats *aNew;
  156570. aNew = (struct Fts3auxColstats *)sqlite3_realloc64(pCsr->aStat,
  156571. sizeof(struct Fts3auxColstats) * nSize
  156572. );
  156573. if( aNew==0 ) return SQLITE_NOMEM;
  156574. memset(&aNew[pCsr->nStat], 0,
  156575. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  156576. );
  156577. pCsr->aStat = aNew;
  156578. pCsr->nStat = nSize;
  156579. }
  156580. return SQLITE_OK;
  156581. }
  156582. /*
  156583. ** xNext - Advance the cursor to the next row, if any.
  156584. */
  156585. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  156586. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  156587. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  156588. int rc;
  156589. /* Increment our pretend rowid value. */
  156590. pCsr->iRowid++;
  156591. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  156592. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  156593. }
  156594. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  156595. if( rc==SQLITE_ROW ){
  156596. int i = 0;
  156597. int nDoclist = pCsr->csr.nDoclist;
  156598. char *aDoclist = pCsr->csr.aDoclist;
  156599. int iCol;
  156600. int eState = 0;
  156601. if( pCsr->zStop ){
  156602. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  156603. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  156604. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  156605. pCsr->isEof = 1;
  156606. return SQLITE_OK;
  156607. }
  156608. }
  156609. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  156610. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  156611. iCol = 0;
  156612. while( i<nDoclist ){
  156613. sqlite3_int64 v = 0;
  156614. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  156615. switch( eState ){
  156616. /* State 0. In this state the integer just read was a docid. */
  156617. case 0:
  156618. pCsr->aStat[0].nDoc++;
  156619. eState = 1;
  156620. iCol = 0;
  156621. break;
  156622. /* State 1. In this state we are expecting either a 1, indicating
  156623. ** that the following integer will be a column number, or the
  156624. ** start of a position list for column 0.
  156625. **
  156626. ** The only difference between state 1 and state 2 is that if the
  156627. ** integer encountered in state 1 is not 0 or 1, then we need to
  156628. ** increment the column 0 "nDoc" count for this term.
  156629. */
  156630. case 1:
  156631. assert( iCol==0 );
  156632. if( v>1 ){
  156633. pCsr->aStat[1].nDoc++;
  156634. }
  156635. eState = 2;
  156636. /* fall through */
  156637. case 2:
  156638. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  156639. eState = 0;
  156640. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  156641. eState = 3;
  156642. }else{ /* 2 or greater. A position. */
  156643. pCsr->aStat[iCol+1].nOcc++;
  156644. pCsr->aStat[0].nOcc++;
  156645. }
  156646. break;
  156647. /* State 3. The integer just read is a column number. */
  156648. default: assert( eState==3 );
  156649. iCol = (int)v;
  156650. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  156651. pCsr->aStat[iCol+1].nDoc++;
  156652. eState = 2;
  156653. break;
  156654. }
  156655. }
  156656. pCsr->iCol = 0;
  156657. rc = SQLITE_OK;
  156658. }else{
  156659. pCsr->isEof = 1;
  156660. }
  156661. return rc;
  156662. }
  156663. /*
  156664. ** xFilter - Initialize a cursor to point at the start of its data.
  156665. */
  156666. static int fts3auxFilterMethod(
  156667. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  156668. int idxNum, /* Strategy index */
  156669. const char *idxStr, /* Unused */
  156670. int nVal, /* Number of elements in apVal */
  156671. sqlite3_value **apVal /* Arguments for the indexing scheme */
  156672. ){
  156673. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  156674. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  156675. int rc;
  156676. int isScan = 0;
  156677. int iLangVal = 0; /* Language id to query */
  156678. int iEq = -1; /* Index of term=? value in apVal */
  156679. int iGe = -1; /* Index of term>=? value in apVal */
  156680. int iLe = -1; /* Index of term<=? value in apVal */
  156681. int iLangid = -1; /* Index of languageid=? value in apVal */
  156682. int iNext = 0;
  156683. UNUSED_PARAMETER(nVal);
  156684. UNUSED_PARAMETER(idxStr);
  156685. assert( idxStr==0 );
  156686. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  156687. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  156688. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  156689. );
  156690. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  156691. iEq = iNext++;
  156692. }else{
  156693. isScan = 1;
  156694. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  156695. iGe = iNext++;
  156696. }
  156697. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  156698. iLe = iNext++;
  156699. }
  156700. }
  156701. if( iNext<nVal ){
  156702. iLangid = iNext++;
  156703. }
  156704. /* In case this cursor is being reused, close and zero it. */
  156705. testcase(pCsr->filter.zTerm);
  156706. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  156707. sqlite3_free((void *)pCsr->filter.zTerm);
  156708. sqlite3_free(pCsr->aStat);
  156709. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  156710. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  156711. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  156712. if( iEq>=0 || iGe>=0 ){
  156713. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  156714. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  156715. if( zStr ){
  156716. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  156717. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  156718. pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm);
  156719. }
  156720. }
  156721. if( iLe>=0 ){
  156722. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  156723. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  156724. pCsr->nStop = (int)strlen(pCsr->zStop);
  156725. }
  156726. if( iLangid>=0 ){
  156727. iLangVal = sqlite3_value_int(apVal[iLangid]);
  156728. /* If the user specified a negative value for the languageid, use zero
  156729. ** instead. This works, as the "languageid=?" constraint will also
  156730. ** be tested by the VDBE layer. The test will always be false (since
  156731. ** this module will not return a row with a negative languageid), and
  156732. ** so the overall query will return zero rows. */
  156733. if( iLangVal<0 ) iLangVal = 0;
  156734. }
  156735. pCsr->iLangid = iLangVal;
  156736. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  156737. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  156738. );
  156739. if( rc==SQLITE_OK ){
  156740. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  156741. }
  156742. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  156743. return rc;
  156744. }
  156745. /*
  156746. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  156747. */
  156748. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  156749. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  156750. return pCsr->isEof;
  156751. }
  156752. /*
  156753. ** xColumn - Return a column value.
  156754. */
  156755. static int fts3auxColumnMethod(
  156756. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  156757. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  156758. int iCol /* Index of column to read value from */
  156759. ){
  156760. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  156761. assert( p->isEof==0 );
  156762. switch( iCol ){
  156763. case 0: /* term */
  156764. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  156765. break;
  156766. case 1: /* col */
  156767. if( p->iCol ){
  156768. sqlite3_result_int(pCtx, p->iCol-1);
  156769. }else{
  156770. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  156771. }
  156772. break;
  156773. case 2: /* documents */
  156774. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  156775. break;
  156776. case 3: /* occurrences */
  156777. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  156778. break;
  156779. default: /* languageid */
  156780. assert( iCol==4 );
  156781. sqlite3_result_int(pCtx, p->iLangid);
  156782. break;
  156783. }
  156784. return SQLITE_OK;
  156785. }
  156786. /*
  156787. ** xRowid - Return the current rowid for the cursor.
  156788. */
  156789. static int fts3auxRowidMethod(
  156790. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  156791. sqlite_int64 *pRowid /* OUT: Rowid value */
  156792. ){
  156793. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  156794. *pRowid = pCsr->iRowid;
  156795. return SQLITE_OK;
  156796. }
  156797. /*
  156798. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  156799. ** if successful or an error code if sqlite3_create_module() fails.
  156800. */
  156801. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  156802. static const sqlite3_module fts3aux_module = {
  156803. 0, /* iVersion */
  156804. fts3auxConnectMethod, /* xCreate */
  156805. fts3auxConnectMethod, /* xConnect */
  156806. fts3auxBestIndexMethod, /* xBestIndex */
  156807. fts3auxDisconnectMethod, /* xDisconnect */
  156808. fts3auxDisconnectMethod, /* xDestroy */
  156809. fts3auxOpenMethod, /* xOpen */
  156810. fts3auxCloseMethod, /* xClose */
  156811. fts3auxFilterMethod, /* xFilter */
  156812. fts3auxNextMethod, /* xNext */
  156813. fts3auxEofMethod, /* xEof */
  156814. fts3auxColumnMethod, /* xColumn */
  156815. fts3auxRowidMethod, /* xRowid */
  156816. 0, /* xUpdate */
  156817. 0, /* xBegin */
  156818. 0, /* xSync */
  156819. 0, /* xCommit */
  156820. 0, /* xRollback */
  156821. 0, /* xFindFunction */
  156822. 0, /* xRename */
  156823. 0, /* xSavepoint */
  156824. 0, /* xRelease */
  156825. 0, /* xRollbackTo */
  156826. 0 /* xShadowName */
  156827. };
  156828. int rc; /* Return code */
  156829. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  156830. return rc;
  156831. }
  156832. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  156833. /************** End of fts3_aux.c ********************************************/
  156834. /************** Begin file fts3_expr.c ***************************************/
  156835. /*
  156836. ** 2008 Nov 28
  156837. **
  156838. ** The author disclaims copyright to this source code. In place of
  156839. ** a legal notice, here is a blessing:
  156840. **
  156841. ** May you do good and not evil.
  156842. ** May you find forgiveness for yourself and forgive others.
  156843. ** May you share freely, never taking more than you give.
  156844. **
  156845. ******************************************************************************
  156846. **
  156847. ** This module contains code that implements a parser for fts3 query strings
  156848. ** (the right-hand argument to the MATCH operator). Because the supported
  156849. ** syntax is relatively simple, the whole tokenizer/parser system is
  156850. ** hand-coded.
  156851. */
  156852. /* #include "fts3Int.h" */
  156853. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  156854. /*
  156855. ** By default, this module parses the legacy syntax that has been
  156856. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  156857. ** is defined, then it uses the new syntax. The differences between
  156858. ** the new and the old syntaxes are:
  156859. **
  156860. ** a) The new syntax supports parenthesis. The old does not.
  156861. **
  156862. ** b) The new syntax supports the AND and NOT operators. The old does not.
  156863. **
  156864. ** c) The old syntax supports the "-" token qualifier. This is not
  156865. ** supported by the new syntax (it is replaced by the NOT operator).
  156866. **
  156867. ** d) When using the old syntax, the OR operator has a greater precedence
  156868. ** than an implicit AND. When using the new, both implicity and explicit
  156869. ** AND operators have a higher precedence than OR.
  156870. **
  156871. ** If compiled with SQLITE_TEST defined, then this module exports the
  156872. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  156873. ** to zero causes the module to use the old syntax. If it is set to
  156874. ** non-zero the new syntax is activated. This is so both syntaxes can
  156875. ** be tested using a single build of testfixture.
  156876. **
  156877. ** The following describes the syntax supported by the fts3 MATCH
  156878. ** operator in a similar format to that used by the lemon parser
  156879. ** generator. This module does not use actually lemon, it uses a
  156880. ** custom parser.
  156881. **
  156882. ** query ::= andexpr (OR andexpr)*.
  156883. **
  156884. ** andexpr ::= notexpr (AND? notexpr)*.
  156885. **
  156886. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  156887. ** notexpr ::= LP query RP.
  156888. **
  156889. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  156890. **
  156891. ** distance_opt ::= .
  156892. ** distance_opt ::= / INTEGER.
  156893. **
  156894. ** phrase ::= TOKEN.
  156895. ** phrase ::= COLUMN:TOKEN.
  156896. ** phrase ::= "TOKEN TOKEN TOKEN...".
  156897. */
  156898. #ifdef SQLITE_TEST
  156899. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  156900. #else
  156901. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  156902. # define sqlite3_fts3_enable_parentheses 1
  156903. # else
  156904. # define sqlite3_fts3_enable_parentheses 0
  156905. # endif
  156906. #endif
  156907. /*
  156908. ** Default span for NEAR operators.
  156909. */
  156910. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  156911. /* #include <string.h> */
  156912. /* #include <assert.h> */
  156913. /*
  156914. ** isNot:
  156915. ** This variable is used by function getNextNode(). When getNextNode() is
  156916. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  156917. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  156918. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  156919. ** zero.
  156920. */
  156921. typedef struct ParseContext ParseContext;
  156922. struct ParseContext {
  156923. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  156924. int iLangid; /* Language id used with tokenizer */
  156925. const char **azCol; /* Array of column names for fts3 table */
  156926. int bFts4; /* True to allow FTS4-only syntax */
  156927. int nCol; /* Number of entries in azCol[] */
  156928. int iDefaultCol; /* Default column to query */
  156929. int isNot; /* True if getNextNode() sees a unary - */
  156930. sqlite3_context *pCtx; /* Write error message here */
  156931. int nNest; /* Number of nested brackets */
  156932. };
  156933. /*
  156934. ** This function is equivalent to the standard isspace() function.
  156935. **
  156936. ** The standard isspace() can be awkward to use safely, because although it
  156937. ** is defined to accept an argument of type int, its behavior when passed
  156938. ** an integer that falls outside of the range of the unsigned char type
  156939. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  156940. ** is defined to accept an argument of type char, and always returns 0 for
  156941. ** any values that fall outside of the range of the unsigned char type (i.e.
  156942. ** negative values).
  156943. */
  156944. static int fts3isspace(char c){
  156945. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  156946. }
  156947. /*
  156948. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  156949. ** zero the memory before returning a pointer to it. If unsuccessful,
  156950. ** return NULL.
  156951. */
  156952. static void *fts3MallocZero(sqlite3_int64 nByte){
  156953. void *pRet = sqlite3_malloc64(nByte);
  156954. if( pRet ) memset(pRet, 0, nByte);
  156955. return pRet;
  156956. }
  156957. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  156958. sqlite3_tokenizer *pTokenizer,
  156959. int iLangid,
  156960. const char *z,
  156961. int n,
  156962. sqlite3_tokenizer_cursor **ppCsr
  156963. ){
  156964. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  156965. sqlite3_tokenizer_cursor *pCsr = 0;
  156966. int rc;
  156967. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  156968. assert( rc==SQLITE_OK || pCsr==0 );
  156969. if( rc==SQLITE_OK ){
  156970. pCsr->pTokenizer = pTokenizer;
  156971. if( pModule->iVersion>=1 ){
  156972. rc = pModule->xLanguageid(pCsr, iLangid);
  156973. if( rc!=SQLITE_OK ){
  156974. pModule->xClose(pCsr);
  156975. pCsr = 0;
  156976. }
  156977. }
  156978. }
  156979. *ppCsr = pCsr;
  156980. return rc;
  156981. }
  156982. /*
  156983. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  156984. ** call fts3ExprParse(). So this forward declaration is required.
  156985. */
  156986. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  156987. /*
  156988. ** Extract the next token from buffer z (length n) using the tokenizer
  156989. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  156990. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  156991. ** single token and set *ppExpr to point to it. If the end of the buffer is
  156992. ** reached before a token is found, set *ppExpr to zero. It is the
  156993. ** responsibility of the caller to eventually deallocate the allocated
  156994. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  156995. **
  156996. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  156997. ** fails.
  156998. */
  156999. static int getNextToken(
  157000. ParseContext *pParse, /* fts3 query parse context */
  157001. int iCol, /* Value for Fts3Phrase.iColumn */
  157002. const char *z, int n, /* Input string */
  157003. Fts3Expr **ppExpr, /* OUT: expression */
  157004. int *pnConsumed /* OUT: Number of bytes consumed */
  157005. ){
  157006. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  157007. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  157008. int rc;
  157009. sqlite3_tokenizer_cursor *pCursor;
  157010. Fts3Expr *pRet = 0;
  157011. int i = 0;
  157012. /* Set variable i to the maximum number of bytes of input to tokenize. */
  157013. for(i=0; i<n; i++){
  157014. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  157015. if( z[i]=='"' ) break;
  157016. }
  157017. *pnConsumed = i;
  157018. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  157019. if( rc==SQLITE_OK ){
  157020. const char *zToken;
  157021. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  157022. sqlite3_int64 nByte; /* total space to allocate */
  157023. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  157024. if( rc==SQLITE_OK ){
  157025. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  157026. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  157027. if( !pRet ){
  157028. rc = SQLITE_NOMEM;
  157029. }else{
  157030. pRet->eType = FTSQUERY_PHRASE;
  157031. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  157032. pRet->pPhrase->nToken = 1;
  157033. pRet->pPhrase->iColumn = iCol;
  157034. pRet->pPhrase->aToken[0].n = nToken;
  157035. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  157036. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  157037. if( iEnd<n && z[iEnd]=='*' ){
  157038. pRet->pPhrase->aToken[0].isPrefix = 1;
  157039. iEnd++;
  157040. }
  157041. while( 1 ){
  157042. if( !sqlite3_fts3_enable_parentheses
  157043. && iStart>0 && z[iStart-1]=='-'
  157044. ){
  157045. pParse->isNot = 1;
  157046. iStart--;
  157047. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  157048. pRet->pPhrase->aToken[0].bFirst = 1;
  157049. iStart--;
  157050. }else{
  157051. break;
  157052. }
  157053. }
  157054. }
  157055. *pnConsumed = iEnd;
  157056. }else if( i && rc==SQLITE_DONE ){
  157057. rc = SQLITE_OK;
  157058. }
  157059. pModule->xClose(pCursor);
  157060. }
  157061. *ppExpr = pRet;
  157062. return rc;
  157063. }
  157064. /*
  157065. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  157066. ** then free the old allocation.
  157067. */
  157068. static void *fts3ReallocOrFree(void *pOrig, sqlite3_int64 nNew){
  157069. void *pRet = sqlite3_realloc64(pOrig, nNew);
  157070. if( !pRet ){
  157071. sqlite3_free(pOrig);
  157072. }
  157073. return pRet;
  157074. }
  157075. /*
  157076. ** Buffer zInput, length nInput, contains the contents of a quoted string
  157077. ** that appeared as part of an fts3 query expression. Neither quote character
  157078. ** is included in the buffer. This function attempts to tokenize the entire
  157079. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  157080. ** containing the results.
  157081. **
  157082. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  157083. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  157084. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  157085. ** to 0.
  157086. */
  157087. static int getNextString(
  157088. ParseContext *pParse, /* fts3 query parse context */
  157089. const char *zInput, int nInput, /* Input string */
  157090. Fts3Expr **ppExpr /* OUT: expression */
  157091. ){
  157092. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  157093. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  157094. int rc;
  157095. Fts3Expr *p = 0;
  157096. sqlite3_tokenizer_cursor *pCursor = 0;
  157097. char *zTemp = 0;
  157098. int nTemp = 0;
  157099. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  157100. int nToken = 0;
  157101. /* The final Fts3Expr data structure, including the Fts3Phrase,
  157102. ** Fts3PhraseToken structures token buffers are all stored as a single
  157103. ** allocation so that the expression can be freed with a single call to
  157104. ** sqlite3_free(). Setting this up requires a two pass approach.
  157105. **
  157106. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  157107. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  157108. ** to assemble data in two dynamic buffers:
  157109. **
  157110. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  157111. ** structure, followed by the array of Fts3PhraseToken
  157112. ** structures. This pass only populates the Fts3PhraseToken array.
  157113. **
  157114. ** Buffer zTemp: Contains copies of all tokens.
  157115. **
  157116. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  157117. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  157118. ** structures.
  157119. */
  157120. rc = sqlite3Fts3OpenTokenizer(
  157121. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  157122. if( rc==SQLITE_OK ){
  157123. int ii;
  157124. for(ii=0; rc==SQLITE_OK; ii++){
  157125. const char *zByte;
  157126. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  157127. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  157128. if( rc==SQLITE_OK ){
  157129. Fts3PhraseToken *pToken;
  157130. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  157131. if( !p ) goto no_mem;
  157132. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  157133. if( !zTemp ) goto no_mem;
  157134. assert( nToken==ii );
  157135. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  157136. memset(pToken, 0, sizeof(Fts3PhraseToken));
  157137. memcpy(&zTemp[nTemp], zByte, nByte);
  157138. nTemp += nByte;
  157139. pToken->n = nByte;
  157140. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  157141. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  157142. nToken = ii+1;
  157143. }
  157144. }
  157145. pModule->xClose(pCursor);
  157146. pCursor = 0;
  157147. }
  157148. if( rc==SQLITE_DONE ){
  157149. int jj;
  157150. char *zBuf = 0;
  157151. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  157152. if( !p ) goto no_mem;
  157153. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  157154. p->eType = FTSQUERY_PHRASE;
  157155. p->pPhrase = (Fts3Phrase *)&p[1];
  157156. p->pPhrase->iColumn = pParse->iDefaultCol;
  157157. p->pPhrase->nToken = nToken;
  157158. zBuf = (char *)&p->pPhrase->aToken[nToken];
  157159. if( zTemp ){
  157160. memcpy(zBuf, zTemp, nTemp);
  157161. sqlite3_free(zTemp);
  157162. }else{
  157163. assert( nTemp==0 );
  157164. }
  157165. for(jj=0; jj<p->pPhrase->nToken; jj++){
  157166. p->pPhrase->aToken[jj].z = zBuf;
  157167. zBuf += p->pPhrase->aToken[jj].n;
  157168. }
  157169. rc = SQLITE_OK;
  157170. }
  157171. *ppExpr = p;
  157172. return rc;
  157173. no_mem:
  157174. if( pCursor ){
  157175. pModule->xClose(pCursor);
  157176. }
  157177. sqlite3_free(zTemp);
  157178. sqlite3_free(p);
  157179. *ppExpr = 0;
  157180. return SQLITE_NOMEM;
  157181. }
  157182. /*
  157183. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  157184. ** structure, or set to 0 if the end of the input buffer is reached.
  157185. **
  157186. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  157187. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  157188. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  157189. */
  157190. static int getNextNode(
  157191. ParseContext *pParse, /* fts3 query parse context */
  157192. const char *z, int n, /* Input string */
  157193. Fts3Expr **ppExpr, /* OUT: expression */
  157194. int *pnConsumed /* OUT: Number of bytes consumed */
  157195. ){
  157196. static const struct Fts3Keyword {
  157197. char *z; /* Keyword text */
  157198. unsigned char n; /* Length of the keyword */
  157199. unsigned char parenOnly; /* Only valid in paren mode */
  157200. unsigned char eType; /* Keyword code */
  157201. } aKeyword[] = {
  157202. { "OR" , 2, 0, FTSQUERY_OR },
  157203. { "AND", 3, 1, FTSQUERY_AND },
  157204. { "NOT", 3, 1, FTSQUERY_NOT },
  157205. { "NEAR", 4, 0, FTSQUERY_NEAR }
  157206. };
  157207. int ii;
  157208. int iCol;
  157209. int iColLen;
  157210. int rc;
  157211. Fts3Expr *pRet = 0;
  157212. const char *zInput = z;
  157213. int nInput = n;
  157214. pParse->isNot = 0;
  157215. /* Skip over any whitespace before checking for a keyword, an open or
  157216. ** close bracket, or a quoted string.
  157217. */
  157218. while( nInput>0 && fts3isspace(*zInput) ){
  157219. nInput--;
  157220. zInput++;
  157221. }
  157222. if( nInput==0 ){
  157223. return SQLITE_DONE;
  157224. }
  157225. /* See if we are dealing with a keyword. */
  157226. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  157227. const struct Fts3Keyword *pKey = &aKeyword[ii];
  157228. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  157229. continue;
  157230. }
  157231. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  157232. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  157233. int nKey = pKey->n;
  157234. char cNext;
  157235. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  157236. if( pKey->eType==FTSQUERY_NEAR ){
  157237. assert( nKey==4 );
  157238. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  157239. nNear = 0;
  157240. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  157241. nNear = nNear * 10 + (zInput[nKey] - '0');
  157242. }
  157243. }
  157244. }
  157245. /* At this point this is probably a keyword. But for that to be true,
  157246. ** the next byte must contain either whitespace, an open or close
  157247. ** parenthesis, a quote character, or EOF.
  157248. */
  157249. cNext = zInput[nKey];
  157250. if( fts3isspace(cNext)
  157251. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  157252. ){
  157253. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  157254. if( !pRet ){
  157255. return SQLITE_NOMEM;
  157256. }
  157257. pRet->eType = pKey->eType;
  157258. pRet->nNear = nNear;
  157259. *ppExpr = pRet;
  157260. *pnConsumed = (int)((zInput - z) + nKey);
  157261. return SQLITE_OK;
  157262. }
  157263. /* Turns out that wasn't a keyword after all. This happens if the
  157264. ** user has supplied a token such as "ORacle". Continue.
  157265. */
  157266. }
  157267. }
  157268. /* See if we are dealing with a quoted phrase. If this is the case, then
  157269. ** search for the closing quote and pass the whole string to getNextString()
  157270. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  157271. ** a quote character embedded in a string.
  157272. */
  157273. if( *zInput=='"' ){
  157274. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  157275. *pnConsumed = (int)((zInput - z) + ii + 1);
  157276. if( ii==nInput ){
  157277. return SQLITE_ERROR;
  157278. }
  157279. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  157280. }
  157281. if( sqlite3_fts3_enable_parentheses ){
  157282. if( *zInput=='(' ){
  157283. int nConsumed = 0;
  157284. pParse->nNest++;
  157285. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  157286. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  157287. return rc;
  157288. }else if( *zInput==')' ){
  157289. pParse->nNest--;
  157290. *pnConsumed = (int)((zInput - z) + 1);
  157291. *ppExpr = 0;
  157292. return SQLITE_DONE;
  157293. }
  157294. }
  157295. /* If control flows to this point, this must be a regular token, or
  157296. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  157297. ** interface. Before doing so, figure out if there is an explicit
  157298. ** column specifier for the token.
  157299. **
  157300. ** TODO: Strangely, it is not possible to associate a column specifier
  157301. ** with a quoted phrase, only with a single token. Not sure if this was
  157302. ** an implementation artifact or an intentional decision when fts3 was
  157303. ** first implemented. Whichever it was, this module duplicates the
  157304. ** limitation.
  157305. */
  157306. iCol = pParse->iDefaultCol;
  157307. iColLen = 0;
  157308. for(ii=0; ii<pParse->nCol; ii++){
  157309. const char *zStr = pParse->azCol[ii];
  157310. int nStr = (int)strlen(zStr);
  157311. if( nInput>nStr && zInput[nStr]==':'
  157312. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  157313. ){
  157314. iCol = ii;
  157315. iColLen = (int)((zInput - z) + nStr + 1);
  157316. break;
  157317. }
  157318. }
  157319. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  157320. *pnConsumed += iColLen;
  157321. return rc;
  157322. }
  157323. /*
  157324. ** The argument is an Fts3Expr structure for a binary operator (any type
  157325. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  157326. ** precedence of the operator. Lower values have a higher precedence (i.e.
  157327. ** group more tightly). For example, in the C language, the == operator
  157328. ** groups more tightly than ||, and would therefore have a higher precedence.
  157329. **
  157330. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  157331. ** is defined), the order of the operators in precedence from highest to
  157332. ** lowest is:
  157333. **
  157334. ** NEAR
  157335. ** NOT
  157336. ** AND (including implicit ANDs)
  157337. ** OR
  157338. **
  157339. ** Note that when using the old query syntax, the OR operator has a higher
  157340. ** precedence than the AND operator.
  157341. */
  157342. static int opPrecedence(Fts3Expr *p){
  157343. assert( p->eType!=FTSQUERY_PHRASE );
  157344. if( sqlite3_fts3_enable_parentheses ){
  157345. return p->eType;
  157346. }else if( p->eType==FTSQUERY_NEAR ){
  157347. return 1;
  157348. }else if( p->eType==FTSQUERY_OR ){
  157349. return 2;
  157350. }
  157351. assert( p->eType==FTSQUERY_AND );
  157352. return 3;
  157353. }
  157354. /*
  157355. ** Argument ppHead contains a pointer to the current head of a query
  157356. ** expression tree being parsed. pPrev is the expression node most recently
  157357. ** inserted into the tree. This function adds pNew, which is always a binary
  157358. ** operator node, into the expression tree based on the relative precedence
  157359. ** of pNew and the existing nodes of the tree. This may result in the head
  157360. ** of the tree changing, in which case *ppHead is set to the new root node.
  157361. */
  157362. static void insertBinaryOperator(
  157363. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  157364. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  157365. Fts3Expr *pNew /* New binary node to insert into expression tree */
  157366. ){
  157367. Fts3Expr *pSplit = pPrev;
  157368. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  157369. pSplit = pSplit->pParent;
  157370. }
  157371. if( pSplit->pParent ){
  157372. assert( pSplit->pParent->pRight==pSplit );
  157373. pSplit->pParent->pRight = pNew;
  157374. pNew->pParent = pSplit->pParent;
  157375. }else{
  157376. *ppHead = pNew;
  157377. }
  157378. pNew->pLeft = pSplit;
  157379. pSplit->pParent = pNew;
  157380. }
  157381. /*
  157382. ** Parse the fts3 query expression found in buffer z, length n. This function
  157383. ** returns either when the end of the buffer is reached or an unmatched
  157384. ** closing bracket - ')' - is encountered.
  157385. **
  157386. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  157387. ** parsed form of the expression and *pnConsumed is set to the number of
  157388. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  157389. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  157390. */
  157391. static int fts3ExprParse(
  157392. ParseContext *pParse, /* fts3 query parse context */
  157393. const char *z, int n, /* Text of MATCH query */
  157394. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  157395. int *pnConsumed /* OUT: Number of bytes consumed */
  157396. ){
  157397. Fts3Expr *pRet = 0;
  157398. Fts3Expr *pPrev = 0;
  157399. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  157400. int nIn = n;
  157401. const char *zIn = z;
  157402. int rc = SQLITE_OK;
  157403. int isRequirePhrase = 1;
  157404. while( rc==SQLITE_OK ){
  157405. Fts3Expr *p = 0;
  157406. int nByte = 0;
  157407. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  157408. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  157409. if( rc==SQLITE_OK ){
  157410. if( p ){
  157411. int isPhrase;
  157412. if( !sqlite3_fts3_enable_parentheses
  157413. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  157414. ){
  157415. /* Create an implicit NOT operator. */
  157416. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  157417. if( !pNot ){
  157418. sqlite3Fts3ExprFree(p);
  157419. rc = SQLITE_NOMEM;
  157420. goto exprparse_out;
  157421. }
  157422. pNot->eType = FTSQUERY_NOT;
  157423. pNot->pRight = p;
  157424. p->pParent = pNot;
  157425. if( pNotBranch ){
  157426. pNot->pLeft = pNotBranch;
  157427. pNotBranch->pParent = pNot;
  157428. }
  157429. pNotBranch = pNot;
  157430. p = pPrev;
  157431. }else{
  157432. int eType = p->eType;
  157433. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  157434. /* The isRequirePhrase variable is set to true if a phrase or
  157435. ** an expression contained in parenthesis is required. If a
  157436. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  157437. ** isRequirePhrase is set, this is a syntax error.
  157438. */
  157439. if( !isPhrase && isRequirePhrase ){
  157440. sqlite3Fts3ExprFree(p);
  157441. rc = SQLITE_ERROR;
  157442. goto exprparse_out;
  157443. }
  157444. if( isPhrase && !isRequirePhrase ){
  157445. /* Insert an implicit AND operator. */
  157446. Fts3Expr *pAnd;
  157447. assert( pRet && pPrev );
  157448. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  157449. if( !pAnd ){
  157450. sqlite3Fts3ExprFree(p);
  157451. rc = SQLITE_NOMEM;
  157452. goto exprparse_out;
  157453. }
  157454. pAnd->eType = FTSQUERY_AND;
  157455. insertBinaryOperator(&pRet, pPrev, pAnd);
  157456. pPrev = pAnd;
  157457. }
  157458. /* This test catches attempts to make either operand of a NEAR
  157459. ** operator something other than a phrase. For example, either of
  157460. ** the following:
  157461. **
  157462. ** (bracketed expression) NEAR phrase
  157463. ** phrase NEAR (bracketed expression)
  157464. **
  157465. ** Return an error in either case.
  157466. */
  157467. if( pPrev && (
  157468. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  157469. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  157470. )){
  157471. sqlite3Fts3ExprFree(p);
  157472. rc = SQLITE_ERROR;
  157473. goto exprparse_out;
  157474. }
  157475. if( isPhrase ){
  157476. if( pRet ){
  157477. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  157478. pPrev->pRight = p;
  157479. p->pParent = pPrev;
  157480. }else{
  157481. pRet = p;
  157482. }
  157483. }else{
  157484. insertBinaryOperator(&pRet, pPrev, p);
  157485. }
  157486. isRequirePhrase = !isPhrase;
  157487. }
  157488. pPrev = p;
  157489. }
  157490. assert( nByte>0 );
  157491. }
  157492. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  157493. nIn -= nByte;
  157494. zIn += nByte;
  157495. }
  157496. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  157497. rc = SQLITE_ERROR;
  157498. }
  157499. if( rc==SQLITE_DONE ){
  157500. rc = SQLITE_OK;
  157501. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  157502. if( !pRet ){
  157503. rc = SQLITE_ERROR;
  157504. }else{
  157505. Fts3Expr *pIter = pNotBranch;
  157506. while( pIter->pLeft ){
  157507. pIter = pIter->pLeft;
  157508. }
  157509. pIter->pLeft = pRet;
  157510. pRet->pParent = pIter;
  157511. pRet = pNotBranch;
  157512. }
  157513. }
  157514. }
  157515. *pnConsumed = n - nIn;
  157516. exprparse_out:
  157517. if( rc!=SQLITE_OK ){
  157518. sqlite3Fts3ExprFree(pRet);
  157519. sqlite3Fts3ExprFree(pNotBranch);
  157520. pRet = 0;
  157521. }
  157522. *ppExpr = pRet;
  157523. return rc;
  157524. }
  157525. /*
  157526. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  157527. ** as the only argument is more than nMaxDepth.
  157528. */
  157529. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  157530. int rc = SQLITE_OK;
  157531. if( p ){
  157532. if( nMaxDepth<0 ){
  157533. rc = SQLITE_TOOBIG;
  157534. }else{
  157535. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  157536. if( rc==SQLITE_OK ){
  157537. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  157538. }
  157539. }
  157540. }
  157541. return rc;
  157542. }
  157543. /*
  157544. ** This function attempts to transform the expression tree at (*pp) to
  157545. ** an equivalent but more balanced form. The tree is modified in place.
  157546. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  157547. ** new root expression node.
  157548. **
  157549. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  157550. **
  157551. ** Otherwise, if an error occurs, an SQLite error code is returned and
  157552. ** expression (*pp) freed.
  157553. */
  157554. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  157555. int rc = SQLITE_OK; /* Return code */
  157556. Fts3Expr *pRoot = *pp; /* Initial root node */
  157557. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  157558. int eType = pRoot->eType; /* Type of node in this tree */
  157559. if( nMaxDepth==0 ){
  157560. rc = SQLITE_ERROR;
  157561. }
  157562. if( rc==SQLITE_OK ){
  157563. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  157564. Fts3Expr **apLeaf;
  157565. apLeaf = (Fts3Expr **)sqlite3_malloc64(sizeof(Fts3Expr *) * nMaxDepth);
  157566. if( 0==apLeaf ){
  157567. rc = SQLITE_NOMEM;
  157568. }else{
  157569. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  157570. }
  157571. if( rc==SQLITE_OK ){
  157572. int i;
  157573. Fts3Expr *p;
  157574. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  157575. for(p=pRoot; p->eType==eType; p=p->pLeft){
  157576. assert( p->pParent==0 || p->pParent->pLeft==p );
  157577. assert( p->pLeft && p->pRight );
  157578. }
  157579. /* This loop runs once for each leaf in the tree of eType nodes. */
  157580. while( 1 ){
  157581. int iLvl;
  157582. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  157583. assert( pParent==0 || pParent->pLeft==p );
  157584. p->pParent = 0;
  157585. if( pParent ){
  157586. pParent->pLeft = 0;
  157587. }else{
  157588. pRoot = 0;
  157589. }
  157590. rc = fts3ExprBalance(&p, nMaxDepth-1);
  157591. if( rc!=SQLITE_OK ) break;
  157592. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  157593. if( apLeaf[iLvl]==0 ){
  157594. apLeaf[iLvl] = p;
  157595. p = 0;
  157596. }else{
  157597. assert( pFree );
  157598. pFree->pLeft = apLeaf[iLvl];
  157599. pFree->pRight = p;
  157600. pFree->pLeft->pParent = pFree;
  157601. pFree->pRight->pParent = pFree;
  157602. p = pFree;
  157603. pFree = pFree->pParent;
  157604. p->pParent = 0;
  157605. apLeaf[iLvl] = 0;
  157606. }
  157607. }
  157608. if( p ){
  157609. sqlite3Fts3ExprFree(p);
  157610. rc = SQLITE_TOOBIG;
  157611. break;
  157612. }
  157613. /* If that was the last leaf node, break out of the loop */
  157614. if( pParent==0 ) break;
  157615. /* Set $p to point to the next leaf in the tree of eType nodes */
  157616. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  157617. /* Remove pParent from the original tree. */
  157618. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  157619. pParent->pRight->pParent = pParent->pParent;
  157620. if( pParent->pParent ){
  157621. pParent->pParent->pLeft = pParent->pRight;
  157622. }else{
  157623. assert( pParent==pRoot );
  157624. pRoot = pParent->pRight;
  157625. }
  157626. /* Link pParent into the free node list. It will be used as an
  157627. ** internal node of the new tree. */
  157628. pParent->pParent = pFree;
  157629. pFree = pParent;
  157630. }
  157631. if( rc==SQLITE_OK ){
  157632. p = 0;
  157633. for(i=0; i<nMaxDepth; i++){
  157634. if( apLeaf[i] ){
  157635. if( p==0 ){
  157636. p = apLeaf[i];
  157637. p->pParent = 0;
  157638. }else{
  157639. assert( pFree!=0 );
  157640. pFree->pRight = p;
  157641. pFree->pLeft = apLeaf[i];
  157642. pFree->pLeft->pParent = pFree;
  157643. pFree->pRight->pParent = pFree;
  157644. p = pFree;
  157645. pFree = pFree->pParent;
  157646. p->pParent = 0;
  157647. }
  157648. }
  157649. }
  157650. pRoot = p;
  157651. }else{
  157652. /* An error occurred. Delete the contents of the apLeaf[] array
  157653. ** and pFree list. Everything else is cleaned up by the call to
  157654. ** sqlite3Fts3ExprFree(pRoot) below. */
  157655. Fts3Expr *pDel;
  157656. for(i=0; i<nMaxDepth; i++){
  157657. sqlite3Fts3ExprFree(apLeaf[i]);
  157658. }
  157659. while( (pDel=pFree)!=0 ){
  157660. pFree = pDel->pParent;
  157661. sqlite3_free(pDel);
  157662. }
  157663. }
  157664. assert( pFree==0 );
  157665. sqlite3_free( apLeaf );
  157666. }
  157667. }else if( eType==FTSQUERY_NOT ){
  157668. Fts3Expr *pLeft = pRoot->pLeft;
  157669. Fts3Expr *pRight = pRoot->pRight;
  157670. pRoot->pLeft = 0;
  157671. pRoot->pRight = 0;
  157672. pLeft->pParent = 0;
  157673. pRight->pParent = 0;
  157674. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  157675. if( rc==SQLITE_OK ){
  157676. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  157677. }
  157678. if( rc!=SQLITE_OK ){
  157679. sqlite3Fts3ExprFree(pRight);
  157680. sqlite3Fts3ExprFree(pLeft);
  157681. }else{
  157682. assert( pLeft && pRight );
  157683. pRoot->pLeft = pLeft;
  157684. pLeft->pParent = pRoot;
  157685. pRoot->pRight = pRight;
  157686. pRight->pParent = pRoot;
  157687. }
  157688. }
  157689. }
  157690. if( rc!=SQLITE_OK ){
  157691. sqlite3Fts3ExprFree(pRoot);
  157692. pRoot = 0;
  157693. }
  157694. *pp = pRoot;
  157695. return rc;
  157696. }
  157697. /*
  157698. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  157699. ** differences:
  157700. **
  157701. ** 1. It does not do expression rebalancing.
  157702. ** 2. It does not check that the expression does not exceed the
  157703. ** maximum allowable depth.
  157704. ** 3. Even if it fails, *ppExpr may still be set to point to an
  157705. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  157706. ** in this case.
  157707. */
  157708. static int fts3ExprParseUnbalanced(
  157709. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  157710. int iLangid, /* Language id for tokenizer */
  157711. char **azCol, /* Array of column names for fts3 table */
  157712. int bFts4, /* True to allow FTS4-only syntax */
  157713. int nCol, /* Number of entries in azCol[] */
  157714. int iDefaultCol, /* Default column to query */
  157715. const char *z, int n, /* Text of MATCH query */
  157716. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  157717. ){
  157718. int nParsed;
  157719. int rc;
  157720. ParseContext sParse;
  157721. memset(&sParse, 0, sizeof(ParseContext));
  157722. sParse.pTokenizer = pTokenizer;
  157723. sParse.iLangid = iLangid;
  157724. sParse.azCol = (const char **)azCol;
  157725. sParse.nCol = nCol;
  157726. sParse.iDefaultCol = iDefaultCol;
  157727. sParse.bFts4 = bFts4;
  157728. if( z==0 ){
  157729. *ppExpr = 0;
  157730. return SQLITE_OK;
  157731. }
  157732. if( n<0 ){
  157733. n = (int)strlen(z);
  157734. }
  157735. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  157736. assert( rc==SQLITE_OK || *ppExpr==0 );
  157737. /* Check for mismatched parenthesis */
  157738. if( rc==SQLITE_OK && sParse.nNest ){
  157739. rc = SQLITE_ERROR;
  157740. }
  157741. return rc;
  157742. }
  157743. /*
  157744. ** Parameters z and n contain a pointer to and length of a buffer containing
  157745. ** an fts3 query expression, respectively. This function attempts to parse the
  157746. ** query expression and create a tree of Fts3Expr structures representing the
  157747. ** parsed expression. If successful, *ppExpr is set to point to the head
  157748. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  157749. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  157750. ** error) is returned and *ppExpr is set to 0.
  157751. **
  157752. ** If parameter n is a negative number, then z is assumed to point to a
  157753. ** nul-terminated string and the length is determined using strlen().
  157754. **
  157755. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  157756. ** use to normalize query tokens while parsing the expression. The azCol[]
  157757. ** array, which is assumed to contain nCol entries, should contain the names
  157758. ** of each column in the target fts3 table, in order from left to right.
  157759. ** Column names must be nul-terminated strings.
  157760. **
  157761. ** The iDefaultCol parameter should be passed the index of the table column
  157762. ** that appears on the left-hand-side of the MATCH operator (the default
  157763. ** column to match against for tokens for which a column name is not explicitly
  157764. ** specified as part of the query string), or -1 if tokens may by default
  157765. ** match any table column.
  157766. */
  157767. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  157768. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  157769. int iLangid, /* Language id for tokenizer */
  157770. char **azCol, /* Array of column names for fts3 table */
  157771. int bFts4, /* True to allow FTS4-only syntax */
  157772. int nCol, /* Number of entries in azCol[] */
  157773. int iDefaultCol, /* Default column to query */
  157774. const char *z, int n, /* Text of MATCH query */
  157775. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  157776. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  157777. ){
  157778. int rc = fts3ExprParseUnbalanced(
  157779. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  157780. );
  157781. /* Rebalance the expression. And check that its depth does not exceed
  157782. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  157783. if( rc==SQLITE_OK && *ppExpr ){
  157784. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  157785. if( rc==SQLITE_OK ){
  157786. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  157787. }
  157788. }
  157789. if( rc!=SQLITE_OK ){
  157790. sqlite3Fts3ExprFree(*ppExpr);
  157791. *ppExpr = 0;
  157792. if( rc==SQLITE_TOOBIG ){
  157793. sqlite3Fts3ErrMsg(pzErr,
  157794. "FTS expression tree is too large (maximum depth %d)",
  157795. SQLITE_FTS3_MAX_EXPR_DEPTH
  157796. );
  157797. rc = SQLITE_ERROR;
  157798. }else if( rc==SQLITE_ERROR ){
  157799. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  157800. }
  157801. }
  157802. return rc;
  157803. }
  157804. /*
  157805. ** Free a single node of an expression tree.
  157806. */
  157807. static void fts3FreeExprNode(Fts3Expr *p){
  157808. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  157809. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  157810. sqlite3_free(p->aMI);
  157811. sqlite3_free(p);
  157812. }
  157813. /*
  157814. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  157815. **
  157816. ** This function would be simpler if it recursively called itself. But
  157817. ** that would mean passing a sufficiently large expression to ExprParse()
  157818. ** could cause a stack overflow.
  157819. */
  157820. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  157821. Fts3Expr *p;
  157822. assert( pDel==0 || pDel->pParent==0 );
  157823. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  157824. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  157825. }
  157826. while( p ){
  157827. Fts3Expr *pParent = p->pParent;
  157828. fts3FreeExprNode(p);
  157829. if( pParent && p==pParent->pLeft && pParent->pRight ){
  157830. p = pParent->pRight;
  157831. while( p && (p->pLeft || p->pRight) ){
  157832. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  157833. p = (p->pLeft ? p->pLeft : p->pRight);
  157834. }
  157835. }else{
  157836. p = pParent;
  157837. }
  157838. }
  157839. }
  157840. /****************************************************************************
  157841. *****************************************************************************
  157842. ** Everything after this point is just test code.
  157843. */
  157844. #ifdef SQLITE_TEST
  157845. /* #include <stdio.h> */
  157846. /*
  157847. ** Return a pointer to a buffer containing a text representation of the
  157848. ** expression passed as the first argument. The buffer is obtained from
  157849. ** sqlite3_malloc(). It is the responsibility of the caller to use
  157850. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  157851. ** NULL is returned.
  157852. **
  157853. ** If the second argument is not NULL, then its contents are prepended to
  157854. ** the returned expression text and then freed using sqlite3_free().
  157855. */
  157856. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  157857. if( pExpr==0 ){
  157858. return sqlite3_mprintf("");
  157859. }
  157860. switch( pExpr->eType ){
  157861. case FTSQUERY_PHRASE: {
  157862. Fts3Phrase *pPhrase = pExpr->pPhrase;
  157863. int i;
  157864. zBuf = sqlite3_mprintf(
  157865. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  157866. for(i=0; zBuf && i<pPhrase->nToken; i++){
  157867. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  157868. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  157869. (pPhrase->aToken[i].isPrefix?"+":"")
  157870. );
  157871. }
  157872. return zBuf;
  157873. }
  157874. case FTSQUERY_NEAR:
  157875. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  157876. break;
  157877. case FTSQUERY_NOT:
  157878. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  157879. break;
  157880. case FTSQUERY_AND:
  157881. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  157882. break;
  157883. case FTSQUERY_OR:
  157884. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  157885. break;
  157886. }
  157887. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  157888. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  157889. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  157890. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  157891. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  157892. return zBuf;
  157893. }
  157894. /*
  157895. ** This is the implementation of a scalar SQL function used to test the
  157896. ** expression parser. It should be called as follows:
  157897. **
  157898. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  157899. **
  157900. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  157901. ** to parse the query expression (see README.tokenizers). The second argument
  157902. ** is the query expression to parse. Each subsequent argument is the name
  157903. ** of a column of the fts3 table that the query expression may refer to.
  157904. ** For example:
  157905. **
  157906. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  157907. */
  157908. static void fts3ExprTestCommon(
  157909. int bRebalance,
  157910. sqlite3_context *context,
  157911. int argc,
  157912. sqlite3_value **argv
  157913. ){
  157914. sqlite3_tokenizer *pTokenizer = 0;
  157915. int rc;
  157916. char **azCol = 0;
  157917. const char *zExpr;
  157918. int nExpr;
  157919. int nCol;
  157920. int ii;
  157921. Fts3Expr *pExpr;
  157922. char *zBuf = 0;
  157923. Fts3Hash *pHash = (Fts3Hash*)sqlite3_user_data(context);
  157924. const char *zTokenizer = 0;
  157925. char *zErr = 0;
  157926. if( argc<3 ){
  157927. sqlite3_result_error(context,
  157928. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  157929. );
  157930. return;
  157931. }
  157932. zTokenizer = (const char*)sqlite3_value_text(argv[0]);
  157933. rc = sqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr);
  157934. if( rc!=SQLITE_OK ){
  157935. if( rc==SQLITE_NOMEM ){
  157936. sqlite3_result_error_nomem(context);
  157937. }else{
  157938. sqlite3_result_error(context, zErr, -1);
  157939. }
  157940. sqlite3_free(zErr);
  157941. return;
  157942. }
  157943. zExpr = (const char *)sqlite3_value_text(argv[1]);
  157944. nExpr = sqlite3_value_bytes(argv[1]);
  157945. nCol = argc-2;
  157946. azCol = (char **)sqlite3_malloc64(nCol*sizeof(char *));
  157947. if( !azCol ){
  157948. sqlite3_result_error_nomem(context);
  157949. goto exprtest_out;
  157950. }
  157951. for(ii=0; ii<nCol; ii++){
  157952. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  157953. }
  157954. if( bRebalance ){
  157955. char *zDummy = 0;
  157956. rc = sqlite3Fts3ExprParse(
  157957. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  157958. );
  157959. assert( rc==SQLITE_OK || pExpr==0 );
  157960. sqlite3_free(zDummy);
  157961. }else{
  157962. rc = fts3ExprParseUnbalanced(
  157963. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  157964. );
  157965. }
  157966. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  157967. sqlite3Fts3ExprFree(pExpr);
  157968. sqlite3_result_error(context, "Error parsing expression", -1);
  157969. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  157970. sqlite3_result_error_nomem(context);
  157971. }else{
  157972. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  157973. sqlite3_free(zBuf);
  157974. }
  157975. sqlite3Fts3ExprFree(pExpr);
  157976. exprtest_out:
  157977. if( pTokenizer ){
  157978. rc = pTokenizer->pModule->xDestroy(pTokenizer);
  157979. }
  157980. sqlite3_free(azCol);
  157981. }
  157982. static void fts3ExprTest(
  157983. sqlite3_context *context,
  157984. int argc,
  157985. sqlite3_value **argv
  157986. ){
  157987. fts3ExprTestCommon(0, context, argc, argv);
  157988. }
  157989. static void fts3ExprTestRebalance(
  157990. sqlite3_context *context,
  157991. int argc,
  157992. sqlite3_value **argv
  157993. ){
  157994. fts3ExprTestCommon(1, context, argc, argv);
  157995. }
  157996. /*
  157997. ** Register the query expression parser test function fts3_exprtest()
  157998. ** with database connection db.
  157999. */
  158000. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
  158001. int rc = sqlite3_create_function(
  158002. db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
  158003. );
  158004. if( rc==SQLITE_OK ){
  158005. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  158006. -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
  158007. );
  158008. }
  158009. return rc;
  158010. }
  158011. #endif
  158012. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  158013. /************** End of fts3_expr.c *******************************************/
  158014. /************** Begin file fts3_hash.c ***************************************/
  158015. /*
  158016. ** 2001 September 22
  158017. **
  158018. ** The author disclaims copyright to this source code. In place of
  158019. ** a legal notice, here is a blessing:
  158020. **
  158021. ** May you do good and not evil.
  158022. ** May you find forgiveness for yourself and forgive others.
  158023. ** May you share freely, never taking more than you give.
  158024. **
  158025. *************************************************************************
  158026. ** This is the implementation of generic hash-tables used in SQLite.
  158027. ** We've modified it slightly to serve as a standalone hash table
  158028. ** implementation for the full-text indexing module.
  158029. */
  158030. /*
  158031. ** The code in this file is only compiled if:
  158032. **
  158033. ** * The FTS3 module is being built as an extension
  158034. ** (in which case SQLITE_CORE is not defined), or
  158035. **
  158036. ** * The FTS3 module is being built into the core of
  158037. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  158038. */
  158039. /* #include "fts3Int.h" */
  158040. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  158041. /* #include <assert.h> */
  158042. /* #include <stdlib.h> */
  158043. /* #include <string.h> */
  158044. /* #include "fts3_hash.h" */
  158045. /*
  158046. ** Malloc and Free functions
  158047. */
  158048. static void *fts3HashMalloc(sqlite3_int64 n){
  158049. void *p = sqlite3_malloc64(n);
  158050. if( p ){
  158051. memset(p, 0, n);
  158052. }
  158053. return p;
  158054. }
  158055. static void fts3HashFree(void *p){
  158056. sqlite3_free(p);
  158057. }
  158058. /* Turn bulk memory into a hash table object by initializing the
  158059. ** fields of the Hash structure.
  158060. **
  158061. ** "pNew" is a pointer to the hash table that is to be initialized.
  158062. ** keyClass is one of the constants
  158063. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  158064. ** determines what kind of key the hash table will use. "copyKey" is
  158065. ** true if the hash table should make its own private copy of keys and
  158066. ** false if it should just use the supplied pointer.
  158067. */
  158068. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  158069. assert( pNew!=0 );
  158070. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  158071. pNew->keyClass = keyClass;
  158072. pNew->copyKey = copyKey;
  158073. pNew->first = 0;
  158074. pNew->count = 0;
  158075. pNew->htsize = 0;
  158076. pNew->ht = 0;
  158077. }
  158078. /* Remove all entries from a hash table. Reclaim all memory.
  158079. ** Call this routine to delete a hash table or to reset a hash table
  158080. ** to the empty state.
  158081. */
  158082. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  158083. Fts3HashElem *elem; /* For looping over all elements of the table */
  158084. assert( pH!=0 );
  158085. elem = pH->first;
  158086. pH->first = 0;
  158087. fts3HashFree(pH->ht);
  158088. pH->ht = 0;
  158089. pH->htsize = 0;
  158090. while( elem ){
  158091. Fts3HashElem *next_elem = elem->next;
  158092. if( pH->copyKey && elem->pKey ){
  158093. fts3HashFree(elem->pKey);
  158094. }
  158095. fts3HashFree(elem);
  158096. elem = next_elem;
  158097. }
  158098. pH->count = 0;
  158099. }
  158100. /*
  158101. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  158102. */
  158103. static int fts3StrHash(const void *pKey, int nKey){
  158104. const char *z = (const char *)pKey;
  158105. unsigned h = 0;
  158106. if( nKey<=0 ) nKey = (int) strlen(z);
  158107. while( nKey > 0 ){
  158108. h = (h<<3) ^ h ^ *z++;
  158109. nKey--;
  158110. }
  158111. return (int)(h & 0x7fffffff);
  158112. }
  158113. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  158114. if( n1!=n2 ) return 1;
  158115. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  158116. }
  158117. /*
  158118. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  158119. */
  158120. static int fts3BinHash(const void *pKey, int nKey){
  158121. int h = 0;
  158122. const char *z = (const char *)pKey;
  158123. while( nKey-- > 0 ){
  158124. h = (h<<3) ^ h ^ *(z++);
  158125. }
  158126. return h & 0x7fffffff;
  158127. }
  158128. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  158129. if( n1!=n2 ) return 1;
  158130. return memcmp(pKey1,pKey2,n1);
  158131. }
  158132. /*
  158133. ** Return a pointer to the appropriate hash function given the key class.
  158134. **
  158135. ** The C syntax in this function definition may be unfamilar to some
  158136. ** programmers, so we provide the following additional explanation:
  158137. **
  158138. ** The name of the function is "ftsHashFunction". The function takes a
  158139. ** single parameter "keyClass". The return value of ftsHashFunction()
  158140. ** is a pointer to another function. Specifically, the return value
  158141. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  158142. ** with types "const void*" and "int" and returns an "int".
  158143. */
  158144. static int (*ftsHashFunction(int keyClass))(const void*,int){
  158145. if( keyClass==FTS3_HASH_STRING ){
  158146. return &fts3StrHash;
  158147. }else{
  158148. assert( keyClass==FTS3_HASH_BINARY );
  158149. return &fts3BinHash;
  158150. }
  158151. }
  158152. /*
  158153. ** Return a pointer to the appropriate hash function given the key class.
  158154. **
  158155. ** For help in interpreted the obscure C code in the function definition,
  158156. ** see the header comment on the previous function.
  158157. */
  158158. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  158159. if( keyClass==FTS3_HASH_STRING ){
  158160. return &fts3StrCompare;
  158161. }else{
  158162. assert( keyClass==FTS3_HASH_BINARY );
  158163. return &fts3BinCompare;
  158164. }
  158165. }
  158166. /* Link an element into the hash table
  158167. */
  158168. static void fts3HashInsertElement(
  158169. Fts3Hash *pH, /* The complete hash table */
  158170. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  158171. Fts3HashElem *pNew /* The element to be inserted */
  158172. ){
  158173. Fts3HashElem *pHead; /* First element already in pEntry */
  158174. pHead = pEntry->chain;
  158175. if( pHead ){
  158176. pNew->next = pHead;
  158177. pNew->prev = pHead->prev;
  158178. if( pHead->prev ){ pHead->prev->next = pNew; }
  158179. else { pH->first = pNew; }
  158180. pHead->prev = pNew;
  158181. }else{
  158182. pNew->next = pH->first;
  158183. if( pH->first ){ pH->first->prev = pNew; }
  158184. pNew->prev = 0;
  158185. pH->first = pNew;
  158186. }
  158187. pEntry->count++;
  158188. pEntry->chain = pNew;
  158189. }
  158190. /* Resize the hash table so that it cantains "new_size" buckets.
  158191. ** "new_size" must be a power of 2. The hash table might fail
  158192. ** to resize if sqliteMalloc() fails.
  158193. **
  158194. ** Return non-zero if a memory allocation error occurs.
  158195. */
  158196. static int fts3Rehash(Fts3Hash *pH, int new_size){
  158197. struct _fts3ht *new_ht; /* The new hash table */
  158198. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  158199. int (*xHash)(const void*,int); /* The hash function */
  158200. assert( (new_size & (new_size-1))==0 );
  158201. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  158202. if( new_ht==0 ) return 1;
  158203. fts3HashFree(pH->ht);
  158204. pH->ht = new_ht;
  158205. pH->htsize = new_size;
  158206. xHash = ftsHashFunction(pH->keyClass);
  158207. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  158208. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  158209. next_elem = elem->next;
  158210. fts3HashInsertElement(pH, &new_ht[h], elem);
  158211. }
  158212. return 0;
  158213. }
  158214. /* This function (for internal use only) locates an element in an
  158215. ** hash table that matches the given key. The hash for this key has
  158216. ** already been computed and is passed as the 4th parameter.
  158217. */
  158218. static Fts3HashElem *fts3FindElementByHash(
  158219. const Fts3Hash *pH, /* The pH to be searched */
  158220. const void *pKey, /* The key we are searching for */
  158221. int nKey,
  158222. int h /* The hash for this key. */
  158223. ){
  158224. Fts3HashElem *elem; /* Used to loop thru the element list */
  158225. int count; /* Number of elements left to test */
  158226. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  158227. if( pH->ht ){
  158228. struct _fts3ht *pEntry = &pH->ht[h];
  158229. elem = pEntry->chain;
  158230. count = pEntry->count;
  158231. xCompare = ftsCompareFunction(pH->keyClass);
  158232. while( count-- && elem ){
  158233. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  158234. return elem;
  158235. }
  158236. elem = elem->next;
  158237. }
  158238. }
  158239. return 0;
  158240. }
  158241. /* Remove a single entry from the hash table given a pointer to that
  158242. ** element and a hash on the element's key.
  158243. */
  158244. static void fts3RemoveElementByHash(
  158245. Fts3Hash *pH, /* The pH containing "elem" */
  158246. Fts3HashElem* elem, /* The element to be removed from the pH */
  158247. int h /* Hash value for the element */
  158248. ){
  158249. struct _fts3ht *pEntry;
  158250. if( elem->prev ){
  158251. elem->prev->next = elem->next;
  158252. }else{
  158253. pH->first = elem->next;
  158254. }
  158255. if( elem->next ){
  158256. elem->next->prev = elem->prev;
  158257. }
  158258. pEntry = &pH->ht[h];
  158259. if( pEntry->chain==elem ){
  158260. pEntry->chain = elem->next;
  158261. }
  158262. pEntry->count--;
  158263. if( pEntry->count<=0 ){
  158264. pEntry->chain = 0;
  158265. }
  158266. if( pH->copyKey && elem->pKey ){
  158267. fts3HashFree(elem->pKey);
  158268. }
  158269. fts3HashFree( elem );
  158270. pH->count--;
  158271. if( pH->count<=0 ){
  158272. assert( pH->first==0 );
  158273. assert( pH->count==0 );
  158274. fts3HashClear(pH);
  158275. }
  158276. }
  158277. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  158278. const Fts3Hash *pH,
  158279. const void *pKey,
  158280. int nKey
  158281. ){
  158282. int h; /* A hash on key */
  158283. int (*xHash)(const void*,int); /* The hash function */
  158284. if( pH==0 || pH->ht==0 ) return 0;
  158285. xHash = ftsHashFunction(pH->keyClass);
  158286. assert( xHash!=0 );
  158287. h = (*xHash)(pKey,nKey);
  158288. assert( (pH->htsize & (pH->htsize-1))==0 );
  158289. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  158290. }
  158291. /*
  158292. ** Attempt to locate an element of the hash table pH with a key
  158293. ** that matches pKey,nKey. Return the data for this element if it is
  158294. ** found, or NULL if there is no match.
  158295. */
  158296. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  158297. Fts3HashElem *pElem; /* The element that matches key (if any) */
  158298. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  158299. return pElem ? pElem->data : 0;
  158300. }
  158301. /* Insert an element into the hash table pH. The key is pKey,nKey
  158302. ** and the data is "data".
  158303. **
  158304. ** If no element exists with a matching key, then a new
  158305. ** element is created. A copy of the key is made if the copyKey
  158306. ** flag is set. NULL is returned.
  158307. **
  158308. ** If another element already exists with the same key, then the
  158309. ** new data replaces the old data and the old data is returned.
  158310. ** The key is not copied in this instance. If a malloc fails, then
  158311. ** the new data is returned and the hash table is unchanged.
  158312. **
  158313. ** If the "data" parameter to this function is NULL, then the
  158314. ** element corresponding to "key" is removed from the hash table.
  158315. */
  158316. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  158317. Fts3Hash *pH, /* The hash table to insert into */
  158318. const void *pKey, /* The key */
  158319. int nKey, /* Number of bytes in the key */
  158320. void *data /* The data */
  158321. ){
  158322. int hraw; /* Raw hash value of the key */
  158323. int h; /* the hash of the key modulo hash table size */
  158324. Fts3HashElem *elem; /* Used to loop thru the element list */
  158325. Fts3HashElem *new_elem; /* New element added to the pH */
  158326. int (*xHash)(const void*,int); /* The hash function */
  158327. assert( pH!=0 );
  158328. xHash = ftsHashFunction(pH->keyClass);
  158329. assert( xHash!=0 );
  158330. hraw = (*xHash)(pKey, nKey);
  158331. assert( (pH->htsize & (pH->htsize-1))==0 );
  158332. h = hraw & (pH->htsize-1);
  158333. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  158334. if( elem ){
  158335. void *old_data = elem->data;
  158336. if( data==0 ){
  158337. fts3RemoveElementByHash(pH,elem,h);
  158338. }else{
  158339. elem->data = data;
  158340. }
  158341. return old_data;
  158342. }
  158343. if( data==0 ) return 0;
  158344. if( (pH->htsize==0 && fts3Rehash(pH,8))
  158345. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  158346. ){
  158347. pH->count = 0;
  158348. return data;
  158349. }
  158350. assert( pH->htsize>0 );
  158351. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  158352. if( new_elem==0 ) return data;
  158353. if( pH->copyKey && pKey!=0 ){
  158354. new_elem->pKey = fts3HashMalloc( nKey );
  158355. if( new_elem->pKey==0 ){
  158356. fts3HashFree(new_elem);
  158357. return data;
  158358. }
  158359. memcpy((void*)new_elem->pKey, pKey, nKey);
  158360. }else{
  158361. new_elem->pKey = (void*)pKey;
  158362. }
  158363. new_elem->nKey = nKey;
  158364. pH->count++;
  158365. assert( pH->htsize>0 );
  158366. assert( (pH->htsize & (pH->htsize-1))==0 );
  158367. h = hraw & (pH->htsize-1);
  158368. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  158369. new_elem->data = data;
  158370. return 0;
  158371. }
  158372. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  158373. /************** End of fts3_hash.c *******************************************/
  158374. /************** Begin file fts3_porter.c *************************************/
  158375. /*
  158376. ** 2006 September 30
  158377. **
  158378. ** The author disclaims copyright to this source code. In place of
  158379. ** a legal notice, here is a blessing:
  158380. **
  158381. ** May you do good and not evil.
  158382. ** May you find forgiveness for yourself and forgive others.
  158383. ** May you share freely, never taking more than you give.
  158384. **
  158385. *************************************************************************
  158386. ** Implementation of the full-text-search tokenizer that implements
  158387. ** a Porter stemmer.
  158388. */
  158389. /*
  158390. ** The code in this file is only compiled if:
  158391. **
  158392. ** * The FTS3 module is being built as an extension
  158393. ** (in which case SQLITE_CORE is not defined), or
  158394. **
  158395. ** * The FTS3 module is being built into the core of
  158396. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  158397. */
  158398. /* #include "fts3Int.h" */
  158399. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  158400. /* #include <assert.h> */
  158401. /* #include <stdlib.h> */
  158402. /* #include <stdio.h> */
  158403. /* #include <string.h> */
  158404. /* #include "fts3_tokenizer.h" */
  158405. /*
  158406. ** Class derived from sqlite3_tokenizer
  158407. */
  158408. typedef struct porter_tokenizer {
  158409. sqlite3_tokenizer base; /* Base class */
  158410. } porter_tokenizer;
  158411. /*
  158412. ** Class derived from sqlite3_tokenizer_cursor
  158413. */
  158414. typedef struct porter_tokenizer_cursor {
  158415. sqlite3_tokenizer_cursor base;
  158416. const char *zInput; /* input we are tokenizing */
  158417. int nInput; /* size of the input */
  158418. int iOffset; /* current position in zInput */
  158419. int iToken; /* index of next token to be returned */
  158420. char *zToken; /* storage for current token */
  158421. int nAllocated; /* space allocated to zToken buffer */
  158422. } porter_tokenizer_cursor;
  158423. /*
  158424. ** Create a new tokenizer instance.
  158425. */
  158426. static int porterCreate(
  158427. int argc, const char * const *argv,
  158428. sqlite3_tokenizer **ppTokenizer
  158429. ){
  158430. porter_tokenizer *t;
  158431. UNUSED_PARAMETER(argc);
  158432. UNUSED_PARAMETER(argv);
  158433. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  158434. if( t==NULL ) return SQLITE_NOMEM;
  158435. memset(t, 0, sizeof(*t));
  158436. *ppTokenizer = &t->base;
  158437. return SQLITE_OK;
  158438. }
  158439. /*
  158440. ** Destroy a tokenizer
  158441. */
  158442. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  158443. sqlite3_free(pTokenizer);
  158444. return SQLITE_OK;
  158445. }
  158446. /*
  158447. ** Prepare to begin tokenizing a particular string. The input
  158448. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  158449. ** used to incrementally tokenize this string is returned in
  158450. ** *ppCursor.
  158451. */
  158452. static int porterOpen(
  158453. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  158454. const char *zInput, int nInput, /* String to be tokenized */
  158455. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  158456. ){
  158457. porter_tokenizer_cursor *c;
  158458. UNUSED_PARAMETER(pTokenizer);
  158459. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  158460. if( c==NULL ) return SQLITE_NOMEM;
  158461. c->zInput = zInput;
  158462. if( zInput==0 ){
  158463. c->nInput = 0;
  158464. }else if( nInput<0 ){
  158465. c->nInput = (int)strlen(zInput);
  158466. }else{
  158467. c->nInput = nInput;
  158468. }
  158469. c->iOffset = 0; /* start tokenizing at the beginning */
  158470. c->iToken = 0;
  158471. c->zToken = NULL; /* no space allocated, yet. */
  158472. c->nAllocated = 0;
  158473. *ppCursor = &c->base;
  158474. return SQLITE_OK;
  158475. }
  158476. /*
  158477. ** Close a tokenization cursor previously opened by a call to
  158478. ** porterOpen() above.
  158479. */
  158480. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  158481. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  158482. sqlite3_free(c->zToken);
  158483. sqlite3_free(c);
  158484. return SQLITE_OK;
  158485. }
  158486. /*
  158487. ** Vowel or consonant
  158488. */
  158489. static const char cType[] = {
  158490. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  158491. 1, 1, 1, 2, 1
  158492. };
  158493. /*
  158494. ** isConsonant() and isVowel() determine if their first character in
  158495. ** the string they point to is a consonant or a vowel, according
  158496. ** to Porter ruls.
  158497. **
  158498. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  158499. ** 'Y' is a consonant unless it follows another consonant,
  158500. ** in which case it is a vowel.
  158501. **
  158502. ** In these routine, the letters are in reverse order. So the 'y' rule
  158503. ** is that 'y' is a consonant unless it is followed by another
  158504. ** consonent.
  158505. */
  158506. static int isVowel(const char*);
  158507. static int isConsonant(const char *z){
  158508. int j;
  158509. char x = *z;
  158510. if( x==0 ) return 0;
  158511. assert( x>='a' && x<='z' );
  158512. j = cType[x-'a'];
  158513. if( j<2 ) return j;
  158514. return z[1]==0 || isVowel(z + 1);
  158515. }
  158516. static int isVowel(const char *z){
  158517. int j;
  158518. char x = *z;
  158519. if( x==0 ) return 0;
  158520. assert( x>='a' && x<='z' );
  158521. j = cType[x-'a'];
  158522. if( j<2 ) return 1-j;
  158523. return isConsonant(z + 1);
  158524. }
  158525. /*
  158526. ** Let any sequence of one or more vowels be represented by V and let
  158527. ** C be sequence of one or more consonants. Then every word can be
  158528. ** represented as:
  158529. **
  158530. ** [C] (VC){m} [V]
  158531. **
  158532. ** In prose: A word is an optional consonant followed by zero or
  158533. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  158534. ** number of vowel consonant pairs. This routine computes the value
  158535. ** of m for the first i bytes of a word.
  158536. **
  158537. ** Return true if the m-value for z is 1 or more. In other words,
  158538. ** return true if z contains at least one vowel that is followed
  158539. ** by a consonant.
  158540. **
  158541. ** In this routine z[] is in reverse order. So we are really looking
  158542. ** for an instance of a consonant followed by a vowel.
  158543. */
  158544. static int m_gt_0(const char *z){
  158545. while( isVowel(z) ){ z++; }
  158546. if( *z==0 ) return 0;
  158547. while( isConsonant(z) ){ z++; }
  158548. return *z!=0;
  158549. }
  158550. /* Like mgt0 above except we are looking for a value of m which is
  158551. ** exactly 1
  158552. */
  158553. static int m_eq_1(const char *z){
  158554. while( isVowel(z) ){ z++; }
  158555. if( *z==0 ) return 0;
  158556. while( isConsonant(z) ){ z++; }
  158557. if( *z==0 ) return 0;
  158558. while( isVowel(z) ){ z++; }
  158559. if( *z==0 ) return 1;
  158560. while( isConsonant(z) ){ z++; }
  158561. return *z==0;
  158562. }
  158563. /* Like mgt0 above except we are looking for a value of m>1 instead
  158564. ** or m>0
  158565. */
  158566. static int m_gt_1(const char *z){
  158567. while( isVowel(z) ){ z++; }
  158568. if( *z==0 ) return 0;
  158569. while( isConsonant(z) ){ z++; }
  158570. if( *z==0 ) return 0;
  158571. while( isVowel(z) ){ z++; }
  158572. if( *z==0 ) return 0;
  158573. while( isConsonant(z) ){ z++; }
  158574. return *z!=0;
  158575. }
  158576. /*
  158577. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  158578. */
  158579. static int hasVowel(const char *z){
  158580. while( isConsonant(z) ){ z++; }
  158581. return *z!=0;
  158582. }
  158583. /*
  158584. ** Return TRUE if the word ends in a double consonant.
  158585. **
  158586. ** The text is reversed here. So we are really looking at
  158587. ** the first two characters of z[].
  158588. */
  158589. static int doubleConsonant(const char *z){
  158590. return isConsonant(z) && z[0]==z[1];
  158591. }
  158592. /*
  158593. ** Return TRUE if the word ends with three letters which
  158594. ** are consonant-vowel-consonent and where the final consonant
  158595. ** is not 'w', 'x', or 'y'.
  158596. **
  158597. ** The word is reversed here. So we are really checking the
  158598. ** first three letters and the first one cannot be in [wxy].
  158599. */
  158600. static int star_oh(const char *z){
  158601. return
  158602. isConsonant(z) &&
  158603. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  158604. isVowel(z+1) &&
  158605. isConsonant(z+2);
  158606. }
  158607. /*
  158608. ** If the word ends with zFrom and xCond() is true for the stem
  158609. ** of the word that preceeds the zFrom ending, then change the
  158610. ** ending to zTo.
  158611. **
  158612. ** The input word *pz and zFrom are both in reverse order. zTo
  158613. ** is in normal order.
  158614. **
  158615. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  158616. ** match. Not that TRUE is returned even if xCond() fails and
  158617. ** no substitution occurs.
  158618. */
  158619. static int stem(
  158620. char **pz, /* The word being stemmed (Reversed) */
  158621. const char *zFrom, /* If the ending matches this... (Reversed) */
  158622. const char *zTo, /* ... change the ending to this (not reversed) */
  158623. int (*xCond)(const char*) /* Condition that must be true */
  158624. ){
  158625. char *z = *pz;
  158626. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  158627. if( *zFrom!=0 ) return 0;
  158628. if( xCond && !xCond(z) ) return 1;
  158629. while( *zTo ){
  158630. *(--z) = *(zTo++);
  158631. }
  158632. *pz = z;
  158633. return 1;
  158634. }
  158635. /*
  158636. ** This is the fallback stemmer used when the porter stemmer is
  158637. ** inappropriate. The input word is copied into the output with
  158638. ** US-ASCII case folding. If the input word is too long (more
  158639. ** than 20 bytes if it contains no digits or more than 6 bytes if
  158640. ** it contains digits) then word is truncated to 20 or 6 bytes
  158641. ** by taking 10 or 3 bytes from the beginning and end.
  158642. */
  158643. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  158644. int i, mx, j;
  158645. int hasDigit = 0;
  158646. for(i=0; i<nIn; i++){
  158647. char c = zIn[i];
  158648. if( c>='A' && c<='Z' ){
  158649. zOut[i] = c - 'A' + 'a';
  158650. }else{
  158651. if( c>='0' && c<='9' ) hasDigit = 1;
  158652. zOut[i] = c;
  158653. }
  158654. }
  158655. mx = hasDigit ? 3 : 10;
  158656. if( nIn>mx*2 ){
  158657. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  158658. zOut[j] = zOut[i];
  158659. }
  158660. i = j;
  158661. }
  158662. zOut[i] = 0;
  158663. *pnOut = i;
  158664. }
  158665. /*
  158666. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  158667. ** zOut is at least big enough to hold nIn bytes. Write the actual
  158668. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  158669. **
  158670. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  158671. ** are converted to lower case. Upper-case UTF characters are
  158672. ** unchanged.
  158673. **
  158674. ** Words that are longer than about 20 bytes are stemmed by retaining
  158675. ** a few bytes from the beginning and the end of the word. If the
  158676. ** word contains digits, 3 bytes are taken from the beginning and
  158677. ** 3 bytes from the end. For long words without digits, 10 bytes
  158678. ** are taken from each end. US-ASCII case folding still applies.
  158679. **
  158680. ** If the input word contains not digits but does characters not
  158681. ** in [a-zA-Z] then no stemming is attempted and this routine just
  158682. ** copies the input into the input into the output with US-ASCII
  158683. ** case folding.
  158684. **
  158685. ** Stemming never increases the length of the word. So there is
  158686. ** no chance of overflowing the zOut buffer.
  158687. */
  158688. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  158689. int i, j;
  158690. char zReverse[28];
  158691. char *z, *z2;
  158692. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  158693. /* The word is too big or too small for the porter stemmer.
  158694. ** Fallback to the copy stemmer */
  158695. copy_stemmer(zIn, nIn, zOut, pnOut);
  158696. return;
  158697. }
  158698. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  158699. char c = zIn[i];
  158700. if( c>='A' && c<='Z' ){
  158701. zReverse[j] = c + 'a' - 'A';
  158702. }else if( c>='a' && c<='z' ){
  158703. zReverse[j] = c;
  158704. }else{
  158705. /* The use of a character not in [a-zA-Z] means that we fallback
  158706. ** to the copy stemmer */
  158707. copy_stemmer(zIn, nIn, zOut, pnOut);
  158708. return;
  158709. }
  158710. }
  158711. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  158712. z = &zReverse[j+1];
  158713. /* Step 1a */
  158714. if( z[0]=='s' ){
  158715. if(
  158716. !stem(&z, "sess", "ss", 0) &&
  158717. !stem(&z, "sei", "i", 0) &&
  158718. !stem(&z, "ss", "ss", 0)
  158719. ){
  158720. z++;
  158721. }
  158722. }
  158723. /* Step 1b */
  158724. z2 = z;
  158725. if( stem(&z, "dee", "ee", m_gt_0) ){
  158726. /* Do nothing. The work was all in the test */
  158727. }else if(
  158728. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  158729. && z!=z2
  158730. ){
  158731. if( stem(&z, "ta", "ate", 0) ||
  158732. stem(&z, "lb", "ble", 0) ||
  158733. stem(&z, "zi", "ize", 0) ){
  158734. /* Do nothing. The work was all in the test */
  158735. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  158736. z++;
  158737. }else if( m_eq_1(z) && star_oh(z) ){
  158738. *(--z) = 'e';
  158739. }
  158740. }
  158741. /* Step 1c */
  158742. if( z[0]=='y' && hasVowel(z+1) ){
  158743. z[0] = 'i';
  158744. }
  158745. /* Step 2 */
  158746. switch( z[1] ){
  158747. case 'a':
  158748. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  158749. stem(&z, "lanoit", "tion", m_gt_0);
  158750. }
  158751. break;
  158752. case 'c':
  158753. if( !stem(&z, "icne", "ence", m_gt_0) ){
  158754. stem(&z, "icna", "ance", m_gt_0);
  158755. }
  158756. break;
  158757. case 'e':
  158758. stem(&z, "rezi", "ize", m_gt_0);
  158759. break;
  158760. case 'g':
  158761. stem(&z, "igol", "log", m_gt_0);
  158762. break;
  158763. case 'l':
  158764. if( !stem(&z, "ilb", "ble", m_gt_0)
  158765. && !stem(&z, "illa", "al", m_gt_0)
  158766. && !stem(&z, "iltne", "ent", m_gt_0)
  158767. && !stem(&z, "ile", "e", m_gt_0)
  158768. ){
  158769. stem(&z, "ilsuo", "ous", m_gt_0);
  158770. }
  158771. break;
  158772. case 'o':
  158773. if( !stem(&z, "noitazi", "ize", m_gt_0)
  158774. && !stem(&z, "noita", "ate", m_gt_0)
  158775. ){
  158776. stem(&z, "rota", "ate", m_gt_0);
  158777. }
  158778. break;
  158779. case 's':
  158780. if( !stem(&z, "msila", "al", m_gt_0)
  158781. && !stem(&z, "ssenevi", "ive", m_gt_0)
  158782. && !stem(&z, "ssenluf", "ful", m_gt_0)
  158783. ){
  158784. stem(&z, "ssensuo", "ous", m_gt_0);
  158785. }
  158786. break;
  158787. case 't':
  158788. if( !stem(&z, "itila", "al", m_gt_0)
  158789. && !stem(&z, "itivi", "ive", m_gt_0)
  158790. ){
  158791. stem(&z, "itilib", "ble", m_gt_0);
  158792. }
  158793. break;
  158794. }
  158795. /* Step 3 */
  158796. switch( z[0] ){
  158797. case 'e':
  158798. if( !stem(&z, "etaci", "ic", m_gt_0)
  158799. && !stem(&z, "evita", "", m_gt_0)
  158800. ){
  158801. stem(&z, "ezila", "al", m_gt_0);
  158802. }
  158803. break;
  158804. case 'i':
  158805. stem(&z, "itici", "ic", m_gt_0);
  158806. break;
  158807. case 'l':
  158808. if( !stem(&z, "laci", "ic", m_gt_0) ){
  158809. stem(&z, "luf", "", m_gt_0);
  158810. }
  158811. break;
  158812. case 's':
  158813. stem(&z, "ssen", "", m_gt_0);
  158814. break;
  158815. }
  158816. /* Step 4 */
  158817. switch( z[1] ){
  158818. case 'a':
  158819. if( z[0]=='l' && m_gt_1(z+2) ){
  158820. z += 2;
  158821. }
  158822. break;
  158823. case 'c':
  158824. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  158825. z += 4;
  158826. }
  158827. break;
  158828. case 'e':
  158829. if( z[0]=='r' && m_gt_1(z+2) ){
  158830. z += 2;
  158831. }
  158832. break;
  158833. case 'i':
  158834. if( z[0]=='c' && m_gt_1(z+2) ){
  158835. z += 2;
  158836. }
  158837. break;
  158838. case 'l':
  158839. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  158840. z += 4;
  158841. }
  158842. break;
  158843. case 'n':
  158844. if( z[0]=='t' ){
  158845. if( z[2]=='a' ){
  158846. if( m_gt_1(z+3) ){
  158847. z += 3;
  158848. }
  158849. }else if( z[2]=='e' ){
  158850. if( !stem(&z, "tneme", "", m_gt_1)
  158851. && !stem(&z, "tnem", "", m_gt_1)
  158852. ){
  158853. stem(&z, "tne", "", m_gt_1);
  158854. }
  158855. }
  158856. }
  158857. break;
  158858. case 'o':
  158859. if( z[0]=='u' ){
  158860. if( m_gt_1(z+2) ){
  158861. z += 2;
  158862. }
  158863. }else if( z[3]=='s' || z[3]=='t' ){
  158864. stem(&z, "noi", "", m_gt_1);
  158865. }
  158866. break;
  158867. case 's':
  158868. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  158869. z += 3;
  158870. }
  158871. break;
  158872. case 't':
  158873. if( !stem(&z, "eta", "", m_gt_1) ){
  158874. stem(&z, "iti", "", m_gt_1);
  158875. }
  158876. break;
  158877. case 'u':
  158878. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  158879. z += 3;
  158880. }
  158881. break;
  158882. case 'v':
  158883. case 'z':
  158884. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  158885. z += 3;
  158886. }
  158887. break;
  158888. }
  158889. /* Step 5a */
  158890. if( z[0]=='e' ){
  158891. if( m_gt_1(z+1) ){
  158892. z++;
  158893. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  158894. z++;
  158895. }
  158896. }
  158897. /* Step 5b */
  158898. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  158899. z++;
  158900. }
  158901. /* z[] is now the stemmed word in reverse order. Flip it back
  158902. ** around into forward order and return.
  158903. */
  158904. *pnOut = i = (int)strlen(z);
  158905. zOut[i] = 0;
  158906. while( *z ){
  158907. zOut[--i] = *(z++);
  158908. }
  158909. }
  158910. /*
  158911. ** Characters that can be part of a token. We assume any character
  158912. ** whose value is greater than 0x80 (any UTF character) can be
  158913. ** part of a token. In other words, delimiters all must have
  158914. ** values of 0x7f or lower.
  158915. */
  158916. static const char porterIdChar[] = {
  158917. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  158918. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  158919. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  158920. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  158921. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  158922. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  158923. };
  158924. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  158925. /*
  158926. ** Extract the next token from a tokenization cursor. The cursor must
  158927. ** have been opened by a prior call to porterOpen().
  158928. */
  158929. static int porterNext(
  158930. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  158931. const char **pzToken, /* OUT: *pzToken is the token text */
  158932. int *pnBytes, /* OUT: Number of bytes in token */
  158933. int *piStartOffset, /* OUT: Starting offset of token */
  158934. int *piEndOffset, /* OUT: Ending offset of token */
  158935. int *piPosition /* OUT: Position integer of token */
  158936. ){
  158937. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  158938. const char *z = c->zInput;
  158939. while( c->iOffset<c->nInput ){
  158940. int iStartOffset, ch;
  158941. /* Scan past delimiter characters */
  158942. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  158943. c->iOffset++;
  158944. }
  158945. /* Count non-delimiter characters. */
  158946. iStartOffset = c->iOffset;
  158947. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  158948. c->iOffset++;
  158949. }
  158950. if( c->iOffset>iStartOffset ){
  158951. int n = c->iOffset-iStartOffset;
  158952. if( n>c->nAllocated ){
  158953. char *pNew;
  158954. c->nAllocated = n+20;
  158955. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  158956. if( !pNew ) return SQLITE_NOMEM;
  158957. c->zToken = pNew;
  158958. }
  158959. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  158960. *pzToken = c->zToken;
  158961. *piStartOffset = iStartOffset;
  158962. *piEndOffset = c->iOffset;
  158963. *piPosition = c->iToken++;
  158964. return SQLITE_OK;
  158965. }
  158966. }
  158967. return SQLITE_DONE;
  158968. }
  158969. /*
  158970. ** The set of routines that implement the porter-stemmer tokenizer
  158971. */
  158972. static const sqlite3_tokenizer_module porterTokenizerModule = {
  158973. 0,
  158974. porterCreate,
  158975. porterDestroy,
  158976. porterOpen,
  158977. porterClose,
  158978. porterNext,
  158979. 0
  158980. };
  158981. /*
  158982. ** Allocate a new porter tokenizer. Return a pointer to the new
  158983. ** tokenizer in *ppModule
  158984. */
  158985. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  158986. sqlite3_tokenizer_module const**ppModule
  158987. ){
  158988. *ppModule = &porterTokenizerModule;
  158989. }
  158990. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  158991. /************** End of fts3_porter.c *****************************************/
  158992. /************** Begin file fts3_tokenizer.c **********************************/
  158993. /*
  158994. ** 2007 June 22
  158995. **
  158996. ** The author disclaims copyright to this source code. In place of
  158997. ** a legal notice, here is a blessing:
  158998. **
  158999. ** May you do good and not evil.
  159000. ** May you find forgiveness for yourself and forgive others.
  159001. ** May you share freely, never taking more than you give.
  159002. **
  159003. ******************************************************************************
  159004. **
  159005. ** This is part of an SQLite module implementing full-text search.
  159006. ** This particular file implements the generic tokenizer interface.
  159007. */
  159008. /*
  159009. ** The code in this file is only compiled if:
  159010. **
  159011. ** * The FTS3 module is being built as an extension
  159012. ** (in which case SQLITE_CORE is not defined), or
  159013. **
  159014. ** * The FTS3 module is being built into the core of
  159015. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  159016. */
  159017. /* #include "fts3Int.h" */
  159018. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  159019. /* #include <assert.h> */
  159020. /* #include <string.h> */
  159021. /*
  159022. ** Return true if the two-argument version of fts3_tokenizer()
  159023. ** has been activated via a prior call to sqlite3_db_config(db,
  159024. ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
  159025. */
  159026. static int fts3TokenizerEnabled(sqlite3_context *context){
  159027. sqlite3 *db = sqlite3_context_db_handle(context);
  159028. int isEnabled = 0;
  159029. sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
  159030. return isEnabled;
  159031. }
  159032. /*
  159033. ** Implementation of the SQL scalar function for accessing the underlying
  159034. ** hash table. This function may be called as follows:
  159035. **
  159036. ** SELECT <function-name>(<key-name>);
  159037. ** SELECT <function-name>(<key-name>, <pointer>);
  159038. **
  159039. ** where <function-name> is the name passed as the second argument
  159040. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  159041. **
  159042. ** If the <pointer> argument is specified, it must be a blob value
  159043. ** containing a pointer to be stored as the hash data corresponding
  159044. ** to the string <key-name>. If <pointer> is not specified, then
  159045. ** the string <key-name> must already exist in the has table. Otherwise,
  159046. ** an error is returned.
  159047. **
  159048. ** Whether or not the <pointer> argument is specified, the value returned
  159049. ** is a blob containing the pointer stored as the hash data corresponding
  159050. ** to string <key-name> (after the hash-table is updated, if applicable).
  159051. */
  159052. static void fts3TokenizerFunc(
  159053. sqlite3_context *context,
  159054. int argc,
  159055. sqlite3_value **argv
  159056. ){
  159057. Fts3Hash *pHash;
  159058. void *pPtr = 0;
  159059. const unsigned char *zName;
  159060. int nName;
  159061. assert( argc==1 || argc==2 );
  159062. pHash = (Fts3Hash *)sqlite3_user_data(context);
  159063. zName = sqlite3_value_text(argv[0]);
  159064. nName = sqlite3_value_bytes(argv[0])+1;
  159065. if( argc==2 ){
  159066. if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[1]) ){
  159067. void *pOld;
  159068. int n = sqlite3_value_bytes(argv[1]);
  159069. if( zName==0 || n!=sizeof(pPtr) ){
  159070. sqlite3_result_error(context, "argument type mismatch", -1);
  159071. return;
  159072. }
  159073. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  159074. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  159075. if( pOld==pPtr ){
  159076. sqlite3_result_error(context, "out of memory", -1);
  159077. }
  159078. }else{
  159079. sqlite3_result_error(context, "fts3tokenize disabled", -1);
  159080. return;
  159081. }
  159082. }else{
  159083. if( zName ){
  159084. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  159085. }
  159086. if( !pPtr ){
  159087. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  159088. sqlite3_result_error(context, zErr, -1);
  159089. sqlite3_free(zErr);
  159090. return;
  159091. }
  159092. }
  159093. if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[0]) ){
  159094. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  159095. }
  159096. }
  159097. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  159098. static const char isFtsIdChar[] = {
  159099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  159100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  159101. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  159102. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  159103. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  159104. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  159105. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  159106. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  159107. };
  159108. return (c&0x80 || isFtsIdChar[(int)(c)]);
  159109. }
  159110. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  159111. const char *z1;
  159112. const char *z2 = 0;
  159113. /* Find the start of the next token. */
  159114. z1 = zStr;
  159115. while( z2==0 ){
  159116. char c = *z1;
  159117. switch( c ){
  159118. case '\0': return 0; /* No more tokens here */
  159119. case '\'':
  159120. case '"':
  159121. case '`': {
  159122. z2 = z1;
  159123. while( *++z2 && (*z2!=c || *++z2==c) );
  159124. break;
  159125. }
  159126. case '[':
  159127. z2 = &z1[1];
  159128. while( *z2 && z2[0]!=']' ) z2++;
  159129. if( *z2 ) z2++;
  159130. break;
  159131. default:
  159132. if( sqlite3Fts3IsIdChar(*z1) ){
  159133. z2 = &z1[1];
  159134. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  159135. }else{
  159136. z1++;
  159137. }
  159138. }
  159139. }
  159140. *pn = (int)(z2-z1);
  159141. return z1;
  159142. }
  159143. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  159144. Fts3Hash *pHash, /* Tokenizer hash table */
  159145. const char *zArg, /* Tokenizer name */
  159146. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  159147. char **pzErr /* OUT: Set to malloced error message */
  159148. ){
  159149. int rc;
  159150. char *z = (char *)zArg;
  159151. int n = 0;
  159152. char *zCopy;
  159153. char *zEnd; /* Pointer to nul-term of zCopy */
  159154. sqlite3_tokenizer_module *m;
  159155. zCopy = sqlite3_mprintf("%s", zArg);
  159156. if( !zCopy ) return SQLITE_NOMEM;
  159157. zEnd = &zCopy[strlen(zCopy)];
  159158. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  159159. if( z==0 ){
  159160. assert( n==0 );
  159161. z = zCopy;
  159162. }
  159163. z[n] = '\0';
  159164. sqlite3Fts3Dequote(z);
  159165. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  159166. if( !m ){
  159167. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  159168. rc = SQLITE_ERROR;
  159169. }else{
  159170. char const **aArg = 0;
  159171. int iArg = 0;
  159172. z = &z[n+1];
  159173. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  159174. sqlite3_int64 nNew = sizeof(char *)*(iArg+1);
  159175. char const **aNew = (const char **)sqlite3_realloc64((void *)aArg, nNew);
  159176. if( !aNew ){
  159177. sqlite3_free(zCopy);
  159178. sqlite3_free((void *)aArg);
  159179. return SQLITE_NOMEM;
  159180. }
  159181. aArg = aNew;
  159182. aArg[iArg++] = z;
  159183. z[n] = '\0';
  159184. sqlite3Fts3Dequote(z);
  159185. z = &z[n+1];
  159186. }
  159187. rc = m->xCreate(iArg, aArg, ppTok);
  159188. assert( rc!=SQLITE_OK || *ppTok );
  159189. if( rc!=SQLITE_OK ){
  159190. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  159191. }else{
  159192. (*ppTok)->pModule = m;
  159193. }
  159194. sqlite3_free((void *)aArg);
  159195. }
  159196. sqlite3_free(zCopy);
  159197. return rc;
  159198. }
  159199. #ifdef SQLITE_TEST
  159200. #if defined(INCLUDE_SQLITE_TCL_H)
  159201. # include "sqlite_tcl.h"
  159202. #else
  159203. # include "tcl.h"
  159204. #endif
  159205. /* #include <string.h> */
  159206. /*
  159207. ** Implementation of a special SQL scalar function for testing tokenizers
  159208. ** designed to be used in concert with the Tcl testing framework. This
  159209. ** function must be called with two or more arguments:
  159210. **
  159211. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  159212. **
  159213. ** where <function-name> is the name passed as the second argument
  159214. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  159215. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  159216. **
  159217. ** The return value is a string that may be interpreted as a Tcl
  159218. ** list. For each token in the <input-string>, three elements are
  159219. ** added to the returned list. The first is the token position, the
  159220. ** second is the token text (folded, stemmed, etc.) and the third is the
  159221. ** substring of <input-string> associated with the token. For example,
  159222. ** using the built-in "simple" tokenizer:
  159223. **
  159224. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  159225. **
  159226. ** will return the string:
  159227. **
  159228. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  159229. **
  159230. */
  159231. static void testFunc(
  159232. sqlite3_context *context,
  159233. int argc,
  159234. sqlite3_value **argv
  159235. ){
  159236. Fts3Hash *pHash;
  159237. sqlite3_tokenizer_module *p;
  159238. sqlite3_tokenizer *pTokenizer = 0;
  159239. sqlite3_tokenizer_cursor *pCsr = 0;
  159240. const char *zErr = 0;
  159241. const char *zName;
  159242. int nName;
  159243. const char *zInput;
  159244. int nInput;
  159245. const char *azArg[64];
  159246. const char *zToken;
  159247. int nToken = 0;
  159248. int iStart = 0;
  159249. int iEnd = 0;
  159250. int iPos = 0;
  159251. int i;
  159252. Tcl_Obj *pRet;
  159253. if( argc<2 ){
  159254. sqlite3_result_error(context, "insufficient arguments", -1);
  159255. return;
  159256. }
  159257. nName = sqlite3_value_bytes(argv[0]);
  159258. zName = (const char *)sqlite3_value_text(argv[0]);
  159259. nInput = sqlite3_value_bytes(argv[argc-1]);
  159260. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  159261. pHash = (Fts3Hash *)sqlite3_user_data(context);
  159262. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  159263. if( !p ){
  159264. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  159265. sqlite3_result_error(context, zErr2, -1);
  159266. sqlite3_free(zErr2);
  159267. return;
  159268. }
  159269. pRet = Tcl_NewObj();
  159270. Tcl_IncrRefCount(pRet);
  159271. for(i=1; i<argc-1; i++){
  159272. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  159273. }
  159274. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  159275. zErr = "error in xCreate()";
  159276. goto finish;
  159277. }
  159278. pTokenizer->pModule = p;
  159279. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  159280. zErr = "error in xOpen()";
  159281. goto finish;
  159282. }
  159283. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  159284. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  159285. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  159286. zToken = &zInput[iStart];
  159287. nToken = iEnd-iStart;
  159288. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  159289. }
  159290. if( SQLITE_OK!=p->xClose(pCsr) ){
  159291. zErr = "error in xClose()";
  159292. goto finish;
  159293. }
  159294. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  159295. zErr = "error in xDestroy()";
  159296. goto finish;
  159297. }
  159298. finish:
  159299. if( zErr ){
  159300. sqlite3_result_error(context, zErr, -1);
  159301. }else{
  159302. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  159303. }
  159304. Tcl_DecrRefCount(pRet);
  159305. }
  159306. static
  159307. int registerTokenizer(
  159308. sqlite3 *db,
  159309. char *zName,
  159310. const sqlite3_tokenizer_module *p
  159311. ){
  159312. int rc;
  159313. sqlite3_stmt *pStmt;
  159314. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  159315. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  159316. if( rc!=SQLITE_OK ){
  159317. return rc;
  159318. }
  159319. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  159320. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  159321. sqlite3_step(pStmt);
  159322. return sqlite3_finalize(pStmt);
  159323. }
  159324. static
  159325. int queryTokenizer(
  159326. sqlite3 *db,
  159327. char *zName,
  159328. const sqlite3_tokenizer_module **pp
  159329. ){
  159330. int rc;
  159331. sqlite3_stmt *pStmt;
  159332. const char zSql[] = "SELECT fts3_tokenizer(?)";
  159333. *pp = 0;
  159334. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  159335. if( rc!=SQLITE_OK ){
  159336. return rc;
  159337. }
  159338. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  159339. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  159340. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  159341. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  159342. }
  159343. }
  159344. return sqlite3_finalize(pStmt);
  159345. }
  159346. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  159347. /*
  159348. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  159349. ** This function is used for testing only, it is not included in the
  159350. ** build unless SQLITE_TEST is defined.
  159351. **
  159352. ** The purpose of this is to test that the fts3_tokenizer() function
  159353. ** can be used as designed by the C-code in the queryTokenizer and
  159354. ** registerTokenizer() functions above. These two functions are repeated
  159355. ** in the README.tokenizer file as an example, so it is important to
  159356. ** test them.
  159357. **
  159358. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  159359. ** function with no arguments. An assert() will fail if a problem is
  159360. ** detected. i.e.:
  159361. **
  159362. ** SELECT fts3_tokenizer_internal_test();
  159363. **
  159364. */
  159365. static void intTestFunc(
  159366. sqlite3_context *context,
  159367. int argc,
  159368. sqlite3_value **argv
  159369. ){
  159370. int rc;
  159371. const sqlite3_tokenizer_module *p1;
  159372. const sqlite3_tokenizer_module *p2;
  159373. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  159374. UNUSED_PARAMETER(argc);
  159375. UNUSED_PARAMETER(argv);
  159376. /* Test the query function */
  159377. sqlite3Fts3SimpleTokenizerModule(&p1);
  159378. rc = queryTokenizer(db, "simple", &p2);
  159379. assert( rc==SQLITE_OK );
  159380. assert( p1==p2 );
  159381. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  159382. assert( rc==SQLITE_ERROR );
  159383. assert( p2==0 );
  159384. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  159385. /* Test the storage function */
  159386. if( fts3TokenizerEnabled(context) ){
  159387. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  159388. assert( rc==SQLITE_OK );
  159389. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  159390. assert( rc==SQLITE_OK );
  159391. assert( p2==p1 );
  159392. }
  159393. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  159394. }
  159395. #endif
  159396. /*
  159397. ** Set up SQL objects in database db used to access the contents of
  159398. ** the hash table pointed to by argument pHash. The hash table must
  159399. ** been initialized to use string keys, and to take a private copy
  159400. ** of the key when a value is inserted. i.e. by a call similar to:
  159401. **
  159402. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  159403. **
  159404. ** This function adds a scalar function (see header comment above
  159405. ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
  159406. ** defined at compilation time, a temporary virtual table (see header
  159407. ** comment above struct HashTableVtab) to the database schema. Both
  159408. ** provide read/write access to the contents of *pHash.
  159409. **
  159410. ** The third argument to this function, zName, is used as the name
  159411. ** of both the scalar and, if created, the virtual table.
  159412. */
  159413. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  159414. sqlite3 *db,
  159415. Fts3Hash *pHash,
  159416. const char *zName
  159417. ){
  159418. int rc = SQLITE_OK;
  159419. void *p = (void *)pHash;
  159420. const int any = SQLITE_ANY;
  159421. #ifdef SQLITE_TEST
  159422. char *zTest = 0;
  159423. char *zTest2 = 0;
  159424. void *pdb = (void *)db;
  159425. zTest = sqlite3_mprintf("%s_test", zName);
  159426. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  159427. if( !zTest || !zTest2 ){
  159428. rc = SQLITE_NOMEM;
  159429. }
  159430. #endif
  159431. if( SQLITE_OK==rc ){
  159432. rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
  159433. }
  159434. if( SQLITE_OK==rc ){
  159435. rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
  159436. }
  159437. #ifdef SQLITE_TEST
  159438. if( SQLITE_OK==rc ){
  159439. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  159440. }
  159441. if( SQLITE_OK==rc ){
  159442. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  159443. }
  159444. #endif
  159445. #ifdef SQLITE_TEST
  159446. sqlite3_free(zTest);
  159447. sqlite3_free(zTest2);
  159448. #endif
  159449. return rc;
  159450. }
  159451. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  159452. /************** End of fts3_tokenizer.c **************************************/
  159453. /************** Begin file fts3_tokenizer1.c *********************************/
  159454. /*
  159455. ** 2006 Oct 10
  159456. **
  159457. ** The author disclaims copyright to this source code. In place of
  159458. ** a legal notice, here is a blessing:
  159459. **
  159460. ** May you do good and not evil.
  159461. ** May you find forgiveness for yourself and forgive others.
  159462. ** May you share freely, never taking more than you give.
  159463. **
  159464. ******************************************************************************
  159465. **
  159466. ** Implementation of the "simple" full-text-search tokenizer.
  159467. */
  159468. /*
  159469. ** The code in this file is only compiled if:
  159470. **
  159471. ** * The FTS3 module is being built as an extension
  159472. ** (in which case SQLITE_CORE is not defined), or
  159473. **
  159474. ** * The FTS3 module is being built into the core of
  159475. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  159476. */
  159477. /* #include "fts3Int.h" */
  159478. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  159479. /* #include <assert.h> */
  159480. /* #include <stdlib.h> */
  159481. /* #include <stdio.h> */
  159482. /* #include <string.h> */
  159483. /* #include "fts3_tokenizer.h" */
  159484. typedef struct simple_tokenizer {
  159485. sqlite3_tokenizer base;
  159486. char delim[128]; /* flag ASCII delimiters */
  159487. } simple_tokenizer;
  159488. typedef struct simple_tokenizer_cursor {
  159489. sqlite3_tokenizer_cursor base;
  159490. const char *pInput; /* input we are tokenizing */
  159491. int nBytes; /* size of the input */
  159492. int iOffset; /* current position in pInput */
  159493. int iToken; /* index of next token to be returned */
  159494. char *pToken; /* storage for current token */
  159495. int nTokenAllocated; /* space allocated to zToken buffer */
  159496. } simple_tokenizer_cursor;
  159497. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  159498. return c<0x80 && t->delim[c];
  159499. }
  159500. static int fts3_isalnum(int x){
  159501. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  159502. }
  159503. /*
  159504. ** Create a new tokenizer instance.
  159505. */
  159506. static int simpleCreate(
  159507. int argc, const char * const *argv,
  159508. sqlite3_tokenizer **ppTokenizer
  159509. ){
  159510. simple_tokenizer *t;
  159511. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  159512. if( t==NULL ) return SQLITE_NOMEM;
  159513. memset(t, 0, sizeof(*t));
  159514. /* TODO(shess) Delimiters need to remain the same from run to run,
  159515. ** else we need to reindex. One solution would be a meta-table to
  159516. ** track such information in the database, then we'd only want this
  159517. ** information on the initial create.
  159518. */
  159519. if( argc>1 ){
  159520. int i, n = (int)strlen(argv[1]);
  159521. for(i=0; i<n; i++){
  159522. unsigned char ch = argv[1][i];
  159523. /* We explicitly don't support UTF-8 delimiters for now. */
  159524. if( ch>=0x80 ){
  159525. sqlite3_free(t);
  159526. return SQLITE_ERROR;
  159527. }
  159528. t->delim[ch] = 1;
  159529. }
  159530. } else {
  159531. /* Mark non-alphanumeric ASCII characters as delimiters */
  159532. int i;
  159533. for(i=1; i<0x80; i++){
  159534. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  159535. }
  159536. }
  159537. *ppTokenizer = &t->base;
  159538. return SQLITE_OK;
  159539. }
  159540. /*
  159541. ** Destroy a tokenizer
  159542. */
  159543. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  159544. sqlite3_free(pTokenizer);
  159545. return SQLITE_OK;
  159546. }
  159547. /*
  159548. ** Prepare to begin tokenizing a particular string. The input
  159549. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  159550. ** used to incrementally tokenize this string is returned in
  159551. ** *ppCursor.
  159552. */
  159553. static int simpleOpen(
  159554. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  159555. const char *pInput, int nBytes, /* String to be tokenized */
  159556. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  159557. ){
  159558. simple_tokenizer_cursor *c;
  159559. UNUSED_PARAMETER(pTokenizer);
  159560. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  159561. if( c==NULL ) return SQLITE_NOMEM;
  159562. c->pInput = pInput;
  159563. if( pInput==0 ){
  159564. c->nBytes = 0;
  159565. }else if( nBytes<0 ){
  159566. c->nBytes = (int)strlen(pInput);
  159567. }else{
  159568. c->nBytes = nBytes;
  159569. }
  159570. c->iOffset = 0; /* start tokenizing at the beginning */
  159571. c->iToken = 0;
  159572. c->pToken = NULL; /* no space allocated, yet. */
  159573. c->nTokenAllocated = 0;
  159574. *ppCursor = &c->base;
  159575. return SQLITE_OK;
  159576. }
  159577. /*
  159578. ** Close a tokenization cursor previously opened by a call to
  159579. ** simpleOpen() above.
  159580. */
  159581. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  159582. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  159583. sqlite3_free(c->pToken);
  159584. sqlite3_free(c);
  159585. return SQLITE_OK;
  159586. }
  159587. /*
  159588. ** Extract the next token from a tokenization cursor. The cursor must
  159589. ** have been opened by a prior call to simpleOpen().
  159590. */
  159591. static int simpleNext(
  159592. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  159593. const char **ppToken, /* OUT: *ppToken is the token text */
  159594. int *pnBytes, /* OUT: Number of bytes in token */
  159595. int *piStartOffset, /* OUT: Starting offset of token */
  159596. int *piEndOffset, /* OUT: Ending offset of token */
  159597. int *piPosition /* OUT: Position integer of token */
  159598. ){
  159599. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  159600. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  159601. unsigned char *p = (unsigned char *)c->pInput;
  159602. while( c->iOffset<c->nBytes ){
  159603. int iStartOffset;
  159604. /* Scan past delimiter characters */
  159605. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  159606. c->iOffset++;
  159607. }
  159608. /* Count non-delimiter characters. */
  159609. iStartOffset = c->iOffset;
  159610. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  159611. c->iOffset++;
  159612. }
  159613. if( c->iOffset>iStartOffset ){
  159614. int i, n = c->iOffset-iStartOffset;
  159615. if( n>c->nTokenAllocated ){
  159616. char *pNew;
  159617. c->nTokenAllocated = n+20;
  159618. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  159619. if( !pNew ) return SQLITE_NOMEM;
  159620. c->pToken = pNew;
  159621. }
  159622. for(i=0; i<n; i++){
  159623. /* TODO(shess) This needs expansion to handle UTF-8
  159624. ** case-insensitivity.
  159625. */
  159626. unsigned char ch = p[iStartOffset+i];
  159627. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  159628. }
  159629. *ppToken = c->pToken;
  159630. *pnBytes = n;
  159631. *piStartOffset = iStartOffset;
  159632. *piEndOffset = c->iOffset;
  159633. *piPosition = c->iToken++;
  159634. return SQLITE_OK;
  159635. }
  159636. }
  159637. return SQLITE_DONE;
  159638. }
  159639. /*
  159640. ** The set of routines that implement the simple tokenizer
  159641. */
  159642. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  159643. 0,
  159644. simpleCreate,
  159645. simpleDestroy,
  159646. simpleOpen,
  159647. simpleClose,
  159648. simpleNext,
  159649. 0,
  159650. };
  159651. /*
  159652. ** Allocate a new simple tokenizer. Return a pointer to the new
  159653. ** tokenizer in *ppModule
  159654. */
  159655. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  159656. sqlite3_tokenizer_module const**ppModule
  159657. ){
  159658. *ppModule = &simpleTokenizerModule;
  159659. }
  159660. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  159661. /************** End of fts3_tokenizer1.c *************************************/
  159662. /************** Begin file fts3_tokenize_vtab.c ******************************/
  159663. /*
  159664. ** 2013 Apr 22
  159665. **
  159666. ** The author disclaims copyright to this source code. In place of
  159667. ** a legal notice, here is a blessing:
  159668. **
  159669. ** May you do good and not evil.
  159670. ** May you find forgiveness for yourself and forgive others.
  159671. ** May you share freely, never taking more than you give.
  159672. **
  159673. ******************************************************************************
  159674. **
  159675. ** This file contains code for the "fts3tokenize" virtual table module.
  159676. ** An fts3tokenize virtual table is created as follows:
  159677. **
  159678. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  159679. ** <tokenizer-name>, <arg-1>, ...
  159680. ** );
  159681. **
  159682. ** The table created has the following schema:
  159683. **
  159684. ** CREATE TABLE <tbl>(input, token, start, end, position)
  159685. **
  159686. ** When queried, the query must include a WHERE clause of type:
  159687. **
  159688. ** input = <string>
  159689. **
  159690. ** The virtual table module tokenizes this <string>, using the FTS3
  159691. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  159692. ** statement and returns one row for each token in the result. With
  159693. ** fields set as follows:
  159694. **
  159695. ** input: Always set to a copy of <string>
  159696. ** token: A token from the input.
  159697. ** start: Byte offset of the token within the input <string>.
  159698. ** end: Byte offset of the byte immediately following the end of the
  159699. ** token within the input string.
  159700. ** pos: Token offset of token within input.
  159701. **
  159702. */
  159703. /* #include "fts3Int.h" */
  159704. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  159705. /* #include <string.h> */
  159706. /* #include <assert.h> */
  159707. typedef struct Fts3tokTable Fts3tokTable;
  159708. typedef struct Fts3tokCursor Fts3tokCursor;
  159709. /*
  159710. ** Virtual table structure.
  159711. */
  159712. struct Fts3tokTable {
  159713. sqlite3_vtab base; /* Base class used by SQLite core */
  159714. const sqlite3_tokenizer_module *pMod;
  159715. sqlite3_tokenizer *pTok;
  159716. };
  159717. /*
  159718. ** Virtual table cursor structure.
  159719. */
  159720. struct Fts3tokCursor {
  159721. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  159722. char *zInput; /* Input string */
  159723. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  159724. int iRowid; /* Current 'rowid' value */
  159725. const char *zToken; /* Current 'token' value */
  159726. int nToken; /* Size of zToken in bytes */
  159727. int iStart; /* Current 'start' value */
  159728. int iEnd; /* Current 'end' value */
  159729. int iPos; /* Current 'pos' value */
  159730. };
  159731. /*
  159732. ** Query FTS for the tokenizer implementation named zName.
  159733. */
  159734. static int fts3tokQueryTokenizer(
  159735. Fts3Hash *pHash,
  159736. const char *zName,
  159737. const sqlite3_tokenizer_module **pp,
  159738. char **pzErr
  159739. ){
  159740. sqlite3_tokenizer_module *p;
  159741. int nName = (int)strlen(zName);
  159742. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  159743. if( !p ){
  159744. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  159745. return SQLITE_ERROR;
  159746. }
  159747. *pp = p;
  159748. return SQLITE_OK;
  159749. }
  159750. /*
  159751. ** The second argument, argv[], is an array of pointers to nul-terminated
  159752. ** strings. This function makes a copy of the array and strings into a
  159753. ** single block of memory. It then dequotes any of the strings that appear
  159754. ** to be quoted.
  159755. **
  159756. ** If successful, output parameter *pazDequote is set to point at the
  159757. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  159758. ** responsible for eventually calling sqlite3_free() to free the array
  159759. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  159760. ** The final value of *pazDequote is undefined in this case.
  159761. */
  159762. static int fts3tokDequoteArray(
  159763. int argc, /* Number of elements in argv[] */
  159764. const char * const *argv, /* Input array */
  159765. char ***pazDequote /* Output array */
  159766. ){
  159767. int rc = SQLITE_OK; /* Return code */
  159768. if( argc==0 ){
  159769. *pazDequote = 0;
  159770. }else{
  159771. int i;
  159772. int nByte = 0;
  159773. char **azDequote;
  159774. for(i=0; i<argc; i++){
  159775. nByte += (int)(strlen(argv[i]) + 1);
  159776. }
  159777. *pazDequote = azDequote = sqlite3_malloc64(sizeof(char *)*argc + nByte);
  159778. if( azDequote==0 ){
  159779. rc = SQLITE_NOMEM;
  159780. }else{
  159781. char *pSpace = (char *)&azDequote[argc];
  159782. for(i=0; i<argc; i++){
  159783. int n = (int)strlen(argv[i]);
  159784. azDequote[i] = pSpace;
  159785. memcpy(pSpace, argv[i], n+1);
  159786. sqlite3Fts3Dequote(pSpace);
  159787. pSpace += (n+1);
  159788. }
  159789. }
  159790. }
  159791. return rc;
  159792. }
  159793. /*
  159794. ** Schema of the tokenizer table.
  159795. */
  159796. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  159797. /*
  159798. ** This function does all the work for both the xConnect and xCreate methods.
  159799. ** These tables have no persistent representation of their own, so xConnect
  159800. ** and xCreate are identical operations.
  159801. **
  159802. ** argv[0]: module name
  159803. ** argv[1]: database name
  159804. ** argv[2]: table name
  159805. ** argv[3]: first argument (tokenizer name)
  159806. */
  159807. static int fts3tokConnectMethod(
  159808. sqlite3 *db, /* Database connection */
  159809. void *pHash, /* Hash table of tokenizers */
  159810. int argc, /* Number of elements in argv array */
  159811. const char * const *argv, /* xCreate/xConnect argument array */
  159812. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  159813. char **pzErr /* OUT: sqlite3_malloc'd error message */
  159814. ){
  159815. Fts3tokTable *pTab = 0;
  159816. const sqlite3_tokenizer_module *pMod = 0;
  159817. sqlite3_tokenizer *pTok = 0;
  159818. int rc;
  159819. char **azDequote = 0;
  159820. int nDequote;
  159821. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  159822. if( rc!=SQLITE_OK ) return rc;
  159823. nDequote = argc-3;
  159824. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  159825. if( rc==SQLITE_OK ){
  159826. const char *zModule;
  159827. if( nDequote<1 ){
  159828. zModule = "simple";
  159829. }else{
  159830. zModule = azDequote[0];
  159831. }
  159832. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  159833. }
  159834. assert( (rc==SQLITE_OK)==(pMod!=0) );
  159835. if( rc==SQLITE_OK ){
  159836. const char * const *azArg = (const char * const *)&azDequote[1];
  159837. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  159838. }
  159839. if( rc==SQLITE_OK ){
  159840. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  159841. if( pTab==0 ){
  159842. rc = SQLITE_NOMEM;
  159843. }
  159844. }
  159845. if( rc==SQLITE_OK ){
  159846. memset(pTab, 0, sizeof(Fts3tokTable));
  159847. pTab->pMod = pMod;
  159848. pTab->pTok = pTok;
  159849. *ppVtab = &pTab->base;
  159850. }else{
  159851. if( pTok ){
  159852. pMod->xDestroy(pTok);
  159853. }
  159854. }
  159855. sqlite3_free(azDequote);
  159856. return rc;
  159857. }
  159858. /*
  159859. ** This function does the work for both the xDisconnect and xDestroy methods.
  159860. ** These tables have no persistent representation of their own, so xDisconnect
  159861. ** and xDestroy are identical operations.
  159862. */
  159863. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  159864. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  159865. pTab->pMod->xDestroy(pTab->pTok);
  159866. sqlite3_free(pTab);
  159867. return SQLITE_OK;
  159868. }
  159869. /*
  159870. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  159871. */
  159872. static int fts3tokBestIndexMethod(
  159873. sqlite3_vtab *pVTab,
  159874. sqlite3_index_info *pInfo
  159875. ){
  159876. int i;
  159877. UNUSED_PARAMETER(pVTab);
  159878. for(i=0; i<pInfo->nConstraint; i++){
  159879. if( pInfo->aConstraint[i].usable
  159880. && pInfo->aConstraint[i].iColumn==0
  159881. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  159882. ){
  159883. pInfo->idxNum = 1;
  159884. pInfo->aConstraintUsage[i].argvIndex = 1;
  159885. pInfo->aConstraintUsage[i].omit = 1;
  159886. pInfo->estimatedCost = 1;
  159887. return SQLITE_OK;
  159888. }
  159889. }
  159890. pInfo->idxNum = 0;
  159891. assert( pInfo->estimatedCost>1000000.0 );
  159892. return SQLITE_OK;
  159893. }
  159894. /*
  159895. ** xOpen - Open a cursor.
  159896. */
  159897. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  159898. Fts3tokCursor *pCsr;
  159899. UNUSED_PARAMETER(pVTab);
  159900. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  159901. if( pCsr==0 ){
  159902. return SQLITE_NOMEM;
  159903. }
  159904. memset(pCsr, 0, sizeof(Fts3tokCursor));
  159905. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  159906. return SQLITE_OK;
  159907. }
  159908. /*
  159909. ** Reset the tokenizer cursor passed as the only argument. As if it had
  159910. ** just been returned by fts3tokOpenMethod().
  159911. */
  159912. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  159913. if( pCsr->pCsr ){
  159914. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  159915. pTab->pMod->xClose(pCsr->pCsr);
  159916. pCsr->pCsr = 0;
  159917. }
  159918. sqlite3_free(pCsr->zInput);
  159919. pCsr->zInput = 0;
  159920. pCsr->zToken = 0;
  159921. pCsr->nToken = 0;
  159922. pCsr->iStart = 0;
  159923. pCsr->iEnd = 0;
  159924. pCsr->iPos = 0;
  159925. pCsr->iRowid = 0;
  159926. }
  159927. /*
  159928. ** xClose - Close a cursor.
  159929. */
  159930. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  159931. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  159932. fts3tokResetCursor(pCsr);
  159933. sqlite3_free(pCsr);
  159934. return SQLITE_OK;
  159935. }
  159936. /*
  159937. ** xNext - Advance the cursor to the next row, if any.
  159938. */
  159939. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  159940. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  159941. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  159942. int rc; /* Return code */
  159943. pCsr->iRowid++;
  159944. rc = pTab->pMod->xNext(pCsr->pCsr,
  159945. &pCsr->zToken, &pCsr->nToken,
  159946. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  159947. );
  159948. if( rc!=SQLITE_OK ){
  159949. fts3tokResetCursor(pCsr);
  159950. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  159951. }
  159952. return rc;
  159953. }
  159954. /*
  159955. ** xFilter - Initialize a cursor to point at the start of its data.
  159956. */
  159957. static int fts3tokFilterMethod(
  159958. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  159959. int idxNum, /* Strategy index */
  159960. const char *idxStr, /* Unused */
  159961. int nVal, /* Number of elements in apVal */
  159962. sqlite3_value **apVal /* Arguments for the indexing scheme */
  159963. ){
  159964. int rc = SQLITE_ERROR;
  159965. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  159966. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  159967. UNUSED_PARAMETER(idxStr);
  159968. UNUSED_PARAMETER(nVal);
  159969. fts3tokResetCursor(pCsr);
  159970. if( idxNum==1 ){
  159971. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  159972. int nByte = sqlite3_value_bytes(apVal[0]);
  159973. pCsr->zInput = sqlite3_malloc64(nByte+1);
  159974. if( pCsr->zInput==0 ){
  159975. rc = SQLITE_NOMEM;
  159976. }else{
  159977. memcpy(pCsr->zInput, zByte, nByte);
  159978. pCsr->zInput[nByte] = 0;
  159979. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  159980. if( rc==SQLITE_OK ){
  159981. pCsr->pCsr->pTokenizer = pTab->pTok;
  159982. }
  159983. }
  159984. }
  159985. if( rc!=SQLITE_OK ) return rc;
  159986. return fts3tokNextMethod(pCursor);
  159987. }
  159988. /*
  159989. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  159990. */
  159991. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  159992. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  159993. return (pCsr->zToken==0);
  159994. }
  159995. /*
  159996. ** xColumn - Return a column value.
  159997. */
  159998. static int fts3tokColumnMethod(
  159999. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  160000. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  160001. int iCol /* Index of column to read value from */
  160002. ){
  160003. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  160004. /* CREATE TABLE x(input, token, start, end, position) */
  160005. switch( iCol ){
  160006. case 0:
  160007. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  160008. break;
  160009. case 1:
  160010. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  160011. break;
  160012. case 2:
  160013. sqlite3_result_int(pCtx, pCsr->iStart);
  160014. break;
  160015. case 3:
  160016. sqlite3_result_int(pCtx, pCsr->iEnd);
  160017. break;
  160018. default:
  160019. assert( iCol==4 );
  160020. sqlite3_result_int(pCtx, pCsr->iPos);
  160021. break;
  160022. }
  160023. return SQLITE_OK;
  160024. }
  160025. /*
  160026. ** xRowid - Return the current rowid for the cursor.
  160027. */
  160028. static int fts3tokRowidMethod(
  160029. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  160030. sqlite_int64 *pRowid /* OUT: Rowid value */
  160031. ){
  160032. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  160033. *pRowid = (sqlite3_int64)pCsr->iRowid;
  160034. return SQLITE_OK;
  160035. }
  160036. /*
  160037. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  160038. ** if successful or an error code if sqlite3_create_module() fails.
  160039. */
  160040. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  160041. static const sqlite3_module fts3tok_module = {
  160042. 0, /* iVersion */
  160043. fts3tokConnectMethod, /* xCreate */
  160044. fts3tokConnectMethod, /* xConnect */
  160045. fts3tokBestIndexMethod, /* xBestIndex */
  160046. fts3tokDisconnectMethod, /* xDisconnect */
  160047. fts3tokDisconnectMethod, /* xDestroy */
  160048. fts3tokOpenMethod, /* xOpen */
  160049. fts3tokCloseMethod, /* xClose */
  160050. fts3tokFilterMethod, /* xFilter */
  160051. fts3tokNextMethod, /* xNext */
  160052. fts3tokEofMethod, /* xEof */
  160053. fts3tokColumnMethod, /* xColumn */
  160054. fts3tokRowidMethod, /* xRowid */
  160055. 0, /* xUpdate */
  160056. 0, /* xBegin */
  160057. 0, /* xSync */
  160058. 0, /* xCommit */
  160059. 0, /* xRollback */
  160060. 0, /* xFindFunction */
  160061. 0, /* xRename */
  160062. 0, /* xSavepoint */
  160063. 0, /* xRelease */
  160064. 0, /* xRollbackTo */
  160065. 0 /* xShadowName */
  160066. };
  160067. int rc; /* Return code */
  160068. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  160069. return rc;
  160070. }
  160071. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  160072. /************** End of fts3_tokenize_vtab.c **********************************/
  160073. /************** Begin file fts3_write.c **************************************/
  160074. /*
  160075. ** 2009 Oct 23
  160076. **
  160077. ** The author disclaims copyright to this source code. In place of
  160078. ** a legal notice, here is a blessing:
  160079. **
  160080. ** May you do good and not evil.
  160081. ** May you find forgiveness for yourself and forgive others.
  160082. ** May you share freely, never taking more than you give.
  160083. **
  160084. ******************************************************************************
  160085. **
  160086. ** This file is part of the SQLite FTS3 extension module. Specifically,
  160087. ** this file contains code to insert, update and delete rows from FTS3
  160088. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  160089. ** of the sub-routines used to merge segments are also used by the query
  160090. ** code in fts3.c.
  160091. */
  160092. /* #include "fts3Int.h" */
  160093. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  160094. /* #include <string.h> */
  160095. /* #include <assert.h> */
  160096. /* #include <stdlib.h> */
  160097. #define FTS_MAX_APPENDABLE_HEIGHT 16
  160098. /*
  160099. ** When full-text index nodes are loaded from disk, the buffer that they
  160100. ** are loaded into has the following number of bytes of padding at the end
  160101. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  160102. ** of 920 bytes is allocated for it.
  160103. **
  160104. ** This means that if we have a pointer into a buffer containing node data,
  160105. ** it is always safe to read up to two varints from it without risking an
  160106. ** overread, even if the node data is corrupted.
  160107. */
  160108. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  160109. /*
  160110. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  160111. ** memory incrementally instead of all at once. This can be a big performance
  160112. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  160113. ** method before retrieving all query results (as may happen, for example,
  160114. ** if a query has a LIMIT clause).
  160115. **
  160116. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  160117. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  160118. ** The code is written so that the hard lower-limit for each of these values
  160119. ** is 1. Clearly such small values would be inefficient, but can be useful
  160120. ** for testing purposes.
  160121. **
  160122. ** If this module is built with SQLITE_TEST defined, these constants may
  160123. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  160124. ** a Tcl interface to read and write the values.
  160125. */
  160126. #ifdef SQLITE_TEST
  160127. int test_fts3_node_chunksize = (4*1024);
  160128. int test_fts3_node_chunk_threshold = (4*1024)*4;
  160129. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  160130. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  160131. #else
  160132. # define FTS3_NODE_CHUNKSIZE (4*1024)
  160133. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  160134. #endif
  160135. /*
  160136. ** The two values that may be meaningfully bound to the :1 parameter in
  160137. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  160138. */
  160139. #define FTS_STAT_DOCTOTAL 0
  160140. #define FTS_STAT_INCRMERGEHINT 1
  160141. #define FTS_STAT_AUTOINCRMERGE 2
  160142. /*
  160143. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  160144. ** and incremental merge operation that takes place. This is used for
  160145. ** debugging FTS only, it should not usually be turned on in production
  160146. ** systems.
  160147. */
  160148. #ifdef FTS3_LOG_MERGES
  160149. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  160150. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  160151. }
  160152. #else
  160153. #define fts3LogMerge(x, y)
  160154. #endif
  160155. typedef struct PendingList PendingList;
  160156. typedef struct SegmentNode SegmentNode;
  160157. typedef struct SegmentWriter SegmentWriter;
  160158. /*
  160159. ** An instance of the following data structure is used to build doclists
  160160. ** incrementally. See function fts3PendingListAppend() for details.
  160161. */
  160162. struct PendingList {
  160163. int nData;
  160164. char *aData;
  160165. int nSpace;
  160166. sqlite3_int64 iLastDocid;
  160167. sqlite3_int64 iLastCol;
  160168. sqlite3_int64 iLastPos;
  160169. };
  160170. /*
  160171. ** Each cursor has a (possibly empty) linked list of the following objects.
  160172. */
  160173. struct Fts3DeferredToken {
  160174. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  160175. int iCol; /* Column token must occur in */
  160176. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  160177. PendingList *pList; /* Doclist is assembled here */
  160178. };
  160179. /*
  160180. ** An instance of this structure is used to iterate through the terms on
  160181. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  160182. ** this structure are only manipulated by code in this file, opaque handles
  160183. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  160184. ** terms when querying the full-text index. See functions:
  160185. **
  160186. ** sqlite3Fts3SegReaderNew()
  160187. ** sqlite3Fts3SegReaderFree()
  160188. ** sqlite3Fts3SegReaderIterate()
  160189. **
  160190. ** Methods used to manipulate Fts3SegReader structures:
  160191. **
  160192. ** fts3SegReaderNext()
  160193. ** fts3SegReaderFirstDocid()
  160194. ** fts3SegReaderNextDocid()
  160195. */
  160196. struct Fts3SegReader {
  160197. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  160198. u8 bLookup; /* True for a lookup only */
  160199. u8 rootOnly; /* True for a root-only reader */
  160200. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  160201. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  160202. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  160203. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  160204. char *aNode; /* Pointer to node data (or NULL) */
  160205. int nNode; /* Size of buffer at aNode (or 0) */
  160206. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  160207. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  160208. Fts3HashElem **ppNextElem;
  160209. /* Variables set by fts3SegReaderNext(). These may be read directly
  160210. ** by the caller. They are valid from the time SegmentReaderNew() returns
  160211. ** until SegmentReaderNext() returns something other than SQLITE_OK
  160212. ** (i.e. SQLITE_DONE).
  160213. */
  160214. int nTerm; /* Number of bytes in current term */
  160215. char *zTerm; /* Pointer to current term */
  160216. int nTermAlloc; /* Allocated size of zTerm buffer */
  160217. char *aDoclist; /* Pointer to doclist of current entry */
  160218. int nDoclist; /* Size of doclist in current entry */
  160219. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  160220. ** through the current doclist (aDoclist/nDoclist).
  160221. */
  160222. char *pOffsetList;
  160223. int nOffsetList; /* For descending pending seg-readers only */
  160224. sqlite3_int64 iDocid;
  160225. };
  160226. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  160227. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  160228. /*
  160229. ** An instance of this structure is used to create a segment b-tree in the
  160230. ** database. The internal details of this type are only accessed by the
  160231. ** following functions:
  160232. **
  160233. ** fts3SegWriterAdd()
  160234. ** fts3SegWriterFlush()
  160235. ** fts3SegWriterFree()
  160236. */
  160237. struct SegmentWriter {
  160238. SegmentNode *pTree; /* Pointer to interior tree structure */
  160239. sqlite3_int64 iFirst; /* First slot in %_segments written */
  160240. sqlite3_int64 iFree; /* Next free slot in %_segments */
  160241. char *zTerm; /* Pointer to previous term buffer */
  160242. int nTerm; /* Number of bytes in zTerm */
  160243. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  160244. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  160245. int nSize; /* Size of allocation at aData */
  160246. int nData; /* Bytes of data in aData */
  160247. char *aData; /* Pointer to block from malloc() */
  160248. i64 nLeafData; /* Number of bytes of leaf data written */
  160249. };
  160250. /*
  160251. ** Type SegmentNode is used by the following three functions to create
  160252. ** the interior part of the segment b+-tree structures (everything except
  160253. ** the leaf nodes). These functions and type are only ever used by code
  160254. ** within the fts3SegWriterXXX() family of functions described above.
  160255. **
  160256. ** fts3NodeAddTerm()
  160257. ** fts3NodeWrite()
  160258. ** fts3NodeFree()
  160259. **
  160260. ** When a b+tree is written to the database (either as a result of a merge
  160261. ** or the pending-terms table being flushed), leaves are written into the
  160262. ** database file as soon as they are completely populated. The interior of
  160263. ** the tree is assembled in memory and written out only once all leaves have
  160264. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  160265. ** very large, meaning that the interior of the tree consumes relatively
  160266. ** little memory.
  160267. */
  160268. struct SegmentNode {
  160269. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  160270. SegmentNode *pRight; /* Pointer to right-sibling */
  160271. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  160272. int nEntry; /* Number of terms written to node so far */
  160273. char *zTerm; /* Pointer to previous term buffer */
  160274. int nTerm; /* Number of bytes in zTerm */
  160275. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  160276. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  160277. int nData; /* Bytes of valid data so far */
  160278. char *aData; /* Node data */
  160279. };
  160280. /*
  160281. ** Valid values for the second argument to fts3SqlStmt().
  160282. */
  160283. #define SQL_DELETE_CONTENT 0
  160284. #define SQL_IS_EMPTY 1
  160285. #define SQL_DELETE_ALL_CONTENT 2
  160286. #define SQL_DELETE_ALL_SEGMENTS 3
  160287. #define SQL_DELETE_ALL_SEGDIR 4
  160288. #define SQL_DELETE_ALL_DOCSIZE 5
  160289. #define SQL_DELETE_ALL_STAT 6
  160290. #define SQL_SELECT_CONTENT_BY_ROWID 7
  160291. #define SQL_NEXT_SEGMENT_INDEX 8
  160292. #define SQL_INSERT_SEGMENTS 9
  160293. #define SQL_NEXT_SEGMENTS_ID 10
  160294. #define SQL_INSERT_SEGDIR 11
  160295. #define SQL_SELECT_LEVEL 12
  160296. #define SQL_SELECT_LEVEL_RANGE 13
  160297. #define SQL_SELECT_LEVEL_COUNT 14
  160298. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  160299. #define SQL_DELETE_SEGDIR_LEVEL 16
  160300. #define SQL_DELETE_SEGMENTS_RANGE 17
  160301. #define SQL_CONTENT_INSERT 18
  160302. #define SQL_DELETE_DOCSIZE 19
  160303. #define SQL_REPLACE_DOCSIZE 20
  160304. #define SQL_SELECT_DOCSIZE 21
  160305. #define SQL_SELECT_STAT 22
  160306. #define SQL_REPLACE_STAT 23
  160307. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  160308. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  160309. #define SQL_DELETE_SEGDIR_RANGE 26
  160310. #define SQL_SELECT_ALL_LANGID 27
  160311. #define SQL_FIND_MERGE_LEVEL 28
  160312. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  160313. #define SQL_DELETE_SEGDIR_ENTRY 30
  160314. #define SQL_SHIFT_SEGDIR_ENTRY 31
  160315. #define SQL_SELECT_SEGDIR 32
  160316. #define SQL_CHOMP_SEGDIR 33
  160317. #define SQL_SEGMENT_IS_APPENDABLE 34
  160318. #define SQL_SELECT_INDEXES 35
  160319. #define SQL_SELECT_MXLEVEL 36
  160320. #define SQL_SELECT_LEVEL_RANGE2 37
  160321. #define SQL_UPDATE_LEVEL_IDX 38
  160322. #define SQL_UPDATE_LEVEL 39
  160323. /*
  160324. ** This function is used to obtain an SQLite prepared statement handle
  160325. ** for the statement identified by the second argument. If successful,
  160326. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  160327. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  160328. **
  160329. ** If argument apVal is not NULL, then it must point to an array with
  160330. ** at least as many entries as the requested statement has bound
  160331. ** parameters. The values are bound to the statements parameters before
  160332. ** returning.
  160333. */
  160334. static int fts3SqlStmt(
  160335. Fts3Table *p, /* Virtual table handle */
  160336. int eStmt, /* One of the SQL_XXX constants above */
  160337. sqlite3_stmt **pp, /* OUT: Statement handle */
  160338. sqlite3_value **apVal /* Values to bind to statement */
  160339. ){
  160340. const char *azSql[] = {
  160341. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  160342. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  160343. /* 2 */ "DELETE FROM %Q.'%q_content'",
  160344. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  160345. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  160346. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  160347. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  160348. /* 7 */ "SELECT %s WHERE rowid=?",
  160349. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  160350. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  160351. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  160352. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  160353. /* Return segments in order from oldest to newest.*/
  160354. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  160355. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  160356. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  160357. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  160358. "ORDER BY level DESC, idx ASC",
  160359. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  160360. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  160361. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  160362. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  160363. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  160364. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  160365. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  160366. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  160367. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  160368. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  160369. /* 24 */ "",
  160370. /* 25 */ "",
  160371. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  160372. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  160373. /* This statement is used to determine which level to read the input from
  160374. ** when performing an incremental merge. It returns the absolute level number
  160375. ** of the oldest level in the db that contains at least ? segments. Or,
  160376. ** if no level in the FTS index contains more than ? segments, the statement
  160377. ** returns zero rows. */
  160378. /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
  160379. " GROUP BY level HAVING cnt>=?"
  160380. " ORDER BY (level %% 1024) ASC LIMIT 1",
  160381. /* Estimate the upper limit on the number of leaf nodes in a new segment
  160382. ** created by merging the oldest :2 segments from absolute level :1. See
  160383. ** function sqlite3Fts3Incrmerge() for details. */
  160384. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  160385. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  160386. /* SQL_DELETE_SEGDIR_ENTRY
  160387. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  160388. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  160389. /* SQL_SHIFT_SEGDIR_ENTRY
  160390. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  160391. ** to :1. */
  160392. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  160393. /* SQL_SELECT_SEGDIR
  160394. ** Read a single entry from the %_segdir table. The entry from absolute
  160395. ** level :1 with index value :2. */
  160396. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  160397. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  160398. /* SQL_CHOMP_SEGDIR
  160399. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  160400. ** entry located on absolute level :3 with index :4. */
  160401. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  160402. "WHERE level = ? AND idx = ?",
  160403. /* SQL_SEGMENT_IS_APPENDABLE
  160404. ** Return a single row if the segment with end_block=? is appendable. Or
  160405. ** no rows otherwise. */
  160406. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  160407. /* SQL_SELECT_INDEXES
  160408. ** Return the list of valid segment indexes for absolute level ? */
  160409. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  160410. /* SQL_SELECT_MXLEVEL
  160411. ** Return the largest relative level in the FTS index or indexes. */
  160412. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  160413. /* Return segments in order from oldest to newest.*/
  160414. /* 37 */ "SELECT level, idx, end_block "
  160415. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  160416. "ORDER BY level DESC, idx ASC",
  160417. /* Update statements used while promoting segments */
  160418. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  160419. "WHERE level=? AND idx=?",
  160420. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  160421. };
  160422. int rc = SQLITE_OK;
  160423. sqlite3_stmt *pStmt;
  160424. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  160425. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  160426. pStmt = p->aStmt[eStmt];
  160427. if( !pStmt ){
  160428. int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
  160429. char *zSql;
  160430. if( eStmt==SQL_CONTENT_INSERT ){
  160431. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  160432. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  160433. f &= ~SQLITE_PREPARE_NO_VTAB;
  160434. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  160435. }else{
  160436. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  160437. }
  160438. if( !zSql ){
  160439. rc = SQLITE_NOMEM;
  160440. }else{
  160441. rc = sqlite3_prepare_v3(p->db, zSql, -1, f, &pStmt, NULL);
  160442. sqlite3_free(zSql);
  160443. assert( rc==SQLITE_OK || pStmt==0 );
  160444. p->aStmt[eStmt] = pStmt;
  160445. }
  160446. }
  160447. if( apVal ){
  160448. int i;
  160449. int nParam = sqlite3_bind_parameter_count(pStmt);
  160450. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  160451. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  160452. }
  160453. }
  160454. *pp = pStmt;
  160455. return rc;
  160456. }
  160457. static int fts3SelectDocsize(
  160458. Fts3Table *pTab, /* FTS3 table handle */
  160459. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  160460. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  160461. ){
  160462. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  160463. int rc; /* Return code */
  160464. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  160465. if( rc==SQLITE_OK ){
  160466. sqlite3_bind_int64(pStmt, 1, iDocid);
  160467. rc = sqlite3_step(pStmt);
  160468. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  160469. rc = sqlite3_reset(pStmt);
  160470. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  160471. pStmt = 0;
  160472. }else{
  160473. rc = SQLITE_OK;
  160474. }
  160475. }
  160476. *ppStmt = pStmt;
  160477. return rc;
  160478. }
  160479. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  160480. Fts3Table *pTab, /* Fts3 table handle */
  160481. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  160482. ){
  160483. sqlite3_stmt *pStmt = 0;
  160484. int rc;
  160485. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  160486. if( rc==SQLITE_OK ){
  160487. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  160488. if( sqlite3_step(pStmt)!=SQLITE_ROW
  160489. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  160490. ){
  160491. rc = sqlite3_reset(pStmt);
  160492. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  160493. pStmt = 0;
  160494. }
  160495. }
  160496. *ppStmt = pStmt;
  160497. return rc;
  160498. }
  160499. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  160500. Fts3Table *pTab, /* Fts3 table handle */
  160501. sqlite3_int64 iDocid, /* Docid to read size data for */
  160502. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  160503. ){
  160504. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  160505. }
  160506. /*
  160507. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  160508. ** array apVal[] to the SQL statement identified by eStmt, the statement
  160509. ** is executed.
  160510. **
  160511. ** Returns SQLITE_OK if the statement is successfully executed, or an
  160512. ** SQLite error code otherwise.
  160513. */
  160514. static void fts3SqlExec(
  160515. int *pRC, /* Result code */
  160516. Fts3Table *p, /* The FTS3 table */
  160517. int eStmt, /* Index of statement to evaluate */
  160518. sqlite3_value **apVal /* Parameters to bind */
  160519. ){
  160520. sqlite3_stmt *pStmt;
  160521. int rc;
  160522. if( *pRC ) return;
  160523. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  160524. if( rc==SQLITE_OK ){
  160525. sqlite3_step(pStmt);
  160526. rc = sqlite3_reset(pStmt);
  160527. }
  160528. *pRC = rc;
  160529. }
  160530. /*
  160531. ** This function ensures that the caller has obtained an exclusive
  160532. ** shared-cache table-lock on the %_segdir table. This is required before
  160533. ** writing data to the fts3 table. If this lock is not acquired first, then
  160534. ** the caller may end up attempting to take this lock as part of committing
  160535. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  160536. ** LOCKED_SHAREDCACHEto a COMMIT command.
  160537. **
  160538. ** It is best to avoid this because if FTS3 returns any error when
  160539. ** committing a transaction, the whole transaction will be rolled back.
  160540. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  160541. ** It can still happen if the user locks the underlying tables directly
  160542. ** instead of accessing them via FTS.
  160543. */
  160544. static int fts3Writelock(Fts3Table *p){
  160545. int rc = SQLITE_OK;
  160546. if( p->nPendingData==0 ){
  160547. sqlite3_stmt *pStmt;
  160548. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  160549. if( rc==SQLITE_OK ){
  160550. sqlite3_bind_null(pStmt, 1);
  160551. sqlite3_step(pStmt);
  160552. rc = sqlite3_reset(pStmt);
  160553. }
  160554. }
  160555. return rc;
  160556. }
  160557. /*
  160558. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  160559. ** Within each language id, a separate index is maintained to store the
  160560. ** document terms, and each configured prefix size (configured the FTS
  160561. ** "prefix=" option). And each index consists of multiple levels ("relative
  160562. ** levels").
  160563. **
  160564. ** All three of these values (the language id, the specific index and the
  160565. ** level within the index) are encoded in 64-bit integer values stored
  160566. ** in the %_segdir table on disk. This function is used to convert three
  160567. ** separate component values into the single 64-bit integer value that
  160568. ** can be used to query the %_segdir table.
  160569. **
  160570. ** Specifically, each language-id/index combination is allocated 1024
  160571. ** 64-bit integer level values ("absolute levels"). The main terms index
  160572. ** for language-id 0 is allocate values 0-1023. The first prefix index
  160573. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  160574. ** Language 1 indexes are allocated immediately following language 0.
  160575. **
  160576. ** So, for a system with nPrefix prefix indexes configured, the block of
  160577. ** absolute levels that corresponds to language-id iLangid and index
  160578. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  160579. */
  160580. static sqlite3_int64 getAbsoluteLevel(
  160581. Fts3Table *p, /* FTS3 table handle */
  160582. int iLangid, /* Language id */
  160583. int iIndex, /* Index in p->aIndex[] */
  160584. int iLevel /* Level of segments */
  160585. ){
  160586. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  160587. assert_fts3_nc( iLangid>=0 );
  160588. assert( p->nIndex>0 );
  160589. assert( iIndex>=0 && iIndex<p->nIndex );
  160590. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  160591. return iBase + iLevel;
  160592. }
  160593. /*
  160594. ** Set *ppStmt to a statement handle that may be used to iterate through
  160595. ** all rows in the %_segdir table, from oldest to newest. If successful,
  160596. ** return SQLITE_OK. If an error occurs while preparing the statement,
  160597. ** return an SQLite error code.
  160598. **
  160599. ** There is only ever one instance of this SQL statement compiled for
  160600. ** each FTS3 table.
  160601. **
  160602. ** The statement returns the following columns from the %_segdir table:
  160603. **
  160604. ** 0: idx
  160605. ** 1: start_block
  160606. ** 2: leaves_end_block
  160607. ** 3: end_block
  160608. ** 4: root
  160609. */
  160610. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  160611. Fts3Table *p, /* FTS3 table */
  160612. int iLangid, /* Language being queried */
  160613. int iIndex, /* Index for p->aIndex[] */
  160614. int iLevel, /* Level to select (relative level) */
  160615. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  160616. ){
  160617. int rc;
  160618. sqlite3_stmt *pStmt = 0;
  160619. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  160620. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  160621. assert( iIndex>=0 && iIndex<p->nIndex );
  160622. if( iLevel<0 ){
  160623. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  160624. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  160625. if( rc==SQLITE_OK ){
  160626. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  160627. sqlite3_bind_int64(pStmt, 2,
  160628. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  160629. );
  160630. }
  160631. }else{
  160632. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  160633. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  160634. if( rc==SQLITE_OK ){
  160635. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  160636. }
  160637. }
  160638. *ppStmt = pStmt;
  160639. return rc;
  160640. }
  160641. /*
  160642. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  160643. ** if successful, or an SQLite error code otherwise.
  160644. **
  160645. ** This function also serves to allocate the PendingList structure itself.
  160646. ** For example, to create a new PendingList structure containing two
  160647. ** varints:
  160648. **
  160649. ** PendingList *p = 0;
  160650. ** fts3PendingListAppendVarint(&p, 1);
  160651. ** fts3PendingListAppendVarint(&p, 2);
  160652. */
  160653. static int fts3PendingListAppendVarint(
  160654. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  160655. sqlite3_int64 i /* Value to append to data */
  160656. ){
  160657. PendingList *p = *pp;
  160658. /* Allocate or grow the PendingList as required. */
  160659. if( !p ){
  160660. p = sqlite3_malloc(sizeof(*p) + 100);
  160661. if( !p ){
  160662. return SQLITE_NOMEM;
  160663. }
  160664. p->nSpace = 100;
  160665. p->aData = (char *)&p[1];
  160666. p->nData = 0;
  160667. }
  160668. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  160669. int nNew = p->nSpace * 2;
  160670. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  160671. if( !p ){
  160672. sqlite3_free(*pp);
  160673. *pp = 0;
  160674. return SQLITE_NOMEM;
  160675. }
  160676. p->nSpace = nNew;
  160677. p->aData = (char *)&p[1];
  160678. }
  160679. /* Append the new serialized varint to the end of the list. */
  160680. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  160681. p->aData[p->nData] = '\0';
  160682. *pp = p;
  160683. return SQLITE_OK;
  160684. }
  160685. /*
  160686. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  160687. ** is returned if the structure is sqlite3_realloced as part of adding
  160688. ** the entry. Otherwise, zero.
  160689. **
  160690. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  160691. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  160692. ** it is set to SQLITE_OK.
  160693. */
  160694. static int fts3PendingListAppend(
  160695. PendingList **pp, /* IN/OUT: PendingList structure */
  160696. sqlite3_int64 iDocid, /* Docid for entry to add */
  160697. sqlite3_int64 iCol, /* Column for entry to add */
  160698. sqlite3_int64 iPos, /* Position of term for entry to add */
  160699. int *pRc /* OUT: Return code */
  160700. ){
  160701. PendingList *p = *pp;
  160702. int rc = SQLITE_OK;
  160703. assert( !p || p->iLastDocid<=iDocid );
  160704. if( !p || p->iLastDocid!=iDocid ){
  160705. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  160706. if( p ){
  160707. assert( p->nData<p->nSpace );
  160708. assert( p->aData[p->nData]==0 );
  160709. p->nData++;
  160710. }
  160711. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  160712. goto pendinglistappend_out;
  160713. }
  160714. p->iLastCol = -1;
  160715. p->iLastPos = 0;
  160716. p->iLastDocid = iDocid;
  160717. }
  160718. if( iCol>0 && p->iLastCol!=iCol ){
  160719. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  160720. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  160721. ){
  160722. goto pendinglistappend_out;
  160723. }
  160724. p->iLastCol = iCol;
  160725. p->iLastPos = 0;
  160726. }
  160727. if( iCol>=0 ){
  160728. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  160729. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  160730. if( rc==SQLITE_OK ){
  160731. p->iLastPos = iPos;
  160732. }
  160733. }
  160734. pendinglistappend_out:
  160735. *pRc = rc;
  160736. if( p!=*pp ){
  160737. *pp = p;
  160738. return 1;
  160739. }
  160740. return 0;
  160741. }
  160742. /*
  160743. ** Free a PendingList object allocated by fts3PendingListAppend().
  160744. */
  160745. static void fts3PendingListDelete(PendingList *pList){
  160746. sqlite3_free(pList);
  160747. }
  160748. /*
  160749. ** Add an entry to one of the pending-terms hash tables.
  160750. */
  160751. static int fts3PendingTermsAddOne(
  160752. Fts3Table *p,
  160753. int iCol,
  160754. int iPos,
  160755. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  160756. const char *zToken,
  160757. int nToken
  160758. ){
  160759. PendingList *pList;
  160760. int rc = SQLITE_OK;
  160761. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  160762. if( pList ){
  160763. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  160764. }
  160765. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  160766. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  160767. /* Malloc failed while inserting the new entry. This can only
  160768. ** happen if there was no previous entry for this token.
  160769. */
  160770. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  160771. sqlite3_free(pList);
  160772. rc = SQLITE_NOMEM;
  160773. }
  160774. }
  160775. if( rc==SQLITE_OK ){
  160776. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  160777. }
  160778. return rc;
  160779. }
  160780. /*
  160781. ** Tokenize the nul-terminated string zText and add all tokens to the
  160782. ** pending-terms hash-table. The docid used is that currently stored in
  160783. ** p->iPrevDocid, and the column is specified by argument iCol.
  160784. **
  160785. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  160786. */
  160787. static int fts3PendingTermsAdd(
  160788. Fts3Table *p, /* Table into which text will be inserted */
  160789. int iLangid, /* Language id to use */
  160790. const char *zText, /* Text of document to be inserted */
  160791. int iCol, /* Column into which text is being inserted */
  160792. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  160793. ){
  160794. int rc;
  160795. int iStart = 0;
  160796. int iEnd = 0;
  160797. int iPos = 0;
  160798. int nWord = 0;
  160799. char const *zToken;
  160800. int nToken = 0;
  160801. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  160802. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  160803. sqlite3_tokenizer_cursor *pCsr;
  160804. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  160805. const char**,int*,int*,int*,int*);
  160806. assert( pTokenizer && pModule );
  160807. /* If the user has inserted a NULL value, this function may be called with
  160808. ** zText==0. In this case, add zero token entries to the hash table and
  160809. ** return early. */
  160810. if( zText==0 ){
  160811. *pnWord = 0;
  160812. return SQLITE_OK;
  160813. }
  160814. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  160815. if( rc!=SQLITE_OK ){
  160816. return rc;
  160817. }
  160818. xNext = pModule->xNext;
  160819. while( SQLITE_OK==rc
  160820. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  160821. ){
  160822. int i;
  160823. if( iPos>=nWord ) nWord = iPos+1;
  160824. /* Positions cannot be negative; we use -1 as a terminator internally.
  160825. ** Tokens must have a non-zero length.
  160826. */
  160827. if( iPos<0 || !zToken || nToken<=0 ){
  160828. rc = SQLITE_ERROR;
  160829. break;
  160830. }
  160831. /* Add the term to the terms index */
  160832. rc = fts3PendingTermsAddOne(
  160833. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  160834. );
  160835. /* Add the term to each of the prefix indexes that it is not too
  160836. ** short for. */
  160837. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  160838. struct Fts3Index *pIndex = &p->aIndex[i];
  160839. if( nToken<pIndex->nPrefix ) continue;
  160840. rc = fts3PendingTermsAddOne(
  160841. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  160842. );
  160843. }
  160844. }
  160845. pModule->xClose(pCsr);
  160846. *pnWord += nWord;
  160847. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  160848. }
  160849. /*
  160850. ** Calling this function indicates that subsequent calls to
  160851. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  160852. ** contents of the document with docid iDocid.
  160853. */
  160854. static int fts3PendingTermsDocid(
  160855. Fts3Table *p, /* Full-text table handle */
  160856. int bDelete, /* True if this op is a delete */
  160857. int iLangid, /* Language id of row being written */
  160858. sqlite_int64 iDocid /* Docid of row being written */
  160859. ){
  160860. assert( iLangid>=0 );
  160861. assert( bDelete==1 || bDelete==0 );
  160862. /* TODO(shess) Explore whether partially flushing the buffer on
  160863. ** forced-flush would provide better performance. I suspect that if
  160864. ** we ordered the doclists by size and flushed the largest until the
  160865. ** buffer was half empty, that would let the less frequent terms
  160866. ** generate longer doclists.
  160867. */
  160868. if( iDocid<p->iPrevDocid
  160869. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  160870. || p->iPrevLangid!=iLangid
  160871. || p->nPendingData>p->nMaxPendingData
  160872. ){
  160873. int rc = sqlite3Fts3PendingTermsFlush(p);
  160874. if( rc!=SQLITE_OK ) return rc;
  160875. }
  160876. p->iPrevDocid = iDocid;
  160877. p->iPrevLangid = iLangid;
  160878. p->bPrevDelete = bDelete;
  160879. return SQLITE_OK;
  160880. }
  160881. /*
  160882. ** Discard the contents of the pending-terms hash tables.
  160883. */
  160884. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  160885. int i;
  160886. for(i=0; i<p->nIndex; i++){
  160887. Fts3HashElem *pElem;
  160888. Fts3Hash *pHash = &p->aIndex[i].hPending;
  160889. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  160890. PendingList *pList = (PendingList *)fts3HashData(pElem);
  160891. fts3PendingListDelete(pList);
  160892. }
  160893. fts3HashClear(pHash);
  160894. }
  160895. p->nPendingData = 0;
  160896. }
  160897. /*
  160898. ** This function is called by the xUpdate() method as part of an INSERT
  160899. ** operation. It adds entries for each term in the new record to the
  160900. ** pendingTerms hash table.
  160901. **
  160902. ** Argument apVal is the same as the similarly named argument passed to
  160903. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  160904. */
  160905. static int fts3InsertTerms(
  160906. Fts3Table *p,
  160907. int iLangid,
  160908. sqlite3_value **apVal,
  160909. u32 *aSz
  160910. ){
  160911. int i; /* Iterator variable */
  160912. for(i=2; i<p->nColumn+2; i++){
  160913. int iCol = i-2;
  160914. if( p->abNotindexed[iCol]==0 ){
  160915. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  160916. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  160917. if( rc!=SQLITE_OK ){
  160918. return rc;
  160919. }
  160920. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  160921. }
  160922. }
  160923. return SQLITE_OK;
  160924. }
  160925. /*
  160926. ** This function is called by the xUpdate() method for an INSERT operation.
  160927. ** The apVal parameter is passed a copy of the apVal argument passed by
  160928. ** SQLite to the xUpdate() method. i.e:
  160929. **
  160930. ** apVal[0] Not used for INSERT.
  160931. ** apVal[1] rowid
  160932. ** apVal[2] Left-most user-defined column
  160933. ** ...
  160934. ** apVal[p->nColumn+1] Right-most user-defined column
  160935. ** apVal[p->nColumn+2] Hidden column with same name as table
  160936. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  160937. ** apVal[p->nColumn+4] Hidden languageid column
  160938. */
  160939. static int fts3InsertData(
  160940. Fts3Table *p, /* Full-text table */
  160941. sqlite3_value **apVal, /* Array of values to insert */
  160942. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  160943. ){
  160944. int rc; /* Return code */
  160945. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  160946. if( p->zContentTbl ){
  160947. sqlite3_value *pRowid = apVal[p->nColumn+3];
  160948. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  160949. pRowid = apVal[1];
  160950. }
  160951. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  160952. return SQLITE_CONSTRAINT;
  160953. }
  160954. *piDocid = sqlite3_value_int64(pRowid);
  160955. return SQLITE_OK;
  160956. }
  160957. /* Locate the statement handle used to insert data into the %_content
  160958. ** table. The SQL for this statement is:
  160959. **
  160960. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  160961. **
  160962. ** The statement features N '?' variables, where N is the number of user
  160963. ** defined columns in the FTS3 table, plus one for the docid field.
  160964. */
  160965. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  160966. if( rc==SQLITE_OK && p->zLanguageid ){
  160967. rc = sqlite3_bind_int(
  160968. pContentInsert, p->nColumn+2,
  160969. sqlite3_value_int(apVal[p->nColumn+4])
  160970. );
  160971. }
  160972. if( rc!=SQLITE_OK ) return rc;
  160973. /* There is a quirk here. The users INSERT statement may have specified
  160974. ** a value for the "rowid" field, for the "docid" field, or for both.
  160975. ** Which is a problem, since "rowid" and "docid" are aliases for the
  160976. ** same value. For example:
  160977. **
  160978. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  160979. **
  160980. ** In FTS3, this is an error. It is an error to specify non-NULL values
  160981. ** for both docid and some other rowid alias.
  160982. */
  160983. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  160984. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  160985. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  160986. ){
  160987. /* A rowid/docid conflict. */
  160988. return SQLITE_ERROR;
  160989. }
  160990. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  160991. if( rc!=SQLITE_OK ) return rc;
  160992. }
  160993. /* Execute the statement to insert the record. Set *piDocid to the
  160994. ** new docid value.
  160995. */
  160996. sqlite3_step(pContentInsert);
  160997. rc = sqlite3_reset(pContentInsert);
  160998. *piDocid = sqlite3_last_insert_rowid(p->db);
  160999. return rc;
  161000. }
  161001. /*
  161002. ** Remove all data from the FTS3 table. Clear the hash table containing
  161003. ** pending terms.
  161004. */
  161005. static int fts3DeleteAll(Fts3Table *p, int bContent){
  161006. int rc = SQLITE_OK; /* Return code */
  161007. /* Discard the contents of the pending-terms hash table. */
  161008. sqlite3Fts3PendingTermsClear(p);
  161009. /* Delete everything from the shadow tables. Except, leave %_content as
  161010. ** is if bContent is false. */
  161011. assert( p->zContentTbl==0 || bContent==0 );
  161012. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  161013. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  161014. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  161015. if( p->bHasDocsize ){
  161016. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  161017. }
  161018. if( p->bHasStat ){
  161019. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  161020. }
  161021. return rc;
  161022. }
  161023. /*
  161024. **
  161025. */
  161026. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  161027. int iLangid = 0;
  161028. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  161029. return iLangid;
  161030. }
  161031. /*
  161032. ** The first element in the apVal[] array is assumed to contain the docid
  161033. ** (an integer) of a row about to be deleted. Remove all terms from the
  161034. ** full-text index.
  161035. */
  161036. static void fts3DeleteTerms(
  161037. int *pRC, /* Result code */
  161038. Fts3Table *p, /* The FTS table to delete from */
  161039. sqlite3_value *pRowid, /* The docid to be deleted */
  161040. u32 *aSz, /* Sizes of deleted document written here */
  161041. int *pbFound /* OUT: Set to true if row really does exist */
  161042. ){
  161043. int rc;
  161044. sqlite3_stmt *pSelect;
  161045. assert( *pbFound==0 );
  161046. if( *pRC ) return;
  161047. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  161048. if( rc==SQLITE_OK ){
  161049. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  161050. int i;
  161051. int iLangid = langidFromSelect(p, pSelect);
  161052. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  161053. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  161054. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  161055. int iCol = i-1;
  161056. if( p->abNotindexed[iCol]==0 ){
  161057. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  161058. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  161059. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  161060. }
  161061. }
  161062. if( rc!=SQLITE_OK ){
  161063. sqlite3_reset(pSelect);
  161064. *pRC = rc;
  161065. return;
  161066. }
  161067. *pbFound = 1;
  161068. }
  161069. rc = sqlite3_reset(pSelect);
  161070. }else{
  161071. sqlite3_reset(pSelect);
  161072. }
  161073. *pRC = rc;
  161074. }
  161075. /*
  161076. ** Forward declaration to account for the circular dependency between
  161077. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  161078. */
  161079. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  161080. /*
  161081. ** This function allocates a new level iLevel index in the segdir table.
  161082. ** Usually, indexes are allocated within a level sequentially starting
  161083. ** with 0, so the allocated index is one greater than the value returned
  161084. ** by:
  161085. **
  161086. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  161087. **
  161088. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  161089. ** level, they are merged into a single level (iLevel+1) segment and the
  161090. ** allocated index is 0.
  161091. **
  161092. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  161093. ** returned. Otherwise, an SQLite error code is returned.
  161094. */
  161095. static int fts3AllocateSegdirIdx(
  161096. Fts3Table *p,
  161097. int iLangid, /* Language id */
  161098. int iIndex, /* Index for p->aIndex */
  161099. int iLevel,
  161100. int *piIdx
  161101. ){
  161102. int rc; /* Return Code */
  161103. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  161104. int iNext = 0; /* Result of query pNextIdx */
  161105. assert( iLangid>=0 );
  161106. assert( p->nIndex>=1 );
  161107. /* Set variable iNext to the next available segdir index at level iLevel. */
  161108. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  161109. if( rc==SQLITE_OK ){
  161110. sqlite3_bind_int64(
  161111. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  161112. );
  161113. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  161114. iNext = sqlite3_column_int(pNextIdx, 0);
  161115. }
  161116. rc = sqlite3_reset(pNextIdx);
  161117. }
  161118. if( rc==SQLITE_OK ){
  161119. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  161120. ** full, merge all segments in level iLevel into a single iLevel+1
  161121. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  161122. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  161123. */
  161124. if( iNext>=FTS3_MERGE_COUNT ){
  161125. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  161126. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  161127. *piIdx = 0;
  161128. }else{
  161129. *piIdx = iNext;
  161130. }
  161131. }
  161132. return rc;
  161133. }
  161134. /*
  161135. ** The %_segments table is declared as follows:
  161136. **
  161137. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  161138. **
  161139. ** This function reads data from a single row of the %_segments table. The
  161140. ** specific row is identified by the iBlockid parameter. If paBlob is not
  161141. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  161142. ** with the contents of the blob stored in the "block" column of the
  161143. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  161144. ** to the size of the blob in bytes before returning.
  161145. **
  161146. ** If an error occurs, or the table does not contain the specified row,
  161147. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  161148. ** paBlob is non-NULL, then it is the responsibility of the caller to
  161149. ** eventually free the returned buffer.
  161150. **
  161151. ** This function may leave an open sqlite3_blob* handle in the
  161152. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  161153. ** to this function. The handle may be closed by calling the
  161154. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  161155. ** performance improvement, but the blob handle should always be closed
  161156. ** before control is returned to the user (to prevent a lock being held
  161157. ** on the database file for longer than necessary). Thus, any virtual table
  161158. ** method (xFilter etc.) that may directly or indirectly call this function
  161159. ** must call sqlite3Fts3SegmentsClose() before returning.
  161160. */
  161161. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  161162. Fts3Table *p, /* FTS3 table handle */
  161163. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  161164. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  161165. int *pnBlob, /* OUT: Size of blob data */
  161166. int *pnLoad /* OUT: Bytes actually loaded */
  161167. ){
  161168. int rc; /* Return code */
  161169. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  161170. assert( pnBlob );
  161171. if( p->pSegments ){
  161172. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  161173. }else{
  161174. if( 0==p->zSegmentsTbl ){
  161175. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  161176. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  161177. }
  161178. rc = sqlite3_blob_open(
  161179. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  161180. );
  161181. }
  161182. if( rc==SQLITE_OK ){
  161183. int nByte = sqlite3_blob_bytes(p->pSegments);
  161184. *pnBlob = nByte;
  161185. if( paBlob ){
  161186. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  161187. if( !aByte ){
  161188. rc = SQLITE_NOMEM;
  161189. }else{
  161190. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  161191. nByte = FTS3_NODE_CHUNKSIZE;
  161192. *pnLoad = nByte;
  161193. }
  161194. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  161195. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  161196. if( rc!=SQLITE_OK ){
  161197. sqlite3_free(aByte);
  161198. aByte = 0;
  161199. }
  161200. }
  161201. *paBlob = aByte;
  161202. }
  161203. }
  161204. return rc;
  161205. }
  161206. /*
  161207. ** Close the blob handle at p->pSegments, if it is open. See comments above
  161208. ** the sqlite3Fts3ReadBlock() function for details.
  161209. */
  161210. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  161211. sqlite3_blob_close(p->pSegments);
  161212. p->pSegments = 0;
  161213. }
  161214. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  161215. int nRead; /* Number of bytes to read */
  161216. int rc; /* Return code */
  161217. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  161218. rc = sqlite3_blob_read(
  161219. pReader->pBlob,
  161220. &pReader->aNode[pReader->nPopulate],
  161221. nRead,
  161222. pReader->nPopulate
  161223. );
  161224. if( rc==SQLITE_OK ){
  161225. pReader->nPopulate += nRead;
  161226. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  161227. if( pReader->nPopulate==pReader->nNode ){
  161228. sqlite3_blob_close(pReader->pBlob);
  161229. pReader->pBlob = 0;
  161230. pReader->nPopulate = 0;
  161231. }
  161232. }
  161233. return rc;
  161234. }
  161235. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  161236. int rc = SQLITE_OK;
  161237. assert( !pReader->pBlob
  161238. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  161239. );
  161240. while( pReader->pBlob && rc==SQLITE_OK
  161241. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  161242. ){
  161243. rc = fts3SegReaderIncrRead(pReader);
  161244. }
  161245. return rc;
  161246. }
  161247. /*
  161248. ** Set an Fts3SegReader cursor to point at EOF.
  161249. */
  161250. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  161251. if( !fts3SegReaderIsRootOnly(pSeg) ){
  161252. sqlite3_free(pSeg->aNode);
  161253. sqlite3_blob_close(pSeg->pBlob);
  161254. pSeg->pBlob = 0;
  161255. }
  161256. pSeg->aNode = 0;
  161257. }
  161258. /*
  161259. ** Move the iterator passed as the first argument to the next term in the
  161260. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  161261. ** SQLITE_DONE. Otherwise, an SQLite error code.
  161262. */
  161263. static int fts3SegReaderNext(
  161264. Fts3Table *p,
  161265. Fts3SegReader *pReader,
  161266. int bIncr
  161267. ){
  161268. int rc; /* Return code of various sub-routines */
  161269. char *pNext; /* Cursor variable */
  161270. int nPrefix; /* Number of bytes in term prefix */
  161271. int nSuffix; /* Number of bytes in term suffix */
  161272. if( !pReader->aDoclist ){
  161273. pNext = pReader->aNode;
  161274. }else{
  161275. pNext = &pReader->aDoclist[pReader->nDoclist];
  161276. }
  161277. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  161278. if( fts3SegReaderIsPending(pReader) ){
  161279. Fts3HashElem *pElem = *(pReader->ppNextElem);
  161280. sqlite3_free(pReader->aNode);
  161281. pReader->aNode = 0;
  161282. if( pElem ){
  161283. char *aCopy;
  161284. PendingList *pList = (PendingList *)fts3HashData(pElem);
  161285. int nCopy = pList->nData+1;
  161286. pReader->zTerm = (char *)fts3HashKey(pElem);
  161287. pReader->nTerm = fts3HashKeysize(pElem);
  161288. aCopy = (char*)sqlite3_malloc(nCopy);
  161289. if( !aCopy ) return SQLITE_NOMEM;
  161290. memcpy(aCopy, pList->aData, nCopy);
  161291. pReader->nNode = pReader->nDoclist = nCopy;
  161292. pReader->aNode = pReader->aDoclist = aCopy;
  161293. pReader->ppNextElem++;
  161294. assert( pReader->aNode );
  161295. }
  161296. return SQLITE_OK;
  161297. }
  161298. fts3SegReaderSetEof(pReader);
  161299. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  161300. ** blocks have already been traversed. */
  161301. #ifdef CORRUPT_DB
  161302. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock || CORRUPT_DB );
  161303. #endif
  161304. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  161305. return SQLITE_OK;
  161306. }
  161307. rc = sqlite3Fts3ReadBlock(
  161308. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  161309. (bIncr ? &pReader->nPopulate : 0)
  161310. );
  161311. if( rc!=SQLITE_OK ) return rc;
  161312. assert( pReader->pBlob==0 );
  161313. if( bIncr && pReader->nPopulate<pReader->nNode ){
  161314. pReader->pBlob = p->pSegments;
  161315. p->pSegments = 0;
  161316. }
  161317. pNext = pReader->aNode;
  161318. }
  161319. assert( !fts3SegReaderIsPending(pReader) );
  161320. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  161321. if( rc!=SQLITE_OK ) return rc;
  161322. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  161323. ** safe (no risk of overread) even if the node data is corrupted. */
  161324. pNext += fts3GetVarint32(pNext, &nPrefix);
  161325. pNext += fts3GetVarint32(pNext, &nSuffix);
  161326. if( nSuffix<=0
  161327. || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix
  161328. || nPrefix>pReader->nTermAlloc
  161329. ){
  161330. return FTS_CORRUPT_VTAB;
  161331. }
  161332. /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are
  161333. ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer
  161334. ** overflow - hence the (i64) casts. */
  161335. if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){
  161336. i64 nNew = ((i64)nPrefix+nSuffix)*2;
  161337. char *zNew = sqlite3_realloc64(pReader->zTerm, nNew);
  161338. if( !zNew ){
  161339. return SQLITE_NOMEM;
  161340. }
  161341. pReader->zTerm = zNew;
  161342. pReader->nTermAlloc = nNew;
  161343. }
  161344. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  161345. if( rc!=SQLITE_OK ) return rc;
  161346. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  161347. pReader->nTerm = nPrefix+nSuffix;
  161348. pNext += nSuffix;
  161349. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  161350. pReader->aDoclist = pNext;
  161351. pReader->pOffsetList = 0;
  161352. /* Check that the doclist does not appear to extend past the end of the
  161353. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  161354. ** of these statements is untrue, then the data structure is corrupt.
  161355. */
  161356. if( pReader->nDoclist > pReader->nNode-(pReader->aDoclist-pReader->aNode)
  161357. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  161358. ){
  161359. return FTS_CORRUPT_VTAB;
  161360. }
  161361. return SQLITE_OK;
  161362. }
  161363. /*
  161364. ** Set the SegReader to point to the first docid in the doclist associated
  161365. ** with the current term.
  161366. */
  161367. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  161368. int rc = SQLITE_OK;
  161369. assert( pReader->aDoclist );
  161370. assert( !pReader->pOffsetList );
  161371. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  161372. u8 bEof = 0;
  161373. pReader->iDocid = 0;
  161374. pReader->nOffsetList = 0;
  161375. sqlite3Fts3DoclistPrev(0,
  161376. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  161377. &pReader->iDocid, &pReader->nOffsetList, &bEof
  161378. );
  161379. }else{
  161380. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  161381. if( rc==SQLITE_OK ){
  161382. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  161383. pReader->pOffsetList = &pReader->aDoclist[n];
  161384. }
  161385. }
  161386. return rc;
  161387. }
  161388. /*
  161389. ** Advance the SegReader to point to the next docid in the doclist
  161390. ** associated with the current term.
  161391. **
  161392. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  161393. ** *ppOffsetList is set to point to the first column-offset list
  161394. ** in the doclist entry (i.e. immediately past the docid varint).
  161395. ** *pnOffsetList is set to the length of the set of column-offset
  161396. ** lists, not including the nul-terminator byte. For example:
  161397. */
  161398. static int fts3SegReaderNextDocid(
  161399. Fts3Table *pTab,
  161400. Fts3SegReader *pReader, /* Reader to advance to next docid */
  161401. char **ppOffsetList, /* OUT: Pointer to current position-list */
  161402. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  161403. ){
  161404. int rc = SQLITE_OK;
  161405. char *p = pReader->pOffsetList;
  161406. char c = 0;
  161407. assert( p );
  161408. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  161409. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  161410. ** Pending-terms doclists are always built up in ascending order, so
  161411. ** we have to iterate through them backwards here. */
  161412. u8 bEof = 0;
  161413. if( ppOffsetList ){
  161414. *ppOffsetList = pReader->pOffsetList;
  161415. *pnOffsetList = pReader->nOffsetList - 1;
  161416. }
  161417. sqlite3Fts3DoclistPrev(0,
  161418. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  161419. &pReader->nOffsetList, &bEof
  161420. );
  161421. if( bEof ){
  161422. pReader->pOffsetList = 0;
  161423. }else{
  161424. pReader->pOffsetList = p;
  161425. }
  161426. }else{
  161427. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  161428. /* Pointer p currently points at the first byte of an offset list. The
  161429. ** following block advances it to point one byte past the end of
  161430. ** the same offset list. */
  161431. while( 1 ){
  161432. /* The following line of code (and the "p++" below the while() loop) is
  161433. ** normally all that is required to move pointer p to the desired
  161434. ** position. The exception is if this node is being loaded from disk
  161435. ** incrementally and pointer "p" now points to the first byte past
  161436. ** the populated part of pReader->aNode[].
  161437. */
  161438. while( *p | c ) c = *p++ & 0x80;
  161439. assert( *p==0 );
  161440. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  161441. rc = fts3SegReaderIncrRead(pReader);
  161442. if( rc!=SQLITE_OK ) return rc;
  161443. }
  161444. p++;
  161445. /* If required, populate the output variables with a pointer to and the
  161446. ** size of the previous offset-list.
  161447. */
  161448. if( ppOffsetList ){
  161449. *ppOffsetList = pReader->pOffsetList;
  161450. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  161451. }
  161452. /* List may have been edited in place by fts3EvalNearTrim() */
  161453. while( p<pEnd && *p==0 ) p++;
  161454. /* If there are no more entries in the doclist, set pOffsetList to
  161455. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  161456. ** Fts3SegReader.pOffsetList to point to the next offset list before
  161457. ** returning.
  161458. */
  161459. if( p>=pEnd ){
  161460. pReader->pOffsetList = 0;
  161461. }else{
  161462. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  161463. if( rc==SQLITE_OK ){
  161464. sqlite3_int64 iDelta;
  161465. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  161466. if( pTab->bDescIdx ){
  161467. pReader->iDocid -= iDelta;
  161468. }else{
  161469. pReader->iDocid += iDelta;
  161470. }
  161471. }
  161472. }
  161473. }
  161474. return SQLITE_OK;
  161475. }
  161476. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  161477. Fts3Cursor *pCsr,
  161478. Fts3MultiSegReader *pMsr,
  161479. int *pnOvfl
  161480. ){
  161481. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  161482. int nOvfl = 0;
  161483. int ii;
  161484. int rc = SQLITE_OK;
  161485. int pgsz = p->nPgsz;
  161486. assert( p->bFts4 );
  161487. assert( pgsz>0 );
  161488. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  161489. Fts3SegReader *pReader = pMsr->apSegment[ii];
  161490. if( !fts3SegReaderIsPending(pReader)
  161491. && !fts3SegReaderIsRootOnly(pReader)
  161492. ){
  161493. sqlite3_int64 jj;
  161494. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  161495. int nBlob;
  161496. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  161497. if( rc!=SQLITE_OK ) break;
  161498. if( (nBlob+35)>pgsz ){
  161499. nOvfl += (nBlob + 34)/pgsz;
  161500. }
  161501. }
  161502. }
  161503. }
  161504. *pnOvfl = nOvfl;
  161505. return rc;
  161506. }
  161507. /*
  161508. ** Free all allocations associated with the iterator passed as the
  161509. ** second argument.
  161510. */
  161511. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  161512. if( pReader ){
  161513. if( !fts3SegReaderIsPending(pReader) ){
  161514. sqlite3_free(pReader->zTerm);
  161515. }
  161516. if( !fts3SegReaderIsRootOnly(pReader) ){
  161517. sqlite3_free(pReader->aNode);
  161518. }
  161519. sqlite3_blob_close(pReader->pBlob);
  161520. }
  161521. sqlite3_free(pReader);
  161522. }
  161523. /*
  161524. ** Allocate a new SegReader object.
  161525. */
  161526. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  161527. int iAge, /* Segment "age". */
  161528. int bLookup, /* True for a lookup only */
  161529. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  161530. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  161531. sqlite3_int64 iEndBlock, /* Final block of segment */
  161532. const char *zRoot, /* Buffer containing root node */
  161533. int nRoot, /* Size of buffer containing root node */
  161534. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  161535. ){
  161536. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  161537. int nExtra = 0; /* Bytes to allocate segment root node */
  161538. assert( zRoot!=0 || nRoot==0 );
  161539. #ifdef CORRUPT_DB
  161540. assert( zRoot!=0 || CORRUPT_DB );
  161541. #endif
  161542. if( iStartLeaf==0 ){
  161543. if( iEndLeaf!=0 ) return FTS_CORRUPT_VTAB;
  161544. nExtra = nRoot + FTS3_NODE_PADDING;
  161545. }
  161546. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  161547. if( !pReader ){
  161548. return SQLITE_NOMEM;
  161549. }
  161550. memset(pReader, 0, sizeof(Fts3SegReader));
  161551. pReader->iIdx = iAge;
  161552. pReader->bLookup = bLookup!=0;
  161553. pReader->iStartBlock = iStartLeaf;
  161554. pReader->iLeafEndBlock = iEndLeaf;
  161555. pReader->iEndBlock = iEndBlock;
  161556. if( nExtra ){
  161557. /* The entire segment is stored in the root node. */
  161558. pReader->aNode = (char *)&pReader[1];
  161559. pReader->rootOnly = 1;
  161560. pReader->nNode = nRoot;
  161561. if( nRoot ) memcpy(pReader->aNode, zRoot, nRoot);
  161562. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  161563. }else{
  161564. pReader->iCurrentBlock = iStartLeaf-1;
  161565. }
  161566. *ppReader = pReader;
  161567. return SQLITE_OK;
  161568. }
  161569. /*
  161570. ** This is a comparison function used as a qsort() callback when sorting
  161571. ** an array of pending terms by term. This occurs as part of flushing
  161572. ** the contents of the pending-terms hash table to the database.
  161573. */
  161574. static int SQLITE_CDECL fts3CompareElemByTerm(
  161575. const void *lhs,
  161576. const void *rhs
  161577. ){
  161578. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  161579. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  161580. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  161581. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  161582. int n = (n1<n2 ? n1 : n2);
  161583. int c = memcmp(z1, z2, n);
  161584. if( c==0 ){
  161585. c = n1 - n2;
  161586. }
  161587. return c;
  161588. }
  161589. /*
  161590. ** This function is used to allocate an Fts3SegReader that iterates through
  161591. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  161592. **
  161593. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  161594. ** through each term in the pending-terms table. Or, if isPrefixIter is
  161595. ** non-zero, it iterates through each term and its prefixes. For example, if
  161596. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  161597. ** "firebird", then the iterator visits the following 'terms' (in the order
  161598. ** shown):
  161599. **
  161600. ** f fi fir fire fireb firebi firebir firebird
  161601. ** m my mys mysq mysql
  161602. ** s sq sql sqli sqlit sqlite
  161603. **
  161604. ** Whereas if isPrefixIter is zero, the terms visited are:
  161605. **
  161606. ** firebird mysql sqlite
  161607. */
  161608. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  161609. Fts3Table *p, /* Virtual table handle */
  161610. int iIndex, /* Index for p->aIndex */
  161611. const char *zTerm, /* Term to search for */
  161612. int nTerm, /* Size of buffer zTerm */
  161613. int bPrefix, /* True for a prefix iterator */
  161614. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  161615. ){
  161616. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  161617. Fts3HashElem *pE; /* Iterator variable */
  161618. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  161619. int nElem = 0; /* Size of array at aElem */
  161620. int rc = SQLITE_OK; /* Return Code */
  161621. Fts3Hash *pHash;
  161622. pHash = &p->aIndex[iIndex].hPending;
  161623. if( bPrefix ){
  161624. int nAlloc = 0; /* Size of allocated array at aElem */
  161625. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  161626. char *zKey = (char *)fts3HashKey(pE);
  161627. int nKey = fts3HashKeysize(pE);
  161628. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  161629. if( nElem==nAlloc ){
  161630. Fts3HashElem **aElem2;
  161631. nAlloc += 16;
  161632. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  161633. aElem, nAlloc*sizeof(Fts3HashElem *)
  161634. );
  161635. if( !aElem2 ){
  161636. rc = SQLITE_NOMEM;
  161637. nElem = 0;
  161638. break;
  161639. }
  161640. aElem = aElem2;
  161641. }
  161642. aElem[nElem++] = pE;
  161643. }
  161644. }
  161645. /* If more than one term matches the prefix, sort the Fts3HashElem
  161646. ** objects in term order using qsort(). This uses the same comparison
  161647. ** callback as is used when flushing terms to disk.
  161648. */
  161649. if( nElem>1 ){
  161650. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  161651. }
  161652. }else{
  161653. /* The query is a simple term lookup that matches at most one term in
  161654. ** the index. All that is required is a straight hash-lookup.
  161655. **
  161656. ** Because the stack address of pE may be accessed via the aElem pointer
  161657. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  161658. ** within this entire function, not just this "else{...}" block.
  161659. */
  161660. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  161661. if( pE ){
  161662. aElem = &pE;
  161663. nElem = 1;
  161664. }
  161665. }
  161666. if( nElem>0 ){
  161667. sqlite3_int64 nByte;
  161668. nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  161669. pReader = (Fts3SegReader *)sqlite3_malloc64(nByte);
  161670. if( !pReader ){
  161671. rc = SQLITE_NOMEM;
  161672. }else{
  161673. memset(pReader, 0, nByte);
  161674. pReader->iIdx = 0x7FFFFFFF;
  161675. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  161676. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  161677. }
  161678. }
  161679. if( bPrefix ){
  161680. sqlite3_free(aElem);
  161681. }
  161682. *ppReader = pReader;
  161683. return rc;
  161684. }
  161685. /*
  161686. ** Compare the entries pointed to by two Fts3SegReader structures.
  161687. ** Comparison is as follows:
  161688. **
  161689. ** 1) EOF is greater than not EOF.
  161690. **
  161691. ** 2) The current terms (if any) are compared using memcmp(). If one
  161692. ** term is a prefix of another, the longer term is considered the
  161693. ** larger.
  161694. **
  161695. ** 3) By segment age. An older segment is considered larger.
  161696. */
  161697. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  161698. int rc;
  161699. if( pLhs->aNode && pRhs->aNode ){
  161700. int rc2 = pLhs->nTerm - pRhs->nTerm;
  161701. if( rc2<0 ){
  161702. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  161703. }else{
  161704. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  161705. }
  161706. if( rc==0 ){
  161707. rc = rc2;
  161708. }
  161709. }else{
  161710. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  161711. }
  161712. if( rc==0 ){
  161713. rc = pRhs->iIdx - pLhs->iIdx;
  161714. }
  161715. assert( rc!=0 );
  161716. return rc;
  161717. }
  161718. /*
  161719. ** A different comparison function for SegReader structures. In this
  161720. ** version, it is assumed that each SegReader points to an entry in
  161721. ** a doclist for identical terms. Comparison is made as follows:
  161722. **
  161723. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  161724. **
  161725. ** 2) By current docid.
  161726. **
  161727. ** 3) By segment age. An older segment is considered larger.
  161728. */
  161729. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  161730. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  161731. if( rc==0 ){
  161732. if( pLhs->iDocid==pRhs->iDocid ){
  161733. rc = pRhs->iIdx - pLhs->iIdx;
  161734. }else{
  161735. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  161736. }
  161737. }
  161738. assert( pLhs->aNode && pRhs->aNode );
  161739. return rc;
  161740. }
  161741. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  161742. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  161743. if( rc==0 ){
  161744. if( pLhs->iDocid==pRhs->iDocid ){
  161745. rc = pRhs->iIdx - pLhs->iIdx;
  161746. }else{
  161747. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  161748. }
  161749. }
  161750. assert( pLhs->aNode && pRhs->aNode );
  161751. return rc;
  161752. }
  161753. /*
  161754. ** Compare the term that the Fts3SegReader object passed as the first argument
  161755. ** points to with the term specified by arguments zTerm and nTerm.
  161756. **
  161757. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  161758. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  161759. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  161760. */
  161761. static int fts3SegReaderTermCmp(
  161762. Fts3SegReader *pSeg, /* Segment reader object */
  161763. const char *zTerm, /* Term to compare to */
  161764. int nTerm /* Size of term zTerm in bytes */
  161765. ){
  161766. int res = 0;
  161767. if( pSeg->aNode ){
  161768. if( pSeg->nTerm>nTerm ){
  161769. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  161770. }else{
  161771. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  161772. }
  161773. if( res==0 ){
  161774. res = pSeg->nTerm-nTerm;
  161775. }
  161776. }
  161777. return res;
  161778. }
  161779. /*
  161780. ** Argument apSegment is an array of nSegment elements. It is known that
  161781. ** the final (nSegment-nSuspect) members are already in sorted order
  161782. ** (according to the comparison function provided). This function shuffles
  161783. ** the array around until all entries are in sorted order.
  161784. */
  161785. static void fts3SegReaderSort(
  161786. Fts3SegReader **apSegment, /* Array to sort entries of */
  161787. int nSegment, /* Size of apSegment array */
  161788. int nSuspect, /* Unsorted entry count */
  161789. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  161790. ){
  161791. int i; /* Iterator variable */
  161792. assert( nSuspect<=nSegment );
  161793. if( nSuspect==nSegment ) nSuspect--;
  161794. for(i=nSuspect-1; i>=0; i--){
  161795. int j;
  161796. for(j=i; j<(nSegment-1); j++){
  161797. Fts3SegReader *pTmp;
  161798. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  161799. pTmp = apSegment[j+1];
  161800. apSegment[j+1] = apSegment[j];
  161801. apSegment[j] = pTmp;
  161802. }
  161803. }
  161804. #ifndef NDEBUG
  161805. /* Check that the list really is sorted now. */
  161806. for(i=0; i<(nSuspect-1); i++){
  161807. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  161808. }
  161809. #endif
  161810. }
  161811. /*
  161812. ** Insert a record into the %_segments table.
  161813. */
  161814. static int fts3WriteSegment(
  161815. Fts3Table *p, /* Virtual table handle */
  161816. sqlite3_int64 iBlock, /* Block id for new block */
  161817. char *z, /* Pointer to buffer containing block data */
  161818. int n /* Size of buffer z in bytes */
  161819. ){
  161820. sqlite3_stmt *pStmt;
  161821. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  161822. if( rc==SQLITE_OK ){
  161823. sqlite3_bind_int64(pStmt, 1, iBlock);
  161824. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  161825. sqlite3_step(pStmt);
  161826. rc = sqlite3_reset(pStmt);
  161827. sqlite3_bind_null(pStmt, 2);
  161828. }
  161829. return rc;
  161830. }
  161831. /*
  161832. ** Find the largest relative level number in the table. If successful, set
  161833. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  161834. ** set *pnMax to zero and return an SQLite error code.
  161835. */
  161836. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  161837. int rc;
  161838. int mxLevel = 0;
  161839. sqlite3_stmt *pStmt = 0;
  161840. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  161841. if( rc==SQLITE_OK ){
  161842. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  161843. mxLevel = sqlite3_column_int(pStmt, 0);
  161844. }
  161845. rc = sqlite3_reset(pStmt);
  161846. }
  161847. *pnMax = mxLevel;
  161848. return rc;
  161849. }
  161850. /*
  161851. ** Insert a record into the %_segdir table.
  161852. */
  161853. static int fts3WriteSegdir(
  161854. Fts3Table *p, /* Virtual table handle */
  161855. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  161856. int iIdx, /* Value for "idx" field */
  161857. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  161858. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  161859. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  161860. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  161861. char *zRoot, /* Blob value for "root" field */
  161862. int nRoot /* Number of bytes in buffer zRoot */
  161863. ){
  161864. sqlite3_stmt *pStmt;
  161865. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  161866. if( rc==SQLITE_OK ){
  161867. sqlite3_bind_int64(pStmt, 1, iLevel);
  161868. sqlite3_bind_int(pStmt, 2, iIdx);
  161869. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  161870. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  161871. if( nLeafData==0 ){
  161872. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  161873. }else{
  161874. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  161875. if( !zEnd ) return SQLITE_NOMEM;
  161876. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  161877. }
  161878. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  161879. sqlite3_step(pStmt);
  161880. rc = sqlite3_reset(pStmt);
  161881. sqlite3_bind_null(pStmt, 6);
  161882. }
  161883. return rc;
  161884. }
  161885. /*
  161886. ** Return the size of the common prefix (if any) shared by zPrev and
  161887. ** zNext, in bytes. For example,
  161888. **
  161889. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  161890. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  161891. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  161892. */
  161893. static int fts3PrefixCompress(
  161894. const char *zPrev, /* Buffer containing previous term */
  161895. int nPrev, /* Size of buffer zPrev in bytes */
  161896. const char *zNext, /* Buffer containing next term */
  161897. int nNext /* Size of buffer zNext in bytes */
  161898. ){
  161899. int n;
  161900. UNUSED_PARAMETER(nNext);
  161901. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  161902. return n;
  161903. }
  161904. /*
  161905. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  161906. ** (according to memcmp) than the previous term.
  161907. */
  161908. static int fts3NodeAddTerm(
  161909. Fts3Table *p, /* Virtual table handle */
  161910. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  161911. int isCopyTerm, /* True if zTerm/nTerm is transient */
  161912. const char *zTerm, /* Pointer to buffer containing term */
  161913. int nTerm /* Size of term in bytes */
  161914. ){
  161915. SegmentNode *pTree = *ppTree;
  161916. int rc;
  161917. SegmentNode *pNew;
  161918. /* First try to append the term to the current node. Return early if
  161919. ** this is possible.
  161920. */
  161921. if( pTree ){
  161922. int nData = pTree->nData; /* Current size of node in bytes */
  161923. int nReq = nData; /* Required space after adding zTerm */
  161924. int nPrefix; /* Number of bytes of prefix compression */
  161925. int nSuffix; /* Suffix length */
  161926. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  161927. nSuffix = nTerm-nPrefix;
  161928. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  161929. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  161930. if( nReq>p->nNodeSize ){
  161931. /* An unusual case: this is the first term to be added to the node
  161932. ** and the static node buffer (p->nNodeSize bytes) is not large
  161933. ** enough. Use a separately malloced buffer instead This wastes
  161934. ** p->nNodeSize bytes, but since this scenario only comes about when
  161935. ** the database contain two terms that share a prefix of almost 2KB,
  161936. ** this is not expected to be a serious problem.
  161937. */
  161938. assert( pTree->aData==(char *)&pTree[1] );
  161939. pTree->aData = (char *)sqlite3_malloc(nReq);
  161940. if( !pTree->aData ){
  161941. return SQLITE_NOMEM;
  161942. }
  161943. }
  161944. if( pTree->zTerm ){
  161945. /* There is no prefix-length field for first term in a node */
  161946. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  161947. }
  161948. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  161949. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  161950. pTree->nData = nData + nSuffix;
  161951. pTree->nEntry++;
  161952. if( isCopyTerm ){
  161953. if( pTree->nMalloc<nTerm ){
  161954. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  161955. if( !zNew ){
  161956. return SQLITE_NOMEM;
  161957. }
  161958. pTree->nMalloc = nTerm*2;
  161959. pTree->zMalloc = zNew;
  161960. }
  161961. pTree->zTerm = pTree->zMalloc;
  161962. memcpy(pTree->zTerm, zTerm, nTerm);
  161963. pTree->nTerm = nTerm;
  161964. }else{
  161965. pTree->zTerm = (char *)zTerm;
  161966. pTree->nTerm = nTerm;
  161967. }
  161968. return SQLITE_OK;
  161969. }
  161970. }
  161971. /* If control flows to here, it was not possible to append zTerm to the
  161972. ** current node. Create a new node (a right-sibling of the current node).
  161973. ** If this is the first node in the tree, the term is added to it.
  161974. **
  161975. ** Otherwise, the term is not added to the new node, it is left empty for
  161976. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  161977. ** has no parent, one is created here.
  161978. */
  161979. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  161980. if( !pNew ){
  161981. return SQLITE_NOMEM;
  161982. }
  161983. memset(pNew, 0, sizeof(SegmentNode));
  161984. pNew->nData = 1 + FTS3_VARINT_MAX;
  161985. pNew->aData = (char *)&pNew[1];
  161986. if( pTree ){
  161987. SegmentNode *pParent = pTree->pParent;
  161988. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  161989. if( pTree->pParent==0 ){
  161990. pTree->pParent = pParent;
  161991. }
  161992. pTree->pRight = pNew;
  161993. pNew->pLeftmost = pTree->pLeftmost;
  161994. pNew->pParent = pParent;
  161995. pNew->zMalloc = pTree->zMalloc;
  161996. pNew->nMalloc = pTree->nMalloc;
  161997. pTree->zMalloc = 0;
  161998. }else{
  161999. pNew->pLeftmost = pNew;
  162000. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  162001. }
  162002. *ppTree = pNew;
  162003. return rc;
  162004. }
  162005. /*
  162006. ** Helper function for fts3NodeWrite().
  162007. */
  162008. static int fts3TreeFinishNode(
  162009. SegmentNode *pTree,
  162010. int iHeight,
  162011. sqlite3_int64 iLeftChild
  162012. ){
  162013. int nStart;
  162014. assert( iHeight>=1 && iHeight<128 );
  162015. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  162016. pTree->aData[nStart] = (char)iHeight;
  162017. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  162018. return nStart;
  162019. }
  162020. /*
  162021. ** Write the buffer for the segment node pTree and all of its peers to the
  162022. ** database. Then call this function recursively to write the parent of
  162023. ** pTree and its peers to the database.
  162024. **
  162025. ** Except, if pTree is a root node, do not write it to the database. Instead,
  162026. ** set output variables *paRoot and *pnRoot to contain the root node.
  162027. **
  162028. ** If successful, SQLITE_OK is returned and output variable *piLast is
  162029. ** set to the largest blockid written to the database (or zero if no
  162030. ** blocks were written to the db). Otherwise, an SQLite error code is
  162031. ** returned.
  162032. */
  162033. static int fts3NodeWrite(
  162034. Fts3Table *p, /* Virtual table handle */
  162035. SegmentNode *pTree, /* SegmentNode handle */
  162036. int iHeight, /* Height of this node in tree */
  162037. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  162038. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  162039. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  162040. char **paRoot, /* OUT: Data for root node */
  162041. int *pnRoot /* OUT: Size of root node in bytes */
  162042. ){
  162043. int rc = SQLITE_OK;
  162044. if( !pTree->pParent ){
  162045. /* Root node of the tree. */
  162046. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  162047. *piLast = iFree-1;
  162048. *pnRoot = pTree->nData - nStart;
  162049. *paRoot = &pTree->aData[nStart];
  162050. }else{
  162051. SegmentNode *pIter;
  162052. sqlite3_int64 iNextFree = iFree;
  162053. sqlite3_int64 iNextLeaf = iLeaf;
  162054. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  162055. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  162056. int nWrite = pIter->nData - nStart;
  162057. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  162058. iNextFree++;
  162059. iNextLeaf += (pIter->nEntry+1);
  162060. }
  162061. if( rc==SQLITE_OK ){
  162062. assert( iNextLeaf==iFree );
  162063. rc = fts3NodeWrite(
  162064. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  162065. );
  162066. }
  162067. }
  162068. return rc;
  162069. }
  162070. /*
  162071. ** Free all memory allocations associated with the tree pTree.
  162072. */
  162073. static void fts3NodeFree(SegmentNode *pTree){
  162074. if( pTree ){
  162075. SegmentNode *p = pTree->pLeftmost;
  162076. fts3NodeFree(p->pParent);
  162077. while( p ){
  162078. SegmentNode *pRight = p->pRight;
  162079. if( p->aData!=(char *)&p[1] ){
  162080. sqlite3_free(p->aData);
  162081. }
  162082. assert( pRight==0 || p->zMalloc==0 );
  162083. sqlite3_free(p->zMalloc);
  162084. sqlite3_free(p);
  162085. p = pRight;
  162086. }
  162087. }
  162088. }
  162089. /*
  162090. ** Add a term to the segment being constructed by the SegmentWriter object
  162091. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  162092. ** be passed NULL. This function will allocate a new SegmentWriter object
  162093. ** and return it via the input/output variable *ppWriter in this case.
  162094. **
  162095. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  162096. */
  162097. static int fts3SegWriterAdd(
  162098. Fts3Table *p, /* Virtual table handle */
  162099. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  162100. int isCopyTerm, /* True if buffer zTerm must be copied */
  162101. const char *zTerm, /* Pointer to buffer containing term */
  162102. int nTerm, /* Size of term in bytes */
  162103. const char *aDoclist, /* Pointer to buffer containing doclist */
  162104. int nDoclist /* Size of doclist in bytes */
  162105. ){
  162106. int nPrefix; /* Size of term prefix in bytes */
  162107. int nSuffix; /* Size of term suffix in bytes */
  162108. int nReq; /* Number of bytes required on leaf page */
  162109. int nData;
  162110. SegmentWriter *pWriter = *ppWriter;
  162111. if( !pWriter ){
  162112. int rc;
  162113. sqlite3_stmt *pStmt;
  162114. /* Allocate the SegmentWriter structure */
  162115. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  162116. if( !pWriter ) return SQLITE_NOMEM;
  162117. memset(pWriter, 0, sizeof(SegmentWriter));
  162118. *ppWriter = pWriter;
  162119. /* Allocate a buffer in which to accumulate data */
  162120. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  162121. if( !pWriter->aData ) return SQLITE_NOMEM;
  162122. pWriter->nSize = p->nNodeSize;
  162123. /* Find the next free blockid in the %_segments table */
  162124. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  162125. if( rc!=SQLITE_OK ) return rc;
  162126. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162127. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  162128. pWriter->iFirst = pWriter->iFree;
  162129. }
  162130. rc = sqlite3_reset(pStmt);
  162131. if( rc!=SQLITE_OK ) return rc;
  162132. }
  162133. nData = pWriter->nData;
  162134. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  162135. nSuffix = nTerm-nPrefix;
  162136. /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
  162137. ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
  162138. ** compared with BINARY collation. This indicates corruption. */
  162139. if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
  162140. /* Figure out how many bytes are required by this new entry */
  162141. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  162142. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  162143. nSuffix + /* Term suffix */
  162144. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  162145. nDoclist; /* Doclist data */
  162146. if( nData>0 && nData+nReq>p->nNodeSize ){
  162147. int rc;
  162148. /* The current leaf node is full. Write it out to the database. */
  162149. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  162150. if( rc!=SQLITE_OK ) return rc;
  162151. p->nLeafAdd++;
  162152. /* Add the current term to the interior node tree. The term added to
  162153. ** the interior tree must:
  162154. **
  162155. ** a) be greater than the largest term on the leaf node just written
  162156. ** to the database (still available in pWriter->zTerm), and
  162157. **
  162158. ** b) be less than or equal to the term about to be added to the new
  162159. ** leaf node (zTerm/nTerm).
  162160. **
  162161. ** In other words, it must be the prefix of zTerm 1 byte longer than
  162162. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  162163. */
  162164. assert( nPrefix<nTerm );
  162165. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  162166. if( rc!=SQLITE_OK ) return rc;
  162167. nData = 0;
  162168. pWriter->nTerm = 0;
  162169. nPrefix = 0;
  162170. nSuffix = nTerm;
  162171. nReq = 1 + /* varint containing prefix size */
  162172. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  162173. nTerm + /* Term suffix */
  162174. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  162175. nDoclist; /* Doclist data */
  162176. }
  162177. /* Increase the total number of bytes written to account for the new entry. */
  162178. pWriter->nLeafData += nReq;
  162179. /* If the buffer currently allocated is too small for this entry, realloc
  162180. ** the buffer to make it large enough.
  162181. */
  162182. if( nReq>pWriter->nSize ){
  162183. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  162184. if( !aNew ) return SQLITE_NOMEM;
  162185. pWriter->aData = aNew;
  162186. pWriter->nSize = nReq;
  162187. }
  162188. assert( nData+nReq<=pWriter->nSize );
  162189. /* Append the prefix-compressed term and doclist to the buffer. */
  162190. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  162191. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  162192. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  162193. nData += nSuffix;
  162194. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  162195. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  162196. pWriter->nData = nData + nDoclist;
  162197. /* Save the current term so that it can be used to prefix-compress the next.
  162198. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  162199. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  162200. ** store a copy of the pointer.
  162201. */
  162202. if( isCopyTerm ){
  162203. if( nTerm>pWriter->nMalloc ){
  162204. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  162205. if( !zNew ){
  162206. return SQLITE_NOMEM;
  162207. }
  162208. pWriter->nMalloc = nTerm*2;
  162209. pWriter->zMalloc = zNew;
  162210. pWriter->zTerm = zNew;
  162211. }
  162212. assert( pWriter->zTerm==pWriter->zMalloc );
  162213. memcpy(pWriter->zTerm, zTerm, nTerm);
  162214. }else{
  162215. pWriter->zTerm = (char *)zTerm;
  162216. }
  162217. pWriter->nTerm = nTerm;
  162218. return SQLITE_OK;
  162219. }
  162220. /*
  162221. ** Flush all data associated with the SegmentWriter object pWriter to the
  162222. ** database. This function must be called after all terms have been added
  162223. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  162224. ** returned. Otherwise, an SQLite error code.
  162225. */
  162226. static int fts3SegWriterFlush(
  162227. Fts3Table *p, /* Virtual table handle */
  162228. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  162229. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  162230. int iIdx /* Value for 'idx' column of %_segdir */
  162231. ){
  162232. int rc; /* Return code */
  162233. if( pWriter->pTree ){
  162234. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  162235. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  162236. char *zRoot = NULL; /* Pointer to buffer containing root node */
  162237. int nRoot = 0; /* Size of buffer zRoot */
  162238. iLastLeaf = pWriter->iFree;
  162239. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  162240. if( rc==SQLITE_OK ){
  162241. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  162242. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  162243. }
  162244. if( rc==SQLITE_OK ){
  162245. rc = fts3WriteSegdir(p, iLevel, iIdx,
  162246. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  162247. }
  162248. }else{
  162249. /* The entire tree fits on the root node. Write it to the segdir table. */
  162250. rc = fts3WriteSegdir(p, iLevel, iIdx,
  162251. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  162252. }
  162253. p->nLeafAdd++;
  162254. return rc;
  162255. }
  162256. /*
  162257. ** Release all memory held by the SegmentWriter object passed as the
  162258. ** first argument.
  162259. */
  162260. static void fts3SegWriterFree(SegmentWriter *pWriter){
  162261. if( pWriter ){
  162262. sqlite3_free(pWriter->aData);
  162263. sqlite3_free(pWriter->zMalloc);
  162264. fts3NodeFree(pWriter->pTree);
  162265. sqlite3_free(pWriter);
  162266. }
  162267. }
  162268. /*
  162269. ** The first value in the apVal[] array is assumed to contain an integer.
  162270. ** This function tests if there exist any documents with docid values that
  162271. ** are different from that integer. i.e. if deleting the document with docid
  162272. ** pRowid would mean the FTS3 table were empty.
  162273. **
  162274. ** If successful, *pisEmpty is set to true if the table is empty except for
  162275. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  162276. ** error occurs, an SQLite error code is returned.
  162277. */
  162278. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  162279. sqlite3_stmt *pStmt;
  162280. int rc;
  162281. if( p->zContentTbl ){
  162282. /* If using the content=xxx option, assume the table is never empty */
  162283. *pisEmpty = 0;
  162284. rc = SQLITE_OK;
  162285. }else{
  162286. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  162287. if( rc==SQLITE_OK ){
  162288. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162289. *pisEmpty = sqlite3_column_int(pStmt, 0);
  162290. }
  162291. rc = sqlite3_reset(pStmt);
  162292. }
  162293. }
  162294. return rc;
  162295. }
  162296. /*
  162297. ** Set *pnMax to the largest segment level in the database for the index
  162298. ** iIndex.
  162299. **
  162300. ** Segment levels are stored in the 'level' column of the %_segdir table.
  162301. **
  162302. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  162303. */
  162304. static int fts3SegmentMaxLevel(
  162305. Fts3Table *p,
  162306. int iLangid,
  162307. int iIndex,
  162308. sqlite3_int64 *pnMax
  162309. ){
  162310. sqlite3_stmt *pStmt;
  162311. int rc;
  162312. assert( iIndex>=0 && iIndex<p->nIndex );
  162313. /* Set pStmt to the compiled version of:
  162314. **
  162315. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  162316. **
  162317. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  162318. */
  162319. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  162320. if( rc!=SQLITE_OK ) return rc;
  162321. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  162322. sqlite3_bind_int64(pStmt, 2,
  162323. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  162324. );
  162325. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162326. *pnMax = sqlite3_column_int64(pStmt, 0);
  162327. }
  162328. return sqlite3_reset(pStmt);
  162329. }
  162330. /*
  162331. ** iAbsLevel is an absolute level that may be assumed to exist within
  162332. ** the database. This function checks if it is the largest level number
  162333. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  162334. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  162335. ** is returned. If an error occurs, an error code is returned and the
  162336. ** final value of *pbMax is undefined.
  162337. */
  162338. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  162339. /* Set pStmt to the compiled version of:
  162340. **
  162341. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  162342. **
  162343. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  162344. */
  162345. sqlite3_stmt *pStmt;
  162346. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  162347. if( rc!=SQLITE_OK ) return rc;
  162348. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  162349. sqlite3_bind_int64(pStmt, 2,
  162350. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  162351. );
  162352. *pbMax = 0;
  162353. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  162354. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  162355. }
  162356. return sqlite3_reset(pStmt);
  162357. }
  162358. /*
  162359. ** Delete all entries in the %_segments table associated with the segment
  162360. ** opened with seg-reader pSeg. This function does not affect the contents
  162361. ** of the %_segdir table.
  162362. */
  162363. static int fts3DeleteSegment(
  162364. Fts3Table *p, /* FTS table handle */
  162365. Fts3SegReader *pSeg /* Segment to delete */
  162366. ){
  162367. int rc = SQLITE_OK; /* Return code */
  162368. if( pSeg->iStartBlock ){
  162369. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  162370. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  162371. if( rc==SQLITE_OK ){
  162372. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  162373. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  162374. sqlite3_step(pDelete);
  162375. rc = sqlite3_reset(pDelete);
  162376. }
  162377. }
  162378. return rc;
  162379. }
  162380. /*
  162381. ** This function is used after merging multiple segments into a single large
  162382. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  162383. ** it:
  162384. **
  162385. ** 1) Deletes all %_segments entries for the segments associated with
  162386. ** each of the SegReader objects in the array passed as the third
  162387. ** argument, and
  162388. **
  162389. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  162390. ** entries regardless of level if (iLevel<0).
  162391. **
  162392. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  162393. */
  162394. static int fts3DeleteSegdir(
  162395. Fts3Table *p, /* Virtual table handle */
  162396. int iLangid, /* Language id */
  162397. int iIndex, /* Index for p->aIndex */
  162398. int iLevel, /* Level of %_segdir entries to delete */
  162399. Fts3SegReader **apSegment, /* Array of SegReader objects */
  162400. int nReader /* Size of array apSegment */
  162401. ){
  162402. int rc = SQLITE_OK; /* Return Code */
  162403. int i; /* Iterator variable */
  162404. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  162405. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  162406. rc = fts3DeleteSegment(p, apSegment[i]);
  162407. }
  162408. if( rc!=SQLITE_OK ){
  162409. return rc;
  162410. }
  162411. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  162412. if( iLevel==FTS3_SEGCURSOR_ALL ){
  162413. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  162414. if( rc==SQLITE_OK ){
  162415. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  162416. sqlite3_bind_int64(pDelete, 2,
  162417. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  162418. );
  162419. }
  162420. }else{
  162421. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  162422. if( rc==SQLITE_OK ){
  162423. sqlite3_bind_int64(
  162424. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  162425. );
  162426. }
  162427. }
  162428. if( rc==SQLITE_OK ){
  162429. sqlite3_step(pDelete);
  162430. rc = sqlite3_reset(pDelete);
  162431. }
  162432. return rc;
  162433. }
  162434. /*
  162435. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  162436. ** a position list that may (or may not) feature multiple columns. This
  162437. ** function adjusts the pointer *ppList and the length *pnList so that they
  162438. ** identify the subset of the position list that corresponds to column iCol.
  162439. **
  162440. ** If there are no entries in the input position list for column iCol, then
  162441. ** *pnList is set to zero before returning.
  162442. **
  162443. ** If parameter bZero is non-zero, then any part of the input list following
  162444. ** the end of the output list is zeroed before returning.
  162445. */
  162446. static void fts3ColumnFilter(
  162447. int iCol, /* Column to filter on */
  162448. int bZero, /* Zero out anything following *ppList */
  162449. char **ppList, /* IN/OUT: Pointer to position list */
  162450. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  162451. ){
  162452. char *pList = *ppList;
  162453. int nList = *pnList;
  162454. char *pEnd = &pList[nList];
  162455. int iCurrent = 0;
  162456. char *p = pList;
  162457. assert( iCol>=0 );
  162458. while( 1 ){
  162459. char c = 0;
  162460. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  162461. if( iCol==iCurrent ){
  162462. nList = (int)(p - pList);
  162463. break;
  162464. }
  162465. nList -= (int)(p - pList);
  162466. pList = p;
  162467. if( nList==0 ){
  162468. break;
  162469. }
  162470. p = &pList[1];
  162471. p += fts3GetVarint32(p, &iCurrent);
  162472. }
  162473. if( bZero && &pList[nList]!=pEnd ){
  162474. memset(&pList[nList], 0, pEnd - &pList[nList]);
  162475. }
  162476. *ppList = pList;
  162477. *pnList = nList;
  162478. }
  162479. /*
  162480. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  162481. ** existing data). Grow the buffer if required.
  162482. **
  162483. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  162484. ** trying to resize the buffer, return SQLITE_NOMEM.
  162485. */
  162486. static int fts3MsrBufferData(
  162487. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  162488. char *pList,
  162489. int nList
  162490. ){
  162491. if( nList>pMsr->nBuffer ){
  162492. char *pNew;
  162493. pMsr->nBuffer = nList*2;
  162494. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  162495. if( !pNew ) return SQLITE_NOMEM;
  162496. pMsr->aBuffer = pNew;
  162497. }
  162498. memcpy(pMsr->aBuffer, pList, nList);
  162499. return SQLITE_OK;
  162500. }
  162501. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  162502. Fts3Table *p, /* Virtual table handle */
  162503. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  162504. sqlite3_int64 *piDocid, /* OUT: Docid value */
  162505. char **paPoslist, /* OUT: Pointer to position list */
  162506. int *pnPoslist /* OUT: Size of position list in bytes */
  162507. ){
  162508. int nMerge = pMsr->nAdvance;
  162509. Fts3SegReader **apSegment = pMsr->apSegment;
  162510. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  162511. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  162512. );
  162513. if( nMerge==0 ){
  162514. *paPoslist = 0;
  162515. return SQLITE_OK;
  162516. }
  162517. while( 1 ){
  162518. Fts3SegReader *pSeg;
  162519. pSeg = pMsr->apSegment[0];
  162520. if( pSeg->pOffsetList==0 ){
  162521. *paPoslist = 0;
  162522. break;
  162523. }else{
  162524. int rc;
  162525. char *pList;
  162526. int nList;
  162527. int j;
  162528. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  162529. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  162530. j = 1;
  162531. while( rc==SQLITE_OK
  162532. && j<nMerge
  162533. && apSegment[j]->pOffsetList
  162534. && apSegment[j]->iDocid==iDocid
  162535. ){
  162536. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  162537. j++;
  162538. }
  162539. if( rc!=SQLITE_OK ) return rc;
  162540. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  162541. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  162542. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  162543. if( rc!=SQLITE_OK ) return rc;
  162544. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  162545. pList = pMsr->aBuffer;
  162546. }
  162547. if( pMsr->iColFilter>=0 ){
  162548. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  162549. }
  162550. if( nList>0 ){
  162551. *paPoslist = pList;
  162552. *piDocid = iDocid;
  162553. *pnPoslist = nList;
  162554. break;
  162555. }
  162556. }
  162557. }
  162558. return SQLITE_OK;
  162559. }
  162560. static int fts3SegReaderStart(
  162561. Fts3Table *p, /* Virtual table handle */
  162562. Fts3MultiSegReader *pCsr, /* Cursor object */
  162563. const char *zTerm, /* Term searched for (or NULL) */
  162564. int nTerm /* Length of zTerm in bytes */
  162565. ){
  162566. int i;
  162567. int nSeg = pCsr->nSegment;
  162568. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  162569. ** for, then advance each segment iterator until it points to a term of
  162570. ** equal or greater value than the specified term. This prevents many
  162571. ** unnecessary merge/sort operations for the case where single segment
  162572. ** b-tree leaf nodes contain more than one term.
  162573. */
  162574. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  162575. int res = 0;
  162576. Fts3SegReader *pSeg = pCsr->apSegment[i];
  162577. do {
  162578. int rc = fts3SegReaderNext(p, pSeg, 0);
  162579. if( rc!=SQLITE_OK ) return rc;
  162580. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  162581. if( pSeg->bLookup && res!=0 ){
  162582. fts3SegReaderSetEof(pSeg);
  162583. }
  162584. }
  162585. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  162586. return SQLITE_OK;
  162587. }
  162588. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  162589. Fts3Table *p, /* Virtual table handle */
  162590. Fts3MultiSegReader *pCsr, /* Cursor object */
  162591. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  162592. ){
  162593. pCsr->pFilter = pFilter;
  162594. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  162595. }
  162596. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  162597. Fts3Table *p, /* Virtual table handle */
  162598. Fts3MultiSegReader *pCsr, /* Cursor object */
  162599. int iCol, /* Column to match on. */
  162600. const char *zTerm, /* Term to iterate through a doclist for */
  162601. int nTerm /* Number of bytes in zTerm */
  162602. ){
  162603. int i;
  162604. int rc;
  162605. int nSegment = pCsr->nSegment;
  162606. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  162607. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  162608. );
  162609. assert( pCsr->pFilter==0 );
  162610. assert( zTerm && nTerm>0 );
  162611. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  162612. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  162613. if( rc!=SQLITE_OK ) return rc;
  162614. /* Determine how many of the segments actually point to zTerm/nTerm. */
  162615. for(i=0; i<nSegment; i++){
  162616. Fts3SegReader *pSeg = pCsr->apSegment[i];
  162617. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  162618. break;
  162619. }
  162620. }
  162621. pCsr->nAdvance = i;
  162622. /* Advance each of the segments to point to the first docid. */
  162623. for(i=0; i<pCsr->nAdvance; i++){
  162624. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  162625. if( rc!=SQLITE_OK ) return rc;
  162626. }
  162627. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  162628. assert( iCol<0 || iCol<p->nColumn );
  162629. pCsr->iColFilter = iCol;
  162630. return SQLITE_OK;
  162631. }
  162632. /*
  162633. ** This function is called on a MultiSegReader that has been started using
  162634. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  162635. ** have been made. Calling this function puts the MultiSegReader in such
  162636. ** a state that if the next two calls are:
  162637. **
  162638. ** sqlite3Fts3SegReaderStart()
  162639. ** sqlite3Fts3SegReaderStep()
  162640. **
  162641. ** then the entire doclist for the term is available in
  162642. ** MultiSegReader.aDoclist/nDoclist.
  162643. */
  162644. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  162645. int i; /* Used to iterate through segment-readers */
  162646. assert( pCsr->zTerm==0 );
  162647. assert( pCsr->nTerm==0 );
  162648. assert( pCsr->aDoclist==0 );
  162649. assert( pCsr->nDoclist==0 );
  162650. pCsr->nAdvance = 0;
  162651. pCsr->bRestart = 1;
  162652. for(i=0; i<pCsr->nSegment; i++){
  162653. pCsr->apSegment[i]->pOffsetList = 0;
  162654. pCsr->apSegment[i]->nOffsetList = 0;
  162655. pCsr->apSegment[i]->iDocid = 0;
  162656. }
  162657. return SQLITE_OK;
  162658. }
  162659. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  162660. Fts3Table *p, /* Virtual table handle */
  162661. Fts3MultiSegReader *pCsr /* Cursor object */
  162662. ){
  162663. int rc = SQLITE_OK;
  162664. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  162665. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  162666. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  162667. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  162668. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  162669. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  162670. Fts3SegReader **apSegment = pCsr->apSegment;
  162671. int nSegment = pCsr->nSegment;
  162672. Fts3SegFilter *pFilter = pCsr->pFilter;
  162673. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  162674. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  162675. );
  162676. if( pCsr->nSegment==0 ) return SQLITE_OK;
  162677. do {
  162678. int nMerge;
  162679. int i;
  162680. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  162681. ** forward. Then sort the list in order of current term again.
  162682. */
  162683. for(i=0; i<pCsr->nAdvance; i++){
  162684. Fts3SegReader *pSeg = apSegment[i];
  162685. if( pSeg->bLookup ){
  162686. fts3SegReaderSetEof(pSeg);
  162687. }else{
  162688. rc = fts3SegReaderNext(p, pSeg, 0);
  162689. }
  162690. if( rc!=SQLITE_OK ) return rc;
  162691. }
  162692. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  162693. pCsr->nAdvance = 0;
  162694. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  162695. assert( rc==SQLITE_OK );
  162696. if( apSegment[0]->aNode==0 ) break;
  162697. pCsr->nTerm = apSegment[0]->nTerm;
  162698. pCsr->zTerm = apSegment[0]->zTerm;
  162699. /* If this is a prefix-search, and if the term that apSegment[0] points
  162700. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  162701. ** required callbacks have been made. In this case exit early.
  162702. **
  162703. ** Similarly, if this is a search for an exact match, and the first term
  162704. ** of segment apSegment[0] is not a match, exit early.
  162705. */
  162706. if( pFilter->zTerm && !isScan ){
  162707. if( pCsr->nTerm<pFilter->nTerm
  162708. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  162709. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  162710. ){
  162711. break;
  162712. }
  162713. }
  162714. nMerge = 1;
  162715. while( nMerge<nSegment
  162716. && apSegment[nMerge]->aNode
  162717. && apSegment[nMerge]->nTerm==pCsr->nTerm
  162718. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  162719. ){
  162720. nMerge++;
  162721. }
  162722. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  162723. if( nMerge==1
  162724. && !isIgnoreEmpty
  162725. && !isFirst
  162726. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  162727. ){
  162728. pCsr->nDoclist = apSegment[0]->nDoclist;
  162729. if( fts3SegReaderIsPending(apSegment[0]) ){
  162730. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  162731. pCsr->aDoclist = pCsr->aBuffer;
  162732. }else{
  162733. pCsr->aDoclist = apSegment[0]->aDoclist;
  162734. }
  162735. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  162736. }else{
  162737. int nDoclist = 0; /* Size of doclist */
  162738. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  162739. /* The current term of the first nMerge entries in the array
  162740. ** of Fts3SegReader objects is the same. The doclists must be merged
  162741. ** and a single term returned with the merged doclist.
  162742. */
  162743. for(i=0; i<nMerge; i++){
  162744. fts3SegReaderFirstDocid(p, apSegment[i]);
  162745. }
  162746. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  162747. while( apSegment[0]->pOffsetList ){
  162748. int j; /* Number of segments that share a docid */
  162749. char *pList = 0;
  162750. int nList = 0;
  162751. int nByte;
  162752. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  162753. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  162754. j = 1;
  162755. while( j<nMerge
  162756. && apSegment[j]->pOffsetList
  162757. && apSegment[j]->iDocid==iDocid
  162758. ){
  162759. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  162760. j++;
  162761. }
  162762. if( isColFilter ){
  162763. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  162764. }
  162765. if( !isIgnoreEmpty || nList>0 ){
  162766. /* Calculate the 'docid' delta value to write into the merged
  162767. ** doclist. */
  162768. sqlite3_int64 iDelta;
  162769. if( p->bDescIdx && nDoclist>0 ){
  162770. iDelta = iPrev - iDocid;
  162771. }else{
  162772. iDelta = iDocid - iPrev;
  162773. }
  162774. if( iDelta<=0 && (nDoclist>0 || iDelta!=iDocid) ){
  162775. return FTS_CORRUPT_VTAB;
  162776. }
  162777. assert( nDoclist>0 || iDelta==iDocid );
  162778. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  162779. if( nDoclist+nByte>pCsr->nBuffer ){
  162780. char *aNew;
  162781. pCsr->nBuffer = (nDoclist+nByte)*2;
  162782. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  162783. if( !aNew ){
  162784. return SQLITE_NOMEM;
  162785. }
  162786. pCsr->aBuffer = aNew;
  162787. }
  162788. if( isFirst ){
  162789. char *a = &pCsr->aBuffer[nDoclist];
  162790. int nWrite;
  162791. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  162792. if( nWrite ){
  162793. iPrev = iDocid;
  162794. nDoclist += nWrite;
  162795. }
  162796. }else{
  162797. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  162798. iPrev = iDocid;
  162799. if( isRequirePos ){
  162800. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  162801. nDoclist += nList;
  162802. pCsr->aBuffer[nDoclist++] = '\0';
  162803. }
  162804. }
  162805. }
  162806. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  162807. }
  162808. if( nDoclist>0 ){
  162809. pCsr->aDoclist = pCsr->aBuffer;
  162810. pCsr->nDoclist = nDoclist;
  162811. rc = SQLITE_ROW;
  162812. }
  162813. }
  162814. pCsr->nAdvance = nMerge;
  162815. }while( rc==SQLITE_OK );
  162816. return rc;
  162817. }
  162818. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  162819. Fts3MultiSegReader *pCsr /* Cursor object */
  162820. ){
  162821. if( pCsr ){
  162822. int i;
  162823. for(i=0; i<pCsr->nSegment; i++){
  162824. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  162825. }
  162826. sqlite3_free(pCsr->apSegment);
  162827. sqlite3_free(pCsr->aBuffer);
  162828. pCsr->nSegment = 0;
  162829. pCsr->apSegment = 0;
  162830. pCsr->aBuffer = 0;
  162831. }
  162832. }
  162833. /*
  162834. ** Decode the "end_block" field, selected by column iCol of the SELECT
  162835. ** statement passed as the first argument.
  162836. **
  162837. ** The "end_block" field may contain either an integer, or a text field
  162838. ** containing the text representation of two non-negative integers separated
  162839. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  162840. ** to the integer value and *pnByte to zero before returning. In the second,
  162841. ** set *piEndBlock to the first value and *pnByte to the second.
  162842. */
  162843. static void fts3ReadEndBlockField(
  162844. sqlite3_stmt *pStmt,
  162845. int iCol,
  162846. i64 *piEndBlock,
  162847. i64 *pnByte
  162848. ){
  162849. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  162850. if( zText ){
  162851. int i;
  162852. int iMul = 1;
  162853. i64 iVal = 0;
  162854. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  162855. iVal = iVal*10 + (zText[i] - '0');
  162856. }
  162857. *piEndBlock = iVal;
  162858. while( zText[i]==' ' ) i++;
  162859. iVal = 0;
  162860. if( zText[i]=='-' ){
  162861. i++;
  162862. iMul = -1;
  162863. }
  162864. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  162865. iVal = iVal*10 + (zText[i] - '0');
  162866. }
  162867. *pnByte = (iVal * (i64)iMul);
  162868. }
  162869. }
  162870. /*
  162871. ** A segment of size nByte bytes has just been written to absolute level
  162872. ** iAbsLevel. Promote any segments that should be promoted as a result.
  162873. */
  162874. static int fts3PromoteSegments(
  162875. Fts3Table *p, /* FTS table handle */
  162876. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  162877. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  162878. ){
  162879. int rc = SQLITE_OK;
  162880. sqlite3_stmt *pRange;
  162881. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  162882. if( rc==SQLITE_OK ){
  162883. int bOk = 0;
  162884. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  162885. i64 nLimit = (nByte*3)/2;
  162886. /* Loop through all entries in the %_segdir table corresponding to
  162887. ** segments in this index on levels greater than iAbsLevel. If there is
  162888. ** at least one such segment, and it is possible to determine that all
  162889. ** such segments are smaller than nLimit bytes in size, they will be
  162890. ** promoted to level iAbsLevel. */
  162891. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  162892. sqlite3_bind_int64(pRange, 2, iLast);
  162893. while( SQLITE_ROW==sqlite3_step(pRange) ){
  162894. i64 nSize = 0, dummy;
  162895. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  162896. if( nSize<=0 || nSize>nLimit ){
  162897. /* If nSize==0, then the %_segdir.end_block field does not not
  162898. ** contain a size value. This happens if it was written by an
  162899. ** old version of FTS. In this case it is not possible to determine
  162900. ** the size of the segment, and so segment promotion does not
  162901. ** take place. */
  162902. bOk = 0;
  162903. break;
  162904. }
  162905. bOk = 1;
  162906. }
  162907. rc = sqlite3_reset(pRange);
  162908. if( bOk ){
  162909. int iIdx = 0;
  162910. sqlite3_stmt *pUpdate1 = 0;
  162911. sqlite3_stmt *pUpdate2 = 0;
  162912. if( rc==SQLITE_OK ){
  162913. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  162914. }
  162915. if( rc==SQLITE_OK ){
  162916. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  162917. }
  162918. if( rc==SQLITE_OK ){
  162919. /* Loop through all %_segdir entries for segments in this index with
  162920. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  162921. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  162922. ** oldest segment in the range, 1 for the next oldest, and so on.
  162923. **
  162924. ** In other words, move all segments being promoted to level -1,
  162925. ** setting the "idx" fields as appropriate to keep them in the same
  162926. ** order. The contents of level -1 (which is never used, except
  162927. ** transiently here), will be moved back to level iAbsLevel below. */
  162928. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  162929. while( SQLITE_ROW==sqlite3_step(pRange) ){
  162930. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  162931. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  162932. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  162933. sqlite3_step(pUpdate1);
  162934. rc = sqlite3_reset(pUpdate1);
  162935. if( rc!=SQLITE_OK ){
  162936. sqlite3_reset(pRange);
  162937. break;
  162938. }
  162939. }
  162940. }
  162941. if( rc==SQLITE_OK ){
  162942. rc = sqlite3_reset(pRange);
  162943. }
  162944. /* Move level -1 to level iAbsLevel */
  162945. if( rc==SQLITE_OK ){
  162946. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  162947. sqlite3_step(pUpdate2);
  162948. rc = sqlite3_reset(pUpdate2);
  162949. }
  162950. }
  162951. }
  162952. return rc;
  162953. }
  162954. /*
  162955. ** Merge all level iLevel segments in the database into a single
  162956. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  162957. ** single segment with a level equal to the numerically largest level
  162958. ** currently present in the database.
  162959. **
  162960. ** If this function is called with iLevel<0, but there is only one
  162961. ** segment in the database, SQLITE_DONE is returned immediately.
  162962. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  162963. ** an SQLite error code is returned.
  162964. */
  162965. static int fts3SegmentMerge(
  162966. Fts3Table *p,
  162967. int iLangid, /* Language id to merge */
  162968. int iIndex, /* Index in p->aIndex[] to merge */
  162969. int iLevel /* Level to merge */
  162970. ){
  162971. int rc; /* Return code */
  162972. int iIdx = 0; /* Index of new segment */
  162973. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  162974. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  162975. Fts3SegFilter filter; /* Segment term filter condition */
  162976. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  162977. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  162978. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  162979. assert( iLevel==FTS3_SEGCURSOR_ALL
  162980. || iLevel==FTS3_SEGCURSOR_PENDING
  162981. || iLevel>=0
  162982. );
  162983. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  162984. assert( iIndex>=0 && iIndex<p->nIndex );
  162985. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  162986. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  162987. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  162988. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  162989. if( rc!=SQLITE_OK ) goto finished;
  162990. }
  162991. if( iLevel==FTS3_SEGCURSOR_ALL ){
  162992. /* This call is to merge all segments in the database to a single
  162993. ** segment. The level of the new segment is equal to the numerically
  162994. ** greatest segment level currently present in the database for this
  162995. ** index. The idx of the new segment is always 0. */
  162996. if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
  162997. rc = SQLITE_DONE;
  162998. goto finished;
  162999. }
  163000. iNewLevel = iMaxLevel;
  163001. bIgnoreEmpty = 1;
  163002. }else{
  163003. /* This call is to merge all segments at level iLevel. find the next
  163004. ** available segment index at level iLevel+1. The call to
  163005. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  163006. ** a single iLevel+2 segment if necessary. */
  163007. assert( FTS3_SEGCURSOR_PENDING==-1 );
  163008. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  163009. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  163010. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  163011. }
  163012. if( rc!=SQLITE_OK ) goto finished;
  163013. assert( csr.nSegment>0 );
  163014. assert_fts3_nc( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  163015. assert_fts3_nc(
  163016. iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL)
  163017. );
  163018. memset(&filter, 0, sizeof(Fts3SegFilter));
  163019. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  163020. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  163021. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  163022. while( SQLITE_OK==rc ){
  163023. rc = sqlite3Fts3SegReaderStep(p, &csr);
  163024. if( rc!=SQLITE_ROW ) break;
  163025. rc = fts3SegWriterAdd(p, &pWriter, 1,
  163026. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  163027. }
  163028. if( rc!=SQLITE_OK ) goto finished;
  163029. assert( pWriter || bIgnoreEmpty );
  163030. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  163031. rc = fts3DeleteSegdir(
  163032. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  163033. );
  163034. if( rc!=SQLITE_OK ) goto finished;
  163035. }
  163036. if( pWriter ){
  163037. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  163038. if( rc==SQLITE_OK ){
  163039. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  163040. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  163041. }
  163042. }
  163043. }
  163044. finished:
  163045. fts3SegWriterFree(pWriter);
  163046. sqlite3Fts3SegReaderFinish(&csr);
  163047. return rc;
  163048. }
  163049. /*
  163050. ** Flush the contents of pendingTerms to level 0 segments.
  163051. */
  163052. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  163053. int rc = SQLITE_OK;
  163054. int i;
  163055. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  163056. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  163057. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  163058. }
  163059. sqlite3Fts3PendingTermsClear(p);
  163060. /* Determine the auto-incr-merge setting if unknown. If enabled,
  163061. ** estimate the number of leaf blocks of content to be written
  163062. */
  163063. if( rc==SQLITE_OK && p->bHasStat
  163064. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  163065. ){
  163066. sqlite3_stmt *pStmt = 0;
  163067. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  163068. if( rc==SQLITE_OK ){
  163069. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  163070. rc = sqlite3_step(pStmt);
  163071. if( rc==SQLITE_ROW ){
  163072. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  163073. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  163074. }else if( rc==SQLITE_DONE ){
  163075. p->nAutoincrmerge = 0;
  163076. }
  163077. rc = sqlite3_reset(pStmt);
  163078. }
  163079. }
  163080. return rc;
  163081. }
  163082. /*
  163083. ** Encode N integers as varints into a blob.
  163084. */
  163085. static void fts3EncodeIntArray(
  163086. int N, /* The number of integers to encode */
  163087. u32 *a, /* The integer values */
  163088. char *zBuf, /* Write the BLOB here */
  163089. int *pNBuf /* Write number of bytes if zBuf[] used here */
  163090. ){
  163091. int i, j;
  163092. for(i=j=0; i<N; i++){
  163093. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  163094. }
  163095. *pNBuf = j;
  163096. }
  163097. /*
  163098. ** Decode a blob of varints into N integers
  163099. */
  163100. static void fts3DecodeIntArray(
  163101. int N, /* The number of integers to decode */
  163102. u32 *a, /* Write the integer values */
  163103. const char *zBuf, /* The BLOB containing the varints */
  163104. int nBuf /* size of the BLOB */
  163105. ){
  163106. int i = 0;
  163107. if( nBuf && (zBuf[nBuf-1]&0x80)==0 ){
  163108. int j;
  163109. for(i=j=0; i<N && j<nBuf; i++){
  163110. sqlite3_int64 x;
  163111. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  163112. a[i] = (u32)(x & 0xffffffff);
  163113. }
  163114. }
  163115. while( i<N ) a[i++] = 0;
  163116. }
  163117. /*
  163118. ** Insert the sizes (in tokens) for each column of the document
  163119. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  163120. ** a blob of varints.
  163121. */
  163122. static void fts3InsertDocsize(
  163123. int *pRC, /* Result code */
  163124. Fts3Table *p, /* Table into which to insert */
  163125. u32 *aSz /* Sizes of each column, in tokens */
  163126. ){
  163127. char *pBlob; /* The BLOB encoding of the document size */
  163128. int nBlob; /* Number of bytes in the BLOB */
  163129. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  163130. int rc; /* Result code from subfunctions */
  163131. if( *pRC ) return;
  163132. pBlob = sqlite3_malloc64( 10*(sqlite3_int64)p->nColumn );
  163133. if( pBlob==0 ){
  163134. *pRC = SQLITE_NOMEM;
  163135. return;
  163136. }
  163137. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  163138. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  163139. if( rc ){
  163140. sqlite3_free(pBlob);
  163141. *pRC = rc;
  163142. return;
  163143. }
  163144. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  163145. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  163146. sqlite3_step(pStmt);
  163147. *pRC = sqlite3_reset(pStmt);
  163148. }
  163149. /*
  163150. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  163151. ** where N is the number of user defined columns in the fts3 table plus
  163152. ** two. If nCol is the number of user defined columns, then values of the
  163153. ** varints are set as follows:
  163154. **
  163155. ** Varint 0: Total number of rows in the table.
  163156. **
  163157. ** Varint 1..nCol: For each column, the total number of tokens stored in
  163158. ** the column for all rows of the table.
  163159. **
  163160. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  163161. ** columns of all rows of the table.
  163162. **
  163163. */
  163164. static void fts3UpdateDocTotals(
  163165. int *pRC, /* The result code */
  163166. Fts3Table *p, /* Table being updated */
  163167. u32 *aSzIns, /* Size increases */
  163168. u32 *aSzDel, /* Size decreases */
  163169. int nChng /* Change in the number of documents */
  163170. ){
  163171. char *pBlob; /* Storage for BLOB written into %_stat */
  163172. int nBlob; /* Size of BLOB written into %_stat */
  163173. u32 *a; /* Array of integers that becomes the BLOB */
  163174. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  163175. int i; /* Loop counter */
  163176. int rc; /* Result code from subfunctions */
  163177. const int nStat = p->nColumn+2;
  163178. if( *pRC ) return;
  163179. a = sqlite3_malloc64( (sizeof(u32)+10)*(sqlite3_int64)nStat );
  163180. if( a==0 ){
  163181. *pRC = SQLITE_NOMEM;
  163182. return;
  163183. }
  163184. pBlob = (char*)&a[nStat];
  163185. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  163186. if( rc ){
  163187. sqlite3_free(a);
  163188. *pRC = rc;
  163189. return;
  163190. }
  163191. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  163192. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  163193. fts3DecodeIntArray(nStat, a,
  163194. sqlite3_column_blob(pStmt, 0),
  163195. sqlite3_column_bytes(pStmt, 0));
  163196. }else{
  163197. memset(a, 0, sizeof(u32)*(nStat) );
  163198. }
  163199. rc = sqlite3_reset(pStmt);
  163200. if( rc!=SQLITE_OK ){
  163201. sqlite3_free(a);
  163202. *pRC = rc;
  163203. return;
  163204. }
  163205. if( nChng<0 && a[0]<(u32)(-nChng) ){
  163206. a[0] = 0;
  163207. }else{
  163208. a[0] += nChng;
  163209. }
  163210. for(i=0; i<p->nColumn+1; i++){
  163211. u32 x = a[i+1];
  163212. if( x+aSzIns[i] < aSzDel[i] ){
  163213. x = 0;
  163214. }else{
  163215. x = x + aSzIns[i] - aSzDel[i];
  163216. }
  163217. a[i+1] = x;
  163218. }
  163219. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  163220. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  163221. if( rc ){
  163222. sqlite3_free(a);
  163223. *pRC = rc;
  163224. return;
  163225. }
  163226. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  163227. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  163228. sqlite3_step(pStmt);
  163229. *pRC = sqlite3_reset(pStmt);
  163230. sqlite3_bind_null(pStmt, 2);
  163231. sqlite3_free(a);
  163232. }
  163233. /*
  163234. ** Merge the entire database so that there is one segment for each
  163235. ** iIndex/iLangid combination.
  163236. */
  163237. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  163238. int bSeenDone = 0;
  163239. int rc;
  163240. sqlite3_stmt *pAllLangid = 0;
  163241. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  163242. if( rc==SQLITE_OK ){
  163243. int rc2;
  163244. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  163245. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  163246. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  163247. int i;
  163248. int iLangid = sqlite3_column_int(pAllLangid, 0);
  163249. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  163250. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  163251. if( rc==SQLITE_DONE ){
  163252. bSeenDone = 1;
  163253. rc = SQLITE_OK;
  163254. }
  163255. }
  163256. }
  163257. rc2 = sqlite3_reset(pAllLangid);
  163258. if( rc==SQLITE_OK ) rc = rc2;
  163259. }
  163260. sqlite3Fts3SegmentsClose(p);
  163261. sqlite3Fts3PendingTermsClear(p);
  163262. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  163263. }
  163264. /*
  163265. ** This function is called when the user executes the following statement:
  163266. **
  163267. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  163268. **
  163269. ** The entire FTS index is discarded and rebuilt. If the table is one
  163270. ** created using the content=xxx option, then the new index is based on
  163271. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  163272. ** on the contents of the %_content table.
  163273. */
  163274. static int fts3DoRebuild(Fts3Table *p){
  163275. int rc; /* Return Code */
  163276. rc = fts3DeleteAll(p, 0);
  163277. if( rc==SQLITE_OK ){
  163278. u32 *aSz = 0;
  163279. u32 *aSzIns = 0;
  163280. u32 *aSzDel = 0;
  163281. sqlite3_stmt *pStmt = 0;
  163282. int nEntry = 0;
  163283. /* Compose and prepare an SQL statement to loop through the content table */
  163284. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  163285. if( !zSql ){
  163286. rc = SQLITE_NOMEM;
  163287. }else{
  163288. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  163289. sqlite3_free(zSql);
  163290. }
  163291. if( rc==SQLITE_OK ){
  163292. sqlite3_int64 nByte = sizeof(u32) * ((sqlite3_int64)p->nColumn+1)*3;
  163293. aSz = (u32 *)sqlite3_malloc64(nByte);
  163294. if( aSz==0 ){
  163295. rc = SQLITE_NOMEM;
  163296. }else{
  163297. memset(aSz, 0, nByte);
  163298. aSzIns = &aSz[p->nColumn+1];
  163299. aSzDel = &aSzIns[p->nColumn+1];
  163300. }
  163301. }
  163302. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  163303. int iCol;
  163304. int iLangid = langidFromSelect(p, pStmt);
  163305. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  163306. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  163307. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  163308. if( p->abNotindexed[iCol]==0 ){
  163309. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  163310. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  163311. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  163312. }
  163313. }
  163314. if( p->bHasDocsize ){
  163315. fts3InsertDocsize(&rc, p, aSz);
  163316. }
  163317. if( rc!=SQLITE_OK ){
  163318. sqlite3_finalize(pStmt);
  163319. pStmt = 0;
  163320. }else{
  163321. nEntry++;
  163322. for(iCol=0; iCol<=p->nColumn; iCol++){
  163323. aSzIns[iCol] += aSz[iCol];
  163324. }
  163325. }
  163326. }
  163327. if( p->bFts4 ){
  163328. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  163329. }
  163330. sqlite3_free(aSz);
  163331. if( pStmt ){
  163332. int rc2 = sqlite3_finalize(pStmt);
  163333. if( rc==SQLITE_OK ){
  163334. rc = rc2;
  163335. }
  163336. }
  163337. }
  163338. return rc;
  163339. }
  163340. /*
  163341. ** This function opens a cursor used to read the input data for an
  163342. ** incremental merge operation. Specifically, it opens a cursor to scan
  163343. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  163344. ** level iAbsLevel.
  163345. */
  163346. static int fts3IncrmergeCsr(
  163347. Fts3Table *p, /* FTS3 table handle */
  163348. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  163349. int nSeg, /* Number of segments to merge */
  163350. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  163351. ){
  163352. int rc; /* Return Code */
  163353. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  163354. sqlite3_int64 nByte; /* Bytes allocated at pCsr->apSegment[] */
  163355. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  163356. memset(pCsr, 0, sizeof(*pCsr));
  163357. nByte = sizeof(Fts3SegReader *) * nSeg;
  163358. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc64(nByte);
  163359. if( pCsr->apSegment==0 ){
  163360. rc = SQLITE_NOMEM;
  163361. }else{
  163362. memset(pCsr->apSegment, 0, nByte);
  163363. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  163364. }
  163365. if( rc==SQLITE_OK ){
  163366. int i;
  163367. int rc2;
  163368. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  163369. assert( pCsr->nSegment==0 );
  163370. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  163371. rc = sqlite3Fts3SegReaderNew(i, 0,
  163372. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  163373. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  163374. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  163375. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  163376. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  163377. &pCsr->apSegment[i]
  163378. );
  163379. pCsr->nSegment++;
  163380. }
  163381. rc2 = sqlite3_reset(pStmt);
  163382. if( rc==SQLITE_OK ) rc = rc2;
  163383. }
  163384. return rc;
  163385. }
  163386. typedef struct IncrmergeWriter IncrmergeWriter;
  163387. typedef struct NodeWriter NodeWriter;
  163388. typedef struct Blob Blob;
  163389. typedef struct NodeReader NodeReader;
  163390. /*
  163391. ** An instance of the following structure is used as a dynamic buffer
  163392. ** to build up nodes or other blobs of data in.
  163393. **
  163394. ** The function blobGrowBuffer() is used to extend the allocation.
  163395. */
  163396. struct Blob {
  163397. char *a; /* Pointer to allocation */
  163398. int n; /* Number of valid bytes of data in a[] */
  163399. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  163400. };
  163401. /*
  163402. ** This structure is used to build up buffers containing segment b-tree
  163403. ** nodes (blocks).
  163404. */
  163405. struct NodeWriter {
  163406. sqlite3_int64 iBlock; /* Current block id */
  163407. Blob key; /* Last key written to the current block */
  163408. Blob block; /* Current block image */
  163409. };
  163410. /*
  163411. ** An object of this type contains the state required to create or append
  163412. ** to an appendable b-tree segment.
  163413. */
  163414. struct IncrmergeWriter {
  163415. int nLeafEst; /* Space allocated for leaf blocks */
  163416. int nWork; /* Number of leaf pages flushed */
  163417. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  163418. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  163419. sqlite3_int64 iStart; /* Block number of first allocated block */
  163420. sqlite3_int64 iEnd; /* Block number of last allocated block */
  163421. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  163422. u8 bNoLeafData; /* If true, store 0 for segment size */
  163423. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  163424. };
  163425. /*
  163426. ** An object of the following type is used to read data from a single
  163427. ** FTS segment node. See the following functions:
  163428. **
  163429. ** nodeReaderInit()
  163430. ** nodeReaderNext()
  163431. ** nodeReaderRelease()
  163432. */
  163433. struct NodeReader {
  163434. const char *aNode;
  163435. int nNode;
  163436. int iOff; /* Current offset within aNode[] */
  163437. /* Output variables. Containing the current node entry. */
  163438. sqlite3_int64 iChild; /* Pointer to child node */
  163439. Blob term; /* Current term */
  163440. const char *aDoclist; /* Pointer to doclist */
  163441. int nDoclist; /* Size of doclist in bytes */
  163442. };
  163443. /*
  163444. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  163445. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  163446. ** bytes in size, extend (realloc) it to be so.
  163447. **
  163448. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  163449. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  163450. ** to reflect the new size of the pBlob->a[] buffer.
  163451. */
  163452. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  163453. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  163454. int nAlloc = nMin;
  163455. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  163456. if( a ){
  163457. pBlob->nAlloc = nAlloc;
  163458. pBlob->a = a;
  163459. }else{
  163460. *pRc = SQLITE_NOMEM;
  163461. }
  163462. }
  163463. }
  163464. /*
  163465. ** Attempt to advance the node-reader object passed as the first argument to
  163466. ** the next entry on the node.
  163467. **
  163468. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  163469. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  163470. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  163471. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  163472. ** variables for the new entry.
  163473. */
  163474. static int nodeReaderNext(NodeReader *p){
  163475. int bFirst = (p->term.n==0); /* True for first term on the node */
  163476. int nPrefix = 0; /* Bytes to copy from previous term */
  163477. int nSuffix = 0; /* Bytes to append to the prefix */
  163478. int rc = SQLITE_OK; /* Return code */
  163479. assert( p->aNode );
  163480. if( p->iChild && bFirst==0 ) p->iChild++;
  163481. if( p->iOff>=p->nNode ){
  163482. /* EOF */
  163483. p->aNode = 0;
  163484. }else{
  163485. if( bFirst==0 ){
  163486. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  163487. }
  163488. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  163489. if( nPrefix>p->iOff || nSuffix>p->nNode-p->iOff ){
  163490. return FTS_CORRUPT_VTAB;
  163491. }
  163492. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  163493. if( rc==SQLITE_OK ){
  163494. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  163495. p->term.n = nPrefix+nSuffix;
  163496. p->iOff += nSuffix;
  163497. if( p->iChild==0 ){
  163498. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  163499. if( (p->nNode-p->iOff)<p->nDoclist ){
  163500. return FTS_CORRUPT_VTAB;
  163501. }
  163502. p->aDoclist = &p->aNode[p->iOff];
  163503. p->iOff += p->nDoclist;
  163504. }
  163505. }
  163506. }
  163507. assert( p->iOff<=p->nNode );
  163508. return rc;
  163509. }
  163510. /*
  163511. ** Release all dynamic resources held by node-reader object *p.
  163512. */
  163513. static void nodeReaderRelease(NodeReader *p){
  163514. sqlite3_free(p->term.a);
  163515. }
  163516. /*
  163517. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  163518. **
  163519. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  163520. ** point to the first entry on the node (if any). Otherwise, an SQLite
  163521. ** error code is returned.
  163522. */
  163523. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  163524. memset(p, 0, sizeof(NodeReader));
  163525. p->aNode = aNode;
  163526. p->nNode = nNode;
  163527. /* Figure out if this is a leaf or an internal node. */
  163528. if( p->aNode[0] ){
  163529. /* An internal node. */
  163530. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  163531. }else{
  163532. p->iOff = 1;
  163533. }
  163534. return nodeReaderNext(p);
  163535. }
  163536. /*
  163537. ** This function is called while writing an FTS segment each time a leaf o
  163538. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  163539. ** to be greater than the largest key on the node just written, but smaller
  163540. ** than or equal to the first key that will be written to the next leaf
  163541. ** node.
  163542. **
  163543. ** The block id of the leaf node just written to disk may be found in
  163544. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  163545. */
  163546. static int fts3IncrmergePush(
  163547. Fts3Table *p, /* Fts3 table handle */
  163548. IncrmergeWriter *pWriter, /* Writer object */
  163549. const char *zTerm, /* Term to write to internal node */
  163550. int nTerm /* Bytes at zTerm */
  163551. ){
  163552. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  163553. int iLayer;
  163554. assert( nTerm>0 );
  163555. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  163556. sqlite3_int64 iNextPtr = 0;
  163557. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  163558. int rc = SQLITE_OK;
  163559. int nPrefix;
  163560. int nSuffix;
  163561. int nSpace;
  163562. /* Figure out how much space the key will consume if it is written to
  163563. ** the current node of layer iLayer. Due to the prefix compression,
  163564. ** the space required changes depending on which node the key is to
  163565. ** be added to. */
  163566. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  163567. nSuffix = nTerm - nPrefix;
  163568. nSpace = sqlite3Fts3VarintLen(nPrefix);
  163569. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  163570. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  163571. /* If the current node of layer iLayer contains zero keys, or if adding
  163572. ** the key to it will not cause it to grow to larger than nNodeSize
  163573. ** bytes in size, write the key here. */
  163574. Blob *pBlk = &pNode->block;
  163575. if( pBlk->n==0 ){
  163576. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  163577. if( rc==SQLITE_OK ){
  163578. pBlk->a[0] = (char)iLayer;
  163579. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  163580. }
  163581. }
  163582. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  163583. blobGrowBuffer(&pNode->key, nTerm, &rc);
  163584. if( rc==SQLITE_OK ){
  163585. if( pNode->key.n ){
  163586. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  163587. }
  163588. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  163589. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  163590. pBlk->n += nSuffix;
  163591. memcpy(pNode->key.a, zTerm, nTerm);
  163592. pNode->key.n = nTerm;
  163593. }
  163594. }else{
  163595. /* Otherwise, flush the current node of layer iLayer to disk.
  163596. ** Then allocate a new, empty sibling node. The key will be written
  163597. ** into the parent of this node. */
  163598. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  163599. assert( pNode->block.nAlloc>=p->nNodeSize );
  163600. pNode->block.a[0] = (char)iLayer;
  163601. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  163602. iNextPtr = pNode->iBlock;
  163603. pNode->iBlock++;
  163604. pNode->key.n = 0;
  163605. }
  163606. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  163607. iPtr = iNextPtr;
  163608. }
  163609. assert( 0 );
  163610. return 0;
  163611. }
  163612. /*
  163613. ** Append a term and (optionally) doclist to the FTS segment node currently
  163614. ** stored in blob *pNode. The node need not contain any terms, but the
  163615. ** header must be written before this function is called.
  163616. **
  163617. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  163618. ** followed by the left-hand-child varint for an internal node.
  163619. **
  163620. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  163621. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  163622. ** node, both aDoclist and nDoclist must be passed 0.
  163623. **
  163624. ** If the size of the value in blob pPrev is zero, then this is the first
  163625. ** term written to the node. Otherwise, pPrev contains a copy of the
  163626. ** previous term. Before this function returns, it is updated to contain a
  163627. ** copy of zTerm/nTerm.
  163628. **
  163629. ** It is assumed that the buffer associated with pNode is already large
  163630. ** enough to accommodate the new entry. The buffer associated with pPrev
  163631. ** is extended by this function if requrired.
  163632. **
  163633. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  163634. ** returned. Otherwise, SQLITE_OK.
  163635. */
  163636. static int fts3AppendToNode(
  163637. Blob *pNode, /* Current node image to append to */
  163638. Blob *pPrev, /* Buffer containing previous term written */
  163639. const char *zTerm, /* New term to write */
  163640. int nTerm, /* Size of zTerm in bytes */
  163641. const char *aDoclist, /* Doclist (or NULL) to write */
  163642. int nDoclist /* Size of aDoclist in bytes */
  163643. ){
  163644. int rc = SQLITE_OK; /* Return code */
  163645. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  163646. int nPrefix; /* Size of term prefix in bytes */
  163647. int nSuffix; /* Size of term suffix in bytes */
  163648. /* Node must have already been started. There must be a doclist for a
  163649. ** leaf node, and there must not be a doclist for an internal node. */
  163650. assert( pNode->n>0 );
  163651. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  163652. blobGrowBuffer(pPrev, nTerm, &rc);
  163653. if( rc!=SQLITE_OK ) return rc;
  163654. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  163655. nSuffix = nTerm - nPrefix;
  163656. memcpy(pPrev->a, zTerm, nTerm);
  163657. pPrev->n = nTerm;
  163658. if( bFirst==0 ){
  163659. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  163660. }
  163661. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  163662. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  163663. pNode->n += nSuffix;
  163664. if( aDoclist ){
  163665. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  163666. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  163667. pNode->n += nDoclist;
  163668. }
  163669. assert( pNode->n<=pNode->nAlloc );
  163670. return SQLITE_OK;
  163671. }
  163672. /*
  163673. ** Append the current term and doclist pointed to by cursor pCsr to the
  163674. ** appendable b-tree segment opened for writing by pWriter.
  163675. **
  163676. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  163677. */
  163678. static int fts3IncrmergeAppend(
  163679. Fts3Table *p, /* Fts3 table handle */
  163680. IncrmergeWriter *pWriter, /* Writer object */
  163681. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  163682. ){
  163683. const char *zTerm = pCsr->zTerm;
  163684. int nTerm = pCsr->nTerm;
  163685. const char *aDoclist = pCsr->aDoclist;
  163686. int nDoclist = pCsr->nDoclist;
  163687. int rc = SQLITE_OK; /* Return code */
  163688. int nSpace; /* Total space in bytes required on leaf */
  163689. int nPrefix; /* Size of prefix shared with previous term */
  163690. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  163691. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  163692. pLeaf = &pWriter->aNodeWriter[0];
  163693. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  163694. nSuffix = nTerm - nPrefix;
  163695. nSpace = sqlite3Fts3VarintLen(nPrefix);
  163696. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  163697. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  163698. /* If the current block is not empty, and if adding this term/doclist
  163699. ** to the current block would make it larger than Fts3Table.nNodeSize
  163700. ** bytes, write this block out to the database. */
  163701. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  163702. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  163703. pWriter->nWork++;
  163704. /* Add the current term to the parent node. The term added to the
  163705. ** parent must:
  163706. **
  163707. ** a) be greater than the largest term on the leaf node just written
  163708. ** to the database (still available in pLeaf->key), and
  163709. **
  163710. ** b) be less than or equal to the term about to be added to the new
  163711. ** leaf node (zTerm/nTerm).
  163712. **
  163713. ** In other words, it must be the prefix of zTerm 1 byte longer than
  163714. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  163715. */
  163716. if( rc==SQLITE_OK ){
  163717. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  163718. }
  163719. /* Advance to the next output block */
  163720. pLeaf->iBlock++;
  163721. pLeaf->key.n = 0;
  163722. pLeaf->block.n = 0;
  163723. nSuffix = nTerm;
  163724. nSpace = 1;
  163725. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  163726. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  163727. }
  163728. pWriter->nLeafData += nSpace;
  163729. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  163730. if( rc==SQLITE_OK ){
  163731. if( pLeaf->block.n==0 ){
  163732. pLeaf->block.n = 1;
  163733. pLeaf->block.a[0] = '\0';
  163734. }
  163735. rc = fts3AppendToNode(
  163736. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  163737. );
  163738. }
  163739. return rc;
  163740. }
  163741. /*
  163742. ** This function is called to release all dynamic resources held by the
  163743. ** merge-writer object pWriter, and if no error has occurred, to flush
  163744. ** all outstanding node buffers held by pWriter to disk.
  163745. **
  163746. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  163747. ** is made to write any data to disk. Instead, this function serves only
  163748. ** to release outstanding resources.
  163749. **
  163750. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  163751. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  163752. ** returning.
  163753. */
  163754. static void fts3IncrmergeRelease(
  163755. Fts3Table *p, /* FTS3 table handle */
  163756. IncrmergeWriter *pWriter, /* Merge-writer object */
  163757. int *pRc /* IN/OUT: Error code */
  163758. ){
  163759. int i; /* Used to iterate through non-root layers */
  163760. int iRoot; /* Index of root in pWriter->aNodeWriter */
  163761. NodeWriter *pRoot; /* NodeWriter for root node */
  163762. int rc = *pRc; /* Error code */
  163763. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  163764. ** root node. If the segment fits entirely on a single leaf node, iRoot
  163765. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  163766. ** will be 1. And so on. */
  163767. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  163768. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  163769. if( pNode->block.n>0 ) break;
  163770. assert( *pRc || pNode->block.nAlloc==0 );
  163771. assert( *pRc || pNode->key.nAlloc==0 );
  163772. sqlite3_free(pNode->block.a);
  163773. sqlite3_free(pNode->key.a);
  163774. }
  163775. /* Empty output segment. This is a no-op. */
  163776. if( iRoot<0 ) return;
  163777. /* The entire output segment fits on a single node. Normally, this means
  163778. ** the node would be stored as a blob in the "root" column of the %_segdir
  163779. ** table. However, this is not permitted in this case. The problem is that
  163780. ** space has already been reserved in the %_segments table, and so the
  163781. ** start_block and end_block fields of the %_segdir table must be populated.
  163782. ** And, by design or by accident, released versions of FTS cannot handle
  163783. ** segments that fit entirely on the root node with start_block!=0.
  163784. **
  163785. ** Instead, create a synthetic root node that contains nothing but a
  163786. ** pointer to the single content node. So that the segment consists of a
  163787. ** single leaf and a single interior (root) node.
  163788. **
  163789. ** Todo: Better might be to defer allocating space in the %_segments
  163790. ** table until we are sure it is needed.
  163791. */
  163792. if( iRoot==0 ){
  163793. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  163794. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  163795. if( rc==SQLITE_OK ){
  163796. pBlock->a[0] = 0x01;
  163797. pBlock->n = 1 + sqlite3Fts3PutVarint(
  163798. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  163799. );
  163800. }
  163801. iRoot = 1;
  163802. }
  163803. pRoot = &pWriter->aNodeWriter[iRoot];
  163804. /* Flush all currently outstanding nodes to disk. */
  163805. for(i=0; i<iRoot; i++){
  163806. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  163807. if( pNode->block.n>0 && rc==SQLITE_OK ){
  163808. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  163809. }
  163810. sqlite3_free(pNode->block.a);
  163811. sqlite3_free(pNode->key.a);
  163812. }
  163813. /* Write the %_segdir record. */
  163814. if( rc==SQLITE_OK ){
  163815. rc = fts3WriteSegdir(p,
  163816. pWriter->iAbsLevel+1, /* level */
  163817. pWriter->iIdx, /* idx */
  163818. pWriter->iStart, /* start_block */
  163819. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  163820. pWriter->iEnd, /* end_block */
  163821. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  163822. pRoot->block.a, pRoot->block.n /* root */
  163823. );
  163824. }
  163825. sqlite3_free(pRoot->block.a);
  163826. sqlite3_free(pRoot->key.a);
  163827. *pRc = rc;
  163828. }
  163829. /*
  163830. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  163831. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  163832. ** the other, it is considered to be smaller than the other.
  163833. **
  163834. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  163835. ** if it is greater.
  163836. */
  163837. static int fts3TermCmp(
  163838. const char *zLhs, int nLhs, /* LHS of comparison */
  163839. const char *zRhs, int nRhs /* RHS of comparison */
  163840. ){
  163841. int nCmp = MIN(nLhs, nRhs);
  163842. int res;
  163843. res = memcmp(zLhs, zRhs, nCmp);
  163844. if( res==0 ) res = nLhs - nRhs;
  163845. return res;
  163846. }
  163847. /*
  163848. ** Query to see if the entry in the %_segments table with blockid iEnd is
  163849. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  163850. ** returning. Otherwise, set *pbRes to 0.
  163851. **
  163852. ** Or, if an error occurs while querying the database, return an SQLite
  163853. ** error code. The final value of *pbRes is undefined in this case.
  163854. **
  163855. ** This is used to test if a segment is an "appendable" segment. If it
  163856. ** is, then a NULL entry has been inserted into the %_segments table
  163857. ** with blockid %_segdir.end_block.
  163858. */
  163859. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  163860. int bRes = 0; /* Result to set *pbRes to */
  163861. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  163862. int rc; /* Return code */
  163863. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  163864. if( rc==SQLITE_OK ){
  163865. sqlite3_bind_int64(pCheck, 1, iEnd);
  163866. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  163867. rc = sqlite3_reset(pCheck);
  163868. }
  163869. *pbRes = bRes;
  163870. return rc;
  163871. }
  163872. /*
  163873. ** This function is called when initializing an incremental-merge operation.
  163874. ** It checks if the existing segment with index value iIdx at absolute level
  163875. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  163876. ** merge-writer object *pWriter is initialized to write to it.
  163877. **
  163878. ** An existing segment can be appended to by an incremental merge if:
  163879. **
  163880. ** * It was initially created as an appendable segment (with all required
  163881. ** space pre-allocated), and
  163882. **
  163883. ** * The first key read from the input (arguments zKey and nKey) is
  163884. ** greater than the largest key currently stored in the potential
  163885. ** output segment.
  163886. */
  163887. static int fts3IncrmergeLoad(
  163888. Fts3Table *p, /* Fts3 table handle */
  163889. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  163890. int iIdx, /* Index of candidate output segment */
  163891. const char *zKey, /* First key to write */
  163892. int nKey, /* Number of bytes in nKey */
  163893. IncrmergeWriter *pWriter /* Populate this object */
  163894. ){
  163895. int rc; /* Return code */
  163896. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  163897. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  163898. if( rc==SQLITE_OK ){
  163899. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  163900. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  163901. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  163902. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  163903. int nRoot = 0; /* Size of aRoot[] in bytes */
  163904. int rc2; /* Return code from sqlite3_reset() */
  163905. int bAppendable = 0; /* Set to true if segment is appendable */
  163906. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  163907. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  163908. sqlite3_bind_int(pSelect, 2, iIdx);
  163909. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  163910. iStart = sqlite3_column_int64(pSelect, 1);
  163911. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  163912. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  163913. if( pWriter->nLeafData<0 ){
  163914. pWriter->nLeafData = pWriter->nLeafData * -1;
  163915. }
  163916. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  163917. nRoot = sqlite3_column_bytes(pSelect, 4);
  163918. aRoot = sqlite3_column_blob(pSelect, 4);
  163919. }else{
  163920. return sqlite3_reset(pSelect);
  163921. }
  163922. /* Check for the zero-length marker in the %_segments table */
  163923. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  163924. /* Check that zKey/nKey is larger than the largest key the candidate */
  163925. if( rc==SQLITE_OK && bAppendable ){
  163926. char *aLeaf = 0;
  163927. int nLeaf = 0;
  163928. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  163929. if( rc==SQLITE_OK ){
  163930. NodeReader reader;
  163931. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  163932. rc==SQLITE_OK && reader.aNode;
  163933. rc = nodeReaderNext(&reader)
  163934. ){
  163935. assert( reader.aNode );
  163936. }
  163937. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  163938. bAppendable = 0;
  163939. }
  163940. nodeReaderRelease(&reader);
  163941. }
  163942. sqlite3_free(aLeaf);
  163943. }
  163944. if( rc==SQLITE_OK && bAppendable ){
  163945. /* It is possible to append to this segment. Set up the IncrmergeWriter
  163946. ** object to do so. */
  163947. int i;
  163948. int nHeight = (int)aRoot[0];
  163949. NodeWriter *pNode;
  163950. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  163951. pWriter->iStart = iStart;
  163952. pWriter->iEnd = iEnd;
  163953. pWriter->iAbsLevel = iAbsLevel;
  163954. pWriter->iIdx = iIdx;
  163955. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  163956. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  163957. }
  163958. pNode = &pWriter->aNodeWriter[nHeight];
  163959. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  163960. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  163961. if( rc==SQLITE_OK ){
  163962. memcpy(pNode->block.a, aRoot, nRoot);
  163963. pNode->block.n = nRoot;
  163964. }
  163965. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  163966. NodeReader reader;
  163967. pNode = &pWriter->aNodeWriter[i];
  163968. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  163969. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  163970. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  163971. if( rc==SQLITE_OK ){
  163972. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  163973. pNode->key.n = reader.term.n;
  163974. if( i>0 ){
  163975. char *aBlock = 0;
  163976. int nBlock = 0;
  163977. pNode = &pWriter->aNodeWriter[i-1];
  163978. pNode->iBlock = reader.iChild;
  163979. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  163980. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  163981. if( rc==SQLITE_OK ){
  163982. memcpy(pNode->block.a, aBlock, nBlock);
  163983. pNode->block.n = nBlock;
  163984. }
  163985. sqlite3_free(aBlock);
  163986. }
  163987. }
  163988. nodeReaderRelease(&reader);
  163989. }
  163990. }
  163991. rc2 = sqlite3_reset(pSelect);
  163992. if( rc==SQLITE_OK ) rc = rc2;
  163993. }
  163994. return rc;
  163995. }
  163996. /*
  163997. ** Determine the largest segment index value that exists within absolute
  163998. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  163999. ** one before returning SQLITE_OK. Or, if there are no segments at all
  164000. ** within level iAbsLevel, set *piIdx to zero.
  164001. **
  164002. ** If an error occurs, return an SQLite error code. The final value of
  164003. ** *piIdx is undefined in this case.
  164004. */
  164005. static int fts3IncrmergeOutputIdx(
  164006. Fts3Table *p, /* FTS Table handle */
  164007. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  164008. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  164009. ){
  164010. int rc;
  164011. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  164012. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  164013. if( rc==SQLITE_OK ){
  164014. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  164015. sqlite3_step(pOutputIdx);
  164016. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  164017. rc = sqlite3_reset(pOutputIdx);
  164018. }
  164019. return rc;
  164020. }
  164021. /*
  164022. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  164023. ** with idx value iIdx.
  164024. **
  164025. ** In the %_segdir table, a segment is defined by the values in three
  164026. ** columns:
  164027. **
  164028. ** start_block
  164029. ** leaves_end_block
  164030. ** end_block
  164031. **
  164032. ** When an appendable segment is allocated, it is estimated that the
  164033. ** maximum number of leaf blocks that may be required is the sum of the
  164034. ** number of leaf blocks consumed by the input segments, plus the number
  164035. ** of input segments, multiplied by two. This value is stored in stack
  164036. ** variable nLeafEst.
  164037. **
  164038. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  164039. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  164040. ** array of leaf nodes starts at the first block allocated. The array
  164041. ** of interior nodes that are parents of the leaf nodes start at block
  164042. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  164043. **
  164044. ** In the actual code below, the value "16" is replaced with the
  164045. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  164046. */
  164047. static int fts3IncrmergeWriter(
  164048. Fts3Table *p, /* Fts3 table handle */
  164049. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  164050. int iIdx, /* Index of new output segment */
  164051. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  164052. IncrmergeWriter *pWriter /* Populate this object */
  164053. ){
  164054. int rc; /* Return Code */
  164055. int i; /* Iterator variable */
  164056. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  164057. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  164058. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  164059. /* Calculate nLeafEst. */
  164060. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  164061. if( rc==SQLITE_OK ){
  164062. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  164063. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  164064. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  164065. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  164066. }
  164067. rc = sqlite3_reset(pLeafEst);
  164068. }
  164069. if( rc!=SQLITE_OK ) return rc;
  164070. /* Calculate the first block to use in the output segment */
  164071. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  164072. if( rc==SQLITE_OK ){
  164073. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  164074. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  164075. pWriter->iEnd = pWriter->iStart - 1;
  164076. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  164077. }
  164078. rc = sqlite3_reset(pFirstBlock);
  164079. }
  164080. if( rc!=SQLITE_OK ) return rc;
  164081. /* Insert the marker in the %_segments table to make sure nobody tries
  164082. ** to steal the space just allocated. This is also used to identify
  164083. ** appendable segments. */
  164084. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  164085. if( rc!=SQLITE_OK ) return rc;
  164086. pWriter->iAbsLevel = iAbsLevel;
  164087. pWriter->nLeafEst = nLeafEst;
  164088. pWriter->iIdx = iIdx;
  164089. /* Set up the array of NodeWriter objects */
  164090. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  164091. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  164092. }
  164093. return SQLITE_OK;
  164094. }
  164095. /*
  164096. ** Remove an entry from the %_segdir table. This involves running the
  164097. ** following two statements:
  164098. **
  164099. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  164100. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  164101. **
  164102. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  164103. ** statement ensures that the remaining segments have contiguously allocated
  164104. ** idx values.
  164105. */
  164106. static int fts3RemoveSegdirEntry(
  164107. Fts3Table *p, /* FTS3 table handle */
  164108. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  164109. int iIdx /* Index of %_segdir entry to delete */
  164110. ){
  164111. int rc; /* Return code */
  164112. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  164113. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  164114. if( rc==SQLITE_OK ){
  164115. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  164116. sqlite3_bind_int(pDelete, 2, iIdx);
  164117. sqlite3_step(pDelete);
  164118. rc = sqlite3_reset(pDelete);
  164119. }
  164120. return rc;
  164121. }
  164122. /*
  164123. ** One or more segments have just been removed from absolute level iAbsLevel.
  164124. ** Update the 'idx' values of the remaining segments in the level so that
  164125. ** the idx values are a contiguous sequence starting from 0.
  164126. */
  164127. static int fts3RepackSegdirLevel(
  164128. Fts3Table *p, /* FTS3 table handle */
  164129. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  164130. ){
  164131. int rc; /* Return code */
  164132. int *aIdx = 0; /* Array of remaining idx values */
  164133. int nIdx = 0; /* Valid entries in aIdx[] */
  164134. int nAlloc = 0; /* Allocated size of aIdx[] */
  164135. int i; /* Iterator variable */
  164136. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  164137. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  164138. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  164139. if( rc==SQLITE_OK ){
  164140. int rc2;
  164141. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  164142. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  164143. if( nIdx>=nAlloc ){
  164144. int *aNew;
  164145. nAlloc += 16;
  164146. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  164147. if( !aNew ){
  164148. rc = SQLITE_NOMEM;
  164149. break;
  164150. }
  164151. aIdx = aNew;
  164152. }
  164153. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  164154. }
  164155. rc2 = sqlite3_reset(pSelect);
  164156. if( rc==SQLITE_OK ) rc = rc2;
  164157. }
  164158. if( rc==SQLITE_OK ){
  164159. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  164160. }
  164161. if( rc==SQLITE_OK ){
  164162. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  164163. }
  164164. assert( p->bIgnoreSavepoint==0 );
  164165. p->bIgnoreSavepoint = 1;
  164166. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  164167. if( aIdx[i]!=i ){
  164168. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  164169. sqlite3_bind_int(pUpdate, 1, i);
  164170. sqlite3_step(pUpdate);
  164171. rc = sqlite3_reset(pUpdate);
  164172. }
  164173. }
  164174. p->bIgnoreSavepoint = 0;
  164175. sqlite3_free(aIdx);
  164176. return rc;
  164177. }
  164178. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  164179. pNode->a[0] = (char)iHeight;
  164180. if( iChild ){
  164181. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  164182. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  164183. }else{
  164184. assert( pNode->nAlloc>=1 );
  164185. pNode->n = 1;
  164186. }
  164187. }
  164188. /*
  164189. ** The first two arguments are a pointer to and the size of a segment b-tree
  164190. ** node. The node may be a leaf or an internal node.
  164191. **
  164192. ** This function creates a new node image in blob object *pNew by copying
  164193. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  164194. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  164195. */
  164196. static int fts3TruncateNode(
  164197. const char *aNode, /* Current node image */
  164198. int nNode, /* Size of aNode in bytes */
  164199. Blob *pNew, /* OUT: Write new node image here */
  164200. const char *zTerm, /* Omit all terms smaller than this */
  164201. int nTerm, /* Size of zTerm in bytes */
  164202. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  164203. ){
  164204. NodeReader reader; /* Reader object */
  164205. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  164206. int rc = SQLITE_OK; /* Return code */
  164207. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  164208. /* Allocate required output space */
  164209. blobGrowBuffer(pNew, nNode, &rc);
  164210. if( rc!=SQLITE_OK ) return rc;
  164211. pNew->n = 0;
  164212. /* Populate new node buffer */
  164213. for(rc = nodeReaderInit(&reader, aNode, nNode);
  164214. rc==SQLITE_OK && reader.aNode;
  164215. rc = nodeReaderNext(&reader)
  164216. ){
  164217. if( pNew->n==0 ){
  164218. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  164219. if( res<0 || (bLeaf==0 && res==0) ) continue;
  164220. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  164221. *piBlock = reader.iChild;
  164222. }
  164223. rc = fts3AppendToNode(
  164224. pNew, &prev, reader.term.a, reader.term.n,
  164225. reader.aDoclist, reader.nDoclist
  164226. );
  164227. if( rc!=SQLITE_OK ) break;
  164228. }
  164229. if( pNew->n==0 ){
  164230. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  164231. *piBlock = reader.iChild;
  164232. }
  164233. assert( pNew->n<=pNew->nAlloc );
  164234. nodeReaderRelease(&reader);
  164235. sqlite3_free(prev.a);
  164236. return rc;
  164237. }
  164238. /*
  164239. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  164240. ** level iAbsLevel. This may involve deleting entries from the %_segments
  164241. ** table, and modifying existing entries in both the %_segments and %_segdir
  164242. ** tables.
  164243. **
  164244. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  164245. ** SQLite error code otherwise.
  164246. */
  164247. static int fts3TruncateSegment(
  164248. Fts3Table *p, /* FTS3 table handle */
  164249. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  164250. int iIdx, /* Index within level of segment to modify */
  164251. const char *zTerm, /* Remove terms smaller than this */
  164252. int nTerm /* Number of bytes in buffer zTerm */
  164253. ){
  164254. int rc = SQLITE_OK; /* Return code */
  164255. Blob root = {0,0,0}; /* New root page image */
  164256. Blob block = {0,0,0}; /* Buffer used for any other block */
  164257. sqlite3_int64 iBlock = 0; /* Block id */
  164258. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  164259. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  164260. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  164261. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  164262. if( rc==SQLITE_OK ){
  164263. int rc2; /* sqlite3_reset() return code */
  164264. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  164265. sqlite3_bind_int(pFetch, 2, iIdx);
  164266. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  164267. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  164268. int nRoot = sqlite3_column_bytes(pFetch, 4);
  164269. iOldStart = sqlite3_column_int64(pFetch, 1);
  164270. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  164271. }
  164272. rc2 = sqlite3_reset(pFetch);
  164273. if( rc==SQLITE_OK ) rc = rc2;
  164274. }
  164275. while( rc==SQLITE_OK && iBlock ){
  164276. char *aBlock = 0;
  164277. int nBlock = 0;
  164278. iNewStart = iBlock;
  164279. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  164280. if( rc==SQLITE_OK ){
  164281. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  164282. }
  164283. if( rc==SQLITE_OK ){
  164284. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  164285. }
  164286. sqlite3_free(aBlock);
  164287. }
  164288. /* Variable iNewStart now contains the first valid leaf node. */
  164289. if( rc==SQLITE_OK && iNewStart ){
  164290. sqlite3_stmt *pDel = 0;
  164291. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  164292. if( rc==SQLITE_OK ){
  164293. sqlite3_bind_int64(pDel, 1, iOldStart);
  164294. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  164295. sqlite3_step(pDel);
  164296. rc = sqlite3_reset(pDel);
  164297. }
  164298. }
  164299. if( rc==SQLITE_OK ){
  164300. sqlite3_stmt *pChomp = 0;
  164301. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  164302. if( rc==SQLITE_OK ){
  164303. sqlite3_bind_int64(pChomp, 1, iNewStart);
  164304. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  164305. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  164306. sqlite3_bind_int(pChomp, 4, iIdx);
  164307. sqlite3_step(pChomp);
  164308. rc = sqlite3_reset(pChomp);
  164309. sqlite3_bind_null(pChomp, 2);
  164310. }
  164311. }
  164312. sqlite3_free(root.a);
  164313. sqlite3_free(block.a);
  164314. return rc;
  164315. }
  164316. /*
  164317. ** This function is called after an incrmental-merge operation has run to
  164318. ** merge (or partially merge) two or more segments from absolute level
  164319. ** iAbsLevel.
  164320. **
  164321. ** Each input segment is either removed from the db completely (if all of
  164322. ** its data was copied to the output segment by the incrmerge operation)
  164323. ** or modified in place so that it no longer contains those entries that
  164324. ** have been duplicated in the output segment.
  164325. */
  164326. static int fts3IncrmergeChomp(
  164327. Fts3Table *p, /* FTS table handle */
  164328. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  164329. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  164330. int *pnRem /* Number of segments not deleted */
  164331. ){
  164332. int i;
  164333. int nRem = 0;
  164334. int rc = SQLITE_OK;
  164335. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  164336. Fts3SegReader *pSeg = 0;
  164337. int j;
  164338. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  164339. ** somewhere in the pCsr->apSegment[] array. */
  164340. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  164341. pSeg = pCsr->apSegment[j];
  164342. if( pSeg->iIdx==i ) break;
  164343. }
  164344. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  164345. if( pSeg->aNode==0 ){
  164346. /* Seg-reader is at EOF. Remove the entire input segment. */
  164347. rc = fts3DeleteSegment(p, pSeg);
  164348. if( rc==SQLITE_OK ){
  164349. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  164350. }
  164351. *pnRem = 0;
  164352. }else{
  164353. /* The incremental merge did not copy all the data from this
  164354. ** segment to the upper level. The segment is modified in place
  164355. ** so that it contains no keys smaller than zTerm/nTerm. */
  164356. const char *zTerm = pSeg->zTerm;
  164357. int nTerm = pSeg->nTerm;
  164358. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  164359. nRem++;
  164360. }
  164361. }
  164362. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  164363. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  164364. }
  164365. *pnRem = nRem;
  164366. return rc;
  164367. }
  164368. /*
  164369. ** Store an incr-merge hint in the database.
  164370. */
  164371. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  164372. sqlite3_stmt *pReplace = 0;
  164373. int rc; /* Return code */
  164374. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  164375. if( rc==SQLITE_OK ){
  164376. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  164377. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  164378. sqlite3_step(pReplace);
  164379. rc = sqlite3_reset(pReplace);
  164380. sqlite3_bind_null(pReplace, 2);
  164381. }
  164382. return rc;
  164383. }
  164384. /*
  164385. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  164386. ** exists, is stored in the rowid==1 row of the %_stat table.
  164387. **
  164388. ** If successful, populate blob *pHint with the value read from the %_stat
  164389. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  164390. ** SQLite error code.
  164391. */
  164392. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  164393. sqlite3_stmt *pSelect = 0;
  164394. int rc;
  164395. pHint->n = 0;
  164396. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  164397. if( rc==SQLITE_OK ){
  164398. int rc2;
  164399. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  164400. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  164401. const char *aHint = sqlite3_column_blob(pSelect, 0);
  164402. int nHint = sqlite3_column_bytes(pSelect, 0);
  164403. if( aHint ){
  164404. blobGrowBuffer(pHint, nHint, &rc);
  164405. if( rc==SQLITE_OK ){
  164406. memcpy(pHint->a, aHint, nHint);
  164407. pHint->n = nHint;
  164408. }
  164409. }
  164410. }
  164411. rc2 = sqlite3_reset(pSelect);
  164412. if( rc==SQLITE_OK ) rc = rc2;
  164413. }
  164414. return rc;
  164415. }
  164416. /*
  164417. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  164418. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  164419. ** consists of two varints, the absolute level number of the input segments
  164420. ** and the number of input segments.
  164421. **
  164422. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  164423. ** set *pRc to an SQLite error code before returning.
  164424. */
  164425. static void fts3IncrmergeHintPush(
  164426. Blob *pHint, /* Hint blob to append to */
  164427. i64 iAbsLevel, /* First varint to store in hint */
  164428. int nInput, /* Second varint to store in hint */
  164429. int *pRc /* IN/OUT: Error code */
  164430. ){
  164431. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  164432. if( *pRc==SQLITE_OK ){
  164433. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  164434. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  164435. }
  164436. }
  164437. /*
  164438. ** Read the last entry (most recently pushed) from the hint blob *pHint
  164439. ** and then remove the entry. Write the two values read to *piAbsLevel and
  164440. ** *pnInput before returning.
  164441. **
  164442. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  164443. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  164444. */
  164445. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  164446. const int nHint = pHint->n;
  164447. int i;
  164448. i = pHint->n-2;
  164449. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  164450. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  164451. pHint->n = i;
  164452. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  164453. i += fts3GetVarint32(&pHint->a[i], pnInput);
  164454. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  164455. return SQLITE_OK;
  164456. }
  164457. /*
  164458. ** Attempt an incremental merge that writes nMerge leaf blocks.
  164459. **
  164460. ** Incremental merges happen nMin segments at a time. The segments
  164461. ** to be merged are the nMin oldest segments (the ones with the smallest
  164462. ** values for the _segdir.idx field) in the highest level that contains
  164463. ** at least nMin segments. Multiple merges might occur in an attempt to
  164464. ** write the quota of nMerge leaf blocks.
  164465. */
  164466. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  164467. int rc; /* Return code */
  164468. int nRem = nMerge; /* Number of leaf pages yet to be written */
  164469. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  164470. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  164471. IncrmergeWriter *pWriter; /* Writer object */
  164472. int nSeg = 0; /* Number of input segments */
  164473. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  164474. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  164475. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  164476. /* Allocate space for the cursor, filter and writer objects */
  164477. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  164478. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  164479. if( !pWriter ) return SQLITE_NOMEM;
  164480. pFilter = (Fts3SegFilter *)&pWriter[1];
  164481. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  164482. rc = fts3IncrmergeHintLoad(p, &hint);
  164483. while( rc==SQLITE_OK && nRem>0 ){
  164484. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  164485. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  164486. int bUseHint = 0; /* True if attempting to append */
  164487. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  164488. /* Search the %_segdir table for the absolute level with the smallest
  164489. ** relative level number that contains at least nMin segments, if any.
  164490. ** If one is found, set iAbsLevel to the absolute level number and
  164491. ** nSeg to nMin. If no level with at least nMin segments can be found,
  164492. ** set nSeg to -1.
  164493. */
  164494. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  164495. sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
  164496. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  164497. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  164498. nSeg = sqlite3_column_int(pFindLevel, 1);
  164499. assert( nSeg>=2 );
  164500. }else{
  164501. nSeg = -1;
  164502. }
  164503. rc = sqlite3_reset(pFindLevel);
  164504. /* If the hint read from the %_stat table is not empty, check if the
  164505. ** last entry in it specifies a relative level smaller than or equal
  164506. ** to the level identified by the block above (if any). If so, this
  164507. ** iteration of the loop will work on merging at the hinted level.
  164508. */
  164509. if( rc==SQLITE_OK && hint.n ){
  164510. int nHint = hint.n;
  164511. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  164512. int nHintSeg = 0; /* Hint number of segments */
  164513. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  164514. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  164515. iAbsLevel = iHintAbsLevel;
  164516. nSeg = nHintSeg;
  164517. bUseHint = 1;
  164518. bDirtyHint = 1;
  164519. }else{
  164520. /* This undoes the effect of the HintPop() above - so that no entry
  164521. ** is removed from the hint blob. */
  164522. hint.n = nHint;
  164523. }
  164524. }
  164525. /* If nSeg is less that zero, then there is no level with at least
  164526. ** nMin segments and no hint in the %_stat table. No work to do.
  164527. ** Exit early in this case. */
  164528. if( nSeg<0 ) break;
  164529. /* Open a cursor to iterate through the contents of the oldest nSeg
  164530. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  164531. ** the 'hint' parameters, it is possible that there are less than nSeg
  164532. ** segments available in level iAbsLevel. In this case, no work is
  164533. ** done on iAbsLevel - fall through to the next iteration of the loop
  164534. ** to start work on some other level. */
  164535. memset(pWriter, 0, nAlloc);
  164536. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  164537. if( rc==SQLITE_OK ){
  164538. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  164539. assert( bUseHint==1 || bUseHint==0 );
  164540. if( iIdx==0 || (bUseHint && iIdx==1) ){
  164541. int bIgnore = 0;
  164542. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  164543. if( bIgnore ){
  164544. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  164545. }
  164546. }
  164547. }
  164548. if( rc==SQLITE_OK ){
  164549. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  164550. }
  164551. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  164552. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  164553. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  164554. ){
  164555. if( bUseHint && iIdx>0 ){
  164556. const char *zKey = pCsr->zTerm;
  164557. int nKey = pCsr->nTerm;
  164558. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  164559. }else{
  164560. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  164561. }
  164562. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  164563. fts3LogMerge(nSeg, iAbsLevel);
  164564. do {
  164565. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  164566. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  164567. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  164568. }while( rc==SQLITE_ROW );
  164569. /* Update or delete the input segments */
  164570. if( rc==SQLITE_OK ){
  164571. nRem -= (1 + pWriter->nWork);
  164572. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  164573. if( nSeg!=0 ){
  164574. bDirtyHint = 1;
  164575. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  164576. }
  164577. }
  164578. }
  164579. if( nSeg!=0 ){
  164580. pWriter->nLeafData = pWriter->nLeafData * -1;
  164581. }
  164582. fts3IncrmergeRelease(p, pWriter, &rc);
  164583. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  164584. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  164585. }
  164586. }
  164587. sqlite3Fts3SegReaderFinish(pCsr);
  164588. }
  164589. /* Write the hint values into the %_stat table for the next incr-merger */
  164590. if( bDirtyHint && rc==SQLITE_OK ){
  164591. rc = fts3IncrmergeHintStore(p, &hint);
  164592. }
  164593. sqlite3_free(pWriter);
  164594. sqlite3_free(hint.a);
  164595. return rc;
  164596. }
  164597. /*
  164598. ** Convert the text beginning at *pz into an integer and return
  164599. ** its value. Advance *pz to point to the first character past
  164600. ** the integer.
  164601. **
  164602. ** This function used for parameters to merge= and incrmerge=
  164603. ** commands.
  164604. */
  164605. static int fts3Getint(const char **pz){
  164606. const char *z = *pz;
  164607. int i = 0;
  164608. while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
  164609. *pz = z;
  164610. return i;
  164611. }
  164612. /*
  164613. ** Process statements of the form:
  164614. **
  164615. ** INSERT INTO table(table) VALUES('merge=A,B');
  164616. **
  164617. ** A and B are integers that decode to be the number of leaf pages
  164618. ** written for the merge, and the minimum number of segments on a level
  164619. ** before it will be selected for a merge, respectively.
  164620. */
  164621. static int fts3DoIncrmerge(
  164622. Fts3Table *p, /* FTS3 table handle */
  164623. const char *zParam /* Nul-terminated string containing "A,B" */
  164624. ){
  164625. int rc;
  164626. int nMin = (FTS3_MERGE_COUNT / 2);
  164627. int nMerge = 0;
  164628. const char *z = zParam;
  164629. /* Read the first integer value */
  164630. nMerge = fts3Getint(&z);
  164631. /* If the first integer value is followed by a ',', read the second
  164632. ** integer value. */
  164633. if( z[0]==',' && z[1]!='\0' ){
  164634. z++;
  164635. nMin = fts3Getint(&z);
  164636. }
  164637. if( z[0]!='\0' || nMin<2 ){
  164638. rc = SQLITE_ERROR;
  164639. }else{
  164640. rc = SQLITE_OK;
  164641. if( !p->bHasStat ){
  164642. assert( p->bFts4==0 );
  164643. sqlite3Fts3CreateStatTable(&rc, p);
  164644. }
  164645. if( rc==SQLITE_OK ){
  164646. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  164647. }
  164648. sqlite3Fts3SegmentsClose(p);
  164649. }
  164650. return rc;
  164651. }
  164652. /*
  164653. ** Process statements of the form:
  164654. **
  164655. ** INSERT INTO table(table) VALUES('automerge=X');
  164656. **
  164657. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  164658. ** turn it on. The setting is persistent.
  164659. */
  164660. static int fts3DoAutoincrmerge(
  164661. Fts3Table *p, /* FTS3 table handle */
  164662. const char *zParam /* Nul-terminated string containing boolean */
  164663. ){
  164664. int rc = SQLITE_OK;
  164665. sqlite3_stmt *pStmt = 0;
  164666. p->nAutoincrmerge = fts3Getint(&zParam);
  164667. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  164668. p->nAutoincrmerge = 8;
  164669. }
  164670. if( !p->bHasStat ){
  164671. assert( p->bFts4==0 );
  164672. sqlite3Fts3CreateStatTable(&rc, p);
  164673. if( rc ) return rc;
  164674. }
  164675. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  164676. if( rc ) return rc;
  164677. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  164678. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  164679. sqlite3_step(pStmt);
  164680. rc = sqlite3_reset(pStmt);
  164681. return rc;
  164682. }
  164683. /*
  164684. ** Return a 64-bit checksum for the FTS index entry specified by the
  164685. ** arguments to this function.
  164686. */
  164687. static u64 fts3ChecksumEntry(
  164688. const char *zTerm, /* Pointer to buffer containing term */
  164689. int nTerm, /* Size of zTerm in bytes */
  164690. int iLangid, /* Language id for current row */
  164691. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  164692. i64 iDocid, /* Docid for current row. */
  164693. int iCol, /* Column number */
  164694. int iPos /* Position */
  164695. ){
  164696. int i;
  164697. u64 ret = (u64)iDocid;
  164698. ret += (ret<<3) + iLangid;
  164699. ret += (ret<<3) + iIndex;
  164700. ret += (ret<<3) + iCol;
  164701. ret += (ret<<3) + iPos;
  164702. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  164703. return ret;
  164704. }
  164705. /*
  164706. ** Return a checksum of all entries in the FTS index that correspond to
  164707. ** language id iLangid. The checksum is calculated by XORing the checksums
  164708. ** of each individual entry (see fts3ChecksumEntry()) together.
  164709. **
  164710. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  164711. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  164712. ** return value is undefined in this case.
  164713. */
  164714. static u64 fts3ChecksumIndex(
  164715. Fts3Table *p, /* FTS3 table handle */
  164716. int iLangid, /* Language id to return cksum for */
  164717. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  164718. int *pRc /* OUT: Return code */
  164719. ){
  164720. Fts3SegFilter filter;
  164721. Fts3MultiSegReader csr;
  164722. int rc;
  164723. u64 cksum = 0;
  164724. assert( *pRc==SQLITE_OK );
  164725. memset(&filter, 0, sizeof(filter));
  164726. memset(&csr, 0, sizeof(csr));
  164727. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  164728. filter.flags |= FTS3_SEGMENT_SCAN;
  164729. rc = sqlite3Fts3SegReaderCursor(
  164730. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  164731. );
  164732. if( rc==SQLITE_OK ){
  164733. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  164734. }
  164735. if( rc==SQLITE_OK ){
  164736. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  164737. char *pCsr = csr.aDoclist;
  164738. char *pEnd = &pCsr[csr.nDoclist];
  164739. i64 iDocid = 0;
  164740. i64 iCol = 0;
  164741. i64 iPos = 0;
  164742. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  164743. while( pCsr<pEnd ){
  164744. i64 iVal = 0;
  164745. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  164746. if( pCsr<pEnd ){
  164747. if( iVal==0 || iVal==1 ){
  164748. iCol = 0;
  164749. iPos = 0;
  164750. if( iVal ){
  164751. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  164752. }else{
  164753. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  164754. iDocid += iVal;
  164755. }
  164756. }else{
  164757. iPos += (iVal - 2);
  164758. cksum = cksum ^ fts3ChecksumEntry(
  164759. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  164760. (int)iCol, (int)iPos
  164761. );
  164762. }
  164763. }
  164764. }
  164765. }
  164766. }
  164767. sqlite3Fts3SegReaderFinish(&csr);
  164768. *pRc = rc;
  164769. return cksum;
  164770. }
  164771. /*
  164772. ** Check if the contents of the FTS index match the current contents of the
  164773. ** content table. If no error occurs and the contents do match, set *pbOk
  164774. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  164775. ** to false before returning.
  164776. **
  164777. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  164778. ** code. The final value of *pbOk is undefined in this case.
  164779. */
  164780. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  164781. int rc = SQLITE_OK; /* Return code */
  164782. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  164783. u64 cksum2 = 0; /* Checksum based on %_content contents */
  164784. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  164785. /* This block calculates the checksum according to the FTS index. */
  164786. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  164787. if( rc==SQLITE_OK ){
  164788. int rc2;
  164789. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  164790. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  164791. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  164792. int iLangid = sqlite3_column_int(pAllLangid, 0);
  164793. int i;
  164794. for(i=0; i<p->nIndex; i++){
  164795. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  164796. }
  164797. }
  164798. rc2 = sqlite3_reset(pAllLangid);
  164799. if( rc==SQLITE_OK ) rc = rc2;
  164800. }
  164801. /* This block calculates the checksum according to the %_content table */
  164802. if( rc==SQLITE_OK ){
  164803. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  164804. sqlite3_stmt *pStmt = 0;
  164805. char *zSql;
  164806. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  164807. if( !zSql ){
  164808. rc = SQLITE_NOMEM;
  164809. }else{
  164810. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  164811. sqlite3_free(zSql);
  164812. }
  164813. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  164814. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  164815. int iLang = langidFromSelect(p, pStmt);
  164816. int iCol;
  164817. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  164818. if( p->abNotindexed[iCol]==0 ){
  164819. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  164820. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  164821. sqlite3_tokenizer_cursor *pT = 0;
  164822. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  164823. while( rc==SQLITE_OK ){
  164824. char const *zToken; /* Buffer containing token */
  164825. int nToken = 0; /* Number of bytes in token */
  164826. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  164827. int iPos = 0; /* Position of token in zText */
  164828. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  164829. if( rc==SQLITE_OK ){
  164830. int i;
  164831. cksum2 = cksum2 ^ fts3ChecksumEntry(
  164832. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  164833. );
  164834. for(i=1; i<p->nIndex; i++){
  164835. if( p->aIndex[i].nPrefix<=nToken ){
  164836. cksum2 = cksum2 ^ fts3ChecksumEntry(
  164837. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  164838. );
  164839. }
  164840. }
  164841. }
  164842. }
  164843. if( pT ) pModule->xClose(pT);
  164844. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  164845. }
  164846. }
  164847. }
  164848. sqlite3_finalize(pStmt);
  164849. }
  164850. *pbOk = (cksum1==cksum2);
  164851. return rc;
  164852. }
  164853. /*
  164854. ** Run the integrity-check. If no error occurs and the current contents of
  164855. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  164856. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  164857. **
  164858. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  164859. ** error code.
  164860. **
  164861. ** The integrity-check works as follows. For each token and indexed token
  164862. ** prefix in the document set, a 64-bit checksum is calculated (by code
  164863. ** in fts3ChecksumEntry()) based on the following:
  164864. **
  164865. ** + The index number (0 for the main index, 1 for the first prefix
  164866. ** index etc.),
  164867. ** + The token (or token prefix) text itself,
  164868. ** + The language-id of the row it appears in,
  164869. ** + The docid of the row it appears in,
  164870. ** + The column it appears in, and
  164871. ** + The tokens position within that column.
  164872. **
  164873. ** The checksums for all entries in the index are XORed together to create
  164874. ** a single checksum for the entire index.
  164875. **
  164876. ** The integrity-check code calculates the same checksum in two ways:
  164877. **
  164878. ** 1. By scanning the contents of the FTS index, and
  164879. ** 2. By scanning and tokenizing the content table.
  164880. **
  164881. ** If the two checksums are identical, the integrity-check is deemed to have
  164882. ** passed.
  164883. */
  164884. static int fts3DoIntegrityCheck(
  164885. Fts3Table *p /* FTS3 table handle */
  164886. ){
  164887. int rc;
  164888. int bOk = 0;
  164889. rc = fts3IntegrityCheck(p, &bOk);
  164890. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  164891. return rc;
  164892. }
  164893. /*
  164894. ** Handle a 'special' INSERT of the form:
  164895. **
  164896. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  164897. **
  164898. ** Argument pVal contains the result of <expr>. Currently the only
  164899. ** meaningful value to insert is the text 'optimize'.
  164900. */
  164901. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  164902. int rc; /* Return Code */
  164903. const char *zVal = (const char *)sqlite3_value_text(pVal);
  164904. int nVal = sqlite3_value_bytes(pVal);
  164905. if( !zVal ){
  164906. return SQLITE_NOMEM;
  164907. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  164908. rc = fts3DoOptimize(p, 0);
  164909. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  164910. rc = fts3DoRebuild(p);
  164911. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  164912. rc = fts3DoIntegrityCheck(p);
  164913. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  164914. rc = fts3DoIncrmerge(p, &zVal[6]);
  164915. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  164916. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  164917. #ifdef SQLITE_TEST
  164918. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  164919. p->nNodeSize = atoi(&zVal[9]);
  164920. rc = SQLITE_OK;
  164921. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  164922. p->nMaxPendingData = atoi(&zVal[11]);
  164923. rc = SQLITE_OK;
  164924. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  164925. p->bNoIncrDoclist = atoi(&zVal[21]);
  164926. rc = SQLITE_OK;
  164927. #endif
  164928. }else{
  164929. rc = SQLITE_ERROR;
  164930. }
  164931. return rc;
  164932. }
  164933. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  164934. /*
  164935. ** Delete all cached deferred doclists. Deferred doclists are cached
  164936. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  164937. */
  164938. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  164939. Fts3DeferredToken *pDef;
  164940. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  164941. fts3PendingListDelete(pDef->pList);
  164942. pDef->pList = 0;
  164943. }
  164944. }
  164945. /*
  164946. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  164947. ** this list using sqlite3Fts3DeferToken().
  164948. */
  164949. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  164950. Fts3DeferredToken *pDef;
  164951. Fts3DeferredToken *pNext;
  164952. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  164953. pNext = pDef->pNext;
  164954. fts3PendingListDelete(pDef->pList);
  164955. sqlite3_free(pDef);
  164956. }
  164957. pCsr->pDeferred = 0;
  164958. }
  164959. /*
  164960. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  164961. ** based on the row that pCsr currently points to.
  164962. **
  164963. ** A deferred-doclist is like any other doclist with position information
  164964. ** included, except that it only contains entries for a single row of the
  164965. ** table, not for all rows.
  164966. */
  164967. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  164968. int rc = SQLITE_OK; /* Return code */
  164969. if( pCsr->pDeferred ){
  164970. int i; /* Used to iterate through table columns */
  164971. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  164972. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  164973. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  164974. sqlite3_tokenizer *pT = p->pTokenizer;
  164975. sqlite3_tokenizer_module const *pModule = pT->pModule;
  164976. assert( pCsr->isRequireSeek==0 );
  164977. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  164978. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  164979. if( p->abNotindexed[i]==0 ){
  164980. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  164981. sqlite3_tokenizer_cursor *pTC = 0;
  164982. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  164983. while( rc==SQLITE_OK ){
  164984. char const *zToken; /* Buffer containing token */
  164985. int nToken = 0; /* Number of bytes in token */
  164986. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  164987. int iPos = 0; /* Position of token in zText */
  164988. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  164989. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  164990. Fts3PhraseToken *pPT = pDef->pToken;
  164991. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  164992. && (pPT->bFirst==0 || iPos==0)
  164993. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  164994. && (0==memcmp(zToken, pPT->z, pPT->n))
  164995. ){
  164996. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  164997. }
  164998. }
  164999. }
  165000. if( pTC ) pModule->xClose(pTC);
  165001. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  165002. }
  165003. }
  165004. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  165005. if( pDef->pList ){
  165006. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  165007. }
  165008. }
  165009. }
  165010. return rc;
  165011. }
  165012. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  165013. Fts3DeferredToken *p,
  165014. char **ppData,
  165015. int *pnData
  165016. ){
  165017. char *pRet;
  165018. int nSkip;
  165019. sqlite3_int64 dummy;
  165020. *ppData = 0;
  165021. *pnData = 0;
  165022. if( p->pList==0 ){
  165023. return SQLITE_OK;
  165024. }
  165025. pRet = (char *)sqlite3_malloc(p->pList->nData);
  165026. if( !pRet ) return SQLITE_NOMEM;
  165027. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  165028. *pnData = p->pList->nData - nSkip;
  165029. *ppData = pRet;
  165030. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  165031. return SQLITE_OK;
  165032. }
  165033. /*
  165034. ** Add an entry for token pToken to the pCsr->pDeferred list.
  165035. */
  165036. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  165037. Fts3Cursor *pCsr, /* Fts3 table cursor */
  165038. Fts3PhraseToken *pToken, /* Token to defer */
  165039. int iCol /* Column that token must appear in (or -1) */
  165040. ){
  165041. Fts3DeferredToken *pDeferred;
  165042. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  165043. if( !pDeferred ){
  165044. return SQLITE_NOMEM;
  165045. }
  165046. memset(pDeferred, 0, sizeof(*pDeferred));
  165047. pDeferred->pToken = pToken;
  165048. pDeferred->pNext = pCsr->pDeferred;
  165049. pDeferred->iCol = iCol;
  165050. pCsr->pDeferred = pDeferred;
  165051. assert( pToken->pDeferred==0 );
  165052. pToken->pDeferred = pDeferred;
  165053. return SQLITE_OK;
  165054. }
  165055. #endif
  165056. /*
  165057. ** SQLite value pRowid contains the rowid of a row that may or may not be
  165058. ** present in the FTS3 table. If it is, delete it and adjust the contents
  165059. ** of subsiduary data structures accordingly.
  165060. */
  165061. static int fts3DeleteByRowid(
  165062. Fts3Table *p,
  165063. sqlite3_value *pRowid,
  165064. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  165065. u32 *aSzDel
  165066. ){
  165067. int rc = SQLITE_OK; /* Return code */
  165068. int bFound = 0; /* True if *pRowid really is in the table */
  165069. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  165070. if( bFound && rc==SQLITE_OK ){
  165071. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  165072. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  165073. if( rc==SQLITE_OK ){
  165074. if( isEmpty ){
  165075. /* Deleting this row means the whole table is empty. In this case
  165076. ** delete the contents of all three tables and throw away any
  165077. ** data in the pendingTerms hash table. */
  165078. rc = fts3DeleteAll(p, 1);
  165079. *pnChng = 0;
  165080. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  165081. }else{
  165082. *pnChng = *pnChng - 1;
  165083. if( p->zContentTbl==0 ){
  165084. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  165085. }
  165086. if( p->bHasDocsize ){
  165087. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  165088. }
  165089. }
  165090. }
  165091. }
  165092. return rc;
  165093. }
  165094. /*
  165095. ** This function does the work for the xUpdate method of FTS3 virtual
  165096. ** tables. The schema of the virtual table being:
  165097. **
  165098. ** CREATE TABLE <table name>(
  165099. ** <user columns>,
  165100. ** <table name> HIDDEN,
  165101. ** docid HIDDEN,
  165102. ** <langid> HIDDEN
  165103. ** );
  165104. **
  165105. **
  165106. */
  165107. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  165108. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  165109. int nArg, /* Size of argument array */
  165110. sqlite3_value **apVal, /* Array of arguments */
  165111. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  165112. ){
  165113. Fts3Table *p = (Fts3Table *)pVtab;
  165114. int rc = SQLITE_OK; /* Return Code */
  165115. u32 *aSzIns = 0; /* Sizes of inserted documents */
  165116. u32 *aSzDel = 0; /* Sizes of deleted documents */
  165117. int nChng = 0; /* Net change in number of documents */
  165118. int bInsertDone = 0;
  165119. /* At this point it must be known if the %_stat table exists or not.
  165120. ** So bHasStat may not be 2. */
  165121. assert( p->bHasStat==0 || p->bHasStat==1 );
  165122. assert( p->pSegments==0 );
  165123. assert(
  165124. nArg==1 /* DELETE operations */
  165125. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  165126. );
  165127. /* Check for a "special" INSERT operation. One of the form:
  165128. **
  165129. ** INSERT INTO xyz(xyz) VALUES('command');
  165130. */
  165131. if( nArg>1
  165132. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  165133. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  165134. ){
  165135. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  165136. goto update_out;
  165137. }
  165138. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  165139. rc = SQLITE_CONSTRAINT;
  165140. goto update_out;
  165141. }
  165142. /* Allocate space to hold the change in document sizes */
  165143. aSzDel = sqlite3_malloc64(sizeof(aSzDel[0])*((sqlite3_int64)p->nColumn+1)*2);
  165144. if( aSzDel==0 ){
  165145. rc = SQLITE_NOMEM;
  165146. goto update_out;
  165147. }
  165148. aSzIns = &aSzDel[p->nColumn+1];
  165149. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  165150. rc = fts3Writelock(p);
  165151. if( rc!=SQLITE_OK ) goto update_out;
  165152. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  165153. ** value, then this operation requires constraint handling.
  165154. **
  165155. ** If the on-conflict mode is REPLACE, this means that the existing row
  165156. ** should be deleted from the database before inserting the new row. Or,
  165157. ** if the on-conflict mode is other than REPLACE, then this method must
  165158. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  165159. ** modify the database file.
  165160. */
  165161. if( nArg>1 && p->zContentTbl==0 ){
  165162. /* Find the value object that holds the new rowid value. */
  165163. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  165164. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  165165. pNewRowid = apVal[1];
  165166. }
  165167. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  165168. sqlite3_value_type(apVal[0])==SQLITE_NULL
  165169. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  165170. )){
  165171. /* The new rowid is not NULL (in this case the rowid will be
  165172. ** automatically assigned and there is no chance of a conflict), and
  165173. ** the statement is either an INSERT or an UPDATE that modifies the
  165174. ** rowid column. So if the conflict mode is REPLACE, then delete any
  165175. ** existing row with rowid=pNewRowid.
  165176. **
  165177. ** Or, if the conflict mode is not REPLACE, insert the new record into
  165178. ** the %_content table. If we hit the duplicate rowid constraint (or any
  165179. ** other error) while doing so, return immediately.
  165180. **
  165181. ** This branch may also run if pNewRowid contains a value that cannot
  165182. ** be losslessly converted to an integer. In this case, the eventual
  165183. ** call to fts3InsertData() (either just below or further on in this
  165184. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  165185. ** invoked, it will delete zero rows (since no row will have
  165186. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  165187. */
  165188. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  165189. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  165190. }else{
  165191. rc = fts3InsertData(p, apVal, pRowid);
  165192. bInsertDone = 1;
  165193. }
  165194. }
  165195. }
  165196. if( rc!=SQLITE_OK ){
  165197. goto update_out;
  165198. }
  165199. /* If this is a DELETE or UPDATE operation, remove the old record. */
  165200. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  165201. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  165202. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  165203. }
  165204. /* If this is an INSERT or UPDATE operation, insert the new record. */
  165205. if( nArg>1 && rc==SQLITE_OK ){
  165206. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  165207. if( bInsertDone==0 ){
  165208. rc = fts3InsertData(p, apVal, pRowid);
  165209. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  165210. rc = FTS_CORRUPT_VTAB;
  165211. }
  165212. }
  165213. if( rc==SQLITE_OK ){
  165214. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  165215. }
  165216. if( rc==SQLITE_OK ){
  165217. assert( p->iPrevDocid==*pRowid );
  165218. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  165219. }
  165220. if( p->bHasDocsize ){
  165221. fts3InsertDocsize(&rc, p, aSzIns);
  165222. }
  165223. nChng++;
  165224. }
  165225. if( p->bFts4 ){
  165226. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  165227. }
  165228. update_out:
  165229. sqlite3_free(aSzDel);
  165230. sqlite3Fts3SegmentsClose(p);
  165231. return rc;
  165232. }
  165233. /*
  165234. ** Flush any data in the pending-terms hash table to disk. If successful,
  165235. ** merge all segments in the database (including the new segment, if
  165236. ** there was any data to flush) into a single segment.
  165237. */
  165238. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  165239. int rc;
  165240. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  165241. if( rc==SQLITE_OK ){
  165242. rc = fts3DoOptimize(p, 1);
  165243. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  165244. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  165245. if( rc2!=SQLITE_OK ) rc = rc2;
  165246. }else{
  165247. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  165248. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  165249. }
  165250. }
  165251. sqlite3Fts3SegmentsClose(p);
  165252. return rc;
  165253. }
  165254. #endif
  165255. /************** End of fts3_write.c ******************************************/
  165256. /************** Begin file fts3_snippet.c ************************************/
  165257. /*
  165258. ** 2009 Oct 23
  165259. **
  165260. ** The author disclaims copyright to this source code. In place of
  165261. ** a legal notice, here is a blessing:
  165262. **
  165263. ** May you do good and not evil.
  165264. ** May you find forgiveness for yourself and forgive others.
  165265. ** May you share freely, never taking more than you give.
  165266. **
  165267. ******************************************************************************
  165268. */
  165269. /* #include "fts3Int.h" */
  165270. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  165271. /* #include <string.h> */
  165272. /* #include <assert.h> */
  165273. /*
  165274. ** Characters that may appear in the second argument to matchinfo().
  165275. */
  165276. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  165277. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  165278. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  165279. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  165280. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  165281. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  165282. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  165283. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  165284. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  165285. /*
  165286. ** The default value for the second argument to matchinfo().
  165287. */
  165288. #define FTS3_MATCHINFO_DEFAULT "pcx"
  165289. /*
  165290. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  165291. ** Fts3Expr.aDoclist[]/nDoclist.
  165292. */
  165293. typedef struct LoadDoclistCtx LoadDoclistCtx;
  165294. struct LoadDoclistCtx {
  165295. Fts3Cursor *pCsr; /* FTS3 Cursor */
  165296. int nPhrase; /* Number of phrases seen so far */
  165297. int nToken; /* Number of tokens seen so far */
  165298. };
  165299. /*
  165300. ** The following types are used as part of the implementation of the
  165301. ** fts3BestSnippet() routine.
  165302. */
  165303. typedef struct SnippetIter SnippetIter;
  165304. typedef struct SnippetPhrase SnippetPhrase;
  165305. typedef struct SnippetFragment SnippetFragment;
  165306. struct SnippetIter {
  165307. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  165308. int iCol; /* Extract snippet from this column */
  165309. int nSnippet; /* Requested snippet length (in tokens) */
  165310. int nPhrase; /* Number of phrases in query */
  165311. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  165312. int iCurrent; /* First token of current snippet */
  165313. };
  165314. struct SnippetPhrase {
  165315. int nToken; /* Number of tokens in phrase */
  165316. char *pList; /* Pointer to start of phrase position list */
  165317. int iHead; /* Next value in position list */
  165318. char *pHead; /* Position list data following iHead */
  165319. int iTail; /* Next value in trailing position list */
  165320. char *pTail; /* Position list data following iTail */
  165321. };
  165322. struct SnippetFragment {
  165323. int iCol; /* Column snippet is extracted from */
  165324. int iPos; /* Index of first token in snippet */
  165325. u64 covered; /* Mask of query phrases covered */
  165326. u64 hlmask; /* Mask of snippet terms to highlight */
  165327. };
  165328. /*
  165329. ** This type is used as an fts3ExprIterate() context object while
  165330. ** accumulating the data returned by the matchinfo() function.
  165331. */
  165332. typedef struct MatchInfo MatchInfo;
  165333. struct MatchInfo {
  165334. Fts3Cursor *pCursor; /* FTS3 Cursor */
  165335. int nCol; /* Number of columns in table */
  165336. int nPhrase; /* Number of matchable phrases in query */
  165337. sqlite3_int64 nDoc; /* Number of docs in database */
  165338. char flag;
  165339. u32 *aMatchinfo; /* Pre-allocated buffer */
  165340. };
  165341. /*
  165342. ** An instance of this structure is used to manage a pair of buffers, each
  165343. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  165344. ** for details.
  165345. */
  165346. struct MatchinfoBuffer {
  165347. u8 aRef[3];
  165348. int nElem;
  165349. int bGlobal; /* Set if global data is loaded */
  165350. char *zMatchinfo;
  165351. u32 aMatchinfo[1];
  165352. };
  165353. /*
  165354. ** The snippet() and offsets() functions both return text values. An instance
  165355. ** of the following structure is used to accumulate those values while the
  165356. ** functions are running. See fts3StringAppend() for details.
  165357. */
  165358. typedef struct StrBuffer StrBuffer;
  165359. struct StrBuffer {
  165360. char *z; /* Pointer to buffer containing string */
  165361. int n; /* Length of z in bytes (excl. nul-term) */
  165362. int nAlloc; /* Allocated size of buffer z in bytes */
  165363. };
  165364. /*************************************************************************
  165365. ** Start of MatchinfoBuffer code.
  165366. */
  165367. /*
  165368. ** Allocate a two-slot MatchinfoBuffer object.
  165369. */
  165370. static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){
  165371. MatchinfoBuffer *pRet;
  165372. sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1)
  165373. + sizeof(MatchinfoBuffer);
  165374. sqlite3_int64 nStr = strlen(zMatchinfo);
  165375. pRet = sqlite3_malloc64(nByte + nStr+1);
  165376. if( pRet ){
  165377. memset(pRet, 0, nByte);
  165378. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  165379. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0]
  165380. + sizeof(u32)*((int)nElem+1);
  165381. pRet->nElem = (int)nElem;
  165382. pRet->zMatchinfo = ((char*)pRet) + nByte;
  165383. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  165384. pRet->aRef[0] = 1;
  165385. }
  165386. return pRet;
  165387. }
  165388. static void fts3MIBufferFree(void *p){
  165389. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  165390. assert( (u32*)p==&pBuf->aMatchinfo[1]
  165391. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  165392. );
  165393. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  165394. pBuf->aRef[1] = 0;
  165395. }else{
  165396. pBuf->aRef[2] = 0;
  165397. }
  165398. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  165399. sqlite3_free(pBuf);
  165400. }
  165401. }
  165402. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  165403. void (*xRet)(void*) = 0;
  165404. u32 *aOut = 0;
  165405. if( p->aRef[1]==0 ){
  165406. p->aRef[1] = 1;
  165407. aOut = &p->aMatchinfo[1];
  165408. xRet = fts3MIBufferFree;
  165409. }
  165410. else if( p->aRef[2]==0 ){
  165411. p->aRef[2] = 1;
  165412. aOut = &p->aMatchinfo[p->nElem+2];
  165413. xRet = fts3MIBufferFree;
  165414. }else{
  165415. aOut = (u32*)sqlite3_malloc64(p->nElem * sizeof(u32));
  165416. if( aOut ){
  165417. xRet = sqlite3_free;
  165418. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  165419. }
  165420. }
  165421. *paOut = aOut;
  165422. return xRet;
  165423. }
  165424. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  165425. p->bGlobal = 1;
  165426. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  165427. }
  165428. /*
  165429. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  165430. */
  165431. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  165432. if( p ){
  165433. assert( p->aRef[0]==1 );
  165434. p->aRef[0] = 0;
  165435. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  165436. sqlite3_free(p);
  165437. }
  165438. }
  165439. }
  165440. /*
  165441. ** End of MatchinfoBuffer code.
  165442. *************************************************************************/
  165443. /*
  165444. ** This function is used to help iterate through a position-list. A position
  165445. ** list is a list of unique integers, sorted from smallest to largest. Each
  165446. ** element of the list is represented by an FTS3 varint that takes the value
  165447. ** of the difference between the current element and the previous one plus
  165448. ** two. For example, to store the position-list:
  165449. **
  165450. ** 4 9 113
  165451. **
  165452. ** the three varints:
  165453. **
  165454. ** 6 7 106
  165455. **
  165456. ** are encoded.
  165457. **
  165458. ** When this function is called, *pp points to the start of an element of
  165459. ** the list. *piPos contains the value of the previous entry in the list.
  165460. ** After it returns, *piPos contains the value of the next element of the
  165461. ** list and *pp is advanced to the following varint.
  165462. */
  165463. static void fts3GetDeltaPosition(char **pp, int *piPos){
  165464. int iVal;
  165465. *pp += fts3GetVarint32(*pp, &iVal);
  165466. *piPos += (iVal-2);
  165467. }
  165468. /*
  165469. ** Helper function for fts3ExprIterate() (see below).
  165470. */
  165471. static int fts3ExprIterate2(
  165472. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  165473. int *piPhrase, /* Pointer to phrase counter */
  165474. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  165475. void *pCtx /* Second argument to pass to callback */
  165476. ){
  165477. int rc; /* Return code */
  165478. int eType = pExpr->eType; /* Type of expression node pExpr */
  165479. if( eType!=FTSQUERY_PHRASE ){
  165480. assert( pExpr->pLeft && pExpr->pRight );
  165481. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  165482. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  165483. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  165484. }
  165485. }else{
  165486. rc = x(pExpr, *piPhrase, pCtx);
  165487. (*piPhrase)++;
  165488. }
  165489. return rc;
  165490. }
  165491. /*
  165492. ** Iterate through all phrase nodes in an FTS3 query, except those that
  165493. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  165494. ** For each phrase node found, the supplied callback function is invoked.
  165495. **
  165496. ** If the callback function returns anything other than SQLITE_OK,
  165497. ** the iteration is abandoned and the error code returned immediately.
  165498. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  165499. ** all eligible phrase nodes.
  165500. */
  165501. static int fts3ExprIterate(
  165502. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  165503. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  165504. void *pCtx /* Second argument to pass to callback */
  165505. ){
  165506. int iPhrase = 0; /* Variable used as the phrase counter */
  165507. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  165508. }
  165509. /*
  165510. ** This is an fts3ExprIterate() callback used while loading the doclists
  165511. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  165512. ** fts3ExprLoadDoclists().
  165513. */
  165514. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  165515. int rc = SQLITE_OK;
  165516. Fts3Phrase *pPhrase = pExpr->pPhrase;
  165517. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  165518. UNUSED_PARAMETER(iPhrase);
  165519. p->nPhrase++;
  165520. p->nToken += pPhrase->nToken;
  165521. return rc;
  165522. }
  165523. /*
  165524. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  165525. ** pCsr.
  165526. **
  165527. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  165528. ** phrases in the expression (all phrases except those directly or
  165529. ** indirectly descended from the right-hand-side of a NOT operator). If
  165530. ** pnToken is not NULL, then it is set to the number of tokens in all
  165531. ** matchable phrases of the expression.
  165532. */
  165533. static int fts3ExprLoadDoclists(
  165534. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  165535. int *pnPhrase, /* OUT: Number of phrases in query */
  165536. int *pnToken /* OUT: Number of tokens in query */
  165537. ){
  165538. int rc; /* Return Code */
  165539. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  165540. sCtx.pCsr = pCsr;
  165541. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  165542. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  165543. if( pnToken ) *pnToken = sCtx.nToken;
  165544. return rc;
  165545. }
  165546. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  165547. (*(int *)ctx)++;
  165548. pExpr->iPhrase = iPhrase;
  165549. return SQLITE_OK;
  165550. }
  165551. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  165552. int nPhrase = 0;
  165553. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  165554. return nPhrase;
  165555. }
  165556. /*
  165557. ** Advance the position list iterator specified by the first two
  165558. ** arguments so that it points to the first element with a value greater
  165559. ** than or equal to parameter iNext.
  165560. */
  165561. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  165562. char *pIter = *ppIter;
  165563. if( pIter ){
  165564. int iIter = *piIter;
  165565. while( iIter<iNext ){
  165566. if( 0==(*pIter & 0xFE) ){
  165567. iIter = -1;
  165568. pIter = 0;
  165569. break;
  165570. }
  165571. fts3GetDeltaPosition(&pIter, &iIter);
  165572. }
  165573. *piIter = iIter;
  165574. *ppIter = pIter;
  165575. }
  165576. }
  165577. /*
  165578. ** Advance the snippet iterator to the next candidate snippet.
  165579. */
  165580. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  165581. int i; /* Loop counter */
  165582. if( pIter->iCurrent<0 ){
  165583. /* The SnippetIter object has just been initialized. The first snippet
  165584. ** candidate always starts at offset 0 (even if this candidate has a
  165585. ** score of 0.0).
  165586. */
  165587. pIter->iCurrent = 0;
  165588. /* Advance the 'head' iterator of each phrase to the first offset that
  165589. ** is greater than or equal to (iNext+nSnippet).
  165590. */
  165591. for(i=0; i<pIter->nPhrase; i++){
  165592. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  165593. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  165594. }
  165595. }else{
  165596. int iStart;
  165597. int iEnd = 0x7FFFFFFF;
  165598. for(i=0; i<pIter->nPhrase; i++){
  165599. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  165600. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  165601. iEnd = pPhrase->iHead;
  165602. }
  165603. }
  165604. if( iEnd==0x7FFFFFFF ){
  165605. return 1;
  165606. }
  165607. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  165608. for(i=0; i<pIter->nPhrase; i++){
  165609. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  165610. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  165611. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  165612. }
  165613. }
  165614. return 0;
  165615. }
  165616. /*
  165617. ** Retrieve information about the current candidate snippet of snippet
  165618. ** iterator pIter.
  165619. */
  165620. static void fts3SnippetDetails(
  165621. SnippetIter *pIter, /* Snippet iterator */
  165622. u64 mCovered, /* Bitmask of phrases already covered */
  165623. int *piToken, /* OUT: First token of proposed snippet */
  165624. int *piScore, /* OUT: "Score" for this snippet */
  165625. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  165626. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  165627. ){
  165628. int iStart = pIter->iCurrent; /* First token of snippet */
  165629. int iScore = 0; /* Score of this snippet */
  165630. int i; /* Loop counter */
  165631. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  165632. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  165633. for(i=0; i<pIter->nPhrase; i++){
  165634. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  165635. if( pPhrase->pTail ){
  165636. char *pCsr = pPhrase->pTail;
  165637. int iCsr = pPhrase->iTail;
  165638. while( iCsr<(iStart+pIter->nSnippet) && iCsr>=iStart ){
  165639. int j;
  165640. u64 mPhrase = (u64)1 << i;
  165641. u64 mPos = (u64)1 << (iCsr - iStart);
  165642. assert( iCsr>=iStart && (iCsr - iStart)<=64 );
  165643. assert( i>=0 && i<=64 );
  165644. if( (mCover|mCovered)&mPhrase ){
  165645. iScore++;
  165646. }else{
  165647. iScore += 1000;
  165648. }
  165649. mCover |= mPhrase;
  165650. for(j=0; j<pPhrase->nToken; j++){
  165651. mHighlight |= (mPos>>j);
  165652. }
  165653. if( 0==(*pCsr & 0x0FE) ) break;
  165654. fts3GetDeltaPosition(&pCsr, &iCsr);
  165655. }
  165656. }
  165657. }
  165658. /* Set the output variables before returning. */
  165659. *piToken = iStart;
  165660. *piScore = iScore;
  165661. *pmCover = mCover;
  165662. *pmHighlight = mHighlight;
  165663. }
  165664. /*
  165665. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  165666. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  165667. */
  165668. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  165669. SnippetIter *p = (SnippetIter *)ctx;
  165670. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  165671. char *pCsr;
  165672. int rc;
  165673. pPhrase->nToken = pExpr->pPhrase->nToken;
  165674. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  165675. assert( rc==SQLITE_OK || pCsr==0 );
  165676. if( pCsr ){
  165677. int iFirst = 0;
  165678. pPhrase->pList = pCsr;
  165679. fts3GetDeltaPosition(&pCsr, &iFirst);
  165680. if( iFirst<0 ){
  165681. rc = FTS_CORRUPT_VTAB;
  165682. }else{
  165683. pPhrase->pHead = pCsr;
  165684. pPhrase->pTail = pCsr;
  165685. pPhrase->iHead = iFirst;
  165686. pPhrase->iTail = iFirst;
  165687. }
  165688. }else{
  165689. assert( rc!=SQLITE_OK || (
  165690. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  165691. ));
  165692. }
  165693. return rc;
  165694. }
  165695. /*
  165696. ** Select the fragment of text consisting of nFragment contiguous tokens
  165697. ** from column iCol that represent the "best" snippet. The best snippet
  165698. ** is the snippet with the highest score, where scores are calculated
  165699. ** by adding:
  165700. **
  165701. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  165702. **
  165703. ** (b) +1000 points for the first occurrence of each matchable phrase in
  165704. ** the snippet for which the corresponding mCovered bit is not set.
  165705. **
  165706. ** The selected snippet parameters are stored in structure *pFragment before
  165707. ** returning. The score of the selected snippet is stored in *piScore
  165708. ** before returning.
  165709. */
  165710. static int fts3BestSnippet(
  165711. int nSnippet, /* Desired snippet length */
  165712. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  165713. int iCol, /* Index of column to create snippet from */
  165714. u64 mCovered, /* Mask of phrases already covered */
  165715. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  165716. SnippetFragment *pFragment, /* OUT: Best snippet found */
  165717. int *piScore /* OUT: Score of snippet pFragment */
  165718. ){
  165719. int rc; /* Return Code */
  165720. int nList; /* Number of phrases in expression */
  165721. SnippetIter sIter; /* Iterates through snippet candidates */
  165722. sqlite3_int64 nByte; /* Number of bytes of space to allocate */
  165723. int iBestScore = -1; /* Best snippet score found so far */
  165724. int i; /* Loop counter */
  165725. memset(&sIter, 0, sizeof(sIter));
  165726. /* Iterate through the phrases in the expression to count them. The same
  165727. ** callback makes sure the doclists are loaded for each phrase.
  165728. */
  165729. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  165730. if( rc!=SQLITE_OK ){
  165731. return rc;
  165732. }
  165733. /* Now that it is known how many phrases there are, allocate and zero
  165734. ** the required space using malloc().
  165735. */
  165736. nByte = sizeof(SnippetPhrase) * nList;
  165737. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc64(nByte);
  165738. if( !sIter.aPhrase ){
  165739. return SQLITE_NOMEM;
  165740. }
  165741. memset(sIter.aPhrase, 0, nByte);
  165742. /* Initialize the contents of the SnippetIter object. Then iterate through
  165743. ** the set of phrases in the expression to populate the aPhrase[] array.
  165744. */
  165745. sIter.pCsr = pCsr;
  165746. sIter.iCol = iCol;
  165747. sIter.nSnippet = nSnippet;
  165748. sIter.nPhrase = nList;
  165749. sIter.iCurrent = -1;
  165750. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  165751. if( rc==SQLITE_OK ){
  165752. /* Set the *pmSeen output variable. */
  165753. for(i=0; i<nList; i++){
  165754. if( sIter.aPhrase[i].pHead ){
  165755. *pmSeen |= (u64)1 << i;
  165756. }
  165757. }
  165758. /* Loop through all candidate snippets. Store the best snippet in
  165759. ** *pFragment. Store its associated 'score' in iBestScore.
  165760. */
  165761. pFragment->iCol = iCol;
  165762. while( !fts3SnippetNextCandidate(&sIter) ){
  165763. int iPos;
  165764. int iScore;
  165765. u64 mCover;
  165766. u64 mHighlite;
  165767. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  165768. assert( iScore>=0 );
  165769. if( iScore>iBestScore ){
  165770. pFragment->iPos = iPos;
  165771. pFragment->hlmask = mHighlite;
  165772. pFragment->covered = mCover;
  165773. iBestScore = iScore;
  165774. }
  165775. }
  165776. *piScore = iBestScore;
  165777. }
  165778. sqlite3_free(sIter.aPhrase);
  165779. return rc;
  165780. }
  165781. /*
  165782. ** Append a string to the string-buffer passed as the first argument.
  165783. **
  165784. ** If nAppend is negative, then the length of the string zAppend is
  165785. ** determined using strlen().
  165786. */
  165787. static int fts3StringAppend(
  165788. StrBuffer *pStr, /* Buffer to append to */
  165789. const char *zAppend, /* Pointer to data to append to buffer */
  165790. int nAppend /* Size of zAppend in bytes (or -1) */
  165791. ){
  165792. if( nAppend<0 ){
  165793. nAppend = (int)strlen(zAppend);
  165794. }
  165795. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  165796. ** to grow the buffer until so that it is big enough to accomadate the
  165797. ** appended data.
  165798. */
  165799. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  165800. sqlite3_int64 nAlloc = pStr->nAlloc+(sqlite3_int64)nAppend+100;
  165801. char *zNew = sqlite3_realloc64(pStr->z, nAlloc);
  165802. if( !zNew ){
  165803. return SQLITE_NOMEM;
  165804. }
  165805. pStr->z = zNew;
  165806. pStr->nAlloc = nAlloc;
  165807. }
  165808. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  165809. /* Append the data to the string buffer. */
  165810. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  165811. pStr->n += nAppend;
  165812. pStr->z[pStr->n] = '\0';
  165813. return SQLITE_OK;
  165814. }
  165815. /*
  165816. ** The fts3BestSnippet() function often selects snippets that end with a
  165817. ** query term. That is, the final term of the snippet is always a term
  165818. ** that requires highlighting. For example, if 'X' is a highlighted term
  165819. ** and '.' is a non-highlighted term, BestSnippet() may select:
  165820. **
  165821. ** ........X.....X
  165822. **
  165823. ** This function "shifts" the beginning of the snippet forward in the
  165824. ** document so that there are approximately the same number of
  165825. ** non-highlighted terms to the right of the final highlighted term as there
  165826. ** are to the left of the first highlighted term. For example, to this:
  165827. **
  165828. ** ....X.....X....
  165829. **
  165830. ** This is done as part of extracting the snippet text, not when selecting
  165831. ** the snippet. Snippet selection is done based on doclists only, so there
  165832. ** is no way for fts3BestSnippet() to know whether or not the document
  165833. ** actually contains terms that follow the final highlighted term.
  165834. */
  165835. static int fts3SnippetShift(
  165836. Fts3Table *pTab, /* FTS3 table snippet comes from */
  165837. int iLangid, /* Language id to use in tokenizing */
  165838. int nSnippet, /* Number of tokens desired for snippet */
  165839. const char *zDoc, /* Document text to extract snippet from */
  165840. int nDoc, /* Size of buffer zDoc in bytes */
  165841. int *piPos, /* IN/OUT: First token of snippet */
  165842. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  165843. ){
  165844. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  165845. if( hlmask ){
  165846. int nLeft; /* Tokens to the left of first highlight */
  165847. int nRight; /* Tokens to the right of last highlight */
  165848. int nDesired; /* Ideal number of tokens to shift forward */
  165849. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  165850. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  165851. assert( (nSnippet-1-nRight)<=63 && (nSnippet-1-nRight)>=0 );
  165852. nDesired = (nLeft-nRight)/2;
  165853. /* Ideally, the start of the snippet should be pushed forward in the
  165854. ** document nDesired tokens. This block checks if there are actually
  165855. ** nDesired tokens to the right of the snippet. If so, *piPos and
  165856. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  165857. ** right. Otherwise, the snippet is shifted by the number of tokens
  165858. ** available.
  165859. */
  165860. if( nDesired>0 ){
  165861. int nShift; /* Number of tokens to shift snippet by */
  165862. int iCurrent = 0; /* Token counter */
  165863. int rc; /* Return Code */
  165864. sqlite3_tokenizer_module *pMod;
  165865. sqlite3_tokenizer_cursor *pC;
  165866. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  165867. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  165868. ** or more tokens in zDoc/nDoc.
  165869. */
  165870. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  165871. if( rc!=SQLITE_OK ){
  165872. return rc;
  165873. }
  165874. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  165875. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  165876. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  165877. }
  165878. pMod->xClose(pC);
  165879. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  165880. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  165881. assert( nShift<=nDesired );
  165882. if( nShift>0 ){
  165883. *piPos += nShift;
  165884. *pHlmask = hlmask >> nShift;
  165885. }
  165886. }
  165887. }
  165888. return SQLITE_OK;
  165889. }
  165890. /*
  165891. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  165892. ** append it to string buffer pOut.
  165893. */
  165894. static int fts3SnippetText(
  165895. Fts3Cursor *pCsr, /* FTS3 Cursor */
  165896. SnippetFragment *pFragment, /* Snippet to extract */
  165897. int iFragment, /* Fragment number */
  165898. int isLast, /* True for final fragment in snippet */
  165899. int nSnippet, /* Number of tokens in extracted snippet */
  165900. const char *zOpen, /* String inserted before highlighted term */
  165901. const char *zClose, /* String inserted after highlighted term */
  165902. const char *zEllipsis, /* String inserted between snippets */
  165903. StrBuffer *pOut /* Write output here */
  165904. ){
  165905. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  165906. int rc; /* Return code */
  165907. const char *zDoc; /* Document text to extract snippet from */
  165908. int nDoc; /* Size of zDoc in bytes */
  165909. int iCurrent = 0; /* Current token number of document */
  165910. int iEnd = 0; /* Byte offset of end of current token */
  165911. int isShiftDone = 0; /* True after snippet is shifted */
  165912. int iPos = pFragment->iPos; /* First token of snippet */
  165913. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  165914. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  165915. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  165916. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  165917. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  165918. if( zDoc==0 ){
  165919. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  165920. return SQLITE_NOMEM;
  165921. }
  165922. return SQLITE_OK;
  165923. }
  165924. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  165925. /* Open a token cursor on the document. */
  165926. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  165927. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  165928. if( rc!=SQLITE_OK ){
  165929. return rc;
  165930. }
  165931. while( rc==SQLITE_OK ){
  165932. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  165933. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  165934. int iBegin = 0; /* Offset in zDoc of start of token */
  165935. int iFin = 0; /* Offset in zDoc of end of token */
  165936. int isHighlight = 0; /* True for highlighted terms */
  165937. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  165938. ** in the FTS code the variable that the third argument to xNext points to
  165939. ** is initialized to zero before the first (*but not necessarily
  165940. ** subsequent*) call to xNext(). This is done for a particular application
  165941. ** that needs to know whether or not the tokenizer is being used for
  165942. ** snippet generation or for some other purpose.
  165943. **
  165944. ** Extreme care is required when writing code to depend on this
  165945. ** initialization. It is not a documented part of the tokenizer interface.
  165946. ** If a tokenizer is used directly by any code outside of FTS, this
  165947. ** convention might not be respected. */
  165948. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  165949. if( rc!=SQLITE_OK ){
  165950. if( rc==SQLITE_DONE ){
  165951. /* Special case - the last token of the snippet is also the last token
  165952. ** of the column. Append any punctuation that occurred between the end
  165953. ** of the previous token and the end of the document to the output.
  165954. ** Then break out of the loop. */
  165955. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  165956. }
  165957. break;
  165958. }
  165959. if( iCurrent<iPos ){ continue; }
  165960. if( !isShiftDone ){
  165961. int n = nDoc - iBegin;
  165962. rc = fts3SnippetShift(
  165963. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  165964. );
  165965. isShiftDone = 1;
  165966. /* Now that the shift has been done, check if the initial "..." are
  165967. ** required. They are required if (a) this is not the first fragment,
  165968. ** or (b) this fragment does not begin at position 0 of its column.
  165969. */
  165970. if( rc==SQLITE_OK ){
  165971. if( iPos>0 || iFragment>0 ){
  165972. rc = fts3StringAppend(pOut, zEllipsis, -1);
  165973. }else if( iBegin ){
  165974. rc = fts3StringAppend(pOut, zDoc, iBegin);
  165975. }
  165976. }
  165977. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  165978. }
  165979. if( iCurrent>=(iPos+nSnippet) ){
  165980. if( isLast ){
  165981. rc = fts3StringAppend(pOut, zEllipsis, -1);
  165982. }
  165983. break;
  165984. }
  165985. /* Set isHighlight to true if this term should be highlighted. */
  165986. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  165987. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  165988. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  165989. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  165990. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  165991. iEnd = iFin;
  165992. }
  165993. pMod->xClose(pC);
  165994. return rc;
  165995. }
  165996. /*
  165997. ** This function is used to count the entries in a column-list (a
  165998. ** delta-encoded list of term offsets within a single column of a single
  165999. ** row). When this function is called, *ppCollist should point to the
  166000. ** beginning of the first varint in the column-list (the varint that
  166001. ** contains the position of the first matching term in the column data).
  166002. ** Before returning, *ppCollist is set to point to the first byte after
  166003. ** the last varint in the column-list (either the 0x00 signifying the end
  166004. ** of the position-list, or the 0x01 that precedes the column number of
  166005. ** the next column in the position-list).
  166006. **
  166007. ** The number of elements in the column-list is returned.
  166008. */
  166009. static int fts3ColumnlistCount(char **ppCollist){
  166010. char *pEnd = *ppCollist;
  166011. char c = 0;
  166012. int nEntry = 0;
  166013. /* A column-list is terminated by either a 0x01 or 0x00. */
  166014. while( 0xFE & (*pEnd | c) ){
  166015. c = *pEnd++ & 0x80;
  166016. if( !c ) nEntry++;
  166017. }
  166018. *ppCollist = pEnd;
  166019. return nEntry;
  166020. }
  166021. /*
  166022. ** This function gathers 'y' or 'b' data for a single phrase.
  166023. */
  166024. static int fts3ExprLHits(
  166025. Fts3Expr *pExpr, /* Phrase expression node */
  166026. MatchInfo *p /* Matchinfo context */
  166027. ){
  166028. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  166029. int iStart;
  166030. Fts3Phrase *pPhrase = pExpr->pPhrase;
  166031. char *pIter = pPhrase->doclist.pList;
  166032. int iCol = 0;
  166033. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  166034. if( p->flag==FTS3_MATCHINFO_LHITS ){
  166035. iStart = pExpr->iPhrase * p->nCol;
  166036. }else{
  166037. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  166038. }
  166039. while( 1 ){
  166040. int nHit = fts3ColumnlistCount(&pIter);
  166041. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  166042. if( p->flag==FTS3_MATCHINFO_LHITS ){
  166043. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  166044. }else if( nHit ){
  166045. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  166046. }
  166047. }
  166048. assert( *pIter==0x00 || *pIter==0x01 );
  166049. if( *pIter!=0x01 ) break;
  166050. pIter++;
  166051. pIter += fts3GetVarint32(pIter, &iCol);
  166052. if( iCol>=p->nCol ) return FTS_CORRUPT_VTAB;
  166053. }
  166054. return SQLITE_OK;
  166055. }
  166056. /*
  166057. ** Gather the results for matchinfo directives 'y' and 'b'.
  166058. */
  166059. static int fts3ExprLHitGather(
  166060. Fts3Expr *pExpr,
  166061. MatchInfo *p
  166062. ){
  166063. int rc = SQLITE_OK;
  166064. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  166065. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  166066. if( pExpr->pLeft ){
  166067. rc = fts3ExprLHitGather(pExpr->pLeft, p);
  166068. if( rc==SQLITE_OK ) rc = fts3ExprLHitGather(pExpr->pRight, p);
  166069. }else{
  166070. rc = fts3ExprLHits(pExpr, p);
  166071. }
  166072. }
  166073. return rc;
  166074. }
  166075. /*
  166076. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  166077. ** for a single query.
  166078. **
  166079. ** fts3ExprIterate() callback to load the 'global' elements of a
  166080. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  166081. ** of the matchinfo array that are constant for all rows returned by the
  166082. ** current query.
  166083. **
  166084. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  166085. ** function populates Matchinfo.aMatchinfo[] as follows:
  166086. **
  166087. ** for(iCol=0; iCol<nCol; iCol++){
  166088. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  166089. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  166090. ** }
  166091. **
  166092. ** where X is the number of matches for phrase iPhrase is column iCol of all
  166093. ** rows of the table. Y is the number of rows for which column iCol contains
  166094. ** at least one instance of phrase iPhrase.
  166095. **
  166096. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  166097. ** Y values are set to nDoc, where nDoc is the number of documents in the
  166098. ** file system. This is done because the full-text index doclist is required
  166099. ** to calculate these values properly, and the full-text index doclist is
  166100. ** not available for deferred tokens.
  166101. */
  166102. static int fts3ExprGlobalHitsCb(
  166103. Fts3Expr *pExpr, /* Phrase expression node */
  166104. int iPhrase, /* Phrase number (numbered from zero) */
  166105. void *pCtx /* Pointer to MatchInfo structure */
  166106. ){
  166107. MatchInfo *p = (MatchInfo *)pCtx;
  166108. return sqlite3Fts3EvalPhraseStats(
  166109. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  166110. );
  166111. }
  166112. /*
  166113. ** fts3ExprIterate() callback used to collect the "local" part of the
  166114. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  166115. ** array that are different for each row returned by the query.
  166116. */
  166117. static int fts3ExprLocalHitsCb(
  166118. Fts3Expr *pExpr, /* Phrase expression node */
  166119. int iPhrase, /* Phrase number */
  166120. void *pCtx /* Pointer to MatchInfo structure */
  166121. ){
  166122. int rc = SQLITE_OK;
  166123. MatchInfo *p = (MatchInfo *)pCtx;
  166124. int iStart = iPhrase * p->nCol * 3;
  166125. int i;
  166126. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  166127. char *pCsr;
  166128. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  166129. if( pCsr ){
  166130. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  166131. }else{
  166132. p->aMatchinfo[iStart+i*3] = 0;
  166133. }
  166134. }
  166135. return rc;
  166136. }
  166137. static int fts3MatchinfoCheck(
  166138. Fts3Table *pTab,
  166139. char cArg,
  166140. char **pzErr
  166141. ){
  166142. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  166143. || (cArg==FTS3_MATCHINFO_NCOL)
  166144. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  166145. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  166146. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  166147. || (cArg==FTS3_MATCHINFO_LCS)
  166148. || (cArg==FTS3_MATCHINFO_HITS)
  166149. || (cArg==FTS3_MATCHINFO_LHITS)
  166150. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  166151. ){
  166152. return SQLITE_OK;
  166153. }
  166154. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  166155. return SQLITE_ERROR;
  166156. }
  166157. static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  166158. size_t nVal; /* Number of integers output by cArg */
  166159. switch( cArg ){
  166160. case FTS3_MATCHINFO_NDOC:
  166161. case FTS3_MATCHINFO_NPHRASE:
  166162. case FTS3_MATCHINFO_NCOL:
  166163. nVal = 1;
  166164. break;
  166165. case FTS3_MATCHINFO_AVGLENGTH:
  166166. case FTS3_MATCHINFO_LENGTH:
  166167. case FTS3_MATCHINFO_LCS:
  166168. nVal = pInfo->nCol;
  166169. break;
  166170. case FTS3_MATCHINFO_LHITS:
  166171. nVal = pInfo->nCol * pInfo->nPhrase;
  166172. break;
  166173. case FTS3_MATCHINFO_LHITS_BM:
  166174. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  166175. break;
  166176. default:
  166177. assert( cArg==FTS3_MATCHINFO_HITS );
  166178. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  166179. break;
  166180. }
  166181. return nVal;
  166182. }
  166183. static int fts3MatchinfoSelectDoctotal(
  166184. Fts3Table *pTab,
  166185. sqlite3_stmt **ppStmt,
  166186. sqlite3_int64 *pnDoc,
  166187. const char **paLen
  166188. ){
  166189. sqlite3_stmt *pStmt;
  166190. const char *a;
  166191. sqlite3_int64 nDoc;
  166192. if( !*ppStmt ){
  166193. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  166194. if( rc!=SQLITE_OK ) return rc;
  166195. }
  166196. pStmt = *ppStmt;
  166197. assert( sqlite3_data_count(pStmt)==1 );
  166198. a = sqlite3_column_blob(pStmt, 0);
  166199. a += sqlite3Fts3GetVarint(a, &nDoc);
  166200. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  166201. *pnDoc = (u32)nDoc;
  166202. if( paLen ) *paLen = a;
  166203. return SQLITE_OK;
  166204. }
  166205. /*
  166206. ** An instance of the following structure is used to store state while
  166207. ** iterating through a multi-column position-list corresponding to the
  166208. ** hits for a single phrase on a single row in order to calculate the
  166209. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  166210. */
  166211. typedef struct LcsIterator LcsIterator;
  166212. struct LcsIterator {
  166213. Fts3Expr *pExpr; /* Pointer to phrase expression */
  166214. int iPosOffset; /* Tokens count up to end of this phrase */
  166215. char *pRead; /* Cursor used to iterate through aDoclist */
  166216. int iPos; /* Current position */
  166217. };
  166218. /*
  166219. ** If LcsIterator.iCol is set to the following value, the iterator has
  166220. ** finished iterating through all offsets for all columns.
  166221. */
  166222. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  166223. static int fts3MatchinfoLcsCb(
  166224. Fts3Expr *pExpr, /* Phrase expression node */
  166225. int iPhrase, /* Phrase number (numbered from zero) */
  166226. void *pCtx /* Pointer to MatchInfo structure */
  166227. ){
  166228. LcsIterator *aIter = (LcsIterator *)pCtx;
  166229. aIter[iPhrase].pExpr = pExpr;
  166230. return SQLITE_OK;
  166231. }
  166232. /*
  166233. ** Advance the iterator passed as an argument to the next position. Return
  166234. ** 1 if the iterator is at EOF or if it now points to the start of the
  166235. ** position list for the next column.
  166236. */
  166237. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  166238. char *pRead = pIter->pRead;
  166239. sqlite3_int64 iRead;
  166240. int rc = 0;
  166241. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  166242. if( iRead==0 || iRead==1 ){
  166243. pRead = 0;
  166244. rc = 1;
  166245. }else{
  166246. pIter->iPos += (int)(iRead-2);
  166247. }
  166248. pIter->pRead = pRead;
  166249. return rc;
  166250. }
  166251. /*
  166252. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  166253. **
  166254. ** If the call is successful, the longest-common-substring lengths for each
  166255. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  166256. ** array before returning. SQLITE_OK is returned in this case.
  166257. **
  166258. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  166259. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  166260. ** undefined.
  166261. */
  166262. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  166263. LcsIterator *aIter;
  166264. int i;
  166265. int iCol;
  166266. int nToken = 0;
  166267. int rc = SQLITE_OK;
  166268. /* Allocate and populate the array of LcsIterator objects. The array
  166269. ** contains one element for each matchable phrase in the query.
  166270. **/
  166271. aIter = sqlite3_malloc64(sizeof(LcsIterator) * pCsr->nPhrase);
  166272. if( !aIter ) return SQLITE_NOMEM;
  166273. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  166274. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  166275. for(i=0; i<pInfo->nPhrase; i++){
  166276. LcsIterator *pIter = &aIter[i];
  166277. nToken -= pIter->pExpr->pPhrase->nToken;
  166278. pIter->iPosOffset = nToken;
  166279. }
  166280. for(iCol=0; iCol<pInfo->nCol; iCol++){
  166281. int nLcs = 0; /* LCS value for this column */
  166282. int nLive = 0; /* Number of iterators in aIter not at EOF */
  166283. for(i=0; i<pInfo->nPhrase; i++){
  166284. LcsIterator *pIt = &aIter[i];
  166285. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  166286. if( rc!=SQLITE_OK ) goto matchinfo_lcs_out;
  166287. if( pIt->pRead ){
  166288. pIt->iPos = pIt->iPosOffset;
  166289. fts3LcsIteratorAdvance(pIt);
  166290. if( pIt->pRead==0 ){
  166291. rc = FTS_CORRUPT_VTAB;
  166292. goto matchinfo_lcs_out;
  166293. }
  166294. nLive++;
  166295. }
  166296. }
  166297. while( nLive>0 ){
  166298. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  166299. int nThisLcs = 0; /* LCS for the current iterator positions */
  166300. for(i=0; i<pInfo->nPhrase; i++){
  166301. LcsIterator *pIter = &aIter[i];
  166302. if( pIter->pRead==0 ){
  166303. /* This iterator is already at EOF for this column. */
  166304. nThisLcs = 0;
  166305. }else{
  166306. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  166307. pAdv = pIter;
  166308. }
  166309. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  166310. nThisLcs++;
  166311. }else{
  166312. nThisLcs = 1;
  166313. }
  166314. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  166315. }
  166316. }
  166317. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  166318. }
  166319. pInfo->aMatchinfo[iCol] = nLcs;
  166320. }
  166321. matchinfo_lcs_out:
  166322. sqlite3_free(aIter);
  166323. return rc;
  166324. }
  166325. /*
  166326. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  166327. ** be returned by the matchinfo() function. Argument zArg contains the
  166328. ** format string passed as the second argument to matchinfo (or the
  166329. ** default value "pcx" if no second argument was specified). The format
  166330. ** string has already been validated and the pInfo->aMatchinfo[] array
  166331. ** is guaranteed to be large enough for the output.
  166332. **
  166333. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  166334. ** If it is false, then assume that those fields that do not change between
  166335. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  166336. ** have already been populated.
  166337. **
  166338. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  166339. ** occurs. If a value other than SQLITE_OK is returned, the state the
  166340. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  166341. */
  166342. static int fts3MatchinfoValues(
  166343. Fts3Cursor *pCsr, /* FTS3 cursor object */
  166344. int bGlobal, /* True to grab the global stats */
  166345. MatchInfo *pInfo, /* Matchinfo context object */
  166346. const char *zArg /* Matchinfo format string */
  166347. ){
  166348. int rc = SQLITE_OK;
  166349. int i;
  166350. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  166351. sqlite3_stmt *pSelect = 0;
  166352. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  166353. pInfo->flag = zArg[i];
  166354. switch( zArg[i] ){
  166355. case FTS3_MATCHINFO_NPHRASE:
  166356. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  166357. break;
  166358. case FTS3_MATCHINFO_NCOL:
  166359. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  166360. break;
  166361. case FTS3_MATCHINFO_NDOC:
  166362. if( bGlobal ){
  166363. sqlite3_int64 nDoc = 0;
  166364. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  166365. pInfo->aMatchinfo[0] = (u32)nDoc;
  166366. }
  166367. break;
  166368. case FTS3_MATCHINFO_AVGLENGTH:
  166369. if( bGlobal ){
  166370. sqlite3_int64 nDoc; /* Number of rows in table */
  166371. const char *a; /* Aggregate column length array */
  166372. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  166373. if( rc==SQLITE_OK ){
  166374. int iCol;
  166375. for(iCol=0; iCol<pInfo->nCol; iCol++){
  166376. u32 iVal;
  166377. sqlite3_int64 nToken;
  166378. a += sqlite3Fts3GetVarint(a, &nToken);
  166379. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  166380. pInfo->aMatchinfo[iCol] = iVal;
  166381. }
  166382. }
  166383. }
  166384. break;
  166385. case FTS3_MATCHINFO_LENGTH: {
  166386. sqlite3_stmt *pSelectDocsize = 0;
  166387. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  166388. if( rc==SQLITE_OK ){
  166389. int iCol;
  166390. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  166391. for(iCol=0; iCol<pInfo->nCol; iCol++){
  166392. sqlite3_int64 nToken;
  166393. a += sqlite3Fts3GetVarint(a, &nToken);
  166394. pInfo->aMatchinfo[iCol] = (u32)nToken;
  166395. }
  166396. }
  166397. sqlite3_reset(pSelectDocsize);
  166398. break;
  166399. }
  166400. case FTS3_MATCHINFO_LCS:
  166401. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  166402. if( rc==SQLITE_OK ){
  166403. rc = fts3MatchinfoLcs(pCsr, pInfo);
  166404. }
  166405. break;
  166406. case FTS3_MATCHINFO_LHITS_BM:
  166407. case FTS3_MATCHINFO_LHITS: {
  166408. size_t nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  166409. memset(pInfo->aMatchinfo, 0, nZero);
  166410. rc = fts3ExprLHitGather(pCsr->pExpr, pInfo);
  166411. break;
  166412. }
  166413. default: {
  166414. Fts3Expr *pExpr;
  166415. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  166416. pExpr = pCsr->pExpr;
  166417. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  166418. if( rc!=SQLITE_OK ) break;
  166419. if( bGlobal ){
  166420. if( pCsr->pDeferred ){
  166421. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  166422. if( rc!=SQLITE_OK ) break;
  166423. }
  166424. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  166425. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  166426. if( rc!=SQLITE_OK ) break;
  166427. }
  166428. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  166429. break;
  166430. }
  166431. }
  166432. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  166433. }
  166434. sqlite3_reset(pSelect);
  166435. return rc;
  166436. }
  166437. /*
  166438. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  166439. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  166440. */
  166441. static void fts3GetMatchinfo(
  166442. sqlite3_context *pCtx, /* Return results here */
  166443. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  166444. const char *zArg /* Second argument to matchinfo() function */
  166445. ){
  166446. MatchInfo sInfo;
  166447. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  166448. int rc = SQLITE_OK;
  166449. int bGlobal = 0; /* Collect 'global' stats as well as local */
  166450. u32 *aOut = 0;
  166451. void (*xDestroyOut)(void*) = 0;
  166452. memset(&sInfo, 0, sizeof(MatchInfo));
  166453. sInfo.pCursor = pCsr;
  166454. sInfo.nCol = pTab->nColumn;
  166455. /* If there is cached matchinfo() data, but the format string for the
  166456. ** cache does not match the format string for this request, discard
  166457. ** the cached data. */
  166458. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  166459. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  166460. pCsr->pMIBuffer = 0;
  166461. }
  166462. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  166463. ** matchinfo function has been called for this query. In this case
  166464. ** allocate the array used to accumulate the matchinfo data and
  166465. ** initialize those elements that are constant for every row.
  166466. */
  166467. if( pCsr->pMIBuffer==0 ){
  166468. size_t nMatchinfo = 0; /* Number of u32 elements in match-info */
  166469. int i; /* Used to iterate through zArg */
  166470. /* Determine the number of phrases in the query */
  166471. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  166472. sInfo.nPhrase = pCsr->nPhrase;
  166473. /* Determine the number of integers in the buffer returned by this call. */
  166474. for(i=0; zArg[i]; i++){
  166475. char *zErr = 0;
  166476. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  166477. sqlite3_result_error(pCtx, zErr, -1);
  166478. sqlite3_free(zErr);
  166479. return;
  166480. }
  166481. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  166482. }
  166483. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  166484. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  166485. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  166486. pCsr->isMatchinfoNeeded = 1;
  166487. bGlobal = 1;
  166488. }
  166489. if( rc==SQLITE_OK ){
  166490. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  166491. if( xDestroyOut==0 ){
  166492. rc = SQLITE_NOMEM;
  166493. }
  166494. }
  166495. if( rc==SQLITE_OK ){
  166496. sInfo.aMatchinfo = aOut;
  166497. sInfo.nPhrase = pCsr->nPhrase;
  166498. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  166499. if( bGlobal ){
  166500. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  166501. }
  166502. }
  166503. if( rc!=SQLITE_OK ){
  166504. sqlite3_result_error_code(pCtx, rc);
  166505. if( xDestroyOut ) xDestroyOut(aOut);
  166506. }else{
  166507. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  166508. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  166509. }
  166510. }
  166511. /*
  166512. ** Implementation of snippet() function.
  166513. */
  166514. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  166515. sqlite3_context *pCtx, /* SQLite function call context */
  166516. Fts3Cursor *pCsr, /* Cursor object */
  166517. const char *zStart, /* Snippet start text - "<b>" */
  166518. const char *zEnd, /* Snippet end text - "</b>" */
  166519. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  166520. int iCol, /* Extract snippet from this column */
  166521. int nToken /* Approximate number of tokens in snippet */
  166522. ){
  166523. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  166524. int rc = SQLITE_OK;
  166525. int i;
  166526. StrBuffer res = {0, 0, 0};
  166527. /* The returned text includes up to four fragments of text extracted from
  166528. ** the data in the current row. The first iteration of the for(...) loop
  166529. ** below attempts to locate a single fragment of text nToken tokens in
  166530. ** size that contains at least one instance of all phrases in the query
  166531. ** expression that appear in the current row. If such a fragment of text
  166532. ** cannot be found, the second iteration of the loop attempts to locate
  166533. ** a pair of fragments, and so on.
  166534. */
  166535. int nSnippet = 0; /* Number of fragments in this snippet */
  166536. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  166537. int nFToken = -1; /* Number of tokens in each fragment */
  166538. if( !pCsr->pExpr ){
  166539. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  166540. return;
  166541. }
  166542. /* Limit the snippet length to 64 tokens. */
  166543. if( nToken<-64 ) nToken = -64;
  166544. if( nToken>+64 ) nToken = +64;
  166545. for(nSnippet=1; 1; nSnippet++){
  166546. int iSnip; /* Loop counter 0..nSnippet-1 */
  166547. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  166548. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  166549. if( nToken>=0 ){
  166550. nFToken = (nToken+nSnippet-1) / nSnippet;
  166551. }else{
  166552. nFToken = -1 * nToken;
  166553. }
  166554. for(iSnip=0; iSnip<nSnippet; iSnip++){
  166555. int iBestScore = -1; /* Best score of columns checked so far */
  166556. int iRead; /* Used to iterate through columns */
  166557. SnippetFragment *pFragment = &aSnippet[iSnip];
  166558. memset(pFragment, 0, sizeof(*pFragment));
  166559. /* Loop through all columns of the table being considered for snippets.
  166560. ** If the iCol argument to this function was negative, this means all
  166561. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  166562. */
  166563. for(iRead=0; iRead<pTab->nColumn; iRead++){
  166564. SnippetFragment sF = {0, 0, 0, 0};
  166565. int iS = 0;
  166566. if( iCol>=0 && iRead!=iCol ) continue;
  166567. /* Find the best snippet of nFToken tokens in column iRead. */
  166568. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  166569. if( rc!=SQLITE_OK ){
  166570. goto snippet_out;
  166571. }
  166572. if( iS>iBestScore ){
  166573. *pFragment = sF;
  166574. iBestScore = iS;
  166575. }
  166576. }
  166577. mCovered |= pFragment->covered;
  166578. }
  166579. /* If all query phrases seen by fts3BestSnippet() are present in at least
  166580. ** one of the nSnippet snippet fragments, break out of the loop.
  166581. */
  166582. assert( (mCovered&mSeen)==mCovered );
  166583. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  166584. }
  166585. assert( nFToken>0 );
  166586. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  166587. rc = fts3SnippetText(pCsr, &aSnippet[i],
  166588. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  166589. );
  166590. }
  166591. snippet_out:
  166592. sqlite3Fts3SegmentsClose(pTab);
  166593. if( rc!=SQLITE_OK ){
  166594. sqlite3_result_error_code(pCtx, rc);
  166595. sqlite3_free(res.z);
  166596. }else{
  166597. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  166598. }
  166599. }
  166600. typedef struct TermOffset TermOffset;
  166601. typedef struct TermOffsetCtx TermOffsetCtx;
  166602. struct TermOffset {
  166603. char *pList; /* Position-list */
  166604. int iPos; /* Position just read from pList */
  166605. int iOff; /* Offset of this term from read positions */
  166606. };
  166607. struct TermOffsetCtx {
  166608. Fts3Cursor *pCsr;
  166609. int iCol; /* Column of table to populate aTerm for */
  166610. int iTerm;
  166611. sqlite3_int64 iDocid;
  166612. TermOffset *aTerm;
  166613. };
  166614. /*
  166615. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  166616. */
  166617. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  166618. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  166619. int nTerm; /* Number of tokens in phrase */
  166620. int iTerm; /* For looping through nTerm phrase terms */
  166621. char *pList; /* Pointer to position list for phrase */
  166622. int iPos = 0; /* First position in position-list */
  166623. int rc;
  166624. UNUSED_PARAMETER(iPhrase);
  166625. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  166626. nTerm = pExpr->pPhrase->nToken;
  166627. if( pList ){
  166628. fts3GetDeltaPosition(&pList, &iPos);
  166629. assert_fts3_nc( iPos>=0 );
  166630. }
  166631. for(iTerm=0; iTerm<nTerm; iTerm++){
  166632. TermOffset *pT = &p->aTerm[p->iTerm++];
  166633. pT->iOff = nTerm-iTerm-1;
  166634. pT->pList = pList;
  166635. pT->iPos = iPos;
  166636. }
  166637. return rc;
  166638. }
  166639. /*
  166640. ** Implementation of offsets() function.
  166641. */
  166642. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  166643. sqlite3_context *pCtx, /* SQLite function call context */
  166644. Fts3Cursor *pCsr /* Cursor object */
  166645. ){
  166646. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  166647. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  166648. int rc; /* Return Code */
  166649. int nToken; /* Number of tokens in query */
  166650. int iCol; /* Column currently being processed */
  166651. StrBuffer res = {0, 0, 0}; /* Result string */
  166652. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  166653. if( !pCsr->pExpr ){
  166654. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  166655. return;
  166656. }
  166657. memset(&sCtx, 0, sizeof(sCtx));
  166658. assert( pCsr->isRequireSeek==0 );
  166659. /* Count the number of terms in the query */
  166660. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  166661. if( rc!=SQLITE_OK ) goto offsets_out;
  166662. /* Allocate the array of TermOffset iterators. */
  166663. sCtx.aTerm = (TermOffset *)sqlite3_malloc64(sizeof(TermOffset)*nToken);
  166664. if( 0==sCtx.aTerm ){
  166665. rc = SQLITE_NOMEM;
  166666. goto offsets_out;
  166667. }
  166668. sCtx.iDocid = pCsr->iPrevId;
  166669. sCtx.pCsr = pCsr;
  166670. /* Loop through the table columns, appending offset information to
  166671. ** string-buffer res for each column.
  166672. */
  166673. for(iCol=0; iCol<pTab->nColumn; iCol++){
  166674. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  166675. const char *ZDUMMY; /* Dummy argument used with xNext() */
  166676. int NDUMMY = 0; /* Dummy argument used with xNext() */
  166677. int iStart = 0;
  166678. int iEnd = 0;
  166679. int iCurrent = 0;
  166680. const char *zDoc;
  166681. int nDoc;
  166682. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  166683. ** no way that this operation can fail, so the return code from
  166684. ** fts3ExprIterate() can be discarded.
  166685. */
  166686. sCtx.iCol = iCol;
  166687. sCtx.iTerm = 0;
  166688. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  166689. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  166690. ** in column iCol, jump immediately to the next iteration of the loop.
  166691. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  166692. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  166693. ** to the caller.
  166694. */
  166695. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  166696. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  166697. if( zDoc==0 ){
  166698. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  166699. continue;
  166700. }
  166701. rc = SQLITE_NOMEM;
  166702. goto offsets_out;
  166703. }
  166704. /* Initialize a tokenizer iterator to iterate through column iCol. */
  166705. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  166706. zDoc, nDoc, &pC
  166707. );
  166708. if( rc!=SQLITE_OK ) goto offsets_out;
  166709. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  166710. while( rc==SQLITE_OK ){
  166711. int i; /* Used to loop through terms */
  166712. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  166713. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  166714. for(i=0; i<nToken; i++){
  166715. TermOffset *pT = &sCtx.aTerm[i];
  166716. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  166717. iMinPos = pT->iPos-pT->iOff;
  166718. pTerm = pT;
  166719. }
  166720. }
  166721. if( !pTerm ){
  166722. /* All offsets for this column have been gathered. */
  166723. rc = SQLITE_DONE;
  166724. }else{
  166725. assert_fts3_nc( iCurrent<=iMinPos );
  166726. if( 0==(0xFE&*pTerm->pList) ){
  166727. pTerm->pList = 0;
  166728. }else{
  166729. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  166730. }
  166731. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  166732. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  166733. }
  166734. if( rc==SQLITE_OK ){
  166735. char aBuffer[64];
  166736. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  166737. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  166738. );
  166739. rc = fts3StringAppend(&res, aBuffer, -1);
  166740. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  166741. rc = FTS_CORRUPT_VTAB;
  166742. }
  166743. }
  166744. }
  166745. if( rc==SQLITE_DONE ){
  166746. rc = SQLITE_OK;
  166747. }
  166748. pMod->xClose(pC);
  166749. if( rc!=SQLITE_OK ) goto offsets_out;
  166750. }
  166751. offsets_out:
  166752. sqlite3_free(sCtx.aTerm);
  166753. assert( rc!=SQLITE_DONE );
  166754. sqlite3Fts3SegmentsClose(pTab);
  166755. if( rc!=SQLITE_OK ){
  166756. sqlite3_result_error_code(pCtx, rc);
  166757. sqlite3_free(res.z);
  166758. }else{
  166759. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  166760. }
  166761. return;
  166762. }
  166763. /*
  166764. ** Implementation of matchinfo() function.
  166765. */
  166766. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  166767. sqlite3_context *pContext, /* Function call context */
  166768. Fts3Cursor *pCsr, /* FTS3 table cursor */
  166769. const char *zArg /* Second arg to matchinfo() function */
  166770. ){
  166771. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  166772. const char *zFormat;
  166773. if( zArg ){
  166774. zFormat = zArg;
  166775. }else{
  166776. zFormat = FTS3_MATCHINFO_DEFAULT;
  166777. }
  166778. if( !pCsr->pExpr ){
  166779. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  166780. return;
  166781. }else{
  166782. /* Retrieve matchinfo() data. */
  166783. fts3GetMatchinfo(pContext, pCsr, zFormat);
  166784. sqlite3Fts3SegmentsClose(pTab);
  166785. }
  166786. }
  166787. #endif
  166788. /************** End of fts3_snippet.c ****************************************/
  166789. /************** Begin file fts3_unicode.c ************************************/
  166790. /*
  166791. ** 2012 May 24
  166792. **
  166793. ** The author disclaims copyright to this source code. In place of
  166794. ** a legal notice, here is a blessing:
  166795. **
  166796. ** May you do good and not evil.
  166797. ** May you find forgiveness for yourself and forgive others.
  166798. ** May you share freely, never taking more than you give.
  166799. **
  166800. ******************************************************************************
  166801. **
  166802. ** Implementation of the "unicode" full-text-search tokenizer.
  166803. */
  166804. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  166805. /* #include "fts3Int.h" */
  166806. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  166807. /* #include <assert.h> */
  166808. /* #include <stdlib.h> */
  166809. /* #include <stdio.h> */
  166810. /* #include <string.h> */
  166811. /* #include "fts3_tokenizer.h" */
  166812. /*
  166813. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  166814. ** from the sqlite3 source file utf.c. If this file is compiled as part
  166815. ** of the amalgamation, they are not required.
  166816. */
  166817. #ifndef SQLITE_AMALGAMATION
  166818. static const unsigned char sqlite3Utf8Trans1[] = {
  166819. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  166820. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  166821. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  166822. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  166823. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  166824. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  166825. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  166826. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  166827. };
  166828. #define READ_UTF8(zIn, zTerm, c) \
  166829. c = *(zIn++); \
  166830. if( c>=0xc0 ){ \
  166831. c = sqlite3Utf8Trans1[c-0xc0]; \
  166832. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  166833. c = (c<<6) + (0x3f & *(zIn++)); \
  166834. } \
  166835. if( c<0x80 \
  166836. || (c&0xFFFFF800)==0xD800 \
  166837. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  166838. }
  166839. #define WRITE_UTF8(zOut, c) { \
  166840. if( c<0x00080 ){ \
  166841. *zOut++ = (u8)(c&0xFF); \
  166842. } \
  166843. else if( c<0x00800 ){ \
  166844. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  166845. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  166846. } \
  166847. else if( c<0x10000 ){ \
  166848. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  166849. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  166850. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  166851. }else{ \
  166852. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  166853. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  166854. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  166855. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  166856. } \
  166857. }
  166858. #endif /* ifndef SQLITE_AMALGAMATION */
  166859. typedef struct unicode_tokenizer unicode_tokenizer;
  166860. typedef struct unicode_cursor unicode_cursor;
  166861. struct unicode_tokenizer {
  166862. sqlite3_tokenizer base;
  166863. int eRemoveDiacritic;
  166864. int nException;
  166865. int *aiException;
  166866. };
  166867. struct unicode_cursor {
  166868. sqlite3_tokenizer_cursor base;
  166869. const unsigned char *aInput; /* Input text being tokenized */
  166870. int nInput; /* Size of aInput[] in bytes */
  166871. int iOff; /* Current offset within aInput[] */
  166872. int iToken; /* Index of next token to be returned */
  166873. char *zToken; /* storage for current token */
  166874. int nAlloc; /* space allocated at zToken */
  166875. };
  166876. /*
  166877. ** Destroy a tokenizer allocated by unicodeCreate().
  166878. */
  166879. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  166880. if( pTokenizer ){
  166881. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  166882. sqlite3_free(p->aiException);
  166883. sqlite3_free(p);
  166884. }
  166885. return SQLITE_OK;
  166886. }
  166887. /*
  166888. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  166889. ** statement has specified that the tokenizer for this table shall consider
  166890. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  166891. ** token characters (if bAlnum==1).
  166892. **
  166893. ** For each codepoint in the zIn/nIn string, this function checks if the
  166894. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  166895. ** If so, no action is taken. Otherwise, the codepoint is added to the
  166896. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  166897. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  166898. ** codepoints in the aiException[] array.
  166899. **
  166900. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  166901. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  166902. ** It is not possible to change the behavior of the tokenizer with respect
  166903. ** to these codepoints.
  166904. */
  166905. static int unicodeAddExceptions(
  166906. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  166907. int bAlnum, /* Replace Isalnum() return value with this */
  166908. const char *zIn, /* Array of characters to make exceptions */
  166909. int nIn /* Length of z in bytes */
  166910. ){
  166911. const unsigned char *z = (const unsigned char *)zIn;
  166912. const unsigned char *zTerm = &z[nIn];
  166913. unsigned int iCode;
  166914. int nEntry = 0;
  166915. assert( bAlnum==0 || bAlnum==1 );
  166916. while( z<zTerm ){
  166917. READ_UTF8(z, zTerm, iCode);
  166918. assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
  166919. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  166920. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  166921. ){
  166922. nEntry++;
  166923. }
  166924. }
  166925. if( nEntry ){
  166926. int *aNew; /* New aiException[] array */
  166927. int nNew; /* Number of valid entries in array aNew[] */
  166928. aNew = sqlite3_realloc64(p->aiException,(p->nException+nEntry)*sizeof(int));
  166929. if( aNew==0 ) return SQLITE_NOMEM;
  166930. nNew = p->nException;
  166931. z = (const unsigned char *)zIn;
  166932. while( z<zTerm ){
  166933. READ_UTF8(z, zTerm, iCode);
  166934. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  166935. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  166936. ){
  166937. int i, j;
  166938. for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
  166939. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  166940. aNew[i] = (int)iCode;
  166941. nNew++;
  166942. }
  166943. }
  166944. p->aiException = aNew;
  166945. p->nException = nNew;
  166946. }
  166947. return SQLITE_OK;
  166948. }
  166949. /*
  166950. ** Return true if the p->aiException[] array contains the value iCode.
  166951. */
  166952. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  166953. if( p->nException>0 ){
  166954. int *a = p->aiException;
  166955. int iLo = 0;
  166956. int iHi = p->nException-1;
  166957. while( iHi>=iLo ){
  166958. int iTest = (iHi + iLo) / 2;
  166959. if( iCode==a[iTest] ){
  166960. return 1;
  166961. }else if( iCode>a[iTest] ){
  166962. iLo = iTest+1;
  166963. }else{
  166964. iHi = iTest-1;
  166965. }
  166966. }
  166967. }
  166968. return 0;
  166969. }
  166970. /*
  166971. ** Return true if, for the purposes of tokenization, codepoint iCode is
  166972. ** considered a token character (not a separator).
  166973. */
  166974. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  166975. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  166976. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  166977. }
  166978. /*
  166979. ** Create a new tokenizer instance.
  166980. */
  166981. static int unicodeCreate(
  166982. int nArg, /* Size of array argv[] */
  166983. const char * const *azArg, /* Tokenizer creation arguments */
  166984. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  166985. ){
  166986. unicode_tokenizer *pNew; /* New tokenizer object */
  166987. int i;
  166988. int rc = SQLITE_OK;
  166989. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  166990. if( pNew==NULL ) return SQLITE_NOMEM;
  166991. memset(pNew, 0, sizeof(unicode_tokenizer));
  166992. pNew->eRemoveDiacritic = 1;
  166993. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  166994. const char *z = azArg[i];
  166995. int n = (int)strlen(z);
  166996. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  166997. pNew->eRemoveDiacritic = 1;
  166998. }
  166999. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  167000. pNew->eRemoveDiacritic = 0;
  167001. }
  167002. else if( n==19 && memcmp("remove_diacritics=2", z, 19)==0 ){
  167003. pNew->eRemoveDiacritic = 2;
  167004. }
  167005. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  167006. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  167007. }
  167008. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  167009. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  167010. }
  167011. else{
  167012. /* Unrecognized argument */
  167013. rc = SQLITE_ERROR;
  167014. }
  167015. }
  167016. if( rc!=SQLITE_OK ){
  167017. unicodeDestroy((sqlite3_tokenizer *)pNew);
  167018. pNew = 0;
  167019. }
  167020. *pp = (sqlite3_tokenizer *)pNew;
  167021. return rc;
  167022. }
  167023. /*
  167024. ** Prepare to begin tokenizing a particular string. The input
  167025. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  167026. ** used to incrementally tokenize this string is returned in
  167027. ** *ppCursor.
  167028. */
  167029. static int unicodeOpen(
  167030. sqlite3_tokenizer *p, /* The tokenizer */
  167031. const char *aInput, /* Input string */
  167032. int nInput, /* Size of string aInput in bytes */
  167033. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  167034. ){
  167035. unicode_cursor *pCsr;
  167036. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  167037. if( pCsr==0 ){
  167038. return SQLITE_NOMEM;
  167039. }
  167040. memset(pCsr, 0, sizeof(unicode_cursor));
  167041. pCsr->aInput = (const unsigned char *)aInput;
  167042. if( aInput==0 ){
  167043. pCsr->nInput = 0;
  167044. }else if( nInput<0 ){
  167045. pCsr->nInput = (int)strlen(aInput);
  167046. }else{
  167047. pCsr->nInput = nInput;
  167048. }
  167049. *pp = &pCsr->base;
  167050. UNUSED_PARAMETER(p);
  167051. return SQLITE_OK;
  167052. }
  167053. /*
  167054. ** Close a tokenization cursor previously opened by a call to
  167055. ** simpleOpen() above.
  167056. */
  167057. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  167058. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  167059. sqlite3_free(pCsr->zToken);
  167060. sqlite3_free(pCsr);
  167061. return SQLITE_OK;
  167062. }
  167063. /*
  167064. ** Extract the next token from a tokenization cursor. The cursor must
  167065. ** have been opened by a prior call to simpleOpen().
  167066. */
  167067. static int unicodeNext(
  167068. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  167069. const char **paToken, /* OUT: Token text */
  167070. int *pnToken, /* OUT: Number of bytes at *paToken */
  167071. int *piStart, /* OUT: Starting offset of token */
  167072. int *piEnd, /* OUT: Ending offset of token */
  167073. int *piPos /* OUT: Position integer of token */
  167074. ){
  167075. unicode_cursor *pCsr = (unicode_cursor *)pC;
  167076. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  167077. unsigned int iCode = 0;
  167078. char *zOut;
  167079. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  167080. const unsigned char *zStart = z;
  167081. const unsigned char *zEnd;
  167082. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  167083. /* Scan past any delimiter characters before the start of the next token.
  167084. ** Return SQLITE_DONE early if this takes us all the way to the end of
  167085. ** the input. */
  167086. while( z<zTerm ){
  167087. READ_UTF8(z, zTerm, iCode);
  167088. if( unicodeIsAlnum(p, (int)iCode) ) break;
  167089. zStart = z;
  167090. }
  167091. if( zStart>=zTerm ) return SQLITE_DONE;
  167092. zOut = pCsr->zToken;
  167093. do {
  167094. int iOut;
  167095. /* Grow the output buffer if required. */
  167096. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  167097. char *zNew = sqlite3_realloc64(pCsr->zToken, pCsr->nAlloc+64);
  167098. if( !zNew ) return SQLITE_NOMEM;
  167099. zOut = &zNew[zOut - pCsr->zToken];
  167100. pCsr->zToken = zNew;
  167101. pCsr->nAlloc += 64;
  167102. }
  167103. /* Write the folded case of the last character read to the output */
  167104. zEnd = z;
  167105. iOut = sqlite3FtsUnicodeFold((int)iCode, p->eRemoveDiacritic);
  167106. if( iOut ){
  167107. WRITE_UTF8(zOut, iOut);
  167108. }
  167109. /* If the cursor is not at EOF, read the next character */
  167110. if( z>=zTerm ) break;
  167111. READ_UTF8(z, zTerm, iCode);
  167112. }while( unicodeIsAlnum(p, (int)iCode)
  167113. || sqlite3FtsUnicodeIsdiacritic((int)iCode)
  167114. );
  167115. /* Set the output variables and return. */
  167116. pCsr->iOff = (int)(z - pCsr->aInput);
  167117. *paToken = pCsr->zToken;
  167118. *pnToken = (int)(zOut - pCsr->zToken);
  167119. *piStart = (int)(zStart - pCsr->aInput);
  167120. *piEnd = (int)(zEnd - pCsr->aInput);
  167121. *piPos = pCsr->iToken++;
  167122. return SQLITE_OK;
  167123. }
  167124. /*
  167125. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  167126. ** structure for the unicode tokenizer.
  167127. */
  167128. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  167129. static const sqlite3_tokenizer_module module = {
  167130. 0,
  167131. unicodeCreate,
  167132. unicodeDestroy,
  167133. unicodeOpen,
  167134. unicodeClose,
  167135. unicodeNext,
  167136. 0,
  167137. };
  167138. *ppModule = &module;
  167139. }
  167140. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  167141. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  167142. /************** End of fts3_unicode.c ****************************************/
  167143. /************** Begin file fts3_unicode2.c ***********************************/
  167144. /*
  167145. ** 2012-05-25
  167146. **
  167147. ** The author disclaims copyright to this source code. In place of
  167148. ** a legal notice, here is a blessing:
  167149. **
  167150. ** May you do good and not evil.
  167151. ** May you find forgiveness for yourself and forgive others.
  167152. ** May you share freely, never taking more than you give.
  167153. **
  167154. ******************************************************************************
  167155. */
  167156. /*
  167157. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  167158. */
  167159. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  167160. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  167161. /* #include <assert.h> */
  167162. /*
  167163. ** Return true if the argument corresponds to a unicode codepoint
  167164. ** classified as either a letter or a number. Otherwise false.
  167165. **
  167166. ** The results are undefined if the value passed to this function
  167167. ** is less than zero.
  167168. */
  167169. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  167170. /* Each unsigned integer in the following array corresponds to a contiguous
  167171. ** range of unicode codepoints that are not either letters or numbers (i.e.
  167172. ** codepoints for which this function should return 0).
  167173. **
  167174. ** The most significant 22 bits in each 32-bit value contain the first
  167175. ** codepoint in the range. The least significant 10 bits are used to store
  167176. ** the size of the range (always at least 1). In other words, the value
  167177. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  167178. ** C. It is not possible to represent a range larger than 1023 codepoints
  167179. ** using this format.
  167180. */
  167181. static const unsigned int aEntry[] = {
  167182. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  167183. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  167184. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  167185. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  167186. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  167187. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  167188. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  167189. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  167190. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  167191. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  167192. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  167193. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  167194. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  167195. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  167196. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  167197. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  167198. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  167199. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  167200. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  167201. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  167202. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  167203. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  167204. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  167205. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  167206. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  167207. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  167208. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  167209. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  167210. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  167211. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  167212. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  167213. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  167214. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  167215. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  167216. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  167217. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  167218. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  167219. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  167220. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  167221. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  167222. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  167223. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  167224. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  167225. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  167226. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  167227. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  167228. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  167229. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  167230. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  167231. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  167232. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  167233. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  167234. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  167235. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  167236. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  167237. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  167238. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  167239. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  167240. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  167241. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  167242. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  167243. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  167244. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  167245. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  167246. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  167247. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  167248. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  167249. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  167250. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  167251. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  167252. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  167253. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  167254. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  167255. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  167256. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  167257. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  167258. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  167259. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  167260. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  167261. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  167262. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  167263. 0x380400F0,
  167264. };
  167265. static const unsigned int aAscii[4] = {
  167266. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  167267. };
  167268. if( (unsigned int)c<128 ){
  167269. return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
  167270. }else if( (unsigned int)c<(1<<22) ){
  167271. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  167272. int iRes = 0;
  167273. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  167274. int iLo = 0;
  167275. while( iHi>=iLo ){
  167276. int iTest = (iHi + iLo) / 2;
  167277. if( key >= aEntry[iTest] ){
  167278. iRes = iTest;
  167279. iLo = iTest+1;
  167280. }else{
  167281. iHi = iTest-1;
  167282. }
  167283. }
  167284. assert( aEntry[0]<key );
  167285. assert( key>=aEntry[iRes] );
  167286. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  167287. }
  167288. return 1;
  167289. }
  167290. /*
  167291. ** If the argument is a codepoint corresponding to a lowercase letter
  167292. ** in the ASCII range with a diacritic added, return the codepoint
  167293. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  167294. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  167295. ** E"). The resuls of passing a codepoint that corresponds to an
  167296. ** uppercase letter are undefined.
  167297. */
  167298. static int remove_diacritic(int c, int bComplex){
  167299. unsigned short aDia[] = {
  167300. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  167301. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  167302. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  167303. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  167304. 3456, 3696, 3712, 3728, 3744, 3766, 3832, 3896,
  167305. 3912, 3928, 3944, 3968, 4008, 4040, 4056, 4106,
  167306. 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344,
  167307. 4408, 4424, 4442, 4472, 4488, 4504, 6148, 6198,
  167308. 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468,
  167309. 61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
  167310. 61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
  167311. 61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
  167312. 62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
  167313. 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
  167314. 62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
  167315. 63182, 63242, 63274, 63310, 63368, 63390,
  167316. };
  167317. #define HIBIT ((unsigned char)0x80)
  167318. unsigned char aChar[] = {
  167319. '\0', 'a', 'c', 'e', 'i', 'n',
  167320. 'o', 'u', 'y', 'y', 'a', 'c',
  167321. 'd', 'e', 'e', 'g', 'h', 'i',
  167322. 'j', 'k', 'l', 'n', 'o', 'r',
  167323. 's', 't', 'u', 'u', 'w', 'y',
  167324. 'z', 'o', 'u', 'a', 'i', 'o',
  167325. 'u', 'u'|HIBIT, 'a'|HIBIT, 'g', 'k', 'o',
  167326. 'o'|HIBIT, 'j', 'g', 'n', 'a'|HIBIT, 'a',
  167327. 'e', 'i', 'o', 'r', 'u', 's',
  167328. 't', 'h', 'a', 'e', 'o'|HIBIT, 'o',
  167329. 'o'|HIBIT, 'y', '\0', '\0', '\0', '\0',
  167330. '\0', '\0', '\0', '\0', 'a', 'b',
  167331. 'c'|HIBIT, 'd', 'd', 'e'|HIBIT, 'e', 'e'|HIBIT,
  167332. 'f', 'g', 'h', 'h', 'i', 'i'|HIBIT,
  167333. 'k', 'l', 'l'|HIBIT, 'l', 'm', 'n',
  167334. 'o'|HIBIT, 'p', 'r', 'r'|HIBIT, 'r', 's',
  167335. 's'|HIBIT, 't', 'u', 'u'|HIBIT, 'v', 'w',
  167336. 'w', 'x', 'y', 'z', 'h', 't',
  167337. 'w', 'y', 'a', 'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
  167338. 'e', 'e'|HIBIT, 'e'|HIBIT, 'i', 'o', 'o'|HIBIT,
  167339. 'o'|HIBIT, 'o'|HIBIT, 'u', 'u'|HIBIT, 'u'|HIBIT, 'y',
  167340. };
  167341. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  167342. int iRes = 0;
  167343. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  167344. int iLo = 0;
  167345. while( iHi>=iLo ){
  167346. int iTest = (iHi + iLo) / 2;
  167347. if( key >= aDia[iTest] ){
  167348. iRes = iTest;
  167349. iLo = iTest+1;
  167350. }else{
  167351. iHi = iTest-1;
  167352. }
  167353. }
  167354. assert( key>=aDia[iRes] );
  167355. if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
  167356. return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
  167357. }
  167358. /*
  167359. ** Return true if the argument interpreted as a unicode codepoint
  167360. ** is a diacritical modifier character.
  167361. */
  167362. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  167363. unsigned int mask0 = 0x08029FDF;
  167364. unsigned int mask1 = 0x000361F8;
  167365. if( c<768 || c>817 ) return 0;
  167366. return (c < 768+32) ?
  167367. (mask0 & ((unsigned int)1 << (c-768))) :
  167368. (mask1 & ((unsigned int)1 << (c-768-32)));
  167369. }
  167370. /*
  167371. ** Interpret the argument as a unicode codepoint. If the codepoint
  167372. ** is an upper case character that has a lower case equivalent,
  167373. ** return the codepoint corresponding to the lower case version.
  167374. ** Otherwise, return a copy of the argument.
  167375. **
  167376. ** The results are undefined if the value passed to this function
  167377. ** is less than zero.
  167378. */
  167379. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){
  167380. /* Each entry in the following array defines a rule for folding a range
  167381. ** of codepoints to lower case. The rule applies to a range of nRange
  167382. ** codepoints starting at codepoint iCode.
  167383. **
  167384. ** If the least significant bit in flags is clear, then the rule applies
  167385. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  167386. ** need to be folded). Or, if it is set, then the rule only applies to
  167387. ** every second codepoint in the range, starting with codepoint C.
  167388. **
  167389. ** The 7 most significant bits in flags are an index into the aiOff[]
  167390. ** array. If a specific codepoint C does require folding, then its lower
  167391. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  167392. **
  167393. ** The contents of this array are generated by parsing the CaseFolding.txt
  167394. ** file distributed as part of the "Unicode Character Database". See
  167395. ** http://www.unicode.org for details.
  167396. */
  167397. static const struct TableEntry {
  167398. unsigned short iCode;
  167399. unsigned char flags;
  167400. unsigned char nRange;
  167401. } aEntry[] = {
  167402. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  167403. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  167404. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  167405. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  167406. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  167407. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  167408. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  167409. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  167410. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  167411. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  167412. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  167413. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  167414. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  167415. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  167416. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  167417. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  167418. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  167419. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  167420. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  167421. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  167422. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  167423. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  167424. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  167425. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  167426. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  167427. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  167428. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  167429. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  167430. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  167431. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  167432. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  167433. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  167434. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  167435. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  167436. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  167437. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  167438. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  167439. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  167440. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  167441. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  167442. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  167443. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  167444. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  167445. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  167446. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  167447. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  167448. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  167449. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  167450. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  167451. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  167452. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  167453. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  167454. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  167455. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  167456. {65313, 14, 26},
  167457. };
  167458. static const unsigned short aiOff[] = {
  167459. 1, 2, 8, 15, 16, 26, 28, 32,
  167460. 37, 38, 40, 48, 63, 64, 69, 71,
  167461. 79, 80, 116, 202, 203, 205, 206, 207,
  167462. 209, 210, 211, 213, 214, 217, 218, 219,
  167463. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  167464. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  167465. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  167466. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  167467. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  167468. 65514, 65521, 65527, 65528, 65529,
  167469. };
  167470. int ret = c;
  167471. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  167472. if( c<128 ){
  167473. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  167474. }else if( c<65536 ){
  167475. const struct TableEntry *p;
  167476. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  167477. int iLo = 0;
  167478. int iRes = -1;
  167479. assert( c>aEntry[0].iCode );
  167480. while( iHi>=iLo ){
  167481. int iTest = (iHi + iLo) / 2;
  167482. int cmp = (c - aEntry[iTest].iCode);
  167483. if( cmp>=0 ){
  167484. iRes = iTest;
  167485. iLo = iTest+1;
  167486. }else{
  167487. iHi = iTest-1;
  167488. }
  167489. }
  167490. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  167491. p = &aEntry[iRes];
  167492. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  167493. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  167494. assert( ret>0 );
  167495. }
  167496. if( eRemoveDiacritic ){
  167497. ret = remove_diacritic(ret, eRemoveDiacritic==2);
  167498. }
  167499. }
  167500. else if( c>=66560 && c<66600 ){
  167501. ret = c + 40;
  167502. }
  167503. return ret;
  167504. }
  167505. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  167506. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  167507. /************** End of fts3_unicode2.c ***************************************/
  167508. /************** Begin file json1.c *******************************************/
  167509. /*
  167510. ** 2015-08-12
  167511. **
  167512. ** The author disclaims copyright to this source code. In place of
  167513. ** a legal notice, here is a blessing:
  167514. **
  167515. ** May you do good and not evil.
  167516. ** May you find forgiveness for yourself and forgive others.
  167517. ** May you share freely, never taking more than you give.
  167518. **
  167519. ******************************************************************************
  167520. **
  167521. ** This SQLite extension implements JSON functions. The interface is
  167522. ** modeled after MySQL JSON functions:
  167523. **
  167524. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  167525. **
  167526. ** For the time being, all JSON is stored as pure text. (We might add
  167527. ** a JSONB type in the future which stores a binary encoding of JSON in
  167528. ** a BLOB, but there is no support for JSONB in the current implementation.
  167529. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  167530. ** how JSONB might improve on that.)
  167531. */
  167532. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  167533. #if !defined(SQLITEINT_H)
  167534. /* #include "sqlite3ext.h" */
  167535. #endif
  167536. SQLITE_EXTENSION_INIT1
  167537. /* #include <assert.h> */
  167538. /* #include <string.h> */
  167539. /* #include <stdlib.h> */
  167540. /* #include <stdarg.h> */
  167541. /* Mark a function parameter as unused, to suppress nuisance compiler
  167542. ** warnings. */
  167543. #ifndef UNUSED_PARAM
  167544. # define UNUSED_PARAM(X) (void)(X)
  167545. #endif
  167546. #ifndef LARGEST_INT64
  167547. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  167548. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  167549. #endif
  167550. /*
  167551. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  167552. ** to pass signed char values.
  167553. */
  167554. #ifdef sqlite3Isdigit
  167555. /* Use the SQLite core versions if this routine is part of the
  167556. ** SQLite amalgamation */
  167557. # define safe_isdigit(x) sqlite3Isdigit(x)
  167558. # define safe_isalnum(x) sqlite3Isalnum(x)
  167559. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  167560. #else
  167561. /* Use the standard library for separate compilation */
  167562. #include <ctype.h> /* amalgamator: keep */
  167563. # define safe_isdigit(x) isdigit((unsigned char)(x))
  167564. # define safe_isalnum(x) isalnum((unsigned char)(x))
  167565. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  167566. #endif
  167567. /*
  167568. ** Growing our own isspace() routine this way is twice as fast as
  167569. ** the library isspace() function, resulting in a 7% overall performance
  167570. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  167571. */
  167572. static const char jsonIsSpace[] = {
  167573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  167574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167575. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167589. };
  167590. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  167591. #ifndef SQLITE_AMALGAMATION
  167592. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  167593. ** but the definitions need to be repeated for separate compilation. */
  167594. typedef sqlite3_uint64 u64;
  167595. typedef unsigned int u32;
  167596. typedef unsigned short int u16;
  167597. typedef unsigned char u8;
  167598. #endif
  167599. /* Objects */
  167600. typedef struct JsonString JsonString;
  167601. typedef struct JsonNode JsonNode;
  167602. typedef struct JsonParse JsonParse;
  167603. /* An instance of this object represents a JSON string
  167604. ** under construction. Really, this is a generic string accumulator
  167605. ** that can be and is used to create strings other than JSON.
  167606. */
  167607. struct JsonString {
  167608. sqlite3_context *pCtx; /* Function context - put error messages here */
  167609. char *zBuf; /* Append JSON content here */
  167610. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  167611. u64 nUsed; /* Bytes of zBuf[] currently used */
  167612. u8 bStatic; /* True if zBuf is static space */
  167613. u8 bErr; /* True if an error has been encountered */
  167614. char zSpace[100]; /* Initial static space */
  167615. };
  167616. /* JSON type values
  167617. */
  167618. #define JSON_NULL 0
  167619. #define JSON_TRUE 1
  167620. #define JSON_FALSE 2
  167621. #define JSON_INT 3
  167622. #define JSON_REAL 4
  167623. #define JSON_STRING 5
  167624. #define JSON_ARRAY 6
  167625. #define JSON_OBJECT 7
  167626. /* The "subtype" set for JSON values */
  167627. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  167628. /*
  167629. ** Names of the various JSON types:
  167630. */
  167631. static const char * const jsonType[] = {
  167632. "null", "true", "false", "integer", "real", "text", "array", "object"
  167633. };
  167634. /* Bit values for the JsonNode.jnFlag field
  167635. */
  167636. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  167637. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  167638. #define JNODE_REMOVE 0x04 /* Do not output */
  167639. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
  167640. #define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
  167641. #define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
  167642. #define JNODE_LABEL 0x40 /* Is a label of an object */
  167643. /* A single node of parsed JSON
  167644. */
  167645. struct JsonNode {
  167646. u8 eType; /* One of the JSON_ type values */
  167647. u8 jnFlags; /* JNODE flags */
  167648. u32 n; /* Bytes of content, or number of sub-nodes */
  167649. union {
  167650. const char *zJContent; /* Content for INT, REAL, and STRING */
  167651. u32 iAppend; /* More terms for ARRAY and OBJECT */
  167652. u32 iKey; /* Key for ARRAY objects in json_tree() */
  167653. u32 iReplace; /* Replacement content for JNODE_REPLACE */
  167654. JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
  167655. } u;
  167656. };
  167657. /* A completely parsed JSON string
  167658. */
  167659. struct JsonParse {
  167660. u32 nNode; /* Number of slots of aNode[] used */
  167661. u32 nAlloc; /* Number of slots of aNode[] allocated */
  167662. JsonNode *aNode; /* Array of nodes containing the parse */
  167663. const char *zJson; /* Original JSON string */
  167664. u32 *aUp; /* Index of parent of each node */
  167665. u8 oom; /* Set to true if out of memory */
  167666. u8 nErr; /* Number of errors seen */
  167667. u16 iDepth; /* Nesting depth */
  167668. int nJson; /* Length of the zJson string in bytes */
  167669. u32 iHold; /* Replace cache line with the lowest iHold value */
  167670. };
  167671. /*
  167672. ** Maximum nesting depth of JSON for this implementation.
  167673. **
  167674. ** This limit is needed to avoid a stack overflow in the recursive
  167675. ** descent parser. A depth of 2000 is far deeper than any sane JSON
  167676. ** should go.
  167677. */
  167678. #define JSON_MAX_DEPTH 2000
  167679. /**************************************************************************
  167680. ** Utility routines for dealing with JsonString objects
  167681. **************************************************************************/
  167682. /* Set the JsonString object to an empty string
  167683. */
  167684. static void jsonZero(JsonString *p){
  167685. p->zBuf = p->zSpace;
  167686. p->nAlloc = sizeof(p->zSpace);
  167687. p->nUsed = 0;
  167688. p->bStatic = 1;
  167689. }
  167690. /* Initialize the JsonString object
  167691. */
  167692. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  167693. p->pCtx = pCtx;
  167694. p->bErr = 0;
  167695. jsonZero(p);
  167696. }
  167697. /* Free all allocated memory and reset the JsonString object back to its
  167698. ** initial state.
  167699. */
  167700. static void jsonReset(JsonString *p){
  167701. if( !p->bStatic ) sqlite3_free(p->zBuf);
  167702. jsonZero(p);
  167703. }
  167704. /* Report an out-of-memory (OOM) condition
  167705. */
  167706. static void jsonOom(JsonString *p){
  167707. p->bErr = 1;
  167708. sqlite3_result_error_nomem(p->pCtx);
  167709. jsonReset(p);
  167710. }
  167711. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  167712. ** Return zero on success. Return non-zero on an OOM error
  167713. */
  167714. static int jsonGrow(JsonString *p, u32 N){
  167715. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  167716. char *zNew;
  167717. if( p->bStatic ){
  167718. if( p->bErr ) return 1;
  167719. zNew = sqlite3_malloc64(nTotal);
  167720. if( zNew==0 ){
  167721. jsonOom(p);
  167722. return SQLITE_NOMEM;
  167723. }
  167724. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  167725. p->zBuf = zNew;
  167726. p->bStatic = 0;
  167727. }else{
  167728. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  167729. if( zNew==0 ){
  167730. jsonOom(p);
  167731. return SQLITE_NOMEM;
  167732. }
  167733. p->zBuf = zNew;
  167734. }
  167735. p->nAlloc = nTotal;
  167736. return SQLITE_OK;
  167737. }
  167738. /* Append N bytes from zIn onto the end of the JsonString string.
  167739. */
  167740. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  167741. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  167742. memcpy(p->zBuf+p->nUsed, zIn, N);
  167743. p->nUsed += N;
  167744. }
  167745. /* Append formatted text (not to exceed N bytes) to the JsonString.
  167746. */
  167747. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  167748. va_list ap;
  167749. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  167750. va_start(ap, zFormat);
  167751. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  167752. va_end(ap);
  167753. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  167754. }
  167755. /* Append a single character
  167756. */
  167757. static void jsonAppendChar(JsonString *p, char c){
  167758. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  167759. p->zBuf[p->nUsed++] = c;
  167760. }
  167761. /* Append a comma separator to the output buffer, if the previous
  167762. ** character is not '[' or '{'.
  167763. */
  167764. static void jsonAppendSeparator(JsonString *p){
  167765. char c;
  167766. if( p->nUsed==0 ) return;
  167767. c = p->zBuf[p->nUsed-1];
  167768. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  167769. }
  167770. /* Append the N-byte string in zIn to the end of the JsonString string
  167771. ** under construction. Enclose the string in "..." and escape
  167772. ** any double-quotes or backslash characters contained within the
  167773. ** string.
  167774. */
  167775. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  167776. u32 i;
  167777. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  167778. p->zBuf[p->nUsed++] = '"';
  167779. for(i=0; i<N; i++){
  167780. unsigned char c = ((unsigned const char*)zIn)[i];
  167781. if( c=='"' || c=='\\' ){
  167782. json_simple_escape:
  167783. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  167784. p->zBuf[p->nUsed++] = '\\';
  167785. }else if( c<=0x1f ){
  167786. static const char aSpecial[] = {
  167787. 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
  167788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  167789. };
  167790. assert( sizeof(aSpecial)==32 );
  167791. assert( aSpecial['\b']=='b' );
  167792. assert( aSpecial['\f']=='f' );
  167793. assert( aSpecial['\n']=='n' );
  167794. assert( aSpecial['\r']=='r' );
  167795. assert( aSpecial['\t']=='t' );
  167796. if( aSpecial[c] ){
  167797. c = aSpecial[c];
  167798. goto json_simple_escape;
  167799. }
  167800. if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
  167801. p->zBuf[p->nUsed++] = '\\';
  167802. p->zBuf[p->nUsed++] = 'u';
  167803. p->zBuf[p->nUsed++] = '0';
  167804. p->zBuf[p->nUsed++] = '0';
  167805. p->zBuf[p->nUsed++] = '0' + (c>>4);
  167806. c = "0123456789abcdef"[c&0xf];
  167807. }
  167808. p->zBuf[p->nUsed++] = c;
  167809. }
  167810. p->zBuf[p->nUsed++] = '"';
  167811. assert( p->nUsed<p->nAlloc );
  167812. }
  167813. /*
  167814. ** Append a function parameter value to the JSON string under
  167815. ** construction.
  167816. */
  167817. static void jsonAppendValue(
  167818. JsonString *p, /* Append to this JSON string */
  167819. sqlite3_value *pValue /* Value to append */
  167820. ){
  167821. switch( sqlite3_value_type(pValue) ){
  167822. case SQLITE_NULL: {
  167823. jsonAppendRaw(p, "null", 4);
  167824. break;
  167825. }
  167826. case SQLITE_INTEGER:
  167827. case SQLITE_FLOAT: {
  167828. const char *z = (const char*)sqlite3_value_text(pValue);
  167829. u32 n = (u32)sqlite3_value_bytes(pValue);
  167830. jsonAppendRaw(p, z, n);
  167831. break;
  167832. }
  167833. case SQLITE_TEXT: {
  167834. const char *z = (const char*)sqlite3_value_text(pValue);
  167835. u32 n = (u32)sqlite3_value_bytes(pValue);
  167836. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  167837. jsonAppendRaw(p, z, n);
  167838. }else{
  167839. jsonAppendString(p, z, n);
  167840. }
  167841. break;
  167842. }
  167843. default: {
  167844. if( p->bErr==0 ){
  167845. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  167846. p->bErr = 2;
  167847. jsonReset(p);
  167848. }
  167849. break;
  167850. }
  167851. }
  167852. }
  167853. /* Make the JSON in p the result of the SQL function.
  167854. */
  167855. static void jsonResult(JsonString *p){
  167856. if( p->bErr==0 ){
  167857. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  167858. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  167859. SQLITE_UTF8);
  167860. jsonZero(p);
  167861. }
  167862. assert( p->bStatic );
  167863. }
  167864. /**************************************************************************
  167865. ** Utility routines for dealing with JsonNode and JsonParse objects
  167866. **************************************************************************/
  167867. /*
  167868. ** Return the number of consecutive JsonNode slots need to represent
  167869. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  167870. ** OBJECT types, the number might be larger.
  167871. **
  167872. ** Appended elements are not counted. The value returned is the number
  167873. ** by which the JsonNode counter should increment in order to go to the
  167874. ** next peer value.
  167875. */
  167876. static u32 jsonNodeSize(JsonNode *pNode){
  167877. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  167878. }
  167879. /*
  167880. ** Reclaim all memory allocated by a JsonParse object. But do not
  167881. ** delete the JsonParse object itself.
  167882. */
  167883. static void jsonParseReset(JsonParse *pParse){
  167884. sqlite3_free(pParse->aNode);
  167885. pParse->aNode = 0;
  167886. pParse->nNode = 0;
  167887. pParse->nAlloc = 0;
  167888. sqlite3_free(pParse->aUp);
  167889. pParse->aUp = 0;
  167890. }
  167891. /*
  167892. ** Free a JsonParse object that was obtained from sqlite3_malloc().
  167893. */
  167894. static void jsonParseFree(JsonParse *pParse){
  167895. jsonParseReset(pParse);
  167896. sqlite3_free(pParse);
  167897. }
  167898. /*
  167899. ** Convert the JsonNode pNode into a pure JSON string and
  167900. ** append to pOut. Subsubstructure is also included. Return
  167901. ** the number of JsonNode objects that are encoded.
  167902. */
  167903. static void jsonRenderNode(
  167904. JsonNode *pNode, /* The node to render */
  167905. JsonString *pOut, /* Write JSON here */
  167906. sqlite3_value **aReplace /* Replacement values */
  167907. ){
  167908. if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
  167909. if( pNode->jnFlags & JNODE_REPLACE ){
  167910. jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
  167911. return;
  167912. }
  167913. pNode = pNode->u.pPatch;
  167914. }
  167915. switch( pNode->eType ){
  167916. default: {
  167917. assert( pNode->eType==JSON_NULL );
  167918. jsonAppendRaw(pOut, "null", 4);
  167919. break;
  167920. }
  167921. case JSON_TRUE: {
  167922. jsonAppendRaw(pOut, "true", 4);
  167923. break;
  167924. }
  167925. case JSON_FALSE: {
  167926. jsonAppendRaw(pOut, "false", 5);
  167927. break;
  167928. }
  167929. case JSON_STRING: {
  167930. if( pNode->jnFlags & JNODE_RAW ){
  167931. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  167932. break;
  167933. }
  167934. /* Fall through into the next case */
  167935. }
  167936. case JSON_REAL:
  167937. case JSON_INT: {
  167938. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  167939. break;
  167940. }
  167941. case JSON_ARRAY: {
  167942. u32 j = 1;
  167943. jsonAppendChar(pOut, '[');
  167944. for(;;){
  167945. while( j<=pNode->n ){
  167946. if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
  167947. jsonAppendSeparator(pOut);
  167948. jsonRenderNode(&pNode[j], pOut, aReplace);
  167949. }
  167950. j += jsonNodeSize(&pNode[j]);
  167951. }
  167952. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  167953. pNode = &pNode[pNode->u.iAppend];
  167954. j = 1;
  167955. }
  167956. jsonAppendChar(pOut, ']');
  167957. break;
  167958. }
  167959. case JSON_OBJECT: {
  167960. u32 j = 1;
  167961. jsonAppendChar(pOut, '{');
  167962. for(;;){
  167963. while( j<=pNode->n ){
  167964. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  167965. jsonAppendSeparator(pOut);
  167966. jsonRenderNode(&pNode[j], pOut, aReplace);
  167967. jsonAppendChar(pOut, ':');
  167968. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  167969. }
  167970. j += 1 + jsonNodeSize(&pNode[j+1]);
  167971. }
  167972. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  167973. pNode = &pNode[pNode->u.iAppend];
  167974. j = 1;
  167975. }
  167976. jsonAppendChar(pOut, '}');
  167977. break;
  167978. }
  167979. }
  167980. }
  167981. /*
  167982. ** Return a JsonNode and all its descendents as a JSON string.
  167983. */
  167984. static void jsonReturnJson(
  167985. JsonNode *pNode, /* Node to return */
  167986. sqlite3_context *pCtx, /* Return value for this function */
  167987. sqlite3_value **aReplace /* Array of replacement values */
  167988. ){
  167989. JsonString s;
  167990. jsonInit(&s, pCtx);
  167991. jsonRenderNode(pNode, &s, aReplace);
  167992. jsonResult(&s);
  167993. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  167994. }
  167995. /*
  167996. ** Make the JsonNode the return value of the function.
  167997. */
  167998. static void jsonReturn(
  167999. JsonNode *pNode, /* Node to return */
  168000. sqlite3_context *pCtx, /* Return value for this function */
  168001. sqlite3_value **aReplace /* Array of replacement values */
  168002. ){
  168003. switch( pNode->eType ){
  168004. default: {
  168005. assert( pNode->eType==JSON_NULL );
  168006. sqlite3_result_null(pCtx);
  168007. break;
  168008. }
  168009. case JSON_TRUE: {
  168010. sqlite3_result_int(pCtx, 1);
  168011. break;
  168012. }
  168013. case JSON_FALSE: {
  168014. sqlite3_result_int(pCtx, 0);
  168015. break;
  168016. }
  168017. case JSON_INT: {
  168018. sqlite3_int64 i = 0;
  168019. const char *z = pNode->u.zJContent;
  168020. if( z[0]=='-' ){ z++; }
  168021. while( z[0]>='0' && z[0]<='9' ){
  168022. unsigned v = *(z++) - '0';
  168023. if( i>=LARGEST_INT64/10 ){
  168024. if( i>LARGEST_INT64/10 ) goto int_as_real;
  168025. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  168026. if( v==9 ) goto int_as_real;
  168027. if( v==8 ){
  168028. if( pNode->u.zJContent[0]=='-' ){
  168029. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  168030. goto int_done;
  168031. }else{
  168032. goto int_as_real;
  168033. }
  168034. }
  168035. }
  168036. i = i*10 + v;
  168037. }
  168038. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  168039. sqlite3_result_int64(pCtx, i);
  168040. int_done:
  168041. break;
  168042. int_as_real: /* fall through to real */;
  168043. }
  168044. case JSON_REAL: {
  168045. double r;
  168046. #ifdef SQLITE_AMALGAMATION
  168047. const char *z = pNode->u.zJContent;
  168048. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  168049. #else
  168050. r = strtod(pNode->u.zJContent, 0);
  168051. #endif
  168052. sqlite3_result_double(pCtx, r);
  168053. break;
  168054. }
  168055. case JSON_STRING: {
  168056. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  168057. ** json_insert() and json_replace() and those routines do not
  168058. ** call jsonReturn() */
  168059. if( pNode->jnFlags & JNODE_RAW ){
  168060. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  168061. SQLITE_TRANSIENT);
  168062. }else
  168063. #endif
  168064. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  168065. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  168066. /* JSON formatted without any backslash-escapes */
  168067. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  168068. SQLITE_TRANSIENT);
  168069. }else{
  168070. /* Translate JSON formatted string into raw text */
  168071. u32 i;
  168072. u32 n = pNode->n;
  168073. const char *z = pNode->u.zJContent;
  168074. char *zOut;
  168075. u32 j;
  168076. zOut = sqlite3_malloc( n+1 );
  168077. if( zOut==0 ){
  168078. sqlite3_result_error_nomem(pCtx);
  168079. break;
  168080. }
  168081. for(i=1, j=0; i<n-1; i++){
  168082. char c = z[i];
  168083. if( c!='\\' ){
  168084. zOut[j++] = c;
  168085. }else{
  168086. c = z[++i];
  168087. if( c=='u' ){
  168088. u32 v = 0, k;
  168089. for(k=0; k<4; i++, k++){
  168090. assert( i<n-2 );
  168091. c = z[i+1];
  168092. assert( safe_isxdigit(c) );
  168093. if( c<='9' ) v = v*16 + c - '0';
  168094. else if( c<='F' ) v = v*16 + c - 'A' + 10;
  168095. else v = v*16 + c - 'a' + 10;
  168096. }
  168097. if( v==0 ) break;
  168098. if( v<=0x7f ){
  168099. zOut[j++] = (char)v;
  168100. }else if( v<=0x7ff ){
  168101. zOut[j++] = (char)(0xc0 | (v>>6));
  168102. zOut[j++] = 0x80 | (v&0x3f);
  168103. }else{
  168104. zOut[j++] = (char)(0xe0 | (v>>12));
  168105. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  168106. zOut[j++] = 0x80 | (v&0x3f);
  168107. }
  168108. }else{
  168109. if( c=='b' ){
  168110. c = '\b';
  168111. }else if( c=='f' ){
  168112. c = '\f';
  168113. }else if( c=='n' ){
  168114. c = '\n';
  168115. }else if( c=='r' ){
  168116. c = '\r';
  168117. }else if( c=='t' ){
  168118. c = '\t';
  168119. }
  168120. zOut[j++] = c;
  168121. }
  168122. }
  168123. }
  168124. zOut[j] = 0;
  168125. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  168126. }
  168127. break;
  168128. }
  168129. case JSON_ARRAY:
  168130. case JSON_OBJECT: {
  168131. jsonReturnJson(pNode, pCtx, aReplace);
  168132. break;
  168133. }
  168134. }
  168135. }
  168136. /* Forward reference */
  168137. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  168138. /*
  168139. ** A macro to hint to the compiler that a function should not be
  168140. ** inlined.
  168141. */
  168142. #if defined(__GNUC__)
  168143. # define JSON_NOINLINE __attribute__((noinline))
  168144. #elif defined(_MSC_VER) && _MSC_VER>=1310
  168145. # define JSON_NOINLINE __declspec(noinline)
  168146. #else
  168147. # define JSON_NOINLINE
  168148. #endif
  168149. static JSON_NOINLINE int jsonParseAddNodeExpand(
  168150. JsonParse *pParse, /* Append the node to this object */
  168151. u32 eType, /* Node type */
  168152. u32 n, /* Content size or sub-node count */
  168153. const char *zContent /* Content */
  168154. ){
  168155. u32 nNew;
  168156. JsonNode *pNew;
  168157. assert( pParse->nNode>=pParse->nAlloc );
  168158. if( pParse->oom ) return -1;
  168159. nNew = pParse->nAlloc*2 + 10;
  168160. pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
  168161. if( pNew==0 ){
  168162. pParse->oom = 1;
  168163. return -1;
  168164. }
  168165. pParse->nAlloc = nNew;
  168166. pParse->aNode = pNew;
  168167. assert( pParse->nNode<pParse->nAlloc );
  168168. return jsonParseAddNode(pParse, eType, n, zContent);
  168169. }
  168170. /*
  168171. ** Create a new JsonNode instance based on the arguments and append that
  168172. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  168173. ** new node, or -1 if a memory allocation fails.
  168174. */
  168175. static int jsonParseAddNode(
  168176. JsonParse *pParse, /* Append the node to this object */
  168177. u32 eType, /* Node type */
  168178. u32 n, /* Content size or sub-node count */
  168179. const char *zContent /* Content */
  168180. ){
  168181. JsonNode *p;
  168182. if( pParse->nNode>=pParse->nAlloc ){
  168183. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  168184. }
  168185. p = &pParse->aNode[pParse->nNode];
  168186. p->eType = (u8)eType;
  168187. p->jnFlags = 0;
  168188. p->n = n;
  168189. p->u.zJContent = zContent;
  168190. return pParse->nNode++;
  168191. }
  168192. /*
  168193. ** Return true if z[] begins with 4 (or more) hexadecimal digits
  168194. */
  168195. static int jsonIs4Hex(const char *z){
  168196. int i;
  168197. for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
  168198. return 1;
  168199. }
  168200. /*
  168201. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  168202. ** index of the first character past the end of the value parsed.
  168203. **
  168204. ** Return negative for a syntax error. Special cases: return -2 if the
  168205. ** first non-whitespace character is '}' and return -3 if the first
  168206. ** non-whitespace character is ']'.
  168207. */
  168208. static int jsonParseValue(JsonParse *pParse, u32 i){
  168209. char c;
  168210. u32 j;
  168211. int iThis;
  168212. int x;
  168213. JsonNode *pNode;
  168214. const char *z = pParse->zJson;
  168215. while( safe_isspace(z[i]) ){ i++; }
  168216. if( (c = z[i])=='{' ){
  168217. /* Parse object */
  168218. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  168219. if( iThis<0 ) return -1;
  168220. for(j=i+1;;j++){
  168221. while( safe_isspace(z[j]) ){ j++; }
  168222. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  168223. x = jsonParseValue(pParse, j);
  168224. if( x<0 ){
  168225. pParse->iDepth--;
  168226. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  168227. return -1;
  168228. }
  168229. if( pParse->oom ) return -1;
  168230. pNode = &pParse->aNode[pParse->nNode-1];
  168231. if( pNode->eType!=JSON_STRING ) return -1;
  168232. pNode->jnFlags |= JNODE_LABEL;
  168233. j = x;
  168234. while( safe_isspace(z[j]) ){ j++; }
  168235. if( z[j]!=':' ) return -1;
  168236. j++;
  168237. x = jsonParseValue(pParse, j);
  168238. pParse->iDepth--;
  168239. if( x<0 ) return -1;
  168240. j = x;
  168241. while( safe_isspace(z[j]) ){ j++; }
  168242. c = z[j];
  168243. if( c==',' ) continue;
  168244. if( c!='}' ) return -1;
  168245. break;
  168246. }
  168247. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  168248. return j+1;
  168249. }else if( c=='[' ){
  168250. /* Parse array */
  168251. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  168252. if( iThis<0 ) return -1;
  168253. for(j=i+1;;j++){
  168254. while( safe_isspace(z[j]) ){ j++; }
  168255. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  168256. x = jsonParseValue(pParse, j);
  168257. pParse->iDepth--;
  168258. if( x<0 ){
  168259. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  168260. return -1;
  168261. }
  168262. j = x;
  168263. while( safe_isspace(z[j]) ){ j++; }
  168264. c = z[j];
  168265. if( c==',' ) continue;
  168266. if( c!=']' ) return -1;
  168267. break;
  168268. }
  168269. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  168270. return j+1;
  168271. }else if( c=='"' ){
  168272. /* Parse string */
  168273. u8 jnFlags = 0;
  168274. j = i+1;
  168275. for(;;){
  168276. c = z[j];
  168277. if( (c & ~0x1f)==0 ){
  168278. /* Control characters are not allowed in strings */
  168279. return -1;
  168280. }
  168281. if( c=='\\' ){
  168282. c = z[++j];
  168283. if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
  168284. || c=='n' || c=='r' || c=='t'
  168285. || (c=='u' && jsonIs4Hex(z+j+1)) ){
  168286. jnFlags = JNODE_ESCAPE;
  168287. }else{
  168288. return -1;
  168289. }
  168290. }else if( c=='"' ){
  168291. break;
  168292. }
  168293. j++;
  168294. }
  168295. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
  168296. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  168297. return j+1;
  168298. }else if( c=='n'
  168299. && strncmp(z+i,"null",4)==0
  168300. && !safe_isalnum(z[i+4]) ){
  168301. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  168302. return i+4;
  168303. }else if( c=='t'
  168304. && strncmp(z+i,"true",4)==0
  168305. && !safe_isalnum(z[i+4]) ){
  168306. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  168307. return i+4;
  168308. }else if( c=='f'
  168309. && strncmp(z+i,"false",5)==0
  168310. && !safe_isalnum(z[i+5]) ){
  168311. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  168312. return i+5;
  168313. }else if( c=='-' || (c>='0' && c<='9') ){
  168314. /* Parse number */
  168315. u8 seenDP = 0;
  168316. u8 seenE = 0;
  168317. assert( '-' < '0' );
  168318. if( c<='0' ){
  168319. j = c=='-' ? i+1 : i;
  168320. if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
  168321. }
  168322. j = i+1;
  168323. for(;; j++){
  168324. c = z[j];
  168325. if( c>='0' && c<='9' ) continue;
  168326. if( c=='.' ){
  168327. if( z[j-1]=='-' ) return -1;
  168328. if( seenDP ) return -1;
  168329. seenDP = 1;
  168330. continue;
  168331. }
  168332. if( c=='e' || c=='E' ){
  168333. if( z[j-1]<'0' ) return -1;
  168334. if( seenE ) return -1;
  168335. seenDP = seenE = 1;
  168336. c = z[j+1];
  168337. if( c=='+' || c=='-' ){
  168338. j++;
  168339. c = z[j+1];
  168340. }
  168341. if( c<'0' || c>'9' ) return -1;
  168342. continue;
  168343. }
  168344. break;
  168345. }
  168346. if( z[j-1]<'0' ) return -1;
  168347. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  168348. j - i, &z[i]);
  168349. return j;
  168350. }else if( c=='}' ){
  168351. return -2; /* End of {...} */
  168352. }else if( c==']' ){
  168353. return -3; /* End of [...] */
  168354. }else if( c==0 ){
  168355. return 0; /* End of file */
  168356. }else{
  168357. return -1; /* Syntax error */
  168358. }
  168359. }
  168360. /*
  168361. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  168362. ** are any errors. If an error occurs, free all memory associated with
  168363. ** pParse.
  168364. **
  168365. ** pParse is uninitialized when this routine is called.
  168366. */
  168367. static int jsonParse(
  168368. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  168369. sqlite3_context *pCtx, /* Report errors here */
  168370. const char *zJson /* Input JSON text to be parsed */
  168371. ){
  168372. int i;
  168373. memset(pParse, 0, sizeof(*pParse));
  168374. if( zJson==0 ) return 1;
  168375. pParse->zJson = zJson;
  168376. i = jsonParseValue(pParse, 0);
  168377. if( pParse->oom ) i = -1;
  168378. if( i>0 ){
  168379. assert( pParse->iDepth==0 );
  168380. while( safe_isspace(zJson[i]) ) i++;
  168381. if( zJson[i] ) i = -1;
  168382. }
  168383. if( i<=0 ){
  168384. if( pCtx!=0 ){
  168385. if( pParse->oom ){
  168386. sqlite3_result_error_nomem(pCtx);
  168387. }else{
  168388. sqlite3_result_error(pCtx, "malformed JSON", -1);
  168389. }
  168390. }
  168391. jsonParseReset(pParse);
  168392. return 1;
  168393. }
  168394. return 0;
  168395. }
  168396. /* Mark node i of pParse as being a child of iParent. Call recursively
  168397. ** to fill in all the descendants of node i.
  168398. */
  168399. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  168400. JsonNode *pNode = &pParse->aNode[i];
  168401. u32 j;
  168402. pParse->aUp[i] = iParent;
  168403. switch( pNode->eType ){
  168404. case JSON_ARRAY: {
  168405. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  168406. jsonParseFillInParentage(pParse, i+j, i);
  168407. }
  168408. break;
  168409. }
  168410. case JSON_OBJECT: {
  168411. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  168412. pParse->aUp[i+j] = i;
  168413. jsonParseFillInParentage(pParse, i+j+1, i);
  168414. }
  168415. break;
  168416. }
  168417. default: {
  168418. break;
  168419. }
  168420. }
  168421. }
  168422. /*
  168423. ** Compute the parentage of all nodes in a completed parse.
  168424. */
  168425. static int jsonParseFindParents(JsonParse *pParse){
  168426. u32 *aUp;
  168427. assert( pParse->aUp==0 );
  168428. aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );
  168429. if( aUp==0 ){
  168430. pParse->oom = 1;
  168431. return SQLITE_NOMEM;
  168432. }
  168433. jsonParseFillInParentage(pParse, 0, 0);
  168434. return SQLITE_OK;
  168435. }
  168436. /*
  168437. ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
  168438. */
  168439. #define JSON_CACHE_ID (-429938) /* First cache entry */
  168440. #define JSON_CACHE_SZ 4 /* Max number of cache entries */
  168441. /*
  168442. ** Obtain a complete parse of the JSON found in the first argument
  168443. ** of the argv array. Use the sqlite3_get_auxdata() cache for this
  168444. ** parse if it is available. If the cache is not available or if it
  168445. ** is no longer valid, parse the JSON again and return the new parse,
  168446. ** and also register the new parse so that it will be available for
  168447. ** future sqlite3_get_auxdata() calls.
  168448. */
  168449. static JsonParse *jsonParseCached(
  168450. sqlite3_context *pCtx,
  168451. sqlite3_value **argv,
  168452. sqlite3_context *pErrCtx
  168453. ){
  168454. const char *zJson = (const char*)sqlite3_value_text(argv[0]);
  168455. int nJson = sqlite3_value_bytes(argv[0]);
  168456. JsonParse *p;
  168457. JsonParse *pMatch = 0;
  168458. int iKey;
  168459. int iMinKey = 0;
  168460. u32 iMinHold = 0xffffffff;
  168461. u32 iMaxHold = 0;
  168462. if( zJson==0 ) return 0;
  168463. for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
  168464. p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
  168465. if( p==0 ){
  168466. iMinKey = iKey;
  168467. break;
  168468. }
  168469. if( pMatch==0
  168470. && p->nJson==nJson
  168471. && memcmp(p->zJson,zJson,nJson)==0
  168472. ){
  168473. p->nErr = 0;
  168474. pMatch = p;
  168475. }else if( p->iHold<iMinHold ){
  168476. iMinHold = p->iHold;
  168477. iMinKey = iKey;
  168478. }
  168479. if( p->iHold>iMaxHold ){
  168480. iMaxHold = p->iHold;
  168481. }
  168482. }
  168483. if( pMatch ){
  168484. pMatch->nErr = 0;
  168485. pMatch->iHold = iMaxHold+1;
  168486. return pMatch;
  168487. }
  168488. p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );
  168489. if( p==0 ){
  168490. sqlite3_result_error_nomem(pCtx);
  168491. return 0;
  168492. }
  168493. memset(p, 0, sizeof(*p));
  168494. p->zJson = (char*)&p[1];
  168495. memcpy((char*)p->zJson, zJson, nJson+1);
  168496. if( jsonParse(p, pErrCtx, p->zJson) ){
  168497. sqlite3_free(p);
  168498. return 0;
  168499. }
  168500. p->nJson = nJson;
  168501. p->iHold = iMaxHold+1;
  168502. sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
  168503. (void(*)(void*))jsonParseFree);
  168504. return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
  168505. }
  168506. /*
  168507. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  168508. ** a match.
  168509. */
  168510. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  168511. if( pNode->jnFlags & JNODE_RAW ){
  168512. if( pNode->n!=nKey ) return 0;
  168513. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  168514. }else{
  168515. if( pNode->n!=nKey+2 ) return 0;
  168516. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  168517. }
  168518. }
  168519. /* forward declaration */
  168520. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  168521. /*
  168522. ** Search along zPath to find the node specified. Return a pointer
  168523. ** to that node, or NULL if zPath is malformed or if there is no such
  168524. ** node.
  168525. **
  168526. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  168527. ** possible to do so and if no existing node corresponds to zPath. If
  168528. ** new nodes are appended *pApnd is set to 1.
  168529. */
  168530. static JsonNode *jsonLookupStep(
  168531. JsonParse *pParse, /* The JSON to search */
  168532. u32 iRoot, /* Begin the search at this node */
  168533. const char *zPath, /* The path to search */
  168534. int *pApnd, /* Append nodes to complete path if not NULL */
  168535. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  168536. ){
  168537. u32 i, j, nKey;
  168538. const char *zKey;
  168539. JsonNode *pRoot = &pParse->aNode[iRoot];
  168540. if( zPath[0]==0 ) return pRoot;
  168541. if( zPath[0]=='.' ){
  168542. if( pRoot->eType!=JSON_OBJECT ) return 0;
  168543. zPath++;
  168544. if( zPath[0]=='"' ){
  168545. zKey = zPath + 1;
  168546. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  168547. nKey = i-1;
  168548. if( zPath[i] ){
  168549. i++;
  168550. }else{
  168551. *pzErr = zPath;
  168552. return 0;
  168553. }
  168554. }else{
  168555. zKey = zPath;
  168556. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  168557. nKey = i;
  168558. }
  168559. if( nKey==0 ){
  168560. *pzErr = zPath;
  168561. return 0;
  168562. }
  168563. j = 1;
  168564. for(;;){
  168565. while( j<=pRoot->n ){
  168566. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  168567. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  168568. }
  168569. j++;
  168570. j += jsonNodeSize(&pRoot[j]);
  168571. }
  168572. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  168573. iRoot += pRoot->u.iAppend;
  168574. pRoot = &pParse->aNode[iRoot];
  168575. j = 1;
  168576. }
  168577. if( pApnd ){
  168578. u32 iStart, iLabel;
  168579. JsonNode *pNode;
  168580. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  168581. iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
  168582. zPath += i;
  168583. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  168584. if( pParse->oom ) return 0;
  168585. if( pNode ){
  168586. pRoot = &pParse->aNode[iRoot];
  168587. pRoot->u.iAppend = iStart - iRoot;
  168588. pRoot->jnFlags |= JNODE_APPEND;
  168589. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  168590. }
  168591. return pNode;
  168592. }
  168593. }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  168594. if( pRoot->eType!=JSON_ARRAY ) return 0;
  168595. i = 0;
  168596. j = 1;
  168597. while( safe_isdigit(zPath[j]) ){
  168598. i = i*10 + zPath[j] - '0';
  168599. j++;
  168600. }
  168601. if( zPath[j]!=']' ){
  168602. *pzErr = zPath;
  168603. return 0;
  168604. }
  168605. zPath += j + 1;
  168606. j = 1;
  168607. for(;;){
  168608. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  168609. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  168610. j += jsonNodeSize(&pRoot[j]);
  168611. }
  168612. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  168613. iRoot += pRoot->u.iAppend;
  168614. pRoot = &pParse->aNode[iRoot];
  168615. j = 1;
  168616. }
  168617. if( j<=pRoot->n ){
  168618. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  168619. }
  168620. if( i==0 && pApnd ){
  168621. u32 iStart;
  168622. JsonNode *pNode;
  168623. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  168624. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  168625. if( pParse->oom ) return 0;
  168626. if( pNode ){
  168627. pRoot = &pParse->aNode[iRoot];
  168628. pRoot->u.iAppend = iStart - iRoot;
  168629. pRoot->jnFlags |= JNODE_APPEND;
  168630. }
  168631. return pNode;
  168632. }
  168633. }else{
  168634. *pzErr = zPath;
  168635. }
  168636. return 0;
  168637. }
  168638. /*
  168639. ** Append content to pParse that will complete zPath. Return a pointer
  168640. ** to the inserted node, or return NULL if the append fails.
  168641. */
  168642. static JsonNode *jsonLookupAppend(
  168643. JsonParse *pParse, /* Append content to the JSON parse */
  168644. const char *zPath, /* Description of content to append */
  168645. int *pApnd, /* Set this flag to 1 */
  168646. const char **pzErr /* Make this point to any syntax error */
  168647. ){
  168648. *pApnd = 1;
  168649. if( zPath[0]==0 ){
  168650. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  168651. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  168652. }
  168653. if( zPath[0]=='.' ){
  168654. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  168655. }else if( strncmp(zPath,"[0]",3)==0 ){
  168656. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  168657. }else{
  168658. return 0;
  168659. }
  168660. if( pParse->oom ) return 0;
  168661. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  168662. }
  168663. /*
  168664. ** Return the text of a syntax error message on a JSON path. Space is
  168665. ** obtained from sqlite3_malloc().
  168666. */
  168667. static char *jsonPathSyntaxError(const char *zErr){
  168668. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  168669. }
  168670. /*
  168671. ** Do a node lookup using zPath. Return a pointer to the node on success.
  168672. ** Return NULL if not found or if there is an error.
  168673. **
  168674. ** On an error, write an error message into pCtx and increment the
  168675. ** pParse->nErr counter.
  168676. **
  168677. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  168678. ** nodes are appended.
  168679. */
  168680. static JsonNode *jsonLookup(
  168681. JsonParse *pParse, /* The JSON to search */
  168682. const char *zPath, /* The path to search */
  168683. int *pApnd, /* Append nodes to complete path if not NULL */
  168684. sqlite3_context *pCtx /* Report errors here, if not NULL */
  168685. ){
  168686. const char *zErr = 0;
  168687. JsonNode *pNode = 0;
  168688. char *zMsg;
  168689. if( zPath==0 ) return 0;
  168690. if( zPath[0]!='$' ){
  168691. zErr = zPath;
  168692. goto lookup_err;
  168693. }
  168694. zPath++;
  168695. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  168696. if( zErr==0 ) return pNode;
  168697. lookup_err:
  168698. pParse->nErr++;
  168699. assert( zErr!=0 && pCtx!=0 );
  168700. zMsg = jsonPathSyntaxError(zErr);
  168701. if( zMsg ){
  168702. sqlite3_result_error(pCtx, zMsg, -1);
  168703. sqlite3_free(zMsg);
  168704. }else{
  168705. sqlite3_result_error_nomem(pCtx);
  168706. }
  168707. return 0;
  168708. }
  168709. /*
  168710. ** Report the wrong number of arguments for json_insert(), json_replace()
  168711. ** or json_set().
  168712. */
  168713. static void jsonWrongNumArgs(
  168714. sqlite3_context *pCtx,
  168715. const char *zFuncName
  168716. ){
  168717. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  168718. zFuncName);
  168719. sqlite3_result_error(pCtx, zMsg, -1);
  168720. sqlite3_free(zMsg);
  168721. }
  168722. /*
  168723. ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
  168724. */
  168725. static void jsonRemoveAllNulls(JsonNode *pNode){
  168726. int i, n;
  168727. assert( pNode->eType==JSON_OBJECT );
  168728. n = pNode->n;
  168729. for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
  168730. switch( pNode[i].eType ){
  168731. case JSON_NULL:
  168732. pNode[i].jnFlags |= JNODE_REMOVE;
  168733. break;
  168734. case JSON_OBJECT:
  168735. jsonRemoveAllNulls(&pNode[i]);
  168736. break;
  168737. }
  168738. }
  168739. }
  168740. /****************************************************************************
  168741. ** SQL functions used for testing and debugging
  168742. ****************************************************************************/
  168743. #ifdef SQLITE_DEBUG
  168744. /*
  168745. ** The json_parse(JSON) function returns a string which describes
  168746. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  168747. ** well-formed.
  168748. */
  168749. static void jsonParseFunc(
  168750. sqlite3_context *ctx,
  168751. int argc,
  168752. sqlite3_value **argv
  168753. ){
  168754. JsonString s; /* Output string - not real JSON */
  168755. JsonParse x; /* The parse */
  168756. u32 i;
  168757. assert( argc==1 );
  168758. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  168759. jsonParseFindParents(&x);
  168760. jsonInit(&s, ctx);
  168761. for(i=0; i<x.nNode; i++){
  168762. const char *zType;
  168763. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  168764. assert( x.aNode[i].eType==JSON_STRING );
  168765. zType = "label";
  168766. }else{
  168767. zType = jsonType[x.aNode[i].eType];
  168768. }
  168769. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  168770. i, zType, x.aNode[i].n, x.aUp[i]);
  168771. if( x.aNode[i].u.zJContent!=0 ){
  168772. jsonAppendRaw(&s, " ", 1);
  168773. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  168774. }
  168775. jsonAppendRaw(&s, "\n", 1);
  168776. }
  168777. jsonParseReset(&x);
  168778. jsonResult(&s);
  168779. }
  168780. /*
  168781. ** The json_test1(JSON) function return true (1) if the input is JSON
  168782. ** text generated by another json function. It returns (0) if the input
  168783. ** is not known to be JSON.
  168784. */
  168785. static void jsonTest1Func(
  168786. sqlite3_context *ctx,
  168787. int argc,
  168788. sqlite3_value **argv
  168789. ){
  168790. UNUSED_PARAM(argc);
  168791. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  168792. }
  168793. #endif /* SQLITE_DEBUG */
  168794. /****************************************************************************
  168795. ** Scalar SQL function implementations
  168796. ****************************************************************************/
  168797. /*
  168798. ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
  168799. ** corresponding to the SQL value input. Mostly this means putting
  168800. ** double-quotes around strings and returning the unquoted string "null"
  168801. ** when given a NULL input.
  168802. */
  168803. static void jsonQuoteFunc(
  168804. sqlite3_context *ctx,
  168805. int argc,
  168806. sqlite3_value **argv
  168807. ){
  168808. JsonString jx;
  168809. UNUSED_PARAM(argc);
  168810. jsonInit(&jx, ctx);
  168811. jsonAppendValue(&jx, argv[0]);
  168812. jsonResult(&jx);
  168813. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  168814. }
  168815. /*
  168816. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  168817. ** array that contains all values given in arguments. Or if any argument
  168818. ** is a BLOB, throw an error.
  168819. */
  168820. static void jsonArrayFunc(
  168821. sqlite3_context *ctx,
  168822. int argc,
  168823. sqlite3_value **argv
  168824. ){
  168825. int i;
  168826. JsonString jx;
  168827. jsonInit(&jx, ctx);
  168828. jsonAppendChar(&jx, '[');
  168829. for(i=0; i<argc; i++){
  168830. jsonAppendSeparator(&jx);
  168831. jsonAppendValue(&jx, argv[i]);
  168832. }
  168833. jsonAppendChar(&jx, ']');
  168834. jsonResult(&jx);
  168835. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  168836. }
  168837. /*
  168838. ** json_array_length(JSON)
  168839. ** json_array_length(JSON, PATH)
  168840. **
  168841. ** Return the number of elements in the top-level JSON array.
  168842. ** Return 0 if the input is not a well-formed JSON array.
  168843. */
  168844. static void jsonArrayLengthFunc(
  168845. sqlite3_context *ctx,
  168846. int argc,
  168847. sqlite3_value **argv
  168848. ){
  168849. JsonParse *p; /* The parse */
  168850. sqlite3_int64 n = 0;
  168851. u32 i;
  168852. JsonNode *pNode;
  168853. p = jsonParseCached(ctx, argv, ctx);
  168854. if( p==0 ) return;
  168855. assert( p->nNode );
  168856. if( argc==2 ){
  168857. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  168858. pNode = jsonLookup(p, zPath, 0, ctx);
  168859. }else{
  168860. pNode = p->aNode;
  168861. }
  168862. if( pNode==0 ){
  168863. return;
  168864. }
  168865. if( pNode->eType==JSON_ARRAY ){
  168866. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  168867. for(i=1; i<=pNode->n; n++){
  168868. i += jsonNodeSize(&pNode[i]);
  168869. }
  168870. }
  168871. sqlite3_result_int64(ctx, n);
  168872. }
  168873. /*
  168874. ** json_extract(JSON, PATH, ...)
  168875. **
  168876. ** Return the element described by PATH. Return NULL if there is no
  168877. ** PATH element. If there are multiple PATHs, then return a JSON array
  168878. ** with the result from each path. Throw an error if the JSON or any PATH
  168879. ** is malformed.
  168880. */
  168881. static void jsonExtractFunc(
  168882. sqlite3_context *ctx,
  168883. int argc,
  168884. sqlite3_value **argv
  168885. ){
  168886. JsonParse *p; /* The parse */
  168887. JsonNode *pNode;
  168888. const char *zPath;
  168889. JsonString jx;
  168890. int i;
  168891. if( argc<2 ) return;
  168892. p = jsonParseCached(ctx, argv, ctx);
  168893. if( p==0 ) return;
  168894. jsonInit(&jx, ctx);
  168895. jsonAppendChar(&jx, '[');
  168896. for(i=1; i<argc; i++){
  168897. zPath = (const char*)sqlite3_value_text(argv[i]);
  168898. pNode = jsonLookup(p, zPath, 0, ctx);
  168899. if( p->nErr ) break;
  168900. if( argc>2 ){
  168901. jsonAppendSeparator(&jx);
  168902. if( pNode ){
  168903. jsonRenderNode(pNode, &jx, 0);
  168904. }else{
  168905. jsonAppendRaw(&jx, "null", 4);
  168906. }
  168907. }else if( pNode ){
  168908. jsonReturn(pNode, ctx, 0);
  168909. }
  168910. }
  168911. if( argc>2 && i==argc ){
  168912. jsonAppendChar(&jx, ']');
  168913. jsonResult(&jx);
  168914. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  168915. }
  168916. jsonReset(&jx);
  168917. }
  168918. /* This is the RFC 7396 MergePatch algorithm.
  168919. */
  168920. static JsonNode *jsonMergePatch(
  168921. JsonParse *pParse, /* The JSON parser that contains the TARGET */
  168922. u32 iTarget, /* Node of the TARGET in pParse */
  168923. JsonNode *pPatch /* The PATCH */
  168924. ){
  168925. u32 i, j;
  168926. u32 iRoot;
  168927. JsonNode *pTarget;
  168928. if( pPatch->eType!=JSON_OBJECT ){
  168929. return pPatch;
  168930. }
  168931. assert( iTarget>=0 && iTarget<pParse->nNode );
  168932. pTarget = &pParse->aNode[iTarget];
  168933. assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
  168934. if( pTarget->eType!=JSON_OBJECT ){
  168935. jsonRemoveAllNulls(pPatch);
  168936. return pPatch;
  168937. }
  168938. iRoot = iTarget;
  168939. for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
  168940. u32 nKey;
  168941. const char *zKey;
  168942. assert( pPatch[i].eType==JSON_STRING );
  168943. assert( pPatch[i].jnFlags & JNODE_LABEL );
  168944. nKey = pPatch[i].n;
  168945. zKey = pPatch[i].u.zJContent;
  168946. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  168947. for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
  168948. assert( pTarget[j].eType==JSON_STRING );
  168949. assert( pTarget[j].jnFlags & JNODE_LABEL );
  168950. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  168951. if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
  168952. if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
  168953. if( pPatch[i+1].eType==JSON_NULL ){
  168954. pTarget[j+1].jnFlags |= JNODE_REMOVE;
  168955. }else{
  168956. JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
  168957. if( pNew==0 ) return 0;
  168958. pTarget = &pParse->aNode[iTarget];
  168959. if( pNew!=&pTarget[j+1] ){
  168960. pTarget[j+1].u.pPatch = pNew;
  168961. pTarget[j+1].jnFlags |= JNODE_PATCH;
  168962. }
  168963. }
  168964. break;
  168965. }
  168966. }
  168967. if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
  168968. int iStart, iPatch;
  168969. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  168970. jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  168971. iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  168972. if( pParse->oom ) return 0;
  168973. jsonRemoveAllNulls(pPatch);
  168974. pTarget = &pParse->aNode[iTarget];
  168975. pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
  168976. pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
  168977. iRoot = iStart;
  168978. pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
  168979. pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
  168980. }
  168981. }
  168982. return pTarget;
  168983. }
  168984. /*
  168985. ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
  168986. ** object that is the result of running the RFC 7396 MergePatch() algorithm
  168987. ** on the two arguments.
  168988. */
  168989. static void jsonPatchFunc(
  168990. sqlite3_context *ctx,
  168991. int argc,
  168992. sqlite3_value **argv
  168993. ){
  168994. JsonParse x; /* The JSON that is being patched */
  168995. JsonParse y; /* The patch */
  168996. JsonNode *pResult; /* The result of the merge */
  168997. UNUSED_PARAM(argc);
  168998. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  168999. if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
  169000. jsonParseReset(&x);
  169001. return;
  169002. }
  169003. pResult = jsonMergePatch(&x, 0, y.aNode);
  169004. assert( pResult!=0 || x.oom );
  169005. if( pResult ){
  169006. jsonReturnJson(pResult, ctx, 0);
  169007. }else{
  169008. sqlite3_result_error_nomem(ctx);
  169009. }
  169010. jsonParseReset(&x);
  169011. jsonParseReset(&y);
  169012. }
  169013. /*
  169014. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  169015. ** object that contains all name/value given in arguments. Or if any name
  169016. ** is not a string or if any value is a BLOB, throw an error.
  169017. */
  169018. static void jsonObjectFunc(
  169019. sqlite3_context *ctx,
  169020. int argc,
  169021. sqlite3_value **argv
  169022. ){
  169023. int i;
  169024. JsonString jx;
  169025. const char *z;
  169026. u32 n;
  169027. if( argc&1 ){
  169028. sqlite3_result_error(ctx, "json_object() requires an even number "
  169029. "of arguments", -1);
  169030. return;
  169031. }
  169032. jsonInit(&jx, ctx);
  169033. jsonAppendChar(&jx, '{');
  169034. for(i=0; i<argc; i+=2){
  169035. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  169036. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  169037. jsonReset(&jx);
  169038. return;
  169039. }
  169040. jsonAppendSeparator(&jx);
  169041. z = (const char*)sqlite3_value_text(argv[i]);
  169042. n = (u32)sqlite3_value_bytes(argv[i]);
  169043. jsonAppendString(&jx, z, n);
  169044. jsonAppendChar(&jx, ':');
  169045. jsonAppendValue(&jx, argv[i+1]);
  169046. }
  169047. jsonAppendChar(&jx, '}');
  169048. jsonResult(&jx);
  169049. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169050. }
  169051. /*
  169052. ** json_remove(JSON, PATH, ...)
  169053. **
  169054. ** Remove the named elements from JSON and return the result. malformed
  169055. ** JSON or PATH arguments result in an error.
  169056. */
  169057. static void jsonRemoveFunc(
  169058. sqlite3_context *ctx,
  169059. int argc,
  169060. sqlite3_value **argv
  169061. ){
  169062. JsonParse x; /* The parse */
  169063. JsonNode *pNode;
  169064. const char *zPath;
  169065. u32 i;
  169066. if( argc<1 ) return;
  169067. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169068. assert( x.nNode );
  169069. for(i=1; i<(u32)argc; i++){
  169070. zPath = (const char*)sqlite3_value_text(argv[i]);
  169071. if( zPath==0 ) goto remove_done;
  169072. pNode = jsonLookup(&x, zPath, 0, ctx);
  169073. if( x.nErr ) goto remove_done;
  169074. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  169075. }
  169076. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  169077. jsonReturnJson(x.aNode, ctx, 0);
  169078. }
  169079. remove_done:
  169080. jsonParseReset(&x);
  169081. }
  169082. /*
  169083. ** json_replace(JSON, PATH, VALUE, ...)
  169084. **
  169085. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  169086. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  169087. */
  169088. static void jsonReplaceFunc(
  169089. sqlite3_context *ctx,
  169090. int argc,
  169091. sqlite3_value **argv
  169092. ){
  169093. JsonParse x; /* The parse */
  169094. JsonNode *pNode;
  169095. const char *zPath;
  169096. u32 i;
  169097. if( argc<1 ) return;
  169098. if( (argc&1)==0 ) {
  169099. jsonWrongNumArgs(ctx, "replace");
  169100. return;
  169101. }
  169102. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169103. assert( x.nNode );
  169104. for(i=1; i<(u32)argc; i+=2){
  169105. zPath = (const char*)sqlite3_value_text(argv[i]);
  169106. pNode = jsonLookup(&x, zPath, 0, ctx);
  169107. if( x.nErr ) goto replace_err;
  169108. if( pNode ){
  169109. pNode->jnFlags |= (u8)JNODE_REPLACE;
  169110. pNode->u.iReplace = i + 1;
  169111. }
  169112. }
  169113. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  169114. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  169115. }else{
  169116. jsonReturnJson(x.aNode, ctx, argv);
  169117. }
  169118. replace_err:
  169119. jsonParseReset(&x);
  169120. }
  169121. /*
  169122. ** json_set(JSON, PATH, VALUE, ...)
  169123. **
  169124. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  169125. ** exist. Overwrite existing values that do exist.
  169126. ** If JSON or PATH is malformed, throw an error.
  169127. **
  169128. ** json_insert(JSON, PATH, VALUE, ...)
  169129. **
  169130. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  169131. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  169132. */
  169133. static void jsonSetFunc(
  169134. sqlite3_context *ctx,
  169135. int argc,
  169136. sqlite3_value **argv
  169137. ){
  169138. JsonParse x; /* The parse */
  169139. JsonNode *pNode;
  169140. const char *zPath;
  169141. u32 i;
  169142. int bApnd;
  169143. int bIsSet = *(int*)sqlite3_user_data(ctx);
  169144. if( argc<1 ) return;
  169145. if( (argc&1)==0 ) {
  169146. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  169147. return;
  169148. }
  169149. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169150. assert( x.nNode );
  169151. for(i=1; i<(u32)argc; i+=2){
  169152. zPath = (const char*)sqlite3_value_text(argv[i]);
  169153. bApnd = 0;
  169154. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  169155. if( x.oom ){
  169156. sqlite3_result_error_nomem(ctx);
  169157. goto jsonSetDone;
  169158. }else if( x.nErr ){
  169159. goto jsonSetDone;
  169160. }else if( pNode && (bApnd || bIsSet) ){
  169161. pNode->jnFlags |= (u8)JNODE_REPLACE;
  169162. pNode->u.iReplace = i + 1;
  169163. }
  169164. }
  169165. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  169166. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  169167. }else{
  169168. jsonReturnJson(x.aNode, ctx, argv);
  169169. }
  169170. jsonSetDone:
  169171. jsonParseReset(&x);
  169172. }
  169173. /*
  169174. ** json_type(JSON)
  169175. ** json_type(JSON, PATH)
  169176. **
  169177. ** Return the top-level "type" of a JSON string. Throw an error if
  169178. ** either the JSON or PATH inputs are not well-formed.
  169179. */
  169180. static void jsonTypeFunc(
  169181. sqlite3_context *ctx,
  169182. int argc,
  169183. sqlite3_value **argv
  169184. ){
  169185. JsonParse *p; /* The parse */
  169186. const char *zPath;
  169187. JsonNode *pNode;
  169188. p = jsonParseCached(ctx, argv, ctx);
  169189. if( p==0 ) return;
  169190. if( argc==2 ){
  169191. zPath = (const char*)sqlite3_value_text(argv[1]);
  169192. pNode = jsonLookup(p, zPath, 0, ctx);
  169193. }else{
  169194. pNode = p->aNode;
  169195. }
  169196. if( pNode ){
  169197. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  169198. }
  169199. }
  169200. /*
  169201. ** json_valid(JSON)
  169202. **
  169203. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  169204. ** Return 0 otherwise.
  169205. */
  169206. static void jsonValidFunc(
  169207. sqlite3_context *ctx,
  169208. int argc,
  169209. sqlite3_value **argv
  169210. ){
  169211. JsonParse *p; /* The parse */
  169212. UNUSED_PARAM(argc);
  169213. p = jsonParseCached(ctx, argv, 0);
  169214. sqlite3_result_int(ctx, p!=0);
  169215. }
  169216. /****************************************************************************
  169217. ** Aggregate SQL function implementations
  169218. ****************************************************************************/
  169219. /*
  169220. ** json_group_array(VALUE)
  169221. **
  169222. ** Return a JSON array composed of all values in the aggregate.
  169223. */
  169224. static void jsonArrayStep(
  169225. sqlite3_context *ctx,
  169226. int argc,
  169227. sqlite3_value **argv
  169228. ){
  169229. JsonString *pStr;
  169230. UNUSED_PARAM(argc);
  169231. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  169232. if( pStr ){
  169233. if( pStr->zBuf==0 ){
  169234. jsonInit(pStr, ctx);
  169235. jsonAppendChar(pStr, '[');
  169236. }else{
  169237. jsonAppendChar(pStr, ',');
  169238. pStr->pCtx = ctx;
  169239. }
  169240. jsonAppendValue(pStr, argv[0]);
  169241. }
  169242. }
  169243. static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
  169244. JsonString *pStr;
  169245. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  169246. if( pStr ){
  169247. pStr->pCtx = ctx;
  169248. jsonAppendChar(pStr, ']');
  169249. if( pStr->bErr ){
  169250. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  169251. assert( pStr->bStatic );
  169252. }else if( isFinal ){
  169253. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
  169254. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  169255. pStr->bStatic = 1;
  169256. }else{
  169257. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
  169258. pStr->nUsed--;
  169259. }
  169260. }else{
  169261. sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  169262. }
  169263. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169264. }
  169265. static void jsonArrayValue(sqlite3_context *ctx){
  169266. jsonArrayCompute(ctx, 0);
  169267. }
  169268. static void jsonArrayFinal(sqlite3_context *ctx){
  169269. jsonArrayCompute(ctx, 1);
  169270. }
  169271. #ifndef SQLITE_OMIT_WINDOWFUNC
  169272. /*
  169273. ** This method works for both json_group_array() and json_group_object().
  169274. ** It works by removing the first element of the group by searching forward
  169275. ** to the first comma (",") that is not within a string and deleting all
  169276. ** text through that comma.
  169277. */
  169278. static void jsonGroupInverse(
  169279. sqlite3_context *ctx,
  169280. int argc,
  169281. sqlite3_value **argv
  169282. ){
  169283. int i;
  169284. int inStr = 0;
  169285. char *z;
  169286. JsonString *pStr;
  169287. UNUSED_PARAM(argc);
  169288. UNUSED_PARAM(argv);
  169289. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  169290. #ifdef NEVER
  169291. /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
  169292. ** always have been called to initalize it */
  169293. if( NEVER(!pStr) ) return;
  169294. #endif
  169295. z = pStr->zBuf;
  169296. for(i=1; z[i]!=',' || inStr; i++){
  169297. assert( i<pStr->nUsed );
  169298. if( z[i]=='"' ){
  169299. inStr = !inStr;
  169300. }else if( z[i]=='\\' ){
  169301. i++;
  169302. }
  169303. }
  169304. pStr->nUsed -= i;
  169305. memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
  169306. }
  169307. #else
  169308. # define jsonGroupInverse 0
  169309. #endif
  169310. /*
  169311. ** json_group_obj(NAME,VALUE)
  169312. **
  169313. ** Return a JSON object composed of all names and values in the aggregate.
  169314. */
  169315. static void jsonObjectStep(
  169316. sqlite3_context *ctx,
  169317. int argc,
  169318. sqlite3_value **argv
  169319. ){
  169320. JsonString *pStr;
  169321. const char *z;
  169322. u32 n;
  169323. UNUSED_PARAM(argc);
  169324. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  169325. if( pStr ){
  169326. if( pStr->zBuf==0 ){
  169327. jsonInit(pStr, ctx);
  169328. jsonAppendChar(pStr, '{');
  169329. }else{
  169330. jsonAppendChar(pStr, ',');
  169331. pStr->pCtx = ctx;
  169332. }
  169333. z = (const char*)sqlite3_value_text(argv[0]);
  169334. n = (u32)sqlite3_value_bytes(argv[0]);
  169335. jsonAppendString(pStr, z, n);
  169336. jsonAppendChar(pStr, ':');
  169337. jsonAppendValue(pStr, argv[1]);
  169338. }
  169339. }
  169340. static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
  169341. JsonString *pStr;
  169342. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  169343. if( pStr ){
  169344. jsonAppendChar(pStr, '}');
  169345. if( pStr->bErr ){
  169346. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  169347. assert( pStr->bStatic );
  169348. }else if( isFinal ){
  169349. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
  169350. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  169351. pStr->bStatic = 1;
  169352. }else{
  169353. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
  169354. pStr->nUsed--;
  169355. }
  169356. }else{
  169357. sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  169358. }
  169359. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169360. }
  169361. static void jsonObjectValue(sqlite3_context *ctx){
  169362. jsonObjectCompute(ctx, 0);
  169363. }
  169364. static void jsonObjectFinal(sqlite3_context *ctx){
  169365. jsonObjectCompute(ctx, 1);
  169366. }
  169367. #ifndef SQLITE_OMIT_VIRTUALTABLE
  169368. /****************************************************************************
  169369. ** The json_each virtual table
  169370. ****************************************************************************/
  169371. typedef struct JsonEachCursor JsonEachCursor;
  169372. struct JsonEachCursor {
  169373. sqlite3_vtab_cursor base; /* Base class - must be first */
  169374. u32 iRowid; /* The rowid */
  169375. u32 iBegin; /* The first node of the scan */
  169376. u32 i; /* Index in sParse.aNode[] of current row */
  169377. u32 iEnd; /* EOF when i equals or exceeds this value */
  169378. u8 eType; /* Type of top-level element */
  169379. u8 bRecursive; /* True for json_tree(). False for json_each() */
  169380. char *zJson; /* Input JSON */
  169381. char *zRoot; /* Path by which to filter zJson */
  169382. JsonParse sParse; /* Parse of the input JSON */
  169383. };
  169384. /* Constructor for the json_each virtual table */
  169385. static int jsonEachConnect(
  169386. sqlite3 *db,
  169387. void *pAux,
  169388. int argc, const char *const*argv,
  169389. sqlite3_vtab **ppVtab,
  169390. char **pzErr
  169391. ){
  169392. sqlite3_vtab *pNew;
  169393. int rc;
  169394. /* Column numbers */
  169395. #define JEACH_KEY 0
  169396. #define JEACH_VALUE 1
  169397. #define JEACH_TYPE 2
  169398. #define JEACH_ATOM 3
  169399. #define JEACH_ID 4
  169400. #define JEACH_PARENT 5
  169401. #define JEACH_FULLKEY 6
  169402. #define JEACH_PATH 7
  169403. /* The xBestIndex method assumes that the JSON and ROOT columns are
  169404. ** the last two columns in the table. Should this ever changes, be
  169405. ** sure to update the xBestIndex method. */
  169406. #define JEACH_JSON 8
  169407. #define JEACH_ROOT 9
  169408. UNUSED_PARAM(pzErr);
  169409. UNUSED_PARAM(argv);
  169410. UNUSED_PARAM(argc);
  169411. UNUSED_PARAM(pAux);
  169412. rc = sqlite3_declare_vtab(db,
  169413. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  169414. "json HIDDEN,root HIDDEN)");
  169415. if( rc==SQLITE_OK ){
  169416. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  169417. if( pNew==0 ) return SQLITE_NOMEM;
  169418. memset(pNew, 0, sizeof(*pNew));
  169419. }
  169420. return rc;
  169421. }
  169422. /* destructor for json_each virtual table */
  169423. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  169424. sqlite3_free(pVtab);
  169425. return SQLITE_OK;
  169426. }
  169427. /* constructor for a JsonEachCursor object for json_each(). */
  169428. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  169429. JsonEachCursor *pCur;
  169430. UNUSED_PARAM(p);
  169431. pCur = sqlite3_malloc( sizeof(*pCur) );
  169432. if( pCur==0 ) return SQLITE_NOMEM;
  169433. memset(pCur, 0, sizeof(*pCur));
  169434. *ppCursor = &pCur->base;
  169435. return SQLITE_OK;
  169436. }
  169437. /* constructor for a JsonEachCursor object for json_tree(). */
  169438. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  169439. int rc = jsonEachOpenEach(p, ppCursor);
  169440. if( rc==SQLITE_OK ){
  169441. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  169442. pCur->bRecursive = 1;
  169443. }
  169444. return rc;
  169445. }
  169446. /* Reset a JsonEachCursor back to its original state. Free any memory
  169447. ** held. */
  169448. static void jsonEachCursorReset(JsonEachCursor *p){
  169449. sqlite3_free(p->zJson);
  169450. sqlite3_free(p->zRoot);
  169451. jsonParseReset(&p->sParse);
  169452. p->iRowid = 0;
  169453. p->i = 0;
  169454. p->iEnd = 0;
  169455. p->eType = 0;
  169456. p->zJson = 0;
  169457. p->zRoot = 0;
  169458. }
  169459. /* Destructor for a jsonEachCursor object */
  169460. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  169461. JsonEachCursor *p = (JsonEachCursor*)cur;
  169462. jsonEachCursorReset(p);
  169463. sqlite3_free(cur);
  169464. return SQLITE_OK;
  169465. }
  169466. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  169467. ** of the JSON object */
  169468. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  169469. JsonEachCursor *p = (JsonEachCursor*)cur;
  169470. return p->i >= p->iEnd;
  169471. }
  169472. /* Advance the cursor to the next element for json_tree() */
  169473. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  169474. JsonEachCursor *p = (JsonEachCursor*)cur;
  169475. if( p->bRecursive ){
  169476. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  169477. p->i++;
  169478. p->iRowid++;
  169479. if( p->i<p->iEnd ){
  169480. u32 iUp = p->sParse.aUp[p->i];
  169481. JsonNode *pUp = &p->sParse.aNode[iUp];
  169482. p->eType = pUp->eType;
  169483. if( pUp->eType==JSON_ARRAY ){
  169484. if( iUp==p->i-1 ){
  169485. pUp->u.iKey = 0;
  169486. }else{
  169487. pUp->u.iKey++;
  169488. }
  169489. }
  169490. }
  169491. }else{
  169492. switch( p->eType ){
  169493. case JSON_ARRAY: {
  169494. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  169495. p->iRowid++;
  169496. break;
  169497. }
  169498. case JSON_OBJECT: {
  169499. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  169500. p->iRowid++;
  169501. break;
  169502. }
  169503. default: {
  169504. p->i = p->iEnd;
  169505. break;
  169506. }
  169507. }
  169508. }
  169509. return SQLITE_OK;
  169510. }
  169511. /* Append the name of the path for element i to pStr
  169512. */
  169513. static void jsonEachComputePath(
  169514. JsonEachCursor *p, /* The cursor */
  169515. JsonString *pStr, /* Write the path here */
  169516. u32 i /* Path to this element */
  169517. ){
  169518. JsonNode *pNode, *pUp;
  169519. u32 iUp;
  169520. if( i==0 ){
  169521. jsonAppendChar(pStr, '$');
  169522. return;
  169523. }
  169524. iUp = p->sParse.aUp[i];
  169525. jsonEachComputePath(p, pStr, iUp);
  169526. pNode = &p->sParse.aNode[i];
  169527. pUp = &p->sParse.aNode[iUp];
  169528. if( pUp->eType==JSON_ARRAY ){
  169529. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  169530. }else{
  169531. assert( pUp->eType==JSON_OBJECT );
  169532. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  169533. assert( pNode->eType==JSON_STRING );
  169534. assert( pNode->jnFlags & JNODE_LABEL );
  169535. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  169536. }
  169537. }
  169538. /* Return the value of a column */
  169539. static int jsonEachColumn(
  169540. sqlite3_vtab_cursor *cur, /* The cursor */
  169541. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  169542. int i /* Which column to return */
  169543. ){
  169544. JsonEachCursor *p = (JsonEachCursor*)cur;
  169545. JsonNode *pThis = &p->sParse.aNode[p->i];
  169546. switch( i ){
  169547. case JEACH_KEY: {
  169548. if( p->i==0 ) break;
  169549. if( p->eType==JSON_OBJECT ){
  169550. jsonReturn(pThis, ctx, 0);
  169551. }else if( p->eType==JSON_ARRAY ){
  169552. u32 iKey;
  169553. if( p->bRecursive ){
  169554. if( p->iRowid==0 ) break;
  169555. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  169556. }else{
  169557. iKey = p->iRowid;
  169558. }
  169559. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  169560. }
  169561. break;
  169562. }
  169563. case JEACH_VALUE: {
  169564. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  169565. jsonReturn(pThis, ctx, 0);
  169566. break;
  169567. }
  169568. case JEACH_TYPE: {
  169569. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  169570. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  169571. break;
  169572. }
  169573. case JEACH_ATOM: {
  169574. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  169575. if( pThis->eType>=JSON_ARRAY ) break;
  169576. jsonReturn(pThis, ctx, 0);
  169577. break;
  169578. }
  169579. case JEACH_ID: {
  169580. sqlite3_result_int64(ctx,
  169581. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  169582. break;
  169583. }
  169584. case JEACH_PARENT: {
  169585. if( p->i>p->iBegin && p->bRecursive ){
  169586. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  169587. }
  169588. break;
  169589. }
  169590. case JEACH_FULLKEY: {
  169591. JsonString x;
  169592. jsonInit(&x, ctx);
  169593. if( p->bRecursive ){
  169594. jsonEachComputePath(p, &x, p->i);
  169595. }else{
  169596. if( p->zRoot ){
  169597. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  169598. }else{
  169599. jsonAppendChar(&x, '$');
  169600. }
  169601. if( p->eType==JSON_ARRAY ){
  169602. jsonPrintf(30, &x, "[%d]", p->iRowid);
  169603. }else if( p->eType==JSON_OBJECT ){
  169604. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  169605. }
  169606. }
  169607. jsonResult(&x);
  169608. break;
  169609. }
  169610. case JEACH_PATH: {
  169611. if( p->bRecursive ){
  169612. JsonString x;
  169613. jsonInit(&x, ctx);
  169614. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  169615. jsonResult(&x);
  169616. break;
  169617. }
  169618. /* For json_each() path and root are the same so fall through
  169619. ** into the root case */
  169620. }
  169621. default: {
  169622. const char *zRoot = p->zRoot;
  169623. if( zRoot==0 ) zRoot = "$";
  169624. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  169625. break;
  169626. }
  169627. case JEACH_JSON: {
  169628. assert( i==JEACH_JSON );
  169629. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  169630. break;
  169631. }
  169632. }
  169633. return SQLITE_OK;
  169634. }
  169635. /* Return the current rowid value */
  169636. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  169637. JsonEachCursor *p = (JsonEachCursor*)cur;
  169638. *pRowid = p->iRowid;
  169639. return SQLITE_OK;
  169640. }
  169641. /* The query strategy is to look for an equality constraint on the json
  169642. ** column. Without such a constraint, the table cannot operate. idxNum is
  169643. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  169644. ** and 0 otherwise.
  169645. */
  169646. static int jsonEachBestIndex(
  169647. sqlite3_vtab *tab,
  169648. sqlite3_index_info *pIdxInfo
  169649. ){
  169650. int i; /* Loop counter or computed array index */
  169651. int aIdx[2]; /* Index of constraints for JSON and ROOT */
  169652. int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */
  169653. int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */
  169654. const struct sqlite3_index_constraint *pConstraint;
  169655. /* This implementation assumes that JSON and ROOT are the last two
  169656. ** columns in the table */
  169657. assert( JEACH_ROOT == JEACH_JSON+1 );
  169658. UNUSED_PARAM(tab);
  169659. aIdx[0] = aIdx[1] = -1;
  169660. pConstraint = pIdxInfo->aConstraint;
  169661. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  169662. int iCol;
  169663. int iMask;
  169664. if( pConstraint->iColumn < JEACH_JSON ) continue;
  169665. iCol = pConstraint->iColumn - JEACH_JSON;
  169666. assert( iCol==0 || iCol==1 );
  169667. iMask = 1 << iCol;
  169668. if( pConstraint->usable==0 ){
  169669. unusableMask |= iMask;
  169670. }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  169671. aIdx[iCol] = i;
  169672. idxMask |= iMask;
  169673. }
  169674. }
  169675. if( (unusableMask & ~idxMask)!=0 ){
  169676. /* If there are any unusable constraints on JSON or ROOT, then reject
  169677. ** this entire plan */
  169678. return SQLITE_CONSTRAINT;
  169679. }
  169680. if( aIdx[0]<0 ){
  169681. /* No JSON input. Leave estimatedCost at the huge value that it was
  169682. ** initialized to to discourage the query planner from selecting this
  169683. ** plan. */
  169684. pIdxInfo->idxNum = 0;
  169685. }else{
  169686. pIdxInfo->estimatedCost = 1.0;
  169687. i = aIdx[0];
  169688. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  169689. pIdxInfo->aConstraintUsage[i].omit = 1;
  169690. if( aIdx[1]<0 ){
  169691. pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */
  169692. }else{
  169693. i = aIdx[1];
  169694. pIdxInfo->aConstraintUsage[i].argvIndex = 2;
  169695. pIdxInfo->aConstraintUsage[i].omit = 1;
  169696. pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */
  169697. }
  169698. }
  169699. return SQLITE_OK;
  169700. }
  169701. /* Start a search on a new JSON string */
  169702. static int jsonEachFilter(
  169703. sqlite3_vtab_cursor *cur,
  169704. int idxNum, const char *idxStr,
  169705. int argc, sqlite3_value **argv
  169706. ){
  169707. JsonEachCursor *p = (JsonEachCursor*)cur;
  169708. const char *z;
  169709. const char *zRoot = 0;
  169710. sqlite3_int64 n;
  169711. UNUSED_PARAM(idxStr);
  169712. UNUSED_PARAM(argc);
  169713. jsonEachCursorReset(p);
  169714. if( idxNum==0 ) return SQLITE_OK;
  169715. z = (const char*)sqlite3_value_text(argv[0]);
  169716. if( z==0 ) return SQLITE_OK;
  169717. n = sqlite3_value_bytes(argv[0]);
  169718. p->zJson = sqlite3_malloc64( n+1 );
  169719. if( p->zJson==0 ) return SQLITE_NOMEM;
  169720. memcpy(p->zJson, z, (size_t)n+1);
  169721. if( jsonParse(&p->sParse, 0, p->zJson) ){
  169722. int rc = SQLITE_NOMEM;
  169723. if( p->sParse.oom==0 ){
  169724. sqlite3_free(cur->pVtab->zErrMsg);
  169725. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  169726. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  169727. }
  169728. jsonEachCursorReset(p);
  169729. return rc;
  169730. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  169731. jsonEachCursorReset(p);
  169732. return SQLITE_NOMEM;
  169733. }else{
  169734. JsonNode *pNode = 0;
  169735. if( idxNum==3 ){
  169736. const char *zErr = 0;
  169737. zRoot = (const char*)sqlite3_value_text(argv[1]);
  169738. if( zRoot==0 ) return SQLITE_OK;
  169739. n = sqlite3_value_bytes(argv[1]);
  169740. p->zRoot = sqlite3_malloc64( n+1 );
  169741. if( p->zRoot==0 ) return SQLITE_NOMEM;
  169742. memcpy(p->zRoot, zRoot, (size_t)n+1);
  169743. if( zRoot[0]!='$' ){
  169744. zErr = zRoot;
  169745. }else{
  169746. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  169747. }
  169748. if( zErr ){
  169749. sqlite3_free(cur->pVtab->zErrMsg);
  169750. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  169751. jsonEachCursorReset(p);
  169752. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  169753. }else if( pNode==0 ){
  169754. return SQLITE_OK;
  169755. }
  169756. }else{
  169757. pNode = p->sParse.aNode;
  169758. }
  169759. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  169760. p->eType = pNode->eType;
  169761. if( p->eType>=JSON_ARRAY ){
  169762. pNode->u.iKey = 0;
  169763. p->iEnd = p->i + pNode->n + 1;
  169764. if( p->bRecursive ){
  169765. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  169766. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  169767. p->i--;
  169768. }
  169769. }else{
  169770. p->i++;
  169771. }
  169772. }else{
  169773. p->iEnd = p->i+1;
  169774. }
  169775. }
  169776. return SQLITE_OK;
  169777. }
  169778. /* The methods of the json_each virtual table */
  169779. static sqlite3_module jsonEachModule = {
  169780. 0, /* iVersion */
  169781. 0, /* xCreate */
  169782. jsonEachConnect, /* xConnect */
  169783. jsonEachBestIndex, /* xBestIndex */
  169784. jsonEachDisconnect, /* xDisconnect */
  169785. 0, /* xDestroy */
  169786. jsonEachOpenEach, /* xOpen - open a cursor */
  169787. jsonEachClose, /* xClose - close a cursor */
  169788. jsonEachFilter, /* xFilter - configure scan constraints */
  169789. jsonEachNext, /* xNext - advance a cursor */
  169790. jsonEachEof, /* xEof - check for end of scan */
  169791. jsonEachColumn, /* xColumn - read data */
  169792. jsonEachRowid, /* xRowid - read data */
  169793. 0, /* xUpdate */
  169794. 0, /* xBegin */
  169795. 0, /* xSync */
  169796. 0, /* xCommit */
  169797. 0, /* xRollback */
  169798. 0, /* xFindMethod */
  169799. 0, /* xRename */
  169800. 0, /* xSavepoint */
  169801. 0, /* xRelease */
  169802. 0, /* xRollbackTo */
  169803. 0 /* xShadowName */
  169804. };
  169805. /* The methods of the json_tree virtual table. */
  169806. static sqlite3_module jsonTreeModule = {
  169807. 0, /* iVersion */
  169808. 0, /* xCreate */
  169809. jsonEachConnect, /* xConnect */
  169810. jsonEachBestIndex, /* xBestIndex */
  169811. jsonEachDisconnect, /* xDisconnect */
  169812. 0, /* xDestroy */
  169813. jsonEachOpenTree, /* xOpen - open a cursor */
  169814. jsonEachClose, /* xClose - close a cursor */
  169815. jsonEachFilter, /* xFilter - configure scan constraints */
  169816. jsonEachNext, /* xNext - advance a cursor */
  169817. jsonEachEof, /* xEof - check for end of scan */
  169818. jsonEachColumn, /* xColumn - read data */
  169819. jsonEachRowid, /* xRowid - read data */
  169820. 0, /* xUpdate */
  169821. 0, /* xBegin */
  169822. 0, /* xSync */
  169823. 0, /* xCommit */
  169824. 0, /* xRollback */
  169825. 0, /* xFindMethod */
  169826. 0, /* xRename */
  169827. 0, /* xSavepoint */
  169828. 0, /* xRelease */
  169829. 0, /* xRollbackTo */
  169830. 0 /* xShadowName */
  169831. };
  169832. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  169833. /****************************************************************************
  169834. ** The following routines are the only publically visible identifiers in this
  169835. ** file. Call the following routines in order to register the various SQL
  169836. ** functions and the virtual table implemented by this file.
  169837. ****************************************************************************/
  169838. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  169839. int rc = SQLITE_OK;
  169840. unsigned int i;
  169841. static const struct {
  169842. const char *zName;
  169843. int nArg;
  169844. int flag;
  169845. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  169846. } aFunc[] = {
  169847. { "json", 1, 0, jsonRemoveFunc },
  169848. { "json_array", -1, 0, jsonArrayFunc },
  169849. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  169850. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  169851. { "json_extract", -1, 0, jsonExtractFunc },
  169852. { "json_insert", -1, 0, jsonSetFunc },
  169853. { "json_object", -1, 0, jsonObjectFunc },
  169854. { "json_patch", 2, 0, jsonPatchFunc },
  169855. { "json_quote", 1, 0, jsonQuoteFunc },
  169856. { "json_remove", -1, 0, jsonRemoveFunc },
  169857. { "json_replace", -1, 0, jsonReplaceFunc },
  169858. { "json_set", -1, 1, jsonSetFunc },
  169859. { "json_type", 1, 0, jsonTypeFunc },
  169860. { "json_type", 2, 0, jsonTypeFunc },
  169861. { "json_valid", 1, 0, jsonValidFunc },
  169862. #if SQLITE_DEBUG
  169863. /* DEBUG and TESTING functions */
  169864. { "json_parse", 1, 0, jsonParseFunc },
  169865. { "json_test1", 1, 0, jsonTest1Func },
  169866. #endif
  169867. };
  169868. static const struct {
  169869. const char *zName;
  169870. int nArg;
  169871. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  169872. void (*xFinal)(sqlite3_context*);
  169873. void (*xValue)(sqlite3_context*);
  169874. } aAgg[] = {
  169875. { "json_group_array", 1,
  169876. jsonArrayStep, jsonArrayFinal, jsonArrayValue },
  169877. { "json_group_object", 2,
  169878. jsonObjectStep, jsonObjectFinal, jsonObjectValue },
  169879. };
  169880. #ifndef SQLITE_OMIT_VIRTUALTABLE
  169881. static const struct {
  169882. const char *zName;
  169883. sqlite3_module *pModule;
  169884. } aMod[] = {
  169885. { "json_each", &jsonEachModule },
  169886. { "json_tree", &jsonTreeModule },
  169887. };
  169888. #endif
  169889. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  169890. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  169891. SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  169892. (void*)&aFunc[i].flag,
  169893. aFunc[i].xFunc, 0, 0);
  169894. }
  169895. #ifndef SQLITE_OMIT_WINDOWFUNC
  169896. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  169897. rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
  169898. SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
  169899. aAgg[i].xStep, aAgg[i].xFinal,
  169900. aAgg[i].xValue, jsonGroupInverse, 0);
  169901. }
  169902. #endif
  169903. #ifndef SQLITE_OMIT_VIRTUALTABLE
  169904. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  169905. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  169906. }
  169907. #endif
  169908. return rc;
  169909. }
  169910. #ifndef SQLITE_CORE
  169911. #ifdef _WIN32
  169912. __declspec(dllexport)
  169913. #endif
  169914. SQLITE_API int sqlite3_json_init(
  169915. sqlite3 *db,
  169916. char **pzErrMsg,
  169917. const sqlite3_api_routines *pApi
  169918. ){
  169919. SQLITE_EXTENSION_INIT2(pApi);
  169920. (void)pzErrMsg; /* Unused parameter */
  169921. return sqlite3Json1Init(db);
  169922. }
  169923. #endif
  169924. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  169925. /************** End of json1.c ***********************************************/
  169926. /************** Begin file rtree.c *******************************************/
  169927. /*
  169928. ** 2001 September 15
  169929. **
  169930. ** The author disclaims copyright to this source code. In place of
  169931. ** a legal notice, here is a blessing:
  169932. **
  169933. ** May you do good and not evil.
  169934. ** May you find forgiveness for yourself and forgive others.
  169935. ** May you share freely, never taking more than you give.
  169936. **
  169937. *************************************************************************
  169938. ** This file contains code for implementations of the r-tree and r*-tree
  169939. ** algorithms packaged as an SQLite virtual table module.
  169940. */
  169941. /*
  169942. ** Database Format of R-Tree Tables
  169943. ** --------------------------------
  169944. **
  169945. ** The data structure for a single virtual r-tree table is stored in three
  169946. ** native SQLite tables declared as follows. In each case, the '%' character
  169947. ** in the table name is replaced with the user-supplied name of the r-tree
  169948. ** table.
  169949. **
  169950. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  169951. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  169952. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
  169953. **
  169954. ** The data for each node of the r-tree structure is stored in the %_node
  169955. ** table. For each node that is not the root node of the r-tree, there is
  169956. ** an entry in the %_parent table associating the node with its parent.
  169957. ** And for each row of data in the table, there is an entry in the %_rowid
  169958. ** table that maps from the entries rowid to the id of the node that it
  169959. ** is stored on. If the r-tree contains auxiliary columns, those are stored
  169960. ** on the end of the %_rowid table.
  169961. **
  169962. ** The root node of an r-tree always exists, even if the r-tree table is
  169963. ** empty. The nodeno of the root node is always 1. All other nodes in the
  169964. ** table must be the same size as the root node. The content of each node
  169965. ** is formatted as follows:
  169966. **
  169967. ** 1. If the node is the root node (node 1), then the first 2 bytes
  169968. ** of the node contain the tree depth as a big-endian integer.
  169969. ** For non-root nodes, the first 2 bytes are left unused.
  169970. **
  169971. ** 2. The next 2 bytes contain the number of entries currently
  169972. ** stored in the node.
  169973. **
  169974. ** 3. The remainder of the node contains the node entries. Each entry
  169975. ** consists of a single 8-byte integer followed by an even number
  169976. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  169977. ** of a record. For internal nodes it is the node number of a
  169978. ** child page.
  169979. */
  169980. #if !defined(SQLITE_CORE) \
  169981. || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
  169982. #ifndef SQLITE_CORE
  169983. /* #include "sqlite3ext.h" */
  169984. SQLITE_EXTENSION_INIT1
  169985. #else
  169986. /* #include "sqlite3.h" */
  169987. #endif
  169988. /* #include <string.h> */
  169989. /* #include <assert.h> */
  169990. /* #include <stdio.h> */
  169991. #ifndef SQLITE_AMALGAMATION
  169992. #include "sqlite3rtree.h"
  169993. typedef sqlite3_int64 i64;
  169994. typedef sqlite3_uint64 u64;
  169995. typedef unsigned char u8;
  169996. typedef unsigned short u16;
  169997. typedef unsigned int u32;
  169998. #endif
  169999. /* The following macro is used to suppress compiler warnings.
  170000. */
  170001. #ifndef UNUSED_PARAMETER
  170002. # define UNUSED_PARAMETER(x) (void)(x)
  170003. #endif
  170004. typedef struct Rtree Rtree;
  170005. typedef struct RtreeCursor RtreeCursor;
  170006. typedef struct RtreeNode RtreeNode;
  170007. typedef struct RtreeCell RtreeCell;
  170008. typedef struct RtreeConstraint RtreeConstraint;
  170009. typedef struct RtreeMatchArg RtreeMatchArg;
  170010. typedef struct RtreeGeomCallback RtreeGeomCallback;
  170011. typedef union RtreeCoord RtreeCoord;
  170012. typedef struct RtreeSearchPoint RtreeSearchPoint;
  170013. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  170014. #define RTREE_MAX_DIMENSIONS 5
  170015. /* Maximum number of auxiliary columns */
  170016. #define RTREE_MAX_AUX_COLUMN 100
  170017. /* Size of hash table Rtree.aHash. This hash table is not expected to
  170018. ** ever contain very many entries, so a fixed number of buckets is
  170019. ** used.
  170020. */
  170021. #define HASHSIZE 97
  170022. /* The xBestIndex method of this virtual table requires an estimate of
  170023. ** the number of rows in the virtual table to calculate the costs of
  170024. ** various strategies. If possible, this estimate is loaded from the
  170025. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  170026. ** Otherwise, if no sqlite_stat1 entry is available, use
  170027. ** RTREE_DEFAULT_ROWEST.
  170028. */
  170029. #define RTREE_DEFAULT_ROWEST 1048576
  170030. #define RTREE_MIN_ROWEST 100
  170031. /*
  170032. ** An rtree virtual-table object.
  170033. */
  170034. struct Rtree {
  170035. sqlite3_vtab base; /* Base class. Must be first */
  170036. sqlite3 *db; /* Host database connection */
  170037. int iNodeSize; /* Size in bytes of each node in the node table */
  170038. u8 nDim; /* Number of dimensions */
  170039. u8 nDim2; /* Twice the number of dimensions */
  170040. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  170041. u8 nBytesPerCell; /* Bytes consumed per cell */
  170042. u8 inWrTrans; /* True if inside write transaction */
  170043. u8 nAux; /* # of auxiliary columns in %_rowid */
  170044. u8 nAuxNotNull; /* Number of initial not-null aux columns */
  170045. #ifdef SQLITE_DEBUG
  170046. u8 bCorrupt; /* Shadow table corruption detected */
  170047. #endif
  170048. int iDepth; /* Current depth of the r-tree structure */
  170049. char *zDb; /* Name of database containing r-tree table */
  170050. char *zName; /* Name of r-tree table */
  170051. u32 nBusy; /* Current number of users of this structure */
  170052. i64 nRowEst; /* Estimated number of rows in this table */
  170053. u32 nCursor; /* Number of open cursors */
  170054. u32 nNodeRef; /* Number RtreeNodes with positive nRef */
  170055. char *zReadAuxSql; /* SQL for statement to read aux data */
  170056. /* List of nodes removed during a CondenseTree operation. List is
  170057. ** linked together via the pointer normally used for hash chains -
  170058. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  170059. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  170060. */
  170061. RtreeNode *pDeleted;
  170062. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  170063. /* Blob I/O on xxx_node */
  170064. sqlite3_blob *pNodeBlob;
  170065. /* Statements to read/write/delete a record from xxx_node */
  170066. sqlite3_stmt *pWriteNode;
  170067. sqlite3_stmt *pDeleteNode;
  170068. /* Statements to read/write/delete a record from xxx_rowid */
  170069. sqlite3_stmt *pReadRowid;
  170070. sqlite3_stmt *pWriteRowid;
  170071. sqlite3_stmt *pDeleteRowid;
  170072. /* Statements to read/write/delete a record from xxx_parent */
  170073. sqlite3_stmt *pReadParent;
  170074. sqlite3_stmt *pWriteParent;
  170075. sqlite3_stmt *pDeleteParent;
  170076. /* Statement for writing to the "aux:" fields, if there are any */
  170077. sqlite3_stmt *pWriteAux;
  170078. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  170079. };
  170080. /* Possible values for Rtree.eCoordType: */
  170081. #define RTREE_COORD_REAL32 0
  170082. #define RTREE_COORD_INT32 1
  170083. /*
  170084. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  170085. ** only deal with integer coordinates. No floating point operations
  170086. ** will be done.
  170087. */
  170088. #ifdef SQLITE_RTREE_INT_ONLY
  170089. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  170090. typedef int RtreeValue; /* Low accuracy coordinate */
  170091. # define RTREE_ZERO 0
  170092. #else
  170093. typedef double RtreeDValue; /* High accuracy coordinate */
  170094. typedef float RtreeValue; /* Low accuracy coordinate */
  170095. # define RTREE_ZERO 0.0
  170096. #endif
  170097. /*
  170098. ** Set the Rtree.bCorrupt flag
  170099. */
  170100. #ifdef SQLITE_DEBUG
  170101. # define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1)
  170102. #else
  170103. # define RTREE_IS_CORRUPT(X)
  170104. #endif
  170105. /*
  170106. ** When doing a search of an r-tree, instances of the following structure
  170107. ** record intermediate results from the tree walk.
  170108. **
  170109. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  170110. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  170111. ** the id is of the parent node and the cell that RtreeSearchPoint
  170112. ** represents is the iCell-th entry in the parent node.
  170113. */
  170114. struct RtreeSearchPoint {
  170115. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  170116. sqlite3_int64 id; /* Node ID */
  170117. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  170118. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  170119. u8 iCell; /* Cell index within the node */
  170120. };
  170121. /*
  170122. ** The minimum number of cells allowed for a node is a third of the
  170123. ** maximum. In Gutman's notation:
  170124. **
  170125. ** m = M/3
  170126. **
  170127. ** If an R*-tree "Reinsert" operation is required, the same number of
  170128. ** cells are removed from the overfull node and reinserted into the tree.
  170129. */
  170130. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  170131. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  170132. #define RTREE_MAXCELLS 51
  170133. /*
  170134. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  170135. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  170136. ** Therefore all non-root nodes must contain at least 3 entries. Since
  170137. ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
  170138. ** 40 or less.
  170139. */
  170140. #define RTREE_MAX_DEPTH 40
  170141. /*
  170142. ** Number of entries in the cursor RtreeNode cache. The first entry is
  170143. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  170144. ** entries cache the RtreeNode for the first elements of the priority queue.
  170145. */
  170146. #define RTREE_CACHE_SZ 5
  170147. /*
  170148. ** An rtree cursor object.
  170149. */
  170150. struct RtreeCursor {
  170151. sqlite3_vtab_cursor base; /* Base class. Must be first */
  170152. u8 atEOF; /* True if at end of search */
  170153. u8 bPoint; /* True if sPoint is valid */
  170154. u8 bAuxValid; /* True if pReadAux is valid */
  170155. int iStrategy; /* Copy of idxNum search parameter */
  170156. int nConstraint; /* Number of entries in aConstraint */
  170157. RtreeConstraint *aConstraint; /* Search constraints. */
  170158. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  170159. int nPoint; /* Number of slots used in aPoint[] */
  170160. int mxLevel; /* iLevel value for root of the tree */
  170161. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  170162. sqlite3_stmt *pReadAux; /* Statement to read aux-data */
  170163. RtreeSearchPoint sPoint; /* Cached next search point */
  170164. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  170165. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  170166. };
  170167. /* Return the Rtree of a RtreeCursor */
  170168. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  170169. /*
  170170. ** A coordinate can be either a floating point number or a integer. All
  170171. ** coordinates within a single R-Tree are always of the same time.
  170172. */
  170173. union RtreeCoord {
  170174. RtreeValue f; /* Floating point value */
  170175. int i; /* Integer value */
  170176. u32 u; /* Unsigned for byte-order conversions */
  170177. };
  170178. /*
  170179. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  170180. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  170181. ** variable pRtree points to the Rtree structure associated with the
  170182. ** RtreeCoord.
  170183. */
  170184. #ifdef SQLITE_RTREE_INT_ONLY
  170185. # define DCOORD(coord) ((RtreeDValue)coord.i)
  170186. #else
  170187. # define DCOORD(coord) ( \
  170188. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  170189. ((double)coord.f) : \
  170190. ((double)coord.i) \
  170191. )
  170192. #endif
  170193. /*
  170194. ** A search constraint.
  170195. */
  170196. struct RtreeConstraint {
  170197. int iCoord; /* Index of constrained coordinate */
  170198. int op; /* Constraining operation */
  170199. union {
  170200. RtreeDValue rValue; /* Constraint value. */
  170201. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  170202. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  170203. } u;
  170204. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  170205. };
  170206. /* Possible values for RtreeConstraint.op */
  170207. #define RTREE_EQ 0x41 /* A */
  170208. #define RTREE_LE 0x42 /* B */
  170209. #define RTREE_LT 0x43 /* C */
  170210. #define RTREE_GE 0x44 /* D */
  170211. #define RTREE_GT 0x45 /* E */
  170212. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  170213. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  170214. /*
  170215. ** An rtree structure node.
  170216. */
  170217. struct RtreeNode {
  170218. RtreeNode *pParent; /* Parent node */
  170219. i64 iNode; /* The node number */
  170220. int nRef; /* Number of references to this node */
  170221. int isDirty; /* True if the node needs to be written to disk */
  170222. u8 *zData; /* Content of the node, as should be on disk */
  170223. RtreeNode *pNext; /* Next node in this hash collision chain */
  170224. };
  170225. /* Return the number of cells in a node */
  170226. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  170227. /*
  170228. ** A single cell from a node, deserialized
  170229. */
  170230. struct RtreeCell {
  170231. i64 iRowid; /* Node or entry ID */
  170232. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  170233. };
  170234. /*
  170235. ** This object becomes the sqlite3_user_data() for the SQL functions
  170236. ** that are created by sqlite3_rtree_geometry_callback() and
  170237. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  170238. ** operators in order to constrain a search.
  170239. **
  170240. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  170241. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  170242. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  170243. ** sqlite3_rtree_query_callback().
  170244. **
  170245. ** This object is deleted automatically by the destructor mechanism in
  170246. ** sqlite3_create_function_v2().
  170247. */
  170248. struct RtreeGeomCallback {
  170249. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  170250. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  170251. void (*xDestructor)(void*);
  170252. void *pContext;
  170253. };
  170254. /*
  170255. ** An instance of this structure (in the form of a BLOB) is returned by
  170256. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  170257. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  170258. ** operand to the MATCH operator of an R-Tree.
  170259. */
  170260. struct RtreeMatchArg {
  170261. u32 iSize; /* Size of this object */
  170262. RtreeGeomCallback cb; /* Info about the callback functions */
  170263. int nParam; /* Number of parameters to the SQL function */
  170264. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  170265. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  170266. };
  170267. #ifndef MAX
  170268. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  170269. #endif
  170270. #ifndef MIN
  170271. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  170272. #endif
  170273. /* What version of GCC is being used. 0 means GCC is not being used .
  170274. ** Note that the GCC_VERSION macro will also be set correctly when using
  170275. ** clang, since clang works hard to be gcc compatible. So the gcc
  170276. ** optimizations will also work when compiling with clang.
  170277. */
  170278. #ifndef GCC_VERSION
  170279. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  170280. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  170281. #else
  170282. # define GCC_VERSION 0
  170283. #endif
  170284. #endif
  170285. /* The testcase() macro should already be defined in the amalgamation. If
  170286. ** it is not, make it a no-op.
  170287. */
  170288. #ifndef SQLITE_AMALGAMATION
  170289. # define testcase(X)
  170290. #endif
  170291. /*
  170292. ** Macros to determine whether the machine is big or little endian,
  170293. ** and whether or not that determination is run-time or compile-time.
  170294. **
  170295. ** For best performance, an attempt is made to guess at the byte-order
  170296. ** using C-preprocessor macros. If that is unsuccessful, or if
  170297. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  170298. ** at run-time.
  170299. */
  170300. #ifndef SQLITE_BYTEORDER
  170301. #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  170302. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  170303. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  170304. defined(__arm__)
  170305. # define SQLITE_BYTEORDER 1234
  170306. #elif defined(sparc) || defined(__ppc__)
  170307. # define SQLITE_BYTEORDER 4321
  170308. #else
  170309. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  170310. #endif
  170311. #endif
  170312. /* What version of MSVC is being used. 0 means MSVC is not being used */
  170313. #ifndef MSVC_VERSION
  170314. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  170315. # define MSVC_VERSION _MSC_VER
  170316. #else
  170317. # define MSVC_VERSION 0
  170318. #endif
  170319. #endif
  170320. /*
  170321. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  170322. ** 64 bit integer. The deserialized value is returned.
  170323. */
  170324. static int readInt16(u8 *p){
  170325. return (p[0]<<8) + p[1];
  170326. }
  170327. static void readCoord(u8 *p, RtreeCoord *pCoord){
  170328. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  170329. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  170330. pCoord->u = _byteswap_ulong(*(u32*)p);
  170331. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  170332. pCoord->u = __builtin_bswap32(*(u32*)p);
  170333. #elif SQLITE_BYTEORDER==4321
  170334. pCoord->u = *(u32*)p;
  170335. #else
  170336. pCoord->u = (
  170337. (((u32)p[0]) << 24) +
  170338. (((u32)p[1]) << 16) +
  170339. (((u32)p[2]) << 8) +
  170340. (((u32)p[3]) << 0)
  170341. );
  170342. #endif
  170343. }
  170344. static i64 readInt64(u8 *p){
  170345. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  170346. u64 x;
  170347. memcpy(&x, p, 8);
  170348. return (i64)_byteswap_uint64(x);
  170349. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  170350. u64 x;
  170351. memcpy(&x, p, 8);
  170352. return (i64)__builtin_bswap64(x);
  170353. #elif SQLITE_BYTEORDER==4321
  170354. i64 x;
  170355. memcpy(&x, p, 8);
  170356. return x;
  170357. #else
  170358. return (i64)(
  170359. (((u64)p[0]) << 56) +
  170360. (((u64)p[1]) << 48) +
  170361. (((u64)p[2]) << 40) +
  170362. (((u64)p[3]) << 32) +
  170363. (((u64)p[4]) << 24) +
  170364. (((u64)p[5]) << 16) +
  170365. (((u64)p[6]) << 8) +
  170366. (((u64)p[7]) << 0)
  170367. );
  170368. #endif
  170369. }
  170370. /*
  170371. ** Functions to serialize a 16 bit integer, 32 bit real number and
  170372. ** 64 bit integer. The value returned is the number of bytes written
  170373. ** to the argument buffer (always 2, 4 and 8 respectively).
  170374. */
  170375. static void writeInt16(u8 *p, int i){
  170376. p[0] = (i>> 8)&0xFF;
  170377. p[1] = (i>> 0)&0xFF;
  170378. }
  170379. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  170380. u32 i;
  170381. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  170382. assert( sizeof(RtreeCoord)==4 );
  170383. assert( sizeof(u32)==4 );
  170384. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  170385. i = __builtin_bswap32(pCoord->u);
  170386. memcpy(p, &i, 4);
  170387. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  170388. i = _byteswap_ulong(pCoord->u);
  170389. memcpy(p, &i, 4);
  170390. #elif SQLITE_BYTEORDER==4321
  170391. i = pCoord->u;
  170392. memcpy(p, &i, 4);
  170393. #else
  170394. i = pCoord->u;
  170395. p[0] = (i>>24)&0xFF;
  170396. p[1] = (i>>16)&0xFF;
  170397. p[2] = (i>> 8)&0xFF;
  170398. p[3] = (i>> 0)&0xFF;
  170399. #endif
  170400. return 4;
  170401. }
  170402. static int writeInt64(u8 *p, i64 i){
  170403. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  170404. i = (i64)__builtin_bswap64((u64)i);
  170405. memcpy(p, &i, 8);
  170406. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  170407. i = (i64)_byteswap_uint64((u64)i);
  170408. memcpy(p, &i, 8);
  170409. #elif SQLITE_BYTEORDER==4321
  170410. memcpy(p, &i, 8);
  170411. #else
  170412. p[0] = (i>>56)&0xFF;
  170413. p[1] = (i>>48)&0xFF;
  170414. p[2] = (i>>40)&0xFF;
  170415. p[3] = (i>>32)&0xFF;
  170416. p[4] = (i>>24)&0xFF;
  170417. p[5] = (i>>16)&0xFF;
  170418. p[6] = (i>> 8)&0xFF;
  170419. p[7] = (i>> 0)&0xFF;
  170420. #endif
  170421. return 8;
  170422. }
  170423. /*
  170424. ** Increment the reference count of node p.
  170425. */
  170426. static void nodeReference(RtreeNode *p){
  170427. if( p ){
  170428. assert( p->nRef>0 );
  170429. p->nRef++;
  170430. }
  170431. }
  170432. /*
  170433. ** Clear the content of node p (set all bytes to 0x00).
  170434. */
  170435. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  170436. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  170437. p->isDirty = 1;
  170438. }
  170439. /*
  170440. ** Given a node number iNode, return the corresponding key to use
  170441. ** in the Rtree.aHash table.
  170442. */
  170443. static unsigned int nodeHash(i64 iNode){
  170444. return ((unsigned)iNode) % HASHSIZE;
  170445. }
  170446. /*
  170447. ** Search the node hash table for node iNode. If found, return a pointer
  170448. ** to it. Otherwise, return 0.
  170449. */
  170450. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  170451. RtreeNode *p;
  170452. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  170453. return p;
  170454. }
  170455. /*
  170456. ** Add node pNode to the node hash table.
  170457. */
  170458. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  170459. int iHash;
  170460. assert( pNode->pNext==0 );
  170461. iHash = nodeHash(pNode->iNode);
  170462. pNode->pNext = pRtree->aHash[iHash];
  170463. pRtree->aHash[iHash] = pNode;
  170464. }
  170465. /*
  170466. ** Remove node pNode from the node hash table.
  170467. */
  170468. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  170469. RtreeNode **pp;
  170470. if( pNode->iNode!=0 ){
  170471. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  170472. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  170473. *pp = pNode->pNext;
  170474. pNode->pNext = 0;
  170475. }
  170476. }
  170477. /*
  170478. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  170479. ** indicating that node has not yet been assigned a node number. It is
  170480. ** assigned a node number when nodeWrite() is called to write the
  170481. ** node contents out to the database.
  170482. */
  170483. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  170484. RtreeNode *pNode;
  170485. pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize);
  170486. if( pNode ){
  170487. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  170488. pNode->zData = (u8 *)&pNode[1];
  170489. pNode->nRef = 1;
  170490. pRtree->nNodeRef++;
  170491. pNode->pParent = pParent;
  170492. pNode->isDirty = 1;
  170493. nodeReference(pParent);
  170494. }
  170495. return pNode;
  170496. }
  170497. /*
  170498. ** Clear the Rtree.pNodeBlob object
  170499. */
  170500. static void nodeBlobReset(Rtree *pRtree){
  170501. if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
  170502. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  170503. pRtree->pNodeBlob = 0;
  170504. sqlite3_blob_close(pBlob);
  170505. }
  170506. }
  170507. /*
  170508. ** Check to see if pNode is the same as pParent or any of the parents
  170509. ** of pParent.
  170510. */
  170511. static int nodeInParentChain(const RtreeNode *pNode, const RtreeNode *pParent){
  170512. do{
  170513. if( pNode==pParent ) return 1;
  170514. pParent = pParent->pParent;
  170515. }while( pParent );
  170516. return 0;
  170517. }
  170518. /*
  170519. ** Obtain a reference to an r-tree node.
  170520. */
  170521. static int nodeAcquire(
  170522. Rtree *pRtree, /* R-tree structure */
  170523. i64 iNode, /* Node number to load */
  170524. RtreeNode *pParent, /* Either the parent node or NULL */
  170525. RtreeNode **ppNode /* OUT: Acquired node */
  170526. ){
  170527. int rc = SQLITE_OK;
  170528. RtreeNode *pNode = 0;
  170529. /* Check if the requested node is already in the hash table. If so,
  170530. ** increase its reference count and return it.
  170531. */
  170532. if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
  170533. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  170534. if( pParent && !pNode->pParent ){
  170535. if( nodeInParentChain(pNode, pParent) ){
  170536. RTREE_IS_CORRUPT(pRtree);
  170537. return SQLITE_CORRUPT_VTAB;
  170538. }
  170539. pParent->nRef++;
  170540. pNode->pParent = pParent;
  170541. }
  170542. pNode->nRef++;
  170543. *ppNode = pNode;
  170544. return SQLITE_OK;
  170545. }
  170546. if( pRtree->pNodeBlob ){
  170547. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  170548. pRtree->pNodeBlob = 0;
  170549. rc = sqlite3_blob_reopen(pBlob, iNode);
  170550. pRtree->pNodeBlob = pBlob;
  170551. if( rc ){
  170552. nodeBlobReset(pRtree);
  170553. if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
  170554. }
  170555. }
  170556. if( pRtree->pNodeBlob==0 ){
  170557. char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
  170558. if( zTab==0 ) return SQLITE_NOMEM;
  170559. rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
  170560. &pRtree->pNodeBlob);
  170561. sqlite3_free(zTab);
  170562. }
  170563. if( rc ){
  170564. nodeBlobReset(pRtree);
  170565. *ppNode = 0;
  170566. /* If unable to open an sqlite3_blob on the desired row, that can only
  170567. ** be because the shadow tables hold erroneous data. */
  170568. if( rc==SQLITE_ERROR ){
  170569. rc = SQLITE_CORRUPT_VTAB;
  170570. RTREE_IS_CORRUPT(pRtree);
  170571. }
  170572. }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
  170573. pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
  170574. if( !pNode ){
  170575. rc = SQLITE_NOMEM;
  170576. }else{
  170577. pNode->pParent = pParent;
  170578. pNode->zData = (u8 *)&pNode[1];
  170579. pNode->nRef = 1;
  170580. pRtree->nNodeRef++;
  170581. pNode->iNode = iNode;
  170582. pNode->isDirty = 0;
  170583. pNode->pNext = 0;
  170584. rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
  170585. pRtree->iNodeSize, 0);
  170586. }
  170587. }
  170588. /* If the root node was just loaded, set pRtree->iDepth to the height
  170589. ** of the r-tree structure. A height of zero means all data is stored on
  170590. ** the root node. A height of one means the children of the root node
  170591. ** are the leaves, and so on. If the depth as specified on the root node
  170592. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  170593. */
  170594. if( pNode && iNode==1 ){
  170595. pRtree->iDepth = readInt16(pNode->zData);
  170596. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  170597. rc = SQLITE_CORRUPT_VTAB;
  170598. RTREE_IS_CORRUPT(pRtree);
  170599. }
  170600. }
  170601. /* If no error has occurred so far, check if the "number of entries"
  170602. ** field on the node is too large. If so, set the return code to
  170603. ** SQLITE_CORRUPT_VTAB.
  170604. */
  170605. if( pNode && rc==SQLITE_OK ){
  170606. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  170607. rc = SQLITE_CORRUPT_VTAB;
  170608. RTREE_IS_CORRUPT(pRtree);
  170609. }
  170610. }
  170611. if( rc==SQLITE_OK ){
  170612. if( pNode!=0 ){
  170613. nodeReference(pParent);
  170614. nodeHashInsert(pRtree, pNode);
  170615. }else{
  170616. rc = SQLITE_CORRUPT_VTAB;
  170617. RTREE_IS_CORRUPT(pRtree);
  170618. }
  170619. *ppNode = pNode;
  170620. }else{
  170621. if( pNode ){
  170622. pRtree->nNodeRef--;
  170623. sqlite3_free(pNode);
  170624. }
  170625. *ppNode = 0;
  170626. }
  170627. return rc;
  170628. }
  170629. /*
  170630. ** Overwrite cell iCell of node pNode with the contents of pCell.
  170631. */
  170632. static void nodeOverwriteCell(
  170633. Rtree *pRtree, /* The overall R-Tree */
  170634. RtreeNode *pNode, /* The node into which the cell is to be written */
  170635. RtreeCell *pCell, /* The cell to write */
  170636. int iCell /* Index into pNode into which pCell is written */
  170637. ){
  170638. int ii;
  170639. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  170640. p += writeInt64(p, pCell->iRowid);
  170641. for(ii=0; ii<pRtree->nDim2; ii++){
  170642. p += writeCoord(p, &pCell->aCoord[ii]);
  170643. }
  170644. pNode->isDirty = 1;
  170645. }
  170646. /*
  170647. ** Remove the cell with index iCell from node pNode.
  170648. */
  170649. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  170650. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  170651. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  170652. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  170653. memmove(pDst, pSrc, nByte);
  170654. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  170655. pNode->isDirty = 1;
  170656. }
  170657. /*
  170658. ** Insert the contents of cell pCell into node pNode. If the insert
  170659. ** is successful, return SQLITE_OK.
  170660. **
  170661. ** If there is not enough free space in pNode, return SQLITE_FULL.
  170662. */
  170663. static int nodeInsertCell(
  170664. Rtree *pRtree, /* The overall R-Tree */
  170665. RtreeNode *pNode, /* Write new cell into this node */
  170666. RtreeCell *pCell /* The cell to be inserted */
  170667. ){
  170668. int nCell; /* Current number of cells in pNode */
  170669. int nMaxCell; /* Maximum number of cells for pNode */
  170670. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  170671. nCell = NCELL(pNode);
  170672. assert( nCell<=nMaxCell );
  170673. if( nCell<nMaxCell ){
  170674. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  170675. writeInt16(&pNode->zData[2], nCell+1);
  170676. pNode->isDirty = 1;
  170677. }
  170678. return (nCell==nMaxCell);
  170679. }
  170680. /*
  170681. ** If the node is dirty, write it out to the database.
  170682. */
  170683. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  170684. int rc = SQLITE_OK;
  170685. if( pNode->isDirty ){
  170686. sqlite3_stmt *p = pRtree->pWriteNode;
  170687. if( pNode->iNode ){
  170688. sqlite3_bind_int64(p, 1, pNode->iNode);
  170689. }else{
  170690. sqlite3_bind_null(p, 1);
  170691. }
  170692. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  170693. sqlite3_step(p);
  170694. pNode->isDirty = 0;
  170695. rc = sqlite3_reset(p);
  170696. sqlite3_bind_null(p, 2);
  170697. if( pNode->iNode==0 && rc==SQLITE_OK ){
  170698. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  170699. nodeHashInsert(pRtree, pNode);
  170700. }
  170701. }
  170702. return rc;
  170703. }
  170704. /*
  170705. ** Release a reference to a node. If the node is dirty and the reference
  170706. ** count drops to zero, the node data is written to the database.
  170707. */
  170708. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  170709. int rc = SQLITE_OK;
  170710. if( pNode ){
  170711. assert( pNode->nRef>0 );
  170712. assert( pRtree->nNodeRef>0 );
  170713. pNode->nRef--;
  170714. if( pNode->nRef==0 ){
  170715. pRtree->nNodeRef--;
  170716. if( pNode->iNode==1 ){
  170717. pRtree->iDepth = -1;
  170718. }
  170719. if( pNode->pParent ){
  170720. rc = nodeRelease(pRtree, pNode->pParent);
  170721. }
  170722. if( rc==SQLITE_OK ){
  170723. rc = nodeWrite(pRtree, pNode);
  170724. }
  170725. nodeHashDelete(pRtree, pNode);
  170726. sqlite3_free(pNode);
  170727. }
  170728. }
  170729. return rc;
  170730. }
  170731. /*
  170732. ** Return the 64-bit integer value associated with cell iCell of
  170733. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  170734. ** an internal node, then the 64-bit integer is a child page number.
  170735. */
  170736. static i64 nodeGetRowid(
  170737. Rtree *pRtree, /* The overall R-Tree */
  170738. RtreeNode *pNode, /* The node from which to extract the ID */
  170739. int iCell /* The cell index from which to extract the ID */
  170740. ){
  170741. assert( iCell<NCELL(pNode) );
  170742. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  170743. }
  170744. /*
  170745. ** Return coordinate iCoord from cell iCell in node pNode.
  170746. */
  170747. static void nodeGetCoord(
  170748. Rtree *pRtree, /* The overall R-Tree */
  170749. RtreeNode *pNode, /* The node from which to extract a coordinate */
  170750. int iCell, /* The index of the cell within the node */
  170751. int iCoord, /* Which coordinate to extract */
  170752. RtreeCoord *pCoord /* OUT: Space to write result to */
  170753. ){
  170754. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  170755. }
  170756. /*
  170757. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  170758. ** to by pCell with the results.
  170759. */
  170760. static void nodeGetCell(
  170761. Rtree *pRtree, /* The overall R-Tree */
  170762. RtreeNode *pNode, /* The node containing the cell to be read */
  170763. int iCell, /* Index of the cell within the node */
  170764. RtreeCell *pCell /* OUT: Write the cell contents here */
  170765. ){
  170766. u8 *pData;
  170767. RtreeCoord *pCoord;
  170768. int ii = 0;
  170769. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  170770. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  170771. pCoord = pCell->aCoord;
  170772. do{
  170773. readCoord(pData, &pCoord[ii]);
  170774. readCoord(pData+4, &pCoord[ii+1]);
  170775. pData += 8;
  170776. ii += 2;
  170777. }while( ii<pRtree->nDim2 );
  170778. }
  170779. /* Forward declaration for the function that does the work of
  170780. ** the virtual table module xCreate() and xConnect() methods.
  170781. */
  170782. static int rtreeInit(
  170783. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  170784. );
  170785. /*
  170786. ** Rtree virtual table module xCreate method.
  170787. */
  170788. static int rtreeCreate(
  170789. sqlite3 *db,
  170790. void *pAux,
  170791. int argc, const char *const*argv,
  170792. sqlite3_vtab **ppVtab,
  170793. char **pzErr
  170794. ){
  170795. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  170796. }
  170797. /*
  170798. ** Rtree virtual table module xConnect method.
  170799. */
  170800. static int rtreeConnect(
  170801. sqlite3 *db,
  170802. void *pAux,
  170803. int argc, const char *const*argv,
  170804. sqlite3_vtab **ppVtab,
  170805. char **pzErr
  170806. ){
  170807. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  170808. }
  170809. /*
  170810. ** Increment the r-tree reference count.
  170811. */
  170812. static void rtreeReference(Rtree *pRtree){
  170813. pRtree->nBusy++;
  170814. }
  170815. /*
  170816. ** Decrement the r-tree reference count. When the reference count reaches
  170817. ** zero the structure is deleted.
  170818. */
  170819. static void rtreeRelease(Rtree *pRtree){
  170820. pRtree->nBusy--;
  170821. if( pRtree->nBusy==0 ){
  170822. pRtree->inWrTrans = 0;
  170823. assert( pRtree->nCursor==0 );
  170824. nodeBlobReset(pRtree);
  170825. assert( pRtree->nNodeRef==0 || pRtree->bCorrupt );
  170826. sqlite3_finalize(pRtree->pWriteNode);
  170827. sqlite3_finalize(pRtree->pDeleteNode);
  170828. sqlite3_finalize(pRtree->pReadRowid);
  170829. sqlite3_finalize(pRtree->pWriteRowid);
  170830. sqlite3_finalize(pRtree->pDeleteRowid);
  170831. sqlite3_finalize(pRtree->pReadParent);
  170832. sqlite3_finalize(pRtree->pWriteParent);
  170833. sqlite3_finalize(pRtree->pDeleteParent);
  170834. sqlite3_finalize(pRtree->pWriteAux);
  170835. sqlite3_free(pRtree->zReadAuxSql);
  170836. sqlite3_free(pRtree);
  170837. }
  170838. }
  170839. /*
  170840. ** Rtree virtual table module xDisconnect method.
  170841. */
  170842. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  170843. rtreeRelease((Rtree *)pVtab);
  170844. return SQLITE_OK;
  170845. }
  170846. /*
  170847. ** Rtree virtual table module xDestroy method.
  170848. */
  170849. static int rtreeDestroy(sqlite3_vtab *pVtab){
  170850. Rtree *pRtree = (Rtree *)pVtab;
  170851. int rc;
  170852. char *zCreate = sqlite3_mprintf(
  170853. "DROP TABLE '%q'.'%q_node';"
  170854. "DROP TABLE '%q'.'%q_rowid';"
  170855. "DROP TABLE '%q'.'%q_parent';",
  170856. pRtree->zDb, pRtree->zName,
  170857. pRtree->zDb, pRtree->zName,
  170858. pRtree->zDb, pRtree->zName
  170859. );
  170860. if( !zCreate ){
  170861. rc = SQLITE_NOMEM;
  170862. }else{
  170863. nodeBlobReset(pRtree);
  170864. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  170865. sqlite3_free(zCreate);
  170866. }
  170867. if( rc==SQLITE_OK ){
  170868. rtreeRelease(pRtree);
  170869. }
  170870. return rc;
  170871. }
  170872. /*
  170873. ** Rtree virtual table module xOpen method.
  170874. */
  170875. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  170876. int rc = SQLITE_NOMEM;
  170877. Rtree *pRtree = (Rtree *)pVTab;
  170878. RtreeCursor *pCsr;
  170879. pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor));
  170880. if( pCsr ){
  170881. memset(pCsr, 0, sizeof(RtreeCursor));
  170882. pCsr->base.pVtab = pVTab;
  170883. rc = SQLITE_OK;
  170884. pRtree->nCursor++;
  170885. }
  170886. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  170887. return rc;
  170888. }
  170889. /*
  170890. ** Free the RtreeCursor.aConstraint[] array and its contents.
  170891. */
  170892. static void freeCursorConstraints(RtreeCursor *pCsr){
  170893. if( pCsr->aConstraint ){
  170894. int i; /* Used to iterate through constraint array */
  170895. for(i=0; i<pCsr->nConstraint; i++){
  170896. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  170897. if( pInfo ){
  170898. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  170899. sqlite3_free(pInfo);
  170900. }
  170901. }
  170902. sqlite3_free(pCsr->aConstraint);
  170903. pCsr->aConstraint = 0;
  170904. }
  170905. }
  170906. /*
  170907. ** Rtree virtual table module xClose method.
  170908. */
  170909. static int rtreeClose(sqlite3_vtab_cursor *cur){
  170910. Rtree *pRtree = (Rtree *)(cur->pVtab);
  170911. int ii;
  170912. RtreeCursor *pCsr = (RtreeCursor *)cur;
  170913. assert( pRtree->nCursor>0 );
  170914. freeCursorConstraints(pCsr);
  170915. sqlite3_finalize(pCsr->pReadAux);
  170916. sqlite3_free(pCsr->aPoint);
  170917. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  170918. sqlite3_free(pCsr);
  170919. pRtree->nCursor--;
  170920. nodeBlobReset(pRtree);
  170921. return SQLITE_OK;
  170922. }
  170923. /*
  170924. ** Rtree virtual table module xEof method.
  170925. **
  170926. ** Return non-zero if the cursor does not currently point to a valid
  170927. ** record (i.e if the scan has finished), or zero otherwise.
  170928. */
  170929. static int rtreeEof(sqlite3_vtab_cursor *cur){
  170930. RtreeCursor *pCsr = (RtreeCursor *)cur;
  170931. return pCsr->atEOF;
  170932. }
  170933. /*
  170934. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  170935. ** The on-disk format is big-endian and needs to be converted for little-
  170936. ** endian platforms. The on-disk record stores integer coordinates if
  170937. ** eInt is true and it stores 32-bit floating point records if eInt is
  170938. ** false. a[] is the four bytes of the on-disk record to be decoded.
  170939. ** Store the results in "r".
  170940. **
  170941. ** There are five versions of this macro. The last one is generic. The
  170942. ** other four are various architectures-specific optimizations.
  170943. */
  170944. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  170945. #define RTREE_DECODE_COORD(eInt, a, r) { \
  170946. RtreeCoord c; /* Coordinate decoded */ \
  170947. c.u = _byteswap_ulong(*(u32*)a); \
  170948. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  170949. }
  170950. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  170951. #define RTREE_DECODE_COORD(eInt, a, r) { \
  170952. RtreeCoord c; /* Coordinate decoded */ \
  170953. c.u = __builtin_bswap32(*(u32*)a); \
  170954. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  170955. }
  170956. #elif SQLITE_BYTEORDER==1234
  170957. #define RTREE_DECODE_COORD(eInt, a, r) { \
  170958. RtreeCoord c; /* Coordinate decoded */ \
  170959. memcpy(&c.u,a,4); \
  170960. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  170961. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  170962. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  170963. }
  170964. #elif SQLITE_BYTEORDER==4321
  170965. #define RTREE_DECODE_COORD(eInt, a, r) { \
  170966. RtreeCoord c; /* Coordinate decoded */ \
  170967. memcpy(&c.u,a,4); \
  170968. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  170969. }
  170970. #else
  170971. #define RTREE_DECODE_COORD(eInt, a, r) { \
  170972. RtreeCoord c; /* Coordinate decoded */ \
  170973. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  170974. +((u32)a[2]<<8) + a[3]; \
  170975. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  170976. }
  170977. #endif
  170978. /*
  170979. ** Check the RTree node or entry given by pCellData and p against the MATCH
  170980. ** constraint pConstraint.
  170981. */
  170982. static int rtreeCallbackConstraint(
  170983. RtreeConstraint *pConstraint, /* The constraint to test */
  170984. int eInt, /* True if RTree holding integer coordinates */
  170985. u8 *pCellData, /* Raw cell content */
  170986. RtreeSearchPoint *pSearch, /* Container of this cell */
  170987. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  170988. int *peWithin /* OUT: visibility of the cell */
  170989. ){
  170990. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  170991. int nCoord = pInfo->nCoord; /* No. of coordinates */
  170992. int rc; /* Callback return code */
  170993. RtreeCoord c; /* Translator union */
  170994. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  170995. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  170996. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  170997. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  170998. pInfo->iRowid = readInt64(pCellData);
  170999. }
  171000. pCellData += 8;
  171001. #ifndef SQLITE_RTREE_INT_ONLY
  171002. if( eInt==0 ){
  171003. switch( nCoord ){
  171004. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
  171005. readCoord(pCellData+32, &c); aCoord[8] = c.f;
  171006. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
  171007. readCoord(pCellData+24, &c); aCoord[6] = c.f;
  171008. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
  171009. readCoord(pCellData+16, &c); aCoord[4] = c.f;
  171010. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
  171011. readCoord(pCellData+8, &c); aCoord[2] = c.f;
  171012. default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
  171013. readCoord(pCellData, &c); aCoord[0] = c.f;
  171014. }
  171015. }else
  171016. #endif
  171017. {
  171018. switch( nCoord ){
  171019. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
  171020. readCoord(pCellData+32, &c); aCoord[8] = c.i;
  171021. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
  171022. readCoord(pCellData+24, &c); aCoord[6] = c.i;
  171023. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
  171024. readCoord(pCellData+16, &c); aCoord[4] = c.i;
  171025. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
  171026. readCoord(pCellData+8, &c); aCoord[2] = c.i;
  171027. default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
  171028. readCoord(pCellData, &c); aCoord[0] = c.i;
  171029. }
  171030. }
  171031. if( pConstraint->op==RTREE_MATCH ){
  171032. int eWithin = 0;
  171033. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  171034. nCoord, aCoord, &eWithin);
  171035. if( eWithin==0 ) *peWithin = NOT_WITHIN;
  171036. *prScore = RTREE_ZERO;
  171037. }else{
  171038. pInfo->aCoord = aCoord;
  171039. pInfo->iLevel = pSearch->iLevel - 1;
  171040. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  171041. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  171042. rc = pConstraint->u.xQueryFunc(pInfo);
  171043. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  171044. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  171045. *prScore = pInfo->rScore;
  171046. }
  171047. }
  171048. return rc;
  171049. }
  171050. /*
  171051. ** Check the internal RTree node given by pCellData against constraint p.
  171052. ** If this constraint cannot be satisfied by any child within the node,
  171053. ** set *peWithin to NOT_WITHIN.
  171054. */
  171055. static void rtreeNonleafConstraint(
  171056. RtreeConstraint *p, /* The constraint to test */
  171057. int eInt, /* True if RTree holds integer coordinates */
  171058. u8 *pCellData, /* Raw cell content as appears on disk */
  171059. int *peWithin /* Adjust downward, as appropriate */
  171060. ){
  171061. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  171062. /* p->iCoord might point to either a lower or upper bound coordinate
  171063. ** in a coordinate pair. But make pCellData point to the lower bound.
  171064. */
  171065. pCellData += 8 + 4*(p->iCoord&0xfe);
  171066. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  171067. || p->op==RTREE_GT || p->op==RTREE_EQ );
  171068. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  171069. switch( p->op ){
  171070. case RTREE_LE:
  171071. case RTREE_LT:
  171072. case RTREE_EQ:
  171073. RTREE_DECODE_COORD(eInt, pCellData, val);
  171074. /* val now holds the lower bound of the coordinate pair */
  171075. if( p->u.rValue>=val ) return;
  171076. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  171077. /* Fall through for the RTREE_EQ case */
  171078. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  171079. pCellData += 4;
  171080. RTREE_DECODE_COORD(eInt, pCellData, val);
  171081. /* val now holds the upper bound of the coordinate pair */
  171082. if( p->u.rValue<=val ) return;
  171083. }
  171084. *peWithin = NOT_WITHIN;
  171085. }
  171086. /*
  171087. ** Check the leaf RTree cell given by pCellData against constraint p.
  171088. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  171089. ** If the constraint is satisfied, leave *peWithin unchanged.
  171090. **
  171091. ** The constraint is of the form: xN op $val
  171092. **
  171093. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  171094. ** pCellData. $val is given by p->u.rValue.
  171095. */
  171096. static void rtreeLeafConstraint(
  171097. RtreeConstraint *p, /* The constraint to test */
  171098. int eInt, /* True if RTree holds integer coordinates */
  171099. u8 *pCellData, /* Raw cell content as appears on disk */
  171100. int *peWithin /* Adjust downward, as appropriate */
  171101. ){
  171102. RtreeDValue xN; /* Coordinate value converted to a double */
  171103. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  171104. || p->op==RTREE_GT || p->op==RTREE_EQ );
  171105. pCellData += 8 + p->iCoord*4;
  171106. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  171107. RTREE_DECODE_COORD(eInt, pCellData, xN);
  171108. switch( p->op ){
  171109. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  171110. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  171111. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  171112. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  171113. default: if( xN == p->u.rValue ) return; break;
  171114. }
  171115. *peWithin = NOT_WITHIN;
  171116. }
  171117. /*
  171118. ** One of the cells in node pNode is guaranteed to have a 64-bit
  171119. ** integer value equal to iRowid. Return the index of this cell.
  171120. */
  171121. static int nodeRowidIndex(
  171122. Rtree *pRtree,
  171123. RtreeNode *pNode,
  171124. i64 iRowid,
  171125. int *piIndex
  171126. ){
  171127. int ii;
  171128. int nCell = NCELL(pNode);
  171129. assert( nCell<200 );
  171130. for(ii=0; ii<nCell; ii++){
  171131. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  171132. *piIndex = ii;
  171133. return SQLITE_OK;
  171134. }
  171135. }
  171136. RTREE_IS_CORRUPT(pRtree);
  171137. return SQLITE_CORRUPT_VTAB;
  171138. }
  171139. /*
  171140. ** Return the index of the cell containing a pointer to node pNode
  171141. ** in its parent. If pNode is the root node, return -1.
  171142. */
  171143. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  171144. RtreeNode *pParent = pNode->pParent;
  171145. if( pParent ){
  171146. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  171147. }
  171148. *piIndex = -1;
  171149. return SQLITE_OK;
  171150. }
  171151. /*
  171152. ** Compare two search points. Return negative, zero, or positive if the first
  171153. ** is less than, equal to, or greater than the second.
  171154. **
  171155. ** The rScore is the primary key. Smaller rScore values come first.
  171156. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  171157. ** iLevel values coming first. In this way, if rScore is the same for all
  171158. ** SearchPoints, then iLevel becomes the deciding factor and the result
  171159. ** is a depth-first search, which is the desired default behavior.
  171160. */
  171161. static int rtreeSearchPointCompare(
  171162. const RtreeSearchPoint *pA,
  171163. const RtreeSearchPoint *pB
  171164. ){
  171165. if( pA->rScore<pB->rScore ) return -1;
  171166. if( pA->rScore>pB->rScore ) return +1;
  171167. if( pA->iLevel<pB->iLevel ) return -1;
  171168. if( pA->iLevel>pB->iLevel ) return +1;
  171169. return 0;
  171170. }
  171171. /*
  171172. ** Interchange two search points in a cursor.
  171173. */
  171174. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  171175. RtreeSearchPoint t = p->aPoint[i];
  171176. assert( i<j );
  171177. p->aPoint[i] = p->aPoint[j];
  171178. p->aPoint[j] = t;
  171179. i++; j++;
  171180. if( i<RTREE_CACHE_SZ ){
  171181. if( j>=RTREE_CACHE_SZ ){
  171182. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  171183. p->aNode[i] = 0;
  171184. }else{
  171185. RtreeNode *pTemp = p->aNode[i];
  171186. p->aNode[i] = p->aNode[j];
  171187. p->aNode[j] = pTemp;
  171188. }
  171189. }
  171190. }
  171191. /*
  171192. ** Return the search point with the lowest current score.
  171193. */
  171194. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  171195. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  171196. }
  171197. /*
  171198. ** Get the RtreeNode for the search point with the lowest score.
  171199. */
  171200. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  171201. sqlite3_int64 id;
  171202. int ii = 1 - pCur->bPoint;
  171203. assert( ii==0 || ii==1 );
  171204. assert( pCur->bPoint || pCur->nPoint );
  171205. if( pCur->aNode[ii]==0 ){
  171206. assert( pRC!=0 );
  171207. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  171208. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  171209. }
  171210. return pCur->aNode[ii];
  171211. }
  171212. /*
  171213. ** Push a new element onto the priority queue
  171214. */
  171215. static RtreeSearchPoint *rtreeEnqueue(
  171216. RtreeCursor *pCur, /* The cursor */
  171217. RtreeDValue rScore, /* Score for the new search point */
  171218. u8 iLevel /* Level for the new search point */
  171219. ){
  171220. int i, j;
  171221. RtreeSearchPoint *pNew;
  171222. if( pCur->nPoint>=pCur->nPointAlloc ){
  171223. int nNew = pCur->nPointAlloc*2 + 8;
  171224. pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  171225. if( pNew==0 ) return 0;
  171226. pCur->aPoint = pNew;
  171227. pCur->nPointAlloc = nNew;
  171228. }
  171229. i = pCur->nPoint++;
  171230. pNew = pCur->aPoint + i;
  171231. pNew->rScore = rScore;
  171232. pNew->iLevel = iLevel;
  171233. assert( iLevel<=RTREE_MAX_DEPTH );
  171234. while( i>0 ){
  171235. RtreeSearchPoint *pParent;
  171236. j = (i-1)/2;
  171237. pParent = pCur->aPoint + j;
  171238. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  171239. rtreeSearchPointSwap(pCur, j, i);
  171240. i = j;
  171241. pNew = pParent;
  171242. }
  171243. return pNew;
  171244. }
  171245. /*
  171246. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  171247. ** NULL if malloc fails.
  171248. */
  171249. static RtreeSearchPoint *rtreeSearchPointNew(
  171250. RtreeCursor *pCur, /* The cursor */
  171251. RtreeDValue rScore, /* Score for the new search point */
  171252. u8 iLevel /* Level for the new search point */
  171253. ){
  171254. RtreeSearchPoint *pNew, *pFirst;
  171255. pFirst = rtreeSearchPointFirst(pCur);
  171256. pCur->anQueue[iLevel]++;
  171257. if( pFirst==0
  171258. || pFirst->rScore>rScore
  171259. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  171260. ){
  171261. if( pCur->bPoint ){
  171262. int ii;
  171263. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  171264. if( pNew==0 ) return 0;
  171265. ii = (int)(pNew - pCur->aPoint) + 1;
  171266. if( ii<RTREE_CACHE_SZ ){
  171267. assert( pCur->aNode[ii]==0 );
  171268. pCur->aNode[ii] = pCur->aNode[0];
  171269. }else{
  171270. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  171271. }
  171272. pCur->aNode[0] = 0;
  171273. *pNew = pCur->sPoint;
  171274. }
  171275. pCur->sPoint.rScore = rScore;
  171276. pCur->sPoint.iLevel = iLevel;
  171277. pCur->bPoint = 1;
  171278. return &pCur->sPoint;
  171279. }else{
  171280. return rtreeEnqueue(pCur, rScore, iLevel);
  171281. }
  171282. }
  171283. #if 0
  171284. /* Tracing routines for the RtreeSearchPoint queue */
  171285. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  171286. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  171287. printf(" %d.%05lld.%02d %g %d",
  171288. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  171289. );
  171290. idx++;
  171291. if( idx<RTREE_CACHE_SZ ){
  171292. printf(" %p\n", pCur->aNode[idx]);
  171293. }else{
  171294. printf("\n");
  171295. }
  171296. }
  171297. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  171298. int ii;
  171299. printf("=== %9s ", zPrefix);
  171300. if( pCur->bPoint ){
  171301. tracePoint(&pCur->sPoint, -1, pCur);
  171302. }
  171303. for(ii=0; ii<pCur->nPoint; ii++){
  171304. if( ii>0 || pCur->bPoint ) printf(" ");
  171305. tracePoint(&pCur->aPoint[ii], ii, pCur);
  171306. }
  171307. }
  171308. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  171309. #else
  171310. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  171311. #endif
  171312. /* Remove the search point with the lowest current score.
  171313. */
  171314. static void rtreeSearchPointPop(RtreeCursor *p){
  171315. int i, j, k, n;
  171316. i = 1 - p->bPoint;
  171317. assert( i==0 || i==1 );
  171318. if( p->aNode[i] ){
  171319. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  171320. p->aNode[i] = 0;
  171321. }
  171322. if( p->bPoint ){
  171323. p->anQueue[p->sPoint.iLevel]--;
  171324. p->bPoint = 0;
  171325. }else if( p->nPoint ){
  171326. p->anQueue[p->aPoint[0].iLevel]--;
  171327. n = --p->nPoint;
  171328. p->aPoint[0] = p->aPoint[n];
  171329. if( n<RTREE_CACHE_SZ-1 ){
  171330. p->aNode[1] = p->aNode[n+1];
  171331. p->aNode[n+1] = 0;
  171332. }
  171333. i = 0;
  171334. while( (j = i*2+1)<n ){
  171335. k = j+1;
  171336. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  171337. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  171338. rtreeSearchPointSwap(p, i, k);
  171339. i = k;
  171340. }else{
  171341. break;
  171342. }
  171343. }else{
  171344. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  171345. rtreeSearchPointSwap(p, i, j);
  171346. i = j;
  171347. }else{
  171348. break;
  171349. }
  171350. }
  171351. }
  171352. }
  171353. }
  171354. /*
  171355. ** Continue the search on cursor pCur until the front of the queue
  171356. ** contains an entry suitable for returning as a result-set row,
  171357. ** or until the RtreeSearchPoint queue is empty, indicating that the
  171358. ** query has completed.
  171359. */
  171360. static int rtreeStepToLeaf(RtreeCursor *pCur){
  171361. RtreeSearchPoint *p;
  171362. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  171363. RtreeNode *pNode;
  171364. int eWithin;
  171365. int rc = SQLITE_OK;
  171366. int nCell;
  171367. int nConstraint = pCur->nConstraint;
  171368. int ii;
  171369. int eInt;
  171370. RtreeSearchPoint x;
  171371. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  171372. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  171373. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  171374. if( rc ) return rc;
  171375. nCell = NCELL(pNode);
  171376. assert( nCell<200 );
  171377. while( p->iCell<nCell ){
  171378. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  171379. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  171380. eWithin = FULLY_WITHIN;
  171381. for(ii=0; ii<nConstraint; ii++){
  171382. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  171383. if( pConstraint->op>=RTREE_MATCH ){
  171384. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  171385. &rScore, &eWithin);
  171386. if( rc ) return rc;
  171387. }else if( p->iLevel==1 ){
  171388. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  171389. }else{
  171390. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  171391. }
  171392. if( eWithin==NOT_WITHIN ) break;
  171393. }
  171394. p->iCell++;
  171395. if( eWithin==NOT_WITHIN ) continue;
  171396. x.iLevel = p->iLevel - 1;
  171397. if( x.iLevel ){
  171398. x.id = readInt64(pCellData);
  171399. x.iCell = 0;
  171400. }else{
  171401. x.id = p->id;
  171402. x.iCell = p->iCell - 1;
  171403. }
  171404. if( p->iCell>=nCell ){
  171405. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  171406. rtreeSearchPointPop(pCur);
  171407. }
  171408. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  171409. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  171410. if( p==0 ) return SQLITE_NOMEM;
  171411. p->eWithin = (u8)eWithin;
  171412. p->id = x.id;
  171413. p->iCell = x.iCell;
  171414. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  171415. break;
  171416. }
  171417. if( p->iCell>=nCell ){
  171418. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  171419. rtreeSearchPointPop(pCur);
  171420. }
  171421. }
  171422. pCur->atEOF = p==0;
  171423. return SQLITE_OK;
  171424. }
  171425. /*
  171426. ** Rtree virtual table module xNext method.
  171427. */
  171428. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  171429. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  171430. int rc = SQLITE_OK;
  171431. /* Move to the next entry that matches the configured constraints. */
  171432. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  171433. if( pCsr->bAuxValid ){
  171434. pCsr->bAuxValid = 0;
  171435. sqlite3_reset(pCsr->pReadAux);
  171436. }
  171437. rtreeSearchPointPop(pCsr);
  171438. rc = rtreeStepToLeaf(pCsr);
  171439. return rc;
  171440. }
  171441. /*
  171442. ** Rtree virtual table module xRowid method.
  171443. */
  171444. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  171445. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  171446. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  171447. int rc = SQLITE_OK;
  171448. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  171449. if( rc==SQLITE_OK && p ){
  171450. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  171451. }
  171452. return rc;
  171453. }
  171454. /*
  171455. ** Rtree virtual table module xColumn method.
  171456. */
  171457. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  171458. Rtree *pRtree = (Rtree *)cur->pVtab;
  171459. RtreeCursor *pCsr = (RtreeCursor *)cur;
  171460. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  171461. RtreeCoord c;
  171462. int rc = SQLITE_OK;
  171463. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  171464. if( rc ) return rc;
  171465. if( p==0 ) return SQLITE_OK;
  171466. if( i==0 ){
  171467. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  171468. }else if( i<=pRtree->nDim2 ){
  171469. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  171470. #ifndef SQLITE_RTREE_INT_ONLY
  171471. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  171472. sqlite3_result_double(ctx, c.f);
  171473. }else
  171474. #endif
  171475. {
  171476. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  171477. sqlite3_result_int(ctx, c.i);
  171478. }
  171479. }else{
  171480. if( !pCsr->bAuxValid ){
  171481. if( pCsr->pReadAux==0 ){
  171482. rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
  171483. &pCsr->pReadAux, 0);
  171484. if( rc ) return rc;
  171485. }
  171486. sqlite3_bind_int64(pCsr->pReadAux, 1,
  171487. nodeGetRowid(pRtree, pNode, p->iCell));
  171488. rc = sqlite3_step(pCsr->pReadAux);
  171489. if( rc==SQLITE_ROW ){
  171490. pCsr->bAuxValid = 1;
  171491. }else{
  171492. sqlite3_reset(pCsr->pReadAux);
  171493. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  171494. return rc;
  171495. }
  171496. }
  171497. sqlite3_result_value(ctx,
  171498. sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
  171499. }
  171500. return SQLITE_OK;
  171501. }
  171502. /*
  171503. ** Use nodeAcquire() to obtain the leaf node containing the record with
  171504. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  171505. ** return SQLITE_OK. If there is no such record in the table, set
  171506. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  171507. ** to zero and return an SQLite error code.
  171508. */
  171509. static int findLeafNode(
  171510. Rtree *pRtree, /* RTree to search */
  171511. i64 iRowid, /* The rowid searching for */
  171512. RtreeNode **ppLeaf, /* Write the node here */
  171513. sqlite3_int64 *piNode /* Write the node-id here */
  171514. ){
  171515. int rc;
  171516. *ppLeaf = 0;
  171517. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  171518. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  171519. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  171520. if( piNode ) *piNode = iNode;
  171521. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  171522. sqlite3_reset(pRtree->pReadRowid);
  171523. }else{
  171524. rc = sqlite3_reset(pRtree->pReadRowid);
  171525. }
  171526. return rc;
  171527. }
  171528. /*
  171529. ** This function is called to configure the RtreeConstraint object passed
  171530. ** as the second argument for a MATCH constraint. The value passed as the
  171531. ** first argument to this function is the right-hand operand to the MATCH
  171532. ** operator.
  171533. */
  171534. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  171535. RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
  171536. sqlite3_rtree_query_info *pInfo; /* Callback information */
  171537. pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
  171538. if( pSrc==0 ) return SQLITE_ERROR;
  171539. pInfo = (sqlite3_rtree_query_info*)
  171540. sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
  171541. if( !pInfo ) return SQLITE_NOMEM;
  171542. memset(pInfo, 0, sizeof(*pInfo));
  171543. pBlob = (RtreeMatchArg*)&pInfo[1];
  171544. memcpy(pBlob, pSrc, pSrc->iSize);
  171545. pInfo->pContext = pBlob->cb.pContext;
  171546. pInfo->nParam = pBlob->nParam;
  171547. pInfo->aParam = pBlob->aParam;
  171548. pInfo->apSqlParam = pBlob->apSqlParam;
  171549. if( pBlob->cb.xGeom ){
  171550. pCons->u.xGeom = pBlob->cb.xGeom;
  171551. }else{
  171552. pCons->op = RTREE_QUERY;
  171553. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  171554. }
  171555. pCons->pInfo = pInfo;
  171556. return SQLITE_OK;
  171557. }
  171558. /*
  171559. ** Rtree virtual table module xFilter method.
  171560. */
  171561. static int rtreeFilter(
  171562. sqlite3_vtab_cursor *pVtabCursor,
  171563. int idxNum, const char *idxStr,
  171564. int argc, sqlite3_value **argv
  171565. ){
  171566. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  171567. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  171568. RtreeNode *pRoot = 0;
  171569. int ii;
  171570. int rc = SQLITE_OK;
  171571. int iCell = 0;
  171572. sqlite3_stmt *pStmt;
  171573. rtreeReference(pRtree);
  171574. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  171575. freeCursorConstraints(pCsr);
  171576. sqlite3_free(pCsr->aPoint);
  171577. pStmt = pCsr->pReadAux;
  171578. memset(pCsr, 0, sizeof(RtreeCursor));
  171579. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  171580. pCsr->pReadAux = pStmt;
  171581. pCsr->iStrategy = idxNum;
  171582. if( idxNum==1 ){
  171583. /* Special case - lookup by rowid. */
  171584. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  171585. RtreeSearchPoint *p; /* Search point for the leaf */
  171586. i64 iRowid = sqlite3_value_int64(argv[0]);
  171587. i64 iNode = 0;
  171588. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  171589. if( rc==SQLITE_OK && pLeaf!=0 ){
  171590. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  171591. assert( p!=0 ); /* Always returns pCsr->sPoint */
  171592. pCsr->aNode[0] = pLeaf;
  171593. p->id = iNode;
  171594. p->eWithin = PARTLY_WITHIN;
  171595. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  171596. p->iCell = (u8)iCell;
  171597. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  171598. }else{
  171599. pCsr->atEOF = 1;
  171600. }
  171601. }else{
  171602. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  171603. ** with the configured constraints.
  171604. */
  171605. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  171606. if( rc==SQLITE_OK && argc>0 ){
  171607. pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc);
  171608. pCsr->nConstraint = argc;
  171609. if( !pCsr->aConstraint ){
  171610. rc = SQLITE_NOMEM;
  171611. }else{
  171612. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  171613. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  171614. assert( (idxStr==0 && argc==0)
  171615. || (idxStr && (int)strlen(idxStr)==argc*2) );
  171616. for(ii=0; ii<argc; ii++){
  171617. RtreeConstraint *p = &pCsr->aConstraint[ii];
  171618. p->op = idxStr[ii*2];
  171619. p->iCoord = idxStr[ii*2+1]-'0';
  171620. if( p->op>=RTREE_MATCH ){
  171621. /* A MATCH operator. The right-hand-side must be a blob that
  171622. ** can be cast into an RtreeMatchArg object. One created using
  171623. ** an sqlite3_rtree_geometry_callback() SQL user function.
  171624. */
  171625. rc = deserializeGeometry(argv[ii], p);
  171626. if( rc!=SQLITE_OK ){
  171627. break;
  171628. }
  171629. p->pInfo->nCoord = pRtree->nDim2;
  171630. p->pInfo->anQueue = pCsr->anQueue;
  171631. p->pInfo->mxLevel = pRtree->iDepth + 1;
  171632. }else{
  171633. #ifdef SQLITE_RTREE_INT_ONLY
  171634. p->u.rValue = sqlite3_value_int64(argv[ii]);
  171635. #else
  171636. p->u.rValue = sqlite3_value_double(argv[ii]);
  171637. #endif
  171638. }
  171639. }
  171640. }
  171641. }
  171642. if( rc==SQLITE_OK ){
  171643. RtreeSearchPoint *pNew;
  171644. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  171645. if( pNew==0 ) return SQLITE_NOMEM;
  171646. pNew->id = 1;
  171647. pNew->iCell = 0;
  171648. pNew->eWithin = PARTLY_WITHIN;
  171649. assert( pCsr->bPoint==1 );
  171650. pCsr->aNode[0] = pRoot;
  171651. pRoot = 0;
  171652. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  171653. rc = rtreeStepToLeaf(pCsr);
  171654. }
  171655. }
  171656. nodeRelease(pRtree, pRoot);
  171657. rtreeRelease(pRtree);
  171658. return rc;
  171659. }
  171660. /*
  171661. ** Rtree virtual table module xBestIndex method. There are three
  171662. ** table scan strategies to choose from (in order from most to
  171663. ** least desirable):
  171664. **
  171665. ** idxNum idxStr Strategy
  171666. ** ------------------------------------------------
  171667. ** 1 Unused Direct lookup by rowid.
  171668. ** 2 See below R-tree query or full-table scan.
  171669. ** ------------------------------------------------
  171670. **
  171671. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  171672. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  171673. ** constraint used. The first two bytes of idxStr correspond to
  171674. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  171675. ** (argvIndex==1) etc.
  171676. **
  171677. ** The first of each pair of bytes in idxStr identifies the constraint
  171678. ** operator as follows:
  171679. **
  171680. ** Operator Byte Value
  171681. ** ----------------------
  171682. ** = 0x41 ('A')
  171683. ** <= 0x42 ('B')
  171684. ** < 0x43 ('C')
  171685. ** >= 0x44 ('D')
  171686. ** > 0x45 ('E')
  171687. ** MATCH 0x46 ('F')
  171688. ** ----------------------
  171689. **
  171690. ** The second of each pair of bytes identifies the coordinate column
  171691. ** to which the constraint applies. The leftmost coordinate column
  171692. ** is 'a', the second from the left 'b' etc.
  171693. */
  171694. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  171695. Rtree *pRtree = (Rtree*)tab;
  171696. int rc = SQLITE_OK;
  171697. int ii;
  171698. int bMatch = 0; /* True if there exists a MATCH constraint */
  171699. i64 nRow; /* Estimated rows returned by this scan */
  171700. int iIdx = 0;
  171701. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  171702. memset(zIdxStr, 0, sizeof(zIdxStr));
  171703. /* Check if there exists a MATCH constraint - even an unusable one. If there
  171704. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  171705. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  171706. ** possible. */
  171707. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  171708. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  171709. bMatch = 1;
  171710. }
  171711. }
  171712. assert( pIdxInfo->idxStr==0 );
  171713. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  171714. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  171715. if( bMatch==0 && p->usable
  171716. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  171717. ){
  171718. /* We have an equality constraint on the rowid. Use strategy 1. */
  171719. int jj;
  171720. for(jj=0; jj<ii; jj++){
  171721. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  171722. pIdxInfo->aConstraintUsage[jj].omit = 0;
  171723. }
  171724. pIdxInfo->idxNum = 1;
  171725. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  171726. pIdxInfo->aConstraintUsage[jj].omit = 1;
  171727. /* This strategy involves a two rowid lookups on an B-Tree structures
  171728. ** and then a linear search of an R-Tree node. This should be
  171729. ** considered almost as quick as a direct rowid lookup (for which
  171730. ** sqlite uses an internal cost of 0.0). It is expected to return
  171731. ** a single row.
  171732. */
  171733. pIdxInfo->estimatedCost = 30.0;
  171734. pIdxInfo->estimatedRows = 1;
  171735. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  171736. return SQLITE_OK;
  171737. }
  171738. if( p->usable
  171739. && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
  171740. || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
  171741. ){
  171742. u8 op;
  171743. switch( p->op ){
  171744. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  171745. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  171746. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  171747. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  171748. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  171749. case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break;
  171750. default: op = 0; break;
  171751. }
  171752. if( op ){
  171753. zIdxStr[iIdx++] = op;
  171754. zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
  171755. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  171756. pIdxInfo->aConstraintUsage[ii].omit = 1;
  171757. }
  171758. }
  171759. }
  171760. pIdxInfo->idxNum = 2;
  171761. pIdxInfo->needToFreeIdxStr = 1;
  171762. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  171763. return SQLITE_NOMEM;
  171764. }
  171765. nRow = pRtree->nRowEst >> (iIdx/2);
  171766. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  171767. pIdxInfo->estimatedRows = nRow;
  171768. return rc;
  171769. }
  171770. /*
  171771. ** Return the N-dimensional volumn of the cell stored in *p.
  171772. */
  171773. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  171774. RtreeDValue area = (RtreeDValue)1;
  171775. assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
  171776. #ifndef SQLITE_RTREE_INT_ONLY
  171777. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  171778. switch( pRtree->nDim ){
  171779. case 5: area = p->aCoord[9].f - p->aCoord[8].f;
  171780. case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
  171781. case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
  171782. case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
  171783. default: area *= p->aCoord[1].f - p->aCoord[0].f;
  171784. }
  171785. }else
  171786. #endif
  171787. {
  171788. switch( pRtree->nDim ){
  171789. case 5: area = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i;
  171790. case 4: area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i;
  171791. case 3: area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i;
  171792. case 2: area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i;
  171793. default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i;
  171794. }
  171795. }
  171796. return area;
  171797. }
  171798. /*
  171799. ** Return the margin length of cell p. The margin length is the sum
  171800. ** of the objects size in each dimension.
  171801. */
  171802. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  171803. RtreeDValue margin = 0;
  171804. int ii = pRtree->nDim2 - 2;
  171805. do{
  171806. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  171807. ii -= 2;
  171808. }while( ii>=0 );
  171809. return margin;
  171810. }
  171811. /*
  171812. ** Store the union of cells p1 and p2 in p1.
  171813. */
  171814. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  171815. int ii = 0;
  171816. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  171817. do{
  171818. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  171819. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  171820. ii += 2;
  171821. }while( ii<pRtree->nDim2 );
  171822. }else{
  171823. do{
  171824. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  171825. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  171826. ii += 2;
  171827. }while( ii<pRtree->nDim2 );
  171828. }
  171829. }
  171830. /*
  171831. ** Return true if the area covered by p2 is a subset of the area covered
  171832. ** by p1. False otherwise.
  171833. */
  171834. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  171835. int ii;
  171836. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  171837. for(ii=0; ii<pRtree->nDim2; ii+=2){
  171838. RtreeCoord *a1 = &p1->aCoord[ii];
  171839. RtreeCoord *a2 = &p2->aCoord[ii];
  171840. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  171841. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  171842. ){
  171843. return 0;
  171844. }
  171845. }
  171846. return 1;
  171847. }
  171848. /*
  171849. ** Return the amount cell p would grow by if it were unioned with pCell.
  171850. */
  171851. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  171852. RtreeDValue area;
  171853. RtreeCell cell;
  171854. memcpy(&cell, p, sizeof(RtreeCell));
  171855. area = cellArea(pRtree, &cell);
  171856. cellUnion(pRtree, &cell, pCell);
  171857. return (cellArea(pRtree, &cell)-area);
  171858. }
  171859. static RtreeDValue cellOverlap(
  171860. Rtree *pRtree,
  171861. RtreeCell *p,
  171862. RtreeCell *aCell,
  171863. int nCell
  171864. ){
  171865. int ii;
  171866. RtreeDValue overlap = RTREE_ZERO;
  171867. for(ii=0; ii<nCell; ii++){
  171868. int jj;
  171869. RtreeDValue o = (RtreeDValue)1;
  171870. for(jj=0; jj<pRtree->nDim2; jj+=2){
  171871. RtreeDValue x1, x2;
  171872. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  171873. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  171874. if( x2<x1 ){
  171875. o = (RtreeDValue)0;
  171876. break;
  171877. }else{
  171878. o = o * (x2-x1);
  171879. }
  171880. }
  171881. overlap += o;
  171882. }
  171883. return overlap;
  171884. }
  171885. /*
  171886. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  171887. ** ChooseSubTree in r*tree terminology.
  171888. */
  171889. static int ChooseLeaf(
  171890. Rtree *pRtree, /* Rtree table */
  171891. RtreeCell *pCell, /* Cell to insert into rtree */
  171892. int iHeight, /* Height of sub-tree rooted at pCell */
  171893. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  171894. ){
  171895. int rc;
  171896. int ii;
  171897. RtreeNode *pNode = 0;
  171898. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  171899. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  171900. int iCell;
  171901. sqlite3_int64 iBest = 0;
  171902. RtreeDValue fMinGrowth = RTREE_ZERO;
  171903. RtreeDValue fMinArea = RTREE_ZERO;
  171904. int nCell = NCELL(pNode);
  171905. RtreeCell cell;
  171906. RtreeNode *pChild;
  171907. RtreeCell *aCell = 0;
  171908. /* Select the child node which will be enlarged the least if pCell
  171909. ** is inserted into it. Resolve ties by choosing the entry with
  171910. ** the smallest area.
  171911. */
  171912. for(iCell=0; iCell<nCell; iCell++){
  171913. int bBest = 0;
  171914. RtreeDValue growth;
  171915. RtreeDValue area;
  171916. nodeGetCell(pRtree, pNode, iCell, &cell);
  171917. growth = cellGrowth(pRtree, &cell, pCell);
  171918. area = cellArea(pRtree, &cell);
  171919. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  171920. bBest = 1;
  171921. }
  171922. if( bBest ){
  171923. fMinGrowth = growth;
  171924. fMinArea = area;
  171925. iBest = cell.iRowid;
  171926. }
  171927. }
  171928. sqlite3_free(aCell);
  171929. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  171930. nodeRelease(pRtree, pNode);
  171931. pNode = pChild;
  171932. }
  171933. *ppLeaf = pNode;
  171934. return rc;
  171935. }
  171936. /*
  171937. ** A cell with the same content as pCell has just been inserted into
  171938. ** the node pNode. This function updates the bounding box cells in
  171939. ** all ancestor elements.
  171940. */
  171941. static int AdjustTree(
  171942. Rtree *pRtree, /* Rtree table */
  171943. RtreeNode *pNode, /* Adjust ancestry of this node. */
  171944. RtreeCell *pCell /* This cell was just inserted */
  171945. ){
  171946. RtreeNode *p = pNode;
  171947. int cnt = 0;
  171948. while( p->pParent ){
  171949. RtreeNode *pParent = p->pParent;
  171950. RtreeCell cell;
  171951. int iCell;
  171952. if( (++cnt)>1000 || nodeParentIndex(pRtree, p, &iCell) ){
  171953. RTREE_IS_CORRUPT(pRtree);
  171954. return SQLITE_CORRUPT_VTAB;
  171955. }
  171956. nodeGetCell(pRtree, pParent, iCell, &cell);
  171957. if( !cellContains(pRtree, &cell, pCell) ){
  171958. cellUnion(pRtree, &cell, pCell);
  171959. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  171960. }
  171961. p = pParent;
  171962. }
  171963. return SQLITE_OK;
  171964. }
  171965. /*
  171966. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  171967. */
  171968. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  171969. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  171970. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  171971. sqlite3_step(pRtree->pWriteRowid);
  171972. return sqlite3_reset(pRtree->pWriteRowid);
  171973. }
  171974. /*
  171975. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  171976. */
  171977. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  171978. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  171979. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  171980. sqlite3_step(pRtree->pWriteParent);
  171981. return sqlite3_reset(pRtree->pWriteParent);
  171982. }
  171983. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  171984. /*
  171985. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  171986. ** nIdx. The aIdx array contains the set of integers from 0 to
  171987. ** (nIdx-1) in no particular order. This function sorts the values
  171988. ** in aIdx according to the indexed values in aDistance. For
  171989. ** example, assuming the inputs:
  171990. **
  171991. ** aIdx = { 0, 1, 2, 3 }
  171992. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  171993. **
  171994. ** this function sets the aIdx array to contain:
  171995. **
  171996. ** aIdx = { 0, 1, 2, 3 }
  171997. **
  171998. ** The aSpare array is used as temporary working space by the
  171999. ** sorting algorithm.
  172000. */
  172001. static void SortByDistance(
  172002. int *aIdx,
  172003. int nIdx,
  172004. RtreeDValue *aDistance,
  172005. int *aSpare
  172006. ){
  172007. if( nIdx>1 ){
  172008. int iLeft = 0;
  172009. int iRight = 0;
  172010. int nLeft = nIdx/2;
  172011. int nRight = nIdx-nLeft;
  172012. int *aLeft = aIdx;
  172013. int *aRight = &aIdx[nLeft];
  172014. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  172015. SortByDistance(aRight, nRight, aDistance, aSpare);
  172016. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  172017. aLeft = aSpare;
  172018. while( iLeft<nLeft || iRight<nRight ){
  172019. if( iLeft==nLeft ){
  172020. aIdx[iLeft+iRight] = aRight[iRight];
  172021. iRight++;
  172022. }else if( iRight==nRight ){
  172023. aIdx[iLeft+iRight] = aLeft[iLeft];
  172024. iLeft++;
  172025. }else{
  172026. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  172027. RtreeDValue fRight = aDistance[aRight[iRight]];
  172028. if( fLeft<fRight ){
  172029. aIdx[iLeft+iRight] = aLeft[iLeft];
  172030. iLeft++;
  172031. }else{
  172032. aIdx[iLeft+iRight] = aRight[iRight];
  172033. iRight++;
  172034. }
  172035. }
  172036. }
  172037. #if 0
  172038. /* Check that the sort worked */
  172039. {
  172040. int jj;
  172041. for(jj=1; jj<nIdx; jj++){
  172042. RtreeDValue left = aDistance[aIdx[jj-1]];
  172043. RtreeDValue right = aDistance[aIdx[jj]];
  172044. assert( left<=right );
  172045. }
  172046. }
  172047. #endif
  172048. }
  172049. }
  172050. /*
  172051. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  172052. ** nIdx. The aIdx array contains the set of integers from 0 to
  172053. ** (nIdx-1) in no particular order. This function sorts the values
  172054. ** in aIdx according to dimension iDim of the cells in aCell. The
  172055. ** minimum value of dimension iDim is considered first, the
  172056. ** maximum used to break ties.
  172057. **
  172058. ** The aSpare array is used as temporary working space by the
  172059. ** sorting algorithm.
  172060. */
  172061. static void SortByDimension(
  172062. Rtree *pRtree,
  172063. int *aIdx,
  172064. int nIdx,
  172065. int iDim,
  172066. RtreeCell *aCell,
  172067. int *aSpare
  172068. ){
  172069. if( nIdx>1 ){
  172070. int iLeft = 0;
  172071. int iRight = 0;
  172072. int nLeft = nIdx/2;
  172073. int nRight = nIdx-nLeft;
  172074. int *aLeft = aIdx;
  172075. int *aRight = &aIdx[nLeft];
  172076. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  172077. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  172078. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  172079. aLeft = aSpare;
  172080. while( iLeft<nLeft || iRight<nRight ){
  172081. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  172082. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  172083. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  172084. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  172085. if( (iLeft!=nLeft) && ((iRight==nRight)
  172086. || (xleft1<xright1)
  172087. || (xleft1==xright1 && xleft2<xright2)
  172088. )){
  172089. aIdx[iLeft+iRight] = aLeft[iLeft];
  172090. iLeft++;
  172091. }else{
  172092. aIdx[iLeft+iRight] = aRight[iRight];
  172093. iRight++;
  172094. }
  172095. }
  172096. #if 0
  172097. /* Check that the sort worked */
  172098. {
  172099. int jj;
  172100. for(jj=1; jj<nIdx; jj++){
  172101. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  172102. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  172103. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  172104. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  172105. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  172106. }
  172107. }
  172108. #endif
  172109. }
  172110. }
  172111. /*
  172112. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  172113. */
  172114. static int splitNodeStartree(
  172115. Rtree *pRtree,
  172116. RtreeCell *aCell,
  172117. int nCell,
  172118. RtreeNode *pLeft,
  172119. RtreeNode *pRight,
  172120. RtreeCell *pBboxLeft,
  172121. RtreeCell *pBboxRight
  172122. ){
  172123. int **aaSorted;
  172124. int *aSpare;
  172125. int ii;
  172126. int iBestDim = 0;
  172127. int iBestSplit = 0;
  172128. RtreeDValue fBestMargin = RTREE_ZERO;
  172129. sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  172130. aaSorted = (int **)sqlite3_malloc64(nByte);
  172131. if( !aaSorted ){
  172132. return SQLITE_NOMEM;
  172133. }
  172134. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  172135. memset(aaSorted, 0, nByte);
  172136. for(ii=0; ii<pRtree->nDim; ii++){
  172137. int jj;
  172138. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  172139. for(jj=0; jj<nCell; jj++){
  172140. aaSorted[ii][jj] = jj;
  172141. }
  172142. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  172143. }
  172144. for(ii=0; ii<pRtree->nDim; ii++){
  172145. RtreeDValue margin = RTREE_ZERO;
  172146. RtreeDValue fBestOverlap = RTREE_ZERO;
  172147. RtreeDValue fBestArea = RTREE_ZERO;
  172148. int iBestLeft = 0;
  172149. int nLeft;
  172150. for(
  172151. nLeft=RTREE_MINCELLS(pRtree);
  172152. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  172153. nLeft++
  172154. ){
  172155. RtreeCell left;
  172156. RtreeCell right;
  172157. int kk;
  172158. RtreeDValue overlap;
  172159. RtreeDValue area;
  172160. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  172161. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  172162. for(kk=1; kk<(nCell-1); kk++){
  172163. if( kk<nLeft ){
  172164. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  172165. }else{
  172166. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  172167. }
  172168. }
  172169. margin += cellMargin(pRtree, &left);
  172170. margin += cellMargin(pRtree, &right);
  172171. overlap = cellOverlap(pRtree, &left, &right, 1);
  172172. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  172173. if( (nLeft==RTREE_MINCELLS(pRtree))
  172174. || (overlap<fBestOverlap)
  172175. || (overlap==fBestOverlap && area<fBestArea)
  172176. ){
  172177. iBestLeft = nLeft;
  172178. fBestOverlap = overlap;
  172179. fBestArea = area;
  172180. }
  172181. }
  172182. if( ii==0 || margin<fBestMargin ){
  172183. iBestDim = ii;
  172184. fBestMargin = margin;
  172185. iBestSplit = iBestLeft;
  172186. }
  172187. }
  172188. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  172189. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  172190. for(ii=0; ii<nCell; ii++){
  172191. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  172192. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  172193. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  172194. nodeInsertCell(pRtree, pTarget, pCell);
  172195. cellUnion(pRtree, pBbox, pCell);
  172196. }
  172197. sqlite3_free(aaSorted);
  172198. return SQLITE_OK;
  172199. }
  172200. static int updateMapping(
  172201. Rtree *pRtree,
  172202. i64 iRowid,
  172203. RtreeNode *pNode,
  172204. int iHeight
  172205. ){
  172206. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  172207. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  172208. if( iHeight>0 ){
  172209. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  172210. if( pChild ){
  172211. nodeRelease(pRtree, pChild->pParent);
  172212. nodeReference(pNode);
  172213. pChild->pParent = pNode;
  172214. }
  172215. }
  172216. return xSetMapping(pRtree, iRowid, pNode->iNode);
  172217. }
  172218. static int SplitNode(
  172219. Rtree *pRtree,
  172220. RtreeNode *pNode,
  172221. RtreeCell *pCell,
  172222. int iHeight
  172223. ){
  172224. int i;
  172225. int newCellIsRight = 0;
  172226. int rc = SQLITE_OK;
  172227. int nCell = NCELL(pNode);
  172228. RtreeCell *aCell;
  172229. int *aiUsed;
  172230. RtreeNode *pLeft = 0;
  172231. RtreeNode *pRight = 0;
  172232. RtreeCell leftbbox;
  172233. RtreeCell rightbbox;
  172234. /* Allocate an array and populate it with a copy of pCell and
  172235. ** all cells from node pLeft. Then zero the original node.
  172236. */
  172237. aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  172238. if( !aCell ){
  172239. rc = SQLITE_NOMEM;
  172240. goto splitnode_out;
  172241. }
  172242. aiUsed = (int *)&aCell[nCell+1];
  172243. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  172244. for(i=0; i<nCell; i++){
  172245. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  172246. }
  172247. nodeZero(pRtree, pNode);
  172248. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  172249. nCell++;
  172250. if( pNode->iNode==1 ){
  172251. pRight = nodeNew(pRtree, pNode);
  172252. pLeft = nodeNew(pRtree, pNode);
  172253. pRtree->iDepth++;
  172254. pNode->isDirty = 1;
  172255. writeInt16(pNode->zData, pRtree->iDepth);
  172256. }else{
  172257. pLeft = pNode;
  172258. pRight = nodeNew(pRtree, pLeft->pParent);
  172259. pLeft->nRef++;
  172260. }
  172261. if( !pLeft || !pRight ){
  172262. rc = SQLITE_NOMEM;
  172263. goto splitnode_out;
  172264. }
  172265. memset(pLeft->zData, 0, pRtree->iNodeSize);
  172266. memset(pRight->zData, 0, pRtree->iNodeSize);
  172267. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  172268. &leftbbox, &rightbbox);
  172269. if( rc!=SQLITE_OK ){
  172270. goto splitnode_out;
  172271. }
  172272. /* Ensure both child nodes have node numbers assigned to them by calling
  172273. ** nodeWrite(). Node pRight always needs a node number, as it was created
  172274. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  172275. ** In this case avoid the all to nodeWrite().
  172276. */
  172277. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  172278. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  172279. ){
  172280. goto splitnode_out;
  172281. }
  172282. rightbbox.iRowid = pRight->iNode;
  172283. leftbbox.iRowid = pLeft->iNode;
  172284. if( pNode->iNode==1 ){
  172285. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  172286. if( rc!=SQLITE_OK ){
  172287. goto splitnode_out;
  172288. }
  172289. }else{
  172290. RtreeNode *pParent = pLeft->pParent;
  172291. int iCell;
  172292. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  172293. if( rc==SQLITE_OK ){
  172294. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  172295. rc = AdjustTree(pRtree, pParent, &leftbbox);
  172296. }
  172297. if( rc!=SQLITE_OK ){
  172298. goto splitnode_out;
  172299. }
  172300. }
  172301. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  172302. goto splitnode_out;
  172303. }
  172304. for(i=0; i<NCELL(pRight); i++){
  172305. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  172306. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  172307. if( iRowid==pCell->iRowid ){
  172308. newCellIsRight = 1;
  172309. }
  172310. if( rc!=SQLITE_OK ){
  172311. goto splitnode_out;
  172312. }
  172313. }
  172314. if( pNode->iNode==1 ){
  172315. for(i=0; i<NCELL(pLeft); i++){
  172316. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  172317. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  172318. if( rc!=SQLITE_OK ){
  172319. goto splitnode_out;
  172320. }
  172321. }
  172322. }else if( newCellIsRight==0 ){
  172323. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  172324. }
  172325. if( rc==SQLITE_OK ){
  172326. rc = nodeRelease(pRtree, pRight);
  172327. pRight = 0;
  172328. }
  172329. if( rc==SQLITE_OK ){
  172330. rc = nodeRelease(pRtree, pLeft);
  172331. pLeft = 0;
  172332. }
  172333. splitnode_out:
  172334. nodeRelease(pRtree, pRight);
  172335. nodeRelease(pRtree, pLeft);
  172336. sqlite3_free(aCell);
  172337. return rc;
  172338. }
  172339. /*
  172340. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  172341. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  172342. ** the pLeaf->pParent chain all the way up to the root node.
  172343. **
  172344. ** This operation is required when a row is deleted (or updated - an update
  172345. ** is implemented as a delete followed by an insert). SQLite provides the
  172346. ** rowid of the row to delete, which can be used to find the leaf on which
  172347. ** the entry resides (argument pLeaf). Once the leaf is located, this
  172348. ** function is called to determine its ancestry.
  172349. */
  172350. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  172351. int rc = SQLITE_OK;
  172352. RtreeNode *pChild = pLeaf;
  172353. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  172354. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  172355. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  172356. rc = sqlite3_step(pRtree->pReadParent);
  172357. if( rc==SQLITE_ROW ){
  172358. RtreeNode *pTest; /* Used to test for reference loops */
  172359. i64 iNode; /* Node number of parent node */
  172360. /* Before setting pChild->pParent, test that we are not creating a
  172361. ** loop of references (as we would if, say, pChild==pParent). We don't
  172362. ** want to do this as it leads to a memory leak when trying to delete
  172363. ** the referenced counted node structures.
  172364. */
  172365. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  172366. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  172367. if( !pTest ){
  172368. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  172369. }
  172370. }
  172371. rc = sqlite3_reset(pRtree->pReadParent);
  172372. if( rc==SQLITE_OK ) rc = rc2;
  172373. if( rc==SQLITE_OK && !pChild->pParent ){
  172374. RTREE_IS_CORRUPT(pRtree);
  172375. rc = SQLITE_CORRUPT_VTAB;
  172376. }
  172377. pChild = pChild->pParent;
  172378. }
  172379. return rc;
  172380. }
  172381. static int deleteCell(Rtree *, RtreeNode *, int, int);
  172382. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  172383. int rc;
  172384. int rc2;
  172385. RtreeNode *pParent = 0;
  172386. int iCell;
  172387. assert( pNode->nRef==1 );
  172388. /* Remove the entry in the parent cell. */
  172389. rc = nodeParentIndex(pRtree, pNode, &iCell);
  172390. if( rc==SQLITE_OK ){
  172391. pParent = pNode->pParent;
  172392. pNode->pParent = 0;
  172393. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  172394. }
  172395. rc2 = nodeRelease(pRtree, pParent);
  172396. if( rc==SQLITE_OK ){
  172397. rc = rc2;
  172398. }
  172399. if( rc!=SQLITE_OK ){
  172400. return rc;
  172401. }
  172402. /* Remove the xxx_node entry. */
  172403. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  172404. sqlite3_step(pRtree->pDeleteNode);
  172405. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  172406. return rc;
  172407. }
  172408. /* Remove the xxx_parent entry. */
  172409. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  172410. sqlite3_step(pRtree->pDeleteParent);
  172411. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  172412. return rc;
  172413. }
  172414. /* Remove the node from the in-memory hash table and link it into
  172415. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  172416. */
  172417. nodeHashDelete(pRtree, pNode);
  172418. pNode->iNode = iHeight;
  172419. pNode->pNext = pRtree->pDeleted;
  172420. pNode->nRef++;
  172421. pRtree->pDeleted = pNode;
  172422. return SQLITE_OK;
  172423. }
  172424. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  172425. RtreeNode *pParent = pNode->pParent;
  172426. int rc = SQLITE_OK;
  172427. if( pParent ){
  172428. int ii;
  172429. int nCell = NCELL(pNode);
  172430. RtreeCell box; /* Bounding box for pNode */
  172431. nodeGetCell(pRtree, pNode, 0, &box);
  172432. for(ii=1; ii<nCell; ii++){
  172433. RtreeCell cell;
  172434. nodeGetCell(pRtree, pNode, ii, &cell);
  172435. cellUnion(pRtree, &box, &cell);
  172436. }
  172437. box.iRowid = pNode->iNode;
  172438. rc = nodeParentIndex(pRtree, pNode, &ii);
  172439. if( rc==SQLITE_OK ){
  172440. nodeOverwriteCell(pRtree, pParent, &box, ii);
  172441. rc = fixBoundingBox(pRtree, pParent);
  172442. }
  172443. }
  172444. return rc;
  172445. }
  172446. /*
  172447. ** Delete the cell at index iCell of node pNode. After removing the
  172448. ** cell, adjust the r-tree data structure if required.
  172449. */
  172450. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  172451. RtreeNode *pParent;
  172452. int rc;
  172453. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  172454. return rc;
  172455. }
  172456. /* Remove the cell from the node. This call just moves bytes around
  172457. ** the in-memory node image, so it cannot fail.
  172458. */
  172459. nodeDeleteCell(pRtree, pNode, iCell);
  172460. /* If the node is not the tree root and now has less than the minimum
  172461. ** number of cells, remove it from the tree. Otherwise, update the
  172462. ** cell in the parent node so that it tightly contains the updated
  172463. ** node.
  172464. */
  172465. pParent = pNode->pParent;
  172466. assert( pParent || pNode->iNode==1 );
  172467. if( pParent ){
  172468. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  172469. rc = removeNode(pRtree, pNode, iHeight);
  172470. }else{
  172471. rc = fixBoundingBox(pRtree, pNode);
  172472. }
  172473. }
  172474. return rc;
  172475. }
  172476. static int Reinsert(
  172477. Rtree *pRtree,
  172478. RtreeNode *pNode,
  172479. RtreeCell *pCell,
  172480. int iHeight
  172481. ){
  172482. int *aOrder;
  172483. int *aSpare;
  172484. RtreeCell *aCell;
  172485. RtreeDValue *aDistance;
  172486. int nCell;
  172487. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  172488. int iDim;
  172489. int ii;
  172490. int rc = SQLITE_OK;
  172491. int n;
  172492. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  172493. nCell = NCELL(pNode)+1;
  172494. n = (nCell+1)&(~1);
  172495. /* Allocate the buffers used by this operation. The allocation is
  172496. ** relinquished before this function returns.
  172497. */
  172498. aCell = (RtreeCell *)sqlite3_malloc64(n * (
  172499. sizeof(RtreeCell) + /* aCell array */
  172500. sizeof(int) + /* aOrder array */
  172501. sizeof(int) + /* aSpare array */
  172502. sizeof(RtreeDValue) /* aDistance array */
  172503. ));
  172504. if( !aCell ){
  172505. return SQLITE_NOMEM;
  172506. }
  172507. aOrder = (int *)&aCell[n];
  172508. aSpare = (int *)&aOrder[n];
  172509. aDistance = (RtreeDValue *)&aSpare[n];
  172510. for(ii=0; ii<nCell; ii++){
  172511. if( ii==(nCell-1) ){
  172512. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  172513. }else{
  172514. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  172515. }
  172516. aOrder[ii] = ii;
  172517. for(iDim=0; iDim<pRtree->nDim; iDim++){
  172518. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  172519. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  172520. }
  172521. }
  172522. for(iDim=0; iDim<pRtree->nDim; iDim++){
  172523. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  172524. }
  172525. for(ii=0; ii<nCell; ii++){
  172526. aDistance[ii] = RTREE_ZERO;
  172527. for(iDim=0; iDim<pRtree->nDim; iDim++){
  172528. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  172529. DCOORD(aCell[ii].aCoord[iDim*2]));
  172530. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  172531. }
  172532. }
  172533. SortByDistance(aOrder, nCell, aDistance, aSpare);
  172534. nodeZero(pRtree, pNode);
  172535. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  172536. RtreeCell *p = &aCell[aOrder[ii]];
  172537. nodeInsertCell(pRtree, pNode, p);
  172538. if( p->iRowid==pCell->iRowid ){
  172539. if( iHeight==0 ){
  172540. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  172541. }else{
  172542. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  172543. }
  172544. }
  172545. }
  172546. if( rc==SQLITE_OK ){
  172547. rc = fixBoundingBox(pRtree, pNode);
  172548. }
  172549. for(; rc==SQLITE_OK && ii<nCell; ii++){
  172550. /* Find a node to store this cell in. pNode->iNode currently contains
  172551. ** the height of the sub-tree headed by the cell.
  172552. */
  172553. RtreeNode *pInsert;
  172554. RtreeCell *p = &aCell[aOrder[ii]];
  172555. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  172556. if( rc==SQLITE_OK ){
  172557. int rc2;
  172558. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  172559. rc2 = nodeRelease(pRtree, pInsert);
  172560. if( rc==SQLITE_OK ){
  172561. rc = rc2;
  172562. }
  172563. }
  172564. }
  172565. sqlite3_free(aCell);
  172566. return rc;
  172567. }
  172568. /*
  172569. ** Insert cell pCell into node pNode. Node pNode is the head of a
  172570. ** subtree iHeight high (leaf nodes have iHeight==0).
  172571. */
  172572. static int rtreeInsertCell(
  172573. Rtree *pRtree,
  172574. RtreeNode *pNode,
  172575. RtreeCell *pCell,
  172576. int iHeight
  172577. ){
  172578. int rc = SQLITE_OK;
  172579. if( iHeight>0 ){
  172580. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  172581. if( pChild ){
  172582. nodeRelease(pRtree, pChild->pParent);
  172583. nodeReference(pNode);
  172584. pChild->pParent = pNode;
  172585. }
  172586. }
  172587. if( nodeInsertCell(pRtree, pNode, pCell) ){
  172588. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  172589. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  172590. }else{
  172591. pRtree->iReinsertHeight = iHeight;
  172592. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  172593. }
  172594. }else{
  172595. rc = AdjustTree(pRtree, pNode, pCell);
  172596. if( rc==SQLITE_OK ){
  172597. if( iHeight==0 ){
  172598. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  172599. }else{
  172600. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  172601. }
  172602. }
  172603. }
  172604. return rc;
  172605. }
  172606. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  172607. int ii;
  172608. int rc = SQLITE_OK;
  172609. int nCell = NCELL(pNode);
  172610. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  172611. RtreeNode *pInsert;
  172612. RtreeCell cell;
  172613. nodeGetCell(pRtree, pNode, ii, &cell);
  172614. /* Find a node to store this cell in. pNode->iNode currently contains
  172615. ** the height of the sub-tree headed by the cell.
  172616. */
  172617. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  172618. if( rc==SQLITE_OK ){
  172619. int rc2;
  172620. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  172621. rc2 = nodeRelease(pRtree, pInsert);
  172622. if( rc==SQLITE_OK ){
  172623. rc = rc2;
  172624. }
  172625. }
  172626. }
  172627. return rc;
  172628. }
  172629. /*
  172630. ** Select a currently unused rowid for a new r-tree record.
  172631. */
  172632. static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){
  172633. int rc;
  172634. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  172635. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  172636. sqlite3_step(pRtree->pWriteRowid);
  172637. rc = sqlite3_reset(pRtree->pWriteRowid);
  172638. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  172639. return rc;
  172640. }
  172641. /*
  172642. ** Remove the entry with rowid=iDelete from the r-tree structure.
  172643. */
  172644. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  172645. int rc; /* Return code */
  172646. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  172647. int iCell; /* Index of iDelete cell in pLeaf */
  172648. RtreeNode *pRoot = 0; /* Root node of rtree structure */
  172649. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  172650. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  172651. /* Obtain a reference to the leaf node that contains the entry
  172652. ** about to be deleted.
  172653. */
  172654. if( rc==SQLITE_OK ){
  172655. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  172656. }
  172657. #ifdef CORRUPT_DB
  172658. assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB );
  172659. #endif
  172660. /* Delete the cell in question from the leaf node. */
  172661. if( rc==SQLITE_OK && pLeaf ){
  172662. int rc2;
  172663. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  172664. if( rc==SQLITE_OK ){
  172665. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  172666. }
  172667. rc2 = nodeRelease(pRtree, pLeaf);
  172668. if( rc==SQLITE_OK ){
  172669. rc = rc2;
  172670. }
  172671. }
  172672. /* Delete the corresponding entry in the <rtree>_rowid table. */
  172673. if( rc==SQLITE_OK ){
  172674. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  172675. sqlite3_step(pRtree->pDeleteRowid);
  172676. rc = sqlite3_reset(pRtree->pDeleteRowid);
  172677. }
  172678. /* Check if the root node now has exactly one child. If so, remove
  172679. ** it, schedule the contents of the child for reinsertion and
  172680. ** reduce the tree height by one.
  172681. **
  172682. ** This is equivalent to copying the contents of the child into
  172683. ** the root node (the operation that Gutman's paper says to perform
  172684. ** in this scenario).
  172685. */
  172686. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  172687. int rc2;
  172688. RtreeNode *pChild = 0;
  172689. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  172690. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  172691. if( rc==SQLITE_OK ){
  172692. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  172693. }
  172694. rc2 = nodeRelease(pRtree, pChild);
  172695. if( rc==SQLITE_OK ) rc = rc2;
  172696. if( rc==SQLITE_OK ){
  172697. pRtree->iDepth--;
  172698. writeInt16(pRoot->zData, pRtree->iDepth);
  172699. pRoot->isDirty = 1;
  172700. }
  172701. }
  172702. /* Re-insert the contents of any underfull nodes removed from the tree. */
  172703. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  172704. if( rc==SQLITE_OK ){
  172705. rc = reinsertNodeContent(pRtree, pLeaf);
  172706. }
  172707. pRtree->pDeleted = pLeaf->pNext;
  172708. pRtree->nNodeRef--;
  172709. sqlite3_free(pLeaf);
  172710. }
  172711. /* Release the reference to the root node. */
  172712. if( rc==SQLITE_OK ){
  172713. rc = nodeRelease(pRtree, pRoot);
  172714. }else{
  172715. nodeRelease(pRtree, pRoot);
  172716. }
  172717. return rc;
  172718. }
  172719. /*
  172720. ** Rounding constants for float->double conversion.
  172721. */
  172722. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  172723. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  172724. #if !defined(SQLITE_RTREE_INT_ONLY)
  172725. /*
  172726. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  172727. ** while taking care to round toward negative or positive, respectively.
  172728. */
  172729. static RtreeValue rtreeValueDown(sqlite3_value *v){
  172730. double d = sqlite3_value_double(v);
  172731. float f = (float)d;
  172732. if( f>d ){
  172733. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  172734. }
  172735. return f;
  172736. }
  172737. static RtreeValue rtreeValueUp(sqlite3_value *v){
  172738. double d = sqlite3_value_double(v);
  172739. float f = (float)d;
  172740. if( f<d ){
  172741. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  172742. }
  172743. return f;
  172744. }
  172745. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  172746. /*
  172747. ** A constraint has failed while inserting a row into an rtree table.
  172748. ** Assuming no OOM error occurs, this function sets the error message
  172749. ** (at pRtree->base.zErrMsg) to an appropriate value and returns
  172750. ** SQLITE_CONSTRAINT.
  172751. **
  172752. ** Parameter iCol is the index of the leftmost column involved in the
  172753. ** constraint failure. If it is 0, then the constraint that failed is
  172754. ** the unique constraint on the id column. Otherwise, it is the rtree
  172755. ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
  172756. **
  172757. ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
  172758. */
  172759. static int rtreeConstraintError(Rtree *pRtree, int iCol){
  172760. sqlite3_stmt *pStmt = 0;
  172761. char *zSql;
  172762. int rc;
  172763. assert( iCol==0 || iCol%2 );
  172764. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
  172765. if( zSql ){
  172766. rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
  172767. }else{
  172768. rc = SQLITE_NOMEM;
  172769. }
  172770. sqlite3_free(zSql);
  172771. if( rc==SQLITE_OK ){
  172772. if( iCol==0 ){
  172773. const char *zCol = sqlite3_column_name(pStmt, 0);
  172774. pRtree->base.zErrMsg = sqlite3_mprintf(
  172775. "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
  172776. );
  172777. }else{
  172778. const char *zCol1 = sqlite3_column_name(pStmt, iCol);
  172779. const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
  172780. pRtree->base.zErrMsg = sqlite3_mprintf(
  172781. "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
  172782. );
  172783. }
  172784. }
  172785. sqlite3_finalize(pStmt);
  172786. return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
  172787. }
  172788. /*
  172789. ** The xUpdate method for rtree module virtual tables.
  172790. */
  172791. static int rtreeUpdate(
  172792. sqlite3_vtab *pVtab,
  172793. int nData,
  172794. sqlite3_value **aData,
  172795. sqlite_int64 *pRowid
  172796. ){
  172797. Rtree *pRtree = (Rtree *)pVtab;
  172798. int rc = SQLITE_OK;
  172799. RtreeCell cell; /* New cell to insert if nData>1 */
  172800. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  172801. if( pRtree->nNodeRef ){
  172802. /* Unable to write to the btree while another cursor is reading from it,
  172803. ** since the write might do a rebalance which would disrupt the read
  172804. ** cursor. */
  172805. return SQLITE_LOCKED_VTAB;
  172806. }
  172807. rtreeReference(pRtree);
  172808. assert(nData>=1);
  172809. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  172810. /* Constraint handling. A write operation on an r-tree table may return
  172811. ** SQLITE_CONSTRAINT for two reasons:
  172812. **
  172813. ** 1. A duplicate rowid value, or
  172814. ** 2. The supplied data violates the "x2>=x1" constraint.
  172815. **
  172816. ** In the first case, if the conflict-handling mode is REPLACE, then
  172817. ** the conflicting row can be removed before proceeding. In the second
  172818. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  172819. ** conflict-handling mode specified by the user.
  172820. */
  172821. if( nData>1 ){
  172822. int ii;
  172823. int nn = nData - 4;
  172824. if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
  172825. /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
  172826. **
  172827. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  172828. ** with "column" that are interpreted as table constraints.
  172829. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  172830. ** This problem was discovered after years of use, so we silently ignore
  172831. ** these kinds of misdeclared tables to avoid breaking any legacy.
  172832. */
  172833. #ifndef SQLITE_RTREE_INT_ONLY
  172834. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  172835. for(ii=0; ii<nn; ii+=2){
  172836. cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
  172837. cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
  172838. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  172839. rc = rtreeConstraintError(pRtree, ii+1);
  172840. goto constraint;
  172841. }
  172842. }
  172843. }else
  172844. #endif
  172845. {
  172846. for(ii=0; ii<nn; ii+=2){
  172847. cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
  172848. cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
  172849. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  172850. rc = rtreeConstraintError(pRtree, ii+1);
  172851. goto constraint;
  172852. }
  172853. }
  172854. }
  172855. /* If a rowid value was supplied, check if it is already present in
  172856. ** the table. If so, the constraint has failed. */
  172857. if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
  172858. cell.iRowid = sqlite3_value_int64(aData[2]);
  172859. if( sqlite3_value_type(aData[0])==SQLITE_NULL
  172860. || sqlite3_value_int64(aData[0])!=cell.iRowid
  172861. ){
  172862. int steprc;
  172863. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  172864. steprc = sqlite3_step(pRtree->pReadRowid);
  172865. rc = sqlite3_reset(pRtree->pReadRowid);
  172866. if( SQLITE_ROW==steprc ){
  172867. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  172868. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  172869. }else{
  172870. rc = rtreeConstraintError(pRtree, 0);
  172871. goto constraint;
  172872. }
  172873. }
  172874. }
  172875. bHaveRowid = 1;
  172876. }
  172877. }
  172878. /* If aData[0] is not an SQL NULL value, it is the rowid of a
  172879. ** record to delete from the r-tree table. The following block does
  172880. ** just that.
  172881. */
  172882. if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
  172883. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
  172884. }
  172885. /* If the aData[] array contains more than one element, elements
  172886. ** (aData[2]..aData[argc-1]) contain a new record to insert into
  172887. ** the r-tree structure.
  172888. */
  172889. if( rc==SQLITE_OK && nData>1 ){
  172890. /* Insert the new record into the r-tree */
  172891. RtreeNode *pLeaf = 0;
  172892. /* Figure out the rowid of the new row. */
  172893. if( bHaveRowid==0 ){
  172894. rc = rtreeNewRowid(pRtree, &cell.iRowid);
  172895. }
  172896. *pRowid = cell.iRowid;
  172897. if( rc==SQLITE_OK ){
  172898. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  172899. }
  172900. if( rc==SQLITE_OK ){
  172901. int rc2;
  172902. pRtree->iReinsertHeight = -1;
  172903. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  172904. rc2 = nodeRelease(pRtree, pLeaf);
  172905. if( rc==SQLITE_OK ){
  172906. rc = rc2;
  172907. }
  172908. }
  172909. if( rc==SQLITE_OK && pRtree->nAux ){
  172910. sqlite3_stmt *pUp = pRtree->pWriteAux;
  172911. int jj;
  172912. sqlite3_bind_int64(pUp, 1, *pRowid);
  172913. for(jj=0; jj<pRtree->nAux; jj++){
  172914. sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
  172915. }
  172916. sqlite3_step(pUp);
  172917. rc = sqlite3_reset(pUp);
  172918. }
  172919. }
  172920. constraint:
  172921. rtreeRelease(pRtree);
  172922. return rc;
  172923. }
  172924. /*
  172925. ** Called when a transaction starts.
  172926. */
  172927. static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
  172928. Rtree *pRtree = (Rtree *)pVtab;
  172929. assert( pRtree->inWrTrans==0 );
  172930. pRtree->inWrTrans++;
  172931. return SQLITE_OK;
  172932. }
  172933. /*
  172934. ** Called when a transaction completes (either by COMMIT or ROLLBACK).
  172935. ** The sqlite3_blob object should be released at this point.
  172936. */
  172937. static int rtreeEndTransaction(sqlite3_vtab *pVtab){
  172938. Rtree *pRtree = (Rtree *)pVtab;
  172939. pRtree->inWrTrans = 0;
  172940. nodeBlobReset(pRtree);
  172941. return SQLITE_OK;
  172942. }
  172943. /*
  172944. ** The xRename method for rtree module virtual tables.
  172945. */
  172946. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  172947. Rtree *pRtree = (Rtree *)pVtab;
  172948. int rc = SQLITE_NOMEM;
  172949. char *zSql = sqlite3_mprintf(
  172950. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  172951. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  172952. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  172953. , pRtree->zDb, pRtree->zName, zNewName
  172954. , pRtree->zDb, pRtree->zName, zNewName
  172955. , pRtree->zDb, pRtree->zName, zNewName
  172956. );
  172957. if( zSql ){
  172958. nodeBlobReset(pRtree);
  172959. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  172960. sqlite3_free(zSql);
  172961. }
  172962. return rc;
  172963. }
  172964. /*
  172965. ** The xSavepoint method.
  172966. **
  172967. ** This module does not need to do anything to support savepoints. However,
  172968. ** it uses this hook to close any open blob handle. This is done because a
  172969. ** DROP TABLE command - which fortunately always opens a savepoint - cannot
  172970. ** succeed if there are any open blob handles. i.e. if the blob handle were
  172971. ** not closed here, the following would fail:
  172972. **
  172973. ** BEGIN;
  172974. ** INSERT INTO rtree...
  172975. ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
  172976. ** COMMIT;
  172977. */
  172978. static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
  172979. Rtree *pRtree = (Rtree *)pVtab;
  172980. u8 iwt = pRtree->inWrTrans;
  172981. UNUSED_PARAMETER(iSavepoint);
  172982. pRtree->inWrTrans = 0;
  172983. nodeBlobReset(pRtree);
  172984. pRtree->inWrTrans = iwt;
  172985. return SQLITE_OK;
  172986. }
  172987. /*
  172988. ** This function populates the pRtree->nRowEst variable with an estimate
  172989. ** of the number of rows in the virtual table. If possible, this is based
  172990. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  172991. */
  172992. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  172993. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  172994. char *zSql;
  172995. sqlite3_stmt *p;
  172996. int rc;
  172997. i64 nRow = 0;
  172998. rc = sqlite3_table_column_metadata(
  172999. db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
  173000. );
  173001. if( rc!=SQLITE_OK ){
  173002. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  173003. return rc==SQLITE_ERROR ? SQLITE_OK : rc;
  173004. }
  173005. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  173006. if( zSql==0 ){
  173007. rc = SQLITE_NOMEM;
  173008. }else{
  173009. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  173010. if( rc==SQLITE_OK ){
  173011. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  173012. rc = sqlite3_finalize(p);
  173013. }else if( rc!=SQLITE_NOMEM ){
  173014. rc = SQLITE_OK;
  173015. }
  173016. if( rc==SQLITE_OK ){
  173017. if( nRow==0 ){
  173018. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  173019. }else{
  173020. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  173021. }
  173022. }
  173023. sqlite3_free(zSql);
  173024. }
  173025. return rc;
  173026. }
  173027. /*
  173028. ** Return true if zName is the extension on one of the shadow tables used
  173029. ** by this module.
  173030. */
  173031. static int rtreeShadowName(const char *zName){
  173032. static const char *azName[] = {
  173033. "node", "parent", "rowid"
  173034. };
  173035. unsigned int i;
  173036. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  173037. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  173038. }
  173039. return 0;
  173040. }
  173041. static sqlite3_module rtreeModule = {
  173042. 3, /* iVersion */
  173043. rtreeCreate, /* xCreate - create a table */
  173044. rtreeConnect, /* xConnect - connect to an existing table */
  173045. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  173046. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  173047. rtreeDestroy, /* xDestroy - Drop a table */
  173048. rtreeOpen, /* xOpen - open a cursor */
  173049. rtreeClose, /* xClose - close a cursor */
  173050. rtreeFilter, /* xFilter - configure scan constraints */
  173051. rtreeNext, /* xNext - advance a cursor */
  173052. rtreeEof, /* xEof */
  173053. rtreeColumn, /* xColumn - read data */
  173054. rtreeRowid, /* xRowid - read data */
  173055. rtreeUpdate, /* xUpdate - write data */
  173056. rtreeBeginTransaction, /* xBegin - begin transaction */
  173057. rtreeEndTransaction, /* xSync - sync transaction */
  173058. rtreeEndTransaction, /* xCommit - commit transaction */
  173059. rtreeEndTransaction, /* xRollback - rollback transaction */
  173060. 0, /* xFindFunction - function overloading */
  173061. rtreeRename, /* xRename - rename the table */
  173062. rtreeSavepoint, /* xSavepoint */
  173063. 0, /* xRelease */
  173064. 0, /* xRollbackTo */
  173065. rtreeShadowName /* xShadowName */
  173066. };
  173067. static int rtreeSqlInit(
  173068. Rtree *pRtree,
  173069. sqlite3 *db,
  173070. const char *zDb,
  173071. const char *zPrefix,
  173072. int isCreate
  173073. ){
  173074. int rc = SQLITE_OK;
  173075. #define N_STATEMENT 8
  173076. static const char *azSql[N_STATEMENT] = {
  173077. /* Write the xxx_node table */
  173078. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
  173079. "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
  173080. /* Read and write the xxx_rowid table */
  173081. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
  173082. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
  173083. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
  173084. /* Read and write the xxx_parent table */
  173085. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
  173086. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
  173087. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
  173088. };
  173089. sqlite3_stmt **appStmt[N_STATEMENT];
  173090. int i;
  173091. const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
  173092. pRtree->db = db;
  173093. if( isCreate ){
  173094. char *zCreate;
  173095. sqlite3_str *p = sqlite3_str_new(db);
  173096. int ii;
  173097. sqlite3_str_appendf(p,
  173098. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
  173099. zDb, zPrefix);
  173100. for(ii=0; ii<pRtree->nAux; ii++){
  173101. sqlite3_str_appendf(p,",a%d",ii);
  173102. }
  173103. sqlite3_str_appendf(p,
  173104. ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
  173105. zDb, zPrefix);
  173106. sqlite3_str_appendf(p,
  173107. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
  173108. zDb, zPrefix);
  173109. sqlite3_str_appendf(p,
  173110. "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
  173111. zDb, zPrefix, pRtree->iNodeSize);
  173112. zCreate = sqlite3_str_finish(p);
  173113. if( !zCreate ){
  173114. return SQLITE_NOMEM;
  173115. }
  173116. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  173117. sqlite3_free(zCreate);
  173118. if( rc!=SQLITE_OK ){
  173119. return rc;
  173120. }
  173121. }
  173122. appStmt[0] = &pRtree->pWriteNode;
  173123. appStmt[1] = &pRtree->pDeleteNode;
  173124. appStmt[2] = &pRtree->pReadRowid;
  173125. appStmt[3] = &pRtree->pWriteRowid;
  173126. appStmt[4] = &pRtree->pDeleteRowid;
  173127. appStmt[5] = &pRtree->pReadParent;
  173128. appStmt[6] = &pRtree->pWriteParent;
  173129. appStmt[7] = &pRtree->pDeleteParent;
  173130. rc = rtreeQueryStat1(db, pRtree);
  173131. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  173132. char *zSql;
  173133. const char *zFormat;
  173134. if( i!=3 || pRtree->nAux==0 ){
  173135. zFormat = azSql[i];
  173136. }else {
  173137. /* An UPSERT is very slightly slower than REPLACE, but it is needed
  173138. ** if there are auxiliary columns */
  173139. zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
  173140. "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
  173141. }
  173142. zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
  173143. if( zSql ){
  173144. rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0);
  173145. }else{
  173146. rc = SQLITE_NOMEM;
  173147. }
  173148. sqlite3_free(zSql);
  173149. }
  173150. if( pRtree->nAux ){
  173151. pRtree->zReadAuxSql = sqlite3_mprintf(
  173152. "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
  173153. zDb, zPrefix);
  173154. if( pRtree->zReadAuxSql==0 ){
  173155. rc = SQLITE_NOMEM;
  173156. }else{
  173157. sqlite3_str *p = sqlite3_str_new(db);
  173158. int ii;
  173159. char *zSql;
  173160. sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
  173161. for(ii=0; ii<pRtree->nAux; ii++){
  173162. if( ii ) sqlite3_str_append(p, ",", 1);
  173163. if( ii<pRtree->nAuxNotNull ){
  173164. sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
  173165. }else{
  173166. sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
  173167. }
  173168. }
  173169. sqlite3_str_appendf(p, " WHERE rowid=?1");
  173170. zSql = sqlite3_str_finish(p);
  173171. if( zSql==0 ){
  173172. rc = SQLITE_NOMEM;
  173173. }else{
  173174. rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0);
  173175. sqlite3_free(zSql);
  173176. }
  173177. }
  173178. }
  173179. return rc;
  173180. }
  173181. /*
  173182. ** The second argument to this function contains the text of an SQL statement
  173183. ** that returns a single integer value. The statement is compiled and executed
  173184. ** using database connection db. If successful, the integer value returned
  173185. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  173186. ** code is returned and the value of *piVal after returning is not defined.
  173187. */
  173188. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  173189. int rc = SQLITE_NOMEM;
  173190. if( zSql ){
  173191. sqlite3_stmt *pStmt = 0;
  173192. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  173193. if( rc==SQLITE_OK ){
  173194. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  173195. *piVal = sqlite3_column_int(pStmt, 0);
  173196. }
  173197. rc = sqlite3_finalize(pStmt);
  173198. }
  173199. }
  173200. return rc;
  173201. }
  173202. /*
  173203. ** This function is called from within the xConnect() or xCreate() method to
  173204. ** determine the node-size used by the rtree table being created or connected
  173205. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  173206. ** Otherwise, an SQLite error code is returned.
  173207. **
  173208. ** If this function is being called as part of an xConnect(), then the rtree
  173209. ** table already exists. In this case the node-size is determined by inspecting
  173210. ** the root node of the tree.
  173211. **
  173212. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  173213. ** This ensures that each node is stored on a single database page. If the
  173214. ** database page-size is so large that more than RTREE_MAXCELLS entries
  173215. ** would fit in a single node, use a smaller node-size.
  173216. */
  173217. static int getNodeSize(
  173218. sqlite3 *db, /* Database handle */
  173219. Rtree *pRtree, /* Rtree handle */
  173220. int isCreate, /* True for xCreate, false for xConnect */
  173221. char **pzErr /* OUT: Error message, if any */
  173222. ){
  173223. int rc;
  173224. char *zSql;
  173225. if( isCreate ){
  173226. int iPageSize = 0;
  173227. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  173228. rc = getIntFromStmt(db, zSql, &iPageSize);
  173229. if( rc==SQLITE_OK ){
  173230. pRtree->iNodeSize = iPageSize-64;
  173231. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  173232. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  173233. }
  173234. }else{
  173235. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  173236. }
  173237. }else{
  173238. zSql = sqlite3_mprintf(
  173239. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  173240. pRtree->zDb, pRtree->zName
  173241. );
  173242. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  173243. if( rc!=SQLITE_OK ){
  173244. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  173245. }else if( pRtree->iNodeSize<(512-64) ){
  173246. rc = SQLITE_CORRUPT_VTAB;
  173247. RTREE_IS_CORRUPT(pRtree);
  173248. *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
  173249. pRtree->zName);
  173250. }
  173251. }
  173252. sqlite3_free(zSql);
  173253. return rc;
  173254. }
  173255. /*
  173256. ** This function is the implementation of both the xConnect and xCreate
  173257. ** methods of the r-tree virtual table.
  173258. **
  173259. ** argv[0] -> module name
  173260. ** argv[1] -> database name
  173261. ** argv[2] -> table name
  173262. ** argv[...] -> column names...
  173263. */
  173264. static int rtreeInit(
  173265. sqlite3 *db, /* Database connection */
  173266. void *pAux, /* One of the RTREE_COORD_* constants */
  173267. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  173268. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  173269. char **pzErr, /* OUT: Error message, if any */
  173270. int isCreate /* True for xCreate, false for xConnect */
  173271. ){
  173272. int rc = SQLITE_OK;
  173273. Rtree *pRtree;
  173274. int nDb; /* Length of string argv[1] */
  173275. int nName; /* Length of string argv[2] */
  173276. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  173277. sqlite3_str *pSql;
  173278. char *zSql;
  173279. int ii = 4;
  173280. int iErr;
  173281. const char *aErrMsg[] = {
  173282. 0, /* 0 */
  173283. "Wrong number of columns for an rtree table", /* 1 */
  173284. "Too few columns for an rtree table", /* 2 */
  173285. "Too many columns for an rtree table", /* 3 */
  173286. "Auxiliary rtree columns must be last" /* 4 */
  173287. };
  173288. assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
  173289. if( argc>RTREE_MAX_AUX_COLUMN+3 ){
  173290. *pzErr = sqlite3_mprintf("%s", aErrMsg[3]);
  173291. return SQLITE_ERROR;
  173292. }
  173293. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  173294. /* Allocate the sqlite3_vtab structure */
  173295. nDb = (int)strlen(argv[1]);
  173296. nName = (int)strlen(argv[2]);
  173297. pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
  173298. if( !pRtree ){
  173299. return SQLITE_NOMEM;
  173300. }
  173301. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  173302. pRtree->nBusy = 1;
  173303. pRtree->base.pModule = &rtreeModule;
  173304. pRtree->zDb = (char *)&pRtree[1];
  173305. pRtree->zName = &pRtree->zDb[nDb+1];
  173306. pRtree->eCoordType = (u8)eCoordType;
  173307. memcpy(pRtree->zDb, argv[1], nDb);
  173308. memcpy(pRtree->zName, argv[2], nName);
  173309. /* Create/Connect to the underlying relational database schema. If
  173310. ** that is successful, call sqlite3_declare_vtab() to configure
  173311. ** the r-tree table schema.
  173312. */
  173313. pSql = sqlite3_str_new(db);
  173314. sqlite3_str_appendf(pSql, "CREATE TABLE x(%s", argv[3]);
  173315. for(ii=4; ii<argc; ii++){
  173316. if( argv[ii][0]=='+' ){
  173317. pRtree->nAux++;
  173318. sqlite3_str_appendf(pSql, ",%s", argv[ii]+1);
  173319. }else if( pRtree->nAux>0 ){
  173320. break;
  173321. }else{
  173322. pRtree->nDim2++;
  173323. sqlite3_str_appendf(pSql, ",%s", argv[ii]);
  173324. }
  173325. }
  173326. sqlite3_str_appendf(pSql, ");");
  173327. zSql = sqlite3_str_finish(pSql);
  173328. if( !zSql ){
  173329. rc = SQLITE_NOMEM;
  173330. }else if( ii<argc ){
  173331. *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
  173332. rc = SQLITE_ERROR;
  173333. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  173334. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  173335. }
  173336. sqlite3_free(zSql);
  173337. if( rc ) goto rtreeInit_fail;
  173338. pRtree->nDim = pRtree->nDim2/2;
  173339. if( pRtree->nDim<1 ){
  173340. iErr = 2;
  173341. }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
  173342. iErr = 3;
  173343. }else if( pRtree->nDim2 % 2 ){
  173344. iErr = 1;
  173345. }else{
  173346. iErr = 0;
  173347. }
  173348. if( iErr ){
  173349. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  173350. goto rtreeInit_fail;
  173351. }
  173352. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  173353. /* Figure out the node size to use. */
  173354. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  173355. if( rc ) goto rtreeInit_fail;
  173356. rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
  173357. if( rc ){
  173358. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  173359. goto rtreeInit_fail;
  173360. }
  173361. *ppVtab = (sqlite3_vtab *)pRtree;
  173362. return SQLITE_OK;
  173363. rtreeInit_fail:
  173364. if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
  173365. assert( *ppVtab==0 );
  173366. assert( pRtree->nBusy==1 );
  173367. rtreeRelease(pRtree);
  173368. return rc;
  173369. }
  173370. /*
  173371. ** Implementation of a scalar function that decodes r-tree nodes to
  173372. ** human readable strings. This can be used for debugging and analysis.
  173373. **
  173374. ** The scalar function takes two arguments: (1) the number of dimensions
  173375. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  173376. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  173377. ** deserialize all nodes, a statement like:
  173378. **
  173379. ** SELECT rtreenode(2, data) FROM rt_node;
  173380. **
  173381. ** The human readable string takes the form of a Tcl list with one
  173382. ** entry for each cell in the r-tree node. Each entry is itself a
  173383. ** list, containing the 8-byte rowid/pageno followed by the
  173384. ** <num-dimension>*2 coordinates.
  173385. */
  173386. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  173387. RtreeNode node;
  173388. Rtree tree;
  173389. int ii;
  173390. int nData;
  173391. int errCode;
  173392. sqlite3_str *pOut;
  173393. UNUSED_PARAMETER(nArg);
  173394. memset(&node, 0, sizeof(RtreeNode));
  173395. memset(&tree, 0, sizeof(Rtree));
  173396. tree.nDim = (u8)sqlite3_value_int(apArg[0]);
  173397. if( tree.nDim<1 || tree.nDim>5 ) return;
  173398. tree.nDim2 = tree.nDim*2;
  173399. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  173400. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  173401. nData = sqlite3_value_bytes(apArg[1]);
  173402. if( nData<4 ) return;
  173403. if( nData<NCELL(&node)*tree.nBytesPerCell ) return;
  173404. pOut = sqlite3_str_new(0);
  173405. for(ii=0; ii<NCELL(&node); ii++){
  173406. RtreeCell cell;
  173407. int jj;
  173408. nodeGetCell(&tree, &node, ii, &cell);
  173409. if( ii>0 ) sqlite3_str_append(pOut, " ", 1);
  173410. sqlite3_str_appendf(pOut, "{%lld", cell.iRowid);
  173411. for(jj=0; jj<tree.nDim2; jj++){
  173412. #ifndef SQLITE_RTREE_INT_ONLY
  173413. sqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f);
  173414. #else
  173415. sqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i);
  173416. #endif
  173417. }
  173418. sqlite3_str_append(pOut, "}", 1);
  173419. }
  173420. errCode = sqlite3_str_errcode(pOut);
  173421. sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free);
  173422. sqlite3_result_error_code(ctx, errCode);
  173423. }
  173424. /* This routine implements an SQL function that returns the "depth" parameter
  173425. ** from the front of a blob that is an r-tree node. For example:
  173426. **
  173427. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  173428. **
  173429. ** The depth value is 0 for all nodes other than the root node, and the root
  173430. ** node always has nodeno=1, so the example above is the primary use for this
  173431. ** routine. This routine is intended for testing and analysis only.
  173432. */
  173433. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  173434. UNUSED_PARAMETER(nArg);
  173435. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  173436. || sqlite3_value_bytes(apArg[0])<2
  173437. ){
  173438. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  173439. }else{
  173440. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  173441. sqlite3_result_int(ctx, readInt16(zBlob));
  173442. }
  173443. }
  173444. /*
  173445. ** Context object passed between the various routines that make up the
  173446. ** implementation of integrity-check function rtreecheck().
  173447. */
  173448. typedef struct RtreeCheck RtreeCheck;
  173449. struct RtreeCheck {
  173450. sqlite3 *db; /* Database handle */
  173451. const char *zDb; /* Database containing rtree table */
  173452. const char *zTab; /* Name of rtree table */
  173453. int bInt; /* True for rtree_i32 table */
  173454. int nDim; /* Number of dimensions for this rtree tbl */
  173455. sqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */
  173456. sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
  173457. int nLeaf; /* Number of leaf cells in table */
  173458. int nNonLeaf; /* Number of non-leaf cells in table */
  173459. int rc; /* Return code */
  173460. char *zReport; /* Message to report */
  173461. int nErr; /* Number of lines in zReport */
  173462. };
  173463. #define RTREE_CHECK_MAX_ERROR 100
  173464. /*
  173465. ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
  173466. ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
  173467. */
  173468. static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
  173469. int rc = sqlite3_reset(pStmt);
  173470. if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
  173471. }
  173472. /*
  173473. ** The second and subsequent arguments to this function are a format string
  173474. ** and printf style arguments. This function formats the string and attempts
  173475. ** to compile it as an SQL statement.
  173476. **
  173477. ** If successful, a pointer to the new SQL statement is returned. Otherwise,
  173478. ** NULL is returned and an error code left in RtreeCheck.rc.
  173479. */
  173480. static sqlite3_stmt *rtreeCheckPrepare(
  173481. RtreeCheck *pCheck, /* RtreeCheck object */
  173482. const char *zFmt, ... /* Format string and trailing args */
  173483. ){
  173484. va_list ap;
  173485. char *z;
  173486. sqlite3_stmt *pRet = 0;
  173487. va_start(ap, zFmt);
  173488. z = sqlite3_vmprintf(zFmt, ap);
  173489. if( pCheck->rc==SQLITE_OK ){
  173490. if( z==0 ){
  173491. pCheck->rc = SQLITE_NOMEM;
  173492. }else{
  173493. pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
  173494. }
  173495. }
  173496. sqlite3_free(z);
  173497. va_end(ap);
  173498. return pRet;
  173499. }
  173500. /*
  173501. ** The second and subsequent arguments to this function are a printf()
  173502. ** style format string and arguments. This function formats the string and
  173503. ** appends it to the report being accumuated in pCheck.
  173504. */
  173505. static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
  173506. va_list ap;
  173507. va_start(ap, zFmt);
  173508. if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
  173509. char *z = sqlite3_vmprintf(zFmt, ap);
  173510. if( z==0 ){
  173511. pCheck->rc = SQLITE_NOMEM;
  173512. }else{
  173513. pCheck->zReport = sqlite3_mprintf("%z%s%z",
  173514. pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
  173515. );
  173516. if( pCheck->zReport==0 ){
  173517. pCheck->rc = SQLITE_NOMEM;
  173518. }
  173519. }
  173520. pCheck->nErr++;
  173521. }
  173522. va_end(ap);
  173523. }
  173524. /*
  173525. ** This function is a no-op if there is already an error code stored
  173526. ** in the RtreeCheck object indicated by the first argument. NULL is
  173527. ** returned in this case.
  173528. **
  173529. ** Otherwise, the contents of rtree table node iNode are loaded from
  173530. ** the database and copied into a buffer obtained from sqlite3_malloc().
  173531. ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
  173532. ** is set to the size of the buffer in bytes.
  173533. **
  173534. ** Or, if an error does occur, NULL is returned and an error code left
  173535. ** in the RtreeCheck object. The final value of *pnNode is undefined in
  173536. ** this case.
  173537. */
  173538. static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
  173539. u8 *pRet = 0; /* Return value */
  173540. if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
  173541. pCheck->pGetNode = rtreeCheckPrepare(pCheck,
  173542. "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
  173543. pCheck->zDb, pCheck->zTab
  173544. );
  173545. }
  173546. if( pCheck->rc==SQLITE_OK ){
  173547. sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
  173548. if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
  173549. int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
  173550. const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
  173551. pRet = sqlite3_malloc64(nNode);
  173552. if( pRet==0 ){
  173553. pCheck->rc = SQLITE_NOMEM;
  173554. }else{
  173555. memcpy(pRet, pNode, nNode);
  173556. *pnNode = nNode;
  173557. }
  173558. }
  173559. rtreeCheckReset(pCheck, pCheck->pGetNode);
  173560. if( pCheck->rc==SQLITE_OK && pRet==0 ){
  173561. rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
  173562. }
  173563. }
  173564. return pRet;
  173565. }
  173566. /*
  173567. ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
  173568. ** (if bLeaf==1) table contains a specified entry. The schemas of the
  173569. ** two tables are:
  173570. **
  173571. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  173572. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
  173573. **
  173574. ** In both cases, this function checks that there exists an entry with
  173575. ** IPK value iKey and the second column set to iVal.
  173576. **
  173577. */
  173578. static void rtreeCheckMapping(
  173579. RtreeCheck *pCheck, /* RtreeCheck object */
  173580. int bLeaf, /* True for a leaf cell, false for interior */
  173581. i64 iKey, /* Key for mapping */
  173582. i64 iVal /* Expected value for mapping */
  173583. ){
  173584. int rc;
  173585. sqlite3_stmt *pStmt;
  173586. const char *azSql[2] = {
  173587. "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
  173588. "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
  173589. };
  173590. assert( bLeaf==0 || bLeaf==1 );
  173591. if( pCheck->aCheckMapping[bLeaf]==0 ){
  173592. pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
  173593. azSql[bLeaf], pCheck->zDb, pCheck->zTab
  173594. );
  173595. }
  173596. if( pCheck->rc!=SQLITE_OK ) return;
  173597. pStmt = pCheck->aCheckMapping[bLeaf];
  173598. sqlite3_bind_int64(pStmt, 1, iKey);
  173599. rc = sqlite3_step(pStmt);
  173600. if( rc==SQLITE_DONE ){
  173601. rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
  173602. iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
  173603. );
  173604. }else if( rc==SQLITE_ROW ){
  173605. i64 ii = sqlite3_column_int64(pStmt, 0);
  173606. if( ii!=iVal ){
  173607. rtreeCheckAppendMsg(pCheck,
  173608. "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
  173609. iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
  173610. );
  173611. }
  173612. }
  173613. rtreeCheckReset(pCheck, pStmt);
  173614. }
  173615. /*
  173616. ** Argument pCell points to an array of coordinates stored on an rtree page.
  173617. ** This function checks that the coordinates are internally consistent (no
  173618. ** x1>x2 conditions) and adds an error message to the RtreeCheck object
  173619. ** if they are not.
  173620. **
  173621. ** Additionally, if pParent is not NULL, then it is assumed to point to
  173622. ** the array of coordinates on the parent page that bound the page
  173623. ** containing pCell. In this case it is also verified that the two
  173624. ** sets of coordinates are mutually consistent and an error message added
  173625. ** to the RtreeCheck object if they are not.
  173626. */
  173627. static void rtreeCheckCellCoord(
  173628. RtreeCheck *pCheck,
  173629. i64 iNode, /* Node id to use in error messages */
  173630. int iCell, /* Cell number to use in error messages */
  173631. u8 *pCell, /* Pointer to cell coordinates */
  173632. u8 *pParent /* Pointer to parent coordinates */
  173633. ){
  173634. RtreeCoord c1, c2;
  173635. RtreeCoord p1, p2;
  173636. int i;
  173637. for(i=0; i<pCheck->nDim; i++){
  173638. readCoord(&pCell[4*2*i], &c1);
  173639. readCoord(&pCell[4*(2*i + 1)], &c2);
  173640. /* printf("%e, %e\n", c1.u.f, c2.u.f); */
  173641. if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
  173642. rtreeCheckAppendMsg(pCheck,
  173643. "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
  173644. );
  173645. }
  173646. if( pParent ){
  173647. readCoord(&pParent[4*2*i], &p1);
  173648. readCoord(&pParent[4*(2*i + 1)], &p2);
  173649. if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
  173650. || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
  173651. ){
  173652. rtreeCheckAppendMsg(pCheck,
  173653. "Dimension %d of cell %d on node %lld is corrupt relative to parent"
  173654. , i, iCell, iNode
  173655. );
  173656. }
  173657. }
  173658. }
  173659. }
  173660. /*
  173661. ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
  173662. ** the r-tree structure. Argument aParent points to the array of coordinates
  173663. ** that bound node iNode on the parent node.
  173664. **
  173665. ** If any problems are discovered, an error message is appended to the
  173666. ** report accumulated in the RtreeCheck object.
  173667. */
  173668. static void rtreeCheckNode(
  173669. RtreeCheck *pCheck,
  173670. int iDepth, /* Depth of iNode (0==leaf) */
  173671. u8 *aParent, /* Buffer containing parent coords */
  173672. i64 iNode /* Node to check */
  173673. ){
  173674. u8 *aNode = 0;
  173675. int nNode = 0;
  173676. assert( iNode==1 || aParent!=0 );
  173677. assert( pCheck->nDim>0 );
  173678. aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
  173679. if( aNode ){
  173680. if( nNode<4 ){
  173681. rtreeCheckAppendMsg(pCheck,
  173682. "Node %lld is too small (%d bytes)", iNode, nNode
  173683. );
  173684. }else{
  173685. int nCell; /* Number of cells on page */
  173686. int i; /* Used to iterate through cells */
  173687. if( aParent==0 ){
  173688. iDepth = readInt16(aNode);
  173689. if( iDepth>RTREE_MAX_DEPTH ){
  173690. rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
  173691. sqlite3_free(aNode);
  173692. return;
  173693. }
  173694. }
  173695. nCell = readInt16(&aNode[2]);
  173696. if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
  173697. rtreeCheckAppendMsg(pCheck,
  173698. "Node %lld is too small for cell count of %d (%d bytes)",
  173699. iNode, nCell, nNode
  173700. );
  173701. }else{
  173702. for(i=0; i<nCell; i++){
  173703. u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
  173704. i64 iVal = readInt64(pCell);
  173705. rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
  173706. if( iDepth>0 ){
  173707. rtreeCheckMapping(pCheck, 0, iVal, iNode);
  173708. rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
  173709. pCheck->nNonLeaf++;
  173710. }else{
  173711. rtreeCheckMapping(pCheck, 1, iVal, iNode);
  173712. pCheck->nLeaf++;
  173713. }
  173714. }
  173715. }
  173716. }
  173717. sqlite3_free(aNode);
  173718. }
  173719. }
  173720. /*
  173721. ** The second argument to this function must be either "_rowid" or
  173722. ** "_parent". This function checks that the number of entries in the
  173723. ** %_rowid or %_parent table is exactly nExpect. If not, it adds
  173724. ** an error message to the report in the RtreeCheck object indicated
  173725. ** by the first argument.
  173726. */
  173727. static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
  173728. if( pCheck->rc==SQLITE_OK ){
  173729. sqlite3_stmt *pCount;
  173730. pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
  173731. pCheck->zDb, pCheck->zTab, zTbl
  173732. );
  173733. if( pCount ){
  173734. if( sqlite3_step(pCount)==SQLITE_ROW ){
  173735. i64 nActual = sqlite3_column_int64(pCount, 0);
  173736. if( nActual!=nExpect ){
  173737. rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
  173738. " - expected %lld, actual %lld" , zTbl, nExpect, nActual
  173739. );
  173740. }
  173741. }
  173742. pCheck->rc = sqlite3_finalize(pCount);
  173743. }
  173744. }
  173745. }
  173746. /*
  173747. ** This function does the bulk of the work for the rtree integrity-check.
  173748. ** It is called by rtreecheck(), which is the SQL function implementation.
  173749. */
  173750. static int rtreeCheckTable(
  173751. sqlite3 *db, /* Database handle to access db through */
  173752. const char *zDb, /* Name of db ("main", "temp" etc.) */
  173753. const char *zTab, /* Name of rtree table to check */
  173754. char **pzReport /* OUT: sqlite3_malloc'd report text */
  173755. ){
  173756. RtreeCheck check; /* Common context for various routines */
  173757. sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */
  173758. int bEnd = 0; /* True if transaction should be closed */
  173759. int nAux = 0; /* Number of extra columns. */
  173760. /* Initialize the context object */
  173761. memset(&check, 0, sizeof(check));
  173762. check.db = db;
  173763. check.zDb = zDb;
  173764. check.zTab = zTab;
  173765. /* If there is not already an open transaction, open one now. This is
  173766. ** to ensure that the queries run as part of this integrity-check operate
  173767. ** on a consistent snapshot. */
  173768. if( sqlite3_get_autocommit(db) ){
  173769. check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
  173770. bEnd = 1;
  173771. }
  173772. /* Find the number of auxiliary columns */
  173773. if( check.rc==SQLITE_OK ){
  173774. pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
  173775. if( pStmt ){
  173776. nAux = sqlite3_column_count(pStmt) - 2;
  173777. sqlite3_finalize(pStmt);
  173778. }
  173779. check.rc = SQLITE_OK;
  173780. }
  173781. /* Find number of dimensions in the rtree table. */
  173782. pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
  173783. if( pStmt ){
  173784. int rc;
  173785. check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
  173786. if( check.nDim<1 ){
  173787. rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
  173788. }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
  173789. check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
  173790. }
  173791. rc = sqlite3_finalize(pStmt);
  173792. if( rc!=SQLITE_CORRUPT ) check.rc = rc;
  173793. }
  173794. /* Do the actual integrity-check */
  173795. if( check.nDim>=1 ){
  173796. if( check.rc==SQLITE_OK ){
  173797. rtreeCheckNode(&check, 0, 0, 1);
  173798. }
  173799. rtreeCheckCount(&check, "_rowid", check.nLeaf);
  173800. rtreeCheckCount(&check, "_parent", check.nNonLeaf);
  173801. }
  173802. /* Finalize SQL statements used by the integrity-check */
  173803. sqlite3_finalize(check.pGetNode);
  173804. sqlite3_finalize(check.aCheckMapping[0]);
  173805. sqlite3_finalize(check.aCheckMapping[1]);
  173806. /* If one was opened, close the transaction */
  173807. if( bEnd ){
  173808. int rc = sqlite3_exec(db, "END", 0, 0, 0);
  173809. if( check.rc==SQLITE_OK ) check.rc = rc;
  173810. }
  173811. *pzReport = check.zReport;
  173812. return check.rc;
  173813. }
  173814. /*
  173815. ** Usage:
  173816. **
  173817. ** rtreecheck(<rtree-table>);
  173818. ** rtreecheck(<database>, <rtree-table>);
  173819. **
  173820. ** Invoking this SQL function runs an integrity-check on the named rtree
  173821. ** table. The integrity-check verifies the following:
  173822. **
  173823. ** 1. For each cell in the r-tree structure (%_node table), that:
  173824. **
  173825. ** a) for each dimension, (coord1 <= coord2).
  173826. **
  173827. ** b) unless the cell is on the root node, that the cell is bounded
  173828. ** by the parent cell on the parent node.
  173829. **
  173830. ** c) for leaf nodes, that there is an entry in the %_rowid
  173831. ** table corresponding to the cell's rowid value that
  173832. ** points to the correct node.
  173833. **
  173834. ** d) for cells on non-leaf nodes, that there is an entry in the
  173835. ** %_parent table mapping from the cell's child node to the
  173836. ** node that it resides on.
  173837. **
  173838. ** 2. That there are the same number of entries in the %_rowid table
  173839. ** as there are leaf cells in the r-tree structure, and that there
  173840. ** is a leaf cell that corresponds to each entry in the %_rowid table.
  173841. **
  173842. ** 3. That there are the same number of entries in the %_parent table
  173843. ** as there are non-leaf cells in the r-tree structure, and that
  173844. ** there is a non-leaf cell that corresponds to each entry in the
  173845. ** %_parent table.
  173846. */
  173847. static void rtreecheck(
  173848. sqlite3_context *ctx,
  173849. int nArg,
  173850. sqlite3_value **apArg
  173851. ){
  173852. if( nArg!=1 && nArg!=2 ){
  173853. sqlite3_result_error(ctx,
  173854. "wrong number of arguments to function rtreecheck()", -1
  173855. );
  173856. }else{
  173857. int rc;
  173858. char *zReport = 0;
  173859. const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
  173860. const char *zTab;
  173861. if( nArg==1 ){
  173862. zTab = zDb;
  173863. zDb = "main";
  173864. }else{
  173865. zTab = (const char*)sqlite3_value_text(apArg[1]);
  173866. }
  173867. rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
  173868. if( rc==SQLITE_OK ){
  173869. sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
  173870. }else{
  173871. sqlite3_result_error_code(ctx, rc);
  173872. }
  173873. sqlite3_free(zReport);
  173874. }
  173875. }
  173876. /* Conditionally include the geopoly code */
  173877. #ifdef SQLITE_ENABLE_GEOPOLY
  173878. /************** Include geopoly.c in the middle of rtree.c *******************/
  173879. /************** Begin file geopoly.c *****************************************/
  173880. /*
  173881. ** 2018-05-25
  173882. **
  173883. ** The author disclaims copyright to this source code. In place of
  173884. ** a legal notice, here is a blessing:
  173885. **
  173886. ** May you do good and not evil.
  173887. ** May you find forgiveness for yourself and forgive others.
  173888. ** May you share freely, never taking more than you give.
  173889. **
  173890. ******************************************************************************
  173891. **
  173892. ** This file implements an alternative R-Tree virtual table that
  173893. ** uses polygons to express the boundaries of 2-dimensional objects.
  173894. **
  173895. ** This file is #include-ed onto the end of "rtree.c" so that it has
  173896. ** access to all of the R-Tree internals.
  173897. */
  173898. /* #include <stdlib.h> */
  173899. /* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */
  173900. #ifdef GEOPOLY_ENABLE_DEBUG
  173901. static int geo_debug = 0;
  173902. # define GEODEBUG(X) if(geo_debug)printf X
  173903. #else
  173904. # define GEODEBUG(X)
  173905. #endif
  173906. #ifndef JSON_NULL /* The following stuff repeats things found in json1 */
  173907. /*
  173908. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  173909. ** to pass signed char values.
  173910. */
  173911. #ifdef sqlite3Isdigit
  173912. /* Use the SQLite core versions if this routine is part of the
  173913. ** SQLite amalgamation */
  173914. # define safe_isdigit(x) sqlite3Isdigit(x)
  173915. # define safe_isalnum(x) sqlite3Isalnum(x)
  173916. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  173917. #else
  173918. /* Use the standard library for separate compilation */
  173919. #include <ctype.h> /* amalgamator: keep */
  173920. # define safe_isdigit(x) isdigit((unsigned char)(x))
  173921. # define safe_isalnum(x) isalnum((unsigned char)(x))
  173922. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  173923. #endif
  173924. /*
  173925. ** Growing our own isspace() routine this way is twice as fast as
  173926. ** the library isspace() function.
  173927. */
  173928. static const char geopolyIsSpace[] = {
  173929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  173930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173931. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173945. };
  173946. #define safe_isspace(x) (geopolyIsSpace[(unsigned char)x])
  173947. #endif /* JSON NULL - back to original code */
  173948. /* Compiler and version */
  173949. #ifndef GCC_VERSION
  173950. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  173951. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  173952. #else
  173953. # define GCC_VERSION 0
  173954. #endif
  173955. #endif
  173956. #ifndef MSVC_VERSION
  173957. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  173958. # define MSVC_VERSION _MSC_VER
  173959. #else
  173960. # define MSVC_VERSION 0
  173961. #endif
  173962. #endif
  173963. /* Datatype for coordinates
  173964. */
  173965. typedef float GeoCoord;
  173966. /*
  173967. ** Internal representation of a polygon.
  173968. **
  173969. ** The polygon consists of a sequence of vertexes. There is a line
  173970. ** segment between each pair of vertexes, and one final segment from
  173971. ** the last vertex back to the first. (This differs from the GeoJSON
  173972. ** standard in which the final vertex is a repeat of the first.)
  173973. **
  173974. ** The polygon follows the right-hand rule. The area to the right of
  173975. ** each segment is "outside" and the area to the left is "inside".
  173976. **
  173977. ** The on-disk representation consists of a 4-byte header followed by
  173978. ** the values. The 4-byte header is:
  173979. **
  173980. ** encoding (1 byte) 0=big-endian, 1=little-endian
  173981. ** nvertex (3 bytes) Number of vertexes as a big-endian integer
  173982. **
  173983. ** Enough space is allocated for 4 coordinates, to work around over-zealous
  173984. ** warnings coming from some compiler (notably, clang). In reality, the size
  173985. ** of each GeoPoly memory allocate is adjusted as necessary so that the
  173986. ** GeoPoly.a[] array at the end is the appropriate size.
  173987. */
  173988. typedef struct GeoPoly GeoPoly;
  173989. struct GeoPoly {
  173990. int nVertex; /* Number of vertexes */
  173991. unsigned char hdr[4]; /* Header for on-disk representation */
  173992. GeoCoord a[8]; /* 2*nVertex values. X (longitude) first, then Y */
  173993. };
  173994. /* The size of a memory allocation needed for a GeoPoly object sufficient
  173995. ** to hold N coordinate pairs.
  173996. */
  173997. #define GEOPOLY_SZ(N) (sizeof(GeoPoly) + sizeof(GeoCoord)*2*((N)-4))
  173998. /* Macros to access coordinates of a GeoPoly.
  173999. ** We have to use these macros, rather than just say p->a[i] in order
  174000. ** to silence (incorrect) UBSAN warnings if the array index is too large.
  174001. */
  174002. #define GeoX(P,I) (((GeoCoord*)(P)->a)[(I)*2])
  174003. #define GeoY(P,I) (((GeoCoord*)(P)->a)[(I)*2+1])
  174004. /*
  174005. ** State of a parse of a GeoJSON input.
  174006. */
  174007. typedef struct GeoParse GeoParse;
  174008. struct GeoParse {
  174009. const unsigned char *z; /* Unparsed input */
  174010. int nVertex; /* Number of vertexes in a[] */
  174011. int nAlloc; /* Space allocated to a[] */
  174012. int nErr; /* Number of errors encountered */
  174013. GeoCoord *a; /* Array of vertexes. From sqlite3_malloc64() */
  174014. };
  174015. /* Do a 4-byte byte swap */
  174016. static void geopolySwab32(unsigned char *a){
  174017. unsigned char t = a[0];
  174018. a[0] = a[3];
  174019. a[3] = t;
  174020. t = a[1];
  174021. a[1] = a[2];
  174022. a[2] = t;
  174023. }
  174024. /* Skip whitespace. Return the next non-whitespace character. */
  174025. static char geopolySkipSpace(GeoParse *p){
  174026. while( safe_isspace(p->z[0]) ) p->z++;
  174027. return p->z[0];
  174028. }
  174029. /* Parse out a number. Write the value into *pVal if pVal!=0.
  174030. ** return non-zero on success and zero if the next token is not a number.
  174031. */
  174032. static int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){
  174033. char c = geopolySkipSpace(p);
  174034. const unsigned char *z = p->z;
  174035. int j = 0;
  174036. int seenDP = 0;
  174037. int seenE = 0;
  174038. if( c=='-' ){
  174039. j = 1;
  174040. c = z[j];
  174041. }
  174042. if( c=='0' && z[j+1]>='0' && z[j+1]<='9' ) return 0;
  174043. for(;; j++){
  174044. c = z[j];
  174045. if( safe_isdigit(c) ) continue;
  174046. if( c=='.' ){
  174047. if( z[j-1]=='-' ) return 0;
  174048. if( seenDP ) return 0;
  174049. seenDP = 1;
  174050. continue;
  174051. }
  174052. if( c=='e' || c=='E' ){
  174053. if( z[j-1]<'0' ) return 0;
  174054. if( seenE ) return -1;
  174055. seenDP = seenE = 1;
  174056. c = z[j+1];
  174057. if( c=='+' || c=='-' ){
  174058. j++;
  174059. c = z[j+1];
  174060. }
  174061. if( c<'0' || c>'9' ) return 0;
  174062. continue;
  174063. }
  174064. break;
  174065. }
  174066. if( z[j-1]<'0' ) return 0;
  174067. if( pVal ){
  174068. #ifdef SQLITE_AMALGAMATION
  174069. /* The sqlite3AtoF() routine is much much faster than atof(), if it
  174070. ** is available */
  174071. double r;
  174072. (void)sqlite3AtoF((const char*)p->z, &r, j, SQLITE_UTF8);
  174073. *pVal = r;
  174074. #else
  174075. *pVal = (GeoCoord)atof((const char*)p->z);
  174076. #endif
  174077. }
  174078. p->z += j;
  174079. return 1;
  174080. }
  174081. /*
  174082. ** If the input is a well-formed JSON array of coordinates with at least
  174083. ** four coordinates and where each coordinate is itself a two-value array,
  174084. ** then convert the JSON into a GeoPoly object and return a pointer to
  174085. ** that object.
  174086. **
  174087. ** If any error occurs, return NULL.
  174088. */
  174089. static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){
  174090. GeoParse s;
  174091. int rc = SQLITE_OK;
  174092. memset(&s, 0, sizeof(s));
  174093. s.z = z;
  174094. if( geopolySkipSpace(&s)=='[' ){
  174095. s.z++;
  174096. while( geopolySkipSpace(&s)=='[' ){
  174097. int ii = 0;
  174098. char c;
  174099. s.z++;
  174100. if( s.nVertex>=s.nAlloc ){
  174101. GeoCoord *aNew;
  174102. s.nAlloc = s.nAlloc*2 + 16;
  174103. aNew = sqlite3_realloc64(s.a, s.nAlloc*sizeof(GeoCoord)*2 );
  174104. if( aNew==0 ){
  174105. rc = SQLITE_NOMEM;
  174106. s.nErr++;
  174107. break;
  174108. }
  174109. s.a = aNew;
  174110. }
  174111. while( geopolyParseNumber(&s, ii<=1 ? &s.a[s.nVertex*2+ii] : 0) ){
  174112. ii++;
  174113. if( ii==2 ) s.nVertex++;
  174114. c = geopolySkipSpace(&s);
  174115. s.z++;
  174116. if( c==',' ) continue;
  174117. if( c==']' && ii>=2 ) break;
  174118. s.nErr++;
  174119. rc = SQLITE_ERROR;
  174120. goto parse_json_err;
  174121. }
  174122. if( geopolySkipSpace(&s)==',' ){
  174123. s.z++;
  174124. continue;
  174125. }
  174126. break;
  174127. }
  174128. if( geopolySkipSpace(&s)==']'
  174129. && s.nVertex>=4
  174130. && s.a[0]==s.a[s.nVertex*2-2]
  174131. && s.a[1]==s.a[s.nVertex*2-1]
  174132. && (s.z++, geopolySkipSpace(&s)==0)
  174133. ){
  174134. GeoPoly *pOut;
  174135. int x = 1;
  174136. s.nVertex--; /* Remove the redundant vertex at the end */
  174137. pOut = sqlite3_malloc64( GEOPOLY_SZ((sqlite3_int64)s.nVertex) );
  174138. x = 1;
  174139. if( pOut==0 ) goto parse_json_err;
  174140. pOut->nVertex = s.nVertex;
  174141. memcpy(pOut->a, s.a, s.nVertex*2*sizeof(GeoCoord));
  174142. pOut->hdr[0] = *(unsigned char*)&x;
  174143. pOut->hdr[1] = (s.nVertex>>16)&0xff;
  174144. pOut->hdr[2] = (s.nVertex>>8)&0xff;
  174145. pOut->hdr[3] = s.nVertex&0xff;
  174146. sqlite3_free(s.a);
  174147. if( pRc ) *pRc = SQLITE_OK;
  174148. return pOut;
  174149. }else{
  174150. s.nErr++;
  174151. rc = SQLITE_ERROR;
  174152. }
  174153. }
  174154. parse_json_err:
  174155. if( pRc ) *pRc = rc;
  174156. sqlite3_free(s.a);
  174157. return 0;
  174158. }
  174159. /*
  174160. ** Given a function parameter, try to interpret it as a polygon, either
  174161. ** in the binary format or JSON text. Compute a GeoPoly object and
  174162. ** return a pointer to that object. Or if the input is not a well-formed
  174163. ** polygon, put an error message in sqlite3_context and return NULL.
  174164. */
  174165. static GeoPoly *geopolyFuncParam(
  174166. sqlite3_context *pCtx, /* Context for error messages */
  174167. sqlite3_value *pVal, /* The value to decode */
  174168. int *pRc /* Write error here */
  174169. ){
  174170. GeoPoly *p = 0;
  174171. int nByte;
  174172. if( sqlite3_value_type(pVal)==SQLITE_BLOB
  174173. && (nByte = sqlite3_value_bytes(pVal))>=(4+6*sizeof(GeoCoord))
  174174. ){
  174175. const unsigned char *a = sqlite3_value_blob(pVal);
  174176. int nVertex;
  174177. nVertex = (a[1]<<16) + (a[2]<<8) + a[3];
  174178. if( (a[0]==0 || a[0]==1)
  174179. && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte
  174180. ){
  174181. p = sqlite3_malloc64( sizeof(*p) + (nVertex-1)*2*sizeof(GeoCoord) );
  174182. if( p==0 ){
  174183. if( pRc ) *pRc = SQLITE_NOMEM;
  174184. if( pCtx ) sqlite3_result_error_nomem(pCtx);
  174185. }else{
  174186. int x = 1;
  174187. p->nVertex = nVertex;
  174188. memcpy(p->hdr, a, nByte);
  174189. if( a[0] != *(unsigned char*)&x ){
  174190. int ii;
  174191. for(ii=0; ii<nVertex; ii++){
  174192. geopolySwab32((unsigned char*)&GeoX(p,ii));
  174193. geopolySwab32((unsigned char*)&GeoY(p,ii));
  174194. }
  174195. p->hdr[0] ^= 1;
  174196. }
  174197. }
  174198. }
  174199. if( pRc ) *pRc = SQLITE_OK;
  174200. return p;
  174201. }else if( sqlite3_value_type(pVal)==SQLITE_TEXT ){
  174202. const unsigned char *zJson = sqlite3_value_text(pVal);
  174203. if( zJson==0 ){
  174204. if( pRc ) *pRc = SQLITE_NOMEM;
  174205. return 0;
  174206. }
  174207. return geopolyParseJson(zJson, pRc);
  174208. }else{
  174209. if( pRc ) *pRc = SQLITE_ERROR;
  174210. return 0;
  174211. }
  174212. }
  174213. /*
  174214. ** Implementation of the geopoly_blob(X) function.
  174215. **
  174216. ** If the input is a well-formed Geopoly BLOB or JSON string
  174217. ** then return the BLOB representation of the polygon. Otherwise
  174218. ** return NULL.
  174219. */
  174220. static void geopolyBlobFunc(
  174221. sqlite3_context *context,
  174222. int argc,
  174223. sqlite3_value **argv
  174224. ){
  174225. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  174226. if( p ){
  174227. sqlite3_result_blob(context, p->hdr,
  174228. 4+8*p->nVertex, SQLITE_TRANSIENT);
  174229. sqlite3_free(p);
  174230. }
  174231. }
  174232. /*
  174233. ** SQL function: geopoly_json(X)
  174234. **
  174235. ** Interpret X as a polygon and render it as a JSON array
  174236. ** of coordinates. Or, if X is not a valid polygon, return NULL.
  174237. */
  174238. static void geopolyJsonFunc(
  174239. sqlite3_context *context,
  174240. int argc,
  174241. sqlite3_value **argv
  174242. ){
  174243. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  174244. if( p ){
  174245. sqlite3 *db = sqlite3_context_db_handle(context);
  174246. sqlite3_str *x = sqlite3_str_new(db);
  174247. int i;
  174248. sqlite3_str_append(x, "[", 1);
  174249. for(i=0; i<p->nVertex; i++){
  174250. sqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i));
  174251. }
  174252. sqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0));
  174253. sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
  174254. sqlite3_free(p);
  174255. }
  174256. }
  174257. /*
  174258. ** SQL function: geopoly_svg(X, ....)
  174259. **
  174260. ** Interpret X as a polygon and render it as a SVG <polyline>.
  174261. ** Additional arguments are added as attributes to the <polyline>.
  174262. */
  174263. static void geopolySvgFunc(
  174264. sqlite3_context *context,
  174265. int argc,
  174266. sqlite3_value **argv
  174267. ){
  174268. GeoPoly *p;
  174269. if( argc<1 ) return;
  174270. p = geopolyFuncParam(context, argv[0], 0);
  174271. if( p ){
  174272. sqlite3 *db = sqlite3_context_db_handle(context);
  174273. sqlite3_str *x = sqlite3_str_new(db);
  174274. int i;
  174275. char cSep = '\'';
  174276. sqlite3_str_appendf(x, "<polyline points=");
  174277. for(i=0; i<p->nVertex; i++){
  174278. sqlite3_str_appendf(x, "%c%g,%g", cSep, GeoX(p,i), GeoY(p,i));
  174279. cSep = ' ';
  174280. }
  174281. sqlite3_str_appendf(x, " %g,%g'", GeoX(p,0), GeoY(p,0));
  174282. for(i=1; i<argc; i++){
  174283. const char *z = (const char*)sqlite3_value_text(argv[i]);
  174284. if( z && z[0] ){
  174285. sqlite3_str_appendf(x, " %s", z);
  174286. }
  174287. }
  174288. sqlite3_str_appendf(x, "></polyline>");
  174289. sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
  174290. sqlite3_free(p);
  174291. }
  174292. }
  174293. /*
  174294. ** SQL Function: geopoly_xform(poly, A, B, C, D, E, F)
  174295. **
  174296. ** Transform and/or translate a polygon as follows:
  174297. **
  174298. ** x1 = A*x0 + B*y0 + E
  174299. ** y1 = C*x0 + D*y0 + F
  174300. **
  174301. ** For a translation:
  174302. **
  174303. ** geopoly_xform(poly, 1, 0, 0, 1, x-offset, y-offset)
  174304. **
  174305. ** Rotate by R around the point (0,0):
  174306. **
  174307. ** geopoly_xform(poly, cos(R), sin(R), -sin(R), cos(R), 0, 0)
  174308. */
  174309. static void geopolyXformFunc(
  174310. sqlite3_context *context,
  174311. int argc,
  174312. sqlite3_value **argv
  174313. ){
  174314. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  174315. double A = sqlite3_value_double(argv[1]);
  174316. double B = sqlite3_value_double(argv[2]);
  174317. double C = sqlite3_value_double(argv[3]);
  174318. double D = sqlite3_value_double(argv[4]);
  174319. double E = sqlite3_value_double(argv[5]);
  174320. double F = sqlite3_value_double(argv[6]);
  174321. GeoCoord x1, y1, x0, y0;
  174322. int ii;
  174323. if( p ){
  174324. for(ii=0; ii<p->nVertex; ii++){
  174325. x0 = GeoX(p,ii);
  174326. y0 = GeoY(p,ii);
  174327. x1 = (GeoCoord)(A*x0 + B*y0 + E);
  174328. y1 = (GeoCoord)(C*x0 + D*y0 + F);
  174329. GeoX(p,ii) = x1;
  174330. GeoY(p,ii) = y1;
  174331. }
  174332. sqlite3_result_blob(context, p->hdr,
  174333. 4+8*p->nVertex, SQLITE_TRANSIENT);
  174334. sqlite3_free(p);
  174335. }
  174336. }
  174337. /*
  174338. ** Compute the area enclosed by the polygon.
  174339. **
  174340. ** This routine can also be used to detect polygons that rotate in
  174341. ** the wrong direction. Polygons are suppose to be counter-clockwise (CCW).
  174342. ** This routine returns a negative value for clockwise (CW) polygons.
  174343. */
  174344. static double geopolyArea(GeoPoly *p){
  174345. double rArea = 0.0;
  174346. int ii;
  174347. for(ii=0; ii<p->nVertex-1; ii++){
  174348. rArea += (GeoX(p,ii) - GeoX(p,ii+1)) /* (x0 - x1) */
  174349. * (GeoY(p,ii) + GeoY(p,ii+1)) /* (y0 + y1) */
  174350. * 0.5;
  174351. }
  174352. rArea += (GeoX(p,ii) - GeoX(p,0)) /* (xN - x0) */
  174353. * (GeoY(p,ii) + GeoY(p,0)) /* (yN + y0) */
  174354. * 0.5;
  174355. return rArea;
  174356. }
  174357. /*
  174358. ** Implementation of the geopoly_area(X) function.
  174359. **
  174360. ** If the input is a well-formed Geopoly BLOB then return the area
  174361. ** enclosed by the polygon. If the polygon circulates clockwise instead
  174362. ** of counterclockwise (as it should) then return the negative of the
  174363. ** enclosed area. Otherwise return NULL.
  174364. */
  174365. static void geopolyAreaFunc(
  174366. sqlite3_context *context,
  174367. int argc,
  174368. sqlite3_value **argv
  174369. ){
  174370. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  174371. if( p ){
  174372. sqlite3_result_double(context, geopolyArea(p));
  174373. sqlite3_free(p);
  174374. }
  174375. }
  174376. /*
  174377. ** Implementation of the geopoly_ccw(X) function.
  174378. **
  174379. ** If the rotation of polygon X is clockwise (incorrect) instead of
  174380. ** counter-clockwise (the correct winding order according to RFC7946)
  174381. ** then reverse the order of the vertexes in polygon X.
  174382. **
  174383. ** In other words, this routine returns a CCW polygon regardless of the
  174384. ** winding order of its input.
  174385. **
  174386. ** Use this routine to sanitize historical inputs that that sometimes
  174387. ** contain polygons that wind in the wrong direction.
  174388. */
  174389. static void geopolyCcwFunc(
  174390. sqlite3_context *context,
  174391. int argc,
  174392. sqlite3_value **argv
  174393. ){
  174394. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  174395. if( p ){
  174396. if( geopolyArea(p)<0.0 ){
  174397. int ii, jj;
  174398. for(ii=1, jj=p->nVertex-1; ii<jj; ii++, jj--){
  174399. GeoCoord t = GeoX(p,ii);
  174400. GeoX(p,ii) = GeoX(p,jj);
  174401. GeoX(p,jj) = t;
  174402. t = GeoY(p,ii);
  174403. GeoY(p,ii) = GeoY(p,jj);
  174404. GeoY(p,jj) = t;
  174405. }
  174406. }
  174407. sqlite3_result_blob(context, p->hdr,
  174408. 4+8*p->nVertex, SQLITE_TRANSIENT);
  174409. sqlite3_free(p);
  174410. }
  174411. }
  174412. #define GEOPOLY_PI 3.1415926535897932385
  174413. /* Fast approximation for sine(X) for X between -0.5*pi and 2*pi
  174414. */
  174415. static double geopolySine(double r){
  174416. assert( r>=-0.5*GEOPOLY_PI && r<=2.0*GEOPOLY_PI );
  174417. if( r>=1.5*GEOPOLY_PI ){
  174418. r -= 2.0*GEOPOLY_PI;
  174419. }
  174420. if( r>=0.5*GEOPOLY_PI ){
  174421. return -geopolySine(r-GEOPOLY_PI);
  174422. }else{
  174423. double r2 = r*r;
  174424. double r3 = r2*r;
  174425. double r5 = r3*r2;
  174426. return 0.9996949*r - 0.1656700*r3 + 0.0075134*r5;
  174427. }
  174428. }
  174429. /*
  174430. ** Function: geopoly_regular(X,Y,R,N)
  174431. **
  174432. ** Construct a simple, convex, regular polygon centered at X, Y
  174433. ** with circumradius R and with N sides.
  174434. */
  174435. static void geopolyRegularFunc(
  174436. sqlite3_context *context,
  174437. int argc,
  174438. sqlite3_value **argv
  174439. ){
  174440. double x = sqlite3_value_double(argv[0]);
  174441. double y = sqlite3_value_double(argv[1]);
  174442. double r = sqlite3_value_double(argv[2]);
  174443. int n = sqlite3_value_int(argv[3]);
  174444. int i;
  174445. GeoPoly *p;
  174446. if( n<3 || r<=0.0 ) return;
  174447. if( n>1000 ) n = 1000;
  174448. p = sqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) );
  174449. if( p==0 ){
  174450. sqlite3_result_error_nomem(context);
  174451. return;
  174452. }
  174453. i = 1;
  174454. p->hdr[0] = *(unsigned char*)&i;
  174455. p->hdr[1] = 0;
  174456. p->hdr[2] = (n>>8)&0xff;
  174457. p->hdr[3] = n&0xff;
  174458. for(i=0; i<n; i++){
  174459. double rAngle = 2.0*GEOPOLY_PI*i/n;
  174460. GeoX(p,i) = x - r*geopolySine(rAngle-0.5*GEOPOLY_PI);
  174461. GeoY(p,i) = y + r*geopolySine(rAngle);
  174462. }
  174463. sqlite3_result_blob(context, p->hdr, 4+8*n, SQLITE_TRANSIENT);
  174464. sqlite3_free(p);
  174465. }
  174466. /*
  174467. ** If pPoly is a polygon, compute its bounding box. Then:
  174468. **
  174469. ** (1) if aCoord!=0 store the bounding box in aCoord, returning NULL
  174470. ** (2) otherwise, compute a GeoPoly for the bounding box and return the
  174471. ** new GeoPoly
  174472. **
  174473. ** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from
  174474. ** the bounding box in aCoord and return a pointer to that GeoPoly.
  174475. */
  174476. static GeoPoly *geopolyBBox(
  174477. sqlite3_context *context, /* For recording the error */
  174478. sqlite3_value *pPoly, /* The polygon */
  174479. RtreeCoord *aCoord, /* Results here */
  174480. int *pRc /* Error code here */
  174481. ){
  174482. GeoPoly *pOut = 0;
  174483. GeoPoly *p;
  174484. float mnX, mxX, mnY, mxY;
  174485. if( pPoly==0 && aCoord!=0 ){
  174486. p = 0;
  174487. mnX = aCoord[0].f;
  174488. mxX = aCoord[1].f;
  174489. mnY = aCoord[2].f;
  174490. mxY = aCoord[3].f;
  174491. goto geopolyBboxFill;
  174492. }else{
  174493. p = geopolyFuncParam(context, pPoly, pRc);
  174494. }
  174495. if( p ){
  174496. int ii;
  174497. mnX = mxX = GeoX(p,0);
  174498. mnY = mxY = GeoY(p,0);
  174499. for(ii=1; ii<p->nVertex; ii++){
  174500. double r = GeoX(p,ii);
  174501. if( r<mnX ) mnX = (float)r;
  174502. else if( r>mxX ) mxX = (float)r;
  174503. r = GeoY(p,ii);
  174504. if( r<mnY ) mnY = (float)r;
  174505. else if( r>mxY ) mxY = (float)r;
  174506. }
  174507. if( pRc ) *pRc = SQLITE_OK;
  174508. if( aCoord==0 ){
  174509. geopolyBboxFill:
  174510. pOut = sqlite3_realloc64(p, GEOPOLY_SZ(4));
  174511. if( pOut==0 ){
  174512. sqlite3_free(p);
  174513. if( context ) sqlite3_result_error_nomem(context);
  174514. if( pRc ) *pRc = SQLITE_NOMEM;
  174515. return 0;
  174516. }
  174517. pOut->nVertex = 4;
  174518. ii = 1;
  174519. pOut->hdr[0] = *(unsigned char*)&ii;
  174520. pOut->hdr[1] = 0;
  174521. pOut->hdr[2] = 0;
  174522. pOut->hdr[3] = 4;
  174523. GeoX(pOut,0) = mnX;
  174524. GeoY(pOut,0) = mnY;
  174525. GeoX(pOut,1) = mxX;
  174526. GeoY(pOut,1) = mnY;
  174527. GeoX(pOut,2) = mxX;
  174528. GeoY(pOut,2) = mxY;
  174529. GeoX(pOut,3) = mnX;
  174530. GeoY(pOut,3) = mxY;
  174531. }else{
  174532. sqlite3_free(p);
  174533. aCoord[0].f = mnX;
  174534. aCoord[1].f = mxX;
  174535. aCoord[2].f = mnY;
  174536. aCoord[3].f = mxY;
  174537. }
  174538. }
  174539. return pOut;
  174540. }
  174541. /*
  174542. ** Implementation of the geopoly_bbox(X) SQL function.
  174543. */
  174544. static void geopolyBBoxFunc(
  174545. sqlite3_context *context,
  174546. int argc,
  174547. sqlite3_value **argv
  174548. ){
  174549. GeoPoly *p = geopolyBBox(context, argv[0], 0, 0);
  174550. if( p ){
  174551. sqlite3_result_blob(context, p->hdr,
  174552. 4+8*p->nVertex, SQLITE_TRANSIENT);
  174553. sqlite3_free(p);
  174554. }
  174555. }
  174556. /*
  174557. ** State vector for the geopoly_group_bbox() aggregate function.
  174558. */
  174559. typedef struct GeoBBox GeoBBox;
  174560. struct GeoBBox {
  174561. int isInit;
  174562. RtreeCoord a[4];
  174563. };
  174564. /*
  174565. ** Implementation of the geopoly_group_bbox(X) aggregate SQL function.
  174566. */
  174567. static void geopolyBBoxStep(
  174568. sqlite3_context *context,
  174569. int argc,
  174570. sqlite3_value **argv
  174571. ){
  174572. RtreeCoord a[4];
  174573. int rc = SQLITE_OK;
  174574. (void)geopolyBBox(context, argv[0], a, &rc);
  174575. if( rc==SQLITE_OK ){
  174576. GeoBBox *pBBox;
  174577. pBBox = (GeoBBox*)sqlite3_aggregate_context(context, sizeof(*pBBox));
  174578. if( pBBox==0 ) return;
  174579. if( pBBox->isInit==0 ){
  174580. pBBox->isInit = 1;
  174581. memcpy(pBBox->a, a, sizeof(RtreeCoord)*4);
  174582. }else{
  174583. if( a[0].f < pBBox->a[0].f ) pBBox->a[0] = a[0];
  174584. if( a[1].f > pBBox->a[1].f ) pBBox->a[1] = a[1];
  174585. if( a[2].f < pBBox->a[2].f ) pBBox->a[2] = a[2];
  174586. if( a[3].f > pBBox->a[3].f ) pBBox->a[3] = a[3];
  174587. }
  174588. }
  174589. }
  174590. static void geopolyBBoxFinal(
  174591. sqlite3_context *context
  174592. ){
  174593. GeoPoly *p;
  174594. GeoBBox *pBBox;
  174595. pBBox = (GeoBBox*)sqlite3_aggregate_context(context, 0);
  174596. if( pBBox==0 ) return;
  174597. p = geopolyBBox(context, 0, pBBox->a, 0);
  174598. if( p ){
  174599. sqlite3_result_blob(context, p->hdr,
  174600. 4+8*p->nVertex, SQLITE_TRANSIENT);
  174601. sqlite3_free(p);
  174602. }
  174603. }
  174604. /*
  174605. ** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2).
  174606. ** Returns:
  174607. **
  174608. ** +2 x0,y0 is on the line segement
  174609. **
  174610. ** +1 x0,y0 is beneath line segment
  174611. **
  174612. ** 0 x0,y0 is not on or beneath the line segment or the line segment
  174613. ** is vertical and x0,y0 is not on the line segment
  174614. **
  174615. ** The left-most coordinate min(x1,x2) is not considered to be part of
  174616. ** the line segment for the purposes of this analysis.
  174617. */
  174618. static int pointBeneathLine(
  174619. double x0, double y0,
  174620. double x1, double y1,
  174621. double x2, double y2
  174622. ){
  174623. double y;
  174624. if( x0==x1 && y0==y1 ) return 2;
  174625. if( x1<x2 ){
  174626. if( x0<=x1 || x0>x2 ) return 0;
  174627. }else if( x1>x2 ){
  174628. if( x0<=x2 || x0>x1 ) return 0;
  174629. }else{
  174630. /* Vertical line segment */
  174631. if( x0!=x1 ) return 0;
  174632. if( y0<y1 && y0<y2 ) return 0;
  174633. if( y0>y1 && y0>y2 ) return 0;
  174634. return 2;
  174635. }
  174636. y = y1 + (y2-y1)*(x0-x1)/(x2-x1);
  174637. if( y0==y ) return 2;
  174638. if( y0<y ) return 1;
  174639. return 0;
  174640. }
  174641. /*
  174642. ** SQL function: geopoly_contains_point(P,X,Y)
  174643. **
  174644. ** Return +2 if point X,Y is within polygon P.
  174645. ** Return +1 if point X,Y is on the polygon boundary.
  174646. ** Return 0 if point X,Y is outside the polygon
  174647. */
  174648. static void geopolyContainsPointFunc(
  174649. sqlite3_context *context,
  174650. int argc,
  174651. sqlite3_value **argv
  174652. ){
  174653. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  174654. double x0 = sqlite3_value_double(argv[1]);
  174655. double y0 = sqlite3_value_double(argv[2]);
  174656. int v = 0;
  174657. int cnt = 0;
  174658. int ii;
  174659. if( p1==0 ) return;
  174660. for(ii=0; ii<p1->nVertex-1; ii++){
  174661. v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
  174662. GeoX(p1,ii+1),GeoY(p1,ii+1));
  174663. if( v==2 ) break;
  174664. cnt += v;
  174665. }
  174666. if( v!=2 ){
  174667. v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
  174668. GeoX(p1,0), GeoY(p1,0));
  174669. }
  174670. if( v==2 ){
  174671. sqlite3_result_int(context, 1);
  174672. }else if( ((v+cnt)&1)==0 ){
  174673. sqlite3_result_int(context, 0);
  174674. }else{
  174675. sqlite3_result_int(context, 2);
  174676. }
  174677. sqlite3_free(p1);
  174678. }
  174679. /* Forward declaration */
  174680. static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2);
  174681. /*
  174682. ** SQL function: geopoly_within(P1,P2)
  174683. **
  174684. ** Return +2 if P1 and P2 are the same polygon
  174685. ** Return +1 if P2 is contained within P1
  174686. ** Return 0 if any part of P2 is on the outside of P1
  174687. **
  174688. */
  174689. static void geopolyWithinFunc(
  174690. sqlite3_context *context,
  174691. int argc,
  174692. sqlite3_value **argv
  174693. ){
  174694. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  174695. GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
  174696. if( p1 && p2 ){
  174697. int x = geopolyOverlap(p1, p2);
  174698. if( x<0 ){
  174699. sqlite3_result_error_nomem(context);
  174700. }else{
  174701. sqlite3_result_int(context, x==2 ? 1 : x==4 ? 2 : 0);
  174702. }
  174703. }
  174704. sqlite3_free(p1);
  174705. sqlite3_free(p2);
  174706. }
  174707. /* Objects used by the overlap algorihm. */
  174708. typedef struct GeoEvent GeoEvent;
  174709. typedef struct GeoSegment GeoSegment;
  174710. typedef struct GeoOverlap GeoOverlap;
  174711. struct GeoEvent {
  174712. double x; /* X coordinate at which event occurs */
  174713. int eType; /* 0 for ADD, 1 for REMOVE */
  174714. GeoSegment *pSeg; /* The segment to be added or removed */
  174715. GeoEvent *pNext; /* Next event in the sorted list */
  174716. };
  174717. struct GeoSegment {
  174718. double C, B; /* y = C*x + B */
  174719. double y; /* Current y value */
  174720. float y0; /* Initial y value */
  174721. unsigned char side; /* 1 for p1, 2 for p2 */
  174722. unsigned int idx; /* Which segment within the side */
  174723. GeoSegment *pNext; /* Next segment in a list sorted by y */
  174724. };
  174725. struct GeoOverlap {
  174726. GeoEvent *aEvent; /* Array of all events */
  174727. GeoSegment *aSegment; /* Array of all segments */
  174728. int nEvent; /* Number of events */
  174729. int nSegment; /* Number of segments */
  174730. };
  174731. /*
  174732. ** Add a single segment and its associated events.
  174733. */
  174734. static void geopolyAddOneSegment(
  174735. GeoOverlap *p,
  174736. GeoCoord x0,
  174737. GeoCoord y0,
  174738. GeoCoord x1,
  174739. GeoCoord y1,
  174740. unsigned char side,
  174741. unsigned int idx
  174742. ){
  174743. GeoSegment *pSeg;
  174744. GeoEvent *pEvent;
  174745. if( x0==x1 ) return; /* Ignore vertical segments */
  174746. if( x0>x1 ){
  174747. GeoCoord t = x0;
  174748. x0 = x1;
  174749. x1 = t;
  174750. t = y0;
  174751. y0 = y1;
  174752. y1 = t;
  174753. }
  174754. pSeg = p->aSegment + p->nSegment;
  174755. p->nSegment++;
  174756. pSeg->C = (y1-y0)/(x1-x0);
  174757. pSeg->B = y1 - x1*pSeg->C;
  174758. pSeg->y0 = y0;
  174759. pSeg->side = side;
  174760. pSeg->idx = idx;
  174761. pEvent = p->aEvent + p->nEvent;
  174762. p->nEvent++;
  174763. pEvent->x = x0;
  174764. pEvent->eType = 0;
  174765. pEvent->pSeg = pSeg;
  174766. pEvent = p->aEvent + p->nEvent;
  174767. p->nEvent++;
  174768. pEvent->x = x1;
  174769. pEvent->eType = 1;
  174770. pEvent->pSeg = pSeg;
  174771. }
  174772. /*
  174773. ** Insert all segments and events for polygon pPoly.
  174774. */
  174775. static void geopolyAddSegments(
  174776. GeoOverlap *p, /* Add segments to this Overlap object */
  174777. GeoPoly *pPoly, /* Take all segments from this polygon */
  174778. unsigned char side /* The side of pPoly */
  174779. ){
  174780. unsigned int i;
  174781. GeoCoord *x;
  174782. for(i=0; i<(unsigned)pPoly->nVertex-1; i++){
  174783. x = &GeoX(pPoly,i);
  174784. geopolyAddOneSegment(p, x[0], x[1], x[2], x[3], side, i);
  174785. }
  174786. x = &GeoX(pPoly,i);
  174787. geopolyAddOneSegment(p, x[0], x[1], pPoly->a[0], pPoly->a[1], side, i);
  174788. }
  174789. /*
  174790. ** Merge two lists of sorted events by X coordinate
  174791. */
  174792. static GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){
  174793. GeoEvent head, *pLast;
  174794. head.pNext = 0;
  174795. pLast = &head;
  174796. while( pRight && pLeft ){
  174797. if( pRight->x <= pLeft->x ){
  174798. pLast->pNext = pRight;
  174799. pLast = pRight;
  174800. pRight = pRight->pNext;
  174801. }else{
  174802. pLast->pNext = pLeft;
  174803. pLast = pLeft;
  174804. pLeft = pLeft->pNext;
  174805. }
  174806. }
  174807. pLast->pNext = pRight ? pRight : pLeft;
  174808. return head.pNext;
  174809. }
  174810. /*
  174811. ** Sort an array of nEvent event objects into a list.
  174812. */
  174813. static GeoEvent *geopolySortEventsByX(GeoEvent *aEvent, int nEvent){
  174814. int mx = 0;
  174815. int i, j;
  174816. GeoEvent *p;
  174817. GeoEvent *a[50];
  174818. for(i=0; i<nEvent; i++){
  174819. p = &aEvent[i];
  174820. p->pNext = 0;
  174821. for(j=0; j<mx && a[j]; j++){
  174822. p = geopolyEventMerge(a[j], p);
  174823. a[j] = 0;
  174824. }
  174825. a[j] = p;
  174826. if( j>=mx ) mx = j+1;
  174827. }
  174828. p = 0;
  174829. for(i=0; i<mx; i++){
  174830. p = geopolyEventMerge(a[i], p);
  174831. }
  174832. return p;
  174833. }
  174834. /*
  174835. ** Merge two lists of sorted segments by Y, and then by C.
  174836. */
  174837. static GeoSegment *geopolySegmentMerge(GeoSegment *pLeft, GeoSegment *pRight){
  174838. GeoSegment head, *pLast;
  174839. head.pNext = 0;
  174840. pLast = &head;
  174841. while( pRight && pLeft ){
  174842. double r = pRight->y - pLeft->y;
  174843. if( r==0.0 ) r = pRight->C - pLeft->C;
  174844. if( r<0.0 ){
  174845. pLast->pNext = pRight;
  174846. pLast = pRight;
  174847. pRight = pRight->pNext;
  174848. }else{
  174849. pLast->pNext = pLeft;
  174850. pLast = pLeft;
  174851. pLeft = pLeft->pNext;
  174852. }
  174853. }
  174854. pLast->pNext = pRight ? pRight : pLeft;
  174855. return head.pNext;
  174856. }
  174857. /*
  174858. ** Sort a list of GeoSegments in order of increasing Y and in the event of
  174859. ** a tie, increasing C (slope).
  174860. */
  174861. static GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){
  174862. int mx = 0;
  174863. int i;
  174864. GeoSegment *p;
  174865. GeoSegment *a[50];
  174866. while( pList ){
  174867. p = pList;
  174868. pList = pList->pNext;
  174869. p->pNext = 0;
  174870. for(i=0; i<mx && a[i]; i++){
  174871. p = geopolySegmentMerge(a[i], p);
  174872. a[i] = 0;
  174873. }
  174874. a[i] = p;
  174875. if( i>=mx ) mx = i+1;
  174876. }
  174877. p = 0;
  174878. for(i=0; i<mx; i++){
  174879. p = geopolySegmentMerge(a[i], p);
  174880. }
  174881. return p;
  174882. }
  174883. /*
  174884. ** Determine the overlap between two polygons
  174885. */
  174886. static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){
  174887. sqlite3_int64 nVertex = p1->nVertex + p2->nVertex + 2;
  174888. GeoOverlap *p;
  174889. sqlite3_int64 nByte;
  174890. GeoEvent *pThisEvent;
  174891. double rX;
  174892. int rc = 0;
  174893. int needSort = 0;
  174894. GeoSegment *pActive = 0;
  174895. GeoSegment *pSeg;
  174896. unsigned char aOverlap[4];
  174897. nByte = sizeof(GeoEvent)*nVertex*2
  174898. + sizeof(GeoSegment)*nVertex
  174899. + sizeof(GeoOverlap);
  174900. p = sqlite3_malloc64( nByte );
  174901. if( p==0 ) return -1;
  174902. p->aEvent = (GeoEvent*)&p[1];
  174903. p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2];
  174904. p->nEvent = p->nSegment = 0;
  174905. geopolyAddSegments(p, p1, 1);
  174906. geopolyAddSegments(p, p2, 2);
  174907. pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent);
  174908. rX = pThisEvent->x==0.0 ? -1.0 : 0.0;
  174909. memset(aOverlap, 0, sizeof(aOverlap));
  174910. while( pThisEvent ){
  174911. if( pThisEvent->x!=rX ){
  174912. GeoSegment *pPrev = 0;
  174913. int iMask = 0;
  174914. GEODEBUG(("Distinct X: %g\n", pThisEvent->x));
  174915. rX = pThisEvent->x;
  174916. if( needSort ){
  174917. GEODEBUG(("SORT\n"));
  174918. pActive = geopolySortSegmentsByYAndC(pActive);
  174919. needSort = 0;
  174920. }
  174921. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  174922. if( pPrev ){
  174923. if( pPrev->y!=pSeg->y ){
  174924. GEODEBUG(("MASK: %d\n", iMask));
  174925. aOverlap[iMask] = 1;
  174926. }
  174927. }
  174928. iMask ^= pSeg->side;
  174929. pPrev = pSeg;
  174930. }
  174931. pPrev = 0;
  174932. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  174933. double y = pSeg->C*rX + pSeg->B;
  174934. GEODEBUG(("Segment %d.%d %g->%g\n", pSeg->side, pSeg->idx, pSeg->y, y));
  174935. pSeg->y = y;
  174936. if( pPrev ){
  174937. if( pPrev->y>pSeg->y && pPrev->side!=pSeg->side ){
  174938. rc = 1;
  174939. GEODEBUG(("Crossing: %d.%d and %d.%d\n",
  174940. pPrev->side, pPrev->idx,
  174941. pSeg->side, pSeg->idx));
  174942. goto geopolyOverlapDone;
  174943. }else if( pPrev->y!=pSeg->y ){
  174944. GEODEBUG(("MASK: %d\n", iMask));
  174945. aOverlap[iMask] = 1;
  174946. }
  174947. }
  174948. iMask ^= pSeg->side;
  174949. pPrev = pSeg;
  174950. }
  174951. }
  174952. GEODEBUG(("%s %d.%d C=%g B=%g\n",
  174953. pThisEvent->eType ? "RM " : "ADD",
  174954. pThisEvent->pSeg->side, pThisEvent->pSeg->idx,
  174955. pThisEvent->pSeg->C,
  174956. pThisEvent->pSeg->B));
  174957. if( pThisEvent->eType==0 ){
  174958. /* Add a segment */
  174959. pSeg = pThisEvent->pSeg;
  174960. pSeg->y = pSeg->y0;
  174961. pSeg->pNext = pActive;
  174962. pActive = pSeg;
  174963. needSort = 1;
  174964. }else{
  174965. /* Remove a segment */
  174966. if( pActive==pThisEvent->pSeg ){
  174967. pActive = pActive->pNext;
  174968. }else{
  174969. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  174970. if( pSeg->pNext==pThisEvent->pSeg ){
  174971. pSeg->pNext = pSeg->pNext->pNext;
  174972. break;
  174973. }
  174974. }
  174975. }
  174976. }
  174977. pThisEvent = pThisEvent->pNext;
  174978. }
  174979. if( aOverlap[3]==0 ){
  174980. rc = 0;
  174981. }else if( aOverlap[1]!=0 && aOverlap[2]==0 ){
  174982. rc = 3;
  174983. }else if( aOverlap[1]==0 && aOverlap[2]!=0 ){
  174984. rc = 2;
  174985. }else if( aOverlap[1]==0 && aOverlap[2]==0 ){
  174986. rc = 4;
  174987. }else{
  174988. rc = 1;
  174989. }
  174990. geopolyOverlapDone:
  174991. sqlite3_free(p);
  174992. return rc;
  174993. }
  174994. /*
  174995. ** SQL function: geopoly_overlap(P1,P2)
  174996. **
  174997. ** Determine whether or not P1 and P2 overlap. Return value:
  174998. **
  174999. ** 0 The two polygons are disjoint
  175000. ** 1 They overlap
  175001. ** 2 P1 is completely contained within P2
  175002. ** 3 P2 is completely contained within P1
  175003. ** 4 P1 and P2 are the same polygon
  175004. ** NULL Either P1 or P2 or both are not valid polygons
  175005. */
  175006. static void geopolyOverlapFunc(
  175007. sqlite3_context *context,
  175008. int argc,
  175009. sqlite3_value **argv
  175010. ){
  175011. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  175012. GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
  175013. if( p1 && p2 ){
  175014. int x = geopolyOverlap(p1, p2);
  175015. if( x<0 ){
  175016. sqlite3_result_error_nomem(context);
  175017. }else{
  175018. sqlite3_result_int(context, x);
  175019. }
  175020. }
  175021. sqlite3_free(p1);
  175022. sqlite3_free(p2);
  175023. }
  175024. /*
  175025. ** Enable or disable debugging output
  175026. */
  175027. static void geopolyDebugFunc(
  175028. sqlite3_context *context,
  175029. int argc,
  175030. sqlite3_value **argv
  175031. ){
  175032. #ifdef GEOPOLY_ENABLE_DEBUG
  175033. geo_debug = sqlite3_value_int(argv[0]);
  175034. #endif
  175035. }
  175036. /*
  175037. ** This function is the implementation of both the xConnect and xCreate
  175038. ** methods of the geopoly virtual table.
  175039. **
  175040. ** argv[0] -> module name
  175041. ** argv[1] -> database name
  175042. ** argv[2] -> table name
  175043. ** argv[...] -> column names...
  175044. */
  175045. static int geopolyInit(
  175046. sqlite3 *db, /* Database connection */
  175047. void *pAux, /* One of the RTREE_COORD_* constants */
  175048. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  175049. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  175050. char **pzErr, /* OUT: Error message, if any */
  175051. int isCreate /* True for xCreate, false for xConnect */
  175052. ){
  175053. int rc = SQLITE_OK;
  175054. Rtree *pRtree;
  175055. sqlite3_int64 nDb; /* Length of string argv[1] */
  175056. sqlite3_int64 nName; /* Length of string argv[2] */
  175057. sqlite3_str *pSql;
  175058. char *zSql;
  175059. int ii;
  175060. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  175061. /* Allocate the sqlite3_vtab structure */
  175062. nDb = strlen(argv[1]);
  175063. nName = strlen(argv[2]);
  175064. pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
  175065. if( !pRtree ){
  175066. return SQLITE_NOMEM;
  175067. }
  175068. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  175069. pRtree->nBusy = 1;
  175070. pRtree->base.pModule = &rtreeModule;
  175071. pRtree->zDb = (char *)&pRtree[1];
  175072. pRtree->zName = &pRtree->zDb[nDb+1];
  175073. pRtree->eCoordType = RTREE_COORD_REAL32;
  175074. pRtree->nDim = 2;
  175075. pRtree->nDim2 = 4;
  175076. memcpy(pRtree->zDb, argv[1], nDb);
  175077. memcpy(pRtree->zName, argv[2], nName);
  175078. /* Create/Connect to the underlying relational database schema. If
  175079. ** that is successful, call sqlite3_declare_vtab() to configure
  175080. ** the r-tree table schema.
  175081. */
  175082. pSql = sqlite3_str_new(db);
  175083. sqlite3_str_appendf(pSql, "CREATE TABLE x(_shape");
  175084. pRtree->nAux = 1; /* Add one for _shape */
  175085. pRtree->nAuxNotNull = 1; /* The _shape column is always not-null */
  175086. for(ii=3; ii<argc; ii++){
  175087. pRtree->nAux++;
  175088. sqlite3_str_appendf(pSql, ",%s", argv[ii]);
  175089. }
  175090. sqlite3_str_appendf(pSql, ");");
  175091. zSql = sqlite3_str_finish(pSql);
  175092. if( !zSql ){
  175093. rc = SQLITE_NOMEM;
  175094. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  175095. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  175096. }
  175097. sqlite3_free(zSql);
  175098. if( rc ) goto geopolyInit_fail;
  175099. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  175100. /* Figure out the node size to use. */
  175101. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  175102. if( rc ) goto geopolyInit_fail;
  175103. rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
  175104. if( rc ){
  175105. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  175106. goto geopolyInit_fail;
  175107. }
  175108. *ppVtab = (sqlite3_vtab *)pRtree;
  175109. return SQLITE_OK;
  175110. geopolyInit_fail:
  175111. if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
  175112. assert( *ppVtab==0 );
  175113. assert( pRtree->nBusy==1 );
  175114. rtreeRelease(pRtree);
  175115. return rc;
  175116. }
  175117. /*
  175118. ** GEOPOLY virtual table module xCreate method.
  175119. */
  175120. static int geopolyCreate(
  175121. sqlite3 *db,
  175122. void *pAux,
  175123. int argc, const char *const*argv,
  175124. sqlite3_vtab **ppVtab,
  175125. char **pzErr
  175126. ){
  175127. return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  175128. }
  175129. /*
  175130. ** GEOPOLY virtual table module xConnect method.
  175131. */
  175132. static int geopolyConnect(
  175133. sqlite3 *db,
  175134. void *pAux,
  175135. int argc, const char *const*argv,
  175136. sqlite3_vtab **ppVtab,
  175137. char **pzErr
  175138. ){
  175139. return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  175140. }
  175141. /*
  175142. ** GEOPOLY virtual table module xFilter method.
  175143. **
  175144. ** Query plans:
  175145. **
  175146. ** 1 rowid lookup
  175147. ** 2 search for objects overlapping the same bounding box
  175148. ** that contains polygon argv[0]
  175149. ** 3 search for objects overlapping the same bounding box
  175150. ** that contains polygon argv[0]
  175151. ** 4 full table scan
  175152. */
  175153. static int geopolyFilter(
  175154. sqlite3_vtab_cursor *pVtabCursor, /* The cursor to initialize */
  175155. int idxNum, /* Query plan */
  175156. const char *idxStr, /* Not Used */
  175157. int argc, sqlite3_value **argv /* Parameters to the query plan */
  175158. ){
  175159. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  175160. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  175161. RtreeNode *pRoot = 0;
  175162. int rc = SQLITE_OK;
  175163. int iCell = 0;
  175164. sqlite3_stmt *pStmt;
  175165. rtreeReference(pRtree);
  175166. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  175167. freeCursorConstraints(pCsr);
  175168. sqlite3_free(pCsr->aPoint);
  175169. pStmt = pCsr->pReadAux;
  175170. memset(pCsr, 0, sizeof(RtreeCursor));
  175171. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  175172. pCsr->pReadAux = pStmt;
  175173. pCsr->iStrategy = idxNum;
  175174. if( idxNum==1 ){
  175175. /* Special case - lookup by rowid. */
  175176. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  175177. RtreeSearchPoint *p; /* Search point for the leaf */
  175178. i64 iRowid = sqlite3_value_int64(argv[0]);
  175179. i64 iNode = 0;
  175180. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  175181. if( rc==SQLITE_OK && pLeaf!=0 ){
  175182. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  175183. assert( p!=0 ); /* Always returns pCsr->sPoint */
  175184. pCsr->aNode[0] = pLeaf;
  175185. p->id = iNode;
  175186. p->eWithin = PARTLY_WITHIN;
  175187. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  175188. p->iCell = (u8)iCell;
  175189. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  175190. }else{
  175191. pCsr->atEOF = 1;
  175192. }
  175193. }else{
  175194. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  175195. ** with the configured constraints.
  175196. */
  175197. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  175198. if( rc==SQLITE_OK && idxNum<=3 ){
  175199. RtreeCoord bbox[4];
  175200. RtreeConstraint *p;
  175201. assert( argc==1 );
  175202. geopolyBBox(0, argv[0], bbox, &rc);
  175203. if( rc ){
  175204. goto geopoly_filter_end;
  175205. }
  175206. pCsr->aConstraint = p = sqlite3_malloc(sizeof(RtreeConstraint)*4);
  175207. pCsr->nConstraint = 4;
  175208. if( p==0 ){
  175209. rc = SQLITE_NOMEM;
  175210. }else{
  175211. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*4);
  175212. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  175213. if( idxNum==2 ){
  175214. /* Overlap query */
  175215. p->op = 'B';
  175216. p->iCoord = 0;
  175217. p->u.rValue = bbox[1].f;
  175218. p++;
  175219. p->op = 'D';
  175220. p->iCoord = 1;
  175221. p->u.rValue = bbox[0].f;
  175222. p++;
  175223. p->op = 'B';
  175224. p->iCoord = 2;
  175225. p->u.rValue = bbox[3].f;
  175226. p++;
  175227. p->op = 'D';
  175228. p->iCoord = 3;
  175229. p->u.rValue = bbox[2].f;
  175230. }else{
  175231. /* Within query */
  175232. p->op = 'D';
  175233. p->iCoord = 0;
  175234. p->u.rValue = bbox[0].f;
  175235. p++;
  175236. p->op = 'B';
  175237. p->iCoord = 1;
  175238. p->u.rValue = bbox[1].f;
  175239. p++;
  175240. p->op = 'D';
  175241. p->iCoord = 2;
  175242. p->u.rValue = bbox[2].f;
  175243. p++;
  175244. p->op = 'B';
  175245. p->iCoord = 3;
  175246. p->u.rValue = bbox[3].f;
  175247. }
  175248. }
  175249. }
  175250. if( rc==SQLITE_OK ){
  175251. RtreeSearchPoint *pNew;
  175252. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  175253. if( pNew==0 ){
  175254. rc = SQLITE_NOMEM;
  175255. goto geopoly_filter_end;
  175256. }
  175257. pNew->id = 1;
  175258. pNew->iCell = 0;
  175259. pNew->eWithin = PARTLY_WITHIN;
  175260. assert( pCsr->bPoint==1 );
  175261. pCsr->aNode[0] = pRoot;
  175262. pRoot = 0;
  175263. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  175264. rc = rtreeStepToLeaf(pCsr);
  175265. }
  175266. }
  175267. geopoly_filter_end:
  175268. nodeRelease(pRtree, pRoot);
  175269. rtreeRelease(pRtree);
  175270. return rc;
  175271. }
  175272. /*
  175273. ** Rtree virtual table module xBestIndex method. There are three
  175274. ** table scan strategies to choose from (in order from most to
  175275. ** least desirable):
  175276. **
  175277. ** idxNum idxStr Strategy
  175278. ** ------------------------------------------------
  175279. ** 1 "rowid" Direct lookup by rowid.
  175280. ** 2 "rtree" R-tree overlap query using geopoly_overlap()
  175281. ** 3 "rtree" R-tree within query using geopoly_within()
  175282. ** 4 "fullscan" full-table scan.
  175283. ** ------------------------------------------------
  175284. */
  175285. static int geopolyBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  175286. int ii;
  175287. int iRowidTerm = -1;
  175288. int iFuncTerm = -1;
  175289. int idxNum = 0;
  175290. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  175291. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  175292. if( !p->usable ) continue;
  175293. if( p->iColumn<0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  175294. iRowidTerm = ii;
  175295. break;
  175296. }
  175297. if( p->iColumn==0 && p->op>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
  175298. /* p->op==SQLITE_INDEX_CONSTRAINT_FUNCTION for geopoly_overlap()
  175299. ** p->op==(SQLITE_INDEX_CONTRAINT_FUNCTION+1) for geopoly_within().
  175300. ** See geopolyFindFunction() */
  175301. iFuncTerm = ii;
  175302. idxNum = p->op - SQLITE_INDEX_CONSTRAINT_FUNCTION + 2;
  175303. }
  175304. }
  175305. if( iRowidTerm>=0 ){
  175306. pIdxInfo->idxNum = 1;
  175307. pIdxInfo->idxStr = "rowid";
  175308. pIdxInfo->aConstraintUsage[iRowidTerm].argvIndex = 1;
  175309. pIdxInfo->aConstraintUsage[iRowidTerm].omit = 1;
  175310. pIdxInfo->estimatedCost = 30.0;
  175311. pIdxInfo->estimatedRows = 1;
  175312. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  175313. return SQLITE_OK;
  175314. }
  175315. if( iFuncTerm>=0 ){
  175316. pIdxInfo->idxNum = idxNum;
  175317. pIdxInfo->idxStr = "rtree";
  175318. pIdxInfo->aConstraintUsage[iFuncTerm].argvIndex = 1;
  175319. pIdxInfo->aConstraintUsage[iFuncTerm].omit = 0;
  175320. pIdxInfo->estimatedCost = 300.0;
  175321. pIdxInfo->estimatedRows = 10;
  175322. return SQLITE_OK;
  175323. }
  175324. pIdxInfo->idxNum = 4;
  175325. pIdxInfo->idxStr = "fullscan";
  175326. pIdxInfo->estimatedCost = 3000000.0;
  175327. pIdxInfo->estimatedRows = 100000;
  175328. return SQLITE_OK;
  175329. }
  175330. /*
  175331. ** GEOPOLY virtual table module xColumn method.
  175332. */
  175333. static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  175334. Rtree *pRtree = (Rtree *)cur->pVtab;
  175335. RtreeCursor *pCsr = (RtreeCursor *)cur;
  175336. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  175337. int rc = SQLITE_OK;
  175338. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  175339. if( rc ) return rc;
  175340. if( p==0 ) return SQLITE_OK;
  175341. if( i==0 && sqlite3_vtab_nochange(ctx) ) return SQLITE_OK;
  175342. if( i<=pRtree->nAux ){
  175343. if( !pCsr->bAuxValid ){
  175344. if( pCsr->pReadAux==0 ){
  175345. rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
  175346. &pCsr->pReadAux, 0);
  175347. if( rc ) return rc;
  175348. }
  175349. sqlite3_bind_int64(pCsr->pReadAux, 1,
  175350. nodeGetRowid(pRtree, pNode, p->iCell));
  175351. rc = sqlite3_step(pCsr->pReadAux);
  175352. if( rc==SQLITE_ROW ){
  175353. pCsr->bAuxValid = 1;
  175354. }else{
  175355. sqlite3_reset(pCsr->pReadAux);
  175356. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  175357. return rc;
  175358. }
  175359. }
  175360. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pReadAux, i+2));
  175361. }
  175362. return SQLITE_OK;
  175363. }
  175364. /*
  175365. ** The xUpdate method for GEOPOLY module virtual tables.
  175366. **
  175367. ** For DELETE:
  175368. **
  175369. ** argv[0] = the rowid to be deleted
  175370. **
  175371. ** For INSERT:
  175372. **
  175373. ** argv[0] = SQL NULL
  175374. ** argv[1] = rowid to insert, or an SQL NULL to select automatically
  175375. ** argv[2] = _shape column
  175376. ** argv[3] = first application-defined column....
  175377. **
  175378. ** For UPDATE:
  175379. **
  175380. ** argv[0] = rowid to modify. Never NULL
  175381. ** argv[1] = rowid after the change. Never NULL
  175382. ** argv[2] = new value for _shape
  175383. ** argv[3] = new value for first application-defined column....
  175384. */
  175385. static int geopolyUpdate(
  175386. sqlite3_vtab *pVtab,
  175387. int nData,
  175388. sqlite3_value **aData,
  175389. sqlite_int64 *pRowid
  175390. ){
  175391. Rtree *pRtree = (Rtree *)pVtab;
  175392. int rc = SQLITE_OK;
  175393. RtreeCell cell; /* New cell to insert if nData>1 */
  175394. i64 oldRowid; /* The old rowid */
  175395. int oldRowidValid; /* True if oldRowid is valid */
  175396. i64 newRowid; /* The new rowid */
  175397. int newRowidValid; /* True if newRowid is valid */
  175398. int coordChange = 0; /* Change in coordinates */
  175399. if( pRtree->nNodeRef ){
  175400. /* Unable to write to the btree while another cursor is reading from it,
  175401. ** since the write might do a rebalance which would disrupt the read
  175402. ** cursor. */
  175403. return SQLITE_LOCKED_VTAB;
  175404. }
  175405. rtreeReference(pRtree);
  175406. assert(nData>=1);
  175407. oldRowidValid = sqlite3_value_type(aData[0])!=SQLITE_NULL;;
  175408. oldRowid = oldRowidValid ? sqlite3_value_int64(aData[0]) : 0;
  175409. newRowidValid = nData>1 && sqlite3_value_type(aData[1])!=SQLITE_NULL;
  175410. newRowid = newRowidValid ? sqlite3_value_int64(aData[1]) : 0;
  175411. cell.iRowid = newRowid;
  175412. if( nData>1 /* not a DELETE */
  175413. && (!oldRowidValid /* INSERT */
  175414. || !sqlite3_value_nochange(aData[2]) /* UPDATE _shape */
  175415. || oldRowid!=newRowid) /* Rowid change */
  175416. ){
  175417. geopolyBBox(0, aData[2], cell.aCoord, &rc);
  175418. if( rc ){
  175419. if( rc==SQLITE_ERROR ){
  175420. pVtab->zErrMsg =
  175421. sqlite3_mprintf("_shape does not contain a valid polygon");
  175422. }
  175423. goto geopoly_update_end;
  175424. }
  175425. coordChange = 1;
  175426. /* If a rowid value was supplied, check if it is already present in
  175427. ** the table. If so, the constraint has failed. */
  175428. if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){
  175429. int steprc;
  175430. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  175431. steprc = sqlite3_step(pRtree->pReadRowid);
  175432. rc = sqlite3_reset(pRtree->pReadRowid);
  175433. if( SQLITE_ROW==steprc ){
  175434. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  175435. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  175436. }else{
  175437. rc = rtreeConstraintError(pRtree, 0);
  175438. }
  175439. }
  175440. }
  175441. }
  175442. /* If aData[0] is not an SQL NULL value, it is the rowid of a
  175443. ** record to delete from the r-tree table. The following block does
  175444. ** just that.
  175445. */
  175446. if( rc==SQLITE_OK && (nData==1 || (coordChange && oldRowidValid)) ){
  175447. rc = rtreeDeleteRowid(pRtree, oldRowid);
  175448. }
  175449. /* If the aData[] array contains more than one element, elements
  175450. ** (aData[2]..aData[argc-1]) contain a new record to insert into
  175451. ** the r-tree structure.
  175452. */
  175453. if( rc==SQLITE_OK && nData>1 && coordChange ){
  175454. /* Insert the new record into the r-tree */
  175455. RtreeNode *pLeaf = 0;
  175456. if( !newRowidValid ){
  175457. rc = rtreeNewRowid(pRtree, &cell.iRowid);
  175458. }
  175459. *pRowid = cell.iRowid;
  175460. if( rc==SQLITE_OK ){
  175461. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  175462. }
  175463. if( rc==SQLITE_OK ){
  175464. int rc2;
  175465. pRtree->iReinsertHeight = -1;
  175466. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  175467. rc2 = nodeRelease(pRtree, pLeaf);
  175468. if( rc==SQLITE_OK ){
  175469. rc = rc2;
  175470. }
  175471. }
  175472. }
  175473. /* Change the data */
  175474. if( rc==SQLITE_OK && nData>1 ){
  175475. sqlite3_stmt *pUp = pRtree->pWriteAux;
  175476. int jj;
  175477. int nChange = 0;
  175478. sqlite3_bind_int64(pUp, 1, cell.iRowid);
  175479. assert( pRtree->nAux>=1 );
  175480. if( sqlite3_value_nochange(aData[2]) ){
  175481. sqlite3_bind_null(pUp, 2);
  175482. }else{
  175483. GeoPoly *p = 0;
  175484. if( sqlite3_value_type(aData[2])==SQLITE_TEXT
  175485. && (p = geopolyFuncParam(0, aData[2], &rc))!=0
  175486. && rc==SQLITE_OK
  175487. ){
  175488. sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT);
  175489. }else{
  175490. sqlite3_bind_value(pUp, 2, aData[2]);
  175491. }
  175492. sqlite3_free(p);
  175493. nChange = 1;
  175494. }
  175495. for(jj=1; jj<pRtree->nAux; jj++){
  175496. nChange++;
  175497. sqlite3_bind_value(pUp, jj+2, aData[jj+2]);
  175498. }
  175499. if( nChange ){
  175500. sqlite3_step(pUp);
  175501. rc = sqlite3_reset(pUp);
  175502. }
  175503. }
  175504. geopoly_update_end:
  175505. rtreeRelease(pRtree);
  175506. return rc;
  175507. }
  175508. /*
  175509. ** Report that geopoly_overlap() is an overloaded function suitable
  175510. ** for use in xBestIndex.
  175511. */
  175512. static int geopolyFindFunction(
  175513. sqlite3_vtab *pVtab,
  175514. int nArg,
  175515. const char *zName,
  175516. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  175517. void **ppArg
  175518. ){
  175519. if( sqlite3_stricmp(zName, "geopoly_overlap")==0 ){
  175520. *pxFunc = geopolyOverlapFunc;
  175521. *ppArg = 0;
  175522. return SQLITE_INDEX_CONSTRAINT_FUNCTION;
  175523. }
  175524. if( sqlite3_stricmp(zName, "geopoly_within")==0 ){
  175525. *pxFunc = geopolyWithinFunc;
  175526. *ppArg = 0;
  175527. return SQLITE_INDEX_CONSTRAINT_FUNCTION+1;
  175528. }
  175529. return 0;
  175530. }
  175531. static sqlite3_module geopolyModule = {
  175532. 3, /* iVersion */
  175533. geopolyCreate, /* xCreate - create a table */
  175534. geopolyConnect, /* xConnect - connect to an existing table */
  175535. geopolyBestIndex, /* xBestIndex - Determine search strategy */
  175536. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  175537. rtreeDestroy, /* xDestroy - Drop a table */
  175538. rtreeOpen, /* xOpen - open a cursor */
  175539. rtreeClose, /* xClose - close a cursor */
  175540. geopolyFilter, /* xFilter - configure scan constraints */
  175541. rtreeNext, /* xNext - advance a cursor */
  175542. rtreeEof, /* xEof */
  175543. geopolyColumn, /* xColumn - read data */
  175544. rtreeRowid, /* xRowid - read data */
  175545. geopolyUpdate, /* xUpdate - write data */
  175546. rtreeBeginTransaction, /* xBegin - begin transaction */
  175547. rtreeEndTransaction, /* xSync - sync transaction */
  175548. rtreeEndTransaction, /* xCommit - commit transaction */
  175549. rtreeEndTransaction, /* xRollback - rollback transaction */
  175550. geopolyFindFunction, /* xFindFunction - function overloading */
  175551. rtreeRename, /* xRename - rename the table */
  175552. rtreeSavepoint, /* xSavepoint */
  175553. 0, /* xRelease */
  175554. 0, /* xRollbackTo */
  175555. rtreeShadowName /* xShadowName */
  175556. };
  175557. static int sqlite3_geopoly_init(sqlite3 *db){
  175558. int rc = SQLITE_OK;
  175559. static const struct {
  175560. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  175561. signed char nArg;
  175562. unsigned char bPure;
  175563. const char *zName;
  175564. } aFunc[] = {
  175565. { geopolyAreaFunc, 1, 1, "geopoly_area" },
  175566. { geopolyBlobFunc, 1, 1, "geopoly_blob" },
  175567. { geopolyJsonFunc, 1, 1, "geopoly_json" },
  175568. { geopolySvgFunc, -1, 1, "geopoly_svg" },
  175569. { geopolyWithinFunc, 2, 1, "geopoly_within" },
  175570. { geopolyContainsPointFunc, 3, 1, "geopoly_contains_point" },
  175571. { geopolyOverlapFunc, 2, 1, "geopoly_overlap" },
  175572. { geopolyDebugFunc, 1, 0, "geopoly_debug" },
  175573. { geopolyBBoxFunc, 1, 1, "geopoly_bbox" },
  175574. { geopolyXformFunc, 7, 1, "geopoly_xform" },
  175575. { geopolyRegularFunc, 4, 1, "geopoly_regular" },
  175576. { geopolyCcwFunc, 1, 1, "geopoly_ccw" },
  175577. };
  175578. static const struct {
  175579. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  175580. void (*xFinal)(sqlite3_context*);
  175581. const char *zName;
  175582. } aAgg[] = {
  175583. { geopolyBBoxStep, geopolyBBoxFinal, "geopoly_group_bbox" },
  175584. };
  175585. int i;
  175586. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  175587. int enc = aFunc[i].bPure ? SQLITE_UTF8|SQLITE_DETERMINISTIC : SQLITE_UTF8;
  175588. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  175589. enc, 0,
  175590. aFunc[i].xFunc, 0, 0);
  175591. }
  175592. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  175593. rc = sqlite3_create_function(db, aAgg[i].zName, 1, SQLITE_UTF8, 0,
  175594. 0, aAgg[i].xStep, aAgg[i].xFinal);
  175595. }
  175596. if( rc==SQLITE_OK ){
  175597. rc = sqlite3_create_module_v2(db, "geopoly", &geopolyModule, 0, 0);
  175598. }
  175599. return rc;
  175600. }
  175601. /************** End of geopoly.c *********************************************/
  175602. /************** Continuing where we left off in rtree.c **********************/
  175603. #endif
  175604. /*
  175605. ** Register the r-tree module with database handle db. This creates the
  175606. ** virtual table module "rtree" and the debugging/analysis scalar
  175607. ** function "rtreenode".
  175608. */
  175609. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  175610. const int utf8 = SQLITE_UTF8;
  175611. int rc;
  175612. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  175613. if( rc==SQLITE_OK ){
  175614. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  175615. }
  175616. if( rc==SQLITE_OK ){
  175617. rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
  175618. }
  175619. if( rc==SQLITE_OK ){
  175620. #ifdef SQLITE_RTREE_INT_ONLY
  175621. void *c = (void *)RTREE_COORD_INT32;
  175622. #else
  175623. void *c = (void *)RTREE_COORD_REAL32;
  175624. #endif
  175625. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  175626. }
  175627. if( rc==SQLITE_OK ){
  175628. void *c = (void *)RTREE_COORD_INT32;
  175629. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  175630. }
  175631. #ifdef SQLITE_ENABLE_GEOPOLY
  175632. if( rc==SQLITE_OK ){
  175633. rc = sqlite3_geopoly_init(db);
  175634. }
  175635. #endif
  175636. return rc;
  175637. }
  175638. /*
  175639. ** This routine deletes the RtreeGeomCallback object that was attached
  175640. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  175641. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  175642. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  175643. ** the corresponding SQL function is deleted.
  175644. */
  175645. static void rtreeFreeCallback(void *p){
  175646. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  175647. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  175648. sqlite3_free(p);
  175649. }
  175650. /*
  175651. ** This routine frees the BLOB that is returned by geomCallback().
  175652. */
  175653. static void rtreeMatchArgFree(void *pArg){
  175654. int i;
  175655. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  175656. for(i=0; i<p->nParam; i++){
  175657. sqlite3_value_free(p->apSqlParam[i]);
  175658. }
  175659. sqlite3_free(p);
  175660. }
  175661. /*
  175662. ** Each call to sqlite3_rtree_geometry_callback() or
  175663. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  175664. ** scalar function that is implemented by this routine.
  175665. **
  175666. ** All this function does is construct an RtreeMatchArg object that
  175667. ** contains the geometry-checking callback routines and a list of
  175668. ** parameters to this function, then return that RtreeMatchArg object
  175669. ** as a BLOB.
  175670. **
  175671. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  175672. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  175673. ** out which elements of the R-Tree should be returned by the query.
  175674. */
  175675. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  175676. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  175677. RtreeMatchArg *pBlob;
  175678. sqlite3_int64 nBlob;
  175679. int memErr = 0;
  175680. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  175681. + nArg*sizeof(sqlite3_value*);
  175682. pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);
  175683. if( !pBlob ){
  175684. sqlite3_result_error_nomem(ctx);
  175685. }else{
  175686. int i;
  175687. pBlob->iSize = nBlob;
  175688. pBlob->cb = pGeomCtx[0];
  175689. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  175690. pBlob->nParam = nArg;
  175691. for(i=0; i<nArg; i++){
  175692. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  175693. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  175694. #ifdef SQLITE_RTREE_INT_ONLY
  175695. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  175696. #else
  175697. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  175698. #endif
  175699. }
  175700. if( memErr ){
  175701. sqlite3_result_error_nomem(ctx);
  175702. rtreeMatchArgFree(pBlob);
  175703. }else{
  175704. sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
  175705. }
  175706. }
  175707. }
  175708. /*
  175709. ** Register a new geometry function for use with the r-tree MATCH operator.
  175710. */
  175711. SQLITE_API int sqlite3_rtree_geometry_callback(
  175712. sqlite3 *db, /* Register SQL function on this connection */
  175713. const char *zGeom, /* Name of the new SQL function */
  175714. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  175715. void *pContext /* Extra data associated with the callback */
  175716. ){
  175717. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  175718. /* Allocate and populate the context object. */
  175719. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  175720. if( !pGeomCtx ) return SQLITE_NOMEM;
  175721. pGeomCtx->xGeom = xGeom;
  175722. pGeomCtx->xQueryFunc = 0;
  175723. pGeomCtx->xDestructor = 0;
  175724. pGeomCtx->pContext = pContext;
  175725. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  175726. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  175727. );
  175728. }
  175729. /*
  175730. ** Register a new 2nd-generation geometry function for use with the
  175731. ** r-tree MATCH operator.
  175732. */
  175733. SQLITE_API int sqlite3_rtree_query_callback(
  175734. sqlite3 *db, /* Register SQL function on this connection */
  175735. const char *zQueryFunc, /* Name of new SQL function */
  175736. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  175737. void *pContext, /* Extra data passed into the callback */
  175738. void (*xDestructor)(void*) /* Destructor for the extra data */
  175739. ){
  175740. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  175741. /* Allocate and populate the context object. */
  175742. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  175743. if( !pGeomCtx ) return SQLITE_NOMEM;
  175744. pGeomCtx->xGeom = 0;
  175745. pGeomCtx->xQueryFunc = xQueryFunc;
  175746. pGeomCtx->xDestructor = xDestructor;
  175747. pGeomCtx->pContext = pContext;
  175748. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  175749. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  175750. );
  175751. }
  175752. #if !SQLITE_CORE
  175753. #ifdef _WIN32
  175754. __declspec(dllexport)
  175755. #endif
  175756. SQLITE_API int sqlite3_rtree_init(
  175757. sqlite3 *db,
  175758. char **pzErrMsg,
  175759. const sqlite3_api_routines *pApi
  175760. ){
  175761. SQLITE_EXTENSION_INIT2(pApi)
  175762. return sqlite3RtreeInit(db);
  175763. }
  175764. #endif
  175765. #endif
  175766. /************** End of rtree.c ***********************************************/
  175767. /************** Begin file icu.c *********************************************/
  175768. /*
  175769. ** 2007 May 6
  175770. **
  175771. ** The author disclaims copyright to this source code. In place of
  175772. ** a legal notice, here is a blessing:
  175773. **
  175774. ** May you do good and not evil.
  175775. ** May you find forgiveness for yourself and forgive others.
  175776. ** May you share freely, never taking more than you give.
  175777. **
  175778. *************************************************************************
  175779. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  175780. **
  175781. ** This file implements an integration between the ICU library
  175782. ** ("International Components for Unicode", an open-source library
  175783. ** for handling unicode data) and SQLite. The integration uses
  175784. ** ICU to provide the following to SQLite:
  175785. **
  175786. ** * An implementation of the SQL regexp() function (and hence REGEXP
  175787. ** operator) using the ICU uregex_XX() APIs.
  175788. **
  175789. ** * Implementations of the SQL scalar upper() and lower() functions
  175790. ** for case mapping.
  175791. **
  175792. ** * Integration of ICU and SQLite collation sequences.
  175793. **
  175794. ** * An implementation of the LIKE operator that uses ICU to
  175795. ** provide case-independent matching.
  175796. */
  175797. #if !defined(SQLITE_CORE) \
  175798. || defined(SQLITE_ENABLE_ICU) \
  175799. || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  175800. /* Include ICU headers */
  175801. #include <unicode/utypes.h>
  175802. #include <unicode/uregex.h>
  175803. #include <unicode/ustring.h>
  175804. #include <unicode/ucol.h>
  175805. /* #include <assert.h> */
  175806. #ifndef SQLITE_CORE
  175807. /* #include "sqlite3ext.h" */
  175808. SQLITE_EXTENSION_INIT1
  175809. #else
  175810. /* #include "sqlite3.h" */
  175811. #endif
  175812. /*
  175813. ** This function is called when an ICU function called from within
  175814. ** the implementation of an SQL scalar function returns an error.
  175815. **
  175816. ** The scalar function context passed as the first argument is
  175817. ** loaded with an error message based on the following two args.
  175818. */
  175819. static void icuFunctionError(
  175820. sqlite3_context *pCtx, /* SQLite scalar function context */
  175821. const char *zName, /* Name of ICU function that failed */
  175822. UErrorCode e /* Error code returned by ICU function */
  175823. ){
  175824. char zBuf[128];
  175825. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  175826. zBuf[127] = '\0';
  175827. sqlite3_result_error(pCtx, zBuf, -1);
  175828. }
  175829. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  175830. /*
  175831. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  175832. ** operator.
  175833. */
  175834. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  175835. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  175836. #endif
  175837. /*
  175838. ** Version of sqlite3_free() that is always a function, never a macro.
  175839. */
  175840. static void xFree(void *p){
  175841. sqlite3_free(p);
  175842. }
  175843. /*
  175844. ** This lookup table is used to help decode the first byte of
  175845. ** a multi-byte UTF8 character. It is copied here from SQLite source
  175846. ** code file utf8.c.
  175847. */
  175848. static const unsigned char icuUtf8Trans1[] = {
  175849. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  175850. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  175851. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  175852. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  175853. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  175854. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  175855. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  175856. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  175857. };
  175858. #define SQLITE_ICU_READ_UTF8(zIn, c) \
  175859. c = *(zIn++); \
  175860. if( c>=0xc0 ){ \
  175861. c = icuUtf8Trans1[c-0xc0]; \
  175862. while( (*zIn & 0xc0)==0x80 ){ \
  175863. c = (c<<6) + (0x3f & *(zIn++)); \
  175864. } \
  175865. }
  175866. #define SQLITE_ICU_SKIP_UTF8(zIn) \
  175867. assert( *zIn ); \
  175868. if( *(zIn++)>=0xc0 ){ \
  175869. while( (*zIn & 0xc0)==0x80 ){zIn++;} \
  175870. }
  175871. /*
  175872. ** Compare two UTF-8 strings for equality where the first string is
  175873. ** a "LIKE" expression. Return true (1) if they are the same and
  175874. ** false (0) if they are different.
  175875. */
  175876. static int icuLikeCompare(
  175877. const uint8_t *zPattern, /* LIKE pattern */
  175878. const uint8_t *zString, /* The UTF-8 string to compare against */
  175879. const UChar32 uEsc /* The escape character */
  175880. ){
  175881. static const uint32_t MATCH_ONE = (uint32_t)'_';
  175882. static const uint32_t MATCH_ALL = (uint32_t)'%';
  175883. int prevEscape = 0; /* True if the previous character was uEsc */
  175884. while( 1 ){
  175885. /* Read (and consume) the next character from the input pattern. */
  175886. uint32_t uPattern;
  175887. SQLITE_ICU_READ_UTF8(zPattern, uPattern);
  175888. if( uPattern==0 ) break;
  175889. /* There are now 4 possibilities:
  175890. **
  175891. ** 1. uPattern is an unescaped match-all character "%",
  175892. ** 2. uPattern is an unescaped match-one character "_",
  175893. ** 3. uPattern is an unescaped escape character, or
  175894. ** 4. uPattern is to be handled as an ordinary character
  175895. */
  175896. if( !prevEscape && uPattern==MATCH_ALL ){
  175897. /* Case 1. */
  175898. uint8_t c;
  175899. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  175900. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  175901. ** test string.
  175902. */
  175903. while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
  175904. if( c==MATCH_ONE ){
  175905. if( *zString==0 ) return 0;
  175906. SQLITE_ICU_SKIP_UTF8(zString);
  175907. }
  175908. zPattern++;
  175909. }
  175910. if( *zPattern==0 ) return 1;
  175911. while( *zString ){
  175912. if( icuLikeCompare(zPattern, zString, uEsc) ){
  175913. return 1;
  175914. }
  175915. SQLITE_ICU_SKIP_UTF8(zString);
  175916. }
  175917. return 0;
  175918. }else if( !prevEscape && uPattern==MATCH_ONE ){
  175919. /* Case 2. */
  175920. if( *zString==0 ) return 0;
  175921. SQLITE_ICU_SKIP_UTF8(zString);
  175922. }else if( !prevEscape && uPattern==(uint32_t)uEsc){
  175923. /* Case 3. */
  175924. prevEscape = 1;
  175925. }else{
  175926. /* Case 4. */
  175927. uint32_t uString;
  175928. SQLITE_ICU_READ_UTF8(zString, uString);
  175929. uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
  175930. uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
  175931. if( uString!=uPattern ){
  175932. return 0;
  175933. }
  175934. prevEscape = 0;
  175935. }
  175936. }
  175937. return *zString==0;
  175938. }
  175939. /*
  175940. ** Implementation of the like() SQL function. This function implements
  175941. ** the build-in LIKE operator. The first argument to the function is the
  175942. ** pattern and the second argument is the string. So, the SQL statements:
  175943. **
  175944. ** A LIKE B
  175945. **
  175946. ** is implemented as like(B, A). If there is an escape character E,
  175947. **
  175948. ** A LIKE B ESCAPE E
  175949. **
  175950. ** is mapped to like(B, A, E).
  175951. */
  175952. static void icuLikeFunc(
  175953. sqlite3_context *context,
  175954. int argc,
  175955. sqlite3_value **argv
  175956. ){
  175957. const unsigned char *zA = sqlite3_value_text(argv[0]);
  175958. const unsigned char *zB = sqlite3_value_text(argv[1]);
  175959. UChar32 uEsc = 0;
  175960. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  175961. ** of deep recursion and N*N behavior in patternCompare().
  175962. */
  175963. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  175964. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  175965. return;
  175966. }
  175967. if( argc==3 ){
  175968. /* The escape character string must consist of a single UTF-8 character.
  175969. ** Otherwise, return an error.
  175970. */
  175971. int nE= sqlite3_value_bytes(argv[2]);
  175972. const unsigned char *zE = sqlite3_value_text(argv[2]);
  175973. int i = 0;
  175974. if( zE==0 ) return;
  175975. U8_NEXT(zE, i, nE, uEsc);
  175976. if( i!=nE){
  175977. sqlite3_result_error(context,
  175978. "ESCAPE expression must be a single character", -1);
  175979. return;
  175980. }
  175981. }
  175982. if( zA && zB ){
  175983. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  175984. }
  175985. }
  175986. /*
  175987. ** Function to delete compiled regexp objects. Registered as
  175988. ** a destructor function with sqlite3_set_auxdata().
  175989. */
  175990. static void icuRegexpDelete(void *p){
  175991. URegularExpression *pExpr = (URegularExpression *)p;
  175992. uregex_close(pExpr);
  175993. }
  175994. /*
  175995. ** Implementation of SQLite REGEXP operator. This scalar function takes
  175996. ** two arguments. The first is a regular expression pattern to compile
  175997. ** the second is a string to match against that pattern. If either
  175998. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  175999. ** is 1 if the string matches the pattern, or 0 otherwise.
  176000. **
  176001. ** SQLite maps the regexp() function to the regexp() operator such
  176002. ** that the following two are equivalent:
  176003. **
  176004. ** zString REGEXP zPattern
  176005. ** regexp(zPattern, zString)
  176006. **
  176007. ** Uses the following ICU regexp APIs:
  176008. **
  176009. ** uregex_open()
  176010. ** uregex_matches()
  176011. ** uregex_close()
  176012. */
  176013. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  176014. UErrorCode status = U_ZERO_ERROR;
  176015. URegularExpression *pExpr;
  176016. UBool res;
  176017. const UChar *zString = sqlite3_value_text16(apArg[1]);
  176018. (void)nArg; /* Unused parameter */
  176019. /* If the left hand side of the regexp operator is NULL,
  176020. ** then the result is also NULL.
  176021. */
  176022. if( !zString ){
  176023. return;
  176024. }
  176025. pExpr = sqlite3_get_auxdata(p, 0);
  176026. if( !pExpr ){
  176027. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  176028. if( !zPattern ){
  176029. return;
  176030. }
  176031. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  176032. if( U_SUCCESS(status) ){
  176033. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  176034. }else{
  176035. assert(!pExpr);
  176036. icuFunctionError(p, "uregex_open", status);
  176037. return;
  176038. }
  176039. }
  176040. /* Configure the text that the regular expression operates on. */
  176041. uregex_setText(pExpr, zString, -1, &status);
  176042. if( !U_SUCCESS(status) ){
  176043. icuFunctionError(p, "uregex_setText", status);
  176044. return;
  176045. }
  176046. /* Attempt the match */
  176047. res = uregex_matches(pExpr, 0, &status);
  176048. if( !U_SUCCESS(status) ){
  176049. icuFunctionError(p, "uregex_matches", status);
  176050. return;
  176051. }
  176052. /* Set the text that the regular expression operates on to a NULL
  176053. ** pointer. This is not really necessary, but it is tidier than
  176054. ** leaving the regular expression object configured with an invalid
  176055. ** pointer after this function returns.
  176056. */
  176057. uregex_setText(pExpr, 0, 0, &status);
  176058. /* Return 1 or 0. */
  176059. sqlite3_result_int(p, res ? 1 : 0);
  176060. }
  176061. /*
  176062. ** Implementations of scalar functions for case mapping - upper() and
  176063. ** lower(). Function upper() converts its input to upper-case (ABC).
  176064. ** Function lower() converts to lower-case (abc).
  176065. **
  176066. ** ICU provides two types of case mapping, "general" case mapping and
  176067. ** "language specific". Refer to ICU documentation for the differences
  176068. ** between the two.
  176069. **
  176070. ** To utilise "general" case mapping, the upper() or lower() scalar
  176071. ** functions are invoked with one argument:
  176072. **
  176073. ** upper('ABC') -> 'abc'
  176074. ** lower('abc') -> 'ABC'
  176075. **
  176076. ** To access ICU "language specific" case mapping, upper() or lower()
  176077. ** should be invoked with two arguments. The second argument is the name
  176078. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  176079. ** as the second argument is the same as invoking the 1 argument version
  176080. ** of upper() or lower().
  176081. **
  176082. ** lower('I', 'en_us') -> 'i'
  176083. ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
  176084. **
  176085. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  176086. */
  176087. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  176088. const UChar *zInput; /* Pointer to input string */
  176089. UChar *zOutput = 0; /* Pointer to output buffer */
  176090. int nInput; /* Size of utf-16 input string in bytes */
  176091. int nOut; /* Size of output buffer in bytes */
  176092. int cnt;
  176093. int bToUpper; /* True for toupper(), false for tolower() */
  176094. UErrorCode status;
  176095. const char *zLocale = 0;
  176096. assert(nArg==1 || nArg==2);
  176097. bToUpper = (sqlite3_user_data(p)!=0);
  176098. if( nArg==2 ){
  176099. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  176100. }
  176101. zInput = sqlite3_value_text16(apArg[0]);
  176102. if( !zInput ){
  176103. return;
  176104. }
  176105. nOut = nInput = sqlite3_value_bytes16(apArg[0]);
  176106. if( nOut==0 ){
  176107. sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
  176108. return;
  176109. }
  176110. for(cnt=0; cnt<2; cnt++){
  176111. UChar *zNew = sqlite3_realloc(zOutput, nOut);
  176112. if( zNew==0 ){
  176113. sqlite3_free(zOutput);
  176114. sqlite3_result_error_nomem(p);
  176115. return;
  176116. }
  176117. zOutput = zNew;
  176118. status = U_ZERO_ERROR;
  176119. if( bToUpper ){
  176120. nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  176121. }else{
  176122. nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  176123. }
  176124. if( U_SUCCESS(status) ){
  176125. sqlite3_result_text16(p, zOutput, nOut, xFree);
  176126. }else if( status==U_BUFFER_OVERFLOW_ERROR ){
  176127. assert( cnt==0 );
  176128. continue;
  176129. }else{
  176130. icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
  176131. }
  176132. return;
  176133. }
  176134. assert( 0 ); /* Unreachable */
  176135. }
  176136. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  176137. /*
  176138. ** Collation sequence destructor function. The pCtx argument points to
  176139. ** a UCollator structure previously allocated using ucol_open().
  176140. */
  176141. static void icuCollationDel(void *pCtx){
  176142. UCollator *p = (UCollator *)pCtx;
  176143. ucol_close(p);
  176144. }
  176145. /*
  176146. ** Collation sequence comparison function. The pCtx argument points to
  176147. ** a UCollator structure previously allocated using ucol_open().
  176148. */
  176149. static int icuCollationColl(
  176150. void *pCtx,
  176151. int nLeft,
  176152. const void *zLeft,
  176153. int nRight,
  176154. const void *zRight
  176155. ){
  176156. UCollationResult res;
  176157. UCollator *p = (UCollator *)pCtx;
  176158. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  176159. switch( res ){
  176160. case UCOL_LESS: return -1;
  176161. case UCOL_GREATER: return +1;
  176162. case UCOL_EQUAL: return 0;
  176163. }
  176164. assert(!"Unexpected return value from ucol_strcoll()");
  176165. return 0;
  176166. }
  176167. /*
  176168. ** Implementation of the scalar function icu_load_collation().
  176169. **
  176170. ** This scalar function is used to add ICU collation based collation
  176171. ** types to an SQLite database connection. It is intended to be called
  176172. ** as follows:
  176173. **
  176174. ** SELECT icu_load_collation(<locale>, <collation-name>);
  176175. **
  176176. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  176177. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  176178. ** collation sequence to create.
  176179. */
  176180. static void icuLoadCollation(
  176181. sqlite3_context *p,
  176182. int nArg,
  176183. sqlite3_value **apArg
  176184. ){
  176185. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  176186. UErrorCode status = U_ZERO_ERROR;
  176187. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  176188. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  176189. UCollator *pUCollator; /* ICU library collation object */
  176190. int rc; /* Return code from sqlite3_create_collation_x() */
  176191. assert(nArg==2);
  176192. (void)nArg; /* Unused parameter */
  176193. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  176194. zName = (const char *)sqlite3_value_text(apArg[1]);
  176195. if( !zLocale || !zName ){
  176196. return;
  176197. }
  176198. pUCollator = ucol_open(zLocale, &status);
  176199. if( !U_SUCCESS(status) ){
  176200. icuFunctionError(p, "ucol_open", status);
  176201. return;
  176202. }
  176203. assert(p);
  176204. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  176205. icuCollationColl, icuCollationDel
  176206. );
  176207. if( rc!=SQLITE_OK ){
  176208. ucol_close(pUCollator);
  176209. sqlite3_result_error(p, "Error registering collation function", -1);
  176210. }
  176211. }
  176212. /*
  176213. ** Register the ICU extension functions with database db.
  176214. */
  176215. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  176216. static const struct IcuScalar {
  176217. const char *zName; /* Function name */
  176218. unsigned char nArg; /* Number of arguments */
  176219. unsigned short enc; /* Optimal text encoding */
  176220. unsigned char iContext; /* sqlite3_user_data() context */
  176221. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  176222. } scalars[] = {
  176223. {"icu_load_collation", 2, SQLITE_UTF8, 1, icuLoadCollation},
  176224. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  176225. {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc},
  176226. {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  176227. {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  176228. {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  176229. {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  176230. {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  176231. {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  176232. {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  176233. {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  176234. {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  176235. {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  176236. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  176237. };
  176238. int rc = SQLITE_OK;
  176239. int i;
  176240. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  176241. const struct IcuScalar *p = &scalars[i];
  176242. rc = sqlite3_create_function(
  176243. db, p->zName, p->nArg, p->enc,
  176244. p->iContext ? (void*)db : (void*)0,
  176245. p->xFunc, 0, 0
  176246. );
  176247. }
  176248. return rc;
  176249. }
  176250. #if !SQLITE_CORE
  176251. #ifdef _WIN32
  176252. __declspec(dllexport)
  176253. #endif
  176254. SQLITE_API int sqlite3_icu_init(
  176255. sqlite3 *db,
  176256. char **pzErrMsg,
  176257. const sqlite3_api_routines *pApi
  176258. ){
  176259. SQLITE_EXTENSION_INIT2(pApi)
  176260. return sqlite3IcuInit(db);
  176261. }
  176262. #endif
  176263. #endif
  176264. /************** End of icu.c *************************************************/
  176265. /************** Begin file fts3_icu.c ****************************************/
  176266. /*
  176267. ** 2007 June 22
  176268. **
  176269. ** The author disclaims copyright to this source code. In place of
  176270. ** a legal notice, here is a blessing:
  176271. **
  176272. ** May you do good and not evil.
  176273. ** May you find forgiveness for yourself and forgive others.
  176274. ** May you share freely, never taking more than you give.
  176275. **
  176276. *************************************************************************
  176277. ** This file implements a tokenizer for fts3 based on the ICU library.
  176278. */
  176279. /* #include "fts3Int.h" */
  176280. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  176281. #ifdef SQLITE_ENABLE_ICU
  176282. /* #include <assert.h> */
  176283. /* #include <string.h> */
  176284. /* #include "fts3_tokenizer.h" */
  176285. #include <unicode/ubrk.h>
  176286. /* #include <unicode/ucol.h> */
  176287. /* #include <unicode/ustring.h> */
  176288. #include <unicode/utf16.h>
  176289. typedef struct IcuTokenizer IcuTokenizer;
  176290. typedef struct IcuCursor IcuCursor;
  176291. struct IcuTokenizer {
  176292. sqlite3_tokenizer base;
  176293. char *zLocale;
  176294. };
  176295. struct IcuCursor {
  176296. sqlite3_tokenizer_cursor base;
  176297. UBreakIterator *pIter; /* ICU break-iterator object */
  176298. int nChar; /* Number of UChar elements in pInput */
  176299. UChar *aChar; /* Copy of input using utf-16 encoding */
  176300. int *aOffset; /* Offsets of each character in utf-8 input */
  176301. int nBuffer;
  176302. char *zBuffer;
  176303. int iToken;
  176304. };
  176305. /*
  176306. ** Create a new tokenizer instance.
  176307. */
  176308. static int icuCreate(
  176309. int argc, /* Number of entries in argv[] */
  176310. const char * const *argv, /* Tokenizer creation arguments */
  176311. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  176312. ){
  176313. IcuTokenizer *p;
  176314. int n = 0;
  176315. if( argc>0 ){
  176316. n = strlen(argv[0])+1;
  176317. }
  176318. p = (IcuTokenizer *)sqlite3_malloc64(sizeof(IcuTokenizer)+n);
  176319. if( !p ){
  176320. return SQLITE_NOMEM;
  176321. }
  176322. memset(p, 0, sizeof(IcuTokenizer));
  176323. if( n ){
  176324. p->zLocale = (char *)&p[1];
  176325. memcpy(p->zLocale, argv[0], n);
  176326. }
  176327. *ppTokenizer = (sqlite3_tokenizer *)p;
  176328. return SQLITE_OK;
  176329. }
  176330. /*
  176331. ** Destroy a tokenizer
  176332. */
  176333. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  176334. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  176335. sqlite3_free(p);
  176336. return SQLITE_OK;
  176337. }
  176338. /*
  176339. ** Prepare to begin tokenizing a particular string. The input
  176340. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  176341. ** used to incrementally tokenize this string is returned in
  176342. ** *ppCursor.
  176343. */
  176344. static int icuOpen(
  176345. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  176346. const char *zInput, /* Input string */
  176347. int nInput, /* Length of zInput in bytes */
  176348. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  176349. ){
  176350. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  176351. IcuCursor *pCsr;
  176352. const int32_t opt = U_FOLD_CASE_DEFAULT;
  176353. UErrorCode status = U_ZERO_ERROR;
  176354. int nChar;
  176355. UChar32 c;
  176356. int iInput = 0;
  176357. int iOut = 0;
  176358. *ppCursor = 0;
  176359. if( zInput==0 ){
  176360. nInput = 0;
  176361. zInput = "";
  176362. }else if( nInput<0 ){
  176363. nInput = strlen(zInput);
  176364. }
  176365. nChar = nInput+1;
  176366. pCsr = (IcuCursor *)sqlite3_malloc64(
  176367. sizeof(IcuCursor) + /* IcuCursor */
  176368. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  176369. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  176370. );
  176371. if( !pCsr ){
  176372. return SQLITE_NOMEM;
  176373. }
  176374. memset(pCsr, 0, sizeof(IcuCursor));
  176375. pCsr->aChar = (UChar *)&pCsr[1];
  176376. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  176377. pCsr->aOffset[iOut] = iInput;
  176378. U8_NEXT(zInput, iInput, nInput, c);
  176379. while( c>0 ){
  176380. int isError = 0;
  176381. c = u_foldCase(c, opt);
  176382. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  176383. if( isError ){
  176384. sqlite3_free(pCsr);
  176385. return SQLITE_ERROR;
  176386. }
  176387. pCsr->aOffset[iOut] = iInput;
  176388. if( iInput<nInput ){
  176389. U8_NEXT(zInput, iInput, nInput, c);
  176390. }else{
  176391. c = 0;
  176392. }
  176393. }
  176394. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  176395. if( !U_SUCCESS(status) ){
  176396. sqlite3_free(pCsr);
  176397. return SQLITE_ERROR;
  176398. }
  176399. pCsr->nChar = iOut;
  176400. ubrk_first(pCsr->pIter);
  176401. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  176402. return SQLITE_OK;
  176403. }
  176404. /*
  176405. ** Close a tokenization cursor previously opened by a call to icuOpen().
  176406. */
  176407. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  176408. IcuCursor *pCsr = (IcuCursor *)pCursor;
  176409. ubrk_close(pCsr->pIter);
  176410. sqlite3_free(pCsr->zBuffer);
  176411. sqlite3_free(pCsr);
  176412. return SQLITE_OK;
  176413. }
  176414. /*
  176415. ** Extract the next token from a tokenization cursor.
  176416. */
  176417. static int icuNext(
  176418. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  176419. const char **ppToken, /* OUT: *ppToken is the token text */
  176420. int *pnBytes, /* OUT: Number of bytes in token */
  176421. int *piStartOffset, /* OUT: Starting offset of token */
  176422. int *piEndOffset, /* OUT: Ending offset of token */
  176423. int *piPosition /* OUT: Position integer of token */
  176424. ){
  176425. IcuCursor *pCsr = (IcuCursor *)pCursor;
  176426. int iStart = 0;
  176427. int iEnd = 0;
  176428. int nByte = 0;
  176429. while( iStart==iEnd ){
  176430. UChar32 c;
  176431. iStart = ubrk_current(pCsr->pIter);
  176432. iEnd = ubrk_next(pCsr->pIter);
  176433. if( iEnd==UBRK_DONE ){
  176434. return SQLITE_DONE;
  176435. }
  176436. while( iStart<iEnd ){
  176437. int iWhite = iStart;
  176438. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  176439. if( u_isspace(c) ){
  176440. iStart = iWhite;
  176441. }else{
  176442. break;
  176443. }
  176444. }
  176445. assert(iStart<=iEnd);
  176446. }
  176447. do {
  176448. UErrorCode status = U_ZERO_ERROR;
  176449. if( nByte ){
  176450. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  176451. if( !zNew ){
  176452. return SQLITE_NOMEM;
  176453. }
  176454. pCsr->zBuffer = zNew;
  176455. pCsr->nBuffer = nByte;
  176456. }
  176457. u_strToUTF8(
  176458. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  176459. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  176460. &status /* Output success/failure */
  176461. );
  176462. } while( nByte>pCsr->nBuffer );
  176463. *ppToken = pCsr->zBuffer;
  176464. *pnBytes = nByte;
  176465. *piStartOffset = pCsr->aOffset[iStart];
  176466. *piEndOffset = pCsr->aOffset[iEnd];
  176467. *piPosition = pCsr->iToken++;
  176468. return SQLITE_OK;
  176469. }
  176470. /*
  176471. ** The set of routines that implement the simple tokenizer
  176472. */
  176473. static const sqlite3_tokenizer_module icuTokenizerModule = {
  176474. 0, /* iVersion */
  176475. icuCreate, /* xCreate */
  176476. icuDestroy, /* xCreate */
  176477. icuOpen, /* xOpen */
  176478. icuClose, /* xClose */
  176479. icuNext, /* xNext */
  176480. 0, /* xLanguageid */
  176481. };
  176482. /*
  176483. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  176484. */
  176485. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  176486. sqlite3_tokenizer_module const**ppModule
  176487. ){
  176488. *ppModule = &icuTokenizerModule;
  176489. }
  176490. #endif /* defined(SQLITE_ENABLE_ICU) */
  176491. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  176492. /************** End of fts3_icu.c ********************************************/
  176493. /************** Begin file sqlite3rbu.c **************************************/
  176494. /*
  176495. ** 2014 August 30
  176496. **
  176497. ** The author disclaims copyright to this source code. In place of
  176498. ** a legal notice, here is a blessing:
  176499. **
  176500. ** May you do good and not evil.
  176501. ** May you find forgiveness for yourself and forgive others.
  176502. ** May you share freely, never taking more than you give.
  176503. **
  176504. *************************************************************************
  176505. **
  176506. **
  176507. ** OVERVIEW
  176508. **
  176509. ** The RBU extension requires that the RBU update be packaged as an
  176510. ** SQLite database. The tables it expects to find are described in
  176511. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  176512. ** that the user wishes to write to, a corresponding data_xyz table is
  176513. ** created in the RBU database and populated with one row for each row to
  176514. ** update, insert or delete from the target table.
  176515. **
  176516. ** The update proceeds in three stages:
  176517. **
  176518. ** 1) The database is updated. The modified database pages are written
  176519. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  176520. ** that it is named "<database>-oal" instead of "<database>-wal".
  176521. ** Because regular SQLite clients do not look for file named
  176522. ** "<database>-oal", they go on using the original database in
  176523. ** rollback mode while the *-oal file is being generated.
  176524. **
  176525. ** During this stage RBU does not update the database by writing
  176526. ** directly to the target tables. Instead it creates "imposter"
  176527. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  176528. ** to update each b-tree individually. All updates required by each
  176529. ** b-tree are completed before moving on to the next, and all
  176530. ** updates are done in sorted key order.
  176531. **
  176532. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  176533. ** location using a call to rename(2). Before doing this the RBU
  176534. ** module takes an EXCLUSIVE lock on the database file, ensuring
  176535. ** that there are no other active readers.
  176536. **
  176537. ** Once the EXCLUSIVE lock is released, any other database readers
  176538. ** detect the new *-wal file and read the database in wal mode. At
  176539. ** this point they see the new version of the database - including
  176540. ** the updates made as part of the RBU update.
  176541. **
  176542. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  176543. ** as a regular database checkpoint, except that a single frame is
  176544. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  176545. ** handle is closed before the entire *-wal file is checkpointed,
  176546. ** the checkpoint progress is saved in the RBU database and the
  176547. ** checkpoint can be resumed by another RBU client at some point in
  176548. ** the future.
  176549. **
  176550. ** POTENTIAL PROBLEMS
  176551. **
  176552. ** The rename() call might not be portable. And RBU is not currently
  176553. ** syncing the directory after renaming the file.
  176554. **
  176555. ** When state is saved, any commit to the *-oal file and the commit to
  176556. ** the RBU update database are not atomic. So if the power fails at the
  176557. ** wrong moment they might get out of sync. As the main database will be
  176558. ** committed before the RBU update database this will likely either just
  176559. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  176560. ** constraint violations).
  176561. **
  176562. ** If some client does modify the target database mid RBU update, or some
  176563. ** other error occurs, the RBU extension will keep throwing errors. It's
  176564. ** not really clear how to get out of this state. The system could just
  176565. ** by delete the RBU update database and *-oal file and have the device
  176566. ** download the update again and start over.
  176567. **
  176568. ** At present, for an UPDATE, both the new.* and old.* records are
  176569. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  176570. ** fields are collected. This means we're probably writing a lot more
  176571. ** data to disk when saving the state of an ongoing update to the RBU
  176572. ** update database than is strictly necessary.
  176573. **
  176574. */
  176575. /* #include <assert.h> */
  176576. /* #include <string.h> */
  176577. /* #include <stdio.h> */
  176578. /* #include "sqlite3.h" */
  176579. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  176580. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  176581. /************** Begin file sqlite3rbu.h **************************************/
  176582. /*
  176583. ** 2014 August 30
  176584. **
  176585. ** The author disclaims copyright to this source code. In place of
  176586. ** a legal notice, here is a blessing:
  176587. **
  176588. ** May you do good and not evil.
  176589. ** May you find forgiveness for yourself and forgive others.
  176590. ** May you share freely, never taking more than you give.
  176591. **
  176592. *************************************************************************
  176593. **
  176594. ** This file contains the public interface for the RBU extension.
  176595. */
  176596. /*
  176597. ** SUMMARY
  176598. **
  176599. ** Writing a transaction containing a large number of operations on
  176600. ** b-tree indexes that are collectively larger than the available cache
  176601. ** memory can be very inefficient.
  176602. **
  176603. ** The problem is that in order to update a b-tree, the leaf page (at least)
  176604. ** containing the entry being inserted or deleted must be modified. If the
  176605. ** working set of leaves is larger than the available cache memory, then a
  176606. ** single leaf that is modified more than once as part of the transaction
  176607. ** may be loaded from or written to the persistent media multiple times.
  176608. ** Additionally, because the index updates are likely to be applied in
  176609. ** random order, access to pages within the database is also likely to be in
  176610. ** random order, which is itself quite inefficient.
  176611. **
  176612. ** One way to improve the situation is to sort the operations on each index
  176613. ** by index key before applying them to the b-tree. This leads to an IO
  176614. ** pattern that resembles a single linear scan through the index b-tree,
  176615. ** and all but guarantees each modified leaf page is loaded and stored
  176616. ** exactly once. SQLite uses this trick to improve the performance of
  176617. ** CREATE INDEX commands. This extension allows it to be used to improve
  176618. ** the performance of large transactions on existing databases.
  176619. **
  176620. ** Additionally, this extension allows the work involved in writing the
  176621. ** large transaction to be broken down into sub-transactions performed
  176622. ** sequentially by separate processes. This is useful if the system cannot
  176623. ** guarantee that a single update process will run for long enough to apply
  176624. ** the entire update, for example because the update is being applied on a
  176625. ** mobile device that is frequently rebooted. Even after the writer process
  176626. ** has committed one or more sub-transactions, other database clients continue
  176627. ** to read from the original database snapshot. In other words, partially
  176628. ** applied transactions are not visible to other clients.
  176629. **
  176630. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  176631. ** transmitted via a wireless network to a mobile device. A transaction
  176632. ** applied using this extension is hence refered to as an "RBU update".
  176633. **
  176634. **
  176635. ** LIMITATIONS
  176636. **
  176637. ** An "RBU update" transaction is subject to the following limitations:
  176638. **
  176639. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  176640. ** only.
  176641. **
  176642. ** * INSERT statements may not use any default values.
  176643. **
  176644. ** * UPDATE and DELETE statements must identify their target rows by
  176645. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  176646. ** KEY fields may not be updated or deleted. If the table being written
  176647. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  176648. **
  176649. ** * UPDATE statements may not modify PRIMARY KEY columns.
  176650. **
  176651. ** * No triggers will be fired.
  176652. **
  176653. ** * No foreign key violations are detected or reported.
  176654. **
  176655. ** * CHECK constraints are not enforced.
  176656. **
  176657. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  176658. **
  176659. **
  176660. ** PREPARATION
  176661. **
  176662. ** An "RBU update" is stored as a separate SQLite database. A database
  176663. ** containing an RBU update is an "RBU database". For each table in the
  176664. ** target database to be updated, the RBU database should contain a table
  176665. ** named "data_<target name>" containing the same set of columns as the
  176666. ** target table, and one more - "rbu_control". The data_% table should
  176667. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  176668. ** the same type as the corresponding column in the target database.
  176669. ** The "rbu_control" column should have no type at all. For example, if
  176670. ** the target database contains:
  176671. **
  176672. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  176673. **
  176674. ** Then the RBU database should contain:
  176675. **
  176676. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  176677. **
  176678. ** The order of the columns in the data_% table does not matter.
  176679. **
  176680. ** Instead of a regular table, the RBU database may also contain virtual
  176681. ** tables or view named using the data_<target> naming scheme.
  176682. **
  176683. ** Instead of the plain data_<target> naming scheme, RBU database tables
  176684. ** may also be named data<integer>_<target>, where <integer> is any sequence
  176685. ** of zero or more numeric characters (0-9). This can be significant because
  176686. ** tables within the RBU database are always processed in order sorted by
  176687. ** name. By judicious selection of the <integer> portion of the names
  176688. ** of the RBU tables the user can therefore control the order in which they
  176689. ** are processed. This can be useful, for example, to ensure that "external
  176690. ** content" FTS4 tables are updated before their underlying content tables.
  176691. **
  176692. ** If the target database table is a virtual table or a table that has no
  176693. ** PRIMARY KEY declaration, the data_% table must also contain a column
  176694. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  176695. ** key column - "rowid". Virtual tables for which the "rowid" column does
  176696. ** not function like a primary key value cannot be updated using RBU. For
  176697. ** example, if the target db contains either of the following:
  176698. **
  176699. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  176700. ** CREATE TABLE x1(a, b)
  176701. **
  176702. ** then the RBU database should contain:
  176703. **
  176704. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  176705. **
  176706. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  176707. ** target table must be present in the input table. For virtual tables,
  176708. ** hidden columns are optional - they are updated by RBU if present in
  176709. ** the input table, or not otherwise. For example, to write to an fts4
  176710. ** table with a hidden languageid column such as:
  176711. **
  176712. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  176713. **
  176714. ** Either of the following input table schemas may be used:
  176715. **
  176716. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  176717. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  176718. **
  176719. ** For each row to INSERT into the target database as part of the RBU
  176720. ** update, the corresponding data_% table should contain a single record
  176721. ** with the "rbu_control" column set to contain integer value 0. The
  176722. ** other columns should be set to the values that make up the new record
  176723. ** to insert.
  176724. **
  176725. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  176726. ** possible to insert a NULL value into the IPK column. Attempting to
  176727. ** do so results in an SQLITE_MISMATCH error.
  176728. **
  176729. ** For each row to DELETE from the target database as part of the RBU
  176730. ** update, the corresponding data_% table should contain a single record
  176731. ** with the "rbu_control" column set to contain integer value 1. The
  176732. ** real primary key values of the row to delete should be stored in the
  176733. ** corresponding columns of the data_% table. The values stored in the
  176734. ** other columns are not used.
  176735. **
  176736. ** For each row to UPDATE from the target database as part of the RBU
  176737. ** update, the corresponding data_% table should contain a single record
  176738. ** with the "rbu_control" column set to contain a value of type text.
  176739. ** The real primary key values identifying the row to update should be
  176740. ** stored in the corresponding columns of the data_% table row, as should
  176741. ** the new values of all columns being update. The text value in the
  176742. ** "rbu_control" column must contain the same number of characters as
  176743. ** there are columns in the target database table, and must consist entirely
  176744. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  176745. ** each column that is being updated, the corresponding character is set to
  176746. ** 'x'. For those that remain as they are, the corresponding character of the
  176747. ** rbu_control value should be set to '.'. For example, given the tables
  176748. ** above, the update statement:
  176749. **
  176750. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  176751. **
  176752. ** is represented by the data_t1 row created by:
  176753. **
  176754. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  176755. **
  176756. ** Instead of an 'x' character, characters of the rbu_control value specified
  176757. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  176758. ** target table with the value stored in the corresponding data_% column, the
  176759. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  176760. ** the target table column. rbu_delta() is invoked with two arguments - the
  176761. ** original value currently stored in the target table column and the
  176762. ** value specified in the data_xxx table.
  176763. **
  176764. ** For example, this row:
  176765. **
  176766. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  176767. **
  176768. ** is similar to an UPDATE statement such as:
  176769. **
  176770. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  176771. **
  176772. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  176773. ** ota_control string, the contents of the data_xxx table column is assumed
  176774. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  176775. ** format used by the fossil source-code management system. In this case
  176776. ** the existing value within the target database table must be of type BLOB.
  176777. ** It is replaced by the result of applying the specified fossil delta to
  176778. ** itself.
  176779. **
  176780. ** If the target database table is a virtual table or a table with no PRIMARY
  176781. ** KEY, the rbu_control value should not include a character corresponding
  176782. ** to the rbu_rowid value. For example, this:
  176783. **
  176784. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  176785. ** VALUES(NULL, 'usa', 12, '.x');
  176786. **
  176787. ** causes a result similar to:
  176788. **
  176789. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  176790. **
  176791. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  176792. ** However, RBU is more efficient if reading the rows in from each data_xxx
  176793. ** table in "rowid" order is roughly the same as reading them sorted by
  176794. ** the PRIMARY KEY of the corresponding target database table. In other
  176795. ** words, rows should be sorted using the destination table PRIMARY KEY
  176796. ** fields before they are inserted into the data_xxx tables.
  176797. **
  176798. ** USAGE
  176799. **
  176800. ** The API declared below allows an application to apply an RBU update
  176801. ** stored on disk to an existing target database. Essentially, the
  176802. ** application:
  176803. **
  176804. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  176805. **
  176806. ** 2) Registers any required virtual table modules with the database
  176807. ** handle returned by sqlite3rbu_db(). Also, if required, register
  176808. ** the rbu_delta() implementation.
  176809. **
  176810. ** 3) Calls the sqlite3rbu_step() function one or more times on
  176811. ** the new handle. Each call to sqlite3rbu_step() performs a single
  176812. ** b-tree operation, so thousands of calls may be required to apply
  176813. ** a complete update.
  176814. **
  176815. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  176816. ** sqlite3rbu_step() has been called enough times to completely
  176817. ** apply the update to the target database, then the RBU database
  176818. ** is marked as fully applied. Otherwise, the state of the RBU
  176819. ** update application is saved in the RBU database for later
  176820. ** resumption.
  176821. **
  176822. ** See comments below for more detail on APIs.
  176823. **
  176824. ** If an update is only partially applied to the target database by the
  176825. ** time sqlite3rbu_close() is called, various state information is saved
  176826. ** within the RBU database. This allows subsequent processes to automatically
  176827. ** resume the RBU update from where it left off.
  176828. **
  176829. ** To remove all RBU extension state information, returning an RBU database
  176830. ** to its original contents, it is sufficient to drop all tables that begin
  176831. ** with the prefix "rbu_"
  176832. **
  176833. ** DATABASE LOCKING
  176834. **
  176835. ** An RBU update may not be applied to a database in WAL mode. Attempting
  176836. ** to do so is an error (SQLITE_ERROR).
  176837. **
  176838. ** While an RBU handle is open, a SHARED lock may be held on the target
  176839. ** database file. This means it is possible for other clients to read the
  176840. ** database, but not to write it.
  176841. **
  176842. ** If an RBU update is started and then suspended before it is completed,
  176843. ** then an external client writes to the database, then attempting to resume
  176844. ** the suspended RBU update is also an error (SQLITE_BUSY).
  176845. */
  176846. #ifndef _SQLITE3RBU_H
  176847. #define _SQLITE3RBU_H
  176848. /* #include "sqlite3.h" ** Required for error code definitions ** */
  176849. #if 0
  176850. extern "C" {
  176851. #endif
  176852. typedef struct sqlite3rbu sqlite3rbu;
  176853. /*
  176854. ** Open an RBU handle.
  176855. **
  176856. ** Argument zTarget is the path to the target database. Argument zRbu is
  176857. ** the path to the RBU database. Each call to this function must be matched
  176858. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  176859. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  176860. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  176861. ** database URI, not a regular file name.
  176862. **
  176863. ** If the zState argument is passed a NULL value, the RBU extension stores
  176864. ** the current state of the update (how many rows have been updated, which
  176865. ** indexes are yet to be updated etc.) within the RBU database itself. This
  176866. ** can be convenient, as it means that the RBU application does not need to
  176867. ** organize removing a separate state file after the update is concluded.
  176868. ** Or, if zState is non-NULL, it must be a path to a database file in which
  176869. ** the RBU extension can store the state of the update.
  176870. **
  176871. ** When resuming an RBU update, the zState argument must be passed the same
  176872. ** value as when the RBU update was started.
  176873. **
  176874. ** Once the RBU update is finished, the RBU extension does not
  176875. ** automatically remove any zState database file, even if it created it.
  176876. **
  176877. ** By default, RBU uses the default VFS to access the files on disk. To
  176878. ** use a VFS other than the default, an SQLite "file:" URI containing a
  176879. ** "vfs=..." option may be passed as the zTarget option.
  176880. **
  176881. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  176882. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  176883. ** not work out of the box with zipvfs. Refer to the comment describing
  176884. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  176885. */
  176886. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  176887. const char *zTarget,
  176888. const char *zRbu,
  176889. const char *zState
  176890. );
  176891. /*
  176892. ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
  176893. ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
  176894. ** that it can be suspended and resumed like an RBU update.
  176895. **
  176896. ** The second argument to this function identifies a database in which
  176897. ** to store the state of the RBU vacuum operation if it is suspended. The
  176898. ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
  176899. ** operation, the state database should either not exist or be empty
  176900. ** (contain no tables). If an RBU vacuum is suspended by calling
  176901. ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
  176902. ** returned SQLITE_DONE, the vacuum state is stored in the state database.
  176903. ** The vacuum can be resumed by calling this function to open a new RBU
  176904. ** handle specifying the same target and state databases.
  176905. **
  176906. ** If the second argument passed to this function is NULL, then the
  176907. ** name of the state database is "<database>-vacuum", where <database>
  176908. ** is the name of the target database file. In this case, on UNIX, if the
  176909. ** state database is not already present in the file-system, it is created
  176910. ** with the same permissions as the target db is made.
  176911. **
  176912. ** With an RBU vacuum, it is an SQLITE_MISUSE error if the name of the
  176913. ** state database ends with "-vactmp". This name is reserved for internal
  176914. ** use.
  176915. **
  176916. ** This function does not delete the state database after an RBU vacuum
  176917. ** is completed, even if it created it. However, if the call to
  176918. ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
  176919. ** of the state tables within the state database are zeroed. This way,
  176920. ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
  176921. ** new RBU vacuum operation.
  176922. **
  176923. ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
  176924. ** describing the sqlite3rbu_create_vfs() API function below for
  176925. ** a description of the complications associated with using RBU with
  176926. ** zipvfs databases.
  176927. */
  176928. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  176929. const char *zTarget,
  176930. const char *zState
  176931. );
  176932. /*
  176933. ** Configure a limit for the amount of temp space that may be used by
  176934. ** the RBU handle passed as the first argument. The new limit is specified
  176935. ** in bytes by the second parameter. If it is positive, the limit is updated.
  176936. ** If the second parameter to this function is passed zero, then the limit
  176937. ** is removed entirely. If the second parameter is negative, the limit is
  176938. ** not modified (this is useful for querying the current limit).
  176939. **
  176940. ** In all cases the returned value is the current limit in bytes (zero
  176941. ** indicates unlimited).
  176942. **
  176943. ** If the temp space limit is exceeded during operation, an SQLITE_FULL
  176944. ** error is returned.
  176945. */
  176946. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
  176947. /*
  176948. ** Return the current amount of temp file space, in bytes, currently used by
  176949. ** the RBU handle passed as the only argument.
  176950. */
  176951. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
  176952. /*
  176953. ** Internally, each RBU connection uses a separate SQLite database
  176954. ** connection to access the target and rbu update databases. This
  176955. ** API allows the application direct access to these database handles.
  176956. **
  176957. ** The first argument passed to this function must be a valid, open, RBU
  176958. ** handle. The second argument should be passed zero to access the target
  176959. ** database handle, or non-zero to access the rbu update database handle.
  176960. ** Accessing the underlying database handles may be useful in the
  176961. ** following scenarios:
  176962. **
  176963. ** * If any target tables are virtual tables, it may be necessary to
  176964. ** call sqlite3_create_module() on the target database handle to
  176965. ** register the required virtual table implementations.
  176966. **
  176967. ** * If the data_xxx tables in the RBU source database are virtual
  176968. ** tables, the application may need to call sqlite3_create_module() on
  176969. ** the rbu update db handle to any required virtual table
  176970. ** implementations.
  176971. **
  176972. ** * If the application uses the "rbu_delta()" feature described above,
  176973. ** it must use sqlite3_create_function() or similar to register the
  176974. ** rbu_delta() implementation with the target database handle.
  176975. **
  176976. ** If an error has occurred, either while opening or stepping the RBU object,
  176977. ** this function may return NULL. The error code and message may be collected
  176978. ** when sqlite3rbu_close() is called.
  176979. **
  176980. ** Database handles returned by this function remain valid until the next
  176981. ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
  176982. */
  176983. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
  176984. /*
  176985. ** Do some work towards applying the RBU update to the target db.
  176986. **
  176987. ** Return SQLITE_DONE if the update has been completely applied, or
  176988. ** SQLITE_OK if no error occurs but there remains work to do to apply
  176989. ** the RBU update. If an error does occur, some other error code is
  176990. ** returned.
  176991. **
  176992. ** Once a call to sqlite3rbu_step() has returned a value other than
  176993. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  176994. ** that immediately return the same value.
  176995. */
  176996. SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
  176997. /*
  176998. ** Force RBU to save its state to disk.
  176999. **
  177000. ** If a power failure or application crash occurs during an update, following
  177001. ** system recovery RBU may resume the update from the point at which the state
  177002. ** was last saved. In other words, from the most recent successful call to
  177003. ** sqlite3rbu_close() or this function.
  177004. **
  177005. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  177006. */
  177007. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
  177008. /*
  177009. ** Close an RBU handle.
  177010. **
  177011. ** If the RBU update has been completely applied, mark the RBU database
  177012. ** as fully applied. Otherwise, assuming no error has occurred, save the
  177013. ** current state of the RBU update appliation to the RBU database.
  177014. **
  177015. ** If an error has already occurred as part of an sqlite3rbu_step()
  177016. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  177017. ** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
  177018. ** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
  177019. ** English language error message. It is the responsibility of the caller to
  177020. ** eventually free any such buffer using sqlite3_free().
  177021. **
  177022. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  177023. ** update has been partially applied, or SQLITE_DONE if it has been
  177024. ** completely applied.
  177025. */
  177026. SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  177027. /*
  177028. ** Return the total number of key-value operations (inserts, deletes or
  177029. ** updates) that have been performed on the target database since the
  177030. ** current RBU update was started.
  177031. */
  177032. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
  177033. /*
  177034. ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
  177035. ** progress indications for the two stages of an RBU update. This API may
  177036. ** be useful for driving GUI progress indicators and similar.
  177037. **
  177038. ** An RBU update is divided into two stages:
  177039. **
  177040. ** * Stage 1, in which changes are accumulated in an oal/wal file, and
  177041. ** * Stage 2, in which the contents of the wal file are copied into the
  177042. ** main database.
  177043. **
  177044. ** The update is visible to non-RBU clients during stage 2. During stage 1
  177045. ** non-RBU reader clients may see the original database.
  177046. **
  177047. ** If this API is called during stage 2 of the update, output variable
  177048. ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
  177049. ** to a value between 0 and 10000 to indicate the permyriadage progress of
  177050. ** stage 2. A value of 5000 indicates that stage 2 is half finished,
  177051. ** 9000 indicates that it is 90% finished, and so on.
  177052. **
  177053. ** If this API is called during stage 1 of the update, output variable
  177054. ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
  177055. ** value to which (*pnOne) is set depends on whether or not the RBU
  177056. ** database contains an "rbu_count" table. The rbu_count table, if it
  177057. ** exists, must contain the same columns as the following:
  177058. **
  177059. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  177060. **
  177061. ** There must be one row in the table for each source (data_xxx) table within
  177062. ** the RBU database. The 'tbl' column should contain the name of the source
  177063. ** table. The 'cnt' column should contain the number of rows within the
  177064. ** source table.
  177065. **
  177066. ** If the rbu_count table is present and populated correctly and this
  177067. ** API is called during stage 1, the *pnOne output variable is set to the
  177068. ** permyriadage progress of the same stage. If the rbu_count table does
  177069. ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
  177070. ** table exists but is not correctly populated, the value of the *pnOne
  177071. ** output variable during stage 1 is undefined.
  177072. */
  177073. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
  177074. /*
  177075. ** Obtain an indication as to the current stage of an RBU update or vacuum.
  177076. ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
  177077. ** defined in this file. Return values should be interpreted as follows:
  177078. **
  177079. ** SQLITE_RBU_STATE_OAL:
  177080. ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
  177081. ** may either add further data to the *-oal file, or compute data that will
  177082. ** be added by a subsequent call.
  177083. **
  177084. ** SQLITE_RBU_STATE_MOVE:
  177085. ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
  177086. ** will move the *-oal file to the equivalent *-wal path. If the current
  177087. ** operation is an RBU update, then the updated version of the database
  177088. ** file will become visible to ordinary SQLite clients following the next
  177089. ** call to sqlite3rbu_step().
  177090. **
  177091. ** SQLITE_RBU_STATE_CHECKPOINT:
  177092. ** RBU is currently performing an incremental checkpoint. The next call to
  177093. ** sqlite3rbu_step() will copy a page of data from the *-wal file into
  177094. ** the target database file.
  177095. **
  177096. ** SQLITE_RBU_STATE_DONE:
  177097. ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
  177098. ** will immediately return SQLITE_DONE.
  177099. **
  177100. ** SQLITE_RBU_STATE_ERROR:
  177101. ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
  177102. ** immediately return the SQLite error code associated with the error.
  177103. */
  177104. #define SQLITE_RBU_STATE_OAL 1
  177105. #define SQLITE_RBU_STATE_MOVE 2
  177106. #define SQLITE_RBU_STATE_CHECKPOINT 3
  177107. #define SQLITE_RBU_STATE_DONE 4
  177108. #define SQLITE_RBU_STATE_ERROR 5
  177109. SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
  177110. /*
  177111. ** Create an RBU VFS named zName that accesses the underlying file-system
  177112. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  177113. ** then the new RBU VFS uses the default system VFS to access the file-system.
  177114. ** The new object is registered as a non-default VFS with SQLite before
  177115. ** returning.
  177116. **
  177117. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  177118. ** object is created and deleted automatically by RBU.
  177119. **
  177120. ** The exception is for applications that also use zipvfs. In this case,
  177121. ** the custom VFS must be explicitly created by the user before the RBU
  177122. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  177123. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  177124. ** (for example multiplexor) to access the file-system. For example,
  177125. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  177126. ** multiplexor (error checking omitted):
  177127. **
  177128. ** // Create a VFS named "multiplex" (not the default).
  177129. ** sqlite3_multiplex_initialize(0, 0);
  177130. **
  177131. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  177132. ** // second argument were replaced with NULL, the "rbu" VFS would
  177133. ** // access the file-system via the system default VFS, bypassing the
  177134. ** // multiplexor.
  177135. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  177136. **
  177137. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  177138. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  177139. **
  177140. ** // Make zipvfs the default VFS.
  177141. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  177142. **
  177143. ** Because the default VFS created above includes a RBU functionality, it
  177144. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  177145. ** that does not include the RBU layer results in an error.
  177146. **
  177147. ** The overhead of adding the "rbu" VFS to the system is negligible for
  177148. ** non-RBU users. There is no harm in an application accessing the
  177149. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  177150. ** occasionally.
  177151. */
  177152. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  177153. /*
  177154. ** Deregister and destroy an RBU vfs created by an earlier call to
  177155. ** sqlite3rbu_create_vfs().
  177156. **
  177157. ** VFS objects are not reference counted. If a VFS object is destroyed
  177158. ** before all database handles that use it have been closed, the results
  177159. ** are undefined.
  177160. */
  177161. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
  177162. #if 0
  177163. } /* end of the 'extern "C"' block */
  177164. #endif
  177165. #endif /* _SQLITE3RBU_H */
  177166. /************** End of sqlite3rbu.h ******************************************/
  177167. /************** Continuing where we left off in sqlite3rbu.c *****************/
  177168. #if defined(_WIN32_WCE)
  177169. /* #include "windows.h" */
  177170. #endif
  177171. /* Maximum number of prepared UPDATE statements held by this module */
  177172. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  177173. /* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM
  177174. ** to enable checksum verification.
  177175. */
  177176. #ifndef RBU_ENABLE_DELTA_CKSUM
  177177. # define RBU_ENABLE_DELTA_CKSUM 0
  177178. #endif
  177179. /*
  177180. ** Swap two objects of type TYPE.
  177181. */
  177182. #if !defined(SQLITE_AMALGAMATION)
  177183. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  177184. #endif
  177185. /*
  177186. ** The rbu_state table is used to save the state of a partially applied
  177187. ** update so that it can be resumed later. The table consists of integer
  177188. ** keys mapped to values as follows:
  177189. **
  177190. ** RBU_STATE_STAGE:
  177191. ** May be set to integer values 1, 2, 4 or 5. As follows:
  177192. ** 1: the *-rbu file is currently under construction.
  177193. ** 2: the *-rbu file has been constructed, but not yet moved
  177194. ** to the *-wal path.
  177195. ** 4: the checkpoint is underway.
  177196. ** 5: the rbu update has been checkpointed.
  177197. **
  177198. ** RBU_STATE_TBL:
  177199. ** Only valid if STAGE==1. The target database name of the table
  177200. ** currently being written.
  177201. **
  177202. ** RBU_STATE_IDX:
  177203. ** Only valid if STAGE==1. The target database name of the index
  177204. ** currently being written, or NULL if the main table is currently being
  177205. ** updated.
  177206. **
  177207. ** RBU_STATE_ROW:
  177208. ** Only valid if STAGE==1. Number of rows already processed for the current
  177209. ** table/index.
  177210. **
  177211. ** RBU_STATE_PROGRESS:
  177212. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  177213. ** rbu update.
  177214. **
  177215. ** RBU_STATE_CKPT:
  177216. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  177217. ** header created by recovering the *-wal file. This is used to detect
  177218. ** cases when another client appends frames to the *-wal file in the
  177219. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  177220. ** be continued if this happens).
  177221. **
  177222. ** RBU_STATE_COOKIE:
  177223. ** Valid if STAGE==1. The current change-counter cookie value in the
  177224. ** target db file.
  177225. **
  177226. ** RBU_STATE_OALSZ:
  177227. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  177228. **
  177229. ** RBU_STATE_DATATBL:
  177230. ** Only valid if STAGE==1. The RBU database name of the table
  177231. ** currently being read.
  177232. */
  177233. #define RBU_STATE_STAGE 1
  177234. #define RBU_STATE_TBL 2
  177235. #define RBU_STATE_IDX 3
  177236. #define RBU_STATE_ROW 4
  177237. #define RBU_STATE_PROGRESS 5
  177238. #define RBU_STATE_CKPT 6
  177239. #define RBU_STATE_COOKIE 7
  177240. #define RBU_STATE_OALSZ 8
  177241. #define RBU_STATE_PHASEONESTEP 9
  177242. #define RBU_STATE_DATATBL 10
  177243. #define RBU_STAGE_OAL 1
  177244. #define RBU_STAGE_MOVE 2
  177245. #define RBU_STAGE_CAPTURE 3
  177246. #define RBU_STAGE_CKPT 4
  177247. #define RBU_STAGE_DONE 5
  177248. #define RBU_CREATE_STATE \
  177249. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  177250. typedef struct RbuFrame RbuFrame;
  177251. typedef struct RbuObjIter RbuObjIter;
  177252. typedef struct RbuState RbuState;
  177253. typedef struct rbu_vfs rbu_vfs;
  177254. typedef struct rbu_file rbu_file;
  177255. typedef struct RbuUpdateStmt RbuUpdateStmt;
  177256. #if !defined(SQLITE_AMALGAMATION)
  177257. typedef unsigned int u32;
  177258. typedef unsigned short u16;
  177259. typedef unsigned char u8;
  177260. typedef sqlite3_int64 i64;
  177261. #endif
  177262. /*
  177263. ** These values must match the values defined in wal.c for the equivalent
  177264. ** locks. These are not magic numbers as they are part of the SQLite file
  177265. ** format.
  177266. */
  177267. #define WAL_LOCK_WRITE 0
  177268. #define WAL_LOCK_CKPT 1
  177269. #define WAL_LOCK_READ0 3
  177270. #define SQLITE_FCNTL_RBUCNT 5149216
  177271. /*
  177272. ** A structure to store values read from the rbu_state table in memory.
  177273. */
  177274. struct RbuState {
  177275. int eStage;
  177276. char *zTbl;
  177277. char *zDataTbl;
  177278. char *zIdx;
  177279. i64 iWalCksum;
  177280. int nRow;
  177281. i64 nProgress;
  177282. u32 iCookie;
  177283. i64 iOalSz;
  177284. i64 nPhaseOneStep;
  177285. };
  177286. struct RbuUpdateStmt {
  177287. char *zMask; /* Copy of update mask used with pUpdate */
  177288. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  177289. RbuUpdateStmt *pNext;
  177290. };
  177291. /*
  177292. ** An iterator of this type is used to iterate through all objects in
  177293. ** the target database that require updating. For each such table, the
  177294. ** iterator visits, in order:
  177295. **
  177296. ** * the table itself,
  177297. ** * each index of the table (zero or more points to visit), and
  177298. ** * a special "cleanup table" state.
  177299. **
  177300. ** abIndexed:
  177301. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  177302. ** it points to an array of flags nTblCol elements in size. The flag is
  177303. ** set for each column that is either a part of the PK or a part of an
  177304. ** index. Or clear otherwise.
  177305. **
  177306. ** If there are one or more partial indexes on the table, all fields of
  177307. ** this array set set to 1. This is because in that case, the module has
  177308. ** no way to tell which fields will be required to add and remove entries
  177309. ** from the partial indexes.
  177310. **
  177311. */
  177312. struct RbuObjIter {
  177313. sqlite3_stmt *pTblIter; /* Iterate through tables */
  177314. sqlite3_stmt *pIdxIter; /* Index iterator */
  177315. int nTblCol; /* Size of azTblCol[] array */
  177316. char **azTblCol; /* Array of unquoted target column names */
  177317. char **azTblType; /* Array of target column types */
  177318. int *aiSrcOrder; /* src table col -> target table col */
  177319. u8 *abTblPk; /* Array of flags, set on target PK columns */
  177320. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  177321. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  177322. int eType; /* Table type - an RBU_PK_XXX value */
  177323. /* Output variables. zTbl==0 implies EOF. */
  177324. int bCleanup; /* True in "cleanup" state */
  177325. const char *zTbl; /* Name of target db table */
  177326. const char *zDataTbl; /* Name of rbu db table (or null) */
  177327. const char *zIdx; /* Name of target db index (or null) */
  177328. int iTnum; /* Root page of current object */
  177329. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  177330. int bUnique; /* Current index is unique */
  177331. int nIndex; /* Number of aux. indexes on table zTbl */
  177332. /* Statements created by rbuObjIterPrepareAll() */
  177333. int nCol; /* Number of columns in current object */
  177334. sqlite3_stmt *pSelect; /* Source data */
  177335. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  177336. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  177337. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  177338. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  177339. RbuUpdateStmt *pRbuUpdate;
  177340. };
  177341. /*
  177342. ** Values for RbuObjIter.eType
  177343. **
  177344. ** 0: Table does not exist (error)
  177345. ** 1: Table has an implicit rowid.
  177346. ** 2: Table has an explicit IPK column.
  177347. ** 3: Table has an external PK index.
  177348. ** 4: Table is WITHOUT ROWID.
  177349. ** 5: Table is a virtual table.
  177350. */
  177351. #define RBU_PK_NOTABLE 0
  177352. #define RBU_PK_NONE 1
  177353. #define RBU_PK_IPK 2
  177354. #define RBU_PK_EXTERNAL 3
  177355. #define RBU_PK_WITHOUT_ROWID 4
  177356. #define RBU_PK_VTAB 5
  177357. /*
  177358. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  177359. ** one of the following operations.
  177360. */
  177361. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  177362. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  177363. #define RBU_REPLACE 3 /* Delete and then insert a row */
  177364. #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
  177365. #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
  177366. #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
  177367. /*
  177368. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  177369. ** file should be copied to page iDbPage of the database file.
  177370. */
  177371. struct RbuFrame {
  177372. u32 iDbPage;
  177373. u32 iWalFrame;
  177374. };
  177375. /*
  177376. ** RBU handle.
  177377. **
  177378. ** nPhaseOneStep:
  177379. ** If the RBU database contains an rbu_count table, this value is set to
  177380. ** a running estimate of the number of b-tree operations required to
  177381. ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
  177382. ** API to calculate the permyriadage progress of populating the *-oal file
  177383. ** using the formula:
  177384. **
  177385. ** permyriadage = (10000 * nProgress) / nPhaseOneStep
  177386. **
  177387. ** nPhaseOneStep is initialized to the sum of:
  177388. **
  177389. ** nRow * (nIndex + 1)
  177390. **
  177391. ** for all source tables in the RBU database, where nRow is the number
  177392. ** of rows in the source table and nIndex the number of indexes on the
  177393. ** corresponding target database table.
  177394. **
  177395. ** This estimate is accurate if the RBU update consists entirely of
  177396. ** INSERT operations. However, it is inaccurate if:
  177397. **
  177398. ** * the RBU update contains any UPDATE operations. If the PK specified
  177399. ** for an UPDATE operation does not exist in the target table, then
  177400. ** no b-tree operations are required on index b-trees. Or if the
  177401. ** specified PK does exist, then (nIndex*2) such operations are
  177402. ** required (one delete and one insert on each index b-tree).
  177403. **
  177404. ** * the RBU update contains any DELETE operations for which the specified
  177405. ** PK does not exist. In this case no operations are required on index
  177406. ** b-trees.
  177407. **
  177408. ** * the RBU update contains REPLACE operations. These are similar to
  177409. ** UPDATE operations.
  177410. **
  177411. ** nPhaseOneStep is updated to account for the conditions above during the
  177412. ** first pass of each source table. The updated nPhaseOneStep value is
  177413. ** stored in the rbu_state table if the RBU update is suspended.
  177414. */
  177415. struct sqlite3rbu {
  177416. int eStage; /* Value of RBU_STATE_STAGE field */
  177417. sqlite3 *dbMain; /* target database handle */
  177418. sqlite3 *dbRbu; /* rbu database handle */
  177419. char *zTarget; /* Path to target db */
  177420. char *zRbu; /* Path to rbu db */
  177421. char *zState; /* Path to state db (or NULL if zRbu) */
  177422. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  177423. int rc; /* Value returned by last rbu_step() call */
  177424. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  177425. int nStep; /* Rows processed for current object */
  177426. int nProgress; /* Rows processed for all objects */
  177427. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  177428. const char *zVfsName; /* Name of automatically created rbu vfs */
  177429. rbu_file *pTargetFd; /* File handle open on target db */
  177430. int nPagePerSector; /* Pages per sector for pTargetFd */
  177431. i64 iOalSz;
  177432. i64 nPhaseOneStep;
  177433. /* The following state variables are used as part of the incremental
  177434. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  177435. ** function rbuSetupCheckpoint() for details. */
  177436. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  177437. u32 mLock;
  177438. int nFrame; /* Entries in aFrame[] array */
  177439. int nFrameAlloc; /* Allocated size of aFrame[] array */
  177440. RbuFrame *aFrame;
  177441. int pgsz;
  177442. u8 *aBuf;
  177443. i64 iWalCksum;
  177444. i64 szTemp; /* Current size of all temp files in use */
  177445. i64 szTempLimit; /* Total size limit for temp files */
  177446. /* Used in RBU vacuum mode only */
  177447. int nRbu; /* Number of RBU VFS in the stack */
  177448. rbu_file *pRbuFd; /* Fd for main db of dbRbu */
  177449. };
  177450. /*
  177451. ** An rbu VFS is implemented using an instance of this structure.
  177452. **
  177453. ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
  177454. ** It is NULL for RBU VFS objects created explicitly using
  177455. ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
  177456. ** space used by the RBU handle.
  177457. */
  177458. struct rbu_vfs {
  177459. sqlite3_vfs base; /* rbu VFS shim methods */
  177460. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  177461. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  177462. sqlite3rbu *pRbu; /* Owner RBU object */
  177463. rbu_file *pMain; /* List of main db files */
  177464. rbu_file *pMainRbu; /* List of main db files with pRbu!=0 */
  177465. };
  177466. /*
  177467. ** Each file opened by an rbu VFS is represented by an instance of
  177468. ** the following structure.
  177469. **
  177470. ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
  177471. ** "sz" is set to the current size of the database file.
  177472. */
  177473. struct rbu_file {
  177474. sqlite3_file base; /* sqlite3_file methods */
  177475. sqlite3_file *pReal; /* Underlying file handle */
  177476. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  177477. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  177478. i64 sz; /* Size of file in bytes (temp only) */
  177479. int openFlags; /* Flags this file was opened with */
  177480. u32 iCookie; /* Cookie value for main db files */
  177481. u8 iWriteVer; /* "write-version" value for main db files */
  177482. u8 bNolock; /* True to fail EXCLUSIVE locks */
  177483. int nShm; /* Number of entries in apShm[] array */
  177484. char **apShm; /* Array of mmap'd *-shm regions */
  177485. char *zDel; /* Delete this when closing file */
  177486. const char *zWal; /* Wal filename for this main db file */
  177487. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  177488. rbu_file *pMainNext; /* Next MAIN_DB file */
  177489. rbu_file *pMainRbuNext; /* Next MAIN_DB file with pRbu!=0 */
  177490. };
  177491. /*
  177492. ** True for an RBU vacuum handle, or false otherwise.
  177493. */
  177494. #define rbuIsVacuum(p) ((p)->zTarget==0)
  177495. /*************************************************************************
  177496. ** The following three functions, found below:
  177497. **
  177498. ** rbuDeltaGetInt()
  177499. ** rbuDeltaChecksum()
  177500. ** rbuDeltaApply()
  177501. **
  177502. ** are lifted from the fossil source code (http://fossil-scm.org). They
  177503. ** are used to implement the scalar SQL function rbu_fossil_delta().
  177504. */
  177505. /*
  177506. ** Read bytes from *pz and convert them into a positive integer. When
  177507. ** finished, leave *pz pointing to the first character past the end of
  177508. ** the integer. The *pLen parameter holds the length of the string
  177509. ** in *pz and is decremented once for each character in the integer.
  177510. */
  177511. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  177512. static const signed char zValue[] = {
  177513. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  177514. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  177515. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  177516. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  177517. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  177518. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  177519. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  177520. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  177521. };
  177522. unsigned int v = 0;
  177523. int c;
  177524. unsigned char *z = (unsigned char*)*pz;
  177525. unsigned char *zStart = z;
  177526. while( (c = zValue[0x7f&*(z++)])>=0 ){
  177527. v = (v<<6) + c;
  177528. }
  177529. z--;
  177530. *pLen -= z - zStart;
  177531. *pz = (char*)z;
  177532. return v;
  177533. }
  177534. #if RBU_ENABLE_DELTA_CKSUM
  177535. /*
  177536. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  177537. */
  177538. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  177539. const unsigned char *z = (const unsigned char *)zIn;
  177540. unsigned sum0 = 0;
  177541. unsigned sum1 = 0;
  177542. unsigned sum2 = 0;
  177543. unsigned sum3 = 0;
  177544. while(N >= 16){
  177545. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  177546. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  177547. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  177548. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  177549. z += 16;
  177550. N -= 16;
  177551. }
  177552. while(N >= 4){
  177553. sum0 += z[0];
  177554. sum1 += z[1];
  177555. sum2 += z[2];
  177556. sum3 += z[3];
  177557. z += 4;
  177558. N -= 4;
  177559. }
  177560. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  177561. switch(N){
  177562. case 3: sum3 += (z[2] << 8);
  177563. case 2: sum3 += (z[1] << 16);
  177564. case 1: sum3 += (z[0] << 24);
  177565. default: ;
  177566. }
  177567. return sum3;
  177568. }
  177569. #endif
  177570. /*
  177571. ** Apply a delta.
  177572. **
  177573. ** The output buffer should be big enough to hold the whole output
  177574. ** file and a NUL terminator at the end. The delta_output_size()
  177575. ** routine will determine this size for you.
  177576. **
  177577. ** The delta string should be null-terminated. But the delta string
  177578. ** may contain embedded NUL characters (if the input and output are
  177579. ** binary files) so we also have to pass in the length of the delta in
  177580. ** the lenDelta parameter.
  177581. **
  177582. ** This function returns the size of the output file in bytes (excluding
  177583. ** the final NUL terminator character). Except, if the delta string is
  177584. ** malformed or intended for use with a source file other than zSrc,
  177585. ** then this routine returns -1.
  177586. **
  177587. ** Refer to the delta_create() documentation above for a description
  177588. ** of the delta file format.
  177589. */
  177590. static int rbuDeltaApply(
  177591. const char *zSrc, /* The source or pattern file */
  177592. int lenSrc, /* Length of the source file */
  177593. const char *zDelta, /* Delta to apply to the pattern */
  177594. int lenDelta, /* Length of the delta */
  177595. char *zOut /* Write the output into this preallocated buffer */
  177596. ){
  177597. unsigned int limit;
  177598. unsigned int total = 0;
  177599. #if RBU_ENABLE_DELTA_CKSUM
  177600. char *zOrigOut = zOut;
  177601. #endif
  177602. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  177603. if( *zDelta!='\n' ){
  177604. /* ERROR: size integer not terminated by "\n" */
  177605. return -1;
  177606. }
  177607. zDelta++; lenDelta--;
  177608. while( *zDelta && lenDelta>0 ){
  177609. unsigned int cnt, ofst;
  177610. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  177611. switch( zDelta[0] ){
  177612. case '@': {
  177613. zDelta++; lenDelta--;
  177614. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  177615. if( lenDelta>0 && zDelta[0]!=',' ){
  177616. /* ERROR: copy command not terminated by ',' */
  177617. return -1;
  177618. }
  177619. zDelta++; lenDelta--;
  177620. total += cnt;
  177621. if( total>limit ){
  177622. /* ERROR: copy exceeds output file size */
  177623. return -1;
  177624. }
  177625. if( (int)(ofst+cnt) > lenSrc ){
  177626. /* ERROR: copy extends past end of input */
  177627. return -1;
  177628. }
  177629. memcpy(zOut, &zSrc[ofst], cnt);
  177630. zOut += cnt;
  177631. break;
  177632. }
  177633. case ':': {
  177634. zDelta++; lenDelta--;
  177635. total += cnt;
  177636. if( total>limit ){
  177637. /* ERROR: insert command gives an output larger than predicted */
  177638. return -1;
  177639. }
  177640. if( (int)cnt>lenDelta ){
  177641. /* ERROR: insert count exceeds size of delta */
  177642. return -1;
  177643. }
  177644. memcpy(zOut, zDelta, cnt);
  177645. zOut += cnt;
  177646. zDelta += cnt;
  177647. lenDelta -= cnt;
  177648. break;
  177649. }
  177650. case ';': {
  177651. zDelta++; lenDelta--;
  177652. zOut[0] = 0;
  177653. #if RBU_ENABLE_DELTA_CKSUM
  177654. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  177655. /* ERROR: bad checksum */
  177656. return -1;
  177657. }
  177658. #endif
  177659. if( total!=limit ){
  177660. /* ERROR: generated size does not match predicted size */
  177661. return -1;
  177662. }
  177663. return total;
  177664. }
  177665. default: {
  177666. /* ERROR: unknown delta operator */
  177667. return -1;
  177668. }
  177669. }
  177670. }
  177671. /* ERROR: unterminated delta */
  177672. return -1;
  177673. }
  177674. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  177675. int size;
  177676. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  177677. if( *zDelta!='\n' ){
  177678. /* ERROR: size integer not terminated by "\n" */
  177679. return -1;
  177680. }
  177681. return size;
  177682. }
  177683. /*
  177684. ** End of code taken from fossil.
  177685. *************************************************************************/
  177686. /*
  177687. ** Implementation of SQL scalar function rbu_fossil_delta().
  177688. **
  177689. ** This function applies a fossil delta patch to a blob. Exactly two
  177690. ** arguments must be passed to this function. The first is the blob to
  177691. ** patch and the second the patch to apply. If no error occurs, this
  177692. ** function returns the patched blob.
  177693. */
  177694. static void rbuFossilDeltaFunc(
  177695. sqlite3_context *context,
  177696. int argc,
  177697. sqlite3_value **argv
  177698. ){
  177699. const char *aDelta;
  177700. int nDelta;
  177701. const char *aOrig;
  177702. int nOrig;
  177703. int nOut;
  177704. int nOut2;
  177705. char *aOut;
  177706. assert( argc==2 );
  177707. nOrig = sqlite3_value_bytes(argv[0]);
  177708. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  177709. nDelta = sqlite3_value_bytes(argv[1]);
  177710. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  177711. /* Figure out the size of the output */
  177712. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  177713. if( nOut<0 ){
  177714. sqlite3_result_error(context, "corrupt fossil delta", -1);
  177715. return;
  177716. }
  177717. aOut = sqlite3_malloc(nOut+1);
  177718. if( aOut==0 ){
  177719. sqlite3_result_error_nomem(context);
  177720. }else{
  177721. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  177722. if( nOut2!=nOut ){
  177723. sqlite3_free(aOut);
  177724. sqlite3_result_error(context, "corrupt fossil delta", -1);
  177725. }else{
  177726. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  177727. }
  177728. }
  177729. }
  177730. /*
  177731. ** Prepare the SQL statement in buffer zSql against database handle db.
  177732. ** If successful, set *ppStmt to point to the new statement and return
  177733. ** SQLITE_OK.
  177734. **
  177735. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  177736. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  177737. ** point to a buffer containing an error message. It is the responsibility
  177738. ** of the caller to (eventually) free this buffer using sqlite3_free().
  177739. */
  177740. static int prepareAndCollectError(
  177741. sqlite3 *db,
  177742. sqlite3_stmt **ppStmt,
  177743. char **pzErrmsg,
  177744. const char *zSql
  177745. ){
  177746. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  177747. if( rc!=SQLITE_OK ){
  177748. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  177749. *ppStmt = 0;
  177750. }
  177751. return rc;
  177752. }
  177753. /*
  177754. ** Reset the SQL statement passed as the first argument. Return a copy
  177755. ** of the value returned by sqlite3_reset().
  177756. **
  177757. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  177758. ** containing an error message. It is the responsibility of the caller
  177759. ** to eventually free this buffer using sqlite3_free().
  177760. */
  177761. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  177762. int rc = sqlite3_reset(pStmt);
  177763. if( rc!=SQLITE_OK ){
  177764. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  177765. }
  177766. return rc;
  177767. }
  177768. /*
  177769. ** Unless it is NULL, argument zSql points to a buffer allocated using
  177770. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  177771. ** statement against database db and frees the buffer. If statement
  177772. ** compilation is successful, *ppStmt is set to point to the new statement
  177773. ** handle and SQLITE_OK is returned.
  177774. **
  177775. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  177776. ** returned. In this case, *pzErrmsg may also be set to point to an error
  177777. ** message. It is the responsibility of the caller to free this error message
  177778. ** buffer using sqlite3_free().
  177779. **
  177780. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  177781. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  177782. */
  177783. static int prepareFreeAndCollectError(
  177784. sqlite3 *db,
  177785. sqlite3_stmt **ppStmt,
  177786. char **pzErrmsg,
  177787. char *zSql
  177788. ){
  177789. int rc;
  177790. assert( *pzErrmsg==0 );
  177791. if( zSql==0 ){
  177792. rc = SQLITE_NOMEM;
  177793. *ppStmt = 0;
  177794. }else{
  177795. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  177796. sqlite3_free(zSql);
  177797. }
  177798. return rc;
  177799. }
  177800. /*
  177801. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  177802. ** by an earlier call to rbuObjIterCacheTableInfo().
  177803. */
  177804. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  177805. int i;
  177806. for(i=0; i<pIter->nTblCol; i++){
  177807. sqlite3_free(pIter->azTblCol[i]);
  177808. sqlite3_free(pIter->azTblType[i]);
  177809. }
  177810. sqlite3_free(pIter->azTblCol);
  177811. pIter->azTblCol = 0;
  177812. pIter->azTblType = 0;
  177813. pIter->aiSrcOrder = 0;
  177814. pIter->abTblPk = 0;
  177815. pIter->abNotNull = 0;
  177816. pIter->nTblCol = 0;
  177817. pIter->eType = 0; /* Invalid value */
  177818. }
  177819. /*
  177820. ** Finalize all statements and free all allocations that are specific to
  177821. ** the current object (table/index pair).
  177822. */
  177823. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  177824. RbuUpdateStmt *pUp;
  177825. sqlite3_finalize(pIter->pSelect);
  177826. sqlite3_finalize(pIter->pInsert);
  177827. sqlite3_finalize(pIter->pDelete);
  177828. sqlite3_finalize(pIter->pTmpInsert);
  177829. pUp = pIter->pRbuUpdate;
  177830. while( pUp ){
  177831. RbuUpdateStmt *pTmp = pUp->pNext;
  177832. sqlite3_finalize(pUp->pUpdate);
  177833. sqlite3_free(pUp);
  177834. pUp = pTmp;
  177835. }
  177836. pIter->pSelect = 0;
  177837. pIter->pInsert = 0;
  177838. pIter->pDelete = 0;
  177839. pIter->pRbuUpdate = 0;
  177840. pIter->pTmpInsert = 0;
  177841. pIter->nCol = 0;
  177842. }
  177843. /*
  177844. ** Clean up any resources allocated as part of the iterator object passed
  177845. ** as the only argument.
  177846. */
  177847. static void rbuObjIterFinalize(RbuObjIter *pIter){
  177848. rbuObjIterClearStatements(pIter);
  177849. sqlite3_finalize(pIter->pTblIter);
  177850. sqlite3_finalize(pIter->pIdxIter);
  177851. rbuObjIterFreeCols(pIter);
  177852. memset(pIter, 0, sizeof(RbuObjIter));
  177853. }
  177854. /*
  177855. ** Advance the iterator to the next position.
  177856. **
  177857. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  177858. ** pointing to the next entry. Otherwise, an error code and message is
  177859. ** left in the RBU handle passed as the first argument. A copy of the
  177860. ** error code is returned.
  177861. */
  177862. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  177863. int rc = p->rc;
  177864. if( rc==SQLITE_OK ){
  177865. /* Free any SQLite statements used while processing the previous object */
  177866. rbuObjIterClearStatements(pIter);
  177867. if( pIter->zIdx==0 ){
  177868. rc = sqlite3_exec(p->dbMain,
  177869. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  177870. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  177871. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  177872. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  177873. , 0, 0, &p->zErrmsg
  177874. );
  177875. }
  177876. if( rc==SQLITE_OK ){
  177877. if( pIter->bCleanup ){
  177878. rbuObjIterFreeCols(pIter);
  177879. pIter->bCleanup = 0;
  177880. rc = sqlite3_step(pIter->pTblIter);
  177881. if( rc!=SQLITE_ROW ){
  177882. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  177883. pIter->zTbl = 0;
  177884. }else{
  177885. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  177886. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  177887. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  177888. }
  177889. }else{
  177890. if( pIter->zIdx==0 ){
  177891. sqlite3_stmt *pIdx = pIter->pIdxIter;
  177892. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  177893. }
  177894. if( rc==SQLITE_OK ){
  177895. rc = sqlite3_step(pIter->pIdxIter);
  177896. if( rc!=SQLITE_ROW ){
  177897. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  177898. pIter->bCleanup = 1;
  177899. pIter->zIdx = 0;
  177900. }else{
  177901. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  177902. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  177903. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  177904. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  177905. }
  177906. }
  177907. }
  177908. }
  177909. }
  177910. if( rc!=SQLITE_OK ){
  177911. rbuObjIterFinalize(pIter);
  177912. p->rc = rc;
  177913. }
  177914. return rc;
  177915. }
  177916. /*
  177917. ** The implementation of the rbu_target_name() SQL function. This function
  177918. ** accepts one or two arguments. The first argument is the name of a table -
  177919. ** the name of a table in the RBU database. The second, if it is present, is 1
  177920. ** for a view or 0 for a table.
  177921. **
  177922. ** For a non-vacuum RBU handle, if the table name matches the pattern:
  177923. **
  177924. ** data[0-9]_<name>
  177925. **
  177926. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  177927. ** Otherwise, if the only argument does not match the above pattern, an SQL
  177928. ** NULL is returned.
  177929. **
  177930. ** "data_t1" -> "t1"
  177931. ** "data0123_t2" -> "t2"
  177932. ** "dataAB_t3" -> NULL
  177933. **
  177934. ** For an rbu vacuum handle, a copy of the first argument is returned if
  177935. ** the second argument is either missing or 0 (not a view).
  177936. */
  177937. static void rbuTargetNameFunc(
  177938. sqlite3_context *pCtx,
  177939. int argc,
  177940. sqlite3_value **argv
  177941. ){
  177942. sqlite3rbu *p = sqlite3_user_data(pCtx);
  177943. const char *zIn;
  177944. assert( argc==1 || argc==2 );
  177945. zIn = (const char*)sqlite3_value_text(argv[0]);
  177946. if( zIn ){
  177947. if( rbuIsVacuum(p) ){
  177948. if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
  177949. sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
  177950. }
  177951. }else{
  177952. if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  177953. int i;
  177954. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  177955. if( zIn[i]=='_' && zIn[i+1] ){
  177956. sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
  177957. }
  177958. }
  177959. }
  177960. }
  177961. }
  177962. /*
  177963. ** Initialize the iterator structure passed as the second argument.
  177964. **
  177965. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  177966. ** pointing to the first entry. Otherwise, an error code and message is
  177967. ** left in the RBU handle passed as the first argument. A copy of the
  177968. ** error code is returned.
  177969. */
  177970. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  177971. int rc;
  177972. memset(pIter, 0, sizeof(RbuObjIter));
  177973. rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  177974. sqlite3_mprintf(
  177975. "SELECT rbu_target_name(name, type='view') AS target, name "
  177976. "FROM sqlite_master "
  177977. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  177978. " %s "
  177979. "ORDER BY name"
  177980. , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
  177981. if( rc==SQLITE_OK ){
  177982. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  177983. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  177984. " FROM main.sqlite_master "
  177985. " WHERE type='index' AND tbl_name = ?"
  177986. );
  177987. }
  177988. pIter->bCleanup = 1;
  177989. p->rc = rc;
  177990. return rbuObjIterNext(p, pIter);
  177991. }
  177992. /*
  177993. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  177994. ** an error code is stored in the RBU handle passed as the first argument.
  177995. **
  177996. ** If an error has already occurred (p->rc is already set to something other
  177997. ** than SQLITE_OK), then this function returns NULL without modifying the
  177998. ** stored error code. In this case it still calls sqlite3_free() on any
  177999. ** printf() parameters associated with %z conversions.
  178000. */
  178001. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  178002. char *zSql = 0;
  178003. va_list ap;
  178004. va_start(ap, zFmt);
  178005. zSql = sqlite3_vmprintf(zFmt, ap);
  178006. if( p->rc==SQLITE_OK ){
  178007. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  178008. }else{
  178009. sqlite3_free(zSql);
  178010. zSql = 0;
  178011. }
  178012. va_end(ap);
  178013. return zSql;
  178014. }
  178015. /*
  178016. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  178017. ** arguments are the usual subsitution values. This function performs
  178018. ** the printf() style substitutions and executes the result as an SQL
  178019. ** statement on the RBU handles database.
  178020. **
  178021. ** If an error occurs, an error code and error message is stored in the
  178022. ** RBU handle. If an error has already occurred when this function is
  178023. ** called, it is a no-op.
  178024. */
  178025. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  178026. va_list ap;
  178027. char *zSql;
  178028. va_start(ap, zFmt);
  178029. zSql = sqlite3_vmprintf(zFmt, ap);
  178030. if( p->rc==SQLITE_OK ){
  178031. if( zSql==0 ){
  178032. p->rc = SQLITE_NOMEM;
  178033. }else{
  178034. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  178035. }
  178036. }
  178037. sqlite3_free(zSql);
  178038. va_end(ap);
  178039. return p->rc;
  178040. }
  178041. /*
  178042. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  178043. ** bytes.
  178044. **
  178045. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  178046. ** error code in the rbu handle passed as the first argument. Or, if an
  178047. ** error has already occurred when this function is called, return NULL
  178048. ** immediately without attempting the allocation or modifying the stored
  178049. ** error code.
  178050. */
  178051. static void *rbuMalloc(sqlite3rbu *p, sqlite3_int64 nByte){
  178052. void *pRet = 0;
  178053. if( p->rc==SQLITE_OK ){
  178054. assert( nByte>0 );
  178055. pRet = sqlite3_malloc64(nByte);
  178056. if( pRet==0 ){
  178057. p->rc = SQLITE_NOMEM;
  178058. }else{
  178059. memset(pRet, 0, nByte);
  178060. }
  178061. }
  178062. return pRet;
  178063. }
  178064. /*
  178065. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  178066. ** there is room for at least nCol elements. If an OOM occurs, store an
  178067. ** error code in the RBU handle passed as the first argument.
  178068. */
  178069. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  178070. sqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  178071. char **azNew;
  178072. azNew = (char**)rbuMalloc(p, nByte);
  178073. if( azNew ){
  178074. pIter->azTblCol = azNew;
  178075. pIter->azTblType = &azNew[nCol];
  178076. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  178077. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  178078. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  178079. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  178080. }
  178081. }
  178082. /*
  178083. ** The first argument must be a nul-terminated string. This function
  178084. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  178085. ** It is the responsibility of the caller to eventually free this memory
  178086. ** using sqlite3_free().
  178087. **
  178088. ** If an OOM condition is encountered when attempting to allocate memory,
  178089. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  178090. ** if the allocation succeeds, (*pRc) is left unchanged.
  178091. */
  178092. static char *rbuStrndup(const char *zStr, int *pRc){
  178093. char *zRet = 0;
  178094. assert( *pRc==SQLITE_OK );
  178095. if( zStr ){
  178096. size_t nCopy = strlen(zStr) + 1;
  178097. zRet = (char*)sqlite3_malloc64(nCopy);
  178098. if( zRet ){
  178099. memcpy(zRet, zStr, nCopy);
  178100. }else{
  178101. *pRc = SQLITE_NOMEM;
  178102. }
  178103. }
  178104. return zRet;
  178105. }
  178106. /*
  178107. ** Finalize the statement passed as the second argument.
  178108. **
  178109. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  178110. ** rbu handle error code is not already set, set the error code and error
  178111. ** message accordingly.
  178112. */
  178113. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  178114. sqlite3 *db = sqlite3_db_handle(pStmt);
  178115. int rc = sqlite3_finalize(pStmt);
  178116. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  178117. p->rc = rc;
  178118. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  178119. }
  178120. }
  178121. /* Determine the type of a table.
  178122. **
  178123. ** peType is of type (int*), a pointer to an output parameter of type
  178124. ** (int). This call sets the output parameter as follows, depending
  178125. ** on the type of the table specified by parameters dbName and zTbl.
  178126. **
  178127. ** RBU_PK_NOTABLE: No such table.
  178128. ** RBU_PK_NONE: Table has an implicit rowid.
  178129. ** RBU_PK_IPK: Table has an explicit IPK column.
  178130. ** RBU_PK_EXTERNAL: Table has an external PK index.
  178131. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  178132. ** RBU_PK_VTAB: Table is a virtual table.
  178133. **
  178134. ** Argument *piPk is also of type (int*), and also points to an output
  178135. ** parameter. Unless the table has an external primary key index
  178136. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  178137. ** if the table does have an external primary key index, then *piPk
  178138. ** is set to the root page number of the primary key index before
  178139. ** returning.
  178140. **
  178141. ** ALGORITHM:
  178142. **
  178143. ** if( no entry exists in sqlite_master ){
  178144. ** return RBU_PK_NOTABLE
  178145. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  178146. ** return RBU_PK_VTAB
  178147. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  178148. ** if( the index that is the pk exists in sqlite_master ){
  178149. ** *piPK = rootpage of that index.
  178150. ** return RBU_PK_EXTERNAL
  178151. ** }else{
  178152. ** return RBU_PK_WITHOUT_ROWID
  178153. ** }
  178154. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  178155. ** return RBU_PK_IPK
  178156. ** }else{
  178157. ** return RBU_PK_NONE
  178158. ** }
  178159. */
  178160. static void rbuTableType(
  178161. sqlite3rbu *p,
  178162. const char *zTab,
  178163. int *peType,
  178164. int *piTnum,
  178165. int *piPk
  178166. ){
  178167. /*
  178168. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  178169. ** 1) PRAGMA index_list = ?
  178170. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  178171. ** 3) PRAGMA table_info = ?
  178172. */
  178173. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  178174. *peType = RBU_PK_NOTABLE;
  178175. *piPk = 0;
  178176. assert( p->rc==SQLITE_OK );
  178177. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  178178. sqlite3_mprintf(
  178179. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  178180. " FROM sqlite_master"
  178181. " WHERE name=%Q", zTab
  178182. ));
  178183. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  178184. /* Either an error, or no such table. */
  178185. goto rbuTableType_end;
  178186. }
  178187. if( sqlite3_column_int(aStmt[0], 0) ){
  178188. *peType = RBU_PK_VTAB; /* virtual table */
  178189. goto rbuTableType_end;
  178190. }
  178191. *piTnum = sqlite3_column_int(aStmt[0], 1);
  178192. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  178193. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  178194. );
  178195. if( p->rc ) goto rbuTableType_end;
  178196. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  178197. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  178198. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  178199. if( zOrig && zIdx && zOrig[0]=='p' ){
  178200. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  178201. sqlite3_mprintf(
  178202. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  178203. ));
  178204. if( p->rc==SQLITE_OK ){
  178205. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  178206. *piPk = sqlite3_column_int(aStmt[2], 0);
  178207. *peType = RBU_PK_EXTERNAL;
  178208. }else{
  178209. *peType = RBU_PK_WITHOUT_ROWID;
  178210. }
  178211. }
  178212. goto rbuTableType_end;
  178213. }
  178214. }
  178215. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  178216. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  178217. );
  178218. if( p->rc==SQLITE_OK ){
  178219. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  178220. if( sqlite3_column_int(aStmt[3],5)>0 ){
  178221. *peType = RBU_PK_IPK; /* explicit IPK column */
  178222. goto rbuTableType_end;
  178223. }
  178224. }
  178225. *peType = RBU_PK_NONE;
  178226. }
  178227. rbuTableType_end: {
  178228. unsigned int i;
  178229. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  178230. rbuFinalize(p, aStmt[i]);
  178231. }
  178232. }
  178233. }
  178234. /*
  178235. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  178236. ** the pIter->abIndexed[] array.
  178237. */
  178238. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  178239. sqlite3_stmt *pList = 0;
  178240. int bIndex = 0;
  178241. if( p->rc==SQLITE_OK ){
  178242. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  178243. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  178244. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  178245. );
  178246. }
  178247. pIter->nIndex = 0;
  178248. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  178249. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  178250. int bPartial = sqlite3_column_int(pList, 4);
  178251. sqlite3_stmt *pXInfo = 0;
  178252. if( zIdx==0 ) break;
  178253. if( bPartial ){
  178254. memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
  178255. }
  178256. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  178257. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  178258. );
  178259. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  178260. int iCid = sqlite3_column_int(pXInfo, 1);
  178261. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  178262. }
  178263. rbuFinalize(p, pXInfo);
  178264. bIndex = 1;
  178265. pIter->nIndex++;
  178266. }
  178267. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  178268. /* "PRAGMA index_list" includes the main PK b-tree */
  178269. pIter->nIndex--;
  178270. }
  178271. rbuFinalize(p, pList);
  178272. if( bIndex==0 ) pIter->abIndexed = 0;
  178273. }
  178274. /*
  178275. ** If they are not already populated, populate the pIter->azTblCol[],
  178276. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  178277. ** the table (not index) that the iterator currently points to.
  178278. **
  178279. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  178280. ** an error does occur, an error code and error message are also left in
  178281. ** the RBU handle.
  178282. */
  178283. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  178284. if( pIter->azTblCol==0 ){
  178285. sqlite3_stmt *pStmt = 0;
  178286. int nCol = 0;
  178287. int i; /* for() loop iterator variable */
  178288. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  178289. int iOrder = 0;
  178290. int iTnum = 0;
  178291. /* Figure out the type of table this step will deal with. */
  178292. assert( pIter->eType==0 );
  178293. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  178294. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  178295. p->rc = SQLITE_ERROR;
  178296. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  178297. }
  178298. if( p->rc ) return p->rc;
  178299. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  178300. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  178301. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  178302. || pIter->eType==RBU_PK_VTAB
  178303. );
  178304. /* Populate the azTblCol[] and nTblCol variables based on the columns
  178305. ** of the input table. Ignore any input table columns that begin with
  178306. ** "rbu_". */
  178307. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  178308. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  178309. );
  178310. if( p->rc==SQLITE_OK ){
  178311. nCol = sqlite3_column_count(pStmt);
  178312. rbuAllocateIterArrays(p, pIter, nCol);
  178313. }
  178314. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  178315. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  178316. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  178317. char *zCopy = rbuStrndup(zName, &p->rc);
  178318. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  178319. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  178320. }
  178321. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  178322. bRbuRowid = 1;
  178323. }
  178324. }
  178325. sqlite3_finalize(pStmt);
  178326. pStmt = 0;
  178327. if( p->rc==SQLITE_OK
  178328. && rbuIsVacuum(p)==0
  178329. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  178330. ){
  178331. p->rc = SQLITE_ERROR;
  178332. p->zErrmsg = sqlite3_mprintf(
  178333. "table %q %s rbu_rowid column", pIter->zDataTbl,
  178334. (bRbuRowid ? "may not have" : "requires")
  178335. );
  178336. }
  178337. /* Check that all non-HIDDEN columns in the destination table are also
  178338. ** present in the input table. Populate the abTblPk[], azTblType[] and
  178339. ** aiTblOrder[] arrays at the same time. */
  178340. if( p->rc==SQLITE_OK ){
  178341. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  178342. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  178343. );
  178344. }
  178345. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  178346. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  178347. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  178348. for(i=iOrder; i<pIter->nTblCol; i++){
  178349. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  178350. }
  178351. if( i==pIter->nTblCol ){
  178352. p->rc = SQLITE_ERROR;
  178353. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  178354. pIter->zDataTbl, zName
  178355. );
  178356. }else{
  178357. int iPk = sqlite3_column_int(pStmt, 5);
  178358. int bNotNull = sqlite3_column_int(pStmt, 3);
  178359. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  178360. if( i!=iOrder ){
  178361. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  178362. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  178363. }
  178364. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  178365. pIter->abTblPk[iOrder] = (iPk!=0);
  178366. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  178367. iOrder++;
  178368. }
  178369. }
  178370. rbuFinalize(p, pStmt);
  178371. rbuObjIterCacheIndexedCols(p, pIter);
  178372. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  178373. assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
  178374. }
  178375. return p->rc;
  178376. }
  178377. /*
  178378. ** This function constructs and returns a pointer to a nul-terminated
  178379. ** string containing some SQL clause or list based on one or more of the
  178380. ** column names currently stored in the pIter->azTblCol[] array.
  178381. */
  178382. static char *rbuObjIterGetCollist(
  178383. sqlite3rbu *p, /* RBU object */
  178384. RbuObjIter *pIter /* Object iterator for column names */
  178385. ){
  178386. char *zList = 0;
  178387. const char *zSep = "";
  178388. int i;
  178389. for(i=0; i<pIter->nTblCol; i++){
  178390. const char *z = pIter->azTblCol[i];
  178391. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  178392. zSep = ", ";
  178393. }
  178394. return zList;
  178395. }
  178396. /*
  178397. ** This function is used to create a SELECT list (the list of SQL
  178398. ** expressions that follows a SELECT keyword) for a SELECT statement
  178399. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  178400. ** index object currently indicated by the iterator object passed as the
  178401. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  178402. ** to obtain the required information.
  178403. **
  178404. ** If the index is of the following form:
  178405. **
  178406. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  178407. **
  178408. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  178409. ** "ipk", the returned string is:
  178410. **
  178411. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  178412. **
  178413. ** As well as the returned string, three other malloc'd strings are
  178414. ** returned via output parameters. As follows:
  178415. **
  178416. ** pzImposterCols: ...
  178417. ** pzImposterPk: ...
  178418. ** pzWhere: ...
  178419. */
  178420. static char *rbuObjIterGetIndexCols(
  178421. sqlite3rbu *p, /* RBU object */
  178422. RbuObjIter *pIter, /* Object iterator for column names */
  178423. char **pzImposterCols, /* OUT: Columns for imposter table */
  178424. char **pzImposterPk, /* OUT: Imposter PK clause */
  178425. char **pzWhere, /* OUT: WHERE clause */
  178426. int *pnBind /* OUT: Trbul number of columns */
  178427. ){
  178428. int rc = p->rc; /* Error code */
  178429. int rc2; /* sqlite3_finalize() return code */
  178430. char *zRet = 0; /* String to return */
  178431. char *zImpCols = 0; /* String to return via *pzImposterCols */
  178432. char *zImpPK = 0; /* String to return via *pzImposterPK */
  178433. char *zWhere = 0; /* String to return via *pzWhere */
  178434. int nBind = 0; /* Value to return via *pnBind */
  178435. const char *zCom = ""; /* Set to ", " later on */
  178436. const char *zAnd = ""; /* Set to " AND " later on */
  178437. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  178438. if( rc==SQLITE_OK ){
  178439. assert( p->zErrmsg==0 );
  178440. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  178441. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  178442. );
  178443. }
  178444. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  178445. int iCid = sqlite3_column_int(pXInfo, 1);
  178446. int bDesc = sqlite3_column_int(pXInfo, 3);
  178447. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  178448. const char *zCol;
  178449. const char *zType;
  178450. if( iCid<0 ){
  178451. /* An integer primary key. If the table has an explicit IPK, use
  178452. ** its name. Otherwise, use "rbu_rowid". */
  178453. if( pIter->eType==RBU_PK_IPK ){
  178454. int i;
  178455. for(i=0; pIter->abTblPk[i]==0; i++);
  178456. assert( i<pIter->nTblCol );
  178457. zCol = pIter->azTblCol[i];
  178458. }else if( rbuIsVacuum(p) ){
  178459. zCol = "_rowid_";
  178460. }else{
  178461. zCol = "rbu_rowid";
  178462. }
  178463. zType = "INTEGER";
  178464. }else{
  178465. zCol = pIter->azTblCol[iCid];
  178466. zType = pIter->azTblType[iCid];
  178467. }
  178468. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  178469. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  178470. const char *zOrder = (bDesc ? " DESC" : "");
  178471. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  178472. zImpPK, zCom, nBind, zCol, zOrder
  178473. );
  178474. }
  178475. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  178476. zImpCols, zCom, nBind, zCol, zType, zCollate
  178477. );
  178478. zWhere = sqlite3_mprintf(
  178479. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  178480. );
  178481. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  178482. zCom = ", ";
  178483. zAnd = " AND ";
  178484. nBind++;
  178485. }
  178486. rc2 = sqlite3_finalize(pXInfo);
  178487. if( rc==SQLITE_OK ) rc = rc2;
  178488. if( rc!=SQLITE_OK ){
  178489. sqlite3_free(zRet);
  178490. sqlite3_free(zImpCols);
  178491. sqlite3_free(zImpPK);
  178492. sqlite3_free(zWhere);
  178493. zRet = 0;
  178494. zImpCols = 0;
  178495. zImpPK = 0;
  178496. zWhere = 0;
  178497. p->rc = rc;
  178498. }
  178499. *pzImposterCols = zImpCols;
  178500. *pzImposterPk = zImpPK;
  178501. *pzWhere = zWhere;
  178502. *pnBind = nBind;
  178503. return zRet;
  178504. }
  178505. /*
  178506. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  178507. ** paramter is passed "old", return a string of the form:
  178508. **
  178509. ** "old.a, old.b, old.b"
  178510. **
  178511. ** With the column names escaped.
  178512. **
  178513. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  178514. ** the text ", old._rowid_" to the returned value.
  178515. */
  178516. static char *rbuObjIterGetOldlist(
  178517. sqlite3rbu *p,
  178518. RbuObjIter *pIter,
  178519. const char *zObj
  178520. ){
  178521. char *zList = 0;
  178522. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  178523. const char *zS = "";
  178524. int i;
  178525. for(i=0; i<pIter->nTblCol; i++){
  178526. if( pIter->abIndexed[i] ){
  178527. const char *zCol = pIter->azTblCol[i];
  178528. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  178529. }else{
  178530. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  178531. }
  178532. zS = ", ";
  178533. if( zList==0 ){
  178534. p->rc = SQLITE_NOMEM;
  178535. break;
  178536. }
  178537. }
  178538. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  178539. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  178540. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  178541. }
  178542. }
  178543. return zList;
  178544. }
  178545. /*
  178546. ** Return an expression that can be used in a WHERE clause to match the
  178547. ** primary key of the current table. For example, if the table is:
  178548. **
  178549. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  178550. **
  178551. ** Return the string:
  178552. **
  178553. ** "b = ?1 AND c = ?2"
  178554. */
  178555. static char *rbuObjIterGetWhere(
  178556. sqlite3rbu *p,
  178557. RbuObjIter *pIter
  178558. ){
  178559. char *zList = 0;
  178560. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  178561. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  178562. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  178563. const char *zSep = "";
  178564. int i;
  178565. for(i=0; i<pIter->nTblCol; i++){
  178566. if( pIter->abTblPk[i] ){
  178567. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  178568. zSep = " AND ";
  178569. }
  178570. }
  178571. zList = rbuMPrintf(p,
  178572. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  178573. );
  178574. }else{
  178575. const char *zSep = "";
  178576. int i;
  178577. for(i=0; i<pIter->nTblCol; i++){
  178578. if( pIter->abTblPk[i] ){
  178579. const char *zCol = pIter->azTblCol[i];
  178580. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  178581. zSep = " AND ";
  178582. }
  178583. }
  178584. }
  178585. return zList;
  178586. }
  178587. /*
  178588. ** The SELECT statement iterating through the keys for the current object
  178589. ** (p->objiter.pSelect) currently points to a valid row. However, there
  178590. ** is something wrong with the rbu_control value in the rbu_control value
  178591. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  178592. ** of the RBU handle to something reflecting this.
  178593. */
  178594. static void rbuBadControlError(sqlite3rbu *p){
  178595. p->rc = SQLITE_ERROR;
  178596. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  178597. }
  178598. /*
  178599. ** Return a nul-terminated string containing the comma separated list of
  178600. ** assignments that should be included following the "SET" keyword of
  178601. ** an UPDATE statement used to update the table object that the iterator
  178602. ** passed as the second argument currently points to if the rbu_control
  178603. ** column of the data_xxx table entry is set to zMask.
  178604. **
  178605. ** The memory for the returned string is obtained from sqlite3_malloc().
  178606. ** It is the responsibility of the caller to eventually free it using
  178607. ** sqlite3_free().
  178608. **
  178609. ** If an OOM error is encountered when allocating space for the new
  178610. ** string, an error code is left in the rbu handle passed as the first
  178611. ** argument and NULL is returned. Or, if an error has already occurred
  178612. ** when this function is called, NULL is returned immediately, without
  178613. ** attempting the allocation or modifying the stored error code.
  178614. */
  178615. static char *rbuObjIterGetSetlist(
  178616. sqlite3rbu *p,
  178617. RbuObjIter *pIter,
  178618. const char *zMask
  178619. ){
  178620. char *zList = 0;
  178621. if( p->rc==SQLITE_OK ){
  178622. int i;
  178623. if( (int)strlen(zMask)!=pIter->nTblCol ){
  178624. rbuBadControlError(p);
  178625. }else{
  178626. const char *zSep = "";
  178627. for(i=0; i<pIter->nTblCol; i++){
  178628. char c = zMask[pIter->aiSrcOrder[i]];
  178629. if( c=='x' ){
  178630. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  178631. zList, zSep, pIter->azTblCol[i], i+1
  178632. );
  178633. zSep = ", ";
  178634. }
  178635. else if( c=='d' ){
  178636. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  178637. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  178638. );
  178639. zSep = ", ";
  178640. }
  178641. else if( c=='f' ){
  178642. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  178643. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  178644. );
  178645. zSep = ", ";
  178646. }
  178647. }
  178648. }
  178649. }
  178650. return zList;
  178651. }
  178652. /*
  178653. ** Return a nul-terminated string consisting of nByte comma separated
  178654. ** "?" expressions. For example, if nByte is 3, return a pointer to
  178655. ** a buffer containing the string "?,?,?".
  178656. **
  178657. ** The memory for the returned string is obtained from sqlite3_malloc().
  178658. ** It is the responsibility of the caller to eventually free it using
  178659. ** sqlite3_free().
  178660. **
  178661. ** If an OOM error is encountered when allocating space for the new
  178662. ** string, an error code is left in the rbu handle passed as the first
  178663. ** argument and NULL is returned. Or, if an error has already occurred
  178664. ** when this function is called, NULL is returned immediately, without
  178665. ** attempting the allocation or modifying the stored error code.
  178666. */
  178667. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  178668. char *zRet = 0;
  178669. sqlite3_int64 nByte = 2*(sqlite3_int64)nBind + 1;
  178670. zRet = (char*)rbuMalloc(p, nByte);
  178671. if( zRet ){
  178672. int i;
  178673. for(i=0; i<nBind; i++){
  178674. zRet[i*2] = '?';
  178675. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  178676. }
  178677. }
  178678. return zRet;
  178679. }
  178680. /*
  178681. ** The iterator currently points to a table (not index) of type
  178682. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  178683. ** declaration for the corresponding imposter table. For example,
  178684. ** if the iterator points to a table created as:
  178685. **
  178686. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  178687. **
  178688. ** this function returns:
  178689. **
  178690. ** PRIMARY KEY("b", "a" DESC)
  178691. */
  178692. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  178693. char *z = 0;
  178694. assert( pIter->zIdx==0 );
  178695. if( p->rc==SQLITE_OK ){
  178696. const char *zSep = "PRIMARY KEY(";
  178697. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  178698. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  178699. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  178700. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  178701. );
  178702. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  178703. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  178704. if( zOrig && strcmp(zOrig, "pk")==0 ){
  178705. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  178706. if( zIdx ){
  178707. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  178708. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  178709. );
  178710. }
  178711. break;
  178712. }
  178713. }
  178714. rbuFinalize(p, pXList);
  178715. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  178716. if( sqlite3_column_int(pXInfo, 5) ){
  178717. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  178718. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  178719. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  178720. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  178721. zSep = ", ";
  178722. }
  178723. }
  178724. z = rbuMPrintf(p, "%z)", z);
  178725. rbuFinalize(p, pXInfo);
  178726. }
  178727. return z;
  178728. }
  178729. /*
  178730. ** This function creates the second imposter table used when writing to
  178731. ** a table b-tree where the table has an external primary key. If the
  178732. ** iterator passed as the second argument does not currently point to
  178733. ** a table (not index) with an external primary key, this function is a
  178734. ** no-op.
  178735. **
  178736. ** Assuming the iterator does point to a table with an external PK, this
  178737. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  178738. ** used to access that PK index. For example, if the target table is
  178739. ** declared as follows:
  178740. **
  178741. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  178742. **
  178743. ** then the imposter table schema is:
  178744. **
  178745. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  178746. **
  178747. */
  178748. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  178749. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  178750. int tnum = pIter->iPkTnum; /* Root page of PK index */
  178751. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  178752. const char *zIdx = 0; /* Name of PK index */
  178753. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  178754. const char *zComma = "";
  178755. char *zCols = 0; /* Used to build up list of table cols */
  178756. char *zPk = 0; /* Used to build up table PK declaration */
  178757. /* Figure out the name of the primary key index for the current table.
  178758. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  178759. ** zIdx to point to a nul-terminated string containing this name. */
  178760. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  178761. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  178762. );
  178763. if( p->rc==SQLITE_OK ){
  178764. sqlite3_bind_int(pQuery, 1, tnum);
  178765. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  178766. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  178767. }
  178768. }
  178769. if( zIdx ){
  178770. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  178771. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  178772. );
  178773. }
  178774. rbuFinalize(p, pQuery);
  178775. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  178776. int bKey = sqlite3_column_int(pXInfo, 5);
  178777. if( bKey ){
  178778. int iCid = sqlite3_column_int(pXInfo, 1);
  178779. int bDesc = sqlite3_column_int(pXInfo, 3);
  178780. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  178781. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma,
  178782. iCid, pIter->azTblType[iCid], zCollate
  178783. );
  178784. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  178785. zComma = ", ";
  178786. }
  178787. }
  178788. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  178789. rbuFinalize(p, pXInfo);
  178790. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  178791. rbuMPrintfExec(p, p->dbMain,
  178792. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  178793. zCols, zPk
  178794. );
  178795. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  178796. }
  178797. }
  178798. /*
  178799. ** If an error has already occurred when this function is called, it
  178800. ** immediately returns zero (without doing any work). Or, if an error
  178801. ** occurs during the execution of this function, it sets the error code
  178802. ** in the sqlite3rbu object indicated by the first argument and returns
  178803. ** zero.
  178804. **
  178805. ** The iterator passed as the second argument is guaranteed to point to
  178806. ** a table (not an index) when this function is called. This function
  178807. ** attempts to create any imposter table required to write to the main
  178808. ** table b-tree of the table before returning. Non-zero is returned if
  178809. ** an imposter table are created, or zero otherwise.
  178810. **
  178811. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  178812. ** virtual tables are written to directly. The imposter table has the
  178813. ** same schema as the actual target table (less any UNIQUE constraints).
  178814. ** More precisely, the "same schema" means the same columns, types,
  178815. ** collation sequences. For tables that do not have an external PRIMARY
  178816. ** KEY, it also means the same PRIMARY KEY declaration.
  178817. */
  178818. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  178819. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  178820. int tnum = pIter->iTnum;
  178821. const char *zComma = "";
  178822. char *zSql = 0;
  178823. int iCol;
  178824. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  178825. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  178826. const char *zPk = "";
  178827. const char *zCol = pIter->azTblCol[iCol];
  178828. const char *zColl = 0;
  178829. p->rc = sqlite3_table_column_metadata(
  178830. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  178831. );
  178832. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  178833. /* If the target table column is an "INTEGER PRIMARY KEY", add
  178834. ** "PRIMARY KEY" to the imposter table column declaration. */
  178835. zPk = "PRIMARY KEY ";
  178836. }
  178837. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
  178838. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  178839. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  178840. );
  178841. zComma = ", ";
  178842. }
  178843. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  178844. char *zPk = rbuWithoutRowidPK(p, pIter);
  178845. if( zPk ){
  178846. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  178847. }
  178848. }
  178849. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  178850. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  178851. pIter->zTbl, zSql,
  178852. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  178853. );
  178854. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  178855. }
  178856. }
  178857. /*
  178858. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  178859. ** Specifically a statement of the form:
  178860. **
  178861. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  178862. **
  178863. ** The number of bound variables is equal to the number of columns in
  178864. ** the target table, plus one (for the rbu_control column), plus one more
  178865. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  178866. ** virtual table.
  178867. */
  178868. static void rbuObjIterPrepareTmpInsert(
  178869. sqlite3rbu *p,
  178870. RbuObjIter *pIter,
  178871. const char *zCollist,
  178872. const char *zRbuRowid
  178873. ){
  178874. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  178875. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  178876. if( zBind ){
  178877. assert( pIter->pTmpInsert==0 );
  178878. p->rc = prepareFreeAndCollectError(
  178879. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  178880. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  178881. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  178882. ));
  178883. }
  178884. }
  178885. static void rbuTmpInsertFunc(
  178886. sqlite3_context *pCtx,
  178887. int nVal,
  178888. sqlite3_value **apVal
  178889. ){
  178890. sqlite3rbu *p = sqlite3_user_data(pCtx);
  178891. int rc = SQLITE_OK;
  178892. int i;
  178893. assert( sqlite3_value_int(apVal[0])!=0
  178894. || p->objiter.eType==RBU_PK_EXTERNAL
  178895. || p->objiter.eType==RBU_PK_NONE
  178896. );
  178897. if( sqlite3_value_int(apVal[0])!=0 ){
  178898. p->nPhaseOneStep += p->objiter.nIndex;
  178899. }
  178900. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  178901. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  178902. }
  178903. if( rc==SQLITE_OK ){
  178904. sqlite3_step(p->objiter.pTmpInsert);
  178905. rc = sqlite3_reset(p->objiter.pTmpInsert);
  178906. }
  178907. if( rc!=SQLITE_OK ){
  178908. sqlite3_result_error_code(pCtx, rc);
  178909. }
  178910. }
  178911. static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){
  178912. sqlite3_stmt *pStmt = 0;
  178913. int rc = p->rc;
  178914. char *zRet = 0;
  178915. if( rc==SQLITE_OK ){
  178916. rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  178917. "SELECT trim(sql) FROM sqlite_master WHERE type='index' AND name=?"
  178918. );
  178919. }
  178920. if( rc==SQLITE_OK ){
  178921. int rc2;
  178922. rc = sqlite3_bind_text(pStmt, 1, pIter->zIdx, -1, SQLITE_STATIC);
  178923. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  178924. const char *zSql = (const char*)sqlite3_column_text(pStmt, 0);
  178925. if( zSql ){
  178926. int nParen = 0; /* Number of open parenthesis */
  178927. int i;
  178928. for(i=0; zSql[i]; i++){
  178929. char c = zSql[i];
  178930. if( c=='(' ){
  178931. nParen++;
  178932. }
  178933. else if( c==')' ){
  178934. nParen--;
  178935. if( nParen==0 ){
  178936. i++;
  178937. break;
  178938. }
  178939. }else if( c=='"' || c=='\'' || c=='`' ){
  178940. for(i++; 1; i++){
  178941. if( zSql[i]==c ){
  178942. if( zSql[i+1]!=c ) break;
  178943. i++;
  178944. }
  178945. }
  178946. }else if( c=='[' ){
  178947. for(i++; 1; i++){
  178948. if( zSql[i]==']' ) break;
  178949. }
  178950. }
  178951. }
  178952. if( zSql[i] ){
  178953. zRet = rbuStrndup(&zSql[i], &rc);
  178954. }
  178955. }
  178956. }
  178957. rc2 = sqlite3_finalize(pStmt);
  178958. if( rc==SQLITE_OK ) rc = rc2;
  178959. }
  178960. p->rc = rc;
  178961. return zRet;
  178962. }
  178963. /*
  178964. ** Ensure that the SQLite statement handles required to update the
  178965. ** target database object currently indicated by the iterator passed
  178966. ** as the second argument are available.
  178967. */
  178968. static int rbuObjIterPrepareAll(
  178969. sqlite3rbu *p,
  178970. RbuObjIter *pIter,
  178971. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  178972. ){
  178973. assert( pIter->bCleanup==0 );
  178974. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  178975. const int tnum = pIter->iTnum;
  178976. char *zCollist = 0; /* List of indexed columns */
  178977. char **pz = &p->zErrmsg;
  178978. const char *zIdx = pIter->zIdx;
  178979. char *zLimit = 0;
  178980. if( nOffset ){
  178981. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  178982. if( !zLimit ) p->rc = SQLITE_NOMEM;
  178983. }
  178984. if( zIdx ){
  178985. const char *zTbl = pIter->zTbl;
  178986. char *zImposterCols = 0; /* Columns for imposter table */
  178987. char *zImposterPK = 0; /* Primary key declaration for imposter */
  178988. char *zWhere = 0; /* WHERE clause on PK columns */
  178989. char *zBind = 0;
  178990. char *zPart = 0;
  178991. int nBind = 0;
  178992. assert( pIter->eType!=RBU_PK_VTAB );
  178993. zCollist = rbuObjIterGetIndexCols(
  178994. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  178995. );
  178996. zBind = rbuObjIterGetBindlist(p, nBind);
  178997. zPart = rbuObjIterGetIndexWhere(p, pIter);
  178998. /* Create the imposter table used to write to this index. */
  178999. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  179000. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  179001. rbuMPrintfExec(p, p->dbMain,
  179002. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  179003. zTbl, zImposterCols, zImposterPK
  179004. );
  179005. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  179006. /* Create the statement to insert index entries */
  179007. pIter->nCol = nBind;
  179008. if( p->rc==SQLITE_OK ){
  179009. p->rc = prepareFreeAndCollectError(
  179010. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  179011. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  179012. );
  179013. }
  179014. /* And to delete index entries */
  179015. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  179016. p->rc = prepareFreeAndCollectError(
  179017. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  179018. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  179019. );
  179020. }
  179021. /* Create the SELECT statement to read keys in sorted order */
  179022. if( p->rc==SQLITE_OK ){
  179023. char *zSql;
  179024. if( rbuIsVacuum(p) ){
  179025. zSql = sqlite3_mprintf(
  179026. "SELECT %s, 0 AS rbu_control FROM '%q' %s ORDER BY %s%s",
  179027. zCollist,
  179028. pIter->zDataTbl,
  179029. zPart, zCollist, zLimit
  179030. );
  179031. }else
  179032. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  179033. zSql = sqlite3_mprintf(
  179034. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s",
  179035. zCollist, p->zStateDb, pIter->zDataTbl,
  179036. zPart, zCollist, zLimit
  179037. );
  179038. }else{
  179039. zSql = sqlite3_mprintf(
  179040. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s "
  179041. "UNION ALL "
  179042. "SELECT %s, rbu_control FROM '%q' "
  179043. "%s %s typeof(rbu_control)='integer' AND rbu_control!=1 "
  179044. "ORDER BY %s%s",
  179045. zCollist, p->zStateDb, pIter->zDataTbl, zPart,
  179046. zCollist, pIter->zDataTbl,
  179047. zPart,
  179048. (zPart ? "AND" : "WHERE"),
  179049. zCollist, zLimit
  179050. );
  179051. }
  179052. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
  179053. }
  179054. sqlite3_free(zImposterCols);
  179055. sqlite3_free(zImposterPK);
  179056. sqlite3_free(zWhere);
  179057. sqlite3_free(zBind);
  179058. sqlite3_free(zPart);
  179059. }else{
  179060. int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
  179061. ||(pIter->eType==RBU_PK_NONE)
  179062. ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
  179063. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  179064. const char *zWrite; /* Imposter table name */
  179065. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  179066. char *zWhere = rbuObjIterGetWhere(p, pIter);
  179067. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  179068. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  179069. zCollist = rbuObjIterGetCollist(p, pIter);
  179070. pIter->nCol = pIter->nTblCol;
  179071. /* Create the imposter table or tables (if required). */
  179072. rbuCreateImposterTable(p, pIter);
  179073. rbuCreateImposterTable2(p, pIter);
  179074. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  179075. /* Create the INSERT statement to write to the target PK b-tree */
  179076. if( p->rc==SQLITE_OK ){
  179077. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  179078. sqlite3_mprintf(
  179079. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  179080. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  179081. )
  179082. );
  179083. }
  179084. /* Create the DELETE statement to write to the target PK b-tree.
  179085. ** Because it only performs INSERT operations, this is not required for
  179086. ** an rbu vacuum handle. */
  179087. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  179088. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  179089. sqlite3_mprintf(
  179090. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  179091. )
  179092. );
  179093. }
  179094. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  179095. const char *zRbuRowid = "";
  179096. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  179097. zRbuRowid = ", rbu_rowid";
  179098. }
  179099. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  179100. rbuMPrintfExec(p, p->dbRbu,
  179101. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  179102. "SELECT *%s FROM '%q' WHERE 0;"
  179103. , p->zStateDb, pIter->zDataTbl
  179104. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  179105. , pIter->zDataTbl
  179106. );
  179107. rbuMPrintfExec(p, p->dbMain,
  179108. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  179109. "BEGIN "
  179110. " SELECT rbu_tmp_insert(3, %s);"
  179111. "END;"
  179112. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  179113. "BEGIN "
  179114. " SELECT rbu_tmp_insert(3, %s);"
  179115. "END;"
  179116. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  179117. "BEGIN "
  179118. " SELECT rbu_tmp_insert(4, %s);"
  179119. "END;",
  179120. zWrite, zTbl, zOldlist,
  179121. zWrite, zTbl, zOldlist,
  179122. zWrite, zTbl, zNewlist
  179123. );
  179124. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  179125. rbuMPrintfExec(p, p->dbMain,
  179126. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  179127. "BEGIN "
  179128. " SELECT rbu_tmp_insert(0, %s);"
  179129. "END;",
  179130. zWrite, zTbl, zNewlist
  179131. );
  179132. }
  179133. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  179134. }
  179135. /* Create the SELECT statement to read keys from data_xxx */
  179136. if( p->rc==SQLITE_OK ){
  179137. const char *zRbuRowid = "";
  179138. if( bRbuRowid ){
  179139. zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
  179140. }
  179141. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  179142. sqlite3_mprintf(
  179143. "SELECT %s,%s rbu_control%s FROM '%q'%s",
  179144. zCollist,
  179145. (rbuIsVacuum(p) ? "0 AS " : ""),
  179146. zRbuRowid,
  179147. pIter->zDataTbl, zLimit
  179148. )
  179149. );
  179150. }
  179151. sqlite3_free(zWhere);
  179152. sqlite3_free(zOldlist);
  179153. sqlite3_free(zNewlist);
  179154. sqlite3_free(zBindings);
  179155. }
  179156. sqlite3_free(zCollist);
  179157. sqlite3_free(zLimit);
  179158. }
  179159. return p->rc;
  179160. }
  179161. /*
  179162. ** Set output variable *ppStmt to point to an UPDATE statement that may
  179163. ** be used to update the imposter table for the main table b-tree of the
  179164. ** table object that pIter currently points to, assuming that the
  179165. ** rbu_control column of the data_xyz table contains zMask.
  179166. **
  179167. ** If the zMask string does not specify any columns to update, then this
  179168. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  179169. */
  179170. static int rbuGetUpdateStmt(
  179171. sqlite3rbu *p, /* RBU handle */
  179172. RbuObjIter *pIter, /* Object iterator */
  179173. const char *zMask, /* rbu_control value ('x.x.') */
  179174. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  179175. ){
  179176. RbuUpdateStmt **pp;
  179177. RbuUpdateStmt *pUp = 0;
  179178. int nUp = 0;
  179179. /* In case an error occurs */
  179180. *ppStmt = 0;
  179181. /* Search for an existing statement. If one is found, shift it to the front
  179182. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  179183. ** to the number of statements currently in the cache and pUp to the
  179184. ** last object in the list. */
  179185. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  179186. pUp = *pp;
  179187. if( strcmp(pUp->zMask, zMask)==0 ){
  179188. *pp = pUp->pNext;
  179189. pUp->pNext = pIter->pRbuUpdate;
  179190. pIter->pRbuUpdate = pUp;
  179191. *ppStmt = pUp->pUpdate;
  179192. return SQLITE_OK;
  179193. }
  179194. nUp++;
  179195. }
  179196. assert( pUp==0 || pUp->pNext==0 );
  179197. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  179198. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  179199. *pp = 0;
  179200. sqlite3_finalize(pUp->pUpdate);
  179201. pUp->pUpdate = 0;
  179202. }else{
  179203. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  179204. }
  179205. if( pUp ){
  179206. char *zWhere = rbuObjIterGetWhere(p, pIter);
  179207. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  179208. char *zUpdate = 0;
  179209. pUp->zMask = (char*)&pUp[1];
  179210. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  179211. pUp->pNext = pIter->pRbuUpdate;
  179212. pIter->pRbuUpdate = pUp;
  179213. if( zSet ){
  179214. const char *zPrefix = "";
  179215. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  179216. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  179217. zPrefix, pIter->zTbl, zSet, zWhere
  179218. );
  179219. p->rc = prepareFreeAndCollectError(
  179220. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  179221. );
  179222. *ppStmt = pUp->pUpdate;
  179223. }
  179224. sqlite3_free(zWhere);
  179225. sqlite3_free(zSet);
  179226. }
  179227. return p->rc;
  179228. }
  179229. static sqlite3 *rbuOpenDbhandle(
  179230. sqlite3rbu *p,
  179231. const char *zName,
  179232. int bUseVfs
  179233. ){
  179234. sqlite3 *db = 0;
  179235. if( p->rc==SQLITE_OK ){
  179236. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  179237. p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
  179238. if( p->rc ){
  179239. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  179240. sqlite3_close(db);
  179241. db = 0;
  179242. }
  179243. }
  179244. return db;
  179245. }
  179246. /*
  179247. ** Free an RbuState object allocated by rbuLoadState().
  179248. */
  179249. static void rbuFreeState(RbuState *p){
  179250. if( p ){
  179251. sqlite3_free(p->zTbl);
  179252. sqlite3_free(p->zDataTbl);
  179253. sqlite3_free(p->zIdx);
  179254. sqlite3_free(p);
  179255. }
  179256. }
  179257. /*
  179258. ** Allocate an RbuState object and load the contents of the rbu_state
  179259. ** table into it. Return a pointer to the new object. It is the
  179260. ** responsibility of the caller to eventually free the object using
  179261. ** sqlite3_free().
  179262. **
  179263. ** If an error occurs, leave an error code and message in the rbu handle
  179264. ** and return NULL.
  179265. */
  179266. static RbuState *rbuLoadState(sqlite3rbu *p){
  179267. RbuState *pRet = 0;
  179268. sqlite3_stmt *pStmt = 0;
  179269. int rc;
  179270. int rc2;
  179271. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  179272. if( pRet==0 ) return 0;
  179273. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  179274. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  179275. );
  179276. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  179277. switch( sqlite3_column_int(pStmt, 0) ){
  179278. case RBU_STATE_STAGE:
  179279. pRet->eStage = sqlite3_column_int(pStmt, 1);
  179280. if( pRet->eStage!=RBU_STAGE_OAL
  179281. && pRet->eStage!=RBU_STAGE_MOVE
  179282. && pRet->eStage!=RBU_STAGE_CKPT
  179283. ){
  179284. p->rc = SQLITE_CORRUPT;
  179285. }
  179286. break;
  179287. case RBU_STATE_TBL:
  179288. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  179289. break;
  179290. case RBU_STATE_IDX:
  179291. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  179292. break;
  179293. case RBU_STATE_ROW:
  179294. pRet->nRow = sqlite3_column_int(pStmt, 1);
  179295. break;
  179296. case RBU_STATE_PROGRESS:
  179297. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  179298. break;
  179299. case RBU_STATE_CKPT:
  179300. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  179301. break;
  179302. case RBU_STATE_COOKIE:
  179303. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  179304. break;
  179305. case RBU_STATE_OALSZ:
  179306. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  179307. break;
  179308. case RBU_STATE_PHASEONESTEP:
  179309. pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
  179310. break;
  179311. case RBU_STATE_DATATBL:
  179312. pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  179313. break;
  179314. default:
  179315. rc = SQLITE_CORRUPT;
  179316. break;
  179317. }
  179318. }
  179319. rc2 = sqlite3_finalize(pStmt);
  179320. if( rc==SQLITE_OK ) rc = rc2;
  179321. p->rc = rc;
  179322. return pRet;
  179323. }
  179324. /*
  179325. ** Open the database handle and attach the RBU database as "rbu". If an
  179326. ** error occurs, leave an error code and message in the RBU handle.
  179327. */
  179328. static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
  179329. assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
  179330. assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
  179331. /* Open the RBU database */
  179332. p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
  179333. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  179334. sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  179335. if( p->zState==0 ){
  179336. const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
  179337. p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
  179338. }
  179339. }
  179340. /* If using separate RBU and state databases, attach the state database to
  179341. ** the RBU db handle now. */
  179342. if( p->zState ){
  179343. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  179344. memcpy(p->zStateDb, "stat", 4);
  179345. }else{
  179346. memcpy(p->zStateDb, "main", 4);
  179347. }
  179348. #if 0
  179349. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  179350. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
  179351. }
  179352. #endif
  179353. /* If it has not already been created, create the rbu_state table */
  179354. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  179355. #if 0
  179356. if( rbuIsVacuum(p) ){
  179357. if( p->rc==SQLITE_OK ){
  179358. int rc2;
  179359. int bOk = 0;
  179360. sqlite3_stmt *pCnt = 0;
  179361. p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
  179362. "SELECT count(*) FROM stat.sqlite_master"
  179363. );
  179364. if( p->rc==SQLITE_OK
  179365. && sqlite3_step(pCnt)==SQLITE_ROW
  179366. && 1==sqlite3_column_int(pCnt, 0)
  179367. ){
  179368. bOk = 1;
  179369. }
  179370. rc2 = sqlite3_finalize(pCnt);
  179371. if( p->rc==SQLITE_OK ) p->rc = rc2;
  179372. if( p->rc==SQLITE_OK && bOk==0 ){
  179373. p->rc = SQLITE_ERROR;
  179374. p->zErrmsg = sqlite3_mprintf("invalid state database");
  179375. }
  179376. if( p->rc==SQLITE_OK ){
  179377. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  179378. }
  179379. }
  179380. }
  179381. #endif
  179382. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  179383. int bOpen = 0;
  179384. int rc;
  179385. p->nRbu = 0;
  179386. p->pRbuFd = 0;
  179387. rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  179388. if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
  179389. if( p->eStage>=RBU_STAGE_MOVE ){
  179390. bOpen = 1;
  179391. }else{
  179392. RbuState *pState = rbuLoadState(p);
  179393. if( pState ){
  179394. bOpen = (pState->eStage>=RBU_STAGE_MOVE);
  179395. rbuFreeState(pState);
  179396. }
  179397. }
  179398. if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
  179399. }
  179400. p->eStage = 0;
  179401. if( p->rc==SQLITE_OK && p->dbMain==0 ){
  179402. if( !rbuIsVacuum(p) ){
  179403. p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
  179404. }else if( p->pRbuFd->pWalFd ){
  179405. if( pbRetry ){
  179406. p->pRbuFd->bNolock = 0;
  179407. sqlite3_close(p->dbRbu);
  179408. sqlite3_close(p->dbMain);
  179409. p->dbMain = 0;
  179410. p->dbRbu = 0;
  179411. *pbRetry = 1;
  179412. return;
  179413. }
  179414. p->rc = SQLITE_ERROR;
  179415. p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
  179416. }else{
  179417. char *zTarget;
  179418. char *zExtra = 0;
  179419. if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
  179420. zExtra = &p->zRbu[5];
  179421. while( *zExtra ){
  179422. if( *zExtra++=='?' ) break;
  179423. }
  179424. if( *zExtra=='\0' ) zExtra = 0;
  179425. }
  179426. zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s",
  179427. sqlite3_db_filename(p->dbRbu, "main"),
  179428. (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
  179429. );
  179430. if( zTarget==0 ){
  179431. p->rc = SQLITE_NOMEM;
  179432. return;
  179433. }
  179434. p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
  179435. sqlite3_free(zTarget);
  179436. }
  179437. }
  179438. if( p->rc==SQLITE_OK ){
  179439. p->rc = sqlite3_create_function(p->dbMain,
  179440. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  179441. );
  179442. }
  179443. if( p->rc==SQLITE_OK ){
  179444. p->rc = sqlite3_create_function(p->dbMain,
  179445. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  179446. );
  179447. }
  179448. if( p->rc==SQLITE_OK ){
  179449. p->rc = sqlite3_create_function(p->dbRbu,
  179450. "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  179451. );
  179452. }
  179453. if( p->rc==SQLITE_OK ){
  179454. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  179455. }
  179456. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  179457. /* Mark the database file just opened as an RBU target database. If
  179458. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  179459. ** This is an error. */
  179460. if( p->rc==SQLITE_OK ){
  179461. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  179462. }
  179463. if( p->rc==SQLITE_NOTFOUND ){
  179464. p->rc = SQLITE_ERROR;
  179465. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  179466. }
  179467. }
  179468. /*
  179469. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  179470. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  179471. **
  179472. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  179473. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  179474. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  179475. ** three characters, then shorten the suffix on z[] to be the last three
  179476. ** characters of the original suffix.
  179477. **
  179478. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  179479. ** do the suffix shortening regardless of URI parameter.
  179480. **
  179481. ** Examples:
  179482. **
  179483. ** test.db-journal => test.nal
  179484. ** test.db-wal => test.wal
  179485. ** test.db-shm => test.shm
  179486. ** test.db-mj7f3319fa => test.9fa
  179487. */
  179488. static void rbuFileSuffix3(const char *zBase, char *z){
  179489. #ifdef SQLITE_ENABLE_8_3_NAMES
  179490. #if SQLITE_ENABLE_8_3_NAMES<2
  179491. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  179492. #endif
  179493. {
  179494. int i, sz;
  179495. sz = (int)strlen(z)&0xffffff;
  179496. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  179497. if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
  179498. }
  179499. #endif
  179500. }
  179501. /*
  179502. ** Return the current wal-index header checksum for the target database
  179503. ** as a 64-bit integer.
  179504. **
  179505. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  179506. ** blob starting at byte offset 40.
  179507. */
  179508. static i64 rbuShmChecksum(sqlite3rbu *p){
  179509. i64 iRet = 0;
  179510. if( p->rc==SQLITE_OK ){
  179511. sqlite3_file *pDb = p->pTargetFd->pReal;
  179512. u32 volatile *ptr;
  179513. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  179514. if( p->rc==SQLITE_OK ){
  179515. iRet = ((i64)ptr[10] << 32) + ptr[11];
  179516. }
  179517. }
  179518. return iRet;
  179519. }
  179520. /*
  179521. ** This function is called as part of initializing or reinitializing an
  179522. ** incremental checkpoint.
  179523. **
  179524. ** It populates the sqlite3rbu.aFrame[] array with the set of
  179525. ** (wal frame -> db page) copy operations required to checkpoint the
  179526. ** current wal file, and obtains the set of shm locks required to safely
  179527. ** perform the copy operations directly on the file-system.
  179528. **
  179529. ** If argument pState is not NULL, then the incremental checkpoint is
  179530. ** being resumed. In this case, if the checksum of the wal-index-header
  179531. ** following recovery is not the same as the checksum saved in the RbuState
  179532. ** object, then the rbu handle is set to DONE state. This occurs if some
  179533. ** other client appends a transaction to the wal file in the middle of
  179534. ** an incremental checkpoint.
  179535. */
  179536. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  179537. /* If pState is NULL, then the wal file may not have been opened and
  179538. ** recovered. Running a read-statement here to ensure that doing so
  179539. ** does not interfere with the "capture" process below. */
  179540. if( pState==0 ){
  179541. p->eStage = 0;
  179542. if( p->rc==SQLITE_OK ){
  179543. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  179544. }
  179545. }
  179546. /* Assuming no error has occurred, run a "restart" checkpoint with the
  179547. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  179548. ** special behaviour in the rbu VFS:
  179549. **
  179550. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  179551. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  179552. ** proceed with running a passive checkpoint instead of failing).
  179553. **
  179554. ** * Attempts to read from the *-wal file or write to the database file
  179555. ** do not perform any IO. Instead, the frame/page combinations that
  179556. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  179557. ** array.
  179558. **
  179559. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  179560. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  179561. ** no-ops. These locks will not be released until the connection
  179562. ** is closed.
  179563. **
  179564. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  179565. ** error.
  179566. **
  179567. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  179568. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  179569. ** array populated with a set of (frame -> page) mappings. Because the
  179570. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  179571. ** data from the wal file into the database file according to the
  179572. ** contents of aFrame[].
  179573. */
  179574. if( p->rc==SQLITE_OK ){
  179575. int rc2;
  179576. p->eStage = RBU_STAGE_CAPTURE;
  179577. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  179578. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  179579. }
  179580. if( p->rc==SQLITE_OK && p->nFrame>0 ){
  179581. p->eStage = RBU_STAGE_CKPT;
  179582. p->nStep = (pState ? pState->nRow : 0);
  179583. p->aBuf = rbuMalloc(p, p->pgsz);
  179584. p->iWalCksum = rbuShmChecksum(p);
  179585. }
  179586. if( p->rc==SQLITE_OK ){
  179587. if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
  179588. p->rc = SQLITE_DONE;
  179589. p->eStage = RBU_STAGE_DONE;
  179590. }else{
  179591. int nSectorSize;
  179592. sqlite3_file *pDb = p->pTargetFd->pReal;
  179593. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  179594. assert( p->nPagePerSector==0 );
  179595. nSectorSize = pDb->pMethods->xSectorSize(pDb);
  179596. if( nSectorSize>p->pgsz ){
  179597. p->nPagePerSector = nSectorSize / p->pgsz;
  179598. }else{
  179599. p->nPagePerSector = 1;
  179600. }
  179601. /* Call xSync() on the wal file. This causes SQLite to sync the
  179602. ** directory in which the target database and the wal file reside, in
  179603. ** case it has not been synced since the rename() call in
  179604. ** rbuMoveOalFile(). */
  179605. p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
  179606. }
  179607. }
  179608. }
  179609. /*
  179610. ** Called when iAmt bytes are read from offset iOff of the wal file while
  179611. ** the rbu object is in capture mode. Record the frame number of the frame
  179612. ** being read in the aFrame[] array.
  179613. */
  179614. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  179615. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  179616. u32 iFrame;
  179617. if( pRbu->mLock!=mReq ){
  179618. pRbu->rc = SQLITE_BUSY;
  179619. return SQLITE_INTERNAL;
  179620. }
  179621. pRbu->pgsz = iAmt;
  179622. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  179623. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  179624. RbuFrame *aNew;
  179625. aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
  179626. if( aNew==0 ) return SQLITE_NOMEM;
  179627. pRbu->aFrame = aNew;
  179628. pRbu->nFrameAlloc = nNew;
  179629. }
  179630. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  179631. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  179632. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  179633. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  179634. pRbu->nFrame++;
  179635. return SQLITE_OK;
  179636. }
  179637. /*
  179638. ** Called when a page of data is written to offset iOff of the database
  179639. ** file while the rbu handle is in capture mode. Record the page number
  179640. ** of the page being written in the aFrame[] array.
  179641. */
  179642. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  179643. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  179644. return SQLITE_OK;
  179645. }
  179646. /*
  179647. ** This is called as part of an incremental checkpoint operation. Copy
  179648. ** a single frame of data from the wal file into the database file, as
  179649. ** indicated by the RbuFrame object.
  179650. */
  179651. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  179652. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  179653. sqlite3_file *pDb = p->pTargetFd->pReal;
  179654. i64 iOff;
  179655. assert( p->rc==SQLITE_OK );
  179656. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  179657. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  179658. if( p->rc ) return;
  179659. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  179660. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  179661. }
  179662. /*
  179663. ** Take an EXCLUSIVE lock on the database file.
  179664. */
  179665. static void rbuLockDatabase(sqlite3rbu *p){
  179666. sqlite3_file *pReal = p->pTargetFd->pReal;
  179667. assert( p->rc==SQLITE_OK );
  179668. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  179669. if( p->rc==SQLITE_OK ){
  179670. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  179671. }
  179672. }
  179673. #if defined(_WIN32_WCE)
  179674. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  179675. int nChar;
  179676. LPWSTR zWideFilename;
  179677. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  179678. if( nChar==0 ){
  179679. return 0;
  179680. }
  179681. zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
  179682. if( zWideFilename==0 ){
  179683. return 0;
  179684. }
  179685. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  179686. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  179687. nChar);
  179688. if( nChar==0 ){
  179689. sqlite3_free(zWideFilename);
  179690. zWideFilename = 0;
  179691. }
  179692. return zWideFilename;
  179693. }
  179694. #endif
  179695. /*
  179696. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  179697. ** on the database file. This proc moves the *-oal file to the *-wal path,
  179698. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  179699. ** If an error occurs, leave an error code and error message in the rbu
  179700. ** handle.
  179701. */
  179702. static void rbuMoveOalFile(sqlite3rbu *p){
  179703. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  179704. const char *zMove = zBase;
  179705. char *zOal;
  179706. char *zWal;
  179707. if( rbuIsVacuum(p) ){
  179708. zMove = sqlite3_db_filename(p->dbRbu, "main");
  179709. }
  179710. zOal = sqlite3_mprintf("%s-oal", zMove);
  179711. zWal = sqlite3_mprintf("%s-wal", zMove);
  179712. assert( p->eStage==RBU_STAGE_MOVE );
  179713. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  179714. if( zWal==0 || zOal==0 ){
  179715. p->rc = SQLITE_NOMEM;
  179716. }else{
  179717. /* Move the *-oal file to *-wal. At this point connection p->db is
  179718. ** holding a SHARED lock on the target database file (because it is
  179719. ** in WAL mode). So no other connection may be writing the db.
  179720. **
  179721. ** In order to ensure that there are no database readers, an EXCLUSIVE
  179722. ** lock is obtained here before the *-oal is moved to *-wal.
  179723. */
  179724. rbuLockDatabase(p);
  179725. if( p->rc==SQLITE_OK ){
  179726. rbuFileSuffix3(zBase, zWal);
  179727. rbuFileSuffix3(zBase, zOal);
  179728. /* Re-open the databases. */
  179729. rbuObjIterFinalize(&p->objiter);
  179730. sqlite3_close(p->dbRbu);
  179731. sqlite3_close(p->dbMain);
  179732. p->dbMain = 0;
  179733. p->dbRbu = 0;
  179734. #if defined(_WIN32_WCE)
  179735. {
  179736. LPWSTR zWideOal;
  179737. LPWSTR zWideWal;
  179738. zWideOal = rbuWinUtf8ToUnicode(zOal);
  179739. if( zWideOal ){
  179740. zWideWal = rbuWinUtf8ToUnicode(zWal);
  179741. if( zWideWal ){
  179742. if( MoveFileW(zWideOal, zWideWal) ){
  179743. p->rc = SQLITE_OK;
  179744. }else{
  179745. p->rc = SQLITE_IOERR;
  179746. }
  179747. sqlite3_free(zWideWal);
  179748. }else{
  179749. p->rc = SQLITE_IOERR_NOMEM;
  179750. }
  179751. sqlite3_free(zWideOal);
  179752. }else{
  179753. p->rc = SQLITE_IOERR_NOMEM;
  179754. }
  179755. }
  179756. #else
  179757. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  179758. #endif
  179759. if( p->rc==SQLITE_OK ){
  179760. rbuOpenDatabase(p, 0);
  179761. rbuSetupCheckpoint(p, 0);
  179762. }
  179763. }
  179764. }
  179765. sqlite3_free(zWal);
  179766. sqlite3_free(zOal);
  179767. }
  179768. /*
  179769. ** The SELECT statement iterating through the keys for the current object
  179770. ** (p->objiter.pSelect) currently points to a valid row. This function
  179771. ** determines the type of operation requested by this row and returns
  179772. ** one of the following values to indicate the result:
  179773. **
  179774. ** * RBU_INSERT
  179775. ** * RBU_DELETE
  179776. ** * RBU_IDX_DELETE
  179777. ** * RBU_UPDATE
  179778. **
  179779. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  179780. ** point to the text value indicating the columns to update.
  179781. **
  179782. ** If the rbu_control field contains an invalid value, an error code and
  179783. ** message are left in the RBU handle and zero returned.
  179784. */
  179785. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  179786. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  179787. int res = 0; /* Return value */
  179788. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  179789. case SQLITE_INTEGER: {
  179790. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  179791. switch( iVal ){
  179792. case 0: res = RBU_INSERT; break;
  179793. case 1: res = RBU_DELETE; break;
  179794. case 2: res = RBU_REPLACE; break;
  179795. case 3: res = RBU_IDX_DELETE; break;
  179796. case 4: res = RBU_IDX_INSERT; break;
  179797. }
  179798. break;
  179799. }
  179800. case SQLITE_TEXT: {
  179801. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  179802. if( z==0 ){
  179803. p->rc = SQLITE_NOMEM;
  179804. }else{
  179805. *pzMask = (const char*)z;
  179806. }
  179807. res = RBU_UPDATE;
  179808. break;
  179809. }
  179810. default:
  179811. break;
  179812. }
  179813. if( res==0 ){
  179814. rbuBadControlError(p);
  179815. }
  179816. return res;
  179817. }
  179818. #ifdef SQLITE_DEBUG
  179819. /*
  179820. ** Assert that column iCol of statement pStmt is named zName.
  179821. */
  179822. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  179823. const char *zCol = sqlite3_column_name(pStmt, iCol);
  179824. assert( 0==sqlite3_stricmp(zName, zCol) );
  179825. }
  179826. #else
  179827. # define assertColumnName(x,y,z)
  179828. #endif
  179829. /*
  179830. ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
  179831. ** RBU_IDX_DELETE. This function performs the work of a single
  179832. ** sqlite3rbu_step() call for the type of operation specified by eType.
  179833. */
  179834. static void rbuStepOneOp(sqlite3rbu *p, int eType){
  179835. RbuObjIter *pIter = &p->objiter;
  179836. sqlite3_value *pVal;
  179837. sqlite3_stmt *pWriter;
  179838. int i;
  179839. assert( p->rc==SQLITE_OK );
  179840. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  179841. assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
  179842. || eType==RBU_INSERT || eType==RBU_IDX_INSERT
  179843. );
  179844. /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
  179845. ** statement below does actually delete a row, nPhaseOneStep will be
  179846. ** incremented by the same amount when SQL function rbu_tmp_insert()
  179847. ** is invoked by the trigger. */
  179848. if( eType==RBU_DELETE ){
  179849. p->nPhaseOneStep -= p->objiter.nIndex;
  179850. }
  179851. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  179852. pWriter = pIter->pDelete;
  179853. }else{
  179854. pWriter = pIter->pInsert;
  179855. }
  179856. for(i=0; i<pIter->nCol; i++){
  179857. /* If this is an INSERT into a table b-tree and the table has an
  179858. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  179859. ** to write a NULL into the IPK column. That is not permitted. */
  179860. if( eType==RBU_INSERT
  179861. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  179862. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  179863. ){
  179864. p->rc = SQLITE_MISMATCH;
  179865. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  179866. return;
  179867. }
  179868. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  179869. continue;
  179870. }
  179871. pVal = sqlite3_column_value(pIter->pSelect, i);
  179872. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  179873. if( p->rc ) return;
  179874. }
  179875. if( pIter->zIdx==0 ){
  179876. if( pIter->eType==RBU_PK_VTAB
  179877. || pIter->eType==RBU_PK_NONE
  179878. || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
  179879. ){
  179880. /* For a virtual table, or a table with no primary key, the
  179881. ** SELECT statement is:
  179882. **
  179883. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  179884. **
  179885. ** Hence column_value(pIter->nCol+1).
  179886. */
  179887. assertColumnName(pIter->pSelect, pIter->nCol+1,
  179888. rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
  179889. );
  179890. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  179891. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  179892. }
  179893. }
  179894. if( p->rc==SQLITE_OK ){
  179895. sqlite3_step(pWriter);
  179896. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  179897. }
  179898. }
  179899. /*
  179900. ** This function does the work for an sqlite3rbu_step() call.
  179901. **
  179902. ** The object-iterator (p->objiter) currently points to a valid object,
  179903. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  179904. ** input row. Perform whatever processing is required and return.
  179905. **
  179906. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  179907. ** and message is left in the RBU handle and a copy of the error code
  179908. ** returned.
  179909. */
  179910. static int rbuStep(sqlite3rbu *p){
  179911. RbuObjIter *pIter = &p->objiter;
  179912. const char *zMask = 0;
  179913. int eType = rbuStepType(p, &zMask);
  179914. if( eType ){
  179915. assert( eType==RBU_INSERT || eType==RBU_DELETE
  179916. || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
  179917. || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
  179918. );
  179919. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  179920. if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
  179921. rbuBadControlError(p);
  179922. }
  179923. else if( eType==RBU_REPLACE ){
  179924. if( pIter->zIdx==0 ){
  179925. p->nPhaseOneStep += p->objiter.nIndex;
  179926. rbuStepOneOp(p, RBU_DELETE);
  179927. }
  179928. if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
  179929. }
  179930. else if( eType!=RBU_UPDATE ){
  179931. rbuStepOneOp(p, eType);
  179932. }
  179933. else{
  179934. sqlite3_value *pVal;
  179935. sqlite3_stmt *pUpdate = 0;
  179936. assert( eType==RBU_UPDATE );
  179937. p->nPhaseOneStep -= p->objiter.nIndex;
  179938. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  179939. if( pUpdate ){
  179940. int i;
  179941. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  179942. char c = zMask[pIter->aiSrcOrder[i]];
  179943. pVal = sqlite3_column_value(pIter->pSelect, i);
  179944. if( pIter->abTblPk[i] || c!='.' ){
  179945. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  179946. }
  179947. }
  179948. if( p->rc==SQLITE_OK
  179949. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  179950. ){
  179951. /* Bind the rbu_rowid value to column _rowid_ */
  179952. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  179953. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  179954. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  179955. }
  179956. if( p->rc==SQLITE_OK ){
  179957. sqlite3_step(pUpdate);
  179958. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  179959. }
  179960. }
  179961. }
  179962. }
  179963. return p->rc;
  179964. }
  179965. /*
  179966. ** Increment the schema cookie of the main database opened by p->dbMain.
  179967. **
  179968. ** Or, if this is an RBU vacuum, set the schema cookie of the main db
  179969. ** opened by p->dbMain to one more than the schema cookie of the main
  179970. ** db opened by p->dbRbu.
  179971. */
  179972. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  179973. if( p->rc==SQLITE_OK ){
  179974. sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  179975. int iCookie = 1000000;
  179976. sqlite3_stmt *pStmt;
  179977. p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
  179978. "PRAGMA schema_version"
  179979. );
  179980. if( p->rc==SQLITE_OK ){
  179981. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  179982. ** is already a transaction open, so the prepared statement cannot
  179983. ** throw an SQLITE_SCHEMA exception. The only database page the
  179984. ** statement reads is page 1, which is guaranteed to be in the cache.
  179985. ** And no memory allocations are required. */
  179986. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  179987. iCookie = sqlite3_column_int(pStmt, 0);
  179988. }
  179989. rbuFinalize(p, pStmt);
  179990. }
  179991. if( p->rc==SQLITE_OK ){
  179992. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  179993. }
  179994. }
  179995. }
  179996. /*
  179997. ** Update the contents of the rbu_state table within the rbu database. The
  179998. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  179999. ** are determined by inspecting the rbu handle passed as the first argument.
  180000. */
  180001. static void rbuSaveState(sqlite3rbu *p, int eStage){
  180002. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  180003. sqlite3_stmt *pInsert = 0;
  180004. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  180005. int rc;
  180006. assert( p->zErrmsg==0 );
  180007. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  180008. sqlite3_mprintf(
  180009. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  180010. "(%d, %d), "
  180011. "(%d, %Q), "
  180012. "(%d, %Q), "
  180013. "(%d, %d), "
  180014. "(%d, %d), "
  180015. "(%d, %lld), "
  180016. "(%d, %lld), "
  180017. "(%d, %lld), "
  180018. "(%d, %lld), "
  180019. "(%d, %Q) ",
  180020. p->zStateDb,
  180021. RBU_STATE_STAGE, eStage,
  180022. RBU_STATE_TBL, p->objiter.zTbl,
  180023. RBU_STATE_IDX, p->objiter.zIdx,
  180024. RBU_STATE_ROW, p->nStep,
  180025. RBU_STATE_PROGRESS, p->nProgress,
  180026. RBU_STATE_CKPT, p->iWalCksum,
  180027. RBU_STATE_COOKIE, (i64)pFd->iCookie,
  180028. RBU_STATE_OALSZ, p->iOalSz,
  180029. RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,
  180030. RBU_STATE_DATATBL, p->objiter.zDataTbl
  180031. )
  180032. );
  180033. assert( pInsert==0 || rc==SQLITE_OK );
  180034. if( rc==SQLITE_OK ){
  180035. sqlite3_step(pInsert);
  180036. rc = sqlite3_finalize(pInsert);
  180037. }
  180038. if( rc!=SQLITE_OK ) p->rc = rc;
  180039. }
  180040. }
  180041. /*
  180042. ** The second argument passed to this function is the name of a PRAGMA
  180043. ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
  180044. ** This function executes the following on sqlite3rbu.dbRbu:
  180045. **
  180046. ** "PRAGMA main.$zPragma"
  180047. **
  180048. ** where $zPragma is the string passed as the second argument, then
  180049. ** on sqlite3rbu.dbMain:
  180050. **
  180051. ** "PRAGMA main.$zPragma = $val"
  180052. **
  180053. ** where $val is the value returned by the first PRAGMA invocation.
  180054. **
  180055. ** In short, it copies the value of the specified PRAGMA setting from
  180056. ** dbRbu to dbMain.
  180057. */
  180058. static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
  180059. if( p->rc==SQLITE_OK ){
  180060. sqlite3_stmt *pPragma = 0;
  180061. p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
  180062. sqlite3_mprintf("PRAGMA main.%s", zPragma)
  180063. );
  180064. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
  180065. p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
  180066. zPragma, sqlite3_column_int(pPragma, 0)
  180067. );
  180068. }
  180069. rbuFinalize(p, pPragma);
  180070. }
  180071. }
  180072. /*
  180073. ** The RBU handle passed as the only argument has just been opened and
  180074. ** the state database is empty. If this RBU handle was opened for an
  180075. ** RBU vacuum operation, create the schema in the target db.
  180076. */
  180077. static void rbuCreateTargetSchema(sqlite3rbu *p){
  180078. sqlite3_stmt *pSql = 0;
  180079. sqlite3_stmt *pInsert = 0;
  180080. assert( rbuIsVacuum(p) );
  180081. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
  180082. if( p->rc==SQLITE_OK ){
  180083. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  180084. "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
  180085. " AND name!='sqlite_sequence' "
  180086. " ORDER BY type DESC"
  180087. );
  180088. }
  180089. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  180090. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  180091. p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
  180092. }
  180093. rbuFinalize(p, pSql);
  180094. if( p->rc!=SQLITE_OK ) return;
  180095. if( p->rc==SQLITE_OK ){
  180096. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  180097. "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
  180098. );
  180099. }
  180100. if( p->rc==SQLITE_OK ){
  180101. p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
  180102. "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
  180103. );
  180104. }
  180105. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  180106. int i;
  180107. for(i=0; i<5; i++){
  180108. sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
  180109. }
  180110. sqlite3_step(pInsert);
  180111. p->rc = sqlite3_reset(pInsert);
  180112. }
  180113. if( p->rc==SQLITE_OK ){
  180114. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
  180115. }
  180116. rbuFinalize(p, pSql);
  180117. rbuFinalize(p, pInsert);
  180118. }
  180119. /*
  180120. ** Step the RBU object.
  180121. */
  180122. SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
  180123. if( p ){
  180124. switch( p->eStage ){
  180125. case RBU_STAGE_OAL: {
  180126. RbuObjIter *pIter = &p->objiter;
  180127. /* If this is an RBU vacuum operation and the state table was empty
  180128. ** when this handle was opened, create the target database schema. */
  180129. if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
  180130. rbuCreateTargetSchema(p);
  180131. rbuCopyPragma(p, "user_version");
  180132. rbuCopyPragma(p, "application_id");
  180133. }
  180134. while( p->rc==SQLITE_OK && pIter->zTbl ){
  180135. if( pIter->bCleanup ){
  180136. /* Clean up the rbu_tmp_xxx table for the previous table. It
  180137. ** cannot be dropped as there are currently active SQL statements.
  180138. ** But the contents can be deleted. */
  180139. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  180140. rbuMPrintfExec(p, p->dbRbu,
  180141. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  180142. );
  180143. }
  180144. }else{
  180145. rbuObjIterPrepareAll(p, pIter, 0);
  180146. /* Advance to the next row to process. */
  180147. if( p->rc==SQLITE_OK ){
  180148. int rc = sqlite3_step(pIter->pSelect);
  180149. if( rc==SQLITE_ROW ){
  180150. p->nProgress++;
  180151. p->nStep++;
  180152. return rbuStep(p);
  180153. }
  180154. p->rc = sqlite3_reset(pIter->pSelect);
  180155. p->nStep = 0;
  180156. }
  180157. }
  180158. rbuObjIterNext(p, pIter);
  180159. }
  180160. if( p->rc==SQLITE_OK ){
  180161. assert( pIter->zTbl==0 );
  180162. rbuSaveState(p, RBU_STAGE_MOVE);
  180163. rbuIncrSchemaCookie(p);
  180164. if( p->rc==SQLITE_OK ){
  180165. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  180166. }
  180167. if( p->rc==SQLITE_OK ){
  180168. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  180169. }
  180170. p->eStage = RBU_STAGE_MOVE;
  180171. }
  180172. break;
  180173. }
  180174. case RBU_STAGE_MOVE: {
  180175. if( p->rc==SQLITE_OK ){
  180176. rbuMoveOalFile(p);
  180177. p->nProgress++;
  180178. }
  180179. break;
  180180. }
  180181. case RBU_STAGE_CKPT: {
  180182. if( p->rc==SQLITE_OK ){
  180183. if( p->nStep>=p->nFrame ){
  180184. sqlite3_file *pDb = p->pTargetFd->pReal;
  180185. /* Sync the db file */
  180186. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  180187. /* Update nBackfill */
  180188. if( p->rc==SQLITE_OK ){
  180189. void volatile *ptr;
  180190. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  180191. if( p->rc==SQLITE_OK ){
  180192. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  180193. }
  180194. }
  180195. if( p->rc==SQLITE_OK ){
  180196. p->eStage = RBU_STAGE_DONE;
  180197. p->rc = SQLITE_DONE;
  180198. }
  180199. }else{
  180200. /* At one point the following block copied a single frame from the
  180201. ** wal file to the database file. So that one call to sqlite3rbu_step()
  180202. ** checkpointed a single frame.
  180203. **
  180204. ** However, if the sector-size is larger than the page-size, and the
  180205. ** application calls sqlite3rbu_savestate() or close() immediately
  180206. ** after this step, then rbu_step() again, then a power failure occurs,
  180207. ** then the database page written here may be damaged. Work around
  180208. ** this by checkpointing frames until the next page in the aFrame[]
  180209. ** lies on a different disk sector to the current one. */
  180210. u32 iSector;
  180211. do{
  180212. RbuFrame *pFrame = &p->aFrame[p->nStep];
  180213. iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
  180214. rbuCheckpointFrame(p, pFrame);
  180215. p->nStep++;
  180216. }while( p->nStep<p->nFrame
  180217. && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
  180218. && p->rc==SQLITE_OK
  180219. );
  180220. }
  180221. p->nProgress++;
  180222. }
  180223. break;
  180224. }
  180225. default:
  180226. break;
  180227. }
  180228. return p->rc;
  180229. }else{
  180230. return SQLITE_NOMEM;
  180231. }
  180232. }
  180233. /*
  180234. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  180235. ** otherwise. Either or both argument may be NULL. Two NULL values are
  180236. ** considered equal, and NULL is considered distinct from all other values.
  180237. */
  180238. static int rbuStrCompare(const char *z1, const char *z2){
  180239. if( z1==0 && z2==0 ) return 0;
  180240. if( z1==0 || z2==0 ) return 1;
  180241. return (sqlite3_stricmp(z1, z2)!=0);
  180242. }
  180243. /*
  180244. ** This function is called as part of sqlite3rbu_open() when initializing
  180245. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  180246. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  180247. ** things so that the next call to sqlite3rbu_step() continues on from
  180248. ** where the previous rbu handle left off.
  180249. **
  180250. ** If an error occurs, an error code and error message are left in the
  180251. ** rbu handle passed as the first argument.
  180252. */
  180253. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  180254. assert( p->rc==SQLITE_OK );
  180255. if( pState->zTbl ){
  180256. RbuObjIter *pIter = &p->objiter;
  180257. int rc = SQLITE_OK;
  180258. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  180259. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  180260. || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
  180261. || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
  180262. )){
  180263. rc = rbuObjIterNext(p, pIter);
  180264. }
  180265. if( rc==SQLITE_OK && !pIter->zTbl ){
  180266. rc = SQLITE_ERROR;
  180267. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  180268. }
  180269. if( rc==SQLITE_OK ){
  180270. p->nStep = pState->nRow;
  180271. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  180272. }
  180273. p->rc = rc;
  180274. }
  180275. }
  180276. /*
  180277. ** If there is a "*-oal" file in the file-system corresponding to the
  180278. ** target database in the file-system, delete it. If an error occurs,
  180279. ** leave an error code and error message in the rbu handle.
  180280. */
  180281. static void rbuDeleteOalFile(sqlite3rbu *p){
  180282. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  180283. if( zOal ){
  180284. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  180285. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  180286. pVfs->xDelete(pVfs, zOal, 0);
  180287. sqlite3_free(zOal);
  180288. }
  180289. }
  180290. /*
  180291. ** Allocate a private rbu VFS for the rbu handle passed as the only
  180292. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  180293. ** specified a URI with a vfs=? option in place of a target database
  180294. ** file name.
  180295. */
  180296. static void rbuCreateVfs(sqlite3rbu *p){
  180297. int rnd;
  180298. char zRnd[64];
  180299. assert( p->rc==SQLITE_OK );
  180300. sqlite3_randomness(sizeof(int), (void*)&rnd);
  180301. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  180302. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  180303. if( p->rc==SQLITE_OK ){
  180304. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  180305. assert( pVfs );
  180306. p->zVfsName = pVfs->zName;
  180307. ((rbu_vfs*)pVfs)->pRbu = p;
  180308. }
  180309. }
  180310. /*
  180311. ** Destroy the private VFS created for the rbu handle passed as the only
  180312. ** argument by an earlier call to rbuCreateVfs().
  180313. */
  180314. static void rbuDeleteVfs(sqlite3rbu *p){
  180315. if( p->zVfsName ){
  180316. sqlite3rbu_destroy_vfs(p->zVfsName);
  180317. p->zVfsName = 0;
  180318. }
  180319. }
  180320. /*
  180321. ** This user-defined SQL function is invoked with a single argument - the
  180322. ** name of a table expected to appear in the target database. It returns
  180323. ** the number of auxilliary indexes on the table.
  180324. */
  180325. static void rbuIndexCntFunc(
  180326. sqlite3_context *pCtx,
  180327. int nVal,
  180328. sqlite3_value **apVal
  180329. ){
  180330. sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
  180331. sqlite3_stmt *pStmt = 0;
  180332. char *zErrmsg = 0;
  180333. int rc;
  180334. assert( nVal==1 );
  180335. rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
  180336. sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
  180337. "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
  180338. );
  180339. if( rc!=SQLITE_OK ){
  180340. sqlite3_result_error(pCtx, zErrmsg, -1);
  180341. }else{
  180342. int nIndex = 0;
  180343. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  180344. nIndex = sqlite3_column_int(pStmt, 0);
  180345. }
  180346. rc = sqlite3_finalize(pStmt);
  180347. if( rc==SQLITE_OK ){
  180348. sqlite3_result_int(pCtx, nIndex);
  180349. }else{
  180350. sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
  180351. }
  180352. }
  180353. sqlite3_free(zErrmsg);
  180354. }
  180355. /*
  180356. ** If the RBU database contains the rbu_count table, use it to initialize
  180357. ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
  180358. ** is assumed to contain the same columns as:
  180359. **
  180360. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  180361. **
  180362. ** There should be one row in the table for each data_xxx table in the
  180363. ** database. The 'tbl' column should contain the name of a data_xxx table,
  180364. ** and the cnt column the number of rows it contains.
  180365. **
  180366. ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
  180367. ** for all rows in the rbu_count table, where nIndex is the number of
  180368. ** indexes on the corresponding target database table.
  180369. */
  180370. static void rbuInitPhaseOneSteps(sqlite3rbu *p){
  180371. if( p->rc==SQLITE_OK ){
  180372. sqlite3_stmt *pStmt = 0;
  180373. int bExists = 0; /* True if rbu_count exists */
  180374. p->nPhaseOneStep = -1;
  180375. p->rc = sqlite3_create_function(p->dbRbu,
  180376. "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
  180377. );
  180378. /* Check for the rbu_count table. If it does not exist, or if an error
  180379. ** occurs, nPhaseOneStep will be left set to -1. */
  180380. if( p->rc==SQLITE_OK ){
  180381. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  180382. "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
  180383. );
  180384. }
  180385. if( p->rc==SQLITE_OK ){
  180386. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  180387. bExists = 1;
  180388. }
  180389. p->rc = sqlite3_finalize(pStmt);
  180390. }
  180391. if( p->rc==SQLITE_OK && bExists ){
  180392. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  180393. "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
  180394. "FROM rbu_count"
  180395. );
  180396. if( p->rc==SQLITE_OK ){
  180397. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  180398. p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
  180399. }
  180400. p->rc = sqlite3_finalize(pStmt);
  180401. }
  180402. }
  180403. }
  180404. }
  180405. static sqlite3rbu *openRbuHandle(
  180406. const char *zTarget,
  180407. const char *zRbu,
  180408. const char *zState
  180409. ){
  180410. sqlite3rbu *p;
  180411. size_t nTarget = zTarget ? strlen(zTarget) : 0;
  180412. size_t nRbu = strlen(zRbu);
  180413. size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
  180414. p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  180415. if( p ){
  180416. RbuState *pState = 0;
  180417. /* Create the custom VFS. */
  180418. memset(p, 0, sizeof(sqlite3rbu));
  180419. rbuCreateVfs(p);
  180420. /* Open the target, RBU and state databases */
  180421. if( p->rc==SQLITE_OK ){
  180422. char *pCsr = (char*)&p[1];
  180423. int bRetry = 0;
  180424. if( zTarget ){
  180425. p->zTarget = pCsr;
  180426. memcpy(p->zTarget, zTarget, nTarget+1);
  180427. pCsr += nTarget+1;
  180428. }
  180429. p->zRbu = pCsr;
  180430. memcpy(p->zRbu, zRbu, nRbu+1);
  180431. pCsr += nRbu+1;
  180432. if( zState ){
  180433. p->zState = rbuMPrintf(p, "%s", zState);
  180434. }
  180435. /* If the first attempt to open the database file fails and the bRetry
  180436. ** flag it set, this means that the db was not opened because it seemed
  180437. ** to be a wal-mode db. But, this may have happened due to an earlier
  180438. ** RBU vacuum operation leaving an old wal file in the directory.
  180439. ** If this is the case, it will have been checkpointed and deleted
  180440. ** when the handle was closed and a second attempt to open the
  180441. ** database may succeed. */
  180442. rbuOpenDatabase(p, &bRetry);
  180443. if( bRetry ){
  180444. rbuOpenDatabase(p, 0);
  180445. }
  180446. }
  180447. if( p->rc==SQLITE_OK ){
  180448. pState = rbuLoadState(p);
  180449. assert( pState || p->rc!=SQLITE_OK );
  180450. if( p->rc==SQLITE_OK ){
  180451. if( pState->eStage==0 ){
  180452. rbuDeleteOalFile(p);
  180453. rbuInitPhaseOneSteps(p);
  180454. p->eStage = RBU_STAGE_OAL;
  180455. }else{
  180456. p->eStage = pState->eStage;
  180457. p->nPhaseOneStep = pState->nPhaseOneStep;
  180458. }
  180459. p->nProgress = pState->nProgress;
  180460. p->iOalSz = pState->iOalSz;
  180461. }
  180462. }
  180463. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  180464. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  180465. if( p->eStage==RBU_STAGE_OAL ){
  180466. p->rc = SQLITE_ERROR;
  180467. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  180468. }else if( p->eStage==RBU_STAGE_MOVE ){
  180469. p->eStage = RBU_STAGE_CKPT;
  180470. p->nStep = 0;
  180471. }
  180472. }
  180473. if( p->rc==SQLITE_OK
  180474. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  180475. && pState->eStage!=0
  180476. ){
  180477. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  180478. if( pFd->iCookie!=pState->iCookie ){
  180479. /* At this point (pTargetFd->iCookie) contains the value of the
  180480. ** change-counter cookie (the thing that gets incremented when a
  180481. ** transaction is committed in rollback mode) currently stored on
  180482. ** page 1 of the database file. */
  180483. p->rc = SQLITE_BUSY;
  180484. p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
  180485. (rbuIsVacuum(p) ? "vacuum" : "update")
  180486. );
  180487. }
  180488. }
  180489. if( p->rc==SQLITE_OK ){
  180490. if( p->eStage==RBU_STAGE_OAL ){
  180491. sqlite3 *db = p->dbMain;
  180492. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
  180493. /* Point the object iterator at the first object */
  180494. if( p->rc==SQLITE_OK ){
  180495. p->rc = rbuObjIterFirst(p, &p->objiter);
  180496. }
  180497. /* If the RBU database contains no data_xxx tables, declare the RBU
  180498. ** update finished. */
  180499. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  180500. p->rc = SQLITE_DONE;
  180501. p->eStage = RBU_STAGE_DONE;
  180502. }else{
  180503. if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
  180504. rbuCopyPragma(p, "page_size");
  180505. rbuCopyPragma(p, "auto_vacuum");
  180506. }
  180507. /* Open transactions both databases. The *-oal file is opened or
  180508. ** created at this point. */
  180509. if( p->rc==SQLITE_OK ){
  180510. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  180511. }
  180512. /* Check if the main database is a zipvfs db. If it is, set the upper
  180513. ** level pager to use "journal_mode=off". This prevents it from
  180514. ** generating a large journal using a temp file. */
  180515. if( p->rc==SQLITE_OK ){
  180516. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  180517. if( frc==SQLITE_OK ){
  180518. p->rc = sqlite3_exec(
  180519. db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  180520. }
  180521. }
  180522. if( p->rc==SQLITE_OK ){
  180523. rbuSetupOal(p, pState);
  180524. }
  180525. }
  180526. }else if( p->eStage==RBU_STAGE_MOVE ){
  180527. /* no-op */
  180528. }else if( p->eStage==RBU_STAGE_CKPT ){
  180529. rbuSetupCheckpoint(p, pState);
  180530. }else if( p->eStage==RBU_STAGE_DONE ){
  180531. p->rc = SQLITE_DONE;
  180532. }else{
  180533. p->rc = SQLITE_CORRUPT;
  180534. }
  180535. }
  180536. rbuFreeState(pState);
  180537. }
  180538. return p;
  180539. }
  180540. /*
  180541. ** Allocate and return an RBU handle with all fields zeroed except for the
  180542. ** error code, which is set to SQLITE_MISUSE.
  180543. */
  180544. static sqlite3rbu *rbuMisuseError(void){
  180545. sqlite3rbu *pRet;
  180546. pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
  180547. if( pRet ){
  180548. memset(pRet, 0, sizeof(sqlite3rbu));
  180549. pRet->rc = SQLITE_MISUSE;
  180550. }
  180551. return pRet;
  180552. }
  180553. /*
  180554. ** Open and return a new RBU handle.
  180555. */
  180556. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  180557. const char *zTarget,
  180558. const char *zRbu,
  180559. const char *zState
  180560. ){
  180561. if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
  180562. /* TODO: Check that zTarget and zRbu are non-NULL */
  180563. return openRbuHandle(zTarget, zRbu, zState);
  180564. }
  180565. /*
  180566. ** Open a handle to begin or resume an RBU VACUUM operation.
  180567. */
  180568. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  180569. const char *zTarget,
  180570. const char *zState
  180571. ){
  180572. if( zTarget==0 ){ return rbuMisuseError(); }
  180573. if( zState ){
  180574. int n = strlen(zState);
  180575. if( n>=7 && 0==memcmp("-vactmp", &zState[n-7], 7) ){
  180576. return rbuMisuseError();
  180577. }
  180578. }
  180579. /* TODO: Check that both arguments are non-NULL */
  180580. return openRbuHandle(0, zTarget, zState);
  180581. }
  180582. /*
  180583. ** Return the database handle used by pRbu.
  180584. */
  180585. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  180586. sqlite3 *db = 0;
  180587. if( pRbu ){
  180588. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  180589. }
  180590. return db;
  180591. }
  180592. /*
  180593. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  180594. ** then edit any error message string so as to remove all occurrences of
  180595. ** the pattern "rbu_imp_[0-9]*".
  180596. */
  180597. static void rbuEditErrmsg(sqlite3rbu *p){
  180598. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  180599. unsigned int i;
  180600. size_t nErrmsg = strlen(p->zErrmsg);
  180601. for(i=0; i<(nErrmsg-8); i++){
  180602. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  180603. int nDel = 8;
  180604. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  180605. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  180606. nErrmsg -= nDel;
  180607. }
  180608. }
  180609. }
  180610. }
  180611. /*
  180612. ** Close the RBU handle.
  180613. */
  180614. SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  180615. int rc;
  180616. if( p ){
  180617. /* Commit the transaction to the *-oal file. */
  180618. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  180619. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  180620. }
  180621. /* Sync the db file if currently doing an incremental checkpoint */
  180622. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  180623. sqlite3_file *pDb = p->pTargetFd->pReal;
  180624. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  180625. }
  180626. rbuSaveState(p, p->eStage);
  180627. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  180628. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  180629. }
  180630. /* Close any open statement handles. */
  180631. rbuObjIterFinalize(&p->objiter);
  180632. /* If this is an RBU vacuum handle and the vacuum has either finished
  180633. ** successfully or encountered an error, delete the contents of the
  180634. ** state table. This causes the next call to sqlite3rbu_vacuum()
  180635. ** specifying the current target and state databases to start a new
  180636. ** vacuum from scratch. */
  180637. if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
  180638. int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
  180639. if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
  180640. }
  180641. /* Close the open database handle and VFS object. */
  180642. sqlite3_close(p->dbRbu);
  180643. sqlite3_close(p->dbMain);
  180644. assert( p->szTemp==0 );
  180645. rbuDeleteVfs(p);
  180646. sqlite3_free(p->aBuf);
  180647. sqlite3_free(p->aFrame);
  180648. rbuEditErrmsg(p);
  180649. rc = p->rc;
  180650. if( pzErrmsg ){
  180651. *pzErrmsg = p->zErrmsg;
  180652. }else{
  180653. sqlite3_free(p->zErrmsg);
  180654. }
  180655. sqlite3_free(p->zState);
  180656. sqlite3_free(p);
  180657. }else{
  180658. rc = SQLITE_NOMEM;
  180659. *pzErrmsg = 0;
  180660. }
  180661. return rc;
  180662. }
  180663. /*
  180664. ** Return the total number of key-value operations (inserts, deletes or
  180665. ** updates) that have been performed on the target database since the
  180666. ** current RBU update was started.
  180667. */
  180668. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
  180669. return pRbu->nProgress;
  180670. }
  180671. /*
  180672. ** Return permyriadage progress indications for the two main stages of
  180673. ** an RBU update.
  180674. */
  180675. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
  180676. const int MAX_PROGRESS = 10000;
  180677. switch( p->eStage ){
  180678. case RBU_STAGE_OAL:
  180679. if( p->nPhaseOneStep>0 ){
  180680. *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
  180681. }else{
  180682. *pnOne = -1;
  180683. }
  180684. *pnTwo = 0;
  180685. break;
  180686. case RBU_STAGE_MOVE:
  180687. *pnOne = MAX_PROGRESS;
  180688. *pnTwo = 0;
  180689. break;
  180690. case RBU_STAGE_CKPT:
  180691. *pnOne = MAX_PROGRESS;
  180692. *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
  180693. break;
  180694. case RBU_STAGE_DONE:
  180695. *pnOne = MAX_PROGRESS;
  180696. *pnTwo = MAX_PROGRESS;
  180697. break;
  180698. default:
  180699. assert( 0 );
  180700. }
  180701. }
  180702. /*
  180703. ** Return the current state of the RBU vacuum or update operation.
  180704. */
  180705. SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
  180706. int aRes[] = {
  180707. 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
  180708. 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
  180709. };
  180710. assert( RBU_STAGE_OAL==1 );
  180711. assert( RBU_STAGE_MOVE==2 );
  180712. assert( RBU_STAGE_CKPT==4 );
  180713. assert( RBU_STAGE_DONE==5 );
  180714. assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
  180715. assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
  180716. assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
  180717. assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
  180718. if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
  180719. return SQLITE_RBU_STATE_ERROR;
  180720. }else{
  180721. assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
  180722. assert( p->eStage==RBU_STAGE_OAL
  180723. || p->eStage==RBU_STAGE_MOVE
  180724. || p->eStage==RBU_STAGE_CKPT
  180725. || p->eStage==RBU_STAGE_DONE
  180726. );
  180727. return aRes[p->eStage];
  180728. }
  180729. }
  180730. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
  180731. int rc = p->rc;
  180732. if( rc==SQLITE_DONE ) return SQLITE_OK;
  180733. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  180734. if( p->eStage==RBU_STAGE_OAL ){
  180735. assert( rc!=SQLITE_DONE );
  180736. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  180737. }
  180738. /* Sync the db file */
  180739. if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  180740. sqlite3_file *pDb = p->pTargetFd->pReal;
  180741. rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  180742. }
  180743. p->rc = rc;
  180744. rbuSaveState(p, p->eStage);
  180745. rc = p->rc;
  180746. if( p->eStage==RBU_STAGE_OAL ){
  180747. assert( rc!=SQLITE_DONE );
  180748. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  180749. if( rc==SQLITE_OK ){
  180750. const char *zBegin = rbuIsVacuum(p) ? "BEGIN" : "BEGIN IMMEDIATE";
  180751. rc = sqlite3_exec(p->dbRbu, zBegin, 0, 0, 0);
  180752. }
  180753. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  180754. }
  180755. p->rc = rc;
  180756. return rc;
  180757. }
  180758. /**************************************************************************
  180759. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  180760. ** of a standard VFS in the following ways:
  180761. **
  180762. ** 1. Whenever the first page of a main database file is read or
  180763. ** written, the value of the change-counter cookie is stored in
  180764. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  180765. ** database header field is stored in rbu_file.iWriteVer. This ensures
  180766. ** that the values are always trustworthy within an open transaction.
  180767. **
  180768. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  180769. ** member variable of the associated database file descriptor is set
  180770. ** to point to the new file. A mutex protected linked list of all main
  180771. ** db fds opened using a particular RBU VFS is maintained at
  180772. ** rbu_vfs.pMain to facilitate this.
  180773. **
  180774. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  180775. ** object can be marked as the target database of an RBU update. This
  180776. ** turns on the following extra special behaviour:
  180777. **
  180778. ** 3a. If xAccess() is called to check if there exists a *-wal file
  180779. ** associated with an RBU target database currently in RBU_STAGE_OAL
  180780. ** stage (preparing the *-oal file), the following special handling
  180781. ** applies:
  180782. **
  180783. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  180784. ** target database may not be in wal mode already.
  180785. **
  180786. ** * if the *-wal file does not exist, set the output parameter to
  180787. ** non-zero (to tell SQLite that it does exist) anyway.
  180788. **
  180789. ** Then, when xOpen() is called to open the *-wal file associated with
  180790. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  180791. ** file, the rbu vfs opens the corresponding *-oal file instead.
  180792. **
  180793. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  180794. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  180795. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  180796. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  180797. ** because assert() statements in some VFS implementations fail if
  180798. ** xShmLock() is called before xShmMap().
  180799. **
  180800. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  180801. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  180802. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  180803. ** from automatically checkpointing a *-wal (or *-oal) file from within
  180804. ** sqlite3_close().
  180805. **
  180806. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  180807. ** all xWrite() calls on the target database file perform no IO.
  180808. ** Instead the frame and page numbers that would be read and written
  180809. ** are recorded. Additionally, successful attempts to obtain exclusive
  180810. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  180811. ** database file are recorded. xShmLock() calls to unlock the same
  180812. ** locks are no-ops (so that once obtained, these locks are never
  180813. ** relinquished). Finally, calls to xSync() on the target database
  180814. ** file fail with SQLITE_INTERNAL errors.
  180815. */
  180816. static void rbuUnlockShm(rbu_file *p){
  180817. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  180818. if( p->pRbu ){
  180819. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  180820. int i;
  180821. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  180822. if( (1<<i) & p->pRbu->mLock ){
  180823. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  180824. }
  180825. }
  180826. p->pRbu->mLock = 0;
  180827. }
  180828. }
  180829. /*
  180830. */
  180831. static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
  180832. sqlite3rbu *pRbu = pFd->pRbu;
  180833. i64 nDiff = nNew - pFd->sz;
  180834. pRbu->szTemp += nDiff;
  180835. pFd->sz = nNew;
  180836. assert( pRbu->szTemp>=0 );
  180837. if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
  180838. return SQLITE_OK;
  180839. }
  180840. /*
  180841. ** Add an item to the main-db lists, if it is not already present.
  180842. **
  180843. ** There are two main-db lists. One for all file descriptors, and one
  180844. ** for all file descriptors with rbu_file.pDb!=0. If the argument has
  180845. ** rbu_file.pDb!=0, then it is assumed to already be present on the
  180846. ** main list and is only added to the pDb!=0 list.
  180847. */
  180848. static void rbuMainlistAdd(rbu_file *p){
  180849. rbu_vfs *pRbuVfs = p->pRbuVfs;
  180850. rbu_file *pIter;
  180851. assert( (p->openFlags & SQLITE_OPEN_MAIN_DB) );
  180852. sqlite3_mutex_enter(pRbuVfs->mutex);
  180853. if( p->pRbu==0 ){
  180854. for(pIter=pRbuVfs->pMain; pIter; pIter=pIter->pMainNext);
  180855. p->pMainNext = pRbuVfs->pMain;
  180856. pRbuVfs->pMain = p;
  180857. }else{
  180858. for(pIter=pRbuVfs->pMainRbu; pIter && pIter!=p; pIter=pIter->pMainRbuNext){}
  180859. if( pIter==0 ){
  180860. p->pMainRbuNext = pRbuVfs->pMainRbu;
  180861. pRbuVfs->pMainRbu = p;
  180862. }
  180863. }
  180864. sqlite3_mutex_leave(pRbuVfs->mutex);
  180865. }
  180866. /*
  180867. ** Remove an item from the main-db lists.
  180868. */
  180869. static void rbuMainlistRemove(rbu_file *p){
  180870. rbu_file **pp;
  180871. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  180872. for(pp=&p->pRbuVfs->pMain; *pp && *pp!=p; pp=&((*pp)->pMainNext)){}
  180873. if( *pp ) *pp = p->pMainNext;
  180874. p->pMainNext = 0;
  180875. for(pp=&p->pRbuVfs->pMainRbu; *pp && *pp!=p; pp=&((*pp)->pMainRbuNext)){}
  180876. if( *pp ) *pp = p->pMainRbuNext;
  180877. p->pMainRbuNext = 0;
  180878. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  180879. }
  180880. /*
  180881. ** Given that zWal points to a buffer containing a wal file name passed to
  180882. ** either the xOpen() or xAccess() VFS method, search the main-db list for
  180883. ** a file-handle opened by the same database connection on the corresponding
  180884. ** database file.
  180885. **
  180886. ** If parameter bRbu is true, only search for file-descriptors with
  180887. ** rbu_file.pDb!=0.
  180888. */
  180889. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal, int bRbu){
  180890. rbu_file *pDb;
  180891. sqlite3_mutex_enter(pRbuVfs->mutex);
  180892. if( bRbu ){
  180893. for(pDb=pRbuVfs->pMainRbu; pDb && pDb->zWal!=zWal; pDb=pDb->pMainRbuNext){}
  180894. }else{
  180895. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
  180896. }
  180897. sqlite3_mutex_leave(pRbuVfs->mutex);
  180898. return pDb;
  180899. }
  180900. /*
  180901. ** Close an rbu file.
  180902. */
  180903. static int rbuVfsClose(sqlite3_file *pFile){
  180904. rbu_file *p = (rbu_file*)pFile;
  180905. int rc;
  180906. int i;
  180907. /* Free the contents of the apShm[] array. And the array itself. */
  180908. for(i=0; i<p->nShm; i++){
  180909. sqlite3_free(p->apShm[i]);
  180910. }
  180911. sqlite3_free(p->apShm);
  180912. p->apShm = 0;
  180913. sqlite3_free(p->zDel);
  180914. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  180915. rbuMainlistRemove(p);
  180916. rbuUnlockShm(p);
  180917. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  180918. }
  180919. else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  180920. rbuUpdateTempSize(p, 0);
  180921. }
  180922. assert( p->pMainNext==0 && p->pRbuVfs->pMain!=p );
  180923. /* Close the underlying file handle */
  180924. rc = p->pReal->pMethods->xClose(p->pReal);
  180925. return rc;
  180926. }
  180927. /*
  180928. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  180929. ** passed as the only argument.
  180930. */
  180931. static u32 rbuGetU32(u8 *aBuf){
  180932. return ((u32)aBuf[0] << 24)
  180933. + ((u32)aBuf[1] << 16)
  180934. + ((u32)aBuf[2] << 8)
  180935. + ((u32)aBuf[3]);
  180936. }
  180937. /*
  180938. ** Write an unsigned 32-bit value in big-endian format to the supplied
  180939. ** buffer.
  180940. */
  180941. static void rbuPutU32(u8 *aBuf, u32 iVal){
  180942. aBuf[0] = (iVal >> 24) & 0xFF;
  180943. aBuf[1] = (iVal >> 16) & 0xFF;
  180944. aBuf[2] = (iVal >> 8) & 0xFF;
  180945. aBuf[3] = (iVal >> 0) & 0xFF;
  180946. }
  180947. static void rbuPutU16(u8 *aBuf, u16 iVal){
  180948. aBuf[0] = (iVal >> 8) & 0xFF;
  180949. aBuf[1] = (iVal >> 0) & 0xFF;
  180950. }
  180951. /*
  180952. ** Read data from an rbuVfs-file.
  180953. */
  180954. static int rbuVfsRead(
  180955. sqlite3_file *pFile,
  180956. void *zBuf,
  180957. int iAmt,
  180958. sqlite_int64 iOfst
  180959. ){
  180960. rbu_file *p = (rbu_file*)pFile;
  180961. sqlite3rbu *pRbu = p->pRbu;
  180962. int rc;
  180963. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  180964. assert( p->openFlags & SQLITE_OPEN_WAL );
  180965. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  180966. }else{
  180967. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  180968. && (p->openFlags & SQLITE_OPEN_WAL)
  180969. && iOfst>=pRbu->iOalSz
  180970. ){
  180971. rc = SQLITE_OK;
  180972. memset(zBuf, 0, iAmt);
  180973. }else{
  180974. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  180975. #if 1
  180976. /* If this is being called to read the first page of the target
  180977. ** database as part of an rbu vacuum operation, synthesize the
  180978. ** contents of the first page if it does not yet exist. Otherwise,
  180979. ** SQLite will not check for a *-wal file. */
  180980. if( pRbu && rbuIsVacuum(pRbu)
  180981. && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
  180982. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  180983. && pRbu->rc==SQLITE_OK
  180984. ){
  180985. sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
  180986. rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
  180987. if( rc==SQLITE_OK ){
  180988. u8 *aBuf = (u8*)zBuf;
  180989. u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
  180990. rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
  180991. rbuPutU32(&aBuf[36], 0); /* number of free pages */
  180992. rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
  180993. rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
  180994. rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
  180995. if( iAmt>100 ){
  180996. memset(&aBuf[100], 0, iAmt-100);
  180997. rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
  180998. aBuf[100] = 0x0D;
  180999. }
  181000. }
  181001. }
  181002. #endif
  181003. }
  181004. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  181005. /* These look like magic numbers. But they are stable, as they are part
  181006. ** of the definition of the SQLite file format, which may not change. */
  181007. u8 *pBuf = (u8*)zBuf;
  181008. p->iCookie = rbuGetU32(&pBuf[24]);
  181009. p->iWriteVer = pBuf[19];
  181010. }
  181011. }
  181012. return rc;
  181013. }
  181014. /*
  181015. ** Write data to an rbuVfs-file.
  181016. */
  181017. static int rbuVfsWrite(
  181018. sqlite3_file *pFile,
  181019. const void *zBuf,
  181020. int iAmt,
  181021. sqlite_int64 iOfst
  181022. ){
  181023. rbu_file *p = (rbu_file*)pFile;
  181024. sqlite3rbu *pRbu = p->pRbu;
  181025. int rc;
  181026. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  181027. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  181028. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  181029. }else{
  181030. if( pRbu ){
  181031. if( pRbu->eStage==RBU_STAGE_OAL
  181032. && (p->openFlags & SQLITE_OPEN_WAL)
  181033. && iOfst>=pRbu->iOalSz
  181034. ){
  181035. pRbu->iOalSz = iAmt + iOfst;
  181036. }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
  181037. i64 szNew = iAmt+iOfst;
  181038. if( szNew>p->sz ){
  181039. rc = rbuUpdateTempSize(p, szNew);
  181040. if( rc!=SQLITE_OK ) return rc;
  181041. }
  181042. }
  181043. }
  181044. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  181045. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  181046. /* These look like magic numbers. But they are stable, as they are part
  181047. ** of the definition of the SQLite file format, which may not change. */
  181048. u8 *pBuf = (u8*)zBuf;
  181049. p->iCookie = rbuGetU32(&pBuf[24]);
  181050. p->iWriteVer = pBuf[19];
  181051. }
  181052. }
  181053. return rc;
  181054. }
  181055. /*
  181056. ** Truncate an rbuVfs-file.
  181057. */
  181058. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  181059. rbu_file *p = (rbu_file*)pFile;
  181060. if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  181061. int rc = rbuUpdateTempSize(p, size);
  181062. if( rc!=SQLITE_OK ) return rc;
  181063. }
  181064. return p->pReal->pMethods->xTruncate(p->pReal, size);
  181065. }
  181066. /*
  181067. ** Sync an rbuVfs-file.
  181068. */
  181069. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  181070. rbu_file *p = (rbu_file *)pFile;
  181071. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  181072. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  181073. return SQLITE_INTERNAL;
  181074. }
  181075. return SQLITE_OK;
  181076. }
  181077. return p->pReal->pMethods->xSync(p->pReal, flags);
  181078. }
  181079. /*
  181080. ** Return the current file-size of an rbuVfs-file.
  181081. */
  181082. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  181083. rbu_file *p = (rbu_file *)pFile;
  181084. int rc;
  181085. rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
  181086. /* If this is an RBU vacuum operation and this is the target database,
  181087. ** pretend that it has at least one page. Otherwise, SQLite will not
  181088. ** check for the existance of a *-wal file. rbuVfsRead() contains
  181089. ** similar logic. */
  181090. if( rc==SQLITE_OK && *pSize==0
  181091. && p->pRbu && rbuIsVacuum(p->pRbu)
  181092. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  181093. ){
  181094. *pSize = 1024;
  181095. }
  181096. return rc;
  181097. }
  181098. /*
  181099. ** Lock an rbuVfs-file.
  181100. */
  181101. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  181102. rbu_file *p = (rbu_file*)pFile;
  181103. sqlite3rbu *pRbu = p->pRbu;
  181104. int rc = SQLITE_OK;
  181105. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  181106. if( eLock==SQLITE_LOCK_EXCLUSIVE
  181107. && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
  181108. ){
  181109. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  181110. ** prevents it from checkpointing the database from sqlite3_close(). */
  181111. rc = SQLITE_BUSY;
  181112. }else{
  181113. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  181114. }
  181115. return rc;
  181116. }
  181117. /*
  181118. ** Unlock an rbuVfs-file.
  181119. */
  181120. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  181121. rbu_file *p = (rbu_file *)pFile;
  181122. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  181123. }
  181124. /*
  181125. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  181126. */
  181127. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  181128. rbu_file *p = (rbu_file *)pFile;
  181129. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  181130. }
  181131. /*
  181132. ** File control method. For custom operations on an rbuVfs-file.
  181133. */
  181134. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  181135. rbu_file *p = (rbu_file *)pFile;
  181136. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  181137. int rc;
  181138. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  181139. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  181140. );
  181141. if( op==SQLITE_FCNTL_RBU ){
  181142. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  181143. /* First try to find another RBU vfs lower down in the vfs stack. If
  181144. ** one is found, this vfs will operate in pass-through mode. The lower
  181145. ** level vfs will do the special RBU handling. */
  181146. rc = xControl(p->pReal, op, pArg);
  181147. if( rc==SQLITE_NOTFOUND ){
  181148. /* Now search for a zipvfs instance lower down in the VFS stack. If
  181149. ** one is found, this is an error. */
  181150. void *dummy = 0;
  181151. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  181152. if( rc==SQLITE_OK ){
  181153. rc = SQLITE_ERROR;
  181154. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  181155. }else if( rc==SQLITE_NOTFOUND ){
  181156. pRbu->pTargetFd = p;
  181157. p->pRbu = pRbu;
  181158. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  181159. rbuMainlistAdd(p);
  181160. }
  181161. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  181162. rc = SQLITE_OK;
  181163. }
  181164. }
  181165. return rc;
  181166. }
  181167. else if( op==SQLITE_FCNTL_RBUCNT ){
  181168. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  181169. pRbu->nRbu++;
  181170. pRbu->pRbuFd = p;
  181171. p->bNolock = 1;
  181172. }
  181173. rc = xControl(p->pReal, op, pArg);
  181174. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  181175. rbu_vfs *pRbuVfs = p->pRbuVfs;
  181176. char *zIn = *(char**)pArg;
  181177. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  181178. *(char**)pArg = zOut;
  181179. if( zOut==0 ) rc = SQLITE_NOMEM;
  181180. }
  181181. return rc;
  181182. }
  181183. /*
  181184. ** Return the sector-size in bytes for an rbuVfs-file.
  181185. */
  181186. static int rbuVfsSectorSize(sqlite3_file *pFile){
  181187. rbu_file *p = (rbu_file *)pFile;
  181188. return p->pReal->pMethods->xSectorSize(p->pReal);
  181189. }
  181190. /*
  181191. ** Return the device characteristic flags supported by an rbuVfs-file.
  181192. */
  181193. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  181194. rbu_file *p = (rbu_file *)pFile;
  181195. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  181196. }
  181197. /*
  181198. ** Take or release a shared-memory lock.
  181199. */
  181200. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  181201. rbu_file *p = (rbu_file*)pFile;
  181202. sqlite3rbu *pRbu = p->pRbu;
  181203. int rc = SQLITE_OK;
  181204. #ifdef SQLITE_AMALGAMATION
  181205. assert( WAL_CKPT_LOCK==1 );
  181206. #endif
  181207. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  181208. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  181209. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  181210. ** taking this lock also prevents any checkpoints from occurring.
  181211. ** todo: really, it's not clear why this might occur, as
  181212. ** wal_autocheckpoint ought to be turned off. */
  181213. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  181214. }else{
  181215. int bCapture = 0;
  181216. if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
  181217. && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
  181218. && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
  181219. ){
  181220. bCapture = 1;
  181221. }
  181222. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  181223. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  181224. if( bCapture && rc==SQLITE_OK ){
  181225. pRbu->mLock |= (1 << ofst);
  181226. }
  181227. }
  181228. }
  181229. return rc;
  181230. }
  181231. /*
  181232. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  181233. */
  181234. static int rbuVfsShmMap(
  181235. sqlite3_file *pFile,
  181236. int iRegion,
  181237. int szRegion,
  181238. int isWrite,
  181239. void volatile **pp
  181240. ){
  181241. rbu_file *p = (rbu_file*)pFile;
  181242. int rc = SQLITE_OK;
  181243. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  181244. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  181245. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  181246. ** instead of a file on disk. */
  181247. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  181248. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  181249. if( iRegion<=p->nShm ){
  181250. sqlite3_int64 nByte = (iRegion+1) * sizeof(char*);
  181251. char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
  181252. if( apNew==0 ){
  181253. rc = SQLITE_NOMEM;
  181254. }else{
  181255. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  181256. p->apShm = apNew;
  181257. p->nShm = iRegion+1;
  181258. }
  181259. }
  181260. if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
  181261. char *pNew = (char*)sqlite3_malloc64(szRegion);
  181262. if( pNew==0 ){
  181263. rc = SQLITE_NOMEM;
  181264. }else{
  181265. memset(pNew, 0, szRegion);
  181266. p->apShm[iRegion] = pNew;
  181267. }
  181268. }
  181269. if( rc==SQLITE_OK ){
  181270. *pp = p->apShm[iRegion];
  181271. }else{
  181272. *pp = 0;
  181273. }
  181274. }else{
  181275. assert( p->apShm==0 );
  181276. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  181277. }
  181278. return rc;
  181279. }
  181280. /*
  181281. ** Memory barrier.
  181282. */
  181283. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  181284. rbu_file *p = (rbu_file *)pFile;
  181285. p->pReal->pMethods->xShmBarrier(p->pReal);
  181286. }
  181287. /*
  181288. ** The xShmUnmap method.
  181289. */
  181290. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  181291. rbu_file *p = (rbu_file*)pFile;
  181292. int rc = SQLITE_OK;
  181293. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  181294. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  181295. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  181296. /* no-op */
  181297. }else{
  181298. /* Release the checkpointer and writer locks */
  181299. rbuUnlockShm(p);
  181300. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  181301. }
  181302. return rc;
  181303. }
  181304. /*
  181305. ** A main database named zName has just been opened. The following
  181306. ** function returns a pointer to a buffer owned by SQLite that contains
  181307. ** the name of the *-wal file this db connection will use. SQLite
  181308. ** happens to pass a pointer to this buffer when using xAccess()
  181309. ** or xOpen() to operate on the *-wal file.
  181310. */
  181311. static const char *rbuMainToWal(const char *zName, int flags){
  181312. int n = (int)strlen(zName);
  181313. const char *z = &zName[n];
  181314. if( flags & SQLITE_OPEN_URI ){
  181315. int odd = 0;
  181316. while( 1 ){
  181317. if( z[0]==0 ){
  181318. odd = 1 - odd;
  181319. if( odd && z[1]==0 ) break;
  181320. }
  181321. z++;
  181322. }
  181323. z += 2;
  181324. }else{
  181325. while( *z==0 ) z++;
  181326. }
  181327. z += (n + 8 + 1);
  181328. return z;
  181329. }
  181330. /*
  181331. ** Open an rbu file handle.
  181332. */
  181333. static int rbuVfsOpen(
  181334. sqlite3_vfs *pVfs,
  181335. const char *zName,
  181336. sqlite3_file *pFile,
  181337. int flags,
  181338. int *pOutFlags
  181339. ){
  181340. static sqlite3_io_methods rbuvfs_io_methods = {
  181341. 2, /* iVersion */
  181342. rbuVfsClose, /* xClose */
  181343. rbuVfsRead, /* xRead */
  181344. rbuVfsWrite, /* xWrite */
  181345. rbuVfsTruncate, /* xTruncate */
  181346. rbuVfsSync, /* xSync */
  181347. rbuVfsFileSize, /* xFileSize */
  181348. rbuVfsLock, /* xLock */
  181349. rbuVfsUnlock, /* xUnlock */
  181350. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  181351. rbuVfsFileControl, /* xFileControl */
  181352. rbuVfsSectorSize, /* xSectorSize */
  181353. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  181354. rbuVfsShmMap, /* xShmMap */
  181355. rbuVfsShmLock, /* xShmLock */
  181356. rbuVfsShmBarrier, /* xShmBarrier */
  181357. rbuVfsShmUnmap, /* xShmUnmap */
  181358. 0, 0 /* xFetch, xUnfetch */
  181359. };
  181360. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  181361. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  181362. rbu_file *pFd = (rbu_file *)pFile;
  181363. int rc = SQLITE_OK;
  181364. const char *zOpen = zName;
  181365. int oflags = flags;
  181366. memset(pFd, 0, sizeof(rbu_file));
  181367. pFd->pReal = (sqlite3_file*)&pFd[1];
  181368. pFd->pRbuVfs = pRbuVfs;
  181369. pFd->openFlags = flags;
  181370. if( zName ){
  181371. if( flags & SQLITE_OPEN_MAIN_DB ){
  181372. /* A main database has just been opened. The following block sets
  181373. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  181374. ** the name of the *-wal file this db connection will use. SQLite
  181375. ** happens to pass a pointer to this buffer when using xAccess()
  181376. ** or xOpen() to operate on the *-wal file. */
  181377. pFd->zWal = rbuMainToWal(zName, flags);
  181378. }
  181379. else if( flags & SQLITE_OPEN_WAL ){
  181380. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);
  181381. if( pDb ){
  181382. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  181383. /* This call is to open a *-wal file. Intead, open the *-oal. This
  181384. ** code ensures that the string passed to xOpen() is terminated by a
  181385. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  181386. ** parameter from it. */
  181387. const char *zBase = zName;
  181388. size_t nCopy;
  181389. char *zCopy;
  181390. if( rbuIsVacuum(pDb->pRbu) ){
  181391. zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
  181392. zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
  181393. }
  181394. nCopy = strlen(zBase);
  181395. zCopy = sqlite3_malloc64(nCopy+2);
  181396. if( zCopy ){
  181397. memcpy(zCopy, zBase, nCopy);
  181398. zCopy[nCopy-3] = 'o';
  181399. zCopy[nCopy] = '\0';
  181400. zCopy[nCopy+1] = '\0';
  181401. zOpen = (const char*)(pFd->zDel = zCopy);
  181402. }else{
  181403. rc = SQLITE_NOMEM;
  181404. }
  181405. pFd->pRbu = pDb->pRbu;
  181406. }
  181407. pDb->pWalFd = pFd;
  181408. }
  181409. }
  181410. }else{
  181411. pFd->pRbu = pRbuVfs->pRbu;
  181412. }
  181413. if( oflags & SQLITE_OPEN_MAIN_DB
  181414. && sqlite3_uri_boolean(zName, "rbu_memory", 0)
  181415. ){
  181416. assert( oflags & SQLITE_OPEN_MAIN_DB );
  181417. oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  181418. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  181419. zOpen = 0;
  181420. }
  181421. if( rc==SQLITE_OK ){
  181422. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
  181423. }
  181424. if( pFd->pReal->pMethods ){
  181425. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  181426. ** pointer and, if the file is a main database file, link it into the
  181427. ** mutex protected linked list of all such files. */
  181428. pFile->pMethods = &rbuvfs_io_methods;
  181429. if( flags & SQLITE_OPEN_MAIN_DB ){
  181430. rbuMainlistAdd(pFd);
  181431. }
  181432. }else{
  181433. sqlite3_free(pFd->zDel);
  181434. }
  181435. return rc;
  181436. }
  181437. /*
  181438. ** Delete the file located at zPath.
  181439. */
  181440. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  181441. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  181442. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  181443. }
  181444. /*
  181445. ** Test for access permissions. Return true if the requested permission
  181446. ** is available, or false otherwise.
  181447. */
  181448. static int rbuVfsAccess(
  181449. sqlite3_vfs *pVfs,
  181450. const char *zPath,
  181451. int flags,
  181452. int *pResOut
  181453. ){
  181454. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  181455. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  181456. int rc;
  181457. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  181458. /* If this call is to check if a *-wal file associated with an RBU target
  181459. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  181460. ** the following special handling is activated:
  181461. **
  181462. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  181463. ** ensures that the RBU extension never tries to update a database
  181464. ** in wal mode, even if the first page of the database file has
  181465. ** been damaged.
  181466. **
  181467. ** b) if the *-wal file does not exist, claim that it does anyway,
  181468. ** causing SQLite to call xOpen() to open it. This call will also
  181469. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  181470. ** file opened instead.
  181471. */
  181472. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  181473. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath, 1);
  181474. if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  181475. if( *pResOut ){
  181476. rc = SQLITE_CANTOPEN;
  181477. }else{
  181478. sqlite3_int64 sz = 0;
  181479. rc = rbuVfsFileSize(&pDb->base, &sz);
  181480. *pResOut = (sz>0);
  181481. }
  181482. }
  181483. }
  181484. return rc;
  181485. }
  181486. /*
  181487. ** Populate buffer zOut with the full canonical pathname corresponding
  181488. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  181489. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  181490. */
  181491. static int rbuVfsFullPathname(
  181492. sqlite3_vfs *pVfs,
  181493. const char *zPath,
  181494. int nOut,
  181495. char *zOut
  181496. ){
  181497. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  181498. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  181499. }
  181500. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  181501. /*
  181502. ** Open the dynamic library located at zPath and return a handle.
  181503. */
  181504. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  181505. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  181506. return pRealVfs->xDlOpen(pRealVfs, zPath);
  181507. }
  181508. /*
  181509. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  181510. ** utf-8 string describing the most recent error encountered associated
  181511. ** with dynamic libraries.
  181512. */
  181513. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  181514. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  181515. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  181516. }
  181517. /*
  181518. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  181519. */
  181520. static void (*rbuVfsDlSym(
  181521. sqlite3_vfs *pVfs,
  181522. void *pArg,
  181523. const char *zSym
  181524. ))(void){
  181525. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  181526. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  181527. }
  181528. /*
  181529. ** Close the dynamic library handle pHandle.
  181530. */
  181531. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  181532. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  181533. pRealVfs->xDlClose(pRealVfs, pHandle);
  181534. }
  181535. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  181536. /*
  181537. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  181538. ** random data.
  181539. */
  181540. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  181541. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  181542. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  181543. }
  181544. /*
  181545. ** Sleep for nMicro microseconds. Return the number of microseconds
  181546. ** actually slept.
  181547. */
  181548. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  181549. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  181550. return pRealVfs->xSleep(pRealVfs, nMicro);
  181551. }
  181552. /*
  181553. ** Return the current time as a Julian Day number in *pTimeOut.
  181554. */
  181555. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  181556. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  181557. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  181558. }
  181559. /*
  181560. ** No-op.
  181561. */
  181562. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  181563. return 0;
  181564. }
  181565. /*
  181566. ** Deregister and destroy an RBU vfs created by an earlier call to
  181567. ** sqlite3rbu_create_vfs().
  181568. */
  181569. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
  181570. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  181571. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  181572. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  181573. sqlite3_vfs_unregister(pVfs);
  181574. sqlite3_free(pVfs);
  181575. }
  181576. }
  181577. /*
  181578. ** Create an RBU VFS named zName that accesses the underlying file-system
  181579. ** via existing VFS zParent. The new object is registered as a non-default
  181580. ** VFS with SQLite before returning.
  181581. */
  181582. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  181583. /* Template for VFS */
  181584. static sqlite3_vfs vfs_template = {
  181585. 1, /* iVersion */
  181586. 0, /* szOsFile */
  181587. 0, /* mxPathname */
  181588. 0, /* pNext */
  181589. 0, /* zName */
  181590. 0, /* pAppData */
  181591. rbuVfsOpen, /* xOpen */
  181592. rbuVfsDelete, /* xDelete */
  181593. rbuVfsAccess, /* xAccess */
  181594. rbuVfsFullPathname, /* xFullPathname */
  181595. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  181596. rbuVfsDlOpen, /* xDlOpen */
  181597. rbuVfsDlError, /* xDlError */
  181598. rbuVfsDlSym, /* xDlSym */
  181599. rbuVfsDlClose, /* xDlClose */
  181600. #else
  181601. 0, 0, 0, 0,
  181602. #endif
  181603. rbuVfsRandomness, /* xRandomness */
  181604. rbuVfsSleep, /* xSleep */
  181605. rbuVfsCurrentTime, /* xCurrentTime */
  181606. rbuVfsGetLastError, /* xGetLastError */
  181607. 0, /* xCurrentTimeInt64 (version 2) */
  181608. 0, 0, 0 /* Unimplemented version 3 methods */
  181609. };
  181610. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  181611. int rc = SQLITE_OK;
  181612. size_t nName;
  181613. size_t nByte;
  181614. nName = strlen(zName);
  181615. nByte = sizeof(rbu_vfs) + nName + 1;
  181616. pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
  181617. if( pNew==0 ){
  181618. rc = SQLITE_NOMEM;
  181619. }else{
  181620. sqlite3_vfs *pParent; /* Parent VFS */
  181621. memset(pNew, 0, nByte);
  181622. pParent = sqlite3_vfs_find(zParent);
  181623. if( pParent==0 ){
  181624. rc = SQLITE_NOTFOUND;
  181625. }else{
  181626. char *zSpace;
  181627. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  181628. pNew->base.mxPathname = pParent->mxPathname;
  181629. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  181630. pNew->pRealVfs = pParent;
  181631. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  181632. memcpy(zSpace, zName, nName);
  181633. /* Allocate the mutex and register the new VFS (not as the default) */
  181634. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  181635. if( pNew->mutex==0 ){
  181636. rc = SQLITE_NOMEM;
  181637. }else{
  181638. rc = sqlite3_vfs_register(&pNew->base, 0);
  181639. }
  181640. }
  181641. if( rc!=SQLITE_OK ){
  181642. sqlite3_mutex_free(pNew->mutex);
  181643. sqlite3_free(pNew);
  181644. }
  181645. }
  181646. return rc;
  181647. }
  181648. /*
  181649. ** Configure the aggregate temp file size limit for this RBU handle.
  181650. */
  181651. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
  181652. if( n>=0 ){
  181653. pRbu->szTempLimit = n;
  181654. }
  181655. return pRbu->szTempLimit;
  181656. }
  181657. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
  181658. return pRbu->szTemp;
  181659. }
  181660. /**************************************************************************/
  181661. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  181662. /************** End of sqlite3rbu.c ******************************************/
  181663. /************** Begin file dbstat.c ******************************************/
  181664. /*
  181665. ** 2010 July 12
  181666. **
  181667. ** The author disclaims copyright to this source code. In place of
  181668. ** a legal notice, here is a blessing:
  181669. **
  181670. ** May you do good and not evil.
  181671. ** May you find forgiveness for yourself and forgive others.
  181672. ** May you share freely, never taking more than you give.
  181673. **
  181674. ******************************************************************************
  181675. **
  181676. ** This file contains an implementation of the "dbstat" virtual table.
  181677. **
  181678. ** The dbstat virtual table is used to extract low-level formatting
  181679. ** information from an SQLite database in order to implement the
  181680. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  181681. ** for an example implementation.
  181682. **
  181683. ** Additional information is available on the "dbstat.html" page of the
  181684. ** official SQLite documentation.
  181685. */
  181686. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  181687. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  181688. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  181689. /*
  181690. ** Page paths:
  181691. **
  181692. ** The value of the 'path' column describes the path taken from the
  181693. ** root-node of the b-tree structure to each page. The value of the
  181694. ** root-node path is '/'.
  181695. **
  181696. ** The value of the path for the left-most child page of the root of
  181697. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  181698. ** so the pages to the left have smaller keys than the pages to the right.)
  181699. ** The next to left-most child of the root page is
  181700. ** '/001', and so on, each sibling page identified by a 3-digit hex
  181701. ** value. The children of the 451st left-most sibling have paths such
  181702. ** as '/1c2/000/, '/1c2/001/' etc.
  181703. **
  181704. ** Overflow pages are specified by appending a '+' character and a
  181705. ** six-digit hexadecimal value to the path to the cell they are linked
  181706. ** from. For example, the three overflow pages in a chain linked from
  181707. ** the left-most cell of the 450th child of the root page are identified
  181708. ** by the paths:
  181709. **
  181710. ** '/1c2/000+000000' // First page in overflow chain
  181711. ** '/1c2/000+000001' // Second page in overflow chain
  181712. ** '/1c2/000+000002' // Third page in overflow chain
  181713. **
  181714. ** If the paths are sorted using the BINARY collation sequence, then
  181715. ** the overflow pages associated with a cell will appear earlier in the
  181716. ** sort-order than its child page:
  181717. **
  181718. ** '/1c2/000/' // Left-most child of 451st child of root
  181719. */
  181720. #define VTAB_SCHEMA \
  181721. "CREATE TABLE xx( " \
  181722. " name TEXT, /* Name of table or index */" \
  181723. " path TEXT, /* Path to page from root */" \
  181724. " pageno INTEGER, /* Page number */" \
  181725. " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \
  181726. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  181727. " payload INTEGER, /* Bytes of payload on this page */" \
  181728. " unused INTEGER, /* Bytes of unused space on this page */" \
  181729. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  181730. " pgoffset INTEGER, /* Offset of page in file */" \
  181731. " pgsize INTEGER, /* Size of the page */" \
  181732. " schema TEXT HIDDEN /* Database schema being analyzed */" \
  181733. ");"
  181734. typedef struct StatTable StatTable;
  181735. typedef struct StatCursor StatCursor;
  181736. typedef struct StatPage StatPage;
  181737. typedef struct StatCell StatCell;
  181738. struct StatCell {
  181739. int nLocal; /* Bytes of local payload */
  181740. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  181741. int nOvfl; /* Entries in aOvfl[] */
  181742. u32 *aOvfl; /* Array of overflow page numbers */
  181743. int nLastOvfl; /* Bytes of payload on final overflow page */
  181744. int iOvfl; /* Iterates through aOvfl[] */
  181745. };
  181746. struct StatPage {
  181747. u32 iPgno;
  181748. DbPage *pPg;
  181749. int iCell;
  181750. char *zPath; /* Path to this page */
  181751. /* Variables populated by statDecodePage(): */
  181752. u8 flags; /* Copy of flags byte */
  181753. int nCell; /* Number of cells on page */
  181754. int nUnused; /* Number of unused bytes on page */
  181755. StatCell *aCell; /* Array of parsed cells */
  181756. u32 iRightChildPg; /* Right-child page number (or 0) */
  181757. int nMxPayload; /* Largest payload of any cell on this page */
  181758. };
  181759. struct StatCursor {
  181760. sqlite3_vtab_cursor base;
  181761. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  181762. int isEof; /* After pStmt has returned SQLITE_DONE */
  181763. int iDb; /* Schema used for this query */
  181764. StatPage aPage[32];
  181765. int iPage; /* Current entry in aPage[] */
  181766. /* Values to return. */
  181767. char *zName; /* Value of 'name' column */
  181768. char *zPath; /* Value of 'path' column */
  181769. u32 iPageno; /* Value of 'pageno' column */
  181770. char *zPagetype; /* Value of 'pagetype' column */
  181771. int nCell; /* Value of 'ncell' column */
  181772. int nPayload; /* Value of 'payload' column */
  181773. int nUnused; /* Value of 'unused' column */
  181774. int nMxPayload; /* Value of 'mx_payload' column */
  181775. i64 iOffset; /* Value of 'pgOffset' column */
  181776. int szPage; /* Value of 'pgSize' column */
  181777. };
  181778. struct StatTable {
  181779. sqlite3_vtab base;
  181780. sqlite3 *db;
  181781. int iDb; /* Index of database to analyze */
  181782. };
  181783. #ifndef get2byte
  181784. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  181785. #endif
  181786. /*
  181787. ** Connect to or create a statvfs virtual table.
  181788. */
  181789. static int statConnect(
  181790. sqlite3 *db,
  181791. void *pAux,
  181792. int argc, const char *const*argv,
  181793. sqlite3_vtab **ppVtab,
  181794. char **pzErr
  181795. ){
  181796. StatTable *pTab = 0;
  181797. int rc = SQLITE_OK;
  181798. int iDb;
  181799. if( argc>=4 ){
  181800. Token nm;
  181801. sqlite3TokenInit(&nm, (char*)argv[3]);
  181802. iDb = sqlite3FindDb(db, &nm);
  181803. if( iDb<0 ){
  181804. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  181805. return SQLITE_ERROR;
  181806. }
  181807. }else{
  181808. iDb = 0;
  181809. }
  181810. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  181811. if( rc==SQLITE_OK ){
  181812. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  181813. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  181814. }
  181815. assert( rc==SQLITE_OK || pTab==0 );
  181816. if( rc==SQLITE_OK ){
  181817. memset(pTab, 0, sizeof(StatTable));
  181818. pTab->db = db;
  181819. pTab->iDb = iDb;
  181820. }
  181821. *ppVtab = (sqlite3_vtab*)pTab;
  181822. return rc;
  181823. }
  181824. /*
  181825. ** Disconnect from or destroy a statvfs virtual table.
  181826. */
  181827. static int statDisconnect(sqlite3_vtab *pVtab){
  181828. sqlite3_free(pVtab);
  181829. return SQLITE_OK;
  181830. }
  181831. /*
  181832. ** There is no "best-index". This virtual table always does a linear
  181833. ** scan. However, a schema=? constraint should cause this table to
  181834. ** operate on a different database schema, so check for it.
  181835. **
  181836. ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
  181837. */
  181838. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  181839. int i;
  181840. /* Look for a valid schema=? constraint. If found, change the idxNum to
  181841. ** 1 and request the value of that constraint be sent to xFilter. And
  181842. ** lower the cost estimate to encourage the constrained version to be
  181843. ** used.
  181844. */
  181845. for(i=0; i<pIdxInfo->nConstraint; i++){
  181846. if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
  181847. if( pIdxInfo->aConstraint[i].usable==0 ) return SQLITE_CONSTRAINT;
  181848. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  181849. pIdxInfo->idxNum = 1;
  181850. pIdxInfo->estimatedCost = 1.0;
  181851. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  181852. pIdxInfo->aConstraintUsage[i].omit = 1;
  181853. break;
  181854. }
  181855. /* Records are always returned in ascending order of (name, path).
  181856. ** If this will satisfy the client, set the orderByConsumed flag so that
  181857. ** SQLite does not do an external sort.
  181858. */
  181859. if( ( pIdxInfo->nOrderBy==1
  181860. && pIdxInfo->aOrderBy[0].iColumn==0
  181861. && pIdxInfo->aOrderBy[0].desc==0
  181862. ) ||
  181863. ( pIdxInfo->nOrderBy==2
  181864. && pIdxInfo->aOrderBy[0].iColumn==0
  181865. && pIdxInfo->aOrderBy[0].desc==0
  181866. && pIdxInfo->aOrderBy[1].iColumn==1
  181867. && pIdxInfo->aOrderBy[1].desc==0
  181868. )
  181869. ){
  181870. pIdxInfo->orderByConsumed = 1;
  181871. }
  181872. return SQLITE_OK;
  181873. }
  181874. /*
  181875. ** Open a new statvfs cursor.
  181876. */
  181877. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  181878. StatTable *pTab = (StatTable *)pVTab;
  181879. StatCursor *pCsr;
  181880. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  181881. if( pCsr==0 ){
  181882. return SQLITE_NOMEM_BKPT;
  181883. }else{
  181884. memset(pCsr, 0, sizeof(StatCursor));
  181885. pCsr->base.pVtab = pVTab;
  181886. pCsr->iDb = pTab->iDb;
  181887. }
  181888. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  181889. return SQLITE_OK;
  181890. }
  181891. static void statClearCells(StatPage *p){
  181892. int i;
  181893. if( p->aCell ){
  181894. for(i=0; i<p->nCell; i++){
  181895. sqlite3_free(p->aCell[i].aOvfl);
  181896. }
  181897. sqlite3_free(p->aCell);
  181898. }
  181899. p->nCell = 0;
  181900. p->aCell = 0;
  181901. }
  181902. static void statClearPage(StatPage *p){
  181903. statClearCells(p);
  181904. sqlite3PagerUnref(p->pPg);
  181905. sqlite3_free(p->zPath);
  181906. memset(p, 0, sizeof(StatPage));
  181907. }
  181908. static void statResetCsr(StatCursor *pCsr){
  181909. int i;
  181910. sqlite3_reset(pCsr->pStmt);
  181911. for(i=0; i<ArraySize(pCsr->aPage); i++){
  181912. statClearPage(&pCsr->aPage[i]);
  181913. }
  181914. pCsr->iPage = 0;
  181915. sqlite3_free(pCsr->zPath);
  181916. pCsr->zPath = 0;
  181917. pCsr->isEof = 0;
  181918. }
  181919. /*
  181920. ** Close a statvfs cursor.
  181921. */
  181922. static int statClose(sqlite3_vtab_cursor *pCursor){
  181923. StatCursor *pCsr = (StatCursor *)pCursor;
  181924. statResetCsr(pCsr);
  181925. sqlite3_finalize(pCsr->pStmt);
  181926. sqlite3_free(pCsr);
  181927. return SQLITE_OK;
  181928. }
  181929. static void getLocalPayload(
  181930. int nUsable, /* Usable bytes per page */
  181931. u8 flags, /* Page flags */
  181932. int nTotal, /* Total record (payload) size */
  181933. int *pnLocal /* OUT: Bytes stored locally */
  181934. ){
  181935. int nLocal;
  181936. int nMinLocal;
  181937. int nMaxLocal;
  181938. if( flags==0x0D ){ /* Table leaf node */
  181939. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  181940. nMaxLocal = nUsable - 35;
  181941. }else{ /* Index interior and leaf nodes */
  181942. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  181943. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  181944. }
  181945. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  181946. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  181947. *pnLocal = nLocal;
  181948. }
  181949. static int statDecodePage(Btree *pBt, StatPage *p){
  181950. int nUnused;
  181951. int iOff;
  181952. int nHdr;
  181953. int isLeaf;
  181954. int szPage;
  181955. u8 *aData = sqlite3PagerGetData(p->pPg);
  181956. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  181957. p->flags = aHdr[0];
  181958. if( p->flags==0x0A || p->flags==0x0D ){
  181959. isLeaf = 1;
  181960. nHdr = 8;
  181961. }else if( p->flags==0x05 || p->flags==0x02 ){
  181962. isLeaf = 0;
  181963. nHdr = 12;
  181964. }else{
  181965. goto statPageIsCorrupt;
  181966. }
  181967. if( p->iPgno==1 ) nHdr += 100;
  181968. p->nCell = get2byte(&aHdr[3]);
  181969. p->nMxPayload = 0;
  181970. szPage = sqlite3BtreeGetPageSize(pBt);
  181971. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  181972. nUnused += (int)aHdr[7];
  181973. iOff = get2byte(&aHdr[1]);
  181974. while( iOff ){
  181975. int iNext;
  181976. if( iOff>=szPage ) goto statPageIsCorrupt;
  181977. nUnused += get2byte(&aData[iOff+2]);
  181978. iNext = get2byte(&aData[iOff]);
  181979. if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt;
  181980. iOff = iNext;
  181981. }
  181982. p->nUnused = nUnused;
  181983. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  181984. if( p->nCell ){
  181985. int i; /* Used to iterate through cells */
  181986. int nUsable; /* Usable bytes per page */
  181987. sqlite3BtreeEnter(pBt);
  181988. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  181989. sqlite3BtreeLeave(pBt);
  181990. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  181991. if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
  181992. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  181993. for(i=0; i<p->nCell; i++){
  181994. StatCell *pCell = &p->aCell[i];
  181995. iOff = get2byte(&aData[nHdr+i*2]);
  181996. if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt;
  181997. if( !isLeaf ){
  181998. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  181999. iOff += 4;
  182000. }
  182001. if( p->flags==0x05 ){
  182002. /* A table interior node. nPayload==0. */
  182003. }else{
  182004. u32 nPayload; /* Bytes of payload total (local+overflow) */
  182005. int nLocal; /* Bytes of payload stored locally */
  182006. iOff += getVarint32(&aData[iOff], nPayload);
  182007. if( p->flags==0x0D ){
  182008. u64 dummy;
  182009. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  182010. }
  182011. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  182012. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  182013. if( nLocal<0 ) goto statPageIsCorrupt;
  182014. pCell->nLocal = nLocal;
  182015. assert( nPayload>=(u32)nLocal );
  182016. assert( nLocal<=(nUsable-35) );
  182017. if( nPayload>(u32)nLocal ){
  182018. int j;
  182019. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  182020. if( iOff+nLocal>nUsable ) goto statPageIsCorrupt;
  182021. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  182022. pCell->nOvfl = nOvfl;
  182023. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  182024. if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
  182025. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  182026. for(j=1; j<nOvfl; j++){
  182027. int rc;
  182028. u32 iPrev = pCell->aOvfl[j-1];
  182029. DbPage *pPg = 0;
  182030. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
  182031. if( rc!=SQLITE_OK ){
  182032. assert( pPg==0 );
  182033. return rc;
  182034. }
  182035. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  182036. sqlite3PagerUnref(pPg);
  182037. }
  182038. }
  182039. }
  182040. }
  182041. }
  182042. return SQLITE_OK;
  182043. statPageIsCorrupt:
  182044. p->flags = 0;
  182045. statClearCells(p);
  182046. return SQLITE_OK;
  182047. }
  182048. /*
  182049. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  182050. ** the current value of pCsr->iPageno.
  182051. */
  182052. static void statSizeAndOffset(StatCursor *pCsr){
  182053. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  182054. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  182055. Pager *pPager = sqlite3BtreePager(pBt);
  182056. sqlite3_file *fd;
  182057. sqlite3_int64 x[2];
  182058. /* The default page size and offset */
  182059. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  182060. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  182061. /* If connected to a ZIPVFS backend, override the page size and
  182062. ** offset with actual values obtained from ZIPVFS.
  182063. */
  182064. fd = sqlite3PagerFile(pPager);
  182065. x[0] = pCsr->iPageno;
  182066. if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  182067. pCsr->iOffset = x[0];
  182068. pCsr->szPage = (int)x[1];
  182069. }
  182070. }
  182071. /*
  182072. ** Move a statvfs cursor to the next entry in the file.
  182073. */
  182074. static int statNext(sqlite3_vtab_cursor *pCursor){
  182075. int rc;
  182076. int nPayload;
  182077. char *z;
  182078. StatCursor *pCsr = (StatCursor *)pCursor;
  182079. StatTable *pTab = (StatTable *)pCursor->pVtab;
  182080. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  182081. Pager *pPager = sqlite3BtreePager(pBt);
  182082. sqlite3_free(pCsr->zPath);
  182083. pCsr->zPath = 0;
  182084. statNextRestart:
  182085. if( pCsr->aPage[0].pPg==0 ){
  182086. rc = sqlite3_step(pCsr->pStmt);
  182087. if( rc==SQLITE_ROW ){
  182088. int nPage;
  182089. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  182090. sqlite3PagerPagecount(pPager, &nPage);
  182091. if( nPage==0 ){
  182092. pCsr->isEof = 1;
  182093. return sqlite3_reset(pCsr->pStmt);
  182094. }
  182095. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
  182096. pCsr->aPage[0].iPgno = iRoot;
  182097. pCsr->aPage[0].iCell = 0;
  182098. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  182099. pCsr->iPage = 0;
  182100. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  182101. }else{
  182102. pCsr->isEof = 1;
  182103. return sqlite3_reset(pCsr->pStmt);
  182104. }
  182105. }else{
  182106. /* Page p itself has already been visited. */
  182107. StatPage *p = &pCsr->aPage[pCsr->iPage];
  182108. while( p->iCell<p->nCell ){
  182109. StatCell *pCell = &p->aCell[p->iCell];
  182110. if( pCell->iOvfl<pCell->nOvfl ){
  182111. int nUsable;
  182112. sqlite3BtreeEnter(pBt);
  182113. nUsable = sqlite3BtreeGetPageSize(pBt) -
  182114. sqlite3BtreeGetReserveNoMutex(pBt);
  182115. sqlite3BtreeLeave(pBt);
  182116. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  182117. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  182118. pCsr->zPagetype = "overflow";
  182119. pCsr->nCell = 0;
  182120. pCsr->nMxPayload = 0;
  182121. pCsr->zPath = z = sqlite3_mprintf(
  182122. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  182123. );
  182124. if( pCell->iOvfl<pCell->nOvfl-1 ){
  182125. pCsr->nUnused = 0;
  182126. pCsr->nPayload = nUsable - 4;
  182127. }else{
  182128. pCsr->nPayload = pCell->nLastOvfl;
  182129. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  182130. }
  182131. pCell->iOvfl++;
  182132. statSizeAndOffset(pCsr);
  182133. return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  182134. }
  182135. if( p->iRightChildPg ) break;
  182136. p->iCell++;
  182137. }
  182138. if( !p->iRightChildPg || p->iCell>p->nCell ){
  182139. statClearPage(p);
  182140. if( pCsr->iPage==0 ) return statNext(pCursor);
  182141. pCsr->iPage--;
  182142. goto statNextRestart; /* Tail recursion */
  182143. }
  182144. pCsr->iPage++;
  182145. if( pCsr->iPage>=ArraySize(pCsr->aPage) ){
  182146. statResetCsr(pCsr);
  182147. return SQLITE_CORRUPT_BKPT;
  182148. }
  182149. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  182150. if( p->iCell==p->nCell ){
  182151. p[1].iPgno = p->iRightChildPg;
  182152. }else{
  182153. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  182154. }
  182155. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
  182156. p[1].iCell = 0;
  182157. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  182158. p->iCell++;
  182159. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  182160. }
  182161. /* Populate the StatCursor fields with the values to be returned
  182162. ** by the xColumn() and xRowid() methods.
  182163. */
  182164. if( rc==SQLITE_OK ){
  182165. int i;
  182166. StatPage *p = &pCsr->aPage[pCsr->iPage];
  182167. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  182168. pCsr->iPageno = p->iPgno;
  182169. rc = statDecodePage(pBt, p);
  182170. if( rc==SQLITE_OK ){
  182171. statSizeAndOffset(pCsr);
  182172. switch( p->flags ){
  182173. case 0x05: /* table internal */
  182174. case 0x02: /* index internal */
  182175. pCsr->zPagetype = "internal";
  182176. break;
  182177. case 0x0D: /* table leaf */
  182178. case 0x0A: /* index leaf */
  182179. pCsr->zPagetype = "leaf";
  182180. break;
  182181. default:
  182182. pCsr->zPagetype = "corrupted";
  182183. break;
  182184. }
  182185. pCsr->nCell = p->nCell;
  182186. pCsr->nUnused = p->nUnused;
  182187. pCsr->nMxPayload = p->nMxPayload;
  182188. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  182189. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  182190. nPayload = 0;
  182191. for(i=0; i<p->nCell; i++){
  182192. nPayload += p->aCell[i].nLocal;
  182193. }
  182194. pCsr->nPayload = nPayload;
  182195. }
  182196. }
  182197. return rc;
  182198. }
  182199. static int statEof(sqlite3_vtab_cursor *pCursor){
  182200. StatCursor *pCsr = (StatCursor *)pCursor;
  182201. return pCsr->isEof;
  182202. }
  182203. static int statFilter(
  182204. sqlite3_vtab_cursor *pCursor,
  182205. int idxNum, const char *idxStr,
  182206. int argc, sqlite3_value **argv
  182207. ){
  182208. StatCursor *pCsr = (StatCursor *)pCursor;
  182209. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  182210. char *zSql;
  182211. int rc = SQLITE_OK;
  182212. if( idxNum==1 ){
  182213. const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
  182214. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  182215. if( pCsr->iDb<0 ){
  182216. sqlite3_free(pCursor->pVtab->zErrMsg);
  182217. pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
  182218. return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
  182219. }
  182220. }else{
  182221. pCsr->iDb = pTab->iDb;
  182222. }
  182223. statResetCsr(pCsr);
  182224. sqlite3_finalize(pCsr->pStmt);
  182225. pCsr->pStmt = 0;
  182226. zSql = sqlite3_mprintf(
  182227. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  182228. " UNION ALL "
  182229. "SELECT name, rootpage, type"
  182230. " FROM \"%w\".sqlite_master WHERE rootpage!=0"
  182231. " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName);
  182232. if( zSql==0 ){
  182233. return SQLITE_NOMEM_BKPT;
  182234. }else{
  182235. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  182236. sqlite3_free(zSql);
  182237. }
  182238. if( rc==SQLITE_OK ){
  182239. rc = statNext(pCursor);
  182240. }
  182241. return rc;
  182242. }
  182243. static int statColumn(
  182244. sqlite3_vtab_cursor *pCursor,
  182245. sqlite3_context *ctx,
  182246. int i
  182247. ){
  182248. StatCursor *pCsr = (StatCursor *)pCursor;
  182249. switch( i ){
  182250. case 0: /* name */
  182251. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  182252. break;
  182253. case 1: /* path */
  182254. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  182255. break;
  182256. case 2: /* pageno */
  182257. sqlite3_result_int64(ctx, pCsr->iPageno);
  182258. break;
  182259. case 3: /* pagetype */
  182260. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  182261. break;
  182262. case 4: /* ncell */
  182263. sqlite3_result_int(ctx, pCsr->nCell);
  182264. break;
  182265. case 5: /* payload */
  182266. sqlite3_result_int(ctx, pCsr->nPayload);
  182267. break;
  182268. case 6: /* unused */
  182269. sqlite3_result_int(ctx, pCsr->nUnused);
  182270. break;
  182271. case 7: /* mx_payload */
  182272. sqlite3_result_int(ctx, pCsr->nMxPayload);
  182273. break;
  182274. case 8: /* pgoffset */
  182275. sqlite3_result_int64(ctx, pCsr->iOffset);
  182276. break;
  182277. case 9: /* pgsize */
  182278. sqlite3_result_int(ctx, pCsr->szPage);
  182279. break;
  182280. default: { /* schema */
  182281. sqlite3 *db = sqlite3_context_db_handle(ctx);
  182282. int iDb = pCsr->iDb;
  182283. sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
  182284. break;
  182285. }
  182286. }
  182287. return SQLITE_OK;
  182288. }
  182289. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  182290. StatCursor *pCsr = (StatCursor *)pCursor;
  182291. *pRowid = pCsr->iPageno;
  182292. return SQLITE_OK;
  182293. }
  182294. /*
  182295. ** Invoke this routine to register the "dbstat" virtual table module
  182296. */
  182297. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  182298. static sqlite3_module dbstat_module = {
  182299. 0, /* iVersion */
  182300. statConnect, /* xCreate */
  182301. statConnect, /* xConnect */
  182302. statBestIndex, /* xBestIndex */
  182303. statDisconnect, /* xDisconnect */
  182304. statDisconnect, /* xDestroy */
  182305. statOpen, /* xOpen - open a cursor */
  182306. statClose, /* xClose - close a cursor */
  182307. statFilter, /* xFilter - configure scan constraints */
  182308. statNext, /* xNext - advance a cursor */
  182309. statEof, /* xEof - check for end of scan */
  182310. statColumn, /* xColumn - read data */
  182311. statRowid, /* xRowid - read data */
  182312. 0, /* xUpdate */
  182313. 0, /* xBegin */
  182314. 0, /* xSync */
  182315. 0, /* xCommit */
  182316. 0, /* xRollback */
  182317. 0, /* xFindMethod */
  182318. 0, /* xRename */
  182319. 0, /* xSavepoint */
  182320. 0, /* xRelease */
  182321. 0, /* xRollbackTo */
  182322. 0 /* xShadowName */
  182323. };
  182324. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  182325. }
  182326. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  182327. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  182328. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  182329. /************** End of dbstat.c **********************************************/
  182330. /************** Begin file dbpage.c ******************************************/
  182331. /*
  182332. ** 2017-10-11
  182333. **
  182334. ** The author disclaims copyright to this source code. In place of
  182335. ** a legal notice, here is a blessing:
  182336. **
  182337. ** May you do good and not evil.
  182338. ** May you find forgiveness for yourself and forgive others.
  182339. ** May you share freely, never taking more than you give.
  182340. **
  182341. ******************************************************************************
  182342. **
  182343. ** This file contains an implementation of the "sqlite_dbpage" virtual table.
  182344. **
  182345. ** The sqlite_dbpage virtual table is used to read or write whole raw
  182346. ** pages of the database file. The pager interface is used so that
  182347. ** uncommitted changes and changes recorded in the WAL file are correctly
  182348. ** retrieved.
  182349. **
  182350. ** Usage example:
  182351. **
  182352. ** SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
  182353. **
  182354. ** This is an eponymous virtual table so it does not need to be created before
  182355. ** use. The optional argument to the sqlite_dbpage() table name is the
  182356. ** schema for the database file that is to be read. The default schema is
  182357. ** "main".
  182358. **
  182359. ** The data field of sqlite_dbpage table can be updated. The new
  182360. ** value must be a BLOB which is the correct page size, otherwise the
  182361. ** update fails. Rows may not be deleted or inserted.
  182362. */
  182363. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  182364. #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
  182365. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  182366. typedef struct DbpageTable DbpageTable;
  182367. typedef struct DbpageCursor DbpageCursor;
  182368. struct DbpageCursor {
  182369. sqlite3_vtab_cursor base; /* Base class. Must be first */
  182370. int pgno; /* Current page number */
  182371. int mxPgno; /* Last page to visit on this scan */
  182372. Pager *pPager; /* Pager being read/written */
  182373. DbPage *pPage1; /* Page 1 of the database */
  182374. int iDb; /* Index of database to analyze */
  182375. int szPage; /* Size of each page in bytes */
  182376. };
  182377. struct DbpageTable {
  182378. sqlite3_vtab base; /* Base class. Must be first */
  182379. sqlite3 *db; /* The database */
  182380. };
  182381. /* Columns */
  182382. #define DBPAGE_COLUMN_PGNO 0
  182383. #define DBPAGE_COLUMN_DATA 1
  182384. #define DBPAGE_COLUMN_SCHEMA 2
  182385. /*
  182386. ** Connect to or create a dbpagevfs virtual table.
  182387. */
  182388. static int dbpageConnect(
  182389. sqlite3 *db,
  182390. void *pAux,
  182391. int argc, const char *const*argv,
  182392. sqlite3_vtab **ppVtab,
  182393. char **pzErr
  182394. ){
  182395. DbpageTable *pTab = 0;
  182396. int rc = SQLITE_OK;
  182397. rc = sqlite3_declare_vtab(db,
  182398. "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
  182399. if( rc==SQLITE_OK ){
  182400. pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
  182401. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  182402. }
  182403. assert( rc==SQLITE_OK || pTab==0 );
  182404. if( rc==SQLITE_OK ){
  182405. memset(pTab, 0, sizeof(DbpageTable));
  182406. pTab->db = db;
  182407. }
  182408. *ppVtab = (sqlite3_vtab*)pTab;
  182409. return rc;
  182410. }
  182411. /*
  182412. ** Disconnect from or destroy a dbpagevfs virtual table.
  182413. */
  182414. static int dbpageDisconnect(sqlite3_vtab *pVtab){
  182415. sqlite3_free(pVtab);
  182416. return SQLITE_OK;
  182417. }
  182418. /*
  182419. ** idxNum:
  182420. **
  182421. ** 0 schema=main, full table scan
  182422. ** 1 schema=main, pgno=?1
  182423. ** 2 schema=?1, full table scan
  182424. ** 3 schema=?1, pgno=?2
  182425. */
  182426. static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  182427. int i;
  182428. int iPlan = 0;
  182429. /* If there is a schema= constraint, it must be honored. Report a
  182430. ** ridiculously large estimated cost if the schema= constraint is
  182431. ** unavailable
  182432. */
  182433. for(i=0; i<pIdxInfo->nConstraint; i++){
  182434. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  182435. if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue;
  182436. if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  182437. if( !p->usable ){
  182438. /* No solution. */
  182439. return SQLITE_CONSTRAINT;
  182440. }
  182441. iPlan = 2;
  182442. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  182443. pIdxInfo->aConstraintUsage[i].omit = 1;
  182444. break;
  182445. }
  182446. /* If we reach this point, it means that either there is no schema=
  182447. ** constraint (in which case we use the "main" schema) or else the
  182448. ** schema constraint was accepted. Lower the estimated cost accordingly
  182449. */
  182450. pIdxInfo->estimatedCost = 1.0e6;
  182451. /* Check for constraints against pgno */
  182452. for(i=0; i<pIdxInfo->nConstraint; i++){
  182453. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  182454. if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  182455. pIdxInfo->estimatedRows = 1;
  182456. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  182457. pIdxInfo->estimatedCost = 1.0;
  182458. pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1;
  182459. pIdxInfo->aConstraintUsage[i].omit = 1;
  182460. iPlan |= 1;
  182461. break;
  182462. }
  182463. }
  182464. pIdxInfo->idxNum = iPlan;
  182465. if( pIdxInfo->nOrderBy>=1
  182466. && pIdxInfo->aOrderBy[0].iColumn<=0
  182467. && pIdxInfo->aOrderBy[0].desc==0
  182468. ){
  182469. pIdxInfo->orderByConsumed = 1;
  182470. }
  182471. return SQLITE_OK;
  182472. }
  182473. /*
  182474. ** Open a new dbpagevfs cursor.
  182475. */
  182476. static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  182477. DbpageCursor *pCsr;
  182478. pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
  182479. if( pCsr==0 ){
  182480. return SQLITE_NOMEM_BKPT;
  182481. }else{
  182482. memset(pCsr, 0, sizeof(DbpageCursor));
  182483. pCsr->base.pVtab = pVTab;
  182484. pCsr->pgno = -1;
  182485. }
  182486. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  182487. return SQLITE_OK;
  182488. }
  182489. /*
  182490. ** Close a dbpagevfs cursor.
  182491. */
  182492. static int dbpageClose(sqlite3_vtab_cursor *pCursor){
  182493. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  182494. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  182495. sqlite3_free(pCsr);
  182496. return SQLITE_OK;
  182497. }
  182498. /*
  182499. ** Move a dbpagevfs cursor to the next entry in the file.
  182500. */
  182501. static int dbpageNext(sqlite3_vtab_cursor *pCursor){
  182502. int rc = SQLITE_OK;
  182503. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  182504. pCsr->pgno++;
  182505. return rc;
  182506. }
  182507. static int dbpageEof(sqlite3_vtab_cursor *pCursor){
  182508. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  182509. return pCsr->pgno > pCsr->mxPgno;
  182510. }
  182511. /*
  182512. ** idxNum:
  182513. **
  182514. ** 0 schema=main, full table scan
  182515. ** 1 schema=main, pgno=?1
  182516. ** 2 schema=?1, full table scan
  182517. ** 3 schema=?1, pgno=?2
  182518. **
  182519. ** idxStr is not used
  182520. */
  182521. static int dbpageFilter(
  182522. sqlite3_vtab_cursor *pCursor,
  182523. int idxNum, const char *idxStr,
  182524. int argc, sqlite3_value **argv
  182525. ){
  182526. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  182527. DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
  182528. int rc;
  182529. sqlite3 *db = pTab->db;
  182530. Btree *pBt;
  182531. /* Default setting is no rows of result */
  182532. pCsr->pgno = 1;
  182533. pCsr->mxPgno = 0;
  182534. if( idxNum & 2 ){
  182535. const char *zSchema;
  182536. assert( argc>=1 );
  182537. zSchema = (const char*)sqlite3_value_text(argv[0]);
  182538. pCsr->iDb = sqlite3FindDbName(db, zSchema);
  182539. if( pCsr->iDb<0 ) return SQLITE_OK;
  182540. }else{
  182541. pCsr->iDb = 0;
  182542. }
  182543. pBt = db->aDb[pCsr->iDb].pBt;
  182544. if( pBt==0 ) return SQLITE_OK;
  182545. pCsr->pPager = sqlite3BtreePager(pBt);
  182546. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  182547. pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
  182548. if( idxNum & 1 ){
  182549. assert( argc>(idxNum>>1) );
  182550. pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]);
  182551. if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){
  182552. pCsr->pgno = 1;
  182553. pCsr->mxPgno = 0;
  182554. }else{
  182555. pCsr->mxPgno = pCsr->pgno;
  182556. }
  182557. }else{
  182558. assert( pCsr->pgno==1 );
  182559. }
  182560. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  182561. rc = sqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0);
  182562. return rc;
  182563. }
  182564. static int dbpageColumn(
  182565. sqlite3_vtab_cursor *pCursor,
  182566. sqlite3_context *ctx,
  182567. int i
  182568. ){
  182569. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  182570. int rc = SQLITE_OK;
  182571. switch( i ){
  182572. case 0: { /* pgno */
  182573. sqlite3_result_int(ctx, pCsr->pgno);
  182574. break;
  182575. }
  182576. case 1: { /* data */
  182577. DbPage *pDbPage = 0;
  182578. rc = sqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
  182579. if( rc==SQLITE_OK ){
  182580. sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pCsr->szPage,
  182581. SQLITE_TRANSIENT);
  182582. }
  182583. sqlite3PagerUnref(pDbPage);
  182584. break;
  182585. }
  182586. default: { /* schema */
  182587. sqlite3 *db = sqlite3_context_db_handle(ctx);
  182588. sqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC);
  182589. break;
  182590. }
  182591. }
  182592. return SQLITE_OK;
  182593. }
  182594. static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  182595. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  182596. *pRowid = pCsr->pgno;
  182597. return SQLITE_OK;
  182598. }
  182599. static int dbpageUpdate(
  182600. sqlite3_vtab *pVtab,
  182601. int argc,
  182602. sqlite3_value **argv,
  182603. sqlite_int64 *pRowid
  182604. ){
  182605. DbpageTable *pTab = (DbpageTable *)pVtab;
  182606. Pgno pgno;
  182607. DbPage *pDbPage = 0;
  182608. int rc = SQLITE_OK;
  182609. char *zErr = 0;
  182610. const char *zSchema;
  182611. int iDb;
  182612. Btree *pBt;
  182613. Pager *pPager;
  182614. int szPage;
  182615. if( pTab->db->flags & SQLITE_Defensive ){
  182616. zErr = "read-only";
  182617. goto update_fail;
  182618. }
  182619. if( argc==1 ){
  182620. zErr = "cannot delete";
  182621. goto update_fail;
  182622. }
  182623. pgno = sqlite3_value_int(argv[0]);
  182624. if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){
  182625. zErr = "cannot insert";
  182626. goto update_fail;
  182627. }
  182628. zSchema = (const char*)sqlite3_value_text(argv[4]);
  182629. iDb = zSchema ? sqlite3FindDbName(pTab->db, zSchema) : -1;
  182630. if( iDb<0 ){
  182631. zErr = "no such schema";
  182632. goto update_fail;
  182633. }
  182634. pBt = pTab->db->aDb[iDb].pBt;
  182635. if( pgno<1 || pBt==0 || pgno>(int)sqlite3BtreeLastPage(pBt) ){
  182636. zErr = "bad page number";
  182637. goto update_fail;
  182638. }
  182639. szPage = sqlite3BtreeGetPageSize(pBt);
  182640. if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
  182641. || sqlite3_value_bytes(argv[3])!=szPage
  182642. ){
  182643. zErr = "bad page value";
  182644. goto update_fail;
  182645. }
  182646. pPager = sqlite3BtreePager(pBt);
  182647. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
  182648. if( rc==SQLITE_OK ){
  182649. rc = sqlite3PagerWrite(pDbPage);
  182650. if( rc==SQLITE_OK ){
  182651. memcpy(sqlite3PagerGetData(pDbPage),
  182652. sqlite3_value_blob(argv[3]),
  182653. szPage);
  182654. }
  182655. }
  182656. sqlite3PagerUnref(pDbPage);
  182657. return rc;
  182658. update_fail:
  182659. sqlite3_free(pVtab->zErrMsg);
  182660. pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
  182661. return SQLITE_ERROR;
  182662. }
  182663. /* Since we do not know in advance which database files will be
  182664. ** written by the sqlite_dbpage virtual table, start a write transaction
  182665. ** on them all.
  182666. */
  182667. static int dbpageBegin(sqlite3_vtab *pVtab){
  182668. DbpageTable *pTab = (DbpageTable *)pVtab;
  182669. sqlite3 *db = pTab->db;
  182670. int i;
  182671. for(i=0; i<db->nDb; i++){
  182672. Btree *pBt = db->aDb[i].pBt;
  182673. if( pBt ) sqlite3BtreeBeginTrans(pBt, 1, 0);
  182674. }
  182675. return SQLITE_OK;
  182676. }
  182677. /*
  182678. ** Invoke this routine to register the "dbpage" virtual table module
  182679. */
  182680. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
  182681. static sqlite3_module dbpage_module = {
  182682. 0, /* iVersion */
  182683. dbpageConnect, /* xCreate */
  182684. dbpageConnect, /* xConnect */
  182685. dbpageBestIndex, /* xBestIndex */
  182686. dbpageDisconnect, /* xDisconnect */
  182687. dbpageDisconnect, /* xDestroy */
  182688. dbpageOpen, /* xOpen - open a cursor */
  182689. dbpageClose, /* xClose - close a cursor */
  182690. dbpageFilter, /* xFilter - configure scan constraints */
  182691. dbpageNext, /* xNext - advance a cursor */
  182692. dbpageEof, /* xEof - check for end of scan */
  182693. dbpageColumn, /* xColumn - read data */
  182694. dbpageRowid, /* xRowid - read data */
  182695. dbpageUpdate, /* xUpdate */
  182696. dbpageBegin, /* xBegin */
  182697. 0, /* xSync */
  182698. 0, /* xCommit */
  182699. 0, /* xRollback */
  182700. 0, /* xFindMethod */
  182701. 0, /* xRename */
  182702. 0, /* xSavepoint */
  182703. 0, /* xRelease */
  182704. 0, /* xRollbackTo */
  182705. 0 /* xShadowName */
  182706. };
  182707. return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
  182708. }
  182709. #elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
  182710. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
  182711. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  182712. /************** End of dbpage.c **********************************************/
  182713. /************** Begin file sqlite3session.c **********************************/
  182714. #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  182715. /* #include "sqlite3session.h" */
  182716. /* #include <assert.h> */
  182717. /* #include <string.h> */
  182718. #ifndef SQLITE_AMALGAMATION
  182719. /* # include "sqliteInt.h" */
  182720. /* # include "vdbeInt.h" */
  182721. #endif
  182722. typedef struct SessionTable SessionTable;
  182723. typedef struct SessionChange SessionChange;
  182724. typedef struct SessionBuffer SessionBuffer;
  182725. typedef struct SessionInput SessionInput;
  182726. /*
  182727. ** Minimum chunk size used by streaming versions of functions.
  182728. */
  182729. #ifndef SESSIONS_STRM_CHUNK_SIZE
  182730. # ifdef SQLITE_TEST
  182731. # define SESSIONS_STRM_CHUNK_SIZE 64
  182732. # else
  182733. # define SESSIONS_STRM_CHUNK_SIZE 1024
  182734. # endif
  182735. #endif
  182736. static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;
  182737. typedef struct SessionHook SessionHook;
  182738. struct SessionHook {
  182739. void *pCtx;
  182740. int (*xOld)(void*,int,sqlite3_value**);
  182741. int (*xNew)(void*,int,sqlite3_value**);
  182742. int (*xCount)(void*);
  182743. int (*xDepth)(void*);
  182744. };
  182745. /*
  182746. ** Session handle structure.
  182747. */
  182748. struct sqlite3_session {
  182749. sqlite3 *db; /* Database handle session is attached to */
  182750. char *zDb; /* Name of database session is attached to */
  182751. int bEnable; /* True if currently recording */
  182752. int bIndirect; /* True if all changes are indirect */
  182753. int bAutoAttach; /* True to auto-attach tables */
  182754. int rc; /* Non-zero if an error has occurred */
  182755. void *pFilterCtx; /* First argument to pass to xTableFilter */
  182756. int (*xTableFilter)(void *pCtx, const char *zTab);
  182757. sqlite3_value *pZeroBlob; /* Value containing X'' */
  182758. sqlite3_session *pNext; /* Next session object on same db. */
  182759. SessionTable *pTable; /* List of attached tables */
  182760. SessionHook hook; /* APIs to grab new and old data with */
  182761. };
  182762. /*
  182763. ** Instances of this structure are used to build strings or binary records.
  182764. */
  182765. struct SessionBuffer {
  182766. u8 *aBuf; /* Pointer to changeset buffer */
  182767. int nBuf; /* Size of buffer aBuf */
  182768. int nAlloc; /* Size of allocation containing aBuf */
  182769. };
  182770. /*
  182771. ** An object of this type is used internally as an abstraction for
  182772. ** input data. Input data may be supplied either as a single large buffer
  182773. ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
  182774. ** sqlite3changeset_start_strm()).
  182775. */
  182776. struct SessionInput {
  182777. int bNoDiscard; /* If true, do not discard in InputBuffer() */
  182778. int iCurrent; /* Offset in aData[] of current change */
  182779. int iNext; /* Offset in aData[] of next change */
  182780. u8 *aData; /* Pointer to buffer containing changeset */
  182781. int nData; /* Number of bytes in aData */
  182782. SessionBuffer buf; /* Current read buffer */
  182783. int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
  182784. void *pIn; /* First argument to xInput */
  182785. int bEof; /* Set to true after xInput finished */
  182786. };
  182787. /*
  182788. ** Structure for changeset iterators.
  182789. */
  182790. struct sqlite3_changeset_iter {
  182791. SessionInput in; /* Input buffer or stream */
  182792. SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
  182793. int bPatchset; /* True if this is a patchset */
  182794. int bInvert; /* True to invert changeset */
  182795. int rc; /* Iterator error code */
  182796. sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
  182797. char *zTab; /* Current table */
  182798. int nCol; /* Number of columns in zTab */
  182799. int op; /* Current operation */
  182800. int bIndirect; /* True if current change was indirect */
  182801. u8 *abPK; /* Primary key array */
  182802. sqlite3_value **apValue; /* old.* and new.* values */
  182803. };
  182804. /*
  182805. ** Each session object maintains a set of the following structures, one
  182806. ** for each table the session object is monitoring. The structures are
  182807. ** stored in a linked list starting at sqlite3_session.pTable.
  182808. **
  182809. ** The keys of the SessionTable.aChange[] hash table are all rows that have
  182810. ** been modified in any way since the session object was attached to the
  182811. ** table.
  182812. **
  182813. ** The data associated with each hash-table entry is a structure containing
  182814. ** a subset of the initial values that the modified row contained at the
  182815. ** start of the session. Or no initial values if the row was inserted.
  182816. */
  182817. struct SessionTable {
  182818. SessionTable *pNext;
  182819. char *zName; /* Local name of table */
  182820. int nCol; /* Number of columns in table zName */
  182821. int bStat1; /* True if this is sqlite_stat1 */
  182822. const char **azCol; /* Column names */
  182823. u8 *abPK; /* Array of primary key flags */
  182824. int nEntry; /* Total number of entries in hash table */
  182825. int nChange; /* Size of apChange[] array */
  182826. SessionChange **apChange; /* Hash table buckets */
  182827. };
  182828. /*
  182829. ** RECORD FORMAT:
  182830. **
  182831. ** The following record format is similar to (but not compatible with) that
  182832. ** used in SQLite database files. This format is used as part of the
  182833. ** change-set binary format, and so must be architecture independent.
  182834. **
  182835. ** Unlike the SQLite database record format, each field is self-contained -
  182836. ** there is no separation of header and data. Each field begins with a
  182837. ** single byte describing its type, as follows:
  182838. **
  182839. ** 0x00: Undefined value.
  182840. ** 0x01: Integer value.
  182841. ** 0x02: Real value.
  182842. ** 0x03: Text value.
  182843. ** 0x04: Blob value.
  182844. ** 0x05: SQL NULL value.
  182845. **
  182846. ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
  182847. ** and so on in sqlite3.h. For undefined and NULL values, the field consists
  182848. ** only of the single type byte. For other types of values, the type byte
  182849. ** is followed by:
  182850. **
  182851. ** Text values:
  182852. ** A varint containing the number of bytes in the value (encoded using
  182853. ** UTF-8). Followed by a buffer containing the UTF-8 representation
  182854. ** of the text value. There is no nul terminator.
  182855. **
  182856. ** Blob values:
  182857. ** A varint containing the number of bytes in the value, followed by
  182858. ** a buffer containing the value itself.
  182859. **
  182860. ** Integer values:
  182861. ** An 8-byte big-endian integer value.
  182862. **
  182863. ** Real values:
  182864. ** An 8-byte big-endian IEEE 754-2008 real value.
  182865. **
  182866. ** Varint values are encoded in the same way as varints in the SQLite
  182867. ** record format.
  182868. **
  182869. ** CHANGESET FORMAT:
  182870. **
  182871. ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
  182872. ** one or more tables. Operations on a single table are grouped together,
  182873. ** but may occur in any order (i.e. deletes, updates and inserts are all
  182874. ** mixed together).
  182875. **
  182876. ** Each group of changes begins with a table header:
  182877. **
  182878. ** 1 byte: Constant 0x54 (capital 'T')
  182879. ** Varint: Number of columns in the table.
  182880. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  182881. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  182882. **
  182883. ** Followed by one or more changes to the table.
  182884. **
  182885. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  182886. ** 1 byte: The "indirect-change" flag.
  182887. ** old.* record: (delete and update only)
  182888. ** new.* record: (insert and update only)
  182889. **
  182890. ** The "old.*" and "new.*" records, if present, are N field records in the
  182891. ** format described above under "RECORD FORMAT", where N is the number of
  182892. ** columns in the table. The i'th field of each record is associated with
  182893. ** the i'th column of the table, counting from left to right in the order
  182894. ** in which columns were declared in the CREATE TABLE statement.
  182895. **
  182896. ** The new.* record that is part of each INSERT change contains the values
  182897. ** that make up the new row. Similarly, the old.* record that is part of each
  182898. ** DELETE change contains the values that made up the row that was deleted
  182899. ** from the database. In the changeset format, the records that are part
  182900. ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
  182901. ** fields.
  182902. **
  182903. ** Within the old.* record associated with an UPDATE change, all fields
  182904. ** associated with table columns that are not PRIMARY KEY columns and are
  182905. ** not modified by the UPDATE change are set to "undefined". Other fields
  182906. ** are set to the values that made up the row before the UPDATE that the
  182907. ** change records took place. Within the new.* record, fields associated
  182908. ** with table columns modified by the UPDATE change contain the new
  182909. ** values. Fields associated with table columns that are not modified
  182910. ** are set to "undefined".
  182911. **
  182912. ** PATCHSET FORMAT:
  182913. **
  182914. ** A patchset is also a collection of changes. It is similar to a changeset,
  182915. ** but leaves undefined those fields that are not useful if no conflict
  182916. ** resolution is required when applying the changeset.
  182917. **
  182918. ** Each group of changes begins with a table header:
  182919. **
  182920. ** 1 byte: Constant 0x50 (capital 'P')
  182921. ** Varint: Number of columns in the table.
  182922. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  182923. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  182924. **
  182925. ** Followed by one or more changes to the table.
  182926. **
  182927. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  182928. ** 1 byte: The "indirect-change" flag.
  182929. ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
  182930. ** full record for INSERT).
  182931. **
  182932. ** As in the changeset format, each field of the single record that is part
  182933. ** of a patchset change is associated with the correspondingly positioned
  182934. ** table column, counting from left to right within the CREATE TABLE
  182935. ** statement.
  182936. **
  182937. ** For a DELETE change, all fields within the record except those associated
  182938. ** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the
  182939. ** values identifying the row to delete.
  182940. **
  182941. ** For an UPDATE change, all fields except those associated with PRIMARY KEY
  182942. ** columns and columns that are modified by the UPDATE are set to "undefined".
  182943. ** PRIMARY KEY fields contain the values identifying the table row to update,
  182944. ** and fields associated with modified columns contain the new column values.
  182945. **
  182946. ** The records associated with INSERT changes are in the same format as for
  182947. ** changesets. It is not possible for a record associated with an INSERT
  182948. ** change to contain a field set to "undefined".
  182949. **
  182950. ** REBASE BLOB FORMAT:
  182951. **
  182952. ** A rebase blob may be output by sqlite3changeset_apply_v2() and its
  182953. ** streaming equivalent for use with the sqlite3_rebaser APIs to rebase
  182954. ** existing changesets. A rebase blob contains one entry for each conflict
  182955. ** resolved using either the OMIT or REPLACE strategies within the apply_v2()
  182956. ** call.
  182957. **
  182958. ** The format used for a rebase blob is very similar to that used for
  182959. ** changesets. All entries related to a single table are grouped together.
  182960. **
  182961. ** Each group of entries begins with a table header in changeset format:
  182962. **
  182963. ** 1 byte: Constant 0x54 (capital 'T')
  182964. ** Varint: Number of columns in the table.
  182965. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  182966. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  182967. **
  182968. ** Followed by one or more entries associated with the table.
  182969. **
  182970. ** 1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09).
  182971. ** 1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT.
  182972. ** record: (in the record format defined above).
  182973. **
  182974. ** In a rebase blob, the first field is set to SQLITE_INSERT if the change
  182975. ** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if
  182976. ** it was a DELETE. The second field is set to 0x01 if the conflict
  182977. ** resolution strategy was REPLACE, or 0x00 if it was OMIT.
  182978. **
  182979. ** If the change that caused the conflict was a DELETE, then the single
  182980. ** record is a copy of the old.* record from the original changeset. If it
  182981. ** was an INSERT, then the single record is a copy of the new.* record. If
  182982. ** the conflicting change was an UPDATE, then the single record is a copy
  182983. ** of the new.* record with the PK fields filled in based on the original
  182984. ** old.* record.
  182985. */
  182986. /*
  182987. ** For each row modified during a session, there exists a single instance of
  182988. ** this structure stored in a SessionTable.aChange[] hash table.
  182989. */
  182990. struct SessionChange {
  182991. int op; /* One of UPDATE, DELETE, INSERT */
  182992. int bIndirect; /* True if this change is "indirect" */
  182993. int nRecord; /* Number of bytes in buffer aRecord[] */
  182994. u8 *aRecord; /* Buffer containing old.* record */
  182995. SessionChange *pNext; /* For hash-table collisions */
  182996. };
  182997. /*
  182998. ** Write a varint with value iVal into the buffer at aBuf. Return the
  182999. ** number of bytes written.
  183000. */
  183001. static int sessionVarintPut(u8 *aBuf, int iVal){
  183002. return putVarint32(aBuf, iVal);
  183003. }
  183004. /*
  183005. ** Return the number of bytes required to store value iVal as a varint.
  183006. */
  183007. static int sessionVarintLen(int iVal){
  183008. return sqlite3VarintLen(iVal);
  183009. }
  183010. /*
  183011. ** Read a varint value from aBuf[] into *piVal. Return the number of
  183012. ** bytes read.
  183013. */
  183014. static int sessionVarintGet(u8 *aBuf, int *piVal){
  183015. return getVarint32(aBuf, *piVal);
  183016. }
  183017. /* Load an unaligned and unsigned 32-bit integer */
  183018. #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  183019. /*
  183020. ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
  183021. ** the value read.
  183022. */
  183023. static sqlite3_int64 sessionGetI64(u8 *aRec){
  183024. u64 x = SESSION_UINT32(aRec);
  183025. u32 y = SESSION_UINT32(aRec+4);
  183026. x = (x<<32) + y;
  183027. return (sqlite3_int64)x;
  183028. }
  183029. /*
  183030. ** Write a 64-bit big-endian integer value to the buffer aBuf[].
  183031. */
  183032. static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
  183033. aBuf[0] = (i>>56) & 0xFF;
  183034. aBuf[1] = (i>>48) & 0xFF;
  183035. aBuf[2] = (i>>40) & 0xFF;
  183036. aBuf[3] = (i>>32) & 0xFF;
  183037. aBuf[4] = (i>>24) & 0xFF;
  183038. aBuf[5] = (i>>16) & 0xFF;
  183039. aBuf[6] = (i>> 8) & 0xFF;
  183040. aBuf[7] = (i>> 0) & 0xFF;
  183041. }
  183042. /*
  183043. ** This function is used to serialize the contents of value pValue (see
  183044. ** comment titled "RECORD FORMAT" above).
  183045. **
  183046. ** If it is non-NULL, the serialized form of the value is written to
  183047. ** buffer aBuf. *pnWrite is set to the number of bytes written before
  183048. ** returning. Or, if aBuf is NULL, the only thing this function does is
  183049. ** set *pnWrite.
  183050. **
  183051. ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
  183052. ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
  183053. ** SQLITE_NOMEM is returned.
  183054. */
  183055. static int sessionSerializeValue(
  183056. u8 *aBuf, /* If non-NULL, write serialized value here */
  183057. sqlite3_value *pValue, /* Value to serialize */
  183058. sqlite3_int64 *pnWrite /* IN/OUT: Increment by bytes written */
  183059. ){
  183060. int nByte; /* Size of serialized value in bytes */
  183061. if( pValue ){
  183062. int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
  183063. eType = sqlite3_value_type(pValue);
  183064. if( aBuf ) aBuf[0] = eType;
  183065. switch( eType ){
  183066. case SQLITE_NULL:
  183067. nByte = 1;
  183068. break;
  183069. case SQLITE_INTEGER:
  183070. case SQLITE_FLOAT:
  183071. if( aBuf ){
  183072. /* TODO: SQLite does something special to deal with mixed-endian
  183073. ** floating point values (e.g. ARM7). This code probably should
  183074. ** too. */
  183075. u64 i;
  183076. if( eType==SQLITE_INTEGER ){
  183077. i = (u64)sqlite3_value_int64(pValue);
  183078. }else{
  183079. double r;
  183080. assert( sizeof(double)==8 && sizeof(u64)==8 );
  183081. r = sqlite3_value_double(pValue);
  183082. memcpy(&i, &r, 8);
  183083. }
  183084. sessionPutI64(&aBuf[1], i);
  183085. }
  183086. nByte = 9;
  183087. break;
  183088. default: {
  183089. u8 *z;
  183090. int n;
  183091. int nVarint;
  183092. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  183093. if( eType==SQLITE_TEXT ){
  183094. z = (u8 *)sqlite3_value_text(pValue);
  183095. }else{
  183096. z = (u8 *)sqlite3_value_blob(pValue);
  183097. }
  183098. n = sqlite3_value_bytes(pValue);
  183099. if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  183100. nVarint = sessionVarintLen(n);
  183101. if( aBuf ){
  183102. sessionVarintPut(&aBuf[1], n);
  183103. if( n ) memcpy(&aBuf[nVarint + 1], z, n);
  183104. }
  183105. nByte = 1 + nVarint + n;
  183106. break;
  183107. }
  183108. }
  183109. }else{
  183110. nByte = 1;
  183111. if( aBuf ) aBuf[0] = '\0';
  183112. }
  183113. if( pnWrite ) *pnWrite += nByte;
  183114. return SQLITE_OK;
  183115. }
  183116. /*
  183117. ** This macro is used to calculate hash key values for data structures. In
  183118. ** order to use this macro, the entire data structure must be represented
  183119. ** as a series of unsigned integers. In order to calculate a hash-key value
  183120. ** for a data structure represented as three such integers, the macro may
  183121. ** then be used as follows:
  183122. **
  183123. ** int hash_key_value;
  183124. ** hash_key_value = HASH_APPEND(0, <value 1>);
  183125. ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
  183126. ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
  183127. **
  183128. ** In practice, the data structures this macro is used for are the primary
  183129. ** key values of modified rows.
  183130. */
  183131. #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
  183132. /*
  183133. ** Append the hash of the 64-bit integer passed as the second argument to the
  183134. ** hash-key value passed as the first. Return the new hash-key value.
  183135. */
  183136. static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
  183137. h = HASH_APPEND(h, i & 0xFFFFFFFF);
  183138. return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
  183139. }
  183140. /*
  183141. ** Append the hash of the blob passed via the second and third arguments to
  183142. ** the hash-key value passed as the first. Return the new hash-key value.
  183143. */
  183144. static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
  183145. int i;
  183146. for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
  183147. return h;
  183148. }
  183149. /*
  183150. ** Append the hash of the data type passed as the second argument to the
  183151. ** hash-key value passed as the first. Return the new hash-key value.
  183152. */
  183153. static unsigned int sessionHashAppendType(unsigned int h, int eType){
  183154. return HASH_APPEND(h, eType);
  183155. }
  183156. /*
  183157. ** This function may only be called from within a pre-update callback.
  183158. ** It calculates a hash based on the primary key values of the old.* or
  183159. ** new.* row currently available and, assuming no error occurs, writes it to
  183160. ** *piHash before returning. If the primary key contains one or more NULL
  183161. ** values, *pbNullPK is set to true before returning.
  183162. **
  183163. ** If an error occurs, an SQLite error code is returned and the final values
  183164. ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
  183165. ** and the output variables are set as described above.
  183166. */
  183167. static int sessionPreupdateHash(
  183168. sqlite3_session *pSession, /* Session object that owns pTab */
  183169. SessionTable *pTab, /* Session table handle */
  183170. int bNew, /* True to hash the new.* PK */
  183171. int *piHash, /* OUT: Hash value */
  183172. int *pbNullPK /* OUT: True if there are NULL values in PK */
  183173. ){
  183174. unsigned int h = 0; /* Hash value to return */
  183175. int i; /* Used to iterate through columns */
  183176. assert( *pbNullPK==0 );
  183177. assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
  183178. for(i=0; i<pTab->nCol; i++){
  183179. if( pTab->abPK[i] ){
  183180. int rc;
  183181. int eType;
  183182. sqlite3_value *pVal;
  183183. if( bNew ){
  183184. rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
  183185. }else{
  183186. rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
  183187. }
  183188. if( rc!=SQLITE_OK ) return rc;
  183189. eType = sqlite3_value_type(pVal);
  183190. h = sessionHashAppendType(h, eType);
  183191. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  183192. i64 iVal;
  183193. if( eType==SQLITE_INTEGER ){
  183194. iVal = sqlite3_value_int64(pVal);
  183195. }else{
  183196. double rVal = sqlite3_value_double(pVal);
  183197. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  183198. memcpy(&iVal, &rVal, 8);
  183199. }
  183200. h = sessionHashAppendI64(h, iVal);
  183201. }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  183202. const u8 *z;
  183203. int n;
  183204. if( eType==SQLITE_TEXT ){
  183205. z = (const u8 *)sqlite3_value_text(pVal);
  183206. }else{
  183207. z = (const u8 *)sqlite3_value_blob(pVal);
  183208. }
  183209. n = sqlite3_value_bytes(pVal);
  183210. if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  183211. h = sessionHashAppendBlob(h, n, z);
  183212. }else{
  183213. assert( eType==SQLITE_NULL );
  183214. assert( pTab->bStat1==0 || i!=1 );
  183215. *pbNullPK = 1;
  183216. }
  183217. }
  183218. }
  183219. *piHash = (h % pTab->nChange);
  183220. return SQLITE_OK;
  183221. }
  183222. /*
  183223. ** The buffer that the argument points to contains a serialized SQL value.
  183224. ** Return the number of bytes of space occupied by the value (including
  183225. ** the type byte).
  183226. */
  183227. static int sessionSerialLen(u8 *a){
  183228. int e = *a;
  183229. int n;
  183230. if( e==0 || e==0xFF ) return 1;
  183231. if( e==SQLITE_NULL ) return 1;
  183232. if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
  183233. return sessionVarintGet(&a[1], &n) + 1 + n;
  183234. }
  183235. /*
  183236. ** Based on the primary key values stored in change aRecord, calculate a
  183237. ** hash key. Assume the has table has nBucket buckets. The hash keys
  183238. ** calculated by this function are compatible with those calculated by
  183239. ** sessionPreupdateHash().
  183240. **
  183241. ** The bPkOnly argument is non-zero if the record at aRecord[] is from
  183242. ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
  183243. */
  183244. static unsigned int sessionChangeHash(
  183245. SessionTable *pTab, /* Table handle */
  183246. int bPkOnly, /* Record consists of PK fields only */
  183247. u8 *aRecord, /* Change record */
  183248. int nBucket /* Assume this many buckets in hash table */
  183249. ){
  183250. unsigned int h = 0; /* Value to return */
  183251. int i; /* Used to iterate through columns */
  183252. u8 *a = aRecord; /* Used to iterate through change record */
  183253. for(i=0; i<pTab->nCol; i++){
  183254. int eType = *a;
  183255. int isPK = pTab->abPK[i];
  183256. if( bPkOnly && isPK==0 ) continue;
  183257. /* It is not possible for eType to be SQLITE_NULL here. The session
  183258. ** module does not record changes for rows with NULL values stored in
  183259. ** primary key columns. */
  183260. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  183261. || eType==SQLITE_TEXT || eType==SQLITE_BLOB
  183262. || eType==SQLITE_NULL || eType==0
  183263. );
  183264. assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
  183265. if( isPK ){
  183266. a++;
  183267. h = sessionHashAppendType(h, eType);
  183268. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  183269. h = sessionHashAppendI64(h, sessionGetI64(a));
  183270. a += 8;
  183271. }else{
  183272. int n;
  183273. a += sessionVarintGet(a, &n);
  183274. h = sessionHashAppendBlob(h, n, a);
  183275. a += n;
  183276. }
  183277. }else{
  183278. a += sessionSerialLen(a);
  183279. }
  183280. }
  183281. return (h % nBucket);
  183282. }
  183283. /*
  183284. ** Arguments aLeft and aRight are pointers to change records for table pTab.
  183285. ** This function returns true if the two records apply to the same row (i.e.
  183286. ** have the same values stored in the primary key columns), or false
  183287. ** otherwise.
  183288. */
  183289. static int sessionChangeEqual(
  183290. SessionTable *pTab, /* Table used for PK definition */
  183291. int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
  183292. u8 *aLeft, /* Change record */
  183293. int bRightPkOnly, /* True if aRight[] contains PK fields only */
  183294. u8 *aRight /* Change record */
  183295. ){
  183296. u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
  183297. u8 *a2 = aRight; /* Cursor to iterate through aRight */
  183298. int iCol; /* Used to iterate through table columns */
  183299. for(iCol=0; iCol<pTab->nCol; iCol++){
  183300. if( pTab->abPK[iCol] ){
  183301. int n1 = sessionSerialLen(a1);
  183302. int n2 = sessionSerialLen(a2);
  183303. if( n1!=n2 || memcmp(a1, a2, n1) ){
  183304. return 0;
  183305. }
  183306. a1 += n1;
  183307. a2 += n2;
  183308. }else{
  183309. if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
  183310. if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
  183311. }
  183312. }
  183313. return 1;
  183314. }
  183315. /*
  183316. ** Arguments aLeft and aRight both point to buffers containing change
  183317. ** records with nCol columns. This function "merges" the two records into
  183318. ** a single records which is written to the buffer at *paOut. *paOut is
  183319. ** then set to point to one byte after the last byte written before
  183320. ** returning.
  183321. **
  183322. ** The merging of records is done as follows: For each column, if the
  183323. ** aRight record contains a value for the column, copy the value from
  183324. ** their. Otherwise, if aLeft contains a value, copy it. If neither
  183325. ** record contains a value for a given column, then neither does the
  183326. ** output record.
  183327. */
  183328. static void sessionMergeRecord(
  183329. u8 **paOut,
  183330. int nCol,
  183331. u8 *aLeft,
  183332. u8 *aRight
  183333. ){
  183334. u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
  183335. u8 *a2 = aRight; /* Cursor used to iterate through aRight */
  183336. u8 *aOut = *paOut; /* Output cursor */
  183337. int iCol; /* Used to iterate from 0 to nCol */
  183338. for(iCol=0; iCol<nCol; iCol++){
  183339. int n1 = sessionSerialLen(a1);
  183340. int n2 = sessionSerialLen(a2);
  183341. if( *a2 ){
  183342. memcpy(aOut, a2, n2);
  183343. aOut += n2;
  183344. }else{
  183345. memcpy(aOut, a1, n1);
  183346. aOut += n1;
  183347. }
  183348. a1 += n1;
  183349. a2 += n2;
  183350. }
  183351. *paOut = aOut;
  183352. }
  183353. /*
  183354. ** This is a helper function used by sessionMergeUpdate().
  183355. **
  183356. ** When this function is called, both *paOne and *paTwo point to a value
  183357. ** within a change record. Before it returns, both have been advanced so
  183358. ** as to point to the next value in the record.
  183359. **
  183360. ** If, when this function is called, *paTwo points to a valid value (i.e.
  183361. ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
  183362. ** pointer is returned and *pnVal is set to the number of bytes in the
  183363. ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
  183364. ** set to the number of bytes in the value at *paOne. If *paOne points
  183365. ** to the "no value" placeholder, *pnVal is set to 1. In other words:
  183366. **
  183367. ** if( *paTwo is valid ) return *paTwo;
  183368. ** return *paOne;
  183369. **
  183370. */
  183371. static u8 *sessionMergeValue(
  183372. u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
  183373. u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
  183374. int *pnVal /* OUT: Bytes in returned value */
  183375. ){
  183376. u8 *a1 = *paOne;
  183377. u8 *a2 = *paTwo;
  183378. u8 *pRet = 0;
  183379. int n1;
  183380. assert( a1 );
  183381. if( a2 ){
  183382. int n2 = sessionSerialLen(a2);
  183383. if( *a2 ){
  183384. *pnVal = n2;
  183385. pRet = a2;
  183386. }
  183387. *paTwo = &a2[n2];
  183388. }
  183389. n1 = sessionSerialLen(a1);
  183390. if( pRet==0 ){
  183391. *pnVal = n1;
  183392. pRet = a1;
  183393. }
  183394. *paOne = &a1[n1];
  183395. return pRet;
  183396. }
  183397. /*
  183398. ** This function is used by changeset_concat() to merge two UPDATE changes
  183399. ** on the same row.
  183400. */
  183401. static int sessionMergeUpdate(
  183402. u8 **paOut, /* IN/OUT: Pointer to output buffer */
  183403. SessionTable *pTab, /* Table change pertains to */
  183404. int bPatchset, /* True if records are patchset records */
  183405. u8 *aOldRecord1, /* old.* record for first change */
  183406. u8 *aOldRecord2, /* old.* record for second change */
  183407. u8 *aNewRecord1, /* new.* record for first change */
  183408. u8 *aNewRecord2 /* new.* record for second change */
  183409. ){
  183410. u8 *aOld1 = aOldRecord1;
  183411. u8 *aOld2 = aOldRecord2;
  183412. u8 *aNew1 = aNewRecord1;
  183413. u8 *aNew2 = aNewRecord2;
  183414. u8 *aOut = *paOut;
  183415. int i;
  183416. if( bPatchset==0 ){
  183417. int bRequired = 0;
  183418. assert( aOldRecord1 && aNewRecord1 );
  183419. /* Write the old.* vector first. */
  183420. for(i=0; i<pTab->nCol; i++){
  183421. int nOld;
  183422. u8 *aOld;
  183423. int nNew;
  183424. u8 *aNew;
  183425. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  183426. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  183427. if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
  183428. if( pTab->abPK[i]==0 ) bRequired = 1;
  183429. memcpy(aOut, aOld, nOld);
  183430. aOut += nOld;
  183431. }else{
  183432. *(aOut++) = '\0';
  183433. }
  183434. }
  183435. if( !bRequired ) return 0;
  183436. }
  183437. /* Write the new.* vector */
  183438. aOld1 = aOldRecord1;
  183439. aOld2 = aOldRecord2;
  183440. aNew1 = aNewRecord1;
  183441. aNew2 = aNewRecord2;
  183442. for(i=0; i<pTab->nCol; i++){
  183443. int nOld;
  183444. u8 *aOld;
  183445. int nNew;
  183446. u8 *aNew;
  183447. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  183448. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  183449. if( bPatchset==0
  183450. && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
  183451. ){
  183452. *(aOut++) = '\0';
  183453. }else{
  183454. memcpy(aOut, aNew, nNew);
  183455. aOut += nNew;
  183456. }
  183457. }
  183458. *paOut = aOut;
  183459. return 1;
  183460. }
  183461. /*
  183462. ** This function is only called from within a pre-update-hook callback.
  183463. ** It determines if the current pre-update-hook change affects the same row
  183464. ** as the change stored in argument pChange. If so, it returns true. Otherwise
  183465. ** if the pre-update-hook does not affect the same row as pChange, it returns
  183466. ** false.
  183467. */
  183468. static int sessionPreupdateEqual(
  183469. sqlite3_session *pSession, /* Session object that owns SessionTable */
  183470. SessionTable *pTab, /* Table associated with change */
  183471. SessionChange *pChange, /* Change to compare to */
  183472. int op /* Current pre-update operation */
  183473. ){
  183474. int iCol; /* Used to iterate through columns */
  183475. u8 *a = pChange->aRecord; /* Cursor used to scan change record */
  183476. assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  183477. for(iCol=0; iCol<pTab->nCol; iCol++){
  183478. if( !pTab->abPK[iCol] ){
  183479. a += sessionSerialLen(a);
  183480. }else{
  183481. sqlite3_value *pVal; /* Value returned by preupdate_new/old */
  183482. int rc; /* Error code from preupdate_new/old */
  183483. int eType = *a++; /* Type of value from change record */
  183484. /* The following calls to preupdate_new() and preupdate_old() can not
  183485. ** fail. This is because they cache their return values, and by the
  183486. ** time control flows to here they have already been called once from
  183487. ** within sessionPreupdateHash(). The first two asserts below verify
  183488. ** this (that the method has already been called). */
  183489. if( op==SQLITE_INSERT ){
  183490. /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
  183491. rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
  183492. }else{
  183493. /* assert( db->pPreUpdate->pUnpacked ); */
  183494. rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
  183495. }
  183496. assert( rc==SQLITE_OK );
  183497. if( sqlite3_value_type(pVal)!=eType ) return 0;
  183498. /* A SessionChange object never has a NULL value in a PK column */
  183499. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  183500. || eType==SQLITE_BLOB || eType==SQLITE_TEXT
  183501. );
  183502. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  183503. i64 iVal = sessionGetI64(a);
  183504. a += 8;
  183505. if( eType==SQLITE_INTEGER ){
  183506. if( sqlite3_value_int64(pVal)!=iVal ) return 0;
  183507. }else{
  183508. double rVal;
  183509. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  183510. memcpy(&rVal, &iVal, 8);
  183511. if( sqlite3_value_double(pVal)!=rVal ) return 0;
  183512. }
  183513. }else{
  183514. int n;
  183515. const u8 *z;
  183516. a += sessionVarintGet(a, &n);
  183517. if( sqlite3_value_bytes(pVal)!=n ) return 0;
  183518. if( eType==SQLITE_TEXT ){
  183519. z = sqlite3_value_text(pVal);
  183520. }else{
  183521. z = sqlite3_value_blob(pVal);
  183522. }
  183523. if( n>0 && memcmp(a, z, n) ) return 0;
  183524. a += n;
  183525. }
  183526. }
  183527. }
  183528. return 1;
  183529. }
  183530. /*
  183531. ** If required, grow the hash table used to store changes on table pTab
  183532. ** (part of the session pSession). If a fatal OOM error occurs, set the
  183533. ** session object to failed and return SQLITE_ERROR. Otherwise, return
  183534. ** SQLITE_OK.
  183535. **
  183536. ** It is possible that a non-fatal OOM error occurs in this function. In
  183537. ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
  183538. ** Growing the hash table in this case is a performance optimization only,
  183539. ** it is not required for correct operation.
  183540. */
  183541. static int sessionGrowHash(int bPatchset, SessionTable *pTab){
  183542. if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
  183543. int i;
  183544. SessionChange **apNew;
  183545. sqlite3_int64 nNew = 2*(sqlite3_int64)(pTab->nChange ? pTab->nChange : 128);
  183546. apNew = (SessionChange **)sqlite3_malloc64(sizeof(SessionChange *) * nNew);
  183547. if( apNew==0 ){
  183548. if( pTab->nChange==0 ){
  183549. return SQLITE_ERROR;
  183550. }
  183551. return SQLITE_OK;
  183552. }
  183553. memset(apNew, 0, sizeof(SessionChange *) * nNew);
  183554. for(i=0; i<pTab->nChange; i++){
  183555. SessionChange *p;
  183556. SessionChange *pNext;
  183557. for(p=pTab->apChange[i]; p; p=pNext){
  183558. int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
  183559. int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
  183560. pNext = p->pNext;
  183561. p->pNext = apNew[iHash];
  183562. apNew[iHash] = p;
  183563. }
  183564. }
  183565. sqlite3_free(pTab->apChange);
  183566. pTab->nChange = nNew;
  183567. pTab->apChange = apNew;
  183568. }
  183569. return SQLITE_OK;
  183570. }
  183571. /*
  183572. ** This function queries the database for the names of the columns of table
  183573. ** zThis, in schema zDb.
  183574. **
  183575. ** Otherwise, if they are not NULL, variable *pnCol is set to the number
  183576. ** of columns in the database table and variable *pzTab is set to point to a
  183577. ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
  183578. ** point to an array of pointers to column names. And *pabPK (again, if not
  183579. ** NULL) is set to point to an array of booleans - true if the corresponding
  183580. ** column is part of the primary key.
  183581. **
  183582. ** For example, if the table is declared as:
  183583. **
  183584. ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
  183585. **
  183586. ** Then the four output variables are populated as follows:
  183587. **
  183588. ** *pnCol = 4
  183589. ** *pzTab = "tbl1"
  183590. ** *pazCol = {"w", "x", "y", "z"}
  183591. ** *pabPK = {1, 0, 0, 1}
  183592. **
  183593. ** All returned buffers are part of the same single allocation, which must
  183594. ** be freed using sqlite3_free() by the caller
  183595. */
  183596. static int sessionTableInfo(
  183597. sqlite3 *db, /* Database connection */
  183598. const char *zDb, /* Name of attached database (e.g. "main") */
  183599. const char *zThis, /* Table name */
  183600. int *pnCol, /* OUT: number of columns */
  183601. const char **pzTab, /* OUT: Copy of zThis */
  183602. const char ***pazCol, /* OUT: Array of column names for table */
  183603. u8 **pabPK /* OUT: Array of booleans - true for PK col */
  183604. ){
  183605. char *zPragma;
  183606. sqlite3_stmt *pStmt;
  183607. int rc;
  183608. sqlite3_int64 nByte;
  183609. int nDbCol = 0;
  183610. int nThis;
  183611. int i;
  183612. u8 *pAlloc = 0;
  183613. char **azCol = 0;
  183614. u8 *abPK = 0;
  183615. assert( pazCol && pabPK );
  183616. nThis = sqlite3Strlen30(zThis);
  183617. if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
  183618. rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
  183619. if( rc==SQLITE_OK ){
  183620. /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
  183621. zPragma = sqlite3_mprintf(
  183622. "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL "
  183623. "SELECT 1, 'idx', '', 0, '', 2 UNION ALL "
  183624. "SELECT 2, 'stat', '', 0, '', 0"
  183625. );
  183626. }else if( rc==SQLITE_ERROR ){
  183627. zPragma = sqlite3_mprintf("");
  183628. }else{
  183629. return rc;
  183630. }
  183631. }else{
  183632. zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
  183633. }
  183634. if( !zPragma ) return SQLITE_NOMEM;
  183635. rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
  183636. sqlite3_free(zPragma);
  183637. if( rc!=SQLITE_OK ) return rc;
  183638. nByte = nThis + 1;
  183639. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  183640. nByte += sqlite3_column_bytes(pStmt, 1);
  183641. nDbCol++;
  183642. }
  183643. rc = sqlite3_reset(pStmt);
  183644. if( rc==SQLITE_OK ){
  183645. nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
  183646. pAlloc = sqlite3_malloc64(nByte);
  183647. if( pAlloc==0 ){
  183648. rc = SQLITE_NOMEM;
  183649. }
  183650. }
  183651. if( rc==SQLITE_OK ){
  183652. azCol = (char **)pAlloc;
  183653. pAlloc = (u8 *)&azCol[nDbCol];
  183654. abPK = (u8 *)pAlloc;
  183655. pAlloc = &abPK[nDbCol];
  183656. if( pzTab ){
  183657. memcpy(pAlloc, zThis, nThis+1);
  183658. *pzTab = (char *)pAlloc;
  183659. pAlloc += nThis+1;
  183660. }
  183661. i = 0;
  183662. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  183663. int nName = sqlite3_column_bytes(pStmt, 1);
  183664. const unsigned char *zName = sqlite3_column_text(pStmt, 1);
  183665. if( zName==0 ) break;
  183666. memcpy(pAlloc, zName, nName+1);
  183667. azCol[i] = (char *)pAlloc;
  183668. pAlloc += nName+1;
  183669. abPK[i] = sqlite3_column_int(pStmt, 5);
  183670. i++;
  183671. }
  183672. rc = sqlite3_reset(pStmt);
  183673. }
  183674. /* If successful, populate the output variables. Otherwise, zero them and
  183675. ** free any allocation made. An error code will be returned in this case.
  183676. */
  183677. if( rc==SQLITE_OK ){
  183678. *pazCol = (const char **)azCol;
  183679. *pabPK = abPK;
  183680. *pnCol = nDbCol;
  183681. }else{
  183682. *pazCol = 0;
  183683. *pabPK = 0;
  183684. *pnCol = 0;
  183685. if( pzTab ) *pzTab = 0;
  183686. sqlite3_free(azCol);
  183687. }
  183688. sqlite3_finalize(pStmt);
  183689. return rc;
  183690. }
  183691. /*
  183692. ** This function is only called from within a pre-update handler for a
  183693. ** write to table pTab, part of session pSession. If this is the first
  183694. ** write to this table, initalize the SessionTable.nCol, azCol[] and
  183695. ** abPK[] arrays accordingly.
  183696. **
  183697. ** If an error occurs, an error code is stored in sqlite3_session.rc and
  183698. ** non-zero returned. Or, if no error occurs but the table has no primary
  183699. ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
  183700. ** indicate that updates on this table should be ignored. SessionTable.abPK
  183701. ** is set to NULL in this case.
  183702. */
  183703. static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  183704. if( pTab->nCol==0 ){
  183705. u8 *abPK;
  183706. assert( pTab->azCol==0 || pTab->abPK==0 );
  183707. pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
  183708. pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
  183709. );
  183710. if( pSession->rc==SQLITE_OK ){
  183711. int i;
  183712. for(i=0; i<pTab->nCol; i++){
  183713. if( abPK[i] ){
  183714. pTab->abPK = abPK;
  183715. break;
  183716. }
  183717. }
  183718. if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
  183719. pTab->bStat1 = 1;
  183720. }
  183721. }
  183722. }
  183723. return (pSession->rc || pTab->abPK==0);
  183724. }
  183725. /*
  183726. ** Versions of the four methods in object SessionHook for use with the
  183727. ** sqlite_stat1 table. The purpose of this is to substitute a zero-length
  183728. ** blob each time a NULL value is read from the "idx" column of the
  183729. ** sqlite_stat1 table.
  183730. */
  183731. typedef struct SessionStat1Ctx SessionStat1Ctx;
  183732. struct SessionStat1Ctx {
  183733. SessionHook hook;
  183734. sqlite3_session *pSession;
  183735. };
  183736. static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
  183737. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  183738. sqlite3_value *pVal = 0;
  183739. int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
  183740. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  183741. pVal = p->pSession->pZeroBlob;
  183742. }
  183743. *ppVal = pVal;
  183744. return rc;
  183745. }
  183746. static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
  183747. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  183748. sqlite3_value *pVal = 0;
  183749. int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
  183750. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  183751. pVal = p->pSession->pZeroBlob;
  183752. }
  183753. *ppVal = pVal;
  183754. return rc;
  183755. }
  183756. static int sessionStat1Count(void *pCtx){
  183757. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  183758. return p->hook.xCount(p->hook.pCtx);
  183759. }
  183760. static int sessionStat1Depth(void *pCtx){
  183761. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  183762. return p->hook.xDepth(p->hook.pCtx);
  183763. }
  183764. /*
  183765. ** This function is only called from with a pre-update-hook reporting a
  183766. ** change on table pTab (attached to session pSession). The type of change
  183767. ** (UPDATE, INSERT, DELETE) is specified by the first argument.
  183768. **
  183769. ** Unless one is already present or an error occurs, an entry is added
  183770. ** to the changed-rows hash table associated with table pTab.
  183771. */
  183772. static void sessionPreupdateOneChange(
  183773. int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
  183774. sqlite3_session *pSession, /* Session object pTab is attached to */
  183775. SessionTable *pTab /* Table that change applies to */
  183776. ){
  183777. int iHash;
  183778. int bNull = 0;
  183779. int rc = SQLITE_OK;
  183780. SessionStat1Ctx stat1 = {{0,0,0,0,0},0};
  183781. if( pSession->rc ) return;
  183782. /* Load table details if required */
  183783. if( sessionInitTable(pSession, pTab) ) return;
  183784. /* Check the number of columns in this xPreUpdate call matches the
  183785. ** number of columns in the table. */
  183786. if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
  183787. pSession->rc = SQLITE_SCHEMA;
  183788. return;
  183789. }
  183790. /* Grow the hash table if required */
  183791. if( sessionGrowHash(0, pTab) ){
  183792. pSession->rc = SQLITE_NOMEM;
  183793. return;
  183794. }
  183795. if( pTab->bStat1 ){
  183796. stat1.hook = pSession->hook;
  183797. stat1.pSession = pSession;
  183798. pSession->hook.pCtx = (void*)&stat1;
  183799. pSession->hook.xNew = sessionStat1New;
  183800. pSession->hook.xOld = sessionStat1Old;
  183801. pSession->hook.xCount = sessionStat1Count;
  183802. pSession->hook.xDepth = sessionStat1Depth;
  183803. if( pSession->pZeroBlob==0 ){
  183804. sqlite3_value *p = sqlite3ValueNew(0);
  183805. if( p==0 ){
  183806. rc = SQLITE_NOMEM;
  183807. goto error_out;
  183808. }
  183809. sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
  183810. pSession->pZeroBlob = p;
  183811. }
  183812. }
  183813. /* Calculate the hash-key for this change. If the primary key of the row
  183814. ** includes a NULL value, exit early. Such changes are ignored by the
  183815. ** session module. */
  183816. rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
  183817. if( rc!=SQLITE_OK ) goto error_out;
  183818. if( bNull==0 ){
  183819. /* Search the hash table for an existing record for this row. */
  183820. SessionChange *pC;
  183821. for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
  183822. if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
  183823. }
  183824. if( pC==0 ){
  183825. /* Create a new change object containing all the old values (if
  183826. ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
  183827. ** values (if this is an INSERT). */
  183828. SessionChange *pChange; /* New change object */
  183829. sqlite3_int64 nByte; /* Number of bytes to allocate */
  183830. int i; /* Used to iterate through columns */
  183831. assert( rc==SQLITE_OK );
  183832. pTab->nEntry++;
  183833. /* Figure out how large an allocation is required */
  183834. nByte = sizeof(SessionChange);
  183835. for(i=0; i<pTab->nCol; i++){
  183836. sqlite3_value *p = 0;
  183837. if( op!=SQLITE_INSERT ){
  183838. TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  183839. assert( trc==SQLITE_OK );
  183840. }else if( pTab->abPK[i] ){
  183841. TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  183842. assert( trc==SQLITE_OK );
  183843. }
  183844. /* This may fail if SQLite value p contains a utf-16 string that must
  183845. ** be converted to utf-8 and an OOM error occurs while doing so. */
  183846. rc = sessionSerializeValue(0, p, &nByte);
  183847. if( rc!=SQLITE_OK ) goto error_out;
  183848. }
  183849. /* Allocate the change object */
  183850. pChange = (SessionChange *)sqlite3_malloc64(nByte);
  183851. if( !pChange ){
  183852. rc = SQLITE_NOMEM;
  183853. goto error_out;
  183854. }else{
  183855. memset(pChange, 0, sizeof(SessionChange));
  183856. pChange->aRecord = (u8 *)&pChange[1];
  183857. }
  183858. /* Populate the change object. None of the preupdate_old(),
  183859. ** preupdate_new() or SerializeValue() calls below may fail as all
  183860. ** required values and encodings have already been cached in memory.
  183861. ** It is not possible for an OOM to occur in this block. */
  183862. nByte = 0;
  183863. for(i=0; i<pTab->nCol; i++){
  183864. sqlite3_value *p = 0;
  183865. if( op!=SQLITE_INSERT ){
  183866. pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  183867. }else if( pTab->abPK[i] ){
  183868. pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  183869. }
  183870. sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
  183871. }
  183872. /* Add the change to the hash-table */
  183873. if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
  183874. pChange->bIndirect = 1;
  183875. }
  183876. pChange->nRecord = nByte;
  183877. pChange->op = op;
  183878. pChange->pNext = pTab->apChange[iHash];
  183879. pTab->apChange[iHash] = pChange;
  183880. }else if( pC->bIndirect ){
  183881. /* If the existing change is considered "indirect", but this current
  183882. ** change is "direct", mark the change object as direct. */
  183883. if( pSession->hook.xDepth(pSession->hook.pCtx)==0
  183884. && pSession->bIndirect==0
  183885. ){
  183886. pC->bIndirect = 0;
  183887. }
  183888. }
  183889. }
  183890. /* If an error has occurred, mark the session object as failed. */
  183891. error_out:
  183892. if( pTab->bStat1 ){
  183893. pSession->hook = stat1.hook;
  183894. }
  183895. if( rc!=SQLITE_OK ){
  183896. pSession->rc = rc;
  183897. }
  183898. }
  183899. static int sessionFindTable(
  183900. sqlite3_session *pSession,
  183901. const char *zName,
  183902. SessionTable **ppTab
  183903. ){
  183904. int rc = SQLITE_OK;
  183905. int nName = sqlite3Strlen30(zName);
  183906. SessionTable *pRet;
  183907. /* Search for an existing table */
  183908. for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
  183909. if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
  183910. }
  183911. if( pRet==0 && pSession->bAutoAttach ){
  183912. /* If there is a table-filter configured, invoke it. If it returns 0,
  183913. ** do not automatically add the new table. */
  183914. if( pSession->xTableFilter==0
  183915. || pSession->xTableFilter(pSession->pFilterCtx, zName)
  183916. ){
  183917. rc = sqlite3session_attach(pSession, zName);
  183918. if( rc==SQLITE_OK ){
  183919. for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
  183920. assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
  183921. }
  183922. }
  183923. }
  183924. assert( rc==SQLITE_OK || pRet==0 );
  183925. *ppTab = pRet;
  183926. return rc;
  183927. }
  183928. /*
  183929. ** The 'pre-update' hook registered by this module with SQLite databases.
  183930. */
  183931. static void xPreUpdate(
  183932. void *pCtx, /* Copy of third arg to preupdate_hook() */
  183933. sqlite3 *db, /* Database handle */
  183934. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  183935. char const *zDb, /* Database name */
  183936. char const *zName, /* Table name */
  183937. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  183938. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  183939. ){
  183940. sqlite3_session *pSession;
  183941. int nDb = sqlite3Strlen30(zDb);
  183942. assert( sqlite3_mutex_held(db->mutex) );
  183943. for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
  183944. SessionTable *pTab;
  183945. /* If this session is attached to a different database ("main", "temp"
  183946. ** etc.), or if it is not currently enabled, there is nothing to do. Skip
  183947. ** to the next session object attached to this database. */
  183948. if( pSession->bEnable==0 ) continue;
  183949. if( pSession->rc ) continue;
  183950. if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
  183951. pSession->rc = sessionFindTable(pSession, zName, &pTab);
  183952. if( pTab ){
  183953. assert( pSession->rc==SQLITE_OK );
  183954. sessionPreupdateOneChange(op, pSession, pTab);
  183955. if( op==SQLITE_UPDATE ){
  183956. sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
  183957. }
  183958. }
  183959. }
  183960. }
  183961. /*
  183962. ** The pre-update hook implementations.
  183963. */
  183964. static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  183965. return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
  183966. }
  183967. static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  183968. return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
  183969. }
  183970. static int sessionPreupdateCount(void *pCtx){
  183971. return sqlite3_preupdate_count((sqlite3*)pCtx);
  183972. }
  183973. static int sessionPreupdateDepth(void *pCtx){
  183974. return sqlite3_preupdate_depth((sqlite3*)pCtx);
  183975. }
  183976. /*
  183977. ** Install the pre-update hooks on the session object passed as the only
  183978. ** argument.
  183979. */
  183980. static void sessionPreupdateHooks(
  183981. sqlite3_session *pSession
  183982. ){
  183983. pSession->hook.pCtx = (void*)pSession->db;
  183984. pSession->hook.xOld = sessionPreupdateOld;
  183985. pSession->hook.xNew = sessionPreupdateNew;
  183986. pSession->hook.xCount = sessionPreupdateCount;
  183987. pSession->hook.xDepth = sessionPreupdateDepth;
  183988. }
  183989. typedef struct SessionDiffCtx SessionDiffCtx;
  183990. struct SessionDiffCtx {
  183991. sqlite3_stmt *pStmt;
  183992. int nOldOff;
  183993. };
  183994. /*
  183995. ** The diff hook implementations.
  183996. */
  183997. static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  183998. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  183999. *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
  184000. return SQLITE_OK;
  184001. }
  184002. static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  184003. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  184004. *ppVal = sqlite3_column_value(p->pStmt, iVal);
  184005. return SQLITE_OK;
  184006. }
  184007. static int sessionDiffCount(void *pCtx){
  184008. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  184009. return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
  184010. }
  184011. static int sessionDiffDepth(void *pCtx){
  184012. return 0;
  184013. }
  184014. /*
  184015. ** Install the diff hooks on the session object passed as the only
  184016. ** argument.
  184017. */
  184018. static void sessionDiffHooks(
  184019. sqlite3_session *pSession,
  184020. SessionDiffCtx *pDiffCtx
  184021. ){
  184022. pSession->hook.pCtx = (void*)pDiffCtx;
  184023. pSession->hook.xOld = sessionDiffOld;
  184024. pSession->hook.xNew = sessionDiffNew;
  184025. pSession->hook.xCount = sessionDiffCount;
  184026. pSession->hook.xDepth = sessionDiffDepth;
  184027. }
  184028. static char *sessionExprComparePK(
  184029. int nCol,
  184030. const char *zDb1, const char *zDb2,
  184031. const char *zTab,
  184032. const char **azCol, u8 *abPK
  184033. ){
  184034. int i;
  184035. const char *zSep = "";
  184036. char *zRet = 0;
  184037. for(i=0; i<nCol; i++){
  184038. if( abPK[i] ){
  184039. zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
  184040. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  184041. );
  184042. zSep = " AND ";
  184043. if( zRet==0 ) break;
  184044. }
  184045. }
  184046. return zRet;
  184047. }
  184048. static char *sessionExprCompareOther(
  184049. int nCol,
  184050. const char *zDb1, const char *zDb2,
  184051. const char *zTab,
  184052. const char **azCol, u8 *abPK
  184053. ){
  184054. int i;
  184055. const char *zSep = "";
  184056. char *zRet = 0;
  184057. int bHave = 0;
  184058. for(i=0; i<nCol; i++){
  184059. if( abPK[i]==0 ){
  184060. bHave = 1;
  184061. zRet = sqlite3_mprintf(
  184062. "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
  184063. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  184064. );
  184065. zSep = " OR ";
  184066. if( zRet==0 ) break;
  184067. }
  184068. }
  184069. if( bHave==0 ){
  184070. assert( zRet==0 );
  184071. zRet = sqlite3_mprintf("0");
  184072. }
  184073. return zRet;
  184074. }
  184075. static char *sessionSelectFindNew(
  184076. int nCol,
  184077. const char *zDb1, /* Pick rows in this db only */
  184078. const char *zDb2, /* But not in this one */
  184079. const char *zTbl, /* Table name */
  184080. const char *zExpr
  184081. ){
  184082. char *zRet = sqlite3_mprintf(
  184083. "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
  184084. " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
  184085. ")",
  184086. zDb1, zTbl, zDb2, zTbl, zExpr
  184087. );
  184088. return zRet;
  184089. }
  184090. static int sessionDiffFindNew(
  184091. int op,
  184092. sqlite3_session *pSession,
  184093. SessionTable *pTab,
  184094. const char *zDb1,
  184095. const char *zDb2,
  184096. char *zExpr
  184097. ){
  184098. int rc = SQLITE_OK;
  184099. char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
  184100. if( zStmt==0 ){
  184101. rc = SQLITE_NOMEM;
  184102. }else{
  184103. sqlite3_stmt *pStmt;
  184104. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  184105. if( rc==SQLITE_OK ){
  184106. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  184107. pDiffCtx->pStmt = pStmt;
  184108. pDiffCtx->nOldOff = 0;
  184109. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  184110. sessionPreupdateOneChange(op, pSession, pTab);
  184111. }
  184112. rc = sqlite3_finalize(pStmt);
  184113. }
  184114. sqlite3_free(zStmt);
  184115. }
  184116. return rc;
  184117. }
  184118. static int sessionDiffFindModified(
  184119. sqlite3_session *pSession,
  184120. SessionTable *pTab,
  184121. const char *zFrom,
  184122. const char *zExpr
  184123. ){
  184124. int rc = SQLITE_OK;
  184125. char *zExpr2 = sessionExprCompareOther(pTab->nCol,
  184126. pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
  184127. );
  184128. if( zExpr2==0 ){
  184129. rc = SQLITE_NOMEM;
  184130. }else{
  184131. char *zStmt = sqlite3_mprintf(
  184132. "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
  184133. pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
  184134. );
  184135. if( zStmt==0 ){
  184136. rc = SQLITE_NOMEM;
  184137. }else{
  184138. sqlite3_stmt *pStmt;
  184139. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  184140. if( rc==SQLITE_OK ){
  184141. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  184142. pDiffCtx->pStmt = pStmt;
  184143. pDiffCtx->nOldOff = pTab->nCol;
  184144. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  184145. sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
  184146. }
  184147. rc = sqlite3_finalize(pStmt);
  184148. }
  184149. sqlite3_free(zStmt);
  184150. }
  184151. }
  184152. return rc;
  184153. }
  184154. SQLITE_API int sqlite3session_diff(
  184155. sqlite3_session *pSession,
  184156. const char *zFrom,
  184157. const char *zTbl,
  184158. char **pzErrMsg
  184159. ){
  184160. const char *zDb = pSession->zDb;
  184161. int rc = pSession->rc;
  184162. SessionDiffCtx d;
  184163. memset(&d, 0, sizeof(d));
  184164. sessionDiffHooks(pSession, &d);
  184165. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  184166. if( pzErrMsg ) *pzErrMsg = 0;
  184167. if( rc==SQLITE_OK ){
  184168. char *zExpr = 0;
  184169. sqlite3 *db = pSession->db;
  184170. SessionTable *pTo; /* Table zTbl */
  184171. /* Locate and if necessary initialize the target table object */
  184172. rc = sessionFindTable(pSession, zTbl, &pTo);
  184173. if( pTo==0 ) goto diff_out;
  184174. if( sessionInitTable(pSession, pTo) ){
  184175. rc = pSession->rc;
  184176. goto diff_out;
  184177. }
  184178. /* Check the table schemas match */
  184179. if( rc==SQLITE_OK ){
  184180. int bHasPk = 0;
  184181. int bMismatch = 0;
  184182. int nCol; /* Columns in zFrom.zTbl */
  184183. u8 *abPK;
  184184. const char **azCol = 0;
  184185. rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
  184186. if( rc==SQLITE_OK ){
  184187. if( pTo->nCol!=nCol ){
  184188. bMismatch = 1;
  184189. }else{
  184190. int i;
  184191. for(i=0; i<nCol; i++){
  184192. if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
  184193. if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
  184194. if( abPK[i] ) bHasPk = 1;
  184195. }
  184196. }
  184197. }
  184198. sqlite3_free((char*)azCol);
  184199. if( bMismatch ){
  184200. *pzErrMsg = sqlite3_mprintf("table schemas do not match");
  184201. rc = SQLITE_SCHEMA;
  184202. }
  184203. if( bHasPk==0 ){
  184204. /* Ignore tables with no primary keys */
  184205. goto diff_out;
  184206. }
  184207. }
  184208. if( rc==SQLITE_OK ){
  184209. zExpr = sessionExprComparePK(pTo->nCol,
  184210. zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
  184211. );
  184212. }
  184213. /* Find new rows */
  184214. if( rc==SQLITE_OK ){
  184215. rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
  184216. }
  184217. /* Find old rows */
  184218. if( rc==SQLITE_OK ){
  184219. rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
  184220. }
  184221. /* Find modified rows */
  184222. if( rc==SQLITE_OK ){
  184223. rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
  184224. }
  184225. sqlite3_free(zExpr);
  184226. }
  184227. diff_out:
  184228. sessionPreupdateHooks(pSession);
  184229. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  184230. return rc;
  184231. }
  184232. /*
  184233. ** Create a session object. This session object will record changes to
  184234. ** database zDb attached to connection db.
  184235. */
  184236. SQLITE_API int sqlite3session_create(
  184237. sqlite3 *db, /* Database handle */
  184238. const char *zDb, /* Name of db (e.g. "main") */
  184239. sqlite3_session **ppSession /* OUT: New session object */
  184240. ){
  184241. sqlite3_session *pNew; /* Newly allocated session object */
  184242. sqlite3_session *pOld; /* Session object already attached to db */
  184243. int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
  184244. /* Zero the output value in case an error occurs. */
  184245. *ppSession = 0;
  184246. /* Allocate and populate the new session object. */
  184247. pNew = (sqlite3_session *)sqlite3_malloc64(sizeof(sqlite3_session) + nDb + 1);
  184248. if( !pNew ) return SQLITE_NOMEM;
  184249. memset(pNew, 0, sizeof(sqlite3_session));
  184250. pNew->db = db;
  184251. pNew->zDb = (char *)&pNew[1];
  184252. pNew->bEnable = 1;
  184253. memcpy(pNew->zDb, zDb, nDb+1);
  184254. sessionPreupdateHooks(pNew);
  184255. /* Add the new session object to the linked list of session objects
  184256. ** attached to database handle $db. Do this under the cover of the db
  184257. ** handle mutex. */
  184258. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  184259. pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
  184260. pNew->pNext = pOld;
  184261. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  184262. *ppSession = pNew;
  184263. return SQLITE_OK;
  184264. }
  184265. /*
  184266. ** Free the list of table objects passed as the first argument. The contents
  184267. ** of the changed-rows hash tables are also deleted.
  184268. */
  184269. static void sessionDeleteTable(SessionTable *pList){
  184270. SessionTable *pNext;
  184271. SessionTable *pTab;
  184272. for(pTab=pList; pTab; pTab=pNext){
  184273. int i;
  184274. pNext = pTab->pNext;
  184275. for(i=0; i<pTab->nChange; i++){
  184276. SessionChange *p;
  184277. SessionChange *pNextChange;
  184278. for(p=pTab->apChange[i]; p; p=pNextChange){
  184279. pNextChange = p->pNext;
  184280. sqlite3_free(p);
  184281. }
  184282. }
  184283. sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
  184284. sqlite3_free(pTab->apChange);
  184285. sqlite3_free(pTab);
  184286. }
  184287. }
  184288. /*
  184289. ** Delete a session object previously allocated using sqlite3session_create().
  184290. */
  184291. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
  184292. sqlite3 *db = pSession->db;
  184293. sqlite3_session *pHead;
  184294. sqlite3_session **pp;
  184295. /* Unlink the session from the linked list of sessions attached to the
  184296. ** database handle. Hold the db mutex while doing so. */
  184297. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  184298. pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
  184299. for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
  184300. if( (*pp)==pSession ){
  184301. *pp = (*pp)->pNext;
  184302. if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
  184303. break;
  184304. }
  184305. }
  184306. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  184307. sqlite3ValueFree(pSession->pZeroBlob);
  184308. /* Delete all attached table objects. And the contents of their
  184309. ** associated hash-tables. */
  184310. sessionDeleteTable(pSession->pTable);
  184311. /* Free the session object itself. */
  184312. sqlite3_free(pSession);
  184313. }
  184314. /*
  184315. ** Set a table filter on a Session Object.
  184316. */
  184317. SQLITE_API void sqlite3session_table_filter(
  184318. sqlite3_session *pSession,
  184319. int(*xFilter)(void*, const char*),
  184320. void *pCtx /* First argument passed to xFilter */
  184321. ){
  184322. pSession->bAutoAttach = 1;
  184323. pSession->pFilterCtx = pCtx;
  184324. pSession->xTableFilter = xFilter;
  184325. }
  184326. /*
  184327. ** Attach a table to a session. All subsequent changes made to the table
  184328. ** while the session object is enabled will be recorded.
  184329. **
  184330. ** Only tables that have a PRIMARY KEY defined may be attached. It does
  184331. ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
  184332. ** or not.
  184333. */
  184334. SQLITE_API int sqlite3session_attach(
  184335. sqlite3_session *pSession, /* Session object */
  184336. const char *zName /* Table name */
  184337. ){
  184338. int rc = SQLITE_OK;
  184339. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  184340. if( !zName ){
  184341. pSession->bAutoAttach = 1;
  184342. }else{
  184343. SessionTable *pTab; /* New table object (if required) */
  184344. int nName; /* Number of bytes in string zName */
  184345. /* First search for an existing entry. If one is found, this call is
  184346. ** a no-op. Return early. */
  184347. nName = sqlite3Strlen30(zName);
  184348. for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
  184349. if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
  184350. }
  184351. if( !pTab ){
  184352. /* Allocate new SessionTable object. */
  184353. pTab = (SessionTable *)sqlite3_malloc64(sizeof(SessionTable) + nName + 1);
  184354. if( !pTab ){
  184355. rc = SQLITE_NOMEM;
  184356. }else{
  184357. /* Populate the new SessionTable object and link it into the list.
  184358. ** The new object must be linked onto the end of the list, not
  184359. ** simply added to the start of it in order to ensure that tables
  184360. ** appear in the correct order when a changeset or patchset is
  184361. ** eventually generated. */
  184362. SessionTable **ppTab;
  184363. memset(pTab, 0, sizeof(SessionTable));
  184364. pTab->zName = (char *)&pTab[1];
  184365. memcpy(pTab->zName, zName, nName+1);
  184366. for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
  184367. *ppTab = pTab;
  184368. }
  184369. }
  184370. }
  184371. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  184372. return rc;
  184373. }
  184374. /*
  184375. ** Ensure that there is room in the buffer to append nByte bytes of data.
  184376. ** If not, use sqlite3_realloc() to grow the buffer so that there is.
  184377. **
  184378. ** If successful, return zero. Otherwise, if an OOM condition is encountered,
  184379. ** set *pRc to SQLITE_NOMEM and return non-zero.
  184380. */
  184381. static int sessionBufferGrow(SessionBuffer *p, size_t nByte, int *pRc){
  184382. if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
  184383. u8 *aNew;
  184384. i64 nNew = p->nAlloc ? p->nAlloc : 128;
  184385. do {
  184386. nNew = nNew*2;
  184387. }while( (nNew-p->nBuf)<nByte );
  184388. aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew);
  184389. if( 0==aNew ){
  184390. *pRc = SQLITE_NOMEM;
  184391. }else{
  184392. p->aBuf = aNew;
  184393. p->nAlloc = nNew;
  184394. }
  184395. }
  184396. return (*pRc!=SQLITE_OK);
  184397. }
  184398. /*
  184399. ** Append the value passed as the second argument to the buffer passed
  184400. ** as the first.
  184401. **
  184402. ** This function is a no-op if *pRc is non-zero when it is called.
  184403. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
  184404. ** before returning.
  184405. */
  184406. static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
  184407. int rc = *pRc;
  184408. if( rc==SQLITE_OK ){
  184409. sqlite3_int64 nByte = 0;
  184410. rc = sessionSerializeValue(0, pVal, &nByte);
  184411. sessionBufferGrow(p, nByte, &rc);
  184412. if( rc==SQLITE_OK ){
  184413. rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
  184414. p->nBuf += nByte;
  184415. }else{
  184416. *pRc = rc;
  184417. }
  184418. }
  184419. }
  184420. /*
  184421. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  184422. ** called. Otherwise, append a single byte to the buffer.
  184423. **
  184424. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  184425. ** returning.
  184426. */
  184427. static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
  184428. if( 0==sessionBufferGrow(p, 1, pRc) ){
  184429. p->aBuf[p->nBuf++] = v;
  184430. }
  184431. }
  184432. /*
  184433. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  184434. ** called. Otherwise, append a single varint to the buffer.
  184435. **
  184436. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  184437. ** returning.
  184438. */
  184439. static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
  184440. if( 0==sessionBufferGrow(p, 9, pRc) ){
  184441. p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
  184442. }
  184443. }
  184444. /*
  184445. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  184446. ** called. Otherwise, append a blob of data to the buffer.
  184447. **
  184448. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  184449. ** returning.
  184450. */
  184451. static void sessionAppendBlob(
  184452. SessionBuffer *p,
  184453. const u8 *aBlob,
  184454. int nBlob,
  184455. int *pRc
  184456. ){
  184457. if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
  184458. memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
  184459. p->nBuf += nBlob;
  184460. }
  184461. }
  184462. /*
  184463. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  184464. ** called. Otherwise, append a string to the buffer. All bytes in the string
  184465. ** up to (but not including) the nul-terminator are written to the buffer.
  184466. **
  184467. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  184468. ** returning.
  184469. */
  184470. static void sessionAppendStr(
  184471. SessionBuffer *p,
  184472. const char *zStr,
  184473. int *pRc
  184474. ){
  184475. int nStr = sqlite3Strlen30(zStr);
  184476. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  184477. memcpy(&p->aBuf[p->nBuf], zStr, nStr);
  184478. p->nBuf += nStr;
  184479. }
  184480. }
  184481. /*
  184482. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  184483. ** called. Otherwise, append the string representation of integer iVal
  184484. ** to the buffer. No nul-terminator is written.
  184485. **
  184486. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  184487. ** returning.
  184488. */
  184489. static void sessionAppendInteger(
  184490. SessionBuffer *p, /* Buffer to append to */
  184491. int iVal, /* Value to write the string rep. of */
  184492. int *pRc /* IN/OUT: Error code */
  184493. ){
  184494. char aBuf[24];
  184495. sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  184496. sessionAppendStr(p, aBuf, pRc);
  184497. }
  184498. /*
  184499. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  184500. ** called. Otherwise, append the string zStr enclosed in quotes (") and
  184501. ** with any embedded quote characters escaped to the buffer. No
  184502. ** nul-terminator byte is written.
  184503. **
  184504. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  184505. ** returning.
  184506. */
  184507. static void sessionAppendIdent(
  184508. SessionBuffer *p, /* Buffer to a append to */
  184509. const char *zStr, /* String to quote, escape and append */
  184510. int *pRc /* IN/OUT: Error code */
  184511. ){
  184512. int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
  184513. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  184514. char *zOut = (char *)&p->aBuf[p->nBuf];
  184515. const char *zIn = zStr;
  184516. *zOut++ = '"';
  184517. while( *zIn ){
  184518. if( *zIn=='"' ) *zOut++ = '"';
  184519. *zOut++ = *(zIn++);
  184520. }
  184521. *zOut++ = '"';
  184522. p->nBuf = (int)((u8 *)zOut - p->aBuf);
  184523. }
  184524. }
  184525. /*
  184526. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  184527. ** called. Otherwse, it appends the serialized version of the value stored
  184528. ** in column iCol of the row that SQL statement pStmt currently points
  184529. ** to to the buffer.
  184530. */
  184531. static void sessionAppendCol(
  184532. SessionBuffer *p, /* Buffer to append to */
  184533. sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
  184534. int iCol, /* Column to read value from */
  184535. int *pRc /* IN/OUT: Error code */
  184536. ){
  184537. if( *pRc==SQLITE_OK ){
  184538. int eType = sqlite3_column_type(pStmt, iCol);
  184539. sessionAppendByte(p, (u8)eType, pRc);
  184540. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  184541. sqlite3_int64 i;
  184542. u8 aBuf[8];
  184543. if( eType==SQLITE_INTEGER ){
  184544. i = sqlite3_column_int64(pStmt, iCol);
  184545. }else{
  184546. double r = sqlite3_column_double(pStmt, iCol);
  184547. memcpy(&i, &r, 8);
  184548. }
  184549. sessionPutI64(aBuf, i);
  184550. sessionAppendBlob(p, aBuf, 8, pRc);
  184551. }
  184552. if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
  184553. u8 *z;
  184554. int nByte;
  184555. if( eType==SQLITE_BLOB ){
  184556. z = (u8 *)sqlite3_column_blob(pStmt, iCol);
  184557. }else{
  184558. z = (u8 *)sqlite3_column_text(pStmt, iCol);
  184559. }
  184560. nByte = sqlite3_column_bytes(pStmt, iCol);
  184561. if( z || (eType==SQLITE_BLOB && nByte==0) ){
  184562. sessionAppendVarint(p, nByte, pRc);
  184563. sessionAppendBlob(p, z, nByte, pRc);
  184564. }else{
  184565. *pRc = SQLITE_NOMEM;
  184566. }
  184567. }
  184568. }
  184569. }
  184570. /*
  184571. **
  184572. ** This function appends an update change to the buffer (see the comments
  184573. ** under "CHANGESET FORMAT" at the top of the file). An update change
  184574. ** consists of:
  184575. **
  184576. ** 1 byte: SQLITE_UPDATE (0x17)
  184577. ** n bytes: old.* record (see RECORD FORMAT)
  184578. ** m bytes: new.* record (see RECORD FORMAT)
  184579. **
  184580. ** The SessionChange object passed as the third argument contains the
  184581. ** values that were stored in the row when the session began (the old.*
  184582. ** values). The statement handle passed as the second argument points
  184583. ** at the current version of the row (the new.* values).
  184584. **
  184585. ** If all of the old.* values are equal to their corresponding new.* value
  184586. ** (i.e. nothing has changed), then no data at all is appended to the buffer.
  184587. **
  184588. ** Otherwise, the old.* record contains all primary key values and the
  184589. ** original values of any fields that have been modified. The new.* record
  184590. ** contains the new values of only those fields that have been modified.
  184591. */
  184592. static int sessionAppendUpdate(
  184593. SessionBuffer *pBuf, /* Buffer to append to */
  184594. int bPatchset, /* True for "patchset", 0 for "changeset" */
  184595. sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
  184596. SessionChange *p, /* Object containing old values */
  184597. u8 *abPK /* Boolean array - true for PK columns */
  184598. ){
  184599. int rc = SQLITE_OK;
  184600. SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
  184601. int bNoop = 1; /* Set to zero if any values are modified */
  184602. int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
  184603. int i; /* Used to iterate through columns */
  184604. u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
  184605. sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
  184606. sessionAppendByte(pBuf, p->bIndirect, &rc);
  184607. for(i=0; i<sqlite3_column_count(pStmt); i++){
  184608. int bChanged = 0;
  184609. int nAdvance;
  184610. int eType = *pCsr;
  184611. switch( eType ){
  184612. case SQLITE_NULL:
  184613. nAdvance = 1;
  184614. if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  184615. bChanged = 1;
  184616. }
  184617. break;
  184618. case SQLITE_FLOAT:
  184619. case SQLITE_INTEGER: {
  184620. nAdvance = 9;
  184621. if( eType==sqlite3_column_type(pStmt, i) ){
  184622. sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
  184623. if( eType==SQLITE_INTEGER ){
  184624. if( iVal==sqlite3_column_int64(pStmt, i) ) break;
  184625. }else{
  184626. double dVal;
  184627. memcpy(&dVal, &iVal, 8);
  184628. if( dVal==sqlite3_column_double(pStmt, i) ) break;
  184629. }
  184630. }
  184631. bChanged = 1;
  184632. break;
  184633. }
  184634. default: {
  184635. int n;
  184636. int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
  184637. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  184638. nAdvance = nHdr + n;
  184639. if( eType==sqlite3_column_type(pStmt, i)
  184640. && n==sqlite3_column_bytes(pStmt, i)
  184641. && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
  184642. ){
  184643. break;
  184644. }
  184645. bChanged = 1;
  184646. }
  184647. }
  184648. /* If at least one field has been modified, this is not a no-op. */
  184649. if( bChanged ) bNoop = 0;
  184650. /* Add a field to the old.* record. This is omitted if this modules is
  184651. ** currently generating a patchset. */
  184652. if( bPatchset==0 ){
  184653. if( bChanged || abPK[i] ){
  184654. sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
  184655. }else{
  184656. sessionAppendByte(pBuf, 0, &rc);
  184657. }
  184658. }
  184659. /* Add a field to the new.* record. Or the only record if currently
  184660. ** generating a patchset. */
  184661. if( bChanged || (bPatchset && abPK[i]) ){
  184662. sessionAppendCol(&buf2, pStmt, i, &rc);
  184663. }else{
  184664. sessionAppendByte(&buf2, 0, &rc);
  184665. }
  184666. pCsr += nAdvance;
  184667. }
  184668. if( bNoop ){
  184669. pBuf->nBuf = nRewind;
  184670. }else{
  184671. sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
  184672. }
  184673. sqlite3_free(buf2.aBuf);
  184674. return rc;
  184675. }
  184676. /*
  184677. ** Append a DELETE change to the buffer passed as the first argument. Use
  184678. ** the changeset format if argument bPatchset is zero, or the patchset
  184679. ** format otherwise.
  184680. */
  184681. static int sessionAppendDelete(
  184682. SessionBuffer *pBuf, /* Buffer to append to */
  184683. int bPatchset, /* True for "patchset", 0 for "changeset" */
  184684. SessionChange *p, /* Object containing old values */
  184685. int nCol, /* Number of columns in table */
  184686. u8 *abPK /* Boolean array - true for PK columns */
  184687. ){
  184688. int rc = SQLITE_OK;
  184689. sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
  184690. sessionAppendByte(pBuf, p->bIndirect, &rc);
  184691. if( bPatchset==0 ){
  184692. sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
  184693. }else{
  184694. int i;
  184695. u8 *a = p->aRecord;
  184696. for(i=0; i<nCol; i++){
  184697. u8 *pStart = a;
  184698. int eType = *a++;
  184699. switch( eType ){
  184700. case 0:
  184701. case SQLITE_NULL:
  184702. assert( abPK[i]==0 );
  184703. break;
  184704. case SQLITE_FLOAT:
  184705. case SQLITE_INTEGER:
  184706. a += 8;
  184707. break;
  184708. default: {
  184709. int n;
  184710. a += sessionVarintGet(a, &n);
  184711. a += n;
  184712. break;
  184713. }
  184714. }
  184715. if( abPK[i] ){
  184716. sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
  184717. }
  184718. }
  184719. assert( (a - p->aRecord)==p->nRecord );
  184720. }
  184721. return rc;
  184722. }
  184723. /*
  184724. ** Formulate and prepare a SELECT statement to retrieve a row from table
  184725. ** zTab in database zDb based on its primary key. i.e.
  184726. **
  184727. ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
  184728. */
  184729. static int sessionSelectStmt(
  184730. sqlite3 *db, /* Database handle */
  184731. const char *zDb, /* Database name */
  184732. const char *zTab, /* Table name */
  184733. int nCol, /* Number of columns in table */
  184734. const char **azCol, /* Names of table columns */
  184735. u8 *abPK, /* PRIMARY KEY array */
  184736. sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
  184737. ){
  184738. int rc = SQLITE_OK;
  184739. char *zSql = 0;
  184740. int nSql = -1;
  184741. if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
  184742. zSql = sqlite3_mprintf(
  184743. "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
  184744. "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
  184745. );
  184746. if( zSql==0 ) rc = SQLITE_NOMEM;
  184747. }else{
  184748. int i;
  184749. const char *zSep = "";
  184750. SessionBuffer buf = {0, 0, 0};
  184751. sessionAppendStr(&buf, "SELECT * FROM ", &rc);
  184752. sessionAppendIdent(&buf, zDb, &rc);
  184753. sessionAppendStr(&buf, ".", &rc);
  184754. sessionAppendIdent(&buf, zTab, &rc);
  184755. sessionAppendStr(&buf, " WHERE ", &rc);
  184756. for(i=0; i<nCol; i++){
  184757. if( abPK[i] ){
  184758. sessionAppendStr(&buf, zSep, &rc);
  184759. sessionAppendIdent(&buf, azCol[i], &rc);
  184760. sessionAppendStr(&buf, " IS ?", &rc);
  184761. sessionAppendInteger(&buf, i+1, &rc);
  184762. zSep = " AND ";
  184763. }
  184764. }
  184765. zSql = (char*)buf.aBuf;
  184766. nSql = buf.nBuf;
  184767. }
  184768. if( rc==SQLITE_OK ){
  184769. rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
  184770. }
  184771. sqlite3_free(zSql);
  184772. return rc;
  184773. }
  184774. /*
  184775. ** Bind the PRIMARY KEY values from the change passed in argument pChange
  184776. ** to the SELECT statement passed as the first argument. The SELECT statement
  184777. ** is as prepared by function sessionSelectStmt().
  184778. **
  184779. ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
  184780. ** error code (e.g. SQLITE_NOMEM) otherwise.
  184781. */
  184782. static int sessionSelectBind(
  184783. sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
  184784. int nCol, /* Number of columns in table */
  184785. u8 *abPK, /* PRIMARY KEY array */
  184786. SessionChange *pChange /* Change structure */
  184787. ){
  184788. int i;
  184789. int rc = SQLITE_OK;
  184790. u8 *a = pChange->aRecord;
  184791. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  184792. int eType = *a++;
  184793. switch( eType ){
  184794. case 0:
  184795. case SQLITE_NULL:
  184796. assert( abPK[i]==0 );
  184797. break;
  184798. case SQLITE_INTEGER: {
  184799. if( abPK[i] ){
  184800. i64 iVal = sessionGetI64(a);
  184801. rc = sqlite3_bind_int64(pSelect, i+1, iVal);
  184802. }
  184803. a += 8;
  184804. break;
  184805. }
  184806. case SQLITE_FLOAT: {
  184807. if( abPK[i] ){
  184808. double rVal;
  184809. i64 iVal = sessionGetI64(a);
  184810. memcpy(&rVal, &iVal, 8);
  184811. rc = sqlite3_bind_double(pSelect, i+1, rVal);
  184812. }
  184813. a += 8;
  184814. break;
  184815. }
  184816. case SQLITE_TEXT: {
  184817. int n;
  184818. a += sessionVarintGet(a, &n);
  184819. if( abPK[i] ){
  184820. rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
  184821. }
  184822. a += n;
  184823. break;
  184824. }
  184825. default: {
  184826. int n;
  184827. assert( eType==SQLITE_BLOB );
  184828. a += sessionVarintGet(a, &n);
  184829. if( abPK[i] ){
  184830. rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
  184831. }
  184832. a += n;
  184833. break;
  184834. }
  184835. }
  184836. }
  184837. return rc;
  184838. }
  184839. /*
  184840. ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
  184841. ** is called. Otherwise, append a serialized table header (part of the binary
  184842. ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
  184843. ** SQLite error code before returning.
  184844. */
  184845. static void sessionAppendTableHdr(
  184846. SessionBuffer *pBuf, /* Append header to this buffer */
  184847. int bPatchset, /* Use the patchset format if true */
  184848. SessionTable *pTab, /* Table object to append header for */
  184849. int *pRc /* IN/OUT: Error code */
  184850. ){
  184851. /* Write a table header */
  184852. sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
  184853. sessionAppendVarint(pBuf, pTab->nCol, pRc);
  184854. sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
  184855. sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
  184856. }
  184857. /*
  184858. ** Generate either a changeset (if argument bPatchset is zero) or a patchset
  184859. ** (if it is non-zero) based on the current contents of the session object
  184860. ** passed as the first argument.
  184861. **
  184862. ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
  184863. ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
  184864. ** occurs, an SQLite error code is returned and both output variables set
  184865. ** to 0.
  184866. */
  184867. static int sessionGenerateChangeset(
  184868. sqlite3_session *pSession, /* Session object */
  184869. int bPatchset, /* True for patchset, false for changeset */
  184870. int (*xOutput)(void *pOut, const void *pData, int nData),
  184871. void *pOut, /* First argument for xOutput */
  184872. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  184873. void **ppChangeset /* OUT: Buffer containing changeset */
  184874. ){
  184875. sqlite3 *db = pSession->db; /* Source database handle */
  184876. SessionTable *pTab; /* Used to iterate through attached tables */
  184877. SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
  184878. int rc; /* Return code */
  184879. assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
  184880. /* Zero the output variables in case an error occurs. If this session
  184881. ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
  184882. ** this call will be a no-op. */
  184883. if( xOutput==0 ){
  184884. *pnChangeset = 0;
  184885. *ppChangeset = 0;
  184886. }
  184887. if( pSession->rc ) return pSession->rc;
  184888. rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
  184889. if( rc!=SQLITE_OK ) return rc;
  184890. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  184891. for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  184892. if( pTab->nEntry ){
  184893. const char *zName = pTab->zName;
  184894. int nCol; /* Number of columns in table */
  184895. u8 *abPK; /* Primary key array */
  184896. const char **azCol = 0; /* Table columns */
  184897. int i; /* Used to iterate through hash buckets */
  184898. sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
  184899. int nRewind = buf.nBuf; /* Initial size of write buffer */
  184900. int nNoop; /* Size of buffer after writing tbl header */
  184901. /* Check the table schema is still Ok. */
  184902. rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
  184903. if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
  184904. rc = SQLITE_SCHEMA;
  184905. }
  184906. /* Write a table header */
  184907. sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
  184908. /* Build and compile a statement to execute: */
  184909. if( rc==SQLITE_OK ){
  184910. rc = sessionSelectStmt(
  184911. db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
  184912. }
  184913. nNoop = buf.nBuf;
  184914. for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
  184915. SessionChange *p; /* Used to iterate through changes */
  184916. for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
  184917. rc = sessionSelectBind(pSel, nCol, abPK, p);
  184918. if( rc!=SQLITE_OK ) continue;
  184919. if( sqlite3_step(pSel)==SQLITE_ROW ){
  184920. if( p->op==SQLITE_INSERT ){
  184921. int iCol;
  184922. sessionAppendByte(&buf, SQLITE_INSERT, &rc);
  184923. sessionAppendByte(&buf, p->bIndirect, &rc);
  184924. for(iCol=0; iCol<nCol; iCol++){
  184925. sessionAppendCol(&buf, pSel, iCol, &rc);
  184926. }
  184927. }else{
  184928. rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
  184929. }
  184930. }else if( p->op!=SQLITE_INSERT ){
  184931. rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
  184932. }
  184933. if( rc==SQLITE_OK ){
  184934. rc = sqlite3_reset(pSel);
  184935. }
  184936. /* If the buffer is now larger than sessions_strm_chunk_size, pass
  184937. ** its contents to the xOutput() callback. */
  184938. if( xOutput
  184939. && rc==SQLITE_OK
  184940. && buf.nBuf>nNoop
  184941. && buf.nBuf>sessions_strm_chunk_size
  184942. ){
  184943. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  184944. nNoop = -1;
  184945. buf.nBuf = 0;
  184946. }
  184947. }
  184948. }
  184949. sqlite3_finalize(pSel);
  184950. if( buf.nBuf==nNoop ){
  184951. buf.nBuf = nRewind;
  184952. }
  184953. sqlite3_free((char*)azCol); /* cast works around VC++ bug */
  184954. }
  184955. }
  184956. if( rc==SQLITE_OK ){
  184957. if( xOutput==0 ){
  184958. *pnChangeset = buf.nBuf;
  184959. *ppChangeset = buf.aBuf;
  184960. buf.aBuf = 0;
  184961. }else if( buf.nBuf>0 ){
  184962. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  184963. }
  184964. }
  184965. sqlite3_free(buf.aBuf);
  184966. sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
  184967. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  184968. return rc;
  184969. }
  184970. /*
  184971. ** Obtain a changeset object containing all changes recorded by the
  184972. ** session object passed as the first argument.
  184973. **
  184974. ** It is the responsibility of the caller to eventually free the buffer
  184975. ** using sqlite3_free().
  184976. */
  184977. SQLITE_API int sqlite3session_changeset(
  184978. sqlite3_session *pSession, /* Session object */
  184979. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  184980. void **ppChangeset /* OUT: Buffer containing changeset */
  184981. ){
  184982. return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
  184983. }
  184984. /*
  184985. ** Streaming version of sqlite3session_changeset().
  184986. */
  184987. SQLITE_API int sqlite3session_changeset_strm(
  184988. sqlite3_session *pSession,
  184989. int (*xOutput)(void *pOut, const void *pData, int nData),
  184990. void *pOut
  184991. ){
  184992. return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
  184993. }
  184994. /*
  184995. ** Streaming version of sqlite3session_patchset().
  184996. */
  184997. SQLITE_API int sqlite3session_patchset_strm(
  184998. sqlite3_session *pSession,
  184999. int (*xOutput)(void *pOut, const void *pData, int nData),
  185000. void *pOut
  185001. ){
  185002. return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
  185003. }
  185004. /*
  185005. ** Obtain a patchset object containing all changes recorded by the
  185006. ** session object passed as the first argument.
  185007. **
  185008. ** It is the responsibility of the caller to eventually free the buffer
  185009. ** using sqlite3_free().
  185010. */
  185011. SQLITE_API int sqlite3session_patchset(
  185012. sqlite3_session *pSession, /* Session object */
  185013. int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
  185014. void **ppPatchset /* OUT: Buffer containing changeset */
  185015. ){
  185016. return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
  185017. }
  185018. /*
  185019. ** Enable or disable the session object passed as the first argument.
  185020. */
  185021. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
  185022. int ret;
  185023. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  185024. if( bEnable>=0 ){
  185025. pSession->bEnable = bEnable;
  185026. }
  185027. ret = pSession->bEnable;
  185028. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  185029. return ret;
  185030. }
  185031. /*
  185032. ** Enable or disable the session object passed as the first argument.
  185033. */
  185034. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
  185035. int ret;
  185036. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  185037. if( bIndirect>=0 ){
  185038. pSession->bIndirect = bIndirect;
  185039. }
  185040. ret = pSession->bIndirect;
  185041. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  185042. return ret;
  185043. }
  185044. /*
  185045. ** Return true if there have been no changes to monitored tables recorded
  185046. ** by the session object passed as the only argument.
  185047. */
  185048. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
  185049. int ret = 0;
  185050. SessionTable *pTab;
  185051. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  185052. for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
  185053. ret = (pTab->nEntry>0);
  185054. }
  185055. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  185056. return (ret==0);
  185057. }
  185058. /*
  185059. ** Do the work for either sqlite3changeset_start() or start_strm().
  185060. */
  185061. static int sessionChangesetStart(
  185062. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  185063. int (*xInput)(void *pIn, void *pData, int *pnData),
  185064. void *pIn,
  185065. int nChangeset, /* Size of buffer pChangeset in bytes */
  185066. void *pChangeset, /* Pointer to buffer containing changeset */
  185067. int bInvert /* True to invert changeset */
  185068. ){
  185069. sqlite3_changeset_iter *pRet; /* Iterator to return */
  185070. int nByte; /* Number of bytes to allocate for iterator */
  185071. assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
  185072. /* Zero the output variable in case an error occurs. */
  185073. *pp = 0;
  185074. /* Allocate and initialize the iterator structure. */
  185075. nByte = sizeof(sqlite3_changeset_iter);
  185076. pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
  185077. if( !pRet ) return SQLITE_NOMEM;
  185078. memset(pRet, 0, sizeof(sqlite3_changeset_iter));
  185079. pRet->in.aData = (u8 *)pChangeset;
  185080. pRet->in.nData = nChangeset;
  185081. pRet->in.xInput = xInput;
  185082. pRet->in.pIn = pIn;
  185083. pRet->in.bEof = (xInput ? 0 : 1);
  185084. pRet->bInvert = bInvert;
  185085. /* Populate the output variable and return success. */
  185086. *pp = pRet;
  185087. return SQLITE_OK;
  185088. }
  185089. /*
  185090. ** Create an iterator used to iterate through the contents of a changeset.
  185091. */
  185092. SQLITE_API int sqlite3changeset_start(
  185093. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  185094. int nChangeset, /* Size of buffer pChangeset in bytes */
  185095. void *pChangeset /* Pointer to buffer containing changeset */
  185096. ){
  185097. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0);
  185098. }
  185099. SQLITE_API int sqlite3changeset_start_v2(
  185100. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  185101. int nChangeset, /* Size of buffer pChangeset in bytes */
  185102. void *pChangeset, /* Pointer to buffer containing changeset */
  185103. int flags
  185104. ){
  185105. int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
  185106. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert);
  185107. }
  185108. /*
  185109. ** Streaming version of sqlite3changeset_start().
  185110. */
  185111. SQLITE_API int sqlite3changeset_start_strm(
  185112. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  185113. int (*xInput)(void *pIn, void *pData, int *pnData),
  185114. void *pIn
  185115. ){
  185116. return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0);
  185117. }
  185118. SQLITE_API int sqlite3changeset_start_v2_strm(
  185119. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  185120. int (*xInput)(void *pIn, void *pData, int *pnData),
  185121. void *pIn,
  185122. int flags
  185123. ){
  185124. int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
  185125. return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert);
  185126. }
  185127. /*
  185128. ** If the SessionInput object passed as the only argument is a streaming
  185129. ** object and the buffer is full, discard some data to free up space.
  185130. */
  185131. static void sessionDiscardData(SessionInput *pIn){
  185132. if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){
  185133. int nMove = pIn->buf.nBuf - pIn->iNext;
  185134. assert( nMove>=0 );
  185135. if( nMove>0 ){
  185136. memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
  185137. }
  185138. pIn->buf.nBuf -= pIn->iNext;
  185139. pIn->iNext = 0;
  185140. pIn->nData = pIn->buf.nBuf;
  185141. }
  185142. }
  185143. /*
  185144. ** Ensure that there are at least nByte bytes available in the buffer. Or,
  185145. ** if there are not nByte bytes remaining in the input, that all available
  185146. ** data is in the buffer.
  185147. **
  185148. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  185149. */
  185150. static int sessionInputBuffer(SessionInput *pIn, int nByte){
  185151. int rc = SQLITE_OK;
  185152. if( pIn->xInput ){
  185153. while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
  185154. int nNew = sessions_strm_chunk_size;
  185155. if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
  185156. if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
  185157. rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
  185158. if( nNew==0 ){
  185159. pIn->bEof = 1;
  185160. }else{
  185161. pIn->buf.nBuf += nNew;
  185162. }
  185163. }
  185164. pIn->aData = pIn->buf.aBuf;
  185165. pIn->nData = pIn->buf.nBuf;
  185166. }
  185167. }
  185168. return rc;
  185169. }
  185170. /*
  185171. ** When this function is called, *ppRec points to the start of a record
  185172. ** that contains nCol values. This function advances the pointer *ppRec
  185173. ** until it points to the byte immediately following that record.
  185174. */
  185175. static void sessionSkipRecord(
  185176. u8 **ppRec, /* IN/OUT: Record pointer */
  185177. int nCol /* Number of values in record */
  185178. ){
  185179. u8 *aRec = *ppRec;
  185180. int i;
  185181. for(i=0; i<nCol; i++){
  185182. int eType = *aRec++;
  185183. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  185184. int nByte;
  185185. aRec += sessionVarintGet((u8*)aRec, &nByte);
  185186. aRec += nByte;
  185187. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  185188. aRec += 8;
  185189. }
  185190. }
  185191. *ppRec = aRec;
  185192. }
  185193. /*
  185194. ** This function sets the value of the sqlite3_value object passed as the
  185195. ** first argument to a copy of the string or blob held in the aData[]
  185196. ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
  185197. ** error occurs.
  185198. */
  185199. static int sessionValueSetStr(
  185200. sqlite3_value *pVal, /* Set the value of this object */
  185201. u8 *aData, /* Buffer containing string or blob data */
  185202. int nData, /* Size of buffer aData[] in bytes */
  185203. u8 enc /* String encoding (0 for blobs) */
  185204. ){
  185205. /* In theory this code could just pass SQLITE_TRANSIENT as the final
  185206. ** argument to sqlite3ValueSetStr() and have the copy created
  185207. ** automatically. But doing so makes it difficult to detect any OOM
  185208. ** error. Hence the code to create the copy externally. */
  185209. u8 *aCopy = sqlite3_malloc64((sqlite3_int64)nData+1);
  185210. if( aCopy==0 ) return SQLITE_NOMEM;
  185211. memcpy(aCopy, aData, nData);
  185212. sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
  185213. return SQLITE_OK;
  185214. }
  185215. /*
  185216. ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
  185217. ** for details.
  185218. **
  185219. ** When this function is called, *paChange points to the start of the record
  185220. ** to deserialize. Assuming no error occurs, *paChange is set to point to
  185221. ** one byte after the end of the same record before this function returns.
  185222. ** If the argument abPK is NULL, then the record contains nCol values. Or,
  185223. ** if abPK is other than NULL, then the record contains only the PK fields
  185224. ** (in other words, it is a patchset DELETE record).
  185225. **
  185226. ** If successful, each element of the apOut[] array (allocated by the caller)
  185227. ** is set to point to an sqlite3_value object containing the value read
  185228. ** from the corresponding position in the record. If that value is not
  185229. ** included in the record (i.e. because the record is part of an UPDATE change
  185230. ** and the field was not modified), the corresponding element of apOut[] is
  185231. ** set to NULL.
  185232. **
  185233. ** It is the responsibility of the caller to free all sqlite_value structures
  185234. ** using sqlite3_free().
  185235. **
  185236. ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  185237. ** The apOut[] array may have been partially populated in this case.
  185238. */
  185239. static int sessionReadRecord(
  185240. SessionInput *pIn, /* Input data */
  185241. int nCol, /* Number of values in record */
  185242. u8 *abPK, /* Array of primary key flags, or NULL */
  185243. sqlite3_value **apOut /* Write values to this array */
  185244. ){
  185245. int i; /* Used to iterate through columns */
  185246. int rc = SQLITE_OK;
  185247. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  185248. int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
  185249. if( abPK && abPK[i]==0 ) continue;
  185250. rc = sessionInputBuffer(pIn, 9);
  185251. if( rc==SQLITE_OK ){
  185252. if( pIn->iNext>=pIn->nData ){
  185253. rc = SQLITE_CORRUPT_BKPT;
  185254. }else{
  185255. eType = pIn->aData[pIn->iNext++];
  185256. assert( apOut[i]==0 );
  185257. if( eType ){
  185258. apOut[i] = sqlite3ValueNew(0);
  185259. if( !apOut[i] ) rc = SQLITE_NOMEM;
  185260. }
  185261. }
  185262. }
  185263. if( rc==SQLITE_OK ){
  185264. u8 *aVal = &pIn->aData[pIn->iNext];
  185265. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  185266. int nByte;
  185267. pIn->iNext += sessionVarintGet(aVal, &nByte);
  185268. rc = sessionInputBuffer(pIn, nByte);
  185269. if( rc==SQLITE_OK ){
  185270. if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
  185271. rc = SQLITE_CORRUPT_BKPT;
  185272. }else{
  185273. u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
  185274. rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
  185275. pIn->iNext += nByte;
  185276. }
  185277. }
  185278. }
  185279. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  185280. sqlite3_int64 v = sessionGetI64(aVal);
  185281. if( eType==SQLITE_INTEGER ){
  185282. sqlite3VdbeMemSetInt64(apOut[i], v);
  185283. }else{
  185284. double d;
  185285. memcpy(&d, &v, 8);
  185286. sqlite3VdbeMemSetDouble(apOut[i], d);
  185287. }
  185288. pIn->iNext += 8;
  185289. }
  185290. }
  185291. }
  185292. return rc;
  185293. }
  185294. /*
  185295. ** The input pointer currently points to the second byte of a table-header.
  185296. ** Specifically, to the following:
  185297. **
  185298. ** + number of columns in table (varint)
  185299. ** + array of PK flags (1 byte per column),
  185300. ** + table name (nul terminated).
  185301. **
  185302. ** This function ensures that all of the above is present in the input
  185303. ** buffer (i.e. that it can be accessed without any calls to xInput()).
  185304. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  185305. ** The input pointer is not moved.
  185306. */
  185307. static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
  185308. int rc = SQLITE_OK;
  185309. int nCol = 0;
  185310. int nRead = 0;
  185311. rc = sessionInputBuffer(pIn, 9);
  185312. if( rc==SQLITE_OK ){
  185313. nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
  185314. /* The hard upper limit for the number of columns in an SQLite
  185315. ** database table is, according to sqliteLimit.h, 32676. So
  185316. ** consider any table-header that purports to have more than 65536
  185317. ** columns to be corrupt. This is convenient because otherwise,
  185318. ** if the (nCol>65536) condition below were omitted, a sufficiently
  185319. ** large value for nCol may cause nRead to wrap around and become
  185320. ** negative. Leading to a crash. */
  185321. if( nCol<0 || nCol>65536 ){
  185322. rc = SQLITE_CORRUPT_BKPT;
  185323. }else{
  185324. rc = sessionInputBuffer(pIn, nRead+nCol+100);
  185325. nRead += nCol;
  185326. }
  185327. }
  185328. while( rc==SQLITE_OK ){
  185329. while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
  185330. nRead++;
  185331. }
  185332. if( (pIn->iNext + nRead)<pIn->nData ) break;
  185333. rc = sessionInputBuffer(pIn, nRead + 100);
  185334. }
  185335. *pnByte = nRead+1;
  185336. return rc;
  185337. }
  185338. /*
  185339. ** The input pointer currently points to the first byte of the first field
  185340. ** of a record consisting of nCol columns. This function ensures the entire
  185341. ** record is buffered. It does not move the input pointer.
  185342. **
  185343. ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
  185344. ** the record in bytes. Otherwise, an SQLite error code is returned. The
  185345. ** final value of *pnByte is undefined in this case.
  185346. */
  185347. static int sessionChangesetBufferRecord(
  185348. SessionInput *pIn, /* Input data */
  185349. int nCol, /* Number of columns in record */
  185350. int *pnByte /* OUT: Size of record in bytes */
  185351. ){
  185352. int rc = SQLITE_OK;
  185353. int nByte = 0;
  185354. int i;
  185355. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  185356. int eType;
  185357. rc = sessionInputBuffer(pIn, nByte + 10);
  185358. if( rc==SQLITE_OK ){
  185359. eType = pIn->aData[pIn->iNext + nByte++];
  185360. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  185361. int n;
  185362. nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
  185363. nByte += n;
  185364. rc = sessionInputBuffer(pIn, nByte);
  185365. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  185366. nByte += 8;
  185367. }
  185368. }
  185369. }
  185370. *pnByte = nByte;
  185371. return rc;
  185372. }
  185373. /*
  185374. ** The input pointer currently points to the second byte of a table-header.
  185375. ** Specifically, to the following:
  185376. **
  185377. ** + number of columns in table (varint)
  185378. ** + array of PK flags (1 byte per column),
  185379. ** + table name (nul terminated).
  185380. **
  185381. ** This function decodes the table-header and populates the p->nCol,
  185382. ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
  185383. ** also allocated or resized according to the new value of p->nCol. The
  185384. ** input pointer is left pointing to the byte following the table header.
  185385. **
  185386. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
  185387. ** is returned and the final values of the various fields enumerated above
  185388. ** are undefined.
  185389. */
  185390. static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
  185391. int rc;
  185392. int nCopy;
  185393. assert( p->rc==SQLITE_OK );
  185394. rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
  185395. if( rc==SQLITE_OK ){
  185396. int nByte;
  185397. int nVarint;
  185398. nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
  185399. if( p->nCol>0 ){
  185400. nCopy -= nVarint;
  185401. p->in.iNext += nVarint;
  185402. nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
  185403. p->tblhdr.nBuf = 0;
  185404. sessionBufferGrow(&p->tblhdr, nByte, &rc);
  185405. }else{
  185406. rc = SQLITE_CORRUPT_BKPT;
  185407. }
  185408. }
  185409. if( rc==SQLITE_OK ){
  185410. size_t iPK = sizeof(sqlite3_value*)*p->nCol*2;
  185411. memset(p->tblhdr.aBuf, 0, iPK);
  185412. memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
  185413. p->in.iNext += nCopy;
  185414. }
  185415. p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
  185416. p->abPK = (u8*)&p->apValue[p->nCol*2];
  185417. p->zTab = (char*)&p->abPK[p->nCol];
  185418. return (p->rc = rc);
  185419. }
  185420. /*
  185421. ** Advance the changeset iterator to the next change.
  185422. **
  185423. ** If both paRec and pnRec are NULL, then this function works like the public
  185424. ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
  185425. ** sqlite3changeset_new() and old() APIs may be used to query for values.
  185426. **
  185427. ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
  185428. ** record is written to *paRec before returning and the number of bytes in
  185429. ** the record to *pnRec.
  185430. **
  185431. ** Either way, this function returns SQLITE_ROW if the iterator is
  185432. ** successfully advanced to the next change in the changeset, an SQLite
  185433. ** error code if an error occurs, or SQLITE_DONE if there are no further
  185434. ** changes in the changeset.
  185435. */
  185436. static int sessionChangesetNext(
  185437. sqlite3_changeset_iter *p, /* Changeset iterator */
  185438. u8 **paRec, /* If non-NULL, store record pointer here */
  185439. int *pnRec, /* If non-NULL, store size of record here */
  185440. int *pbNew /* If non-NULL, true if new table */
  185441. ){
  185442. int i;
  185443. u8 op;
  185444. assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
  185445. /* If the iterator is in the error-state, return immediately. */
  185446. if( p->rc!=SQLITE_OK ) return p->rc;
  185447. /* Free the current contents of p->apValue[], if any. */
  185448. if( p->apValue ){
  185449. for(i=0; i<p->nCol*2; i++){
  185450. sqlite3ValueFree(p->apValue[i]);
  185451. }
  185452. memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
  185453. }
  185454. /* Make sure the buffer contains at least 10 bytes of input data, or all
  185455. ** remaining data if there are less than 10 bytes available. This is
  185456. ** sufficient either for the 'T' or 'P' byte and the varint that follows
  185457. ** it, or for the two single byte values otherwise. */
  185458. p->rc = sessionInputBuffer(&p->in, 2);
  185459. if( p->rc!=SQLITE_OK ) return p->rc;
  185460. /* If the iterator is already at the end of the changeset, return DONE. */
  185461. if( p->in.iNext>=p->in.nData ){
  185462. return SQLITE_DONE;
  185463. }
  185464. sessionDiscardData(&p->in);
  185465. p->in.iCurrent = p->in.iNext;
  185466. op = p->in.aData[p->in.iNext++];
  185467. while( op=='T' || op=='P' ){
  185468. if( pbNew ) *pbNew = 1;
  185469. p->bPatchset = (op=='P');
  185470. if( sessionChangesetReadTblhdr(p) ) return p->rc;
  185471. if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
  185472. p->in.iCurrent = p->in.iNext;
  185473. if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
  185474. op = p->in.aData[p->in.iNext++];
  185475. }
  185476. if( p->zTab==0 || (p->bPatchset && p->bInvert) ){
  185477. /* The first record in the changeset is not a table header. Must be a
  185478. ** corrupt changeset. */
  185479. assert( p->in.iNext==1 || p->zTab );
  185480. return (p->rc = SQLITE_CORRUPT_BKPT);
  185481. }
  185482. p->op = op;
  185483. p->bIndirect = p->in.aData[p->in.iNext++];
  185484. if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
  185485. return (p->rc = SQLITE_CORRUPT_BKPT);
  185486. }
  185487. if( paRec ){
  185488. int nVal; /* Number of values to buffer */
  185489. if( p->bPatchset==0 && op==SQLITE_UPDATE ){
  185490. nVal = p->nCol * 2;
  185491. }else if( p->bPatchset && op==SQLITE_DELETE ){
  185492. nVal = 0;
  185493. for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
  185494. }else{
  185495. nVal = p->nCol;
  185496. }
  185497. p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
  185498. if( p->rc!=SQLITE_OK ) return p->rc;
  185499. *paRec = &p->in.aData[p->in.iNext];
  185500. p->in.iNext += *pnRec;
  185501. }else{
  185502. sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue);
  185503. sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]);
  185504. /* If this is an UPDATE or DELETE, read the old.* record. */
  185505. if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
  185506. u8 *abPK = p->bPatchset ? p->abPK : 0;
  185507. p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld);
  185508. if( p->rc!=SQLITE_OK ) return p->rc;
  185509. }
  185510. /* If this is an INSERT or UPDATE, read the new.* record. */
  185511. if( p->op!=SQLITE_DELETE ){
  185512. p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew);
  185513. if( p->rc!=SQLITE_OK ) return p->rc;
  185514. }
  185515. if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){
  185516. /* If this is an UPDATE that is part of a patchset, then all PK and
  185517. ** modified fields are present in the new.* record. The old.* record
  185518. ** is currently completely empty. This block shifts the PK fields from
  185519. ** new.* to old.*, to accommodate the code that reads these arrays. */
  185520. for(i=0; i<p->nCol; i++){
  185521. assert( p->bPatchset==0 || p->apValue[i]==0 );
  185522. if( p->abPK[i] ){
  185523. assert( p->apValue[i]==0 );
  185524. p->apValue[i] = p->apValue[i+p->nCol];
  185525. if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
  185526. p->apValue[i+p->nCol] = 0;
  185527. }
  185528. }
  185529. }else if( p->bInvert ){
  185530. if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE;
  185531. else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT;
  185532. }
  185533. }
  185534. return SQLITE_ROW;
  185535. }
  185536. /*
  185537. ** Advance an iterator created by sqlite3changeset_start() to the next
  185538. ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
  185539. ** or SQLITE_CORRUPT.
  185540. **
  185541. ** This function may not be called on iterators passed to a conflict handler
  185542. ** callback by changeset_apply().
  185543. */
  185544. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
  185545. return sessionChangesetNext(p, 0, 0, 0);
  185546. }
  185547. /*
  185548. ** The following function extracts information on the current change
  185549. ** from a changeset iterator. It may only be called after changeset_next()
  185550. ** has returned SQLITE_ROW.
  185551. */
  185552. SQLITE_API int sqlite3changeset_op(
  185553. sqlite3_changeset_iter *pIter, /* Iterator handle */
  185554. const char **pzTab, /* OUT: Pointer to table name */
  185555. int *pnCol, /* OUT: Number of columns in table */
  185556. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  185557. int *pbIndirect /* OUT: True if change is indirect */
  185558. ){
  185559. *pOp = pIter->op;
  185560. *pnCol = pIter->nCol;
  185561. *pzTab = pIter->zTab;
  185562. if( pbIndirect ) *pbIndirect = pIter->bIndirect;
  185563. return SQLITE_OK;
  185564. }
  185565. /*
  185566. ** Return information regarding the PRIMARY KEY and number of columns in
  185567. ** the database table affected by the change that pIter currently points
  185568. ** to. This function may only be called after changeset_next() returns
  185569. ** SQLITE_ROW.
  185570. */
  185571. SQLITE_API int sqlite3changeset_pk(
  185572. sqlite3_changeset_iter *pIter, /* Iterator object */
  185573. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  185574. int *pnCol /* OUT: Number of entries in output array */
  185575. ){
  185576. *pabPK = pIter->abPK;
  185577. if( pnCol ) *pnCol = pIter->nCol;
  185578. return SQLITE_OK;
  185579. }
  185580. /*
  185581. ** This function may only be called while the iterator is pointing to an
  185582. ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
  185583. ** Otherwise, SQLITE_MISUSE is returned.
  185584. **
  185585. ** It sets *ppValue to point to an sqlite3_value structure containing the
  185586. ** iVal'th value in the old.* record. Or, if that particular value is not
  185587. ** included in the record (because the change is an UPDATE and the field
  185588. ** was not modified and is not a PK column), set *ppValue to NULL.
  185589. **
  185590. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  185591. ** not modified. Otherwise, SQLITE_OK.
  185592. */
  185593. SQLITE_API int sqlite3changeset_old(
  185594. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  185595. int iVal, /* Index of old.* value to retrieve */
  185596. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  185597. ){
  185598. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
  185599. return SQLITE_MISUSE;
  185600. }
  185601. if( iVal<0 || iVal>=pIter->nCol ){
  185602. return SQLITE_RANGE;
  185603. }
  185604. *ppValue = pIter->apValue[iVal];
  185605. return SQLITE_OK;
  185606. }
  185607. /*
  185608. ** This function may only be called while the iterator is pointing to an
  185609. ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
  185610. ** Otherwise, SQLITE_MISUSE is returned.
  185611. **
  185612. ** It sets *ppValue to point to an sqlite3_value structure containing the
  185613. ** iVal'th value in the new.* record. Or, if that particular value is not
  185614. ** included in the record (because the change is an UPDATE and the field
  185615. ** was not modified), set *ppValue to NULL.
  185616. **
  185617. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  185618. ** not modified. Otherwise, SQLITE_OK.
  185619. */
  185620. SQLITE_API int sqlite3changeset_new(
  185621. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  185622. int iVal, /* Index of new.* value to retrieve */
  185623. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  185624. ){
  185625. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
  185626. return SQLITE_MISUSE;
  185627. }
  185628. if( iVal<0 || iVal>=pIter->nCol ){
  185629. return SQLITE_RANGE;
  185630. }
  185631. *ppValue = pIter->apValue[pIter->nCol+iVal];
  185632. return SQLITE_OK;
  185633. }
  185634. /*
  185635. ** The following two macros are used internally. They are similar to the
  185636. ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
  185637. ** they omit all error checking and return a pointer to the requested value.
  185638. */
  185639. #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
  185640. #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
  185641. /*
  185642. ** This function may only be called with a changeset iterator that has been
  185643. ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
  185644. ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
  185645. **
  185646. ** If successful, *ppValue is set to point to an sqlite3_value structure
  185647. ** containing the iVal'th value of the conflicting record.
  185648. **
  185649. ** If value iVal is out-of-range or some other error occurs, an SQLite error
  185650. ** code is returned. Otherwise, SQLITE_OK.
  185651. */
  185652. SQLITE_API int sqlite3changeset_conflict(
  185653. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  185654. int iVal, /* Index of conflict record value to fetch */
  185655. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  185656. ){
  185657. if( !pIter->pConflict ){
  185658. return SQLITE_MISUSE;
  185659. }
  185660. if( iVal<0 || iVal>=pIter->nCol ){
  185661. return SQLITE_RANGE;
  185662. }
  185663. *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
  185664. return SQLITE_OK;
  185665. }
  185666. /*
  185667. ** This function may only be called with an iterator passed to an
  185668. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  185669. ** it sets the output variable to the total number of known foreign key
  185670. ** violations in the destination database and returns SQLITE_OK.
  185671. **
  185672. ** In all other cases this function returns SQLITE_MISUSE.
  185673. */
  185674. SQLITE_API int sqlite3changeset_fk_conflicts(
  185675. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  185676. int *pnOut /* OUT: Number of FK violations */
  185677. ){
  185678. if( pIter->pConflict || pIter->apValue ){
  185679. return SQLITE_MISUSE;
  185680. }
  185681. *pnOut = pIter->nCol;
  185682. return SQLITE_OK;
  185683. }
  185684. /*
  185685. ** Finalize an iterator allocated with sqlite3changeset_start().
  185686. **
  185687. ** This function may not be called on iterators passed to a conflict handler
  185688. ** callback by changeset_apply().
  185689. */
  185690. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
  185691. int rc = SQLITE_OK;
  185692. if( p ){
  185693. int i; /* Used to iterate through p->apValue[] */
  185694. rc = p->rc;
  185695. if( p->apValue ){
  185696. for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
  185697. }
  185698. sqlite3_free(p->tblhdr.aBuf);
  185699. sqlite3_free(p->in.buf.aBuf);
  185700. sqlite3_free(p);
  185701. }
  185702. return rc;
  185703. }
  185704. static int sessionChangesetInvert(
  185705. SessionInput *pInput, /* Input changeset */
  185706. int (*xOutput)(void *pOut, const void *pData, int nData),
  185707. void *pOut,
  185708. int *pnInverted, /* OUT: Number of bytes in output changeset */
  185709. void **ppInverted /* OUT: Inverse of pChangeset */
  185710. ){
  185711. int rc = SQLITE_OK; /* Return value */
  185712. SessionBuffer sOut; /* Output buffer */
  185713. int nCol = 0; /* Number of cols in current table */
  185714. u8 *abPK = 0; /* PK array for current table */
  185715. sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
  185716. SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
  185717. /* Initialize the output buffer */
  185718. memset(&sOut, 0, sizeof(SessionBuffer));
  185719. /* Zero the output variables in case an error occurs. */
  185720. if( ppInverted ){
  185721. *ppInverted = 0;
  185722. *pnInverted = 0;
  185723. }
  185724. while( 1 ){
  185725. u8 eType;
  185726. /* Test for EOF. */
  185727. if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
  185728. if( pInput->iNext>=pInput->nData ) break;
  185729. eType = pInput->aData[pInput->iNext];
  185730. switch( eType ){
  185731. case 'T': {
  185732. /* A 'table' record consists of:
  185733. **
  185734. ** * A constant 'T' character,
  185735. ** * Number of columns in said table (a varint),
  185736. ** * An array of nCol bytes (sPK),
  185737. ** * A nul-terminated table name.
  185738. */
  185739. int nByte;
  185740. int nVar;
  185741. pInput->iNext++;
  185742. if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
  185743. goto finished_invert;
  185744. }
  185745. nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
  185746. sPK.nBuf = 0;
  185747. sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
  185748. sessionAppendByte(&sOut, eType, &rc);
  185749. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  185750. if( rc ) goto finished_invert;
  185751. pInput->iNext += nByte;
  185752. sqlite3_free(apVal);
  185753. apVal = 0;
  185754. abPK = sPK.aBuf;
  185755. break;
  185756. }
  185757. case SQLITE_INSERT:
  185758. case SQLITE_DELETE: {
  185759. int nByte;
  185760. int bIndirect = pInput->aData[pInput->iNext+1];
  185761. int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
  185762. pInput->iNext += 2;
  185763. assert( rc==SQLITE_OK );
  185764. rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
  185765. sessionAppendByte(&sOut, eType2, &rc);
  185766. sessionAppendByte(&sOut, bIndirect, &rc);
  185767. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  185768. pInput->iNext += nByte;
  185769. if( rc ) goto finished_invert;
  185770. break;
  185771. }
  185772. case SQLITE_UPDATE: {
  185773. int iCol;
  185774. if( 0==apVal ){
  185775. apVal = (sqlite3_value **)sqlite3_malloc64(sizeof(apVal[0])*nCol*2);
  185776. if( 0==apVal ){
  185777. rc = SQLITE_NOMEM;
  185778. goto finished_invert;
  185779. }
  185780. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  185781. }
  185782. /* Write the header for the new UPDATE change. Same as the original. */
  185783. sessionAppendByte(&sOut, eType, &rc);
  185784. sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
  185785. /* Read the old.* and new.* records for the update change. */
  185786. pInput->iNext += 2;
  185787. rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
  185788. if( rc==SQLITE_OK ){
  185789. rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
  185790. }
  185791. /* Write the new old.* record. Consists of the PK columns from the
  185792. ** original old.* record, and the other values from the original
  185793. ** new.* record. */
  185794. for(iCol=0; iCol<nCol; iCol++){
  185795. sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
  185796. sessionAppendValue(&sOut, pVal, &rc);
  185797. }
  185798. /* Write the new new.* record. Consists of a copy of all values
  185799. ** from the original old.* record, except for the PK columns, which
  185800. ** are set to "undefined". */
  185801. for(iCol=0; iCol<nCol; iCol++){
  185802. sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
  185803. sessionAppendValue(&sOut, pVal, &rc);
  185804. }
  185805. for(iCol=0; iCol<nCol*2; iCol++){
  185806. sqlite3ValueFree(apVal[iCol]);
  185807. }
  185808. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  185809. if( rc!=SQLITE_OK ){
  185810. goto finished_invert;
  185811. }
  185812. break;
  185813. }
  185814. default:
  185815. rc = SQLITE_CORRUPT_BKPT;
  185816. goto finished_invert;
  185817. }
  185818. assert( rc==SQLITE_OK );
  185819. if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){
  185820. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  185821. sOut.nBuf = 0;
  185822. if( rc!=SQLITE_OK ) goto finished_invert;
  185823. }
  185824. }
  185825. assert( rc==SQLITE_OK );
  185826. if( pnInverted ){
  185827. *pnInverted = sOut.nBuf;
  185828. *ppInverted = sOut.aBuf;
  185829. sOut.aBuf = 0;
  185830. }else if( sOut.nBuf>0 ){
  185831. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  185832. }
  185833. finished_invert:
  185834. sqlite3_free(sOut.aBuf);
  185835. sqlite3_free(apVal);
  185836. sqlite3_free(sPK.aBuf);
  185837. return rc;
  185838. }
  185839. /*
  185840. ** Invert a changeset object.
  185841. */
  185842. SQLITE_API int sqlite3changeset_invert(
  185843. int nChangeset, /* Number of bytes in input */
  185844. const void *pChangeset, /* Input changeset */
  185845. int *pnInverted, /* OUT: Number of bytes in output changeset */
  185846. void **ppInverted /* OUT: Inverse of pChangeset */
  185847. ){
  185848. SessionInput sInput;
  185849. /* Set up the input stream */
  185850. memset(&sInput, 0, sizeof(SessionInput));
  185851. sInput.nData = nChangeset;
  185852. sInput.aData = (u8*)pChangeset;
  185853. return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
  185854. }
  185855. /*
  185856. ** Streaming version of sqlite3changeset_invert().
  185857. */
  185858. SQLITE_API int sqlite3changeset_invert_strm(
  185859. int (*xInput)(void *pIn, void *pData, int *pnData),
  185860. void *pIn,
  185861. int (*xOutput)(void *pOut, const void *pData, int nData),
  185862. void *pOut
  185863. ){
  185864. SessionInput sInput;
  185865. int rc;
  185866. /* Set up the input stream */
  185867. memset(&sInput, 0, sizeof(SessionInput));
  185868. sInput.xInput = xInput;
  185869. sInput.pIn = pIn;
  185870. rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
  185871. sqlite3_free(sInput.buf.aBuf);
  185872. return rc;
  185873. }
  185874. typedef struct SessionApplyCtx SessionApplyCtx;
  185875. struct SessionApplyCtx {
  185876. sqlite3 *db;
  185877. sqlite3_stmt *pDelete; /* DELETE statement */
  185878. sqlite3_stmt *pUpdate; /* UPDATE statement */
  185879. sqlite3_stmt *pInsert; /* INSERT statement */
  185880. sqlite3_stmt *pSelect; /* SELECT statement */
  185881. int nCol; /* Size of azCol[] and abPK[] arrays */
  185882. const char **azCol; /* Array of column names */
  185883. u8 *abPK; /* Boolean array - true if column is in PK */
  185884. int bStat1; /* True if table is sqlite_stat1 */
  185885. int bDeferConstraints; /* True to defer constraints */
  185886. SessionBuffer constraints; /* Deferred constraints are stored here */
  185887. SessionBuffer rebase; /* Rebase information (if any) here */
  185888. u8 bRebaseStarted; /* If table header is already in rebase */
  185889. u8 bRebase; /* True to collect rebase information */
  185890. };
  185891. /*
  185892. ** Formulate a statement to DELETE a row from database db. Assuming a table
  185893. ** structure like this:
  185894. **
  185895. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  185896. **
  185897. ** The DELETE statement looks like this:
  185898. **
  185899. ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
  185900. **
  185901. ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
  185902. ** matching b and d values, or 1 otherwise. The second case comes up if the
  185903. ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
  185904. **
  185905. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
  185906. ** pointing to the prepared version of the SQL statement.
  185907. */
  185908. static int sessionDeleteRow(
  185909. sqlite3 *db, /* Database handle */
  185910. const char *zTab, /* Table name */
  185911. SessionApplyCtx *p /* Session changeset-apply context */
  185912. ){
  185913. int i;
  185914. const char *zSep = "";
  185915. int rc = SQLITE_OK;
  185916. SessionBuffer buf = {0, 0, 0};
  185917. int nPk = 0;
  185918. sessionAppendStr(&buf, "DELETE FROM ", &rc);
  185919. sessionAppendIdent(&buf, zTab, &rc);
  185920. sessionAppendStr(&buf, " WHERE ", &rc);
  185921. for(i=0; i<p->nCol; i++){
  185922. if( p->abPK[i] ){
  185923. nPk++;
  185924. sessionAppendStr(&buf, zSep, &rc);
  185925. sessionAppendIdent(&buf, p->azCol[i], &rc);
  185926. sessionAppendStr(&buf, " = ?", &rc);
  185927. sessionAppendInteger(&buf, i+1, &rc);
  185928. zSep = " AND ";
  185929. }
  185930. }
  185931. if( nPk<p->nCol ){
  185932. sessionAppendStr(&buf, " AND (?", &rc);
  185933. sessionAppendInteger(&buf, p->nCol+1, &rc);
  185934. sessionAppendStr(&buf, " OR ", &rc);
  185935. zSep = "";
  185936. for(i=0; i<p->nCol; i++){
  185937. if( !p->abPK[i] ){
  185938. sessionAppendStr(&buf, zSep, &rc);
  185939. sessionAppendIdent(&buf, p->azCol[i], &rc);
  185940. sessionAppendStr(&buf, " IS ?", &rc);
  185941. sessionAppendInteger(&buf, i+1, &rc);
  185942. zSep = "AND ";
  185943. }
  185944. }
  185945. sessionAppendStr(&buf, ")", &rc);
  185946. }
  185947. if( rc==SQLITE_OK ){
  185948. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
  185949. }
  185950. sqlite3_free(buf.aBuf);
  185951. return rc;
  185952. }
  185953. /*
  185954. ** Formulate and prepare a statement to UPDATE a row from database db.
  185955. ** Assuming a table structure like this:
  185956. **
  185957. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  185958. **
  185959. ** The UPDATE statement looks like this:
  185960. **
  185961. ** UPDATE x SET
  185962. ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
  185963. ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
  185964. ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
  185965. ** d = CASE WHEN ?11 THEN ?12 ELSE d END
  185966. ** WHERE a = ?1 AND c = ?7 AND (?13 OR
  185967. ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
  185968. ** )
  185969. **
  185970. ** For each column in the table, there are three variables to bind:
  185971. **
  185972. ** ?(i*3+1) The old.* value of the column, if any.
  185973. ** ?(i*3+2) A boolean flag indicating that the value is being modified.
  185974. ** ?(i*3+3) The new.* value of the column, if any.
  185975. **
  185976. ** Also, a boolean flag that, if set to true, causes the statement to update
  185977. ** a row even if the non-PK values do not match. This is required if the
  185978. ** conflict-handler is invoked with CHANGESET_DATA and returns
  185979. ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
  185980. **
  185981. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
  185982. ** pointing to the prepared version of the SQL statement.
  185983. */
  185984. static int sessionUpdateRow(
  185985. sqlite3 *db, /* Database handle */
  185986. const char *zTab, /* Table name */
  185987. SessionApplyCtx *p /* Session changeset-apply context */
  185988. ){
  185989. int rc = SQLITE_OK;
  185990. int i;
  185991. const char *zSep = "";
  185992. SessionBuffer buf = {0, 0, 0};
  185993. /* Append "UPDATE tbl SET " */
  185994. sessionAppendStr(&buf, "UPDATE ", &rc);
  185995. sessionAppendIdent(&buf, zTab, &rc);
  185996. sessionAppendStr(&buf, " SET ", &rc);
  185997. /* Append the assignments */
  185998. for(i=0; i<p->nCol; i++){
  185999. sessionAppendStr(&buf, zSep, &rc);
  186000. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186001. sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
  186002. sessionAppendInteger(&buf, i*3+2, &rc);
  186003. sessionAppendStr(&buf, " THEN ?", &rc);
  186004. sessionAppendInteger(&buf, i*3+3, &rc);
  186005. sessionAppendStr(&buf, " ELSE ", &rc);
  186006. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186007. sessionAppendStr(&buf, " END", &rc);
  186008. zSep = ", ";
  186009. }
  186010. /* Append the PK part of the WHERE clause */
  186011. sessionAppendStr(&buf, " WHERE ", &rc);
  186012. for(i=0; i<p->nCol; i++){
  186013. if( p->abPK[i] ){
  186014. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186015. sessionAppendStr(&buf, " = ?", &rc);
  186016. sessionAppendInteger(&buf, i*3+1, &rc);
  186017. sessionAppendStr(&buf, " AND ", &rc);
  186018. }
  186019. }
  186020. /* Append the non-PK part of the WHERE clause */
  186021. sessionAppendStr(&buf, " (?", &rc);
  186022. sessionAppendInteger(&buf, p->nCol*3+1, &rc);
  186023. sessionAppendStr(&buf, " OR 1", &rc);
  186024. for(i=0; i<p->nCol; i++){
  186025. if( !p->abPK[i] ){
  186026. sessionAppendStr(&buf, " AND (?", &rc);
  186027. sessionAppendInteger(&buf, i*3+2, &rc);
  186028. sessionAppendStr(&buf, "=0 OR ", &rc);
  186029. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186030. sessionAppendStr(&buf, " IS ?", &rc);
  186031. sessionAppendInteger(&buf, i*3+1, &rc);
  186032. sessionAppendStr(&buf, ")", &rc);
  186033. }
  186034. }
  186035. sessionAppendStr(&buf, ")", &rc);
  186036. if( rc==SQLITE_OK ){
  186037. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
  186038. }
  186039. sqlite3_free(buf.aBuf);
  186040. return rc;
  186041. }
  186042. /*
  186043. ** Formulate and prepare an SQL statement to query table zTab by primary
  186044. ** key. Assuming the following table structure:
  186045. **
  186046. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  186047. **
  186048. ** The SELECT statement looks like this:
  186049. **
  186050. ** SELECT * FROM x WHERE a = ?1 AND c = ?3
  186051. **
  186052. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
  186053. ** pointing to the prepared version of the SQL statement.
  186054. */
  186055. static int sessionSelectRow(
  186056. sqlite3 *db, /* Database handle */
  186057. const char *zTab, /* Table name */
  186058. SessionApplyCtx *p /* Session changeset-apply context */
  186059. ){
  186060. return sessionSelectStmt(
  186061. db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
  186062. }
  186063. /*
  186064. ** Formulate and prepare an INSERT statement to add a record to table zTab.
  186065. ** For example:
  186066. **
  186067. ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
  186068. **
  186069. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
  186070. ** pointing to the prepared version of the SQL statement.
  186071. */
  186072. static int sessionInsertRow(
  186073. sqlite3 *db, /* Database handle */
  186074. const char *zTab, /* Table name */
  186075. SessionApplyCtx *p /* Session changeset-apply context */
  186076. ){
  186077. int rc = SQLITE_OK;
  186078. int i;
  186079. SessionBuffer buf = {0, 0, 0};
  186080. sessionAppendStr(&buf, "INSERT INTO main.", &rc);
  186081. sessionAppendIdent(&buf, zTab, &rc);
  186082. sessionAppendStr(&buf, "(", &rc);
  186083. for(i=0; i<p->nCol; i++){
  186084. if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
  186085. sessionAppendIdent(&buf, p->azCol[i], &rc);
  186086. }
  186087. sessionAppendStr(&buf, ") VALUES(?", &rc);
  186088. for(i=1; i<p->nCol; i++){
  186089. sessionAppendStr(&buf, ", ?", &rc);
  186090. }
  186091. sessionAppendStr(&buf, ")", &rc);
  186092. if( rc==SQLITE_OK ){
  186093. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
  186094. }
  186095. sqlite3_free(buf.aBuf);
  186096. return rc;
  186097. }
  186098. static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
  186099. return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
  186100. }
  186101. /*
  186102. ** Prepare statements for applying changes to the sqlite_stat1 table.
  186103. ** These are similar to those created by sessionSelectRow(),
  186104. ** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
  186105. ** other tables.
  186106. */
  186107. static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
  186108. int rc = sessionSelectRow(db, "sqlite_stat1", p);
  186109. if( rc==SQLITE_OK ){
  186110. rc = sessionPrepare(db, &p->pInsert,
  186111. "INSERT INTO main.sqlite_stat1 VALUES(?1, "
  186112. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
  186113. "?3)"
  186114. );
  186115. }
  186116. if( rc==SQLITE_OK ){
  186117. rc = sessionPrepare(db, &p->pUpdate,
  186118. "UPDATE main.sqlite_stat1 SET "
  186119. "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, "
  186120. "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, "
  186121. "stat = CASE WHEN ?8 THEN ?9 ELSE stat END "
  186122. "WHERE tbl=?1 AND idx IS "
  186123. "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END "
  186124. "AND (?10 OR ?8=0 OR stat IS ?7)"
  186125. );
  186126. }
  186127. if( rc==SQLITE_OK ){
  186128. rc = sessionPrepare(db, &p->pDelete,
  186129. "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
  186130. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
  186131. "AND (?4 OR stat IS ?3)"
  186132. );
  186133. }
  186134. return rc;
  186135. }
  186136. /*
  186137. ** A wrapper around sqlite3_bind_value() that detects an extra problem.
  186138. ** See comments in the body of this function for details.
  186139. */
  186140. static int sessionBindValue(
  186141. sqlite3_stmt *pStmt, /* Statement to bind value to */
  186142. int i, /* Parameter number to bind to */
  186143. sqlite3_value *pVal /* Value to bind */
  186144. ){
  186145. int eType = sqlite3_value_type(pVal);
  186146. /* COVERAGE: The (pVal->z==0) branch is never true using current versions
  186147. ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
  186148. ** the (pVal->z) variable remains as it was or the type of the value is
  186149. ** set to SQLITE_NULL. */
  186150. if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
  186151. /* This condition occurs when an earlier OOM in a call to
  186152. ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
  186153. ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
  186154. return SQLITE_NOMEM;
  186155. }
  186156. return sqlite3_bind_value(pStmt, i, pVal);
  186157. }
  186158. /*
  186159. ** Iterator pIter must point to an SQLITE_INSERT entry. This function
  186160. ** transfers new.* values from the current iterator entry to statement
  186161. ** pStmt. The table being inserted into has nCol columns.
  186162. **
  186163. ** New.* value $i from the iterator is bound to variable ($i+1) of
  186164. ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
  186165. ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
  186166. ** to an array nCol elements in size. In this case only those values for
  186167. ** which abPK[$i] is true are read from the iterator and bound to the
  186168. ** statement.
  186169. **
  186170. ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
  186171. */
  186172. static int sessionBindRow(
  186173. sqlite3_changeset_iter *pIter, /* Iterator to read values from */
  186174. int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
  186175. int nCol, /* Number of columns */
  186176. u8 *abPK, /* If not NULL, bind only if true */
  186177. sqlite3_stmt *pStmt /* Bind values to this statement */
  186178. ){
  186179. int i;
  186180. int rc = SQLITE_OK;
  186181. /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
  186182. ** argument iterator points to a suitable entry. Make sure that xValue
  186183. ** is one of these to guarantee that it is safe to ignore the return
  186184. ** in the code below. */
  186185. assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
  186186. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  186187. if( !abPK || abPK[i] ){
  186188. sqlite3_value *pVal;
  186189. (void)xValue(pIter, i, &pVal);
  186190. if( pVal==0 ){
  186191. /* The value in the changeset was "undefined". This indicates a
  186192. ** corrupt changeset blob. */
  186193. rc = SQLITE_CORRUPT_BKPT;
  186194. }else{
  186195. rc = sessionBindValue(pStmt, i+1, pVal);
  186196. }
  186197. }
  186198. }
  186199. return rc;
  186200. }
  186201. /*
  186202. ** SQL statement pSelect is as generated by the sessionSelectRow() function.
  186203. ** This function binds the primary key values from the change that changeset
  186204. ** iterator pIter points to to the SELECT and attempts to seek to the table
  186205. ** entry. If a row is found, the SELECT statement left pointing at the row
  186206. ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
  186207. ** has occured, the statement is reset and SQLITE_OK is returned. If an
  186208. ** error occurs, the statement is reset and an SQLite error code is returned.
  186209. **
  186210. ** If this function returns SQLITE_ROW, the caller must eventually reset()
  186211. ** statement pSelect. If any other value is returned, the statement does
  186212. ** not require a reset().
  186213. **
  186214. ** If the iterator currently points to an INSERT record, bind values from the
  186215. ** new.* record to the SELECT statement. Or, if it points to a DELETE or
  186216. ** UPDATE, bind values from the old.* record.
  186217. */
  186218. static int sessionSeekToRow(
  186219. sqlite3 *db, /* Database handle */
  186220. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  186221. u8 *abPK, /* Primary key flags array */
  186222. sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
  186223. ){
  186224. int rc; /* Return code */
  186225. int nCol; /* Number of columns in table */
  186226. int op; /* Changset operation (SQLITE_UPDATE etc.) */
  186227. const char *zDummy; /* Unused */
  186228. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  186229. rc = sessionBindRow(pIter,
  186230. op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
  186231. nCol, abPK, pSelect
  186232. );
  186233. if( rc==SQLITE_OK ){
  186234. rc = sqlite3_step(pSelect);
  186235. if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
  186236. }
  186237. return rc;
  186238. }
  186239. /*
  186240. ** This function is called from within sqlite3changeset_apply_v2() when
  186241. ** a conflict is encountered and resolved using conflict resolution
  186242. ** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
  186243. ** It adds a conflict resolution record to the buffer in
  186244. ** SessionApplyCtx.rebase, which will eventually be returned to the caller
  186245. ** of apply_v2() as the "rebase" buffer.
  186246. **
  186247. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  186248. */
  186249. static int sessionRebaseAdd(
  186250. SessionApplyCtx *p, /* Apply context */
  186251. int eType, /* Conflict resolution (OMIT or REPLACE) */
  186252. sqlite3_changeset_iter *pIter /* Iterator pointing at current change */
  186253. ){
  186254. int rc = SQLITE_OK;
  186255. if( p->bRebase ){
  186256. int i;
  186257. int eOp = pIter->op;
  186258. if( p->bRebaseStarted==0 ){
  186259. /* Append a table-header to the rebase buffer */
  186260. const char *zTab = pIter->zTab;
  186261. sessionAppendByte(&p->rebase, 'T', &rc);
  186262. sessionAppendVarint(&p->rebase, p->nCol, &rc);
  186263. sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);
  186264. sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);
  186265. p->bRebaseStarted = 1;
  186266. }
  186267. assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
  186268. assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
  186269. sessionAppendByte(&p->rebase,
  186270. (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
  186271. );
  186272. sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
  186273. for(i=0; i<p->nCol; i++){
  186274. sqlite3_value *pVal = 0;
  186275. if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){
  186276. sqlite3changeset_old(pIter, i, &pVal);
  186277. }else{
  186278. sqlite3changeset_new(pIter, i, &pVal);
  186279. }
  186280. sessionAppendValue(&p->rebase, pVal, &rc);
  186281. }
  186282. }
  186283. return rc;
  186284. }
  186285. /*
  186286. ** Invoke the conflict handler for the change that the changeset iterator
  186287. ** currently points to.
  186288. **
  186289. ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
  186290. ** If argument pbReplace is NULL, then the type of conflict handler invoked
  186291. ** depends solely on eType, as follows:
  186292. **
  186293. ** eType value Value passed to xConflict
  186294. ** -------------------------------------------------
  186295. ** CHANGESET_DATA CHANGESET_NOTFOUND
  186296. ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
  186297. **
  186298. ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
  186299. ** record with the same primary key as the record about to be deleted, updated
  186300. ** or inserted. If such a record can be found, it is available to the conflict
  186301. ** handler as the "conflicting" record. In this case the type of conflict
  186302. ** handler invoked is as follows:
  186303. **
  186304. ** eType value PK Record found? Value passed to xConflict
  186305. ** ----------------------------------------------------------------
  186306. ** CHANGESET_DATA Yes CHANGESET_DATA
  186307. ** CHANGESET_DATA No CHANGESET_NOTFOUND
  186308. ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
  186309. ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
  186310. **
  186311. ** If pbReplace is not NULL, and a record with a matching PK is found, and
  186312. ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
  186313. ** is set to non-zero before returning SQLITE_OK.
  186314. **
  186315. ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
  186316. ** returned. Or, if the conflict handler returns an invalid value,
  186317. ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
  186318. ** this function returns SQLITE_OK.
  186319. */
  186320. static int sessionConflictHandler(
  186321. int eType, /* Either CHANGESET_DATA or CONFLICT */
  186322. SessionApplyCtx *p, /* changeset_apply() context */
  186323. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  186324. int(*xConflict)(void *, int, sqlite3_changeset_iter*),
  186325. void *pCtx, /* First argument for conflict handler */
  186326. int *pbReplace /* OUT: Set to true if PK row is found */
  186327. ){
  186328. int res = 0; /* Value returned by conflict handler */
  186329. int rc;
  186330. int nCol;
  186331. int op;
  186332. const char *zDummy;
  186333. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  186334. assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
  186335. assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
  186336. assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
  186337. /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
  186338. if( pbReplace ){
  186339. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  186340. }else{
  186341. rc = SQLITE_OK;
  186342. }
  186343. if( rc==SQLITE_ROW ){
  186344. /* There exists another row with the new.* primary key. */
  186345. pIter->pConflict = p->pSelect;
  186346. res = xConflict(pCtx, eType, pIter);
  186347. pIter->pConflict = 0;
  186348. rc = sqlite3_reset(p->pSelect);
  186349. }else if( rc==SQLITE_OK ){
  186350. if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
  186351. /* Instead of invoking the conflict handler, append the change blob
  186352. ** to the SessionApplyCtx.constraints buffer. */
  186353. u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
  186354. int nBlob = pIter->in.iNext - pIter->in.iCurrent;
  186355. sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
  186356. return SQLITE_OK;
  186357. }else{
  186358. /* No other row with the new.* primary key. */
  186359. res = xConflict(pCtx, eType+1, pIter);
  186360. if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
  186361. }
  186362. }
  186363. if( rc==SQLITE_OK ){
  186364. switch( res ){
  186365. case SQLITE_CHANGESET_REPLACE:
  186366. assert( pbReplace );
  186367. *pbReplace = 1;
  186368. break;
  186369. case SQLITE_CHANGESET_OMIT:
  186370. break;
  186371. case SQLITE_CHANGESET_ABORT:
  186372. rc = SQLITE_ABORT;
  186373. break;
  186374. default:
  186375. rc = SQLITE_MISUSE;
  186376. break;
  186377. }
  186378. if( rc==SQLITE_OK ){
  186379. rc = sessionRebaseAdd(p, res, pIter);
  186380. }
  186381. }
  186382. return rc;
  186383. }
  186384. /*
  186385. ** Attempt to apply the change that the iterator passed as the first argument
  186386. ** currently points to to the database. If a conflict is encountered, invoke
  186387. ** the conflict handler callback.
  186388. **
  186389. ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
  186390. ** one is encountered, update or delete the row with the matching primary key
  186391. ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
  186392. ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
  186393. ** to true before returning. In this case the caller will invoke this function
  186394. ** again, this time with pbRetry set to NULL.
  186395. **
  186396. ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
  186397. ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
  186398. ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
  186399. ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
  186400. ** before retrying. In this case the caller attempts to remove the conflicting
  186401. ** row before invoking this function again, this time with pbReplace set
  186402. ** to NULL.
  186403. **
  186404. ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
  186405. ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
  186406. ** returned.
  186407. */
  186408. static int sessionApplyOneOp(
  186409. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  186410. SessionApplyCtx *p, /* changeset_apply() context */
  186411. int(*xConflict)(void *, int, sqlite3_changeset_iter *),
  186412. void *pCtx, /* First argument for the conflict handler */
  186413. int *pbReplace, /* OUT: True to remove PK row and retry */
  186414. int *pbRetry /* OUT: True to retry. */
  186415. ){
  186416. const char *zDummy;
  186417. int op;
  186418. int nCol;
  186419. int rc = SQLITE_OK;
  186420. assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
  186421. assert( p->azCol && p->abPK );
  186422. assert( !pbReplace || *pbReplace==0 );
  186423. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  186424. if( op==SQLITE_DELETE ){
  186425. /* Bind values to the DELETE statement. If conflict handling is required,
  186426. ** bind values for all columns and set bound variable (nCol+1) to true.
  186427. ** Or, if conflict handling is not required, bind just the PK column
  186428. ** values and, if it exists, set (nCol+1) to false. Conflict handling
  186429. ** is not required if:
  186430. **
  186431. ** * this is a patchset, or
  186432. ** * (pbRetry==0), or
  186433. ** * all columns of the table are PK columns (in this case there is
  186434. ** no (nCol+1) variable to bind to).
  186435. */
  186436. u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
  186437. rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
  186438. if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
  186439. rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
  186440. }
  186441. if( rc!=SQLITE_OK ) return rc;
  186442. sqlite3_step(p->pDelete);
  186443. rc = sqlite3_reset(p->pDelete);
  186444. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  186445. rc = sessionConflictHandler(
  186446. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  186447. );
  186448. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  186449. rc = sessionConflictHandler(
  186450. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  186451. );
  186452. }
  186453. }else if( op==SQLITE_UPDATE ){
  186454. int i;
  186455. /* Bind values to the UPDATE statement. */
  186456. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  186457. sqlite3_value *pOld = sessionChangesetOld(pIter, i);
  186458. sqlite3_value *pNew = sessionChangesetNew(pIter, i);
  186459. sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
  186460. if( pOld ){
  186461. rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
  186462. }
  186463. if( rc==SQLITE_OK && pNew ){
  186464. rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
  186465. }
  186466. }
  186467. if( rc==SQLITE_OK ){
  186468. sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
  186469. }
  186470. if( rc!=SQLITE_OK ) return rc;
  186471. /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
  186472. ** the result will be SQLITE_OK with 0 rows modified. */
  186473. sqlite3_step(p->pUpdate);
  186474. rc = sqlite3_reset(p->pUpdate);
  186475. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  186476. /* A NOTFOUND or DATA error. Search the table to see if it contains
  186477. ** a row with a matching primary key. If so, this is a DATA conflict.
  186478. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
  186479. rc = sessionConflictHandler(
  186480. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  186481. );
  186482. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  186483. /* This is always a CONSTRAINT conflict. */
  186484. rc = sessionConflictHandler(
  186485. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  186486. );
  186487. }
  186488. }else{
  186489. assert( op==SQLITE_INSERT );
  186490. if( p->bStat1 ){
  186491. /* Check if there is a conflicting row. For sqlite_stat1, this needs
  186492. ** to be done using a SELECT, as there is no PRIMARY KEY in the
  186493. ** database schema to throw an exception if a duplicate is inserted. */
  186494. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  186495. if( rc==SQLITE_ROW ){
  186496. rc = SQLITE_CONSTRAINT;
  186497. sqlite3_reset(p->pSelect);
  186498. }
  186499. }
  186500. if( rc==SQLITE_OK ){
  186501. rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
  186502. if( rc!=SQLITE_OK ) return rc;
  186503. sqlite3_step(p->pInsert);
  186504. rc = sqlite3_reset(p->pInsert);
  186505. }
  186506. if( (rc&0xff)==SQLITE_CONSTRAINT ){
  186507. rc = sessionConflictHandler(
  186508. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
  186509. );
  186510. }
  186511. }
  186512. return rc;
  186513. }
  186514. /*
  186515. ** Attempt to apply the change that the iterator passed as the first argument
  186516. ** currently points to to the database. If a conflict is encountered, invoke
  186517. ** the conflict handler callback.
  186518. **
  186519. ** The difference between this function and sessionApplyOne() is that this
  186520. ** function handles the case where the conflict-handler is invoked and
  186521. ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
  186522. ** retried in some manner.
  186523. */
  186524. static int sessionApplyOneWithRetry(
  186525. sqlite3 *db, /* Apply change to "main" db of this handle */
  186526. sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
  186527. SessionApplyCtx *pApply, /* Apply context */
  186528. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  186529. void *pCtx /* First argument passed to xConflict */
  186530. ){
  186531. int bReplace = 0;
  186532. int bRetry = 0;
  186533. int rc;
  186534. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
  186535. if( rc==SQLITE_OK ){
  186536. /* If the bRetry flag is set, the change has not been applied due to an
  186537. ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
  186538. ** a row with the correct PK is present in the db, but one or more other
  186539. ** fields do not contain the expected values) and the conflict handler
  186540. ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
  186541. ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
  186542. ** the SQLITE_CHANGESET_DATA problem. */
  186543. if( bRetry ){
  186544. assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
  186545. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  186546. }
  186547. /* If the bReplace flag is set, the change is an INSERT that has not
  186548. ** been performed because the database already contains a row with the
  186549. ** specified primary key and the conflict handler returned
  186550. ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
  186551. ** before reattempting the INSERT. */
  186552. else if( bReplace ){
  186553. assert( pIter->op==SQLITE_INSERT );
  186554. rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
  186555. if( rc==SQLITE_OK ){
  186556. rc = sessionBindRow(pIter,
  186557. sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
  186558. sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
  186559. }
  186560. if( rc==SQLITE_OK ){
  186561. sqlite3_step(pApply->pDelete);
  186562. rc = sqlite3_reset(pApply->pDelete);
  186563. }
  186564. if( rc==SQLITE_OK ){
  186565. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  186566. }
  186567. if( rc==SQLITE_OK ){
  186568. rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
  186569. }
  186570. }
  186571. }
  186572. return rc;
  186573. }
  186574. /*
  186575. ** Retry the changes accumulated in the pApply->constraints buffer.
  186576. */
  186577. static int sessionRetryConstraints(
  186578. sqlite3 *db,
  186579. int bPatchset,
  186580. const char *zTab,
  186581. SessionApplyCtx *pApply,
  186582. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  186583. void *pCtx /* First argument passed to xConflict */
  186584. ){
  186585. int rc = SQLITE_OK;
  186586. while( pApply->constraints.nBuf ){
  186587. sqlite3_changeset_iter *pIter2 = 0;
  186588. SessionBuffer cons = pApply->constraints;
  186589. memset(&pApply->constraints, 0, sizeof(SessionBuffer));
  186590. rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf, 0);
  186591. if( rc==SQLITE_OK ){
  186592. size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
  186593. int rc2;
  186594. pIter2->bPatchset = bPatchset;
  186595. pIter2->zTab = (char*)zTab;
  186596. pIter2->nCol = pApply->nCol;
  186597. pIter2->abPK = pApply->abPK;
  186598. sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
  186599. pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
  186600. if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
  186601. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
  186602. rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
  186603. }
  186604. rc2 = sqlite3changeset_finalize(pIter2);
  186605. if( rc==SQLITE_OK ) rc = rc2;
  186606. }
  186607. assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
  186608. sqlite3_free(cons.aBuf);
  186609. if( rc!=SQLITE_OK ) break;
  186610. if( pApply->constraints.nBuf>=cons.nBuf ){
  186611. /* No progress was made on the last round. */
  186612. pApply->bDeferConstraints = 0;
  186613. }
  186614. }
  186615. return rc;
  186616. }
  186617. /*
  186618. ** Argument pIter is a changeset iterator that has been initialized, but
  186619. ** not yet passed to sqlite3changeset_next(). This function applies the
  186620. ** changeset to the main database attached to handle "db". The supplied
  186621. ** conflict handler callback is invoked to resolve any conflicts encountered
  186622. ** while applying the change.
  186623. */
  186624. static int sessionChangesetApply(
  186625. sqlite3 *db, /* Apply change to "main" db of this handle */
  186626. sqlite3_changeset_iter *pIter, /* Changeset to apply */
  186627. int(*xFilter)(
  186628. void *pCtx, /* Copy of sixth arg to _apply() */
  186629. const char *zTab /* Table name */
  186630. ),
  186631. int(*xConflict)(
  186632. void *pCtx, /* Copy of fifth arg to _apply() */
  186633. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  186634. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  186635. ),
  186636. void *pCtx, /* First argument passed to xConflict */
  186637. void **ppRebase, int *pnRebase, /* OUT: Rebase information */
  186638. int flags /* SESSION_APPLY_XXX flags */
  186639. ){
  186640. int schemaMismatch = 0;
  186641. int rc = SQLITE_OK; /* Return code */
  186642. const char *zTab = 0; /* Name of current table */
  186643. int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
  186644. SessionApplyCtx sApply; /* changeset_apply() context object */
  186645. int bPatchset;
  186646. assert( xConflict!=0 );
  186647. pIter->in.bNoDiscard = 1;
  186648. memset(&sApply, 0, sizeof(sApply));
  186649. sApply.bRebase = (ppRebase && pnRebase);
  186650. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  186651. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  186652. rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  186653. }
  186654. if( rc==SQLITE_OK ){
  186655. rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
  186656. }
  186657. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
  186658. int nCol;
  186659. int op;
  186660. const char *zNew;
  186661. sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
  186662. if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
  186663. u8 *abPK;
  186664. rc = sessionRetryConstraints(
  186665. db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
  186666. );
  186667. if( rc!=SQLITE_OK ) break;
  186668. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  186669. sqlite3_finalize(sApply.pDelete);
  186670. sqlite3_finalize(sApply.pUpdate);
  186671. sqlite3_finalize(sApply.pInsert);
  186672. sqlite3_finalize(sApply.pSelect);
  186673. sApply.db = db;
  186674. sApply.pDelete = 0;
  186675. sApply.pUpdate = 0;
  186676. sApply.pInsert = 0;
  186677. sApply.pSelect = 0;
  186678. sApply.nCol = 0;
  186679. sApply.azCol = 0;
  186680. sApply.abPK = 0;
  186681. sApply.bStat1 = 0;
  186682. sApply.bDeferConstraints = 1;
  186683. sApply.bRebaseStarted = 0;
  186684. memset(&sApply.constraints, 0, sizeof(SessionBuffer));
  186685. /* If an xFilter() callback was specified, invoke it now. If the
  186686. ** xFilter callback returns zero, skip this table. If it returns
  186687. ** non-zero, proceed. */
  186688. schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
  186689. if( schemaMismatch ){
  186690. zTab = sqlite3_mprintf("%s", zNew);
  186691. if( zTab==0 ){
  186692. rc = SQLITE_NOMEM;
  186693. break;
  186694. }
  186695. nTab = (int)strlen(zTab);
  186696. sApply.azCol = (const char **)zTab;
  186697. }else{
  186698. int nMinCol = 0;
  186699. int i;
  186700. sqlite3changeset_pk(pIter, &abPK, 0);
  186701. rc = sessionTableInfo(
  186702. db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
  186703. );
  186704. if( rc!=SQLITE_OK ) break;
  186705. for(i=0; i<sApply.nCol; i++){
  186706. if( sApply.abPK[i] ) nMinCol = i+1;
  186707. }
  186708. if( sApply.nCol==0 ){
  186709. schemaMismatch = 1;
  186710. sqlite3_log(SQLITE_SCHEMA,
  186711. "sqlite3changeset_apply(): no such table: %s", zTab
  186712. );
  186713. }
  186714. else if( sApply.nCol<nCol ){
  186715. schemaMismatch = 1;
  186716. sqlite3_log(SQLITE_SCHEMA,
  186717. "sqlite3changeset_apply(): table %s has %d columns, "
  186718. "expected %d or more",
  186719. zTab, sApply.nCol, nCol
  186720. );
  186721. }
  186722. else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
  186723. schemaMismatch = 1;
  186724. sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
  186725. "primary key mismatch for table %s", zTab
  186726. );
  186727. }
  186728. else{
  186729. sApply.nCol = nCol;
  186730. if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
  186731. if( (rc = sessionStat1Sql(db, &sApply) ) ){
  186732. break;
  186733. }
  186734. sApply.bStat1 = 1;
  186735. }else{
  186736. if((rc = sessionSelectRow(db, zTab, &sApply))
  186737. || (rc = sessionUpdateRow(db, zTab, &sApply))
  186738. || (rc = sessionDeleteRow(db, zTab, &sApply))
  186739. || (rc = sessionInsertRow(db, zTab, &sApply))
  186740. ){
  186741. break;
  186742. }
  186743. sApply.bStat1 = 0;
  186744. }
  186745. }
  186746. nTab = sqlite3Strlen30(zTab);
  186747. }
  186748. }
  186749. /* If there is a schema mismatch on the current table, proceed to the
  186750. ** next change. A log message has already been issued. */
  186751. if( schemaMismatch ) continue;
  186752. rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
  186753. }
  186754. bPatchset = pIter->bPatchset;
  186755. if( rc==SQLITE_OK ){
  186756. rc = sqlite3changeset_finalize(pIter);
  186757. }else{
  186758. sqlite3changeset_finalize(pIter);
  186759. }
  186760. if( rc==SQLITE_OK ){
  186761. rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
  186762. }
  186763. if( rc==SQLITE_OK ){
  186764. int nFk, notUsed;
  186765. sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
  186766. if( nFk!=0 ){
  186767. int res = SQLITE_CHANGESET_ABORT;
  186768. sqlite3_changeset_iter sIter;
  186769. memset(&sIter, 0, sizeof(sIter));
  186770. sIter.nCol = nFk;
  186771. res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
  186772. if( res!=SQLITE_CHANGESET_OMIT ){
  186773. rc = SQLITE_CONSTRAINT;
  186774. }
  186775. }
  186776. }
  186777. sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
  186778. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  186779. if( rc==SQLITE_OK ){
  186780. rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  186781. }else{
  186782. sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
  186783. sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  186784. }
  186785. }
  186786. assert( sApply.bRebase || sApply.rebase.nBuf==0 );
  186787. if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){
  186788. *ppRebase = (void*)sApply.rebase.aBuf;
  186789. *pnRebase = sApply.rebase.nBuf;
  186790. sApply.rebase.aBuf = 0;
  186791. }
  186792. sqlite3_finalize(sApply.pInsert);
  186793. sqlite3_finalize(sApply.pDelete);
  186794. sqlite3_finalize(sApply.pUpdate);
  186795. sqlite3_finalize(sApply.pSelect);
  186796. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  186797. sqlite3_free((char*)sApply.constraints.aBuf);
  186798. sqlite3_free((char*)sApply.rebase.aBuf);
  186799. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  186800. return rc;
  186801. }
  186802. /*
  186803. ** Apply the changeset passed via pChangeset/nChangeset to the main
  186804. ** database attached to handle "db".
  186805. */
  186806. SQLITE_API int sqlite3changeset_apply_v2(
  186807. sqlite3 *db, /* Apply change to "main" db of this handle */
  186808. int nChangeset, /* Size of changeset in bytes */
  186809. void *pChangeset, /* Changeset blob */
  186810. int(*xFilter)(
  186811. void *pCtx, /* Copy of sixth arg to _apply() */
  186812. const char *zTab /* Table name */
  186813. ),
  186814. int(*xConflict)(
  186815. void *pCtx, /* Copy of sixth arg to _apply() */
  186816. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  186817. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  186818. ),
  186819. void *pCtx, /* First argument passed to xConflict */
  186820. void **ppRebase, int *pnRebase,
  186821. int flags
  186822. ){
  186823. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  186824. int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
  186825. int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset,bInverse);
  186826. if( rc==SQLITE_OK ){
  186827. rc = sessionChangesetApply(
  186828. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  186829. );
  186830. }
  186831. return rc;
  186832. }
  186833. /*
  186834. ** Apply the changeset passed via pChangeset/nChangeset to the main database
  186835. ** attached to handle "db". Invoke the supplied conflict handler callback
  186836. ** to resolve any conflicts encountered while applying the change.
  186837. */
  186838. SQLITE_API int sqlite3changeset_apply(
  186839. sqlite3 *db, /* Apply change to "main" db of this handle */
  186840. int nChangeset, /* Size of changeset in bytes */
  186841. void *pChangeset, /* Changeset blob */
  186842. int(*xFilter)(
  186843. void *pCtx, /* Copy of sixth arg to _apply() */
  186844. const char *zTab /* Table name */
  186845. ),
  186846. int(*xConflict)(
  186847. void *pCtx, /* Copy of fifth arg to _apply() */
  186848. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  186849. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  186850. ),
  186851. void *pCtx /* First argument passed to xConflict */
  186852. ){
  186853. return sqlite3changeset_apply_v2(
  186854. db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0
  186855. );
  186856. }
  186857. /*
  186858. ** Apply the changeset passed via xInput/pIn to the main database
  186859. ** attached to handle "db". Invoke the supplied conflict handler callback
  186860. ** to resolve any conflicts encountered while applying the change.
  186861. */
  186862. SQLITE_API int sqlite3changeset_apply_v2_strm(
  186863. sqlite3 *db, /* Apply change to "main" db of this handle */
  186864. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  186865. void *pIn, /* First arg for xInput */
  186866. int(*xFilter)(
  186867. void *pCtx, /* Copy of sixth arg to _apply() */
  186868. const char *zTab /* Table name */
  186869. ),
  186870. int(*xConflict)(
  186871. void *pCtx, /* Copy of sixth arg to _apply() */
  186872. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  186873. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  186874. ),
  186875. void *pCtx, /* First argument passed to xConflict */
  186876. void **ppRebase, int *pnRebase,
  186877. int flags
  186878. ){
  186879. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  186880. int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
  186881. int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse);
  186882. if( rc==SQLITE_OK ){
  186883. rc = sessionChangesetApply(
  186884. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  186885. );
  186886. }
  186887. return rc;
  186888. }
  186889. SQLITE_API int sqlite3changeset_apply_strm(
  186890. sqlite3 *db, /* Apply change to "main" db of this handle */
  186891. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  186892. void *pIn, /* First arg for xInput */
  186893. int(*xFilter)(
  186894. void *pCtx, /* Copy of sixth arg to _apply() */
  186895. const char *zTab /* Table name */
  186896. ),
  186897. int(*xConflict)(
  186898. void *pCtx, /* Copy of sixth arg to _apply() */
  186899. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  186900. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  186901. ),
  186902. void *pCtx /* First argument passed to xConflict */
  186903. ){
  186904. return sqlite3changeset_apply_v2_strm(
  186905. db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0
  186906. );
  186907. }
  186908. /*
  186909. ** sqlite3_changegroup handle.
  186910. */
  186911. struct sqlite3_changegroup {
  186912. int rc; /* Error code */
  186913. int bPatch; /* True to accumulate patchsets */
  186914. SessionTable *pList; /* List of tables in current patch */
  186915. };
  186916. /*
  186917. ** This function is called to merge two changes to the same row together as
  186918. ** part of an sqlite3changeset_concat() operation. A new change object is
  186919. ** allocated and a pointer to it stored in *ppNew.
  186920. */
  186921. static int sessionChangeMerge(
  186922. SessionTable *pTab, /* Table structure */
  186923. int bRebase, /* True for a rebase hash-table */
  186924. int bPatchset, /* True for patchsets */
  186925. SessionChange *pExist, /* Existing change */
  186926. int op2, /* Second change operation */
  186927. int bIndirect, /* True if second change is indirect */
  186928. u8 *aRec, /* Second change record */
  186929. int nRec, /* Number of bytes in aRec */
  186930. SessionChange **ppNew /* OUT: Merged change */
  186931. ){
  186932. SessionChange *pNew = 0;
  186933. int rc = SQLITE_OK;
  186934. if( !pExist ){
  186935. pNew = (SessionChange *)sqlite3_malloc64(sizeof(SessionChange) + nRec);
  186936. if( !pNew ){
  186937. return SQLITE_NOMEM;
  186938. }
  186939. memset(pNew, 0, sizeof(SessionChange));
  186940. pNew->op = op2;
  186941. pNew->bIndirect = bIndirect;
  186942. pNew->aRecord = (u8*)&pNew[1];
  186943. if( bIndirect==0 || bRebase==0 ){
  186944. pNew->nRecord = nRec;
  186945. memcpy(pNew->aRecord, aRec, nRec);
  186946. }else{
  186947. int i;
  186948. u8 *pIn = aRec;
  186949. u8 *pOut = pNew->aRecord;
  186950. for(i=0; i<pTab->nCol; i++){
  186951. int nIn = sessionSerialLen(pIn);
  186952. if( *pIn==0 ){
  186953. *pOut++ = 0;
  186954. }else if( pTab->abPK[i]==0 ){
  186955. *pOut++ = 0xFF;
  186956. }else{
  186957. memcpy(pOut, pIn, nIn);
  186958. pOut += nIn;
  186959. }
  186960. pIn += nIn;
  186961. }
  186962. pNew->nRecord = pOut - pNew->aRecord;
  186963. }
  186964. }else if( bRebase ){
  186965. if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){
  186966. *ppNew = pExist;
  186967. }else{
  186968. sqlite3_int64 nByte = nRec + pExist->nRecord + sizeof(SessionChange);
  186969. pNew = (SessionChange*)sqlite3_malloc64(nByte);
  186970. if( pNew==0 ){
  186971. rc = SQLITE_NOMEM;
  186972. }else{
  186973. int i;
  186974. u8 *a1 = pExist->aRecord;
  186975. u8 *a2 = aRec;
  186976. u8 *pOut;
  186977. memset(pNew, 0, nByte);
  186978. pNew->bIndirect = bIndirect || pExist->bIndirect;
  186979. pNew->op = op2;
  186980. pOut = pNew->aRecord = (u8*)&pNew[1];
  186981. for(i=0; i<pTab->nCol; i++){
  186982. int n1 = sessionSerialLen(a1);
  186983. int n2 = sessionSerialLen(a2);
  186984. if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){
  186985. *pOut++ = 0xFF;
  186986. }else if( *a2==0 ){
  186987. memcpy(pOut, a1, n1);
  186988. pOut += n1;
  186989. }else{
  186990. memcpy(pOut, a2, n2);
  186991. pOut += n2;
  186992. }
  186993. a1 += n1;
  186994. a2 += n2;
  186995. }
  186996. pNew->nRecord = pOut - pNew->aRecord;
  186997. }
  186998. sqlite3_free(pExist);
  186999. }
  187000. }else{
  187001. int op1 = pExist->op;
  187002. /*
  187003. ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
  187004. ** op1=INSERT, op2=UPDATE -> INSERT.
  187005. ** op1=INSERT, op2=DELETE -> (none)
  187006. **
  187007. ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
  187008. ** op1=UPDATE, op2=UPDATE -> UPDATE.
  187009. ** op1=UPDATE, op2=DELETE -> DELETE.
  187010. **
  187011. ** op1=DELETE, op2=INSERT -> UPDATE.
  187012. ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
  187013. ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
  187014. */
  187015. if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
  187016. || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
  187017. || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
  187018. || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
  187019. ){
  187020. pNew = pExist;
  187021. }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
  187022. sqlite3_free(pExist);
  187023. assert( pNew==0 );
  187024. }else{
  187025. u8 *aExist = pExist->aRecord;
  187026. sqlite3_int64 nByte;
  187027. u8 *aCsr;
  187028. /* Allocate a new SessionChange object. Ensure that the aRecord[]
  187029. ** buffer of the new object is large enough to hold any record that
  187030. ** may be generated by combining the input records. */
  187031. nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
  187032. pNew = (SessionChange *)sqlite3_malloc64(nByte);
  187033. if( !pNew ){
  187034. sqlite3_free(pExist);
  187035. return SQLITE_NOMEM;
  187036. }
  187037. memset(pNew, 0, sizeof(SessionChange));
  187038. pNew->bIndirect = (bIndirect && pExist->bIndirect);
  187039. aCsr = pNew->aRecord = (u8 *)&pNew[1];
  187040. if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
  187041. u8 *a1 = aRec;
  187042. assert( op2==SQLITE_UPDATE );
  187043. pNew->op = SQLITE_INSERT;
  187044. if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
  187045. sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
  187046. }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
  187047. assert( op2==SQLITE_INSERT );
  187048. pNew->op = SQLITE_UPDATE;
  187049. if( bPatchset ){
  187050. memcpy(aCsr, aRec, nRec);
  187051. aCsr += nRec;
  187052. }else{
  187053. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
  187054. sqlite3_free(pNew);
  187055. pNew = 0;
  187056. }
  187057. }
  187058. }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
  187059. u8 *a1 = aExist;
  187060. u8 *a2 = aRec;
  187061. assert( op1==SQLITE_UPDATE );
  187062. if( bPatchset==0 ){
  187063. sessionSkipRecord(&a1, pTab->nCol);
  187064. sessionSkipRecord(&a2, pTab->nCol);
  187065. }
  187066. pNew->op = SQLITE_UPDATE;
  187067. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
  187068. sqlite3_free(pNew);
  187069. pNew = 0;
  187070. }
  187071. }else{ /* UPDATE + DELETE */
  187072. assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
  187073. pNew->op = SQLITE_DELETE;
  187074. if( bPatchset ){
  187075. memcpy(aCsr, aRec, nRec);
  187076. aCsr += nRec;
  187077. }else{
  187078. sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
  187079. }
  187080. }
  187081. if( pNew ){
  187082. pNew->nRecord = (int)(aCsr - pNew->aRecord);
  187083. }
  187084. sqlite3_free(pExist);
  187085. }
  187086. }
  187087. *ppNew = pNew;
  187088. return rc;
  187089. }
  187090. /*
  187091. ** Add all changes in the changeset traversed by the iterator passed as
  187092. ** the first argument to the changegroup hash tables.
  187093. */
  187094. static int sessionChangesetToHash(
  187095. sqlite3_changeset_iter *pIter, /* Iterator to read from */
  187096. sqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */
  187097. int bRebase /* True if hash table is for rebasing */
  187098. ){
  187099. u8 *aRec;
  187100. int nRec;
  187101. int rc = SQLITE_OK;
  187102. SessionTable *pTab = 0;
  187103. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){
  187104. const char *zNew;
  187105. int nCol;
  187106. int op;
  187107. int iHash;
  187108. int bIndirect;
  187109. SessionChange *pChange;
  187110. SessionChange *pExist = 0;
  187111. SessionChange **pp;
  187112. if( pGrp->pList==0 ){
  187113. pGrp->bPatch = pIter->bPatchset;
  187114. }else if( pIter->bPatchset!=pGrp->bPatch ){
  187115. rc = SQLITE_ERROR;
  187116. break;
  187117. }
  187118. sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
  187119. if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
  187120. /* Search the list for a matching table */
  187121. int nNew = (int)strlen(zNew);
  187122. u8 *abPK;
  187123. sqlite3changeset_pk(pIter, &abPK, 0);
  187124. for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
  187125. if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
  187126. }
  187127. if( !pTab ){
  187128. SessionTable **ppTab;
  187129. pTab = sqlite3_malloc64(sizeof(SessionTable) + nCol + nNew+1);
  187130. if( !pTab ){
  187131. rc = SQLITE_NOMEM;
  187132. break;
  187133. }
  187134. memset(pTab, 0, sizeof(SessionTable));
  187135. pTab->nCol = nCol;
  187136. pTab->abPK = (u8*)&pTab[1];
  187137. memcpy(pTab->abPK, abPK, nCol);
  187138. pTab->zName = (char*)&pTab->abPK[nCol];
  187139. memcpy(pTab->zName, zNew, nNew+1);
  187140. /* The new object must be linked on to the end of the list, not
  187141. ** simply added to the start of it. This is to ensure that the
  187142. ** tables within the output of sqlite3changegroup_output() are in
  187143. ** the right order. */
  187144. for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
  187145. *ppTab = pTab;
  187146. }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
  187147. rc = SQLITE_SCHEMA;
  187148. break;
  187149. }
  187150. }
  187151. if( sessionGrowHash(pIter->bPatchset, pTab) ){
  187152. rc = SQLITE_NOMEM;
  187153. break;
  187154. }
  187155. iHash = sessionChangeHash(
  187156. pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
  187157. );
  187158. /* Search for existing entry. If found, remove it from the hash table.
  187159. ** Code below may link it back in.
  187160. */
  187161. for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
  187162. int bPkOnly1 = 0;
  187163. int bPkOnly2 = 0;
  187164. if( pIter->bPatchset ){
  187165. bPkOnly1 = (*pp)->op==SQLITE_DELETE;
  187166. bPkOnly2 = op==SQLITE_DELETE;
  187167. }
  187168. if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
  187169. pExist = *pp;
  187170. *pp = (*pp)->pNext;
  187171. pTab->nEntry--;
  187172. break;
  187173. }
  187174. }
  187175. rc = sessionChangeMerge(pTab, bRebase,
  187176. pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
  187177. );
  187178. if( rc ) break;
  187179. if( pChange ){
  187180. pChange->pNext = pTab->apChange[iHash];
  187181. pTab->apChange[iHash] = pChange;
  187182. pTab->nEntry++;
  187183. }
  187184. }
  187185. if( rc==SQLITE_OK ) rc = pIter->rc;
  187186. return rc;
  187187. }
  187188. /*
  187189. ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
  187190. ** added to the changegroup object passed as the first argument.
  187191. **
  187192. ** If xOutput is not NULL, then the changeset/patchset is returned to the
  187193. ** user via one or more calls to xOutput, as with the other streaming
  187194. ** interfaces.
  187195. **
  187196. ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
  187197. ** buffer containing the output changeset before this function returns. In
  187198. ** this case (*pnOut) is set to the size of the output buffer in bytes. It
  187199. ** is the responsibility of the caller to free the output buffer using
  187200. ** sqlite3_free() when it is no longer required.
  187201. **
  187202. ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
  187203. ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
  187204. ** are both set to 0 before returning.
  187205. */
  187206. static int sessionChangegroupOutput(
  187207. sqlite3_changegroup *pGrp,
  187208. int (*xOutput)(void *pOut, const void *pData, int nData),
  187209. void *pOut,
  187210. int *pnOut,
  187211. void **ppOut
  187212. ){
  187213. int rc = SQLITE_OK;
  187214. SessionBuffer buf = {0, 0, 0};
  187215. SessionTable *pTab;
  187216. assert( xOutput==0 || (ppOut==0 && pnOut==0) );
  187217. /* Create the serialized output changeset based on the contents of the
  187218. ** hash tables attached to the SessionTable objects in list p->pList.
  187219. */
  187220. for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  187221. int i;
  187222. if( pTab->nEntry==0 ) continue;
  187223. sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
  187224. for(i=0; i<pTab->nChange; i++){
  187225. SessionChange *p;
  187226. for(p=pTab->apChange[i]; p; p=p->pNext){
  187227. sessionAppendByte(&buf, p->op, &rc);
  187228. sessionAppendByte(&buf, p->bIndirect, &rc);
  187229. sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
  187230. if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){
  187231. rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  187232. buf.nBuf = 0;
  187233. }
  187234. }
  187235. }
  187236. }
  187237. if( rc==SQLITE_OK ){
  187238. if( xOutput ){
  187239. if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  187240. }else{
  187241. *ppOut = buf.aBuf;
  187242. *pnOut = buf.nBuf;
  187243. buf.aBuf = 0;
  187244. }
  187245. }
  187246. sqlite3_free(buf.aBuf);
  187247. return rc;
  187248. }
  187249. /*
  187250. ** Allocate a new, empty, sqlite3_changegroup.
  187251. */
  187252. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
  187253. int rc = SQLITE_OK; /* Return code */
  187254. sqlite3_changegroup *p; /* New object */
  187255. p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
  187256. if( p==0 ){
  187257. rc = SQLITE_NOMEM;
  187258. }else{
  187259. memset(p, 0, sizeof(sqlite3_changegroup));
  187260. }
  187261. *pp = p;
  187262. return rc;
  187263. }
  187264. /*
  187265. ** Add the changeset currently stored in buffer pData, size nData bytes,
  187266. ** to changeset-group p.
  187267. */
  187268. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
  187269. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  187270. int rc; /* Return code */
  187271. rc = sqlite3changeset_start(&pIter, nData, pData);
  187272. if( rc==SQLITE_OK ){
  187273. rc = sessionChangesetToHash(pIter, pGrp, 0);
  187274. }
  187275. sqlite3changeset_finalize(pIter);
  187276. return rc;
  187277. }
  187278. /*
  187279. ** Obtain a buffer containing a changeset representing the concatenation
  187280. ** of all changesets added to the group so far.
  187281. */
  187282. SQLITE_API int sqlite3changegroup_output(
  187283. sqlite3_changegroup *pGrp,
  187284. int *pnData,
  187285. void **ppData
  187286. ){
  187287. return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
  187288. }
  187289. /*
  187290. ** Streaming versions of changegroup_add().
  187291. */
  187292. SQLITE_API int sqlite3changegroup_add_strm(
  187293. sqlite3_changegroup *pGrp,
  187294. int (*xInput)(void *pIn, void *pData, int *pnData),
  187295. void *pIn
  187296. ){
  187297. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  187298. int rc; /* Return code */
  187299. rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  187300. if( rc==SQLITE_OK ){
  187301. rc = sessionChangesetToHash(pIter, pGrp, 0);
  187302. }
  187303. sqlite3changeset_finalize(pIter);
  187304. return rc;
  187305. }
  187306. /*
  187307. ** Streaming versions of changegroup_output().
  187308. */
  187309. SQLITE_API int sqlite3changegroup_output_strm(
  187310. sqlite3_changegroup *pGrp,
  187311. int (*xOutput)(void *pOut, const void *pData, int nData),
  187312. void *pOut
  187313. ){
  187314. return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
  187315. }
  187316. /*
  187317. ** Delete a changegroup object.
  187318. */
  187319. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
  187320. if( pGrp ){
  187321. sessionDeleteTable(pGrp->pList);
  187322. sqlite3_free(pGrp);
  187323. }
  187324. }
  187325. /*
  187326. ** Combine two changesets together.
  187327. */
  187328. SQLITE_API int sqlite3changeset_concat(
  187329. int nLeft, /* Number of bytes in lhs input */
  187330. void *pLeft, /* Lhs input changeset */
  187331. int nRight /* Number of bytes in rhs input */,
  187332. void *pRight, /* Rhs input changeset */
  187333. int *pnOut, /* OUT: Number of bytes in output changeset */
  187334. void **ppOut /* OUT: changeset (left <concat> right) */
  187335. ){
  187336. sqlite3_changegroup *pGrp;
  187337. int rc;
  187338. rc = sqlite3changegroup_new(&pGrp);
  187339. if( rc==SQLITE_OK ){
  187340. rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
  187341. }
  187342. if( rc==SQLITE_OK ){
  187343. rc = sqlite3changegroup_add(pGrp, nRight, pRight);
  187344. }
  187345. if( rc==SQLITE_OK ){
  187346. rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  187347. }
  187348. sqlite3changegroup_delete(pGrp);
  187349. return rc;
  187350. }
  187351. /*
  187352. ** Streaming version of sqlite3changeset_concat().
  187353. */
  187354. SQLITE_API int sqlite3changeset_concat_strm(
  187355. int (*xInputA)(void *pIn, void *pData, int *pnData),
  187356. void *pInA,
  187357. int (*xInputB)(void *pIn, void *pData, int *pnData),
  187358. void *pInB,
  187359. int (*xOutput)(void *pOut, const void *pData, int nData),
  187360. void *pOut
  187361. ){
  187362. sqlite3_changegroup *pGrp;
  187363. int rc;
  187364. rc = sqlite3changegroup_new(&pGrp);
  187365. if( rc==SQLITE_OK ){
  187366. rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
  187367. }
  187368. if( rc==SQLITE_OK ){
  187369. rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
  187370. }
  187371. if( rc==SQLITE_OK ){
  187372. rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
  187373. }
  187374. sqlite3changegroup_delete(pGrp);
  187375. return rc;
  187376. }
  187377. /*
  187378. ** Changeset rebaser handle.
  187379. */
  187380. struct sqlite3_rebaser {
  187381. sqlite3_changegroup grp; /* Hash table */
  187382. };
  187383. /*
  187384. ** Buffers a1 and a2 must both contain a sessions module record nCol
  187385. ** fields in size. This function appends an nCol sessions module
  187386. ** record to buffer pBuf that is a copy of a1, except that for
  187387. ** each field that is undefined in a1[], swap in the field from a2[].
  187388. */
  187389. static void sessionAppendRecordMerge(
  187390. SessionBuffer *pBuf, /* Buffer to append to */
  187391. int nCol, /* Number of columns in each record */
  187392. u8 *a1, int n1, /* Record 1 */
  187393. u8 *a2, int n2, /* Record 2 */
  187394. int *pRc /* IN/OUT: error code */
  187395. ){
  187396. sessionBufferGrow(pBuf, n1+n2, pRc);
  187397. if( *pRc==SQLITE_OK ){
  187398. int i;
  187399. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  187400. for(i=0; i<nCol; i++){
  187401. int nn1 = sessionSerialLen(a1);
  187402. int nn2 = sessionSerialLen(a2);
  187403. if( *a1==0 || *a1==0xFF ){
  187404. memcpy(pOut, a2, nn2);
  187405. pOut += nn2;
  187406. }else{
  187407. memcpy(pOut, a1, nn1);
  187408. pOut += nn1;
  187409. }
  187410. a1 += nn1;
  187411. a2 += nn2;
  187412. }
  187413. pBuf->nBuf = pOut-pBuf->aBuf;
  187414. assert( pBuf->nBuf<=pBuf->nAlloc );
  187415. }
  187416. }
  187417. /*
  187418. ** This function is called when rebasing a local UPDATE change against one
  187419. ** or more remote UPDATE changes. The aRec/nRec buffer contains the current
  187420. ** old.* and new.* records for the change. The rebase buffer (a single
  187421. ** record) is in aChange/nChange. The rebased change is appended to buffer
  187422. ** pBuf.
  187423. **
  187424. ** Rebasing the UPDATE involves:
  187425. **
  187426. ** * Removing any changes to fields for which the corresponding field
  187427. ** in the rebase buffer is set to "replaced" (type 0xFF). If this
  187428. ** means the UPDATE change updates no fields, nothing is appended
  187429. ** to the output buffer.
  187430. **
  187431. ** * For each field modified by the local change for which the
  187432. ** corresponding field in the rebase buffer is not "undefined" (0x00)
  187433. ** or "replaced" (0xFF), the old.* value is replaced by the value
  187434. ** in the rebase buffer.
  187435. */
  187436. static void sessionAppendPartialUpdate(
  187437. SessionBuffer *pBuf, /* Append record here */
  187438. sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */
  187439. u8 *aRec, int nRec, /* Local change */
  187440. u8 *aChange, int nChange, /* Record to rebase against */
  187441. int *pRc /* IN/OUT: Return Code */
  187442. ){
  187443. sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
  187444. if( *pRc==SQLITE_OK ){
  187445. int bData = 0;
  187446. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  187447. int i;
  187448. u8 *a1 = aRec;
  187449. u8 *a2 = aChange;
  187450. *pOut++ = SQLITE_UPDATE;
  187451. *pOut++ = pIter->bIndirect;
  187452. for(i=0; i<pIter->nCol; i++){
  187453. int n1 = sessionSerialLen(a1);
  187454. int n2 = sessionSerialLen(a2);
  187455. if( pIter->abPK[i] || a2[0]==0 ){
  187456. if( !pIter->abPK[i] ) bData = 1;
  187457. memcpy(pOut, a1, n1);
  187458. pOut += n1;
  187459. }else if( a2[0]!=0xFF ){
  187460. bData = 1;
  187461. memcpy(pOut, a2, n2);
  187462. pOut += n2;
  187463. }else{
  187464. *pOut++ = '\0';
  187465. }
  187466. a1 += n1;
  187467. a2 += n2;
  187468. }
  187469. if( bData ){
  187470. a2 = aChange;
  187471. for(i=0; i<pIter->nCol; i++){
  187472. int n1 = sessionSerialLen(a1);
  187473. int n2 = sessionSerialLen(a2);
  187474. if( pIter->abPK[i] || a2[0]!=0xFF ){
  187475. memcpy(pOut, a1, n1);
  187476. pOut += n1;
  187477. }else{
  187478. *pOut++ = '\0';
  187479. }
  187480. a1 += n1;
  187481. a2 += n2;
  187482. }
  187483. pBuf->nBuf = (pOut - pBuf->aBuf);
  187484. }
  187485. }
  187486. }
  187487. /*
  187488. ** pIter is configured to iterate through a changeset. This function rebases
  187489. ** that changeset according to the current configuration of the rebaser
  187490. ** object passed as the first argument. If no error occurs and argument xOutput
  187491. ** is not NULL, then the changeset is returned to the caller by invoking
  187492. ** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
  187493. ** then (*ppOut) is set to point to a buffer containing the rebased changeset
  187494. ** before this function returns. In this case (*pnOut) is set to the size of
  187495. ** the buffer in bytes. It is the responsibility of the caller to eventually
  187496. ** free the (*ppOut) buffer using sqlite3_free().
  187497. **
  187498. ** If an error occurs, an SQLite error code is returned. If ppOut and
  187499. ** pnOut are not NULL, then the two output parameters are set to 0 before
  187500. ** returning.
  187501. */
  187502. static int sessionRebase(
  187503. sqlite3_rebaser *p, /* Rebaser hash table */
  187504. sqlite3_changeset_iter *pIter, /* Input data */
  187505. int (*xOutput)(void *pOut, const void *pData, int nData),
  187506. void *pOut, /* Context for xOutput callback */
  187507. int *pnOut, /* OUT: Number of bytes in output changeset */
  187508. void **ppOut /* OUT: Inverse of pChangeset */
  187509. ){
  187510. int rc = SQLITE_OK;
  187511. u8 *aRec = 0;
  187512. int nRec = 0;
  187513. int bNew = 0;
  187514. SessionTable *pTab = 0;
  187515. SessionBuffer sOut = {0,0,0};
  187516. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){
  187517. SessionChange *pChange = 0;
  187518. int bDone = 0;
  187519. if( bNew ){
  187520. const char *zTab = pIter->zTab;
  187521. for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){
  187522. if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;
  187523. }
  187524. bNew = 0;
  187525. /* A patchset may not be rebased */
  187526. if( pIter->bPatchset ){
  187527. rc = SQLITE_ERROR;
  187528. }
  187529. /* Append a table header to the output for this new table */
  187530. sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);
  187531. sessionAppendVarint(&sOut, pIter->nCol, &rc);
  187532. sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);
  187533. sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);
  187534. }
  187535. if( pTab && rc==SQLITE_OK ){
  187536. int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);
  187537. for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){
  187538. if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){
  187539. break;
  187540. }
  187541. }
  187542. }
  187543. if( pChange ){
  187544. assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );
  187545. switch( pIter->op ){
  187546. case SQLITE_INSERT:
  187547. if( pChange->op==SQLITE_INSERT ){
  187548. bDone = 1;
  187549. if( pChange->bIndirect==0 ){
  187550. sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);
  187551. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  187552. sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);
  187553. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  187554. }
  187555. }
  187556. break;
  187557. case SQLITE_UPDATE:
  187558. bDone = 1;
  187559. if( pChange->op==SQLITE_DELETE ){
  187560. if( pChange->bIndirect==0 ){
  187561. u8 *pCsr = aRec;
  187562. sessionSkipRecord(&pCsr, pIter->nCol);
  187563. sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
  187564. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  187565. sessionAppendRecordMerge(&sOut, pIter->nCol,
  187566. pCsr, nRec-(pCsr-aRec),
  187567. pChange->aRecord, pChange->nRecord, &rc
  187568. );
  187569. }
  187570. }else{
  187571. sessionAppendPartialUpdate(&sOut, pIter,
  187572. aRec, nRec, pChange->aRecord, pChange->nRecord, &rc
  187573. );
  187574. }
  187575. break;
  187576. default:
  187577. assert( pIter->op==SQLITE_DELETE );
  187578. bDone = 1;
  187579. if( pChange->op==SQLITE_INSERT ){
  187580. sessionAppendByte(&sOut, SQLITE_DELETE, &rc);
  187581. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  187582. sessionAppendRecordMerge(&sOut, pIter->nCol,
  187583. pChange->aRecord, pChange->nRecord, aRec, nRec, &rc
  187584. );
  187585. }
  187586. break;
  187587. }
  187588. }
  187589. if( bDone==0 ){
  187590. sessionAppendByte(&sOut, pIter->op, &rc);
  187591. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  187592. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  187593. }
  187594. if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){
  187595. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  187596. sOut.nBuf = 0;
  187597. }
  187598. if( rc ) break;
  187599. }
  187600. if( rc!=SQLITE_OK ){
  187601. sqlite3_free(sOut.aBuf);
  187602. memset(&sOut, 0, sizeof(sOut));
  187603. }
  187604. if( rc==SQLITE_OK ){
  187605. if( xOutput ){
  187606. if( sOut.nBuf>0 ){
  187607. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  187608. }
  187609. }else{
  187610. *ppOut = (void*)sOut.aBuf;
  187611. *pnOut = sOut.nBuf;
  187612. sOut.aBuf = 0;
  187613. }
  187614. }
  187615. sqlite3_free(sOut.aBuf);
  187616. return rc;
  187617. }
  187618. /*
  187619. ** Create a new rebaser object.
  187620. */
  187621. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
  187622. int rc = SQLITE_OK;
  187623. sqlite3_rebaser *pNew;
  187624. pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));
  187625. if( pNew==0 ){
  187626. rc = SQLITE_NOMEM;
  187627. }else{
  187628. memset(pNew, 0, sizeof(sqlite3_rebaser));
  187629. }
  187630. *ppNew = pNew;
  187631. return rc;
  187632. }
  187633. /*
  187634. ** Call this one or more times to configure a rebaser.
  187635. */
  187636. SQLITE_API int sqlite3rebaser_configure(
  187637. sqlite3_rebaser *p,
  187638. int nRebase, const void *pRebase
  187639. ){
  187640. sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
  187641. int rc; /* Return code */
  187642. rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
  187643. if( rc==SQLITE_OK ){
  187644. rc = sessionChangesetToHash(pIter, &p->grp, 1);
  187645. }
  187646. sqlite3changeset_finalize(pIter);
  187647. return rc;
  187648. }
  187649. /*
  187650. ** Rebase a changeset according to current rebaser configuration
  187651. */
  187652. SQLITE_API int sqlite3rebaser_rebase(
  187653. sqlite3_rebaser *p,
  187654. int nIn, const void *pIn,
  187655. int *pnOut, void **ppOut
  187656. ){
  187657. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  187658. int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
  187659. if( rc==SQLITE_OK ){
  187660. rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);
  187661. sqlite3changeset_finalize(pIter);
  187662. }
  187663. return rc;
  187664. }
  187665. /*
  187666. ** Rebase a changeset according to current rebaser configuration
  187667. */
  187668. SQLITE_API int sqlite3rebaser_rebase_strm(
  187669. sqlite3_rebaser *p,
  187670. int (*xInput)(void *pIn, void *pData, int *pnData),
  187671. void *pIn,
  187672. int (*xOutput)(void *pOut, const void *pData, int nData),
  187673. void *pOut
  187674. ){
  187675. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  187676. int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  187677. if( rc==SQLITE_OK ){
  187678. rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);
  187679. sqlite3changeset_finalize(pIter);
  187680. }
  187681. return rc;
  187682. }
  187683. /*
  187684. ** Destroy a rebaser object
  187685. */
  187686. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){
  187687. if( p ){
  187688. sessionDeleteTable(p->grp.pList);
  187689. sqlite3_free(p);
  187690. }
  187691. }
  187692. /*
  187693. ** Global configuration
  187694. */
  187695. SQLITE_API int sqlite3session_config(int op, void *pArg){
  187696. int rc = SQLITE_OK;
  187697. switch( op ){
  187698. case SQLITE_SESSION_CONFIG_STRMSIZE: {
  187699. int *pInt = (int*)pArg;
  187700. if( *pInt>0 ){
  187701. sessions_strm_chunk_size = *pInt;
  187702. }
  187703. *pInt = sessions_strm_chunk_size;
  187704. break;
  187705. }
  187706. default:
  187707. rc = SQLITE_MISUSE;
  187708. break;
  187709. }
  187710. return rc;
  187711. }
  187712. #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
  187713. /************** End of sqlite3session.c **************************************/
  187714. /************** Begin file fts5.c ********************************************/
  187715. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  187716. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  187717. # define NDEBUG 1
  187718. #endif
  187719. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  187720. # undef NDEBUG
  187721. #endif
  187722. /*
  187723. ** 2014 May 31
  187724. **
  187725. ** The author disclaims copyright to this source code. In place of
  187726. ** a legal notice, here is a blessing:
  187727. **
  187728. ** May you do good and not evil.
  187729. ** May you find forgiveness for yourself and forgive others.
  187730. ** May you share freely, never taking more than you give.
  187731. **
  187732. ******************************************************************************
  187733. **
  187734. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  187735. ** FTS5 may be extended with:
  187736. **
  187737. ** * custom tokenizers, and
  187738. ** * custom auxiliary functions.
  187739. */
  187740. #ifndef _FTS5_H
  187741. #define _FTS5_H
  187742. /* #include "sqlite3.h" */
  187743. #if 0
  187744. extern "C" {
  187745. #endif
  187746. /*************************************************************************
  187747. ** CUSTOM AUXILIARY FUNCTIONS
  187748. **
  187749. ** Virtual table implementations may overload SQL functions by implementing
  187750. ** the sqlite3_module.xFindFunction() method.
  187751. */
  187752. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  187753. typedef struct Fts5Context Fts5Context;
  187754. typedef struct Fts5PhraseIter Fts5PhraseIter;
  187755. typedef void (*fts5_extension_function)(
  187756. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  187757. Fts5Context *pFts, /* First arg to pass to pApi functions */
  187758. sqlite3_context *pCtx, /* Context for returning result/error */
  187759. int nVal, /* Number of values in apVal[] array */
  187760. sqlite3_value **apVal /* Array of trailing arguments */
  187761. );
  187762. struct Fts5PhraseIter {
  187763. const unsigned char *a;
  187764. const unsigned char *b;
  187765. };
  187766. /*
  187767. ** EXTENSION API FUNCTIONS
  187768. **
  187769. ** xUserData(pFts):
  187770. ** Return a copy of the context pointer the extension function was
  187771. ** registered with.
  187772. **
  187773. ** xColumnTotalSize(pFts, iCol, pnToken):
  187774. ** If parameter iCol is less than zero, set output variable *pnToken
  187775. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  187776. ** non-negative but less than the number of columns in the table, return
  187777. ** the total number of tokens in column iCol, considering all rows in
  187778. ** the FTS5 table.
  187779. **
  187780. ** If parameter iCol is greater than or equal to the number of columns
  187781. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  187782. ** an OOM condition or IO error), an appropriate SQLite error code is
  187783. ** returned.
  187784. **
  187785. ** xColumnCount(pFts):
  187786. ** Return the number of columns in the table.
  187787. **
  187788. ** xColumnSize(pFts, iCol, pnToken):
  187789. ** If parameter iCol is less than zero, set output variable *pnToken
  187790. ** to the total number of tokens in the current row. Or, if iCol is
  187791. ** non-negative but less than the number of columns in the table, set
  187792. ** *pnToken to the number of tokens in column iCol of the current row.
  187793. **
  187794. ** If parameter iCol is greater than or equal to the number of columns
  187795. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  187796. ** an OOM condition or IO error), an appropriate SQLite error code is
  187797. ** returned.
  187798. **
  187799. ** This function may be quite inefficient if used with an FTS5 table
  187800. ** created with the "columnsize=0" option.
  187801. **
  187802. ** xColumnText:
  187803. ** This function attempts to retrieve the text of column iCol of the
  187804. ** current document. If successful, (*pz) is set to point to a buffer
  187805. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  187806. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  187807. ** if an error occurs, an SQLite error code is returned and the final values
  187808. ** of (*pz) and (*pn) are undefined.
  187809. **
  187810. ** xPhraseCount:
  187811. ** Returns the number of phrases in the current query expression.
  187812. **
  187813. ** xPhraseSize:
  187814. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  187815. ** are numbered starting from zero.
  187816. **
  187817. ** xInstCount:
  187818. ** Set *pnInst to the total number of occurrences of all phrases within
  187819. ** the query within the current row. Return SQLITE_OK if successful, or
  187820. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  187821. **
  187822. ** This API can be quite slow if used with an FTS5 table created with the
  187823. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  187824. ** with either "detail=none" or "detail=column" and "content=" option
  187825. ** (i.e. if it is a contentless table), then this API always returns 0.
  187826. **
  187827. ** xInst:
  187828. ** Query for the details of phrase match iIdx within the current row.
  187829. ** Phrase matches are numbered starting from zero, so the iIdx argument
  187830. ** should be greater than or equal to zero and smaller than the value
  187831. ** output by xInstCount().
  187832. **
  187833. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  187834. ** to the column in which it occurs and *piOff the token offset of the
  187835. ** first token of the phrase. Returns SQLITE_OK if successful, or an error
  187836. ** code (i.e. SQLITE_NOMEM) if an error occurs.
  187837. **
  187838. ** This API can be quite slow if used with an FTS5 table created with the
  187839. ** "detail=none" or "detail=column" option.
  187840. **
  187841. ** xRowid:
  187842. ** Returns the rowid of the current row.
  187843. **
  187844. ** xTokenize:
  187845. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  187846. **
  187847. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  187848. ** This API function is used to query the FTS table for phrase iPhrase
  187849. ** of the current query. Specifically, a query equivalent to:
  187850. **
  187851. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  187852. **
  187853. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  187854. ** current query is executed. Any column filter that applies to
  187855. ** phrase iPhrase of the current query is included in $p. For each
  187856. ** row visited, the callback function passed as the fourth argument
  187857. ** is invoked. The context and API objects passed to the callback
  187858. ** function may be used to access the properties of each matched row.
  187859. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  187860. ** the third argument to pUserData.
  187861. **
  187862. ** If the callback function returns any value other than SQLITE_OK, the
  187863. ** query is abandoned and the xQueryPhrase function returns immediately.
  187864. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  187865. ** Otherwise, the error code is propagated upwards.
  187866. **
  187867. ** If the query runs to completion without incident, SQLITE_OK is returned.
  187868. ** Or, if some error occurs before the query completes or is aborted by
  187869. ** the callback, an SQLite error code is returned.
  187870. **
  187871. **
  187872. ** xSetAuxdata(pFts5, pAux, xDelete)
  187873. **
  187874. ** Save the pointer passed as the second argument as the extension functions
  187875. ** "auxiliary data". The pointer may then be retrieved by the current or any
  187876. ** future invocation of the same fts5 extension function made as part of
  187877. ** the same MATCH query using the xGetAuxdata() API.
  187878. **
  187879. ** Each extension function is allocated a single auxiliary data slot for
  187880. ** each FTS query (MATCH expression). If the extension function is invoked
  187881. ** more than once for a single FTS query, then all invocations share a
  187882. ** single auxiliary data context.
  187883. **
  187884. ** If there is already an auxiliary data pointer when this function is
  187885. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  187886. ** was specified along with the original pointer, it is invoked at this
  187887. ** point.
  187888. **
  187889. ** The xDelete callback, if one is specified, is also invoked on the
  187890. ** auxiliary data pointer after the FTS5 query has finished.
  187891. **
  187892. ** If an error (e.g. an OOM condition) occurs within this function,
  187893. ** the auxiliary data is set to NULL and an error code returned. If the
  187894. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  187895. ** pointer before returning.
  187896. **
  187897. **
  187898. ** xGetAuxdata(pFts5, bClear)
  187899. **
  187900. ** Returns the current auxiliary data pointer for the fts5 extension
  187901. ** function. See the xSetAuxdata() method for details.
  187902. **
  187903. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  187904. ** (set to NULL) before this function returns. In this case the xDelete,
  187905. ** if any, is not invoked.
  187906. **
  187907. **
  187908. ** xRowCount(pFts5, pnRow)
  187909. **
  187910. ** This function is used to retrieve the total number of rows in the table.
  187911. ** In other words, the same value that would be returned by:
  187912. **
  187913. ** SELECT count(*) FROM ftstable;
  187914. **
  187915. ** xPhraseFirst()
  187916. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  187917. ** method, to iterate through all instances of a single query phrase within
  187918. ** the current row. This is the same information as is accessible via the
  187919. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  187920. ** to use, this API may be faster under some circumstances. To iterate
  187921. ** through instances of phrase iPhrase, use the following code:
  187922. **
  187923. ** Fts5PhraseIter iter;
  187924. ** int iCol, iOff;
  187925. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  187926. ** iCol>=0;
  187927. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  187928. ** ){
  187929. ** // An instance of phrase iPhrase at offset iOff of column iCol
  187930. ** }
  187931. **
  187932. ** The Fts5PhraseIter structure is defined above. Applications should not
  187933. ** modify this structure directly - it should only be used as shown above
  187934. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  187935. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  187936. **
  187937. ** This API can be quite slow if used with an FTS5 table created with the
  187938. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  187939. ** with either "detail=none" or "detail=column" and "content=" option
  187940. ** (i.e. if it is a contentless table), then this API always iterates
  187941. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  187942. **
  187943. ** xPhraseNext()
  187944. ** See xPhraseFirst above.
  187945. **
  187946. ** xPhraseFirstColumn()
  187947. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  187948. ** and xPhraseNext() APIs described above. The difference is that instead
  187949. ** of iterating through all instances of a phrase in the current row, these
  187950. ** APIs are used to iterate through the set of columns in the current row
  187951. ** that contain one or more instances of a specified phrase. For example:
  187952. **
  187953. ** Fts5PhraseIter iter;
  187954. ** int iCol;
  187955. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  187956. ** iCol>=0;
  187957. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  187958. ** ){
  187959. ** // Column iCol contains at least one instance of phrase iPhrase
  187960. ** }
  187961. **
  187962. ** This API can be quite slow if used with an FTS5 table created with the
  187963. ** "detail=none" option. If the FTS5 table is created with either
  187964. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  187965. ** then this API always iterates through an empty set (all calls to
  187966. ** xPhraseFirstColumn() set iCol to -1).
  187967. **
  187968. ** The information accessed using this API and its companion
  187969. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  187970. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  187971. ** significantly more efficient than those alternatives when used with
  187972. ** "detail=column" tables.
  187973. **
  187974. ** xPhraseNextColumn()
  187975. ** See xPhraseFirstColumn above.
  187976. */
  187977. struct Fts5ExtensionApi {
  187978. int iVersion; /* Currently always set to 3 */
  187979. void *(*xUserData)(Fts5Context*);
  187980. int (*xColumnCount)(Fts5Context*);
  187981. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  187982. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  187983. int (*xTokenize)(Fts5Context*,
  187984. const char *pText, int nText, /* Text to tokenize */
  187985. void *pCtx, /* Context passed to xToken() */
  187986. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  187987. );
  187988. int (*xPhraseCount)(Fts5Context*);
  187989. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  187990. int (*xInstCount)(Fts5Context*, int *pnInst);
  187991. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  187992. sqlite3_int64 (*xRowid)(Fts5Context*);
  187993. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  187994. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  187995. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  187996. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  187997. );
  187998. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  187999. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  188000. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  188001. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  188002. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  188003. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  188004. };
  188005. /*
  188006. ** CUSTOM AUXILIARY FUNCTIONS
  188007. *************************************************************************/
  188008. /*************************************************************************
  188009. ** CUSTOM TOKENIZERS
  188010. **
  188011. ** Applications may also register custom tokenizer types. A tokenizer
  188012. ** is registered by providing fts5 with a populated instance of the
  188013. ** following structure. All structure methods must be defined, setting
  188014. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  188015. ** behaviour. The structure methods are expected to function as follows:
  188016. **
  188017. ** xCreate:
  188018. ** This function is used to allocate and initialize a tokenizer instance.
  188019. ** A tokenizer instance is required to actually tokenize text.
  188020. **
  188021. ** The first argument passed to this function is a copy of the (void*)
  188022. ** pointer provided by the application when the fts5_tokenizer object
  188023. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  188024. ** The second and third arguments are an array of nul-terminated strings
  188025. ** containing the tokenizer arguments, if any, specified following the
  188026. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  188027. ** to create the FTS5 table.
  188028. **
  188029. ** The final argument is an output variable. If successful, (*ppOut)
  188030. ** should be set to point to the new tokenizer handle and SQLITE_OK
  188031. ** returned. If an error occurs, some value other than SQLITE_OK should
  188032. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  188033. ** is undefined.
  188034. **
  188035. ** xDelete:
  188036. ** This function is invoked to delete a tokenizer handle previously
  188037. ** allocated using xCreate(). Fts5 guarantees that this function will
  188038. ** be invoked exactly once for each successful call to xCreate().
  188039. **
  188040. ** xTokenize:
  188041. ** This function is expected to tokenize the nText byte string indicated
  188042. ** by argument pText. pText may or may not be nul-terminated. The first
  188043. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  188044. ** returned by an earlier call to xCreate().
  188045. **
  188046. ** The second argument indicates the reason that FTS5 is requesting
  188047. ** tokenization of the supplied text. This is always one of the following
  188048. ** four values:
  188049. **
  188050. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  188051. ** or removed from the FTS table. The tokenizer is being invoked to
  188052. ** determine the set of tokens to add to (or delete from) the
  188053. ** FTS index.
  188054. **
  188055. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  188056. ** against the FTS index. The tokenizer is being called to tokenize
  188057. ** a bareword or quoted string specified as part of the query.
  188058. **
  188059. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  188060. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  188061. ** followed by a "*" character, indicating that the last token
  188062. ** returned by the tokenizer will be treated as a token prefix.
  188063. **
  188064. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  188065. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  188066. ** function. Or an fts5_api.xColumnSize() request made by the same
  188067. ** on a columnsize=0 database.
  188068. ** </ul>
  188069. **
  188070. ** For each token in the input string, the supplied callback xToken() must
  188071. ** be invoked. The first argument to it should be a copy of the pointer
  188072. ** passed as the second argument to xTokenize(). The third and fourth
  188073. ** arguments are a pointer to a buffer containing the token text, and the
  188074. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  188075. ** of the first byte of and first byte immediately following the text from
  188076. ** which the token is derived within the input.
  188077. **
  188078. ** The second argument passed to the xToken() callback ("tflags") should
  188079. ** normally be set to 0. The exception is if the tokenizer supports
  188080. ** synonyms. In this case see the discussion below for details.
  188081. **
  188082. ** FTS5 assumes the xToken() callback is invoked for each token in the
  188083. ** order that they occur within the input text.
  188084. **
  188085. ** If an xToken() callback returns any value other than SQLITE_OK, then
  188086. ** the tokenization should be abandoned and the xTokenize() method should
  188087. ** immediately return a copy of the xToken() return value. Or, if the
  188088. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  188089. ** if an error occurs with the xTokenize() implementation itself, it
  188090. ** may abandon the tokenization and return any error code other than
  188091. ** SQLITE_OK or SQLITE_DONE.
  188092. **
  188093. ** SYNONYM SUPPORT
  188094. **
  188095. ** Custom tokenizers may also support synonyms. Consider a case in which a
  188096. ** user wishes to query for a phrase such as "first place". Using the
  188097. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  188098. ** of "first place" within the document set, but not alternative forms
  188099. ** such as "1st place". In some applications, it would be better to match
  188100. ** all instances of "first place" or "1st place" regardless of which form
  188101. ** the user specified in the MATCH query text.
  188102. **
  188103. ** There are several ways to approach this in FTS5:
  188104. **
  188105. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  188106. ** In the above example, this means that the tokenizer returns the
  188107. ** same token for inputs "first" and "1st". Say that token is in
  188108. ** fact "first", so that when the user inserts the document "I won
  188109. ** 1st place" entries are added to the index for tokens "i", "won",
  188110. ** "first" and "place". If the user then queries for '1st + place',
  188111. ** the tokenizer substitutes "first" for "1st" and the query works
  188112. ** as expected.
  188113. **
  188114. ** <li> By querying the index for all synonyms of each query term
  188115. ** separately. In this case, when tokenizing query text, the
  188116. ** tokenizer may provide multiple synonyms for a single term
  188117. ** within the document. FTS5 then queries the index for each
  188118. ** synonym individually. For example, faced with the query:
  188119. **
  188120. ** <codeblock>
  188121. ** ... MATCH 'first place'</codeblock>
  188122. **
  188123. ** the tokenizer offers both "1st" and "first" as synonyms for the
  188124. ** first token in the MATCH query and FTS5 effectively runs a query
  188125. ** similar to:
  188126. **
  188127. ** <codeblock>
  188128. ** ... MATCH '(first OR 1st) place'</codeblock>
  188129. **
  188130. ** except that, for the purposes of auxiliary functions, the query
  188131. ** still appears to contain just two phrases - "(first OR 1st)"
  188132. ** being treated as a single phrase.
  188133. **
  188134. ** <li> By adding multiple synonyms for a single term to the FTS index.
  188135. ** Using this method, when tokenizing document text, the tokenizer
  188136. ** provides multiple synonyms for each token. So that when a
  188137. ** document such as "I won first place" is tokenized, entries are
  188138. ** added to the FTS index for "i", "won", "first", "1st" and
  188139. ** "place".
  188140. **
  188141. ** This way, even if the tokenizer does not provide synonyms
  188142. ** when tokenizing query text (it should not - to do so would be
  188143. ** inefficient), it doesn't matter if the user queries for
  188144. ** 'first + place' or '1st + place', as there are entries in the
  188145. ** FTS index corresponding to both forms of the first token.
  188146. ** </ol>
  188147. **
  188148. ** Whether it is parsing document or query text, any call to xToken that
  188149. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  188150. ** is considered to supply a synonym for the previous token. For example,
  188151. ** when parsing the document "I won first place", a tokenizer that supports
  188152. ** synonyms would call xToken() 5 times, as follows:
  188153. **
  188154. ** <codeblock>
  188155. ** xToken(pCtx, 0, "i", 1, 0, 1);
  188156. ** xToken(pCtx, 0, "won", 3, 2, 5);
  188157. ** xToken(pCtx, 0, "first", 5, 6, 11);
  188158. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  188159. ** xToken(pCtx, 0, "place", 5, 12, 17);
  188160. **</codeblock>
  188161. **
  188162. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  188163. ** xToken() is called. Multiple synonyms may be specified for a single token
  188164. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  188165. ** There is no limit to the number of synonyms that may be provided for a
  188166. ** single token.
  188167. **
  188168. ** In many cases, method (1) above is the best approach. It does not add
  188169. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  188170. ** so it is efficient in terms of disk space and query speed. However, it
  188171. ** does not support prefix queries very well. If, as suggested above, the
  188172. ** token "first" is substituted for "1st" by the tokenizer, then the query:
  188173. **
  188174. ** <codeblock>
  188175. ** ... MATCH '1s*'</codeblock>
  188176. **
  188177. ** will not match documents that contain the token "1st" (as the tokenizer
  188178. ** will probably not map "1s" to any prefix of "first").
  188179. **
  188180. ** For full prefix support, method (3) may be preferred. In this case,
  188181. ** because the index contains entries for both "first" and "1st", prefix
  188182. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  188183. ** extra entries are added to the FTS index, this method uses more space
  188184. ** within the database.
  188185. **
  188186. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  188187. ** a query such as '1s*' will match documents that contain the literal
  188188. ** token "1st", but not "first" (assuming the tokenizer is not able to
  188189. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  188190. ** will match against "1st" and "first". This method does not require
  188191. ** extra disk space, as no extra entries are added to the FTS index.
  188192. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  188193. ** as separate queries of the FTS index are required for each synonym.
  188194. **
  188195. ** When using methods (2) or (3), it is important that the tokenizer only
  188196. ** provide synonyms when tokenizing document text (method (2)) or query
  188197. ** text (method (3)), not both. Doing so will not cause any errors, but is
  188198. ** inefficient.
  188199. */
  188200. typedef struct Fts5Tokenizer Fts5Tokenizer;
  188201. typedef struct fts5_tokenizer fts5_tokenizer;
  188202. struct fts5_tokenizer {
  188203. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  188204. void (*xDelete)(Fts5Tokenizer*);
  188205. int (*xTokenize)(Fts5Tokenizer*,
  188206. void *pCtx,
  188207. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  188208. const char *pText, int nText,
  188209. int (*xToken)(
  188210. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  188211. int tflags, /* Mask of FTS5_TOKEN_* flags */
  188212. const char *pToken, /* Pointer to buffer containing token */
  188213. int nToken, /* Size of token in bytes */
  188214. int iStart, /* Byte offset of token within input text */
  188215. int iEnd /* Byte offset of end of token within input text */
  188216. )
  188217. );
  188218. };
  188219. /* Flags that may be passed as the third argument to xTokenize() */
  188220. #define FTS5_TOKENIZE_QUERY 0x0001
  188221. #define FTS5_TOKENIZE_PREFIX 0x0002
  188222. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  188223. #define FTS5_TOKENIZE_AUX 0x0008
  188224. /* Flags that may be passed by the tokenizer implementation back to FTS5
  188225. ** as the third argument to the supplied xToken callback. */
  188226. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  188227. /*
  188228. ** END OF CUSTOM TOKENIZERS
  188229. *************************************************************************/
  188230. /*************************************************************************
  188231. ** FTS5 EXTENSION REGISTRATION API
  188232. */
  188233. typedef struct fts5_api fts5_api;
  188234. struct fts5_api {
  188235. int iVersion; /* Currently always set to 2 */
  188236. /* Create a new tokenizer */
  188237. int (*xCreateTokenizer)(
  188238. fts5_api *pApi,
  188239. const char *zName,
  188240. void *pContext,
  188241. fts5_tokenizer *pTokenizer,
  188242. void (*xDestroy)(void*)
  188243. );
  188244. /* Find an existing tokenizer */
  188245. int (*xFindTokenizer)(
  188246. fts5_api *pApi,
  188247. const char *zName,
  188248. void **ppContext,
  188249. fts5_tokenizer *pTokenizer
  188250. );
  188251. /* Create a new auxiliary function */
  188252. int (*xCreateFunction)(
  188253. fts5_api *pApi,
  188254. const char *zName,
  188255. void *pContext,
  188256. fts5_extension_function xFunction,
  188257. void (*xDestroy)(void*)
  188258. );
  188259. };
  188260. /*
  188261. ** END OF REGISTRATION API
  188262. *************************************************************************/
  188263. #if 0
  188264. } /* end of the 'extern "C"' block */
  188265. #endif
  188266. #endif /* _FTS5_H */
  188267. /*
  188268. ** 2014 May 31
  188269. **
  188270. ** The author disclaims copyright to this source code. In place of
  188271. ** a legal notice, here is a blessing:
  188272. **
  188273. ** May you do good and not evil.
  188274. ** May you find forgiveness for yourself and forgive others.
  188275. ** May you share freely, never taking more than you give.
  188276. **
  188277. ******************************************************************************
  188278. **
  188279. */
  188280. #ifndef _FTS5INT_H
  188281. #define _FTS5INT_H
  188282. /* #include "fts5.h" */
  188283. /* #include "sqlite3ext.h" */
  188284. SQLITE_EXTENSION_INIT1
  188285. /* #include <string.h> */
  188286. /* #include <assert.h> */
  188287. #ifndef SQLITE_AMALGAMATION
  188288. typedef unsigned char u8;
  188289. typedef unsigned int u32;
  188290. typedef unsigned short u16;
  188291. typedef short i16;
  188292. typedef sqlite3_int64 i64;
  188293. typedef sqlite3_uint64 u64;
  188294. #ifndef ArraySize
  188295. # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
  188296. #endif
  188297. #define testcase(x)
  188298. #define ALWAYS(x) 1
  188299. #define NEVER(x) 0
  188300. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  188301. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  188302. /*
  188303. ** Constants for the largest and smallest possible 64-bit signed integers.
  188304. */
  188305. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  188306. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  188307. #endif
  188308. /* Truncate very long tokens to this many bytes. Hard limit is
  188309. ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
  188310. ** field that occurs at the start of each leaf page (see fts5_index.c). */
  188311. #define FTS5_MAX_TOKEN_SIZE 32768
  188312. /*
  188313. ** Maximum number of prefix indexes on single FTS5 table. This must be
  188314. ** less than 32. If it is set to anything large than that, an #error
  188315. ** directive in fts5_index.c will cause the build to fail.
  188316. */
  188317. #define FTS5_MAX_PREFIX_INDEXES 31
  188318. #define FTS5_DEFAULT_NEARDIST 10
  188319. #define FTS5_DEFAULT_RANK "bm25"
  188320. /* Name of rank and rowid columns */
  188321. #define FTS5_RANK_NAME "rank"
  188322. #define FTS5_ROWID_NAME "rowid"
  188323. #ifdef SQLITE_DEBUG
  188324. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  188325. static int sqlite3Fts5Corrupt(void);
  188326. #else
  188327. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  188328. #endif
  188329. /*
  188330. ** The assert_nc() macro is similar to the assert() macro, except that it
  188331. ** is used for assert() conditions that are true only if it can be
  188332. ** guranteed that the database is not corrupt.
  188333. */
  188334. #ifdef SQLITE_DEBUG
  188335. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  188336. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  188337. #else
  188338. # define assert_nc(x) assert(x)
  188339. #endif
  188340. /*
  188341. ** A version of memcmp() that does not cause asan errors if one of the pointer
  188342. ** parameters is NULL and the number of bytes to compare is zero.
  188343. */
  188344. #define fts5Memcmp(s1, s2, n) ((n)==0 ? 0 : memcmp((s1), (s2), (n)))
  188345. /* Mark a function parameter as unused, to suppress nuisance compiler
  188346. ** warnings. */
  188347. #ifndef UNUSED_PARAM
  188348. # define UNUSED_PARAM(X) (void)(X)
  188349. #endif
  188350. #ifndef UNUSED_PARAM2
  188351. # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
  188352. #endif
  188353. typedef struct Fts5Global Fts5Global;
  188354. typedef struct Fts5Colset Fts5Colset;
  188355. /* If a NEAR() clump or phrase may only match a specific set of columns,
  188356. ** then an object of the following type is used to record the set of columns.
  188357. ** Each entry in the aiCol[] array is a column that may be matched.
  188358. **
  188359. ** This object is used by fts5_expr.c and fts5_index.c.
  188360. */
  188361. struct Fts5Colset {
  188362. int nCol;
  188363. int aiCol[1];
  188364. };
  188365. /**************************************************************************
  188366. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  188367. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  188368. */
  188369. typedef struct Fts5Config Fts5Config;
  188370. /*
  188371. ** An instance of the following structure encodes all information that can
  188372. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  188373. **
  188374. ** And all information loaded from the %_config table.
  188375. **
  188376. ** nAutomerge:
  188377. ** The minimum number of segments that an auto-merge operation should
  188378. ** attempt to merge together. A value of 1 sets the object to use the
  188379. ** compile time default. Zero disables auto-merge altogether.
  188380. **
  188381. ** zContent:
  188382. **
  188383. ** zContentRowid:
  188384. ** The value of the content_rowid= option, if one was specified. Or
  188385. ** the string "rowid" otherwise. This text is not quoted - if it is
  188386. ** used as part of an SQL statement it needs to be quoted appropriately.
  188387. **
  188388. ** zContentExprlist:
  188389. **
  188390. ** pzErrmsg:
  188391. ** This exists in order to allow the fts5_index.c module to return a
  188392. ** decent error message if it encounters a file-format version it does
  188393. ** not understand.
  188394. **
  188395. ** bColumnsize:
  188396. ** True if the %_docsize table is created.
  188397. **
  188398. ** bPrefixIndex:
  188399. ** This is only used for debugging. If set to false, any prefix indexes
  188400. ** are ignored. This value is configured using:
  188401. **
  188402. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  188403. **
  188404. */
  188405. struct Fts5Config {
  188406. sqlite3 *db; /* Database handle */
  188407. char *zDb; /* Database holding FTS index (e.g. "main") */
  188408. char *zName; /* Name of FTS index */
  188409. int nCol; /* Number of columns */
  188410. char **azCol; /* Column names */
  188411. u8 *abUnindexed; /* True for unindexed columns */
  188412. int nPrefix; /* Number of prefix indexes */
  188413. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  188414. int eContent; /* An FTS5_CONTENT value */
  188415. char *zContent; /* content table */
  188416. char *zContentRowid; /* "content_rowid=" option value */
  188417. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  188418. int eDetail; /* FTS5_DETAIL_XXX value */
  188419. char *zContentExprlist;
  188420. Fts5Tokenizer *pTok;
  188421. fts5_tokenizer *pTokApi;
  188422. /* Values loaded from the %_config table */
  188423. int iCookie; /* Incremented when %_config is modified */
  188424. int pgsz; /* Approximate page size used in %_data */
  188425. int nAutomerge; /* 'automerge' setting */
  188426. int nCrisisMerge; /* Maximum allowed segments per level */
  188427. int nUsermerge; /* 'usermerge' setting */
  188428. int nHashSize; /* Bytes of memory for in-memory hash */
  188429. char *zRank; /* Name of rank function */
  188430. char *zRankArgs; /* Arguments to rank function */
  188431. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  188432. char **pzErrmsg;
  188433. #ifdef SQLITE_DEBUG
  188434. int bPrefixIndex; /* True to use prefix-indexes */
  188435. #endif
  188436. };
  188437. /* Current expected value of %_config table 'version' field */
  188438. #define FTS5_CURRENT_VERSION 4
  188439. #define FTS5_CONTENT_NORMAL 0
  188440. #define FTS5_CONTENT_NONE 1
  188441. #define FTS5_CONTENT_EXTERNAL 2
  188442. #define FTS5_DETAIL_FULL 0
  188443. #define FTS5_DETAIL_NONE 1
  188444. #define FTS5_DETAIL_COLUMNS 2
  188445. static int sqlite3Fts5ConfigParse(
  188446. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  188447. );
  188448. static void sqlite3Fts5ConfigFree(Fts5Config*);
  188449. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  188450. static int sqlite3Fts5Tokenize(
  188451. Fts5Config *pConfig, /* FTS5 Configuration object */
  188452. int flags, /* FTS5_TOKENIZE_* flags */
  188453. const char *pText, int nText, /* Text to tokenize */
  188454. void *pCtx, /* Context passed to xToken() */
  188455. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  188456. );
  188457. static void sqlite3Fts5Dequote(char *z);
  188458. /* Load the contents of the %_config table */
  188459. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  188460. /* Set the value of a single config attribute */
  188461. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  188462. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  188463. /*
  188464. ** End of interface to code in fts5_config.c.
  188465. **************************************************************************/
  188466. /**************************************************************************
  188467. ** Interface to code in fts5_buffer.c.
  188468. */
  188469. /*
  188470. ** Buffer object for the incremental building of string data.
  188471. */
  188472. typedef struct Fts5Buffer Fts5Buffer;
  188473. struct Fts5Buffer {
  188474. u8 *p;
  188475. int n;
  188476. int nSpace;
  188477. };
  188478. static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
  188479. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  188480. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
  188481. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  188482. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  188483. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  188484. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  188485. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  188486. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  188487. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  188488. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  188489. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  188490. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  188491. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  188492. #define fts5BufferGrow(pRc,pBuf,nn) ( \
  188493. (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
  188494. sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
  188495. )
  188496. /* Write and decode big-endian 32-bit integer values */
  188497. static void sqlite3Fts5Put32(u8*, int);
  188498. static int sqlite3Fts5Get32(const u8*);
  188499. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  188500. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0x7FFFFFFF)
  188501. typedef struct Fts5PoslistReader Fts5PoslistReader;
  188502. struct Fts5PoslistReader {
  188503. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  188504. const u8 *a; /* Position list to iterate through */
  188505. int n; /* Size of buffer at a[] in bytes */
  188506. int i; /* Current offset in a[] */
  188507. u8 bFlag; /* For client use (any custom purpose) */
  188508. /* Output variables */
  188509. u8 bEof; /* Set to true at EOF */
  188510. i64 iPos; /* (iCol<<32) + iPos */
  188511. };
  188512. static int sqlite3Fts5PoslistReaderInit(
  188513. const u8 *a, int n, /* Poslist buffer to iterate through */
  188514. Fts5PoslistReader *pIter /* Iterator object to initialize */
  188515. );
  188516. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  188517. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  188518. struct Fts5PoslistWriter {
  188519. i64 iPrev;
  188520. };
  188521. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  188522. static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
  188523. static int sqlite3Fts5PoslistNext64(
  188524. const u8 *a, int n, /* Buffer containing poslist */
  188525. int *pi, /* IN/OUT: Offset within a[] */
  188526. i64 *piOff /* IN/OUT: Current offset */
  188527. );
  188528. /* Malloc utility */
  188529. static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte);
  188530. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  188531. /* Character set tests (like isspace(), isalpha() etc.) */
  188532. static int sqlite3Fts5IsBareword(char t);
  188533. /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
  188534. typedef struct Fts5Termset Fts5Termset;
  188535. static int sqlite3Fts5TermsetNew(Fts5Termset**);
  188536. static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
  188537. static void sqlite3Fts5TermsetFree(Fts5Termset*);
  188538. /*
  188539. ** End of interface to code in fts5_buffer.c.
  188540. **************************************************************************/
  188541. /**************************************************************************
  188542. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  188543. ** to access the data stored in the %_data table.
  188544. */
  188545. typedef struct Fts5Index Fts5Index;
  188546. typedef struct Fts5IndexIter Fts5IndexIter;
  188547. struct Fts5IndexIter {
  188548. i64 iRowid;
  188549. const u8 *pData;
  188550. int nData;
  188551. u8 bEof;
  188552. };
  188553. #define sqlite3Fts5IterEof(x) ((x)->bEof)
  188554. /*
  188555. ** Values used as part of the flags argument passed to IndexQuery().
  188556. */
  188557. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  188558. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  188559. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  188560. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  188561. /* The following are used internally by the fts5_index.c module. They are
  188562. ** defined here only to make it easier to avoid clashes with the flags
  188563. ** above. */
  188564. #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
  188565. #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
  188566. /*
  188567. ** Create/destroy an Fts5Index object.
  188568. */
  188569. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  188570. static int sqlite3Fts5IndexClose(Fts5Index *p);
  188571. /*
  188572. ** Return a simple checksum value based on the arguments.
  188573. */
  188574. static u64 sqlite3Fts5IndexEntryCksum(
  188575. i64 iRowid,
  188576. int iCol,
  188577. int iPos,
  188578. int iIdx,
  188579. const char *pTerm,
  188580. int nTerm
  188581. );
  188582. /*
  188583. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  188584. ** size. Return the number of bytes in the nChar character prefix of the
  188585. ** buffer, or 0 if there are less than nChar characters in total.
  188586. */
  188587. static int sqlite3Fts5IndexCharlenToBytelen(
  188588. const char *p,
  188589. int nByte,
  188590. int nChar
  188591. );
  188592. /*
  188593. ** Open a new iterator to iterate though all rowids that match the
  188594. ** specified token or token prefix.
  188595. */
  188596. static int sqlite3Fts5IndexQuery(
  188597. Fts5Index *p, /* FTS index to query */
  188598. const char *pToken, int nToken, /* Token (or prefix) to query for */
  188599. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  188600. Fts5Colset *pColset, /* Match these columns only */
  188601. Fts5IndexIter **ppIter /* OUT: New iterator object */
  188602. );
  188603. /*
  188604. ** The various operations on open token or token prefix iterators opened
  188605. ** using sqlite3Fts5IndexQuery().
  188606. */
  188607. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  188608. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  188609. /*
  188610. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  188611. */
  188612. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  188613. /*
  188614. ** This interface is used by the fts5vocab module.
  188615. */
  188616. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  188617. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  188618. /*
  188619. ** Insert or remove data to or from the index. Each time a document is
  188620. ** added to or removed from the index, this function is called one or more
  188621. ** times.
  188622. **
  188623. ** For an insert, it must be called once for each token in the new document.
  188624. ** If the operation is a delete, it must be called (at least) once for each
  188625. ** unique token in the document with an iCol value less than zero. The iPos
  188626. ** argument is ignored for a delete.
  188627. */
  188628. static int sqlite3Fts5IndexWrite(
  188629. Fts5Index *p, /* Index to write to */
  188630. int iCol, /* Column token appears in (-ve -> delete) */
  188631. int iPos, /* Position of token within column */
  188632. const char *pToken, int nToken /* Token to add or remove to or from index */
  188633. );
  188634. /*
  188635. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  188636. ** document iDocid.
  188637. */
  188638. static int sqlite3Fts5IndexBeginWrite(
  188639. Fts5Index *p, /* Index to write to */
  188640. int bDelete, /* True if current operation is a delete */
  188641. i64 iDocid /* Docid to add or remove data from */
  188642. );
  188643. /*
  188644. ** Flush any data stored in the in-memory hash tables to the database.
  188645. ** Also close any open blob handles.
  188646. */
  188647. static int sqlite3Fts5IndexSync(Fts5Index *p);
  188648. /*
  188649. ** Discard any data stored in the in-memory hash tables. Do not write it
  188650. ** to the database. Additionally, assume that the contents of the %_data
  188651. ** table may have changed on disk. So any in-memory caches of %_data
  188652. ** records must be invalidated.
  188653. */
  188654. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  188655. /*
  188656. ** Get or set the "averages" values.
  188657. */
  188658. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  188659. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  188660. /*
  188661. ** Functions called by the storage module as part of integrity-check.
  188662. */
  188663. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  188664. /*
  188665. ** Called during virtual module initialization to register UDF
  188666. ** fts5_decode() with SQLite
  188667. */
  188668. static int sqlite3Fts5IndexInit(sqlite3*);
  188669. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  188670. /*
  188671. ** Return the total number of entries read from the %_data table by
  188672. ** this connection since it was created.
  188673. */
  188674. static int sqlite3Fts5IndexReads(Fts5Index *p);
  188675. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  188676. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  188677. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  188678. static int sqlite3Fts5IndexReset(Fts5Index *p);
  188679. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  188680. /*
  188681. ** End of interface to code in fts5_index.c.
  188682. **************************************************************************/
  188683. /**************************************************************************
  188684. ** Interface to code in fts5_varint.c.
  188685. */
  188686. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  188687. static int sqlite3Fts5GetVarintLen(u32 iVal);
  188688. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  188689. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  188690. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  188691. #define fts5GetVarint sqlite3Fts5GetVarint
  188692. #define fts5FastGetVarint32(a, iOff, nVal) { \
  188693. nVal = (a)[iOff++]; \
  188694. if( nVal & 0x80 ){ \
  188695. iOff--; \
  188696. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  188697. } \
  188698. }
  188699. /*
  188700. ** End of interface to code in fts5_varint.c.
  188701. **************************************************************************/
  188702. /**************************************************************************
  188703. ** Interface to code in fts5_main.c.
  188704. */
  188705. /*
  188706. ** Virtual-table object.
  188707. */
  188708. typedef struct Fts5Table Fts5Table;
  188709. struct Fts5Table {
  188710. sqlite3_vtab base; /* Base class used by SQLite core */
  188711. Fts5Config *pConfig; /* Virtual table configuration */
  188712. Fts5Index *pIndex; /* Full-text index */
  188713. };
  188714. static int sqlite3Fts5GetTokenizer(
  188715. Fts5Global*,
  188716. const char **azArg,
  188717. int nArg,
  188718. Fts5Tokenizer**,
  188719. fts5_tokenizer**,
  188720. char **pzErr
  188721. );
  188722. static Fts5Table *sqlite3Fts5TableFromCsrid(Fts5Global*, i64);
  188723. static int sqlite3Fts5FlushToDisk(Fts5Table*);
  188724. /*
  188725. ** End of interface to code in fts5.c.
  188726. **************************************************************************/
  188727. /**************************************************************************
  188728. ** Interface to code in fts5_hash.c.
  188729. */
  188730. typedef struct Fts5Hash Fts5Hash;
  188731. /*
  188732. ** Create a hash table, free a hash table.
  188733. */
  188734. static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
  188735. static void sqlite3Fts5HashFree(Fts5Hash*);
  188736. static int sqlite3Fts5HashWrite(
  188737. Fts5Hash*,
  188738. i64 iRowid, /* Rowid for this entry */
  188739. int iCol, /* Column token appears in (-ve -> delete) */
  188740. int iPos, /* Position of token within column */
  188741. char bByte,
  188742. const char *pToken, int nToken /* Token to add or remove to or from index */
  188743. );
  188744. /*
  188745. ** Empty (but do not delete) a hash table.
  188746. */
  188747. static void sqlite3Fts5HashClear(Fts5Hash*);
  188748. static int sqlite3Fts5HashQuery(
  188749. Fts5Hash*, /* Hash table to query */
  188750. int nPre,
  188751. const char *pTerm, int nTerm, /* Query term */
  188752. void **ppObj, /* OUT: Pointer to doclist for pTerm */
  188753. int *pnDoclist /* OUT: Size of doclist in bytes */
  188754. );
  188755. static int sqlite3Fts5HashScanInit(
  188756. Fts5Hash*, /* Hash table to query */
  188757. const char *pTerm, int nTerm /* Query prefix */
  188758. );
  188759. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  188760. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  188761. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  188762. const char **pzTerm, /* OUT: term (nul-terminated) */
  188763. const u8 **ppDoclist, /* OUT: pointer to doclist */
  188764. int *pnDoclist /* OUT: size of doclist in bytes */
  188765. );
  188766. /*
  188767. ** End of interface to code in fts5_hash.c.
  188768. **************************************************************************/
  188769. /**************************************************************************
  188770. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  188771. ** code to access the data stored in the %_content and %_docsize tables.
  188772. */
  188773. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  188774. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  188775. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  188776. typedef struct Fts5Storage Fts5Storage;
  188777. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  188778. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  188779. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  188780. static int sqlite3Fts5DropAll(Fts5Config*);
  188781. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  188782. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
  188783. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  188784. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  188785. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  188786. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  188787. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  188788. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  188789. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  188790. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  188791. static int sqlite3Fts5StorageSync(Fts5Storage *p);
  188792. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  188793. static int sqlite3Fts5StorageConfigValue(
  188794. Fts5Storage *p, const char*, sqlite3_value*, int
  188795. );
  188796. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  188797. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  188798. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  188799. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  188800. static int sqlite3Fts5StorageReset(Fts5Storage *p);
  188801. /*
  188802. ** End of interface to code in fts5_storage.c.
  188803. **************************************************************************/
  188804. /**************************************************************************
  188805. ** Interface to code in fts5_expr.c.
  188806. */
  188807. typedef struct Fts5Expr Fts5Expr;
  188808. typedef struct Fts5ExprNode Fts5ExprNode;
  188809. typedef struct Fts5Parse Fts5Parse;
  188810. typedef struct Fts5Token Fts5Token;
  188811. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  188812. typedef struct Fts5ExprNearset Fts5ExprNearset;
  188813. struct Fts5Token {
  188814. const char *p; /* Token text (not NULL terminated) */
  188815. int n; /* Size of buffer p in bytes */
  188816. };
  188817. /* Parse a MATCH expression. */
  188818. static int sqlite3Fts5ExprNew(
  188819. Fts5Config *pConfig,
  188820. int iCol, /* Column on LHS of MATCH operator */
  188821. const char *zExpr,
  188822. Fts5Expr **ppNew,
  188823. char **pzErr
  188824. );
  188825. /*
  188826. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  188827. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  188828. ** rc = sqlite3Fts5ExprNext(pExpr)
  188829. ** ){
  188830. ** // The document with rowid iRowid matches the expression!
  188831. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  188832. ** }
  188833. */
  188834. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  188835. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  188836. static int sqlite3Fts5ExprEof(Fts5Expr*);
  188837. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  188838. static void sqlite3Fts5ExprFree(Fts5Expr*);
  188839. /* Called during startup to register a UDF with SQLite */
  188840. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  188841. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  188842. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  188843. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  188844. typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
  188845. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
  188846. static int sqlite3Fts5ExprPopulatePoslists(
  188847. Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
  188848. );
  188849. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
  188850. static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
  188851. static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
  188852. /*******************************************
  188853. ** The fts5_expr.c API above this point is used by the other hand-written
  188854. ** C code in this module. The interfaces below this point are called by
  188855. ** the parser code in fts5parse.y. */
  188856. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  188857. static Fts5ExprNode *sqlite3Fts5ParseNode(
  188858. Fts5Parse *pParse,
  188859. int eType,
  188860. Fts5ExprNode *pLeft,
  188861. Fts5ExprNode *pRight,
  188862. Fts5ExprNearset *pNear
  188863. );
  188864. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  188865. Fts5Parse *pParse,
  188866. Fts5ExprNode *pLeft,
  188867. Fts5ExprNode *pRight
  188868. );
  188869. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  188870. Fts5Parse *pParse,
  188871. Fts5ExprPhrase *pPhrase,
  188872. Fts5Token *pToken,
  188873. int bPrefix
  188874. );
  188875. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);
  188876. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  188877. Fts5Parse*,
  188878. Fts5ExprNearset*,
  188879. Fts5ExprPhrase*
  188880. );
  188881. static Fts5Colset *sqlite3Fts5ParseColset(
  188882. Fts5Parse*,
  188883. Fts5Colset*,
  188884. Fts5Token *
  188885. );
  188886. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  188887. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  188888. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  188889. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  188890. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
  188891. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
  188892. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  188893. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  188894. /*
  188895. ** End of interface to code in fts5_expr.c.
  188896. **************************************************************************/
  188897. /**************************************************************************
  188898. ** Interface to code in fts5_aux.c.
  188899. */
  188900. static int sqlite3Fts5AuxInit(fts5_api*);
  188901. /*
  188902. ** End of interface to code in fts5_aux.c.
  188903. **************************************************************************/
  188904. /**************************************************************************
  188905. ** Interface to code in fts5_tokenizer.c.
  188906. */
  188907. static int sqlite3Fts5TokenizerInit(fts5_api*);
  188908. /*
  188909. ** End of interface to code in fts5_tokenizer.c.
  188910. **************************************************************************/
  188911. /**************************************************************************
  188912. ** Interface to code in fts5_vocab.c.
  188913. */
  188914. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  188915. /*
  188916. ** End of interface to code in fts5_vocab.c.
  188917. **************************************************************************/
  188918. /**************************************************************************
  188919. ** Interface to automatically generated code in fts5_unicode2.c.
  188920. */
  188921. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  188922. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  188923. static int sqlite3Fts5UnicodeCatParse(const char*, u8*);
  188924. static int sqlite3Fts5UnicodeCategory(u32 iCode);
  188925. static void sqlite3Fts5UnicodeAscii(u8*, u8*);
  188926. /*
  188927. ** End of interface to code in fts5_unicode2.c.
  188928. **************************************************************************/
  188929. #endif
  188930. #define FTS5_OR 1
  188931. #define FTS5_AND 2
  188932. #define FTS5_NOT 3
  188933. #define FTS5_TERM 4
  188934. #define FTS5_COLON 5
  188935. #define FTS5_MINUS 6
  188936. #define FTS5_LCP 7
  188937. #define FTS5_RCP 8
  188938. #define FTS5_STRING 9
  188939. #define FTS5_LP 10
  188940. #define FTS5_RP 11
  188941. #define FTS5_CARET 12
  188942. #define FTS5_COMMA 13
  188943. #define FTS5_PLUS 14
  188944. #define FTS5_STAR 15
  188945. /*
  188946. ** 2000-05-29
  188947. **
  188948. ** The author disclaims copyright to this source code. In place of
  188949. ** a legal notice, here is a blessing:
  188950. **
  188951. ** May you do good and not evil.
  188952. ** May you find forgiveness for yourself and forgive others.
  188953. ** May you share freely, never taking more than you give.
  188954. **
  188955. *************************************************************************
  188956. ** Driver template for the LEMON parser generator.
  188957. **
  188958. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  188959. ** this template to construct a parser. The "lemon" program inserts text
  188960. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  188961. ** interstitial "-" characters) contained in this template is changed into
  188962. ** the value of the %name directive from the grammar. Otherwise, the content
  188963. ** of this template is copied straight through into the generate parser
  188964. ** source file.
  188965. **
  188966. ** The following is the concatenation of all %include directives from the
  188967. ** input grammar file:
  188968. */
  188969. /* #include <stdio.h> */
  188970. /* #include <assert.h> */
  188971. /************ Begin %include sections from the grammar ************************/
  188972. /* #include "fts5Int.h" */
  188973. /* #include "fts5parse.h" */
  188974. /*
  188975. ** Disable all error recovery processing in the parser push-down
  188976. ** automaton.
  188977. */
  188978. #define fts5YYNOERRORRECOVERY 1
  188979. /*
  188980. ** Make fts5yytestcase() the same as testcase()
  188981. */
  188982. #define fts5yytestcase(X) testcase(X)
  188983. /*
  188984. ** Indicate that sqlite3ParserFree() will never be called with a null
  188985. ** pointer.
  188986. */
  188987. #define fts5YYPARSEFREENOTNULL 1
  188988. /*
  188989. ** Alternative datatype for the argument to the malloc() routine passed
  188990. ** into sqlite3ParserAlloc(). The default is size_t.
  188991. */
  188992. #define fts5YYMALLOCARGTYPE u64
  188993. /**************** End of %include directives **********************************/
  188994. /* These constants specify the various numeric values for terminal symbols
  188995. ** in a format understandable to "makeheaders". This section is blank unless
  188996. ** "lemon" is run with the "-m" command-line option.
  188997. ***************** Begin makeheaders token definitions *************************/
  188998. /**************** End makeheaders token definitions ***************************/
  188999. /* The next sections is a series of control #defines.
  189000. ** various aspects of the generated parser.
  189001. ** fts5YYCODETYPE is the data type used to store the integer codes
  189002. ** that represent terminal and non-terminal symbols.
  189003. ** "unsigned char" is used if there are fewer than
  189004. ** 256 symbols. Larger types otherwise.
  189005. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
  189006. ** any terminal or nonterminal symbol.
  189007. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  189008. ** (also known as: "terminal symbols") have fall-back
  189009. ** values which should be used if the original symbol
  189010. ** would not parse. This permits keywords to sometimes
  189011. ** be used as identifiers, for example.
  189012. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
  189013. ** that indicate what to do in response to the next
  189014. ** token.
  189015. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
  189016. ** symbols. Background: A "minor type" is a semantic
  189017. ** value associated with a terminal or non-terminal
  189018. ** symbols. For example, for an "ID" terminal symbol,
  189019. ** the minor type might be the name of the identifier.
  189020. ** Each non-terminal can have a different minor type.
  189021. ** Terminal symbols all have the same minor type, though.
  189022. ** This macros defines the minor type for terminal
  189023. ** symbols.
  189024. ** fts5YYMINORTYPE is the data type used for all minor types.
  189025. ** This is typically a union of many types, one of
  189026. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  189027. ** for terminal symbols is called "fts5yy0".
  189028. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  189029. ** zero the stack is dynamically sized using realloc()
  189030. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  189031. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  189032. ** sqlite3Fts5ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
  189033. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  189034. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  189035. ** sqlite3Fts5ParserCTX_* As sqlite3Fts5ParserARG_ except for %extra_context
  189036. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  189037. ** defined, then do no error processing.
  189038. ** fts5YYNSTATE the combined number of states.
  189039. ** fts5YYNRULE the number of rules in the grammar
  189040. ** fts5YYNFTS5TOKEN Number of terminal symbols
  189041. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  189042. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  189043. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  189044. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  189045. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  189046. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  189047. ** fts5YY_MIN_REDUCE Minimum value for reduce actions
  189048. ** fts5YY_MAX_REDUCE Maximum value for reduce actions
  189049. */
  189050. #ifndef INTERFACE
  189051. # define INTERFACE 1
  189052. #endif
  189053. /************* Begin control #defines *****************************************/
  189054. #define fts5YYCODETYPE unsigned char
  189055. #define fts5YYNOCODE 27
  189056. #define fts5YYACTIONTYPE unsigned char
  189057. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  189058. typedef union {
  189059. int fts5yyinit;
  189060. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  189061. int fts5yy4;
  189062. Fts5Colset* fts5yy11;
  189063. Fts5ExprNode* fts5yy24;
  189064. Fts5ExprNearset* fts5yy46;
  189065. Fts5ExprPhrase* fts5yy53;
  189066. } fts5YYMINORTYPE;
  189067. #ifndef fts5YYSTACKDEPTH
  189068. #define fts5YYSTACKDEPTH 100
  189069. #endif
  189070. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  189071. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  189072. #define sqlite3Fts5ParserARG_PARAM ,pParse
  189073. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse=fts5yypParser->pParse;
  189074. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse=pParse;
  189075. #define sqlite3Fts5ParserCTX_SDECL
  189076. #define sqlite3Fts5ParserCTX_PDECL
  189077. #define sqlite3Fts5ParserCTX_PARAM
  189078. #define sqlite3Fts5ParserCTX_FETCH
  189079. #define sqlite3Fts5ParserCTX_STORE
  189080. #define fts5YYNSTATE 35
  189081. #define fts5YYNRULE 28
  189082. #define fts5YYNFTS5TOKEN 16
  189083. #define fts5YY_MAX_SHIFT 34
  189084. #define fts5YY_MIN_SHIFTREDUCE 52
  189085. #define fts5YY_MAX_SHIFTREDUCE 79
  189086. #define fts5YY_ERROR_ACTION 80
  189087. #define fts5YY_ACCEPT_ACTION 81
  189088. #define fts5YY_NO_ACTION 82
  189089. #define fts5YY_MIN_REDUCE 83
  189090. #define fts5YY_MAX_REDUCE 110
  189091. /************* End control #defines *******************************************/
  189092. #define fts5YY_NLOOKAHEAD ((int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])))
  189093. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  189094. ** otherwise.
  189095. **
  189096. ** Applications can choose to define fts5yytestcase() in the %include section
  189097. ** to a macro that can assist in verifying code coverage. For production
  189098. ** code the fts5yytestcase() macro should be turned off. But it is useful
  189099. ** for testing.
  189100. */
  189101. #ifndef fts5yytestcase
  189102. # define fts5yytestcase(X)
  189103. #endif
  189104. /* Next are the tables used to determine what action to take based on the
  189105. ** current state and lookahead token. These tables are used to implement
  189106. ** functions that take a state number and lookahead value and return an
  189107. ** action integer.
  189108. **
  189109. ** Suppose the action integer is N. Then the action is determined as
  189110. ** follows
  189111. **
  189112. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  189113. ** token onto the stack and goto state N.
  189114. **
  189115. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  189116. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  189117. **
  189118. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  189119. **
  189120. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  189121. **
  189122. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  189123. ** slots in the fts5yy_action[] table.
  189124. **
  189125. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  189126. ** and fts5YY_MAX_REDUCE
  189127. **
  189128. ** The action table is constructed as a single large table named fts5yy_action[].
  189129. ** Given state S and lookahead X, the action is computed as either:
  189130. **
  189131. ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  189132. ** (B) N = fts5yy_default[S]
  189133. **
  189134. ** The (A) formula is preferred. The B formula is used instead if
  189135. ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X.
  189136. **
  189137. ** The formulas above are for computing the action when the lookahead is
  189138. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  189139. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  189140. ** the fts5yy_shift_ofst[] array.
  189141. **
  189142. ** The following are the tables generated in this section:
  189143. **
  189144. ** fts5yy_action[] A single table containing all actions.
  189145. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  189146. ** fts5yy_action. Used to detect hash collisions.
  189147. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  189148. ** shifting terminals.
  189149. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  189150. ** shifting non-terminals after a reduce.
  189151. ** fts5yy_default[] Default action for each state.
  189152. **
  189153. *********** Begin parsing tables **********************************************/
  189154. #define fts5YY_ACTTAB_COUNT (105)
  189155. static const fts5YYACTIONTYPE fts5yy_action[] = {
  189156. /* 0 */ 81, 20, 96, 6, 28, 99, 98, 26, 26, 18,
  189157. /* 10 */ 96, 6, 28, 17, 98, 56, 26, 19, 96, 6,
  189158. /* 20 */ 28, 14, 98, 14, 26, 31, 92, 96, 6, 28,
  189159. /* 30 */ 108, 98, 25, 26, 21, 96, 6, 28, 78, 98,
  189160. /* 40 */ 58, 26, 29, 96, 6, 28, 107, 98, 22, 26,
  189161. /* 50 */ 24, 16, 12, 11, 1, 13, 13, 24, 16, 23,
  189162. /* 60 */ 11, 33, 34, 13, 97, 8, 27, 32, 98, 7,
  189163. /* 70 */ 26, 3, 4, 5, 3, 4, 5, 3, 83, 4,
  189164. /* 80 */ 5, 3, 63, 5, 3, 62, 12, 2, 86, 13,
  189165. /* 90 */ 9, 30, 10, 10, 54, 57, 75, 78, 78, 53,
  189166. /* 100 */ 57, 15, 82, 82, 71,
  189167. };
  189168. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  189169. /* 0 */ 16, 17, 18, 19, 20, 22, 22, 24, 24, 17,
  189170. /* 10 */ 18, 19, 20, 7, 22, 9, 24, 17, 18, 19,
  189171. /* 20 */ 20, 9, 22, 9, 24, 13, 17, 18, 19, 20,
  189172. /* 30 */ 26, 22, 24, 24, 17, 18, 19, 20, 15, 22,
  189173. /* 40 */ 9, 24, 17, 18, 19, 20, 26, 22, 21, 24,
  189174. /* 50 */ 6, 7, 9, 9, 10, 12, 12, 6, 7, 21,
  189175. /* 60 */ 9, 24, 25, 12, 18, 5, 20, 14, 22, 5,
  189176. /* 70 */ 24, 3, 1, 2, 3, 1, 2, 3, 0, 1,
  189177. /* 80 */ 2, 3, 11, 2, 3, 11, 9, 10, 5, 12,
  189178. /* 90 */ 23, 24, 10, 10, 8, 9, 9, 15, 15, 8,
  189179. /* 100 */ 9, 9, 27, 27, 11, 27, 27, 27, 27, 27,
  189180. /* 110 */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  189181. /* 120 */ 27,
  189182. };
  189183. #define fts5YY_SHIFT_COUNT (34)
  189184. #define fts5YY_SHIFT_MIN (0)
  189185. #define fts5YY_SHIFT_MAX (93)
  189186. static const unsigned char fts5yy_shift_ofst[] = {
  189187. /* 0 */ 44, 44, 44, 44, 44, 44, 51, 77, 43, 12,
  189188. /* 10 */ 14, 83, 82, 14, 23, 23, 31, 31, 71, 74,
  189189. /* 20 */ 78, 81, 86, 91, 6, 53, 53, 60, 64, 68,
  189190. /* 30 */ 53, 87, 92, 53, 93,
  189191. };
  189192. #define fts5YY_REDUCE_COUNT (17)
  189193. #define fts5YY_REDUCE_MIN (-17)
  189194. #define fts5YY_REDUCE_MAX (67)
  189195. static const signed char fts5yy_reduce_ofst[] = {
  189196. /* 0 */ -16, -8, 0, 9, 17, 25, 46, -17, -17, 37,
  189197. /* 10 */ 67, 4, 4, 8, 4, 20, 27, 38,
  189198. };
  189199. static const fts5YYACTIONTYPE fts5yy_default[] = {
  189200. /* 0 */ 80, 80, 80, 80, 80, 80, 95, 80, 80, 105,
  189201. /* 10 */ 80, 110, 110, 80, 110, 110, 80, 80, 80, 80,
  189202. /* 20 */ 80, 91, 80, 80, 80, 101, 100, 80, 80, 90,
  189203. /* 30 */ 103, 80, 80, 104, 80,
  189204. };
  189205. /********** End of lemon-generated parsing tables *****************************/
  189206. /* The next table maps tokens (terminal symbols) into fallback tokens.
  189207. ** If a construct like the following:
  189208. **
  189209. ** %fallback ID X Y Z.
  189210. **
  189211. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  189212. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  189213. ** but it does not parse, the type of the token is changed to ID and
  189214. ** the parse is retried before an error is thrown.
  189215. **
  189216. ** This feature can be used, for example, to cause some keywords in a language
  189217. ** to revert to identifiers if they keyword does not apply in the context where
  189218. ** it appears.
  189219. */
  189220. #ifdef fts5YYFALLBACK
  189221. static const fts5YYCODETYPE fts5yyFallback[] = {
  189222. };
  189223. #endif /* fts5YYFALLBACK */
  189224. /* The following structure represents a single element of the
  189225. ** parser's stack. Information stored includes:
  189226. **
  189227. ** + The state number for the parser at this level of the stack.
  189228. **
  189229. ** + The value of the token stored at this level of the stack.
  189230. ** (In other words, the "major" token.)
  189231. **
  189232. ** + The semantic value stored at this level of the stack. This is
  189233. ** the information used by the action routines in the grammar.
  189234. ** It is sometimes called the "minor" token.
  189235. **
  189236. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  189237. ** actually contains the reduce action for the second half of the
  189238. ** SHIFTREDUCE.
  189239. */
  189240. struct fts5yyStackEntry {
  189241. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  189242. fts5YYCODETYPE major; /* The major token value. This is the code
  189243. ** number for the token at this stack level */
  189244. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  189245. ** is the value of the token */
  189246. };
  189247. typedef struct fts5yyStackEntry fts5yyStackEntry;
  189248. /* The state of the parser is completely contained in an instance of
  189249. ** the following structure */
  189250. struct fts5yyParser {
  189251. fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
  189252. #ifdef fts5YYTRACKMAXSTACKDEPTH
  189253. int fts5yyhwm; /* High-water mark of the stack */
  189254. #endif
  189255. #ifndef fts5YYNOERRORRECOVERY
  189256. int fts5yyerrcnt; /* Shifts left before out of the error */
  189257. #endif
  189258. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  189259. sqlite3Fts5ParserCTX_SDECL /* A place to hold %extra_context */
  189260. #if fts5YYSTACKDEPTH<=0
  189261. int fts5yystksz; /* Current side of the stack */
  189262. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  189263. fts5yyStackEntry fts5yystk0; /* First stack entry */
  189264. #else
  189265. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  189266. fts5yyStackEntry *fts5yystackEnd; /* Last entry in the stack */
  189267. #endif
  189268. };
  189269. typedef struct fts5yyParser fts5yyParser;
  189270. #ifndef NDEBUG
  189271. /* #include <stdio.h> */
  189272. static FILE *fts5yyTraceFILE = 0;
  189273. static char *fts5yyTracePrompt = 0;
  189274. #endif /* NDEBUG */
  189275. #ifndef NDEBUG
  189276. /*
  189277. ** Turn parser tracing on by giving a stream to which to write the trace
  189278. ** and a prompt to preface each trace message. Tracing is turned off
  189279. ** by making either argument NULL
  189280. **
  189281. ** Inputs:
  189282. ** <ul>
  189283. ** <li> A FILE* to which trace output should be written.
  189284. ** If NULL, then tracing is turned off.
  189285. ** <li> A prefix string written at the beginning of every
  189286. ** line of trace output. If NULL, then tracing is
  189287. ** turned off.
  189288. ** </ul>
  189289. **
  189290. ** Outputs:
  189291. ** None.
  189292. */
  189293. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  189294. fts5yyTraceFILE = TraceFILE;
  189295. fts5yyTracePrompt = zTracePrompt;
  189296. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  189297. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  189298. }
  189299. #endif /* NDEBUG */
  189300. #if defined(fts5YYCOVERAGE) || !defined(NDEBUG)
  189301. /* For tracing shifts, the names of all terminals and nonterminals
  189302. ** are required. The following table supplies these names */
  189303. static const char *const fts5yyTokenName[] = {
  189304. /* 0 */ "$",
  189305. /* 1 */ "OR",
  189306. /* 2 */ "AND",
  189307. /* 3 */ "NOT",
  189308. /* 4 */ "TERM",
  189309. /* 5 */ "COLON",
  189310. /* 6 */ "MINUS",
  189311. /* 7 */ "LCP",
  189312. /* 8 */ "RCP",
  189313. /* 9 */ "STRING",
  189314. /* 10 */ "LP",
  189315. /* 11 */ "RP",
  189316. /* 12 */ "CARET",
  189317. /* 13 */ "COMMA",
  189318. /* 14 */ "PLUS",
  189319. /* 15 */ "STAR",
  189320. /* 16 */ "input",
  189321. /* 17 */ "expr",
  189322. /* 18 */ "cnearset",
  189323. /* 19 */ "exprlist",
  189324. /* 20 */ "colset",
  189325. /* 21 */ "colsetlist",
  189326. /* 22 */ "nearset",
  189327. /* 23 */ "nearphrases",
  189328. /* 24 */ "phrase",
  189329. /* 25 */ "neardist_opt",
  189330. /* 26 */ "star_opt",
  189331. };
  189332. #endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */
  189333. #ifndef NDEBUG
  189334. /* For tracing reduce actions, the names of all rules are required.
  189335. */
  189336. static const char *const fts5yyRuleName[] = {
  189337. /* 0 */ "input ::= expr",
  189338. /* 1 */ "colset ::= MINUS LCP colsetlist RCP",
  189339. /* 2 */ "colset ::= LCP colsetlist RCP",
  189340. /* 3 */ "colset ::= STRING",
  189341. /* 4 */ "colset ::= MINUS STRING",
  189342. /* 5 */ "colsetlist ::= colsetlist STRING",
  189343. /* 6 */ "colsetlist ::= STRING",
  189344. /* 7 */ "expr ::= expr AND expr",
  189345. /* 8 */ "expr ::= expr OR expr",
  189346. /* 9 */ "expr ::= expr NOT expr",
  189347. /* 10 */ "expr ::= colset COLON LP expr RP",
  189348. /* 11 */ "expr ::= LP expr RP",
  189349. /* 12 */ "expr ::= exprlist",
  189350. /* 13 */ "exprlist ::= cnearset",
  189351. /* 14 */ "exprlist ::= exprlist cnearset",
  189352. /* 15 */ "cnearset ::= nearset",
  189353. /* 16 */ "cnearset ::= colset COLON nearset",
  189354. /* 17 */ "nearset ::= phrase",
  189355. /* 18 */ "nearset ::= CARET phrase",
  189356. /* 19 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  189357. /* 20 */ "nearphrases ::= phrase",
  189358. /* 21 */ "nearphrases ::= nearphrases phrase",
  189359. /* 22 */ "neardist_opt ::=",
  189360. /* 23 */ "neardist_opt ::= COMMA STRING",
  189361. /* 24 */ "phrase ::= phrase PLUS STRING star_opt",
  189362. /* 25 */ "phrase ::= STRING star_opt",
  189363. /* 26 */ "star_opt ::= STAR",
  189364. /* 27 */ "star_opt ::=",
  189365. };
  189366. #endif /* NDEBUG */
  189367. #if fts5YYSTACKDEPTH<=0
  189368. /*
  189369. ** Try to increase the size of the parser stack. Return the number
  189370. ** of errors. Return 0 on success.
  189371. */
  189372. static int fts5yyGrowStack(fts5yyParser *p){
  189373. int newSize;
  189374. int idx;
  189375. fts5yyStackEntry *pNew;
  189376. newSize = p->fts5yystksz*2 + 100;
  189377. idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
  189378. if( p->fts5yystack==&p->fts5yystk0 ){
  189379. pNew = malloc(newSize*sizeof(pNew[0]));
  189380. if( pNew ) pNew[0] = p->fts5yystk0;
  189381. }else{
  189382. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  189383. }
  189384. if( pNew ){
  189385. p->fts5yystack = pNew;
  189386. p->fts5yytos = &p->fts5yystack[idx];
  189387. #ifndef NDEBUG
  189388. if( fts5yyTraceFILE ){
  189389. fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  189390. fts5yyTracePrompt, p->fts5yystksz, newSize);
  189391. }
  189392. #endif
  189393. p->fts5yystksz = newSize;
  189394. }
  189395. return pNew==0;
  189396. }
  189397. #endif
  189398. /* Datatype of the argument to the memory allocated passed as the
  189399. ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
  189400. ** putting an appropriate #define in the %include section of the input
  189401. ** grammar.
  189402. */
  189403. #ifndef fts5YYMALLOCARGTYPE
  189404. # define fts5YYMALLOCARGTYPE size_t
  189405. #endif
  189406. /* Initialize a new parser that has already been allocated.
  189407. */
  189408. static void sqlite3Fts5ParserInit(void *fts5yypRawParser sqlite3Fts5ParserCTX_PDECL){
  189409. fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yypRawParser;
  189410. sqlite3Fts5ParserCTX_STORE
  189411. #ifdef fts5YYTRACKMAXSTACKDEPTH
  189412. fts5yypParser->fts5yyhwm = 0;
  189413. #endif
  189414. #if fts5YYSTACKDEPTH<=0
  189415. fts5yypParser->fts5yytos = NULL;
  189416. fts5yypParser->fts5yystack = NULL;
  189417. fts5yypParser->fts5yystksz = 0;
  189418. if( fts5yyGrowStack(fts5yypParser) ){
  189419. fts5yypParser->fts5yystack = &fts5yypParser->fts5yystk0;
  189420. fts5yypParser->fts5yystksz = 1;
  189421. }
  189422. #endif
  189423. #ifndef fts5YYNOERRORRECOVERY
  189424. fts5yypParser->fts5yyerrcnt = -1;
  189425. #endif
  189426. fts5yypParser->fts5yytos = fts5yypParser->fts5yystack;
  189427. fts5yypParser->fts5yystack[0].stateno = 0;
  189428. fts5yypParser->fts5yystack[0].major = 0;
  189429. #if fts5YYSTACKDEPTH>0
  189430. fts5yypParser->fts5yystackEnd = &fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1];
  189431. #endif
  189432. }
  189433. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  189434. /*
  189435. ** This function allocates a new parser.
  189436. ** The only argument is a pointer to a function which works like
  189437. ** malloc.
  189438. **
  189439. ** Inputs:
  189440. ** A pointer to the function used to allocate memory.
  189441. **
  189442. ** Outputs:
  189443. ** A pointer to a parser. This pointer is used in subsequent calls
  189444. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  189445. */
  189446. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE) sqlite3Fts5ParserCTX_PDECL){
  189447. fts5yyParser *fts5yypParser;
  189448. fts5yypParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
  189449. if( fts5yypParser ){
  189450. sqlite3Fts5ParserCTX_STORE
  189451. sqlite3Fts5ParserInit(fts5yypParser sqlite3Fts5ParserCTX_PARAM);
  189452. }
  189453. return (void*)fts5yypParser;
  189454. }
  189455. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  189456. /* The following function deletes the "minor type" or semantic value
  189457. ** associated with a symbol. The symbol can be either a terminal
  189458. ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
  189459. ** a pointer to the value to be deleted. The code used to do the
  189460. ** deletions is derived from the %destructor and/or %token_destructor
  189461. ** directives of the input grammar.
  189462. */
  189463. static void fts5yy_destructor(
  189464. fts5yyParser *fts5yypParser, /* The parser */
  189465. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  189466. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  189467. ){
  189468. sqlite3Fts5ParserARG_FETCH
  189469. sqlite3Fts5ParserCTX_FETCH
  189470. switch( fts5yymajor ){
  189471. /* Here is inserted the actions which take place when a
  189472. ** terminal or non-terminal is destroyed. This can happen
  189473. ** when the symbol is popped from the stack during a
  189474. ** reduce or during error processing or when a parser is
  189475. ** being destroyed before it is finished parsing.
  189476. **
  189477. ** Note: during a reduce, the only symbols destroyed are those
  189478. ** which appear on the RHS of the rule, but which are *not* used
  189479. ** inside the C code.
  189480. */
  189481. /********* Begin destructor definitions ***************************************/
  189482. case 16: /* input */
  189483. {
  189484. (void)pParse;
  189485. }
  189486. break;
  189487. case 17: /* expr */
  189488. case 18: /* cnearset */
  189489. case 19: /* exprlist */
  189490. {
  189491. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
  189492. }
  189493. break;
  189494. case 20: /* colset */
  189495. case 21: /* colsetlist */
  189496. {
  189497. sqlite3_free((fts5yypminor->fts5yy11));
  189498. }
  189499. break;
  189500. case 22: /* nearset */
  189501. case 23: /* nearphrases */
  189502. {
  189503. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
  189504. }
  189505. break;
  189506. case 24: /* phrase */
  189507. {
  189508. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
  189509. }
  189510. break;
  189511. /********* End destructor definitions *****************************************/
  189512. default: break; /* If no destructor action specified: do nothing */
  189513. }
  189514. }
  189515. /*
  189516. ** Pop the parser's stack once.
  189517. **
  189518. ** If there is a destructor routine associated with the token which
  189519. ** is popped from the stack, then call it.
  189520. */
  189521. static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
  189522. fts5yyStackEntry *fts5yytos;
  189523. assert( pParser->fts5yytos!=0 );
  189524. assert( pParser->fts5yytos > pParser->fts5yystack );
  189525. fts5yytos = pParser->fts5yytos--;
  189526. #ifndef NDEBUG
  189527. if( fts5yyTraceFILE ){
  189528. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  189529. fts5yyTracePrompt,
  189530. fts5yyTokenName[fts5yytos->major]);
  189531. }
  189532. #endif
  189533. fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
  189534. }
  189535. /*
  189536. ** Clear all secondary memory allocations from the parser
  189537. */
  189538. static void sqlite3Fts5ParserFinalize(void *p){
  189539. fts5yyParser *pParser = (fts5yyParser*)p;
  189540. while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
  189541. #if fts5YYSTACKDEPTH<=0
  189542. if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
  189543. #endif
  189544. }
  189545. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  189546. /*
  189547. ** Deallocate and destroy a parser. Destructors are called for
  189548. ** all stack elements before shutting the parser down.
  189549. **
  189550. ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
  189551. ** is defined in a %include section of the input grammar) then it is
  189552. ** assumed that the input pointer is never NULL.
  189553. */
  189554. static void sqlite3Fts5ParserFree(
  189555. void *p, /* The parser to be deleted */
  189556. void (*freeProc)(void*) /* Function used to reclaim memory */
  189557. ){
  189558. #ifndef fts5YYPARSEFREENEVERNULL
  189559. if( p==0 ) return;
  189560. #endif
  189561. sqlite3Fts5ParserFinalize(p);
  189562. (*freeProc)(p);
  189563. }
  189564. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  189565. /*
  189566. ** Return the peak depth of the stack for a parser.
  189567. */
  189568. #ifdef fts5YYTRACKMAXSTACKDEPTH
  189569. static int sqlite3Fts5ParserStackPeak(void *p){
  189570. fts5yyParser *pParser = (fts5yyParser*)p;
  189571. return pParser->fts5yyhwm;
  189572. }
  189573. #endif
  189574. /* This array of booleans keeps track of the parser statement
  189575. ** coverage. The element fts5yycoverage[X][Y] is set when the parser
  189576. ** is in state X and has a lookahead token Y. In a well-tested
  189577. ** systems, every element of this matrix should end up being set.
  189578. */
  189579. #if defined(fts5YYCOVERAGE)
  189580. static unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN];
  189581. #endif
  189582. /*
  189583. ** Write into out a description of every state/lookahead combination that
  189584. **
  189585. ** (1) has not been used by the parser, and
  189586. ** (2) is not a syntax error.
  189587. **
  189588. ** Return the number of missed state/lookahead combinations.
  189589. */
  189590. #if defined(fts5YYCOVERAGE)
  189591. static int sqlite3Fts5ParserCoverage(FILE *out){
  189592. int stateno, iLookAhead, i;
  189593. int nMissed = 0;
  189594. for(stateno=0; stateno<fts5YYNSTATE; stateno++){
  189595. i = fts5yy_shift_ofst[stateno];
  189596. for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){
  189597. if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  189598. if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  189599. if( out ){
  189600. fprintf(out,"State %d lookahead %s %s\n", stateno,
  189601. fts5yyTokenName[iLookAhead],
  189602. fts5yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  189603. }
  189604. }
  189605. }
  189606. return nMissed;
  189607. }
  189608. #endif
  189609. /*
  189610. ** Find the appropriate action for a parser given the terminal
  189611. ** look-ahead token iLookAhead.
  189612. */
  189613. static fts5YYACTIONTYPE fts5yy_find_shift_action(
  189614. fts5YYCODETYPE iLookAhead, /* The look-ahead token */
  189615. fts5YYACTIONTYPE stateno /* Current state number */
  189616. ){
  189617. int i;
  189618. if( stateno>fts5YY_MAX_SHIFT ) return stateno;
  189619. assert( stateno <= fts5YY_SHIFT_COUNT );
  189620. #if defined(fts5YYCOVERAGE)
  189621. fts5yycoverage[stateno][iLookAhead] = 1;
  189622. #endif
  189623. do{
  189624. i = fts5yy_shift_ofst[stateno];
  189625. assert( i>=0 );
  189626. /* assert( i+fts5YYNFTS5TOKEN<=(int)fts5YY_NLOOKAHEAD ); */
  189627. assert( iLookAhead!=fts5YYNOCODE );
  189628. assert( iLookAhead < fts5YYNFTS5TOKEN );
  189629. i += iLookAhead;
  189630. if( i>=fts5YY_NLOOKAHEAD || fts5yy_lookahead[i]!=iLookAhead ){
  189631. #ifdef fts5YYFALLBACK
  189632. fts5YYCODETYPE iFallback; /* Fallback token */
  189633. if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
  189634. && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
  189635. #ifndef NDEBUG
  189636. if( fts5yyTraceFILE ){
  189637. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  189638. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  189639. }
  189640. #endif
  189641. assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  189642. iLookAhead = iFallback;
  189643. continue;
  189644. }
  189645. #endif
  189646. #ifdef fts5YYWILDCARD
  189647. {
  189648. int j = i - iLookAhead + fts5YYWILDCARD;
  189649. if(
  189650. #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
  189651. j>=0 &&
  189652. #endif
  189653. #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
  189654. j<fts5YY_ACTTAB_COUNT &&
  189655. #endif
  189656. j<(int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])) &&
  189657. fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
  189658. ){
  189659. #ifndef NDEBUG
  189660. if( fts5yyTraceFILE ){
  189661. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  189662. fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
  189663. fts5yyTokenName[fts5YYWILDCARD]);
  189664. }
  189665. #endif /* NDEBUG */
  189666. return fts5yy_action[j];
  189667. }
  189668. }
  189669. #endif /* fts5YYWILDCARD */
  189670. return fts5yy_default[stateno];
  189671. }else{
  189672. return fts5yy_action[i];
  189673. }
  189674. }while(1);
  189675. }
  189676. /*
  189677. ** Find the appropriate action for a parser given the non-terminal
  189678. ** look-ahead token iLookAhead.
  189679. */
  189680. static fts5YYACTIONTYPE fts5yy_find_reduce_action(
  189681. fts5YYACTIONTYPE stateno, /* Current state number */
  189682. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  189683. ){
  189684. int i;
  189685. #ifdef fts5YYERRORSYMBOL
  189686. if( stateno>fts5YY_REDUCE_COUNT ){
  189687. return fts5yy_default[stateno];
  189688. }
  189689. #else
  189690. assert( stateno<=fts5YY_REDUCE_COUNT );
  189691. #endif
  189692. i = fts5yy_reduce_ofst[stateno];
  189693. assert( iLookAhead!=fts5YYNOCODE );
  189694. i += iLookAhead;
  189695. #ifdef fts5YYERRORSYMBOL
  189696. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  189697. return fts5yy_default[stateno];
  189698. }
  189699. #else
  189700. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  189701. assert( fts5yy_lookahead[i]==iLookAhead );
  189702. #endif
  189703. return fts5yy_action[i];
  189704. }
  189705. /*
  189706. ** The following routine is called if the stack overflows.
  189707. */
  189708. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
  189709. sqlite3Fts5ParserARG_FETCH
  189710. sqlite3Fts5ParserCTX_FETCH
  189711. #ifndef NDEBUG
  189712. if( fts5yyTraceFILE ){
  189713. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  189714. }
  189715. #endif
  189716. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  189717. /* Here code is inserted which will execute if the parser
  189718. ** stack every overflows */
  189719. /******** Begin %stack_overflow code ******************************************/
  189720. sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
  189721. /******** End %stack_overflow code ********************************************/
  189722. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument var */
  189723. sqlite3Fts5ParserCTX_STORE
  189724. }
  189725. /*
  189726. ** Print tracing information for a SHIFT action
  189727. */
  189728. #ifndef NDEBUG
  189729. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){
  189730. if( fts5yyTraceFILE ){
  189731. if( fts5yyNewState<fts5YYNSTATE ){
  189732. fprintf(fts5yyTraceFILE,"%s%s '%s', go to state %d\n",
  189733. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  189734. fts5yyNewState);
  189735. }else{
  189736. fprintf(fts5yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  189737. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  189738. fts5yyNewState - fts5YY_MIN_REDUCE);
  189739. }
  189740. }
  189741. }
  189742. #else
  189743. # define fts5yyTraceShift(X,Y,Z)
  189744. #endif
  189745. /*
  189746. ** Perform a shift action.
  189747. */
  189748. static void fts5yy_shift(
  189749. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  189750. fts5YYACTIONTYPE fts5yyNewState, /* The new state to shift in */
  189751. fts5YYCODETYPE fts5yyMajor, /* The major token to shift in */
  189752. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
  189753. ){
  189754. fts5yyStackEntry *fts5yytos;
  189755. fts5yypParser->fts5yytos++;
  189756. #ifdef fts5YYTRACKMAXSTACKDEPTH
  189757. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  189758. fts5yypParser->fts5yyhwm++;
  189759. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
  189760. }
  189761. #endif
  189762. #if fts5YYSTACKDEPTH>0
  189763. if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
  189764. fts5yypParser->fts5yytos--;
  189765. fts5yyStackOverflow(fts5yypParser);
  189766. return;
  189767. }
  189768. #else
  189769. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
  189770. if( fts5yyGrowStack(fts5yypParser) ){
  189771. fts5yypParser->fts5yytos--;
  189772. fts5yyStackOverflow(fts5yypParser);
  189773. return;
  189774. }
  189775. }
  189776. #endif
  189777. if( fts5yyNewState > fts5YY_MAX_SHIFT ){
  189778. fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  189779. }
  189780. fts5yytos = fts5yypParser->fts5yytos;
  189781. fts5yytos->stateno = fts5yyNewState;
  189782. fts5yytos->major = fts5yyMajor;
  189783. fts5yytos->minor.fts5yy0 = fts5yyMinor;
  189784. fts5yyTraceShift(fts5yypParser, fts5yyNewState, "Shift");
  189785. }
  189786. /* For rule J, fts5yyRuleInfoLhs[J] contains the symbol on the left-hand side
  189787. ** of that rule */
  189788. static const fts5YYCODETYPE fts5yyRuleInfoLhs[] = {
  189789. 16, /* (0) input ::= expr */
  189790. 20, /* (1) colset ::= MINUS LCP colsetlist RCP */
  189791. 20, /* (2) colset ::= LCP colsetlist RCP */
  189792. 20, /* (3) colset ::= STRING */
  189793. 20, /* (4) colset ::= MINUS STRING */
  189794. 21, /* (5) colsetlist ::= colsetlist STRING */
  189795. 21, /* (6) colsetlist ::= STRING */
  189796. 17, /* (7) expr ::= expr AND expr */
  189797. 17, /* (8) expr ::= expr OR expr */
  189798. 17, /* (9) expr ::= expr NOT expr */
  189799. 17, /* (10) expr ::= colset COLON LP expr RP */
  189800. 17, /* (11) expr ::= LP expr RP */
  189801. 17, /* (12) expr ::= exprlist */
  189802. 19, /* (13) exprlist ::= cnearset */
  189803. 19, /* (14) exprlist ::= exprlist cnearset */
  189804. 18, /* (15) cnearset ::= nearset */
  189805. 18, /* (16) cnearset ::= colset COLON nearset */
  189806. 22, /* (17) nearset ::= phrase */
  189807. 22, /* (18) nearset ::= CARET phrase */
  189808. 22, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
  189809. 23, /* (20) nearphrases ::= phrase */
  189810. 23, /* (21) nearphrases ::= nearphrases phrase */
  189811. 25, /* (22) neardist_opt ::= */
  189812. 25, /* (23) neardist_opt ::= COMMA STRING */
  189813. 24, /* (24) phrase ::= phrase PLUS STRING star_opt */
  189814. 24, /* (25) phrase ::= STRING star_opt */
  189815. 26, /* (26) star_opt ::= STAR */
  189816. 26, /* (27) star_opt ::= */
  189817. };
  189818. /* For rule J, fts5yyRuleInfoNRhs[J] contains the negative of the number
  189819. ** of symbols on the right-hand side of that rule. */
  189820. static const signed char fts5yyRuleInfoNRhs[] = {
  189821. -1, /* (0) input ::= expr */
  189822. -4, /* (1) colset ::= MINUS LCP colsetlist RCP */
  189823. -3, /* (2) colset ::= LCP colsetlist RCP */
  189824. -1, /* (3) colset ::= STRING */
  189825. -2, /* (4) colset ::= MINUS STRING */
  189826. -2, /* (5) colsetlist ::= colsetlist STRING */
  189827. -1, /* (6) colsetlist ::= STRING */
  189828. -3, /* (7) expr ::= expr AND expr */
  189829. -3, /* (8) expr ::= expr OR expr */
  189830. -3, /* (9) expr ::= expr NOT expr */
  189831. -5, /* (10) expr ::= colset COLON LP expr RP */
  189832. -3, /* (11) expr ::= LP expr RP */
  189833. -1, /* (12) expr ::= exprlist */
  189834. -1, /* (13) exprlist ::= cnearset */
  189835. -2, /* (14) exprlist ::= exprlist cnearset */
  189836. -1, /* (15) cnearset ::= nearset */
  189837. -3, /* (16) cnearset ::= colset COLON nearset */
  189838. -1, /* (17) nearset ::= phrase */
  189839. -2, /* (18) nearset ::= CARET phrase */
  189840. -5, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
  189841. -1, /* (20) nearphrases ::= phrase */
  189842. -2, /* (21) nearphrases ::= nearphrases phrase */
  189843. 0, /* (22) neardist_opt ::= */
  189844. -2, /* (23) neardist_opt ::= COMMA STRING */
  189845. -4, /* (24) phrase ::= phrase PLUS STRING star_opt */
  189846. -2, /* (25) phrase ::= STRING star_opt */
  189847. -1, /* (26) star_opt ::= STAR */
  189848. 0, /* (27) star_opt ::= */
  189849. };
  189850. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  189851. /*
  189852. ** Perform a reduce action and the shift that must immediately
  189853. ** follow the reduce.
  189854. **
  189855. ** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions
  189856. ** access to the lookahead token (if any). The fts5yyLookahead will be fts5YYNOCODE
  189857. ** if the lookahead token has already been consumed. As this procedure is
  189858. ** only called from one place, optimizing compilers will in-line it, which
  189859. ** means that the extra parameters have no performance impact.
  189860. */
  189861. static fts5YYACTIONTYPE fts5yy_reduce(
  189862. fts5yyParser *fts5yypParser, /* The parser */
  189863. unsigned int fts5yyruleno, /* Number of the rule by which to reduce */
  189864. int fts5yyLookahead, /* Lookahead token, or fts5YYNOCODE if none */
  189865. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken /* Value of the lookahead token */
  189866. sqlite3Fts5ParserCTX_PDECL /* %extra_context */
  189867. ){
  189868. int fts5yygoto; /* The next state */
  189869. fts5YYACTIONTYPE fts5yyact; /* The next action */
  189870. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  189871. int fts5yysize; /* Amount to pop the stack */
  189872. sqlite3Fts5ParserARG_FETCH
  189873. (void)fts5yyLookahead;
  189874. (void)fts5yyLookaheadToken;
  189875. fts5yymsp = fts5yypParser->fts5yytos;
  189876. #ifndef NDEBUG
  189877. if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  189878. fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
  189879. if( fts5yysize ){
  189880. fprintf(fts5yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
  189881. fts5yyTracePrompt,
  189882. fts5yyruleno, fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
  189883. }else{
  189884. fprintf(fts5yyTraceFILE, "%sReduce %d [%s].\n",
  189885. fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno]);
  189886. }
  189887. }
  189888. #endif /* NDEBUG */
  189889. /* Check that the stack is large enough to grow by a single entry
  189890. ** if the RHS of the rule is empty. This ensures that there is room
  189891. ** enough on the stack to push the LHS value */
  189892. if( fts5yyRuleInfoNRhs[fts5yyruleno]==0 ){
  189893. #ifdef fts5YYTRACKMAXSTACKDEPTH
  189894. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  189895. fts5yypParser->fts5yyhwm++;
  189896. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
  189897. }
  189898. #endif
  189899. #if fts5YYSTACKDEPTH>0
  189900. if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
  189901. fts5yyStackOverflow(fts5yypParser);
  189902. /* The call to fts5yyStackOverflow() above pops the stack until it is
  189903. ** empty, causing the main parser loop to exit. So the return value
  189904. ** is never used and does not matter. */
  189905. return 0;
  189906. }
  189907. #else
  189908. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
  189909. if( fts5yyGrowStack(fts5yypParser) ){
  189910. fts5yyStackOverflow(fts5yypParser);
  189911. /* The call to fts5yyStackOverflow() above pops the stack until it is
  189912. ** empty, causing the main parser loop to exit. So the return value
  189913. ** is never used and does not matter. */
  189914. return 0;
  189915. }
  189916. fts5yymsp = fts5yypParser->fts5yytos;
  189917. }
  189918. #endif
  189919. }
  189920. switch( fts5yyruleno ){
  189921. /* Beginning here are the reduction cases. A typical example
  189922. ** follows:
  189923. ** case 0:
  189924. ** #line <lineno> <grammarfile>
  189925. ** { ... } // User supplied code
  189926. ** #line <lineno> <thisfile>
  189927. ** break;
  189928. */
  189929. /********** Begin reduce actions **********************************************/
  189930. fts5YYMINORTYPE fts5yylhsminor;
  189931. case 0: /* input ::= expr */
  189932. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
  189933. break;
  189934. case 1: /* colset ::= MINUS LCP colsetlist RCP */
  189935. {
  189936. fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  189937. }
  189938. break;
  189939. case 2: /* colset ::= LCP colsetlist RCP */
  189940. { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
  189941. break;
  189942. case 3: /* colset ::= STRING */
  189943. {
  189944. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  189945. }
  189946. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  189947. break;
  189948. case 4: /* colset ::= MINUS STRING */
  189949. {
  189950. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  189951. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  189952. }
  189953. break;
  189954. case 5: /* colsetlist ::= colsetlist STRING */
  189955. {
  189956. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
  189957. fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  189958. break;
  189959. case 6: /* colsetlist ::= STRING */
  189960. {
  189961. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  189962. }
  189963. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  189964. break;
  189965. case 7: /* expr ::= expr AND expr */
  189966. {
  189967. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  189968. }
  189969. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  189970. break;
  189971. case 8: /* expr ::= expr OR expr */
  189972. {
  189973. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  189974. }
  189975. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  189976. break;
  189977. case 9: /* expr ::= expr NOT expr */
  189978. {
  189979. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  189980. }
  189981. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  189982. break;
  189983. case 10: /* expr ::= colset COLON LP expr RP */
  189984. {
  189985. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
  189986. fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
  189987. }
  189988. fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  189989. break;
  189990. case 11: /* expr ::= LP expr RP */
  189991. {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
  189992. break;
  189993. case 12: /* expr ::= exprlist */
  189994. case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
  189995. {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
  189996. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  189997. break;
  189998. case 14: /* exprlist ::= exprlist cnearset */
  189999. {
  190000. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
  190001. }
  190002. fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  190003. break;
  190004. case 15: /* cnearset ::= nearset */
  190005. {
  190006. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  190007. }
  190008. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  190009. break;
  190010. case 16: /* cnearset ::= colset COLON nearset */
  190011. {
  190012. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  190013. sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
  190014. }
  190015. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  190016. break;
  190017. case 17: /* nearset ::= phrase */
  190018. { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
  190019. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  190020. break;
  190021. case 18: /* nearset ::= CARET phrase */
  190022. {
  190023. sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy53);
  190024. fts5yymsp[-1].minor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  190025. }
  190026. break;
  190027. case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  190028. {
  190029. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  190030. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
  190031. fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
  190032. }
  190033. fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  190034. break;
  190035. case 20: /* nearphrases ::= phrase */
  190036. {
  190037. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  190038. }
  190039. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  190040. break;
  190041. case 21: /* nearphrases ::= nearphrases phrase */
  190042. {
  190043. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
  190044. }
  190045. fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  190046. break;
  190047. case 22: /* neardist_opt ::= */
  190048. { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
  190049. break;
  190050. case 23: /* neardist_opt ::= COMMA STRING */
  190051. { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  190052. break;
  190053. case 24: /* phrase ::= phrase PLUS STRING star_opt */
  190054. {
  190055. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  190056. }
  190057. fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  190058. break;
  190059. case 25: /* phrase ::= STRING star_opt */
  190060. {
  190061. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  190062. }
  190063. fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  190064. break;
  190065. case 26: /* star_opt ::= STAR */
  190066. { fts5yymsp[0].minor.fts5yy4 = 1; }
  190067. break;
  190068. case 27: /* star_opt ::= */
  190069. { fts5yymsp[1].minor.fts5yy4 = 0; }
  190070. break;
  190071. default:
  190072. break;
  190073. /********** End reduce actions ************************************************/
  190074. };
  190075. assert( fts5yyruleno<sizeof(fts5yyRuleInfoLhs)/sizeof(fts5yyRuleInfoLhs[0]) );
  190076. fts5yygoto = fts5yyRuleInfoLhs[fts5yyruleno];
  190077. fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
  190078. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  190079. /* There are no SHIFTREDUCE actions on nonterminals because the table
  190080. ** generator has simplified them to pure REDUCE actions. */
  190081. assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
  190082. /* It is not possible for a REDUCE to be followed by an error */
  190083. assert( fts5yyact!=fts5YY_ERROR_ACTION );
  190084. fts5yymsp += fts5yysize+1;
  190085. fts5yypParser->fts5yytos = fts5yymsp;
  190086. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  190087. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  190088. fts5yyTraceShift(fts5yypParser, fts5yyact, "... then shift");
  190089. return fts5yyact;
  190090. }
  190091. /*
  190092. ** The following code executes when the parse fails
  190093. */
  190094. #ifndef fts5YYNOERRORRECOVERY
  190095. static void fts5yy_parse_failed(
  190096. fts5yyParser *fts5yypParser /* The parser */
  190097. ){
  190098. sqlite3Fts5ParserARG_FETCH
  190099. sqlite3Fts5ParserCTX_FETCH
  190100. #ifndef NDEBUG
  190101. if( fts5yyTraceFILE ){
  190102. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  190103. }
  190104. #endif
  190105. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  190106. /* Here code is inserted which will be executed whenever the
  190107. ** parser fails */
  190108. /************ Begin %parse_failure code ***************************************/
  190109. /************ End %parse_failure code *****************************************/
  190110. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  190111. sqlite3Fts5ParserCTX_STORE
  190112. }
  190113. #endif /* fts5YYNOERRORRECOVERY */
  190114. /*
  190115. ** The following code executes when a syntax error first occurs.
  190116. */
  190117. static void fts5yy_syntax_error(
  190118. fts5yyParser *fts5yypParser, /* The parser */
  190119. int fts5yymajor, /* The major type of the error token */
  190120. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
  190121. ){
  190122. sqlite3Fts5ParserARG_FETCH
  190123. sqlite3Fts5ParserCTX_FETCH
  190124. #define FTS5TOKEN fts5yyminor
  190125. /************ Begin %syntax_error code ****************************************/
  190126. UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
  190127. sqlite3Fts5ParseError(
  190128. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  190129. );
  190130. /************ End %syntax_error code ******************************************/
  190131. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  190132. sqlite3Fts5ParserCTX_STORE
  190133. }
  190134. /*
  190135. ** The following is executed when the parser accepts
  190136. */
  190137. static void fts5yy_accept(
  190138. fts5yyParser *fts5yypParser /* The parser */
  190139. ){
  190140. sqlite3Fts5ParserARG_FETCH
  190141. sqlite3Fts5ParserCTX_FETCH
  190142. #ifndef NDEBUG
  190143. if( fts5yyTraceFILE ){
  190144. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  190145. }
  190146. #endif
  190147. #ifndef fts5YYNOERRORRECOVERY
  190148. fts5yypParser->fts5yyerrcnt = -1;
  190149. #endif
  190150. assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
  190151. /* Here code is inserted which will be executed whenever the
  190152. ** parser accepts */
  190153. /*********** Begin %parse_accept code *****************************************/
  190154. /*********** End %parse_accept code *******************************************/
  190155. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  190156. sqlite3Fts5ParserCTX_STORE
  190157. }
  190158. /* The main parser program.
  190159. ** The first argument is a pointer to a structure obtained from
  190160. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  190161. ** The second argument is the major token number. The third is
  190162. ** the minor token. The fourth optional argument is whatever the
  190163. ** user wants (and specified in the grammar) and is available for
  190164. ** use by the action routines.
  190165. **
  190166. ** Inputs:
  190167. ** <ul>
  190168. ** <li> A pointer to the parser (an opaque structure.)
  190169. ** <li> The major token number.
  190170. ** <li> The minor token number.
  190171. ** <li> An option argument of a grammar-specified type.
  190172. ** </ul>
  190173. **
  190174. ** Outputs:
  190175. ** None.
  190176. */
  190177. static void sqlite3Fts5Parser(
  190178. void *fts5yyp, /* The parser */
  190179. int fts5yymajor, /* The major token code number */
  190180. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  190181. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  190182. ){
  190183. fts5YYMINORTYPE fts5yyminorunion;
  190184. fts5YYACTIONTYPE fts5yyact; /* The parser action. */
  190185. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  190186. int fts5yyendofinput; /* True if we are at the end of input */
  190187. #endif
  190188. #ifdef fts5YYERRORSYMBOL
  190189. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  190190. #endif
  190191. fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yyp; /* The parser */
  190192. sqlite3Fts5ParserCTX_FETCH
  190193. sqlite3Fts5ParserARG_STORE
  190194. assert( fts5yypParser->fts5yytos!=0 );
  190195. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  190196. fts5yyendofinput = (fts5yymajor==0);
  190197. #endif
  190198. fts5yyact = fts5yypParser->fts5yytos->stateno;
  190199. #ifndef NDEBUG
  190200. if( fts5yyTraceFILE ){
  190201. if( fts5yyact < fts5YY_MIN_REDUCE ){
  190202. fprintf(fts5yyTraceFILE,"%sInput '%s' in state %d\n",
  190203. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact);
  190204. }else{
  190205. fprintf(fts5yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  190206. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact-fts5YY_MIN_REDUCE);
  190207. }
  190208. }
  190209. #endif
  190210. do{
  190211. assert( fts5yyact==fts5yypParser->fts5yytos->stateno );
  190212. fts5yyact = fts5yy_find_shift_action((fts5YYCODETYPE)fts5yymajor,fts5yyact);
  190213. if( fts5yyact >= fts5YY_MIN_REDUCE ){
  190214. fts5yyact = fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE,fts5yymajor,
  190215. fts5yyminor sqlite3Fts5ParserCTX_PARAM);
  190216. }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  190217. fts5yy_shift(fts5yypParser,fts5yyact,(fts5YYCODETYPE)fts5yymajor,fts5yyminor);
  190218. #ifndef fts5YYNOERRORRECOVERY
  190219. fts5yypParser->fts5yyerrcnt--;
  190220. #endif
  190221. break;
  190222. }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){
  190223. fts5yypParser->fts5yytos--;
  190224. fts5yy_accept(fts5yypParser);
  190225. return;
  190226. }else{
  190227. assert( fts5yyact == fts5YY_ERROR_ACTION );
  190228. fts5yyminorunion.fts5yy0 = fts5yyminor;
  190229. #ifdef fts5YYERRORSYMBOL
  190230. int fts5yymx;
  190231. #endif
  190232. #ifndef NDEBUG
  190233. if( fts5yyTraceFILE ){
  190234. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  190235. }
  190236. #endif
  190237. #ifdef fts5YYERRORSYMBOL
  190238. /* A syntax error has occurred.
  190239. ** The response to an error depends upon whether or not the
  190240. ** grammar defines an error token "ERROR".
  190241. **
  190242. ** This is what we do if the grammar does define ERROR:
  190243. **
  190244. ** * Call the %syntax_error function.
  190245. **
  190246. ** * Begin popping the stack until we enter a state where
  190247. ** it is legal to shift the error symbol, then shift
  190248. ** the error symbol.
  190249. **
  190250. ** * Set the error count to three.
  190251. **
  190252. ** * Begin accepting and shifting new tokens. No new error
  190253. ** processing will occur until three tokens have been
  190254. ** shifted successfully.
  190255. **
  190256. */
  190257. if( fts5yypParser->fts5yyerrcnt<0 ){
  190258. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
  190259. }
  190260. fts5yymx = fts5yypParser->fts5yytos->major;
  190261. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  190262. #ifndef NDEBUG
  190263. if( fts5yyTraceFILE ){
  190264. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  190265. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  190266. }
  190267. #endif
  190268. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
  190269. fts5yymajor = fts5YYNOCODE;
  190270. }else{
  190271. while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
  190272. && (fts5yyact = fts5yy_find_reduce_action(
  190273. fts5yypParser->fts5yytos->stateno,
  190274. fts5YYERRORSYMBOL)) > fts5YY_MAX_SHIFTREDUCE
  190275. ){
  190276. fts5yy_pop_parser_stack(fts5yypParser);
  190277. }
  190278. if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
  190279. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  190280. fts5yy_parse_failed(fts5yypParser);
  190281. #ifndef fts5YYNOERRORRECOVERY
  190282. fts5yypParser->fts5yyerrcnt = -1;
  190283. #endif
  190284. fts5yymajor = fts5YYNOCODE;
  190285. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  190286. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
  190287. }
  190288. }
  190289. fts5yypParser->fts5yyerrcnt = 3;
  190290. fts5yyerrorhit = 1;
  190291. if( fts5yymajor==fts5YYNOCODE ) break;
  190292. fts5yyact = fts5yypParser->fts5yytos->stateno;
  190293. #elif defined(fts5YYNOERRORRECOVERY)
  190294. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  190295. ** do any kind of error recovery. Instead, simply invoke the syntax
  190296. ** error routine and continue going as if nothing had happened.
  190297. **
  190298. ** Applications can set this macro (for example inside %include) if
  190299. ** they intend to abandon the parse upon the first syntax error seen.
  190300. */
  190301. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  190302. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  190303. break;
  190304. #else /* fts5YYERRORSYMBOL is not defined */
  190305. /* This is what we do if the grammar does not define ERROR:
  190306. **
  190307. ** * Report an error message, and throw away the input token.
  190308. **
  190309. ** * If the input token is $, then fail the parse.
  190310. **
  190311. ** As before, subsequent error messages are suppressed until
  190312. ** three input tokens have been successfully shifted.
  190313. */
  190314. if( fts5yypParser->fts5yyerrcnt<=0 ){
  190315. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  190316. }
  190317. fts5yypParser->fts5yyerrcnt = 3;
  190318. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  190319. if( fts5yyendofinput ){
  190320. fts5yy_parse_failed(fts5yypParser);
  190321. #ifndef fts5YYNOERRORRECOVERY
  190322. fts5yypParser->fts5yyerrcnt = -1;
  190323. #endif
  190324. }
  190325. break;
  190326. #endif
  190327. }
  190328. }while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
  190329. #ifndef NDEBUG
  190330. if( fts5yyTraceFILE ){
  190331. fts5yyStackEntry *i;
  190332. char cDiv = '[';
  190333. fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
  190334. for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
  190335. fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
  190336. cDiv = ' ';
  190337. }
  190338. fprintf(fts5yyTraceFILE,"]\n");
  190339. }
  190340. #endif
  190341. return;
  190342. }
  190343. /*
  190344. ** Return the fallback token corresponding to canonical token iToken, or
  190345. ** 0 if iToken has no fallback.
  190346. */
  190347. static int sqlite3Fts5ParserFallback(int iToken){
  190348. #ifdef fts5YYFALLBACK
  190349. if( iToken<(int)(sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])) ){
  190350. return fts5yyFallback[iToken];
  190351. }
  190352. #else
  190353. (void)iToken;
  190354. #endif
  190355. return 0;
  190356. }
  190357. /*
  190358. ** 2014 May 31
  190359. **
  190360. ** The author disclaims copyright to this source code. In place of
  190361. ** a legal notice, here is a blessing:
  190362. **
  190363. ** May you do good and not evil.
  190364. ** May you find forgiveness for yourself and forgive others.
  190365. ** May you share freely, never taking more than you give.
  190366. **
  190367. ******************************************************************************
  190368. */
  190369. /* #include "fts5Int.h" */
  190370. #include <math.h> /* amalgamator: keep */
  190371. /*
  190372. ** Object used to iterate through all "coalesced phrase instances" in
  190373. ** a single column of the current row. If the phrase instances in the
  190374. ** column being considered do not overlap, this object simply iterates
  190375. ** through them. Or, if they do overlap (share one or more tokens in
  190376. ** common), each set of overlapping instances is treated as a single
  190377. ** match. See documentation for the highlight() auxiliary function for
  190378. ** details.
  190379. **
  190380. ** Usage is:
  190381. **
  190382. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  190383. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  190384. ** rc = fts5CInstIterNext(&iter)
  190385. ** ){
  190386. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  190387. ** }
  190388. **
  190389. */
  190390. typedef struct CInstIter CInstIter;
  190391. struct CInstIter {
  190392. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  190393. Fts5Context *pFts; /* First arg to pass to pApi functions */
  190394. int iCol; /* Column to search */
  190395. int iInst; /* Next phrase instance index */
  190396. int nInst; /* Total number of phrase instances */
  190397. /* Output variables */
  190398. int iStart; /* First token in coalesced phrase instance */
  190399. int iEnd; /* Last token in coalesced phrase instance */
  190400. };
  190401. /*
  190402. ** Advance the iterator to the next coalesced phrase instance. Return
  190403. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  190404. */
  190405. static int fts5CInstIterNext(CInstIter *pIter){
  190406. int rc = SQLITE_OK;
  190407. pIter->iStart = -1;
  190408. pIter->iEnd = -1;
  190409. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  190410. int ip; int ic; int io;
  190411. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  190412. if( rc==SQLITE_OK ){
  190413. if( ic==pIter->iCol ){
  190414. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  190415. if( pIter->iStart<0 ){
  190416. pIter->iStart = io;
  190417. pIter->iEnd = iEnd;
  190418. }else if( io<=pIter->iEnd ){
  190419. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  190420. }else{
  190421. break;
  190422. }
  190423. }
  190424. pIter->iInst++;
  190425. }
  190426. }
  190427. return rc;
  190428. }
  190429. /*
  190430. ** Initialize the iterator object indicated by the final parameter to
  190431. ** iterate through coalesced phrase instances in column iCol.
  190432. */
  190433. static int fts5CInstIterInit(
  190434. const Fts5ExtensionApi *pApi,
  190435. Fts5Context *pFts,
  190436. int iCol,
  190437. CInstIter *pIter
  190438. ){
  190439. int rc;
  190440. memset(pIter, 0, sizeof(CInstIter));
  190441. pIter->pApi = pApi;
  190442. pIter->pFts = pFts;
  190443. pIter->iCol = iCol;
  190444. rc = pApi->xInstCount(pFts, &pIter->nInst);
  190445. if( rc==SQLITE_OK ){
  190446. rc = fts5CInstIterNext(pIter);
  190447. }
  190448. return rc;
  190449. }
  190450. /*************************************************************************
  190451. ** Start of highlight() implementation.
  190452. */
  190453. typedef struct HighlightContext HighlightContext;
  190454. struct HighlightContext {
  190455. CInstIter iter; /* Coalesced Instance Iterator */
  190456. int iPos; /* Current token offset in zIn[] */
  190457. int iRangeStart; /* First token to include */
  190458. int iRangeEnd; /* If non-zero, last token to include */
  190459. const char *zOpen; /* Opening highlight */
  190460. const char *zClose; /* Closing highlight */
  190461. const char *zIn; /* Input text */
  190462. int nIn; /* Size of input text in bytes */
  190463. int iOff; /* Current offset within zIn[] */
  190464. char *zOut; /* Output value */
  190465. };
  190466. /*
  190467. ** Append text to the HighlightContext output string - p->zOut. Argument
  190468. ** z points to a buffer containing n bytes of text to append. If n is
  190469. ** negative, everything up until the first '\0' is appended to the output.
  190470. **
  190471. ** If *pRc is set to any value other than SQLITE_OK when this function is
  190472. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  190473. ** *pRc is set to an error code before returning.
  190474. */
  190475. static void fts5HighlightAppend(
  190476. int *pRc,
  190477. HighlightContext *p,
  190478. const char *z, int n
  190479. ){
  190480. if( *pRc==SQLITE_OK && z ){
  190481. if( n<0 ) n = (int)strlen(z);
  190482. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  190483. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  190484. }
  190485. }
  190486. /*
  190487. ** Tokenizer callback used by implementation of highlight() function.
  190488. */
  190489. static int fts5HighlightCb(
  190490. void *pContext, /* Pointer to HighlightContext object */
  190491. int tflags, /* Mask of FTS5_TOKEN_* flags */
  190492. const char *pToken, /* Buffer containing token */
  190493. int nToken, /* Size of token in bytes */
  190494. int iStartOff, /* Start offset of token */
  190495. int iEndOff /* End offset of token */
  190496. ){
  190497. HighlightContext *p = (HighlightContext*)pContext;
  190498. int rc = SQLITE_OK;
  190499. int iPos;
  190500. UNUSED_PARAM2(pToken, nToken);
  190501. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  190502. iPos = p->iPos++;
  190503. if( p->iRangeEnd>0 ){
  190504. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  190505. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  190506. }
  190507. if( iPos==p->iter.iStart ){
  190508. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  190509. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  190510. p->iOff = iStartOff;
  190511. }
  190512. if( iPos==p->iter.iEnd ){
  190513. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  190514. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  190515. }
  190516. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  190517. fts5HighlightAppend(&rc, p, p->zClose, -1);
  190518. p->iOff = iEndOff;
  190519. if( rc==SQLITE_OK ){
  190520. rc = fts5CInstIterNext(&p->iter);
  190521. }
  190522. }
  190523. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  190524. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  190525. p->iOff = iEndOff;
  190526. if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
  190527. fts5HighlightAppend(&rc, p, p->zClose, -1);
  190528. }
  190529. }
  190530. return rc;
  190531. }
  190532. /*
  190533. ** Implementation of highlight() function.
  190534. */
  190535. static void fts5HighlightFunction(
  190536. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  190537. Fts5Context *pFts, /* First arg to pass to pApi functions */
  190538. sqlite3_context *pCtx, /* Context for returning result/error */
  190539. int nVal, /* Number of values in apVal[] array */
  190540. sqlite3_value **apVal /* Array of trailing arguments */
  190541. ){
  190542. HighlightContext ctx;
  190543. int rc;
  190544. int iCol;
  190545. if( nVal!=3 ){
  190546. const char *zErr = "wrong number of arguments to function highlight()";
  190547. sqlite3_result_error(pCtx, zErr, -1);
  190548. return;
  190549. }
  190550. iCol = sqlite3_value_int(apVal[0]);
  190551. memset(&ctx, 0, sizeof(HighlightContext));
  190552. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  190553. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  190554. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  190555. if( ctx.zIn ){
  190556. if( rc==SQLITE_OK ){
  190557. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  190558. }
  190559. if( rc==SQLITE_OK ){
  190560. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  190561. }
  190562. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  190563. if( rc==SQLITE_OK ){
  190564. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  190565. }
  190566. sqlite3_free(ctx.zOut);
  190567. }
  190568. if( rc!=SQLITE_OK ){
  190569. sqlite3_result_error_code(pCtx, rc);
  190570. }
  190571. }
  190572. /*
  190573. ** End of highlight() implementation.
  190574. **************************************************************************/
  190575. /*
  190576. ** Context object passed to the fts5SentenceFinderCb() function.
  190577. */
  190578. typedef struct Fts5SFinder Fts5SFinder;
  190579. struct Fts5SFinder {
  190580. int iPos; /* Current token position */
  190581. int nFirstAlloc; /* Allocated size of aFirst[] */
  190582. int nFirst; /* Number of entries in aFirst[] */
  190583. int *aFirst; /* Array of first token in each sentence */
  190584. const char *zDoc; /* Document being tokenized */
  190585. };
  190586. /*
  190587. ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
  190588. ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
  190589. ** error occurs.
  190590. */
  190591. static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
  190592. if( p->nFirstAlloc==p->nFirst ){
  190593. int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
  190594. int *aNew;
  190595. aNew = (int*)sqlite3_realloc64(p->aFirst, nNew*sizeof(int));
  190596. if( aNew==0 ) return SQLITE_NOMEM;
  190597. p->aFirst = aNew;
  190598. p->nFirstAlloc = nNew;
  190599. }
  190600. p->aFirst[p->nFirst++] = iAdd;
  190601. return SQLITE_OK;
  190602. }
  190603. /*
  190604. ** This function is an xTokenize() callback used by the auxiliary snippet()
  190605. ** function. Its job is to identify tokens that are the first in a sentence.
  190606. ** For each such token, an entry is added to the SFinder.aFirst[] array.
  190607. */
  190608. static int fts5SentenceFinderCb(
  190609. void *pContext, /* Pointer to HighlightContext object */
  190610. int tflags, /* Mask of FTS5_TOKEN_* flags */
  190611. const char *pToken, /* Buffer containing token */
  190612. int nToken, /* Size of token in bytes */
  190613. int iStartOff, /* Start offset of token */
  190614. int iEndOff /* End offset of token */
  190615. ){
  190616. int rc = SQLITE_OK;
  190617. UNUSED_PARAM2(pToken, nToken);
  190618. UNUSED_PARAM(iEndOff);
  190619. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  190620. Fts5SFinder *p = (Fts5SFinder*)pContext;
  190621. if( p->iPos>0 ){
  190622. int i;
  190623. char c = 0;
  190624. for(i=iStartOff-1; i>=0; i--){
  190625. c = p->zDoc[i];
  190626. if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
  190627. }
  190628. if( i!=iStartOff-1 && (c=='.' || c==':') ){
  190629. rc = fts5SentenceFinderAdd(p, p->iPos);
  190630. }
  190631. }else{
  190632. rc = fts5SentenceFinderAdd(p, 0);
  190633. }
  190634. p->iPos++;
  190635. }
  190636. return rc;
  190637. }
  190638. static int fts5SnippetScore(
  190639. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  190640. Fts5Context *pFts, /* First arg to pass to pApi functions */
  190641. int nDocsize, /* Size of column in tokens */
  190642. unsigned char *aSeen, /* Array with one element per query phrase */
  190643. int iCol, /* Column to score */
  190644. int iPos, /* Starting offset to score */
  190645. int nToken, /* Max tokens per snippet */
  190646. int *pnScore, /* OUT: Score */
  190647. int *piPos /* OUT: Adjusted offset */
  190648. ){
  190649. int rc;
  190650. int i;
  190651. int ip = 0;
  190652. int ic = 0;
  190653. int iOff = 0;
  190654. int iFirst = -1;
  190655. int nInst;
  190656. int nScore = 0;
  190657. int iLast = 0;
  190658. sqlite3_int64 iEnd = (sqlite3_int64)iPos + nToken;
  190659. rc = pApi->xInstCount(pFts, &nInst);
  190660. for(i=0; i<nInst && rc==SQLITE_OK; i++){
  190661. rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
  190662. if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<iEnd ){
  190663. nScore += (aSeen[ip] ? 1 : 1000);
  190664. aSeen[ip] = 1;
  190665. if( iFirst<0 ) iFirst = iOff;
  190666. iLast = iOff + pApi->xPhraseSize(pFts, ip);
  190667. }
  190668. }
  190669. *pnScore = nScore;
  190670. if( piPos ){
  190671. sqlite3_int64 iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
  190672. if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
  190673. if( iAdj<0 ) iAdj = 0;
  190674. *piPos = (int)iAdj;
  190675. }
  190676. return rc;
  190677. }
  190678. /*
  190679. ** Return the value in pVal interpreted as utf-8 text. Except, if pVal
  190680. ** contains a NULL value, return a pointer to a static string zero
  190681. ** bytes in length instead of a NULL pointer.
  190682. */
  190683. static const char *fts5ValueToText(sqlite3_value *pVal){
  190684. const char *zRet = (const char*)sqlite3_value_text(pVal);
  190685. return zRet ? zRet : "";
  190686. }
  190687. /*
  190688. ** Implementation of snippet() function.
  190689. */
  190690. static void fts5SnippetFunction(
  190691. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  190692. Fts5Context *pFts, /* First arg to pass to pApi functions */
  190693. sqlite3_context *pCtx, /* Context for returning result/error */
  190694. int nVal, /* Number of values in apVal[] array */
  190695. sqlite3_value **apVal /* Array of trailing arguments */
  190696. ){
  190697. HighlightContext ctx;
  190698. int rc = SQLITE_OK; /* Return code */
  190699. int iCol; /* 1st argument to snippet() */
  190700. const char *zEllips; /* 4th argument to snippet() */
  190701. int nToken; /* 5th argument to snippet() */
  190702. int nInst = 0; /* Number of instance matches this row */
  190703. int i; /* Used to iterate through instances */
  190704. int nPhrase; /* Number of phrases in query */
  190705. unsigned char *aSeen; /* Array of "seen instance" flags */
  190706. int iBestCol; /* Column containing best snippet */
  190707. int iBestStart = 0; /* First token of best snippet */
  190708. int nBestScore = 0; /* Score of best snippet */
  190709. int nColSize = 0; /* Total size of iBestCol in tokens */
  190710. Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
  190711. int nCol;
  190712. if( nVal!=5 ){
  190713. const char *zErr = "wrong number of arguments to function snippet()";
  190714. sqlite3_result_error(pCtx, zErr, -1);
  190715. return;
  190716. }
  190717. nCol = pApi->xColumnCount(pFts);
  190718. memset(&ctx, 0, sizeof(HighlightContext));
  190719. iCol = sqlite3_value_int(apVal[0]);
  190720. ctx.zOpen = fts5ValueToText(apVal[1]);
  190721. ctx.zClose = fts5ValueToText(apVal[2]);
  190722. zEllips = fts5ValueToText(apVal[3]);
  190723. nToken = sqlite3_value_int(apVal[4]);
  190724. iBestCol = (iCol>=0 ? iCol : 0);
  190725. nPhrase = pApi->xPhraseCount(pFts);
  190726. aSeen = sqlite3_malloc(nPhrase);
  190727. if( aSeen==0 ){
  190728. rc = SQLITE_NOMEM;
  190729. }
  190730. if( rc==SQLITE_OK ){
  190731. rc = pApi->xInstCount(pFts, &nInst);
  190732. }
  190733. memset(&sFinder, 0, sizeof(Fts5SFinder));
  190734. for(i=0; i<nCol; i++){
  190735. if( iCol<0 || iCol==i ){
  190736. int nDoc;
  190737. int nDocsize;
  190738. int ii;
  190739. sFinder.iPos = 0;
  190740. sFinder.nFirst = 0;
  190741. rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
  190742. if( rc!=SQLITE_OK ) break;
  190743. rc = pApi->xTokenize(pFts,
  190744. sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
  190745. );
  190746. if( rc!=SQLITE_OK ) break;
  190747. rc = pApi->xColumnSize(pFts, i, &nDocsize);
  190748. if( rc!=SQLITE_OK ) break;
  190749. for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
  190750. int ip, ic, io;
  190751. int iAdj;
  190752. int nScore;
  190753. int jj;
  190754. rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
  190755. if( ic!=i ) continue;
  190756. if( io>nDocsize ) rc = FTS5_CORRUPT;
  190757. if( rc!=SQLITE_OK ) continue;
  190758. memset(aSeen, 0, nPhrase);
  190759. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  190760. io, nToken, &nScore, &iAdj
  190761. );
  190762. if( rc==SQLITE_OK && nScore>nBestScore ){
  190763. nBestScore = nScore;
  190764. iBestCol = i;
  190765. iBestStart = iAdj;
  190766. nColSize = nDocsize;
  190767. }
  190768. if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
  190769. for(jj=0; jj<(sFinder.nFirst-1); jj++){
  190770. if( sFinder.aFirst[jj+1]>io ) break;
  190771. }
  190772. if( sFinder.aFirst[jj]<io ){
  190773. memset(aSeen, 0, nPhrase);
  190774. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  190775. sFinder.aFirst[jj], nToken, &nScore, 0
  190776. );
  190777. nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
  190778. if( rc==SQLITE_OK && nScore>nBestScore ){
  190779. nBestScore = nScore;
  190780. iBestCol = i;
  190781. iBestStart = sFinder.aFirst[jj];
  190782. nColSize = nDocsize;
  190783. }
  190784. }
  190785. }
  190786. }
  190787. }
  190788. }
  190789. if( rc==SQLITE_OK ){
  190790. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  190791. }
  190792. if( rc==SQLITE_OK && nColSize==0 ){
  190793. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  190794. }
  190795. if( ctx.zIn ){
  190796. if( rc==SQLITE_OK ){
  190797. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  190798. }
  190799. ctx.iRangeStart = iBestStart;
  190800. ctx.iRangeEnd = iBestStart + nToken - 1;
  190801. if( iBestStart>0 ){
  190802. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  190803. }
  190804. /* Advance iterator ctx.iter so that it points to the first coalesced
  190805. ** phrase instance at or following position iBestStart. */
  190806. while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
  190807. rc = fts5CInstIterNext(&ctx.iter);
  190808. }
  190809. if( rc==SQLITE_OK ){
  190810. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  190811. }
  190812. if( ctx.iRangeEnd>=(nColSize-1) ){
  190813. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  190814. }else{
  190815. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  190816. }
  190817. }
  190818. if( rc==SQLITE_OK ){
  190819. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  190820. }else{
  190821. sqlite3_result_error_code(pCtx, rc);
  190822. }
  190823. sqlite3_free(ctx.zOut);
  190824. sqlite3_free(aSeen);
  190825. sqlite3_free(sFinder.aFirst);
  190826. }
  190827. /************************************************************************/
  190828. /*
  190829. ** The first time the bm25() function is called for a query, an instance
  190830. ** of the following structure is allocated and populated.
  190831. */
  190832. typedef struct Fts5Bm25Data Fts5Bm25Data;
  190833. struct Fts5Bm25Data {
  190834. int nPhrase; /* Number of phrases in query */
  190835. double avgdl; /* Average number of tokens in each row */
  190836. double *aIDF; /* IDF for each phrase */
  190837. double *aFreq; /* Array used to calculate phrase freq. */
  190838. };
  190839. /*
  190840. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  190841. ** table matched by each individual phrase within the query.
  190842. */
  190843. static int fts5CountCb(
  190844. const Fts5ExtensionApi *pApi,
  190845. Fts5Context *pFts,
  190846. void *pUserData /* Pointer to sqlite3_int64 variable */
  190847. ){
  190848. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  190849. UNUSED_PARAM2(pApi, pFts);
  190850. (*pn)++;
  190851. return SQLITE_OK;
  190852. }
  190853. /*
  190854. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  190855. ** If the object has not already been allocated, allocate and populate it
  190856. ** now.
  190857. */
  190858. static int fts5Bm25GetData(
  190859. const Fts5ExtensionApi *pApi,
  190860. Fts5Context *pFts,
  190861. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  190862. ){
  190863. int rc = SQLITE_OK; /* Return code */
  190864. Fts5Bm25Data *p; /* Object to return */
  190865. p = pApi->xGetAuxdata(pFts, 0);
  190866. if( p==0 ){
  190867. int nPhrase; /* Number of phrases in query */
  190868. sqlite3_int64 nRow = 0; /* Number of rows in table */
  190869. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  190870. sqlite3_int64 nByte; /* Bytes of space to allocate */
  190871. int i;
  190872. /* Allocate the Fts5Bm25Data object */
  190873. nPhrase = pApi->xPhraseCount(pFts);
  190874. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  190875. p = (Fts5Bm25Data*)sqlite3_malloc64(nByte);
  190876. if( p==0 ){
  190877. rc = SQLITE_NOMEM;
  190878. }else{
  190879. memset(p, 0, (size_t)nByte);
  190880. p->nPhrase = nPhrase;
  190881. p->aIDF = (double*)&p[1];
  190882. p->aFreq = &p->aIDF[nPhrase];
  190883. }
  190884. /* Calculate the average document length for this FTS5 table */
  190885. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  190886. assert( rc!=SQLITE_OK || nRow>0 );
  190887. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  190888. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  190889. /* Calculate an IDF for each phrase in the query */
  190890. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  190891. sqlite3_int64 nHit = 0;
  190892. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  190893. if( rc==SQLITE_OK ){
  190894. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  190895. ** This is done using the standard BM25 formula as found on wikipedia:
  190896. **
  190897. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  190898. **
  190899. ** where "N" is the total number of documents in the set and nHit
  190900. ** is the number that contain at least one instance of the phrase
  190901. ** under consideration.
  190902. **
  190903. ** The problem with this is that if (N < 2*nHit), the IDF is
  190904. ** negative. Which is undesirable. So the mimimum allowable IDF is
  190905. ** (1e-6) - roughly the same as a term that appears in just over
  190906. ** half of set of 5,000,000 documents. */
  190907. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  190908. if( idf<=0.0 ) idf = 1e-6;
  190909. p->aIDF[i] = idf;
  190910. }
  190911. }
  190912. if( rc!=SQLITE_OK ){
  190913. sqlite3_free(p);
  190914. }else{
  190915. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  190916. }
  190917. if( rc!=SQLITE_OK ) p = 0;
  190918. }
  190919. *ppData = p;
  190920. return rc;
  190921. }
  190922. /*
  190923. ** Implementation of bm25() function.
  190924. */
  190925. static void fts5Bm25Function(
  190926. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  190927. Fts5Context *pFts, /* First arg to pass to pApi functions */
  190928. sqlite3_context *pCtx, /* Context for returning result/error */
  190929. int nVal, /* Number of values in apVal[] array */
  190930. sqlite3_value **apVal /* Array of trailing arguments */
  190931. ){
  190932. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  190933. const double b = 0.75; /* Constant "b" from BM25 formula */
  190934. int rc = SQLITE_OK; /* Error code */
  190935. double score = 0.0; /* SQL function return value */
  190936. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  190937. int i; /* Iterator variable */
  190938. int nInst = 0; /* Value returned by xInstCount() */
  190939. double D = 0.0; /* Total number of tokens in row */
  190940. double *aFreq = 0; /* Array of phrase freq. for current row */
  190941. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  190942. ** for each phrase in the query for the current row. */
  190943. rc = fts5Bm25GetData(pApi, pFts, &pData);
  190944. if( rc==SQLITE_OK ){
  190945. aFreq = pData->aFreq;
  190946. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  190947. rc = pApi->xInstCount(pFts, &nInst);
  190948. }
  190949. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  190950. int ip; int ic; int io;
  190951. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  190952. if( rc==SQLITE_OK ){
  190953. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  190954. aFreq[ip] += w;
  190955. }
  190956. }
  190957. /* Figure out the total size of the current row in tokens. */
  190958. if( rc==SQLITE_OK ){
  190959. int nTok;
  190960. rc = pApi->xColumnSize(pFts, -1, &nTok);
  190961. D = (double)nTok;
  190962. }
  190963. /* Determine the BM25 score for the current row. */
  190964. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  190965. score += pData->aIDF[i] * (
  190966. ( aFreq[i] * (k1 + 1.0) ) /
  190967. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  190968. );
  190969. }
  190970. /* If no error has occurred, return the calculated score. Otherwise,
  190971. ** throw an SQL exception. */
  190972. if( rc==SQLITE_OK ){
  190973. sqlite3_result_double(pCtx, -1.0 * score);
  190974. }else{
  190975. sqlite3_result_error_code(pCtx, rc);
  190976. }
  190977. }
  190978. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  190979. struct Builtin {
  190980. const char *zFunc; /* Function name (nul-terminated) */
  190981. void *pUserData; /* User-data pointer */
  190982. fts5_extension_function xFunc;/* Callback function */
  190983. void (*xDestroy)(void*); /* Destructor function */
  190984. } aBuiltin [] = {
  190985. { "snippet", 0, fts5SnippetFunction, 0 },
  190986. { "highlight", 0, fts5HighlightFunction, 0 },
  190987. { "bm25", 0, fts5Bm25Function, 0 },
  190988. };
  190989. int rc = SQLITE_OK; /* Return code */
  190990. int i; /* To iterate through builtin functions */
  190991. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  190992. rc = pApi->xCreateFunction(pApi,
  190993. aBuiltin[i].zFunc,
  190994. aBuiltin[i].pUserData,
  190995. aBuiltin[i].xFunc,
  190996. aBuiltin[i].xDestroy
  190997. );
  190998. }
  190999. return rc;
  191000. }
  191001. /*
  191002. ** 2014 May 31
  191003. **
  191004. ** The author disclaims copyright to this source code. In place of
  191005. ** a legal notice, here is a blessing:
  191006. **
  191007. ** May you do good and not evil.
  191008. ** May you find forgiveness for yourself and forgive others.
  191009. ** May you share freely, never taking more than you give.
  191010. **
  191011. ******************************************************************************
  191012. */
  191013. /* #include "fts5Int.h" */
  191014. static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
  191015. if( (u32)pBuf->nSpace<nByte ){
  191016. u64 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
  191017. u8 *pNew;
  191018. while( nNew<nByte ){
  191019. nNew = nNew * 2;
  191020. }
  191021. pNew = sqlite3_realloc64(pBuf->p, nNew);
  191022. if( pNew==0 ){
  191023. *pRc = SQLITE_NOMEM;
  191024. return 1;
  191025. }else{
  191026. pBuf->nSpace = (int)nNew;
  191027. pBuf->p = pNew;
  191028. }
  191029. }
  191030. return 0;
  191031. }
  191032. /*
  191033. ** Encode value iVal as an SQLite varint and append it to the buffer object
  191034. ** pBuf. If an OOM error occurs, set the error code in p.
  191035. */
  191036. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  191037. if( fts5BufferGrow(pRc, pBuf, 9) ) return;
  191038. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  191039. }
  191040. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  191041. aBuf[0] = (iVal>>24) & 0x00FF;
  191042. aBuf[1] = (iVal>>16) & 0x00FF;
  191043. aBuf[2] = (iVal>> 8) & 0x00FF;
  191044. aBuf[3] = (iVal>> 0) & 0x00FF;
  191045. }
  191046. static int sqlite3Fts5Get32(const u8 *aBuf){
  191047. return (int)((((u32)aBuf[0])<<24) + (aBuf[1]<<16) + (aBuf[2]<<8) + aBuf[3]);
  191048. }
  191049. /*
  191050. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  191051. ** the error code in p. If an error has already occurred when this function
  191052. ** is called, it is a no-op.
  191053. */
  191054. static void sqlite3Fts5BufferAppendBlob(
  191055. int *pRc,
  191056. Fts5Buffer *pBuf,
  191057. u32 nData,
  191058. const u8 *pData
  191059. ){
  191060. assert_nc( *pRc || nData>=0 );
  191061. if( nData ){
  191062. if( fts5BufferGrow(pRc, pBuf, nData) ) return;
  191063. memcpy(&pBuf->p[pBuf->n], pData, nData);
  191064. pBuf->n += nData;
  191065. }
  191066. }
  191067. /*
  191068. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  191069. ** ensures that the byte following the buffer data is set to 0x00, even
  191070. ** though this byte is not included in the pBuf->n count.
  191071. */
  191072. static void sqlite3Fts5BufferAppendString(
  191073. int *pRc,
  191074. Fts5Buffer *pBuf,
  191075. const char *zStr
  191076. ){
  191077. int nStr = (int)strlen(zStr);
  191078. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  191079. pBuf->n--;
  191080. }
  191081. /*
  191082. ** Argument zFmt is a printf() style format string. This function performs
  191083. ** the printf() style processing, then appends the results to buffer pBuf.
  191084. **
  191085. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  191086. ** following the buffer data is set to 0x00, even though this byte is not
  191087. ** included in the pBuf->n count.
  191088. */
  191089. static void sqlite3Fts5BufferAppendPrintf(
  191090. int *pRc,
  191091. Fts5Buffer *pBuf,
  191092. char *zFmt, ...
  191093. ){
  191094. if( *pRc==SQLITE_OK ){
  191095. char *zTmp;
  191096. va_list ap;
  191097. va_start(ap, zFmt);
  191098. zTmp = sqlite3_vmprintf(zFmt, ap);
  191099. va_end(ap);
  191100. if( zTmp==0 ){
  191101. *pRc = SQLITE_NOMEM;
  191102. }else{
  191103. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  191104. sqlite3_free(zTmp);
  191105. }
  191106. }
  191107. }
  191108. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  191109. char *zRet = 0;
  191110. if( *pRc==SQLITE_OK ){
  191111. va_list ap;
  191112. va_start(ap, zFmt);
  191113. zRet = sqlite3_vmprintf(zFmt, ap);
  191114. va_end(ap);
  191115. if( zRet==0 ){
  191116. *pRc = SQLITE_NOMEM;
  191117. }
  191118. }
  191119. return zRet;
  191120. }
  191121. /*
  191122. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  191123. */
  191124. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  191125. sqlite3_free(pBuf->p);
  191126. memset(pBuf, 0, sizeof(Fts5Buffer));
  191127. }
  191128. /*
  191129. ** Zero the contents of the buffer object. But do not free the associated
  191130. ** memory allocation.
  191131. */
  191132. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  191133. pBuf->n = 0;
  191134. }
  191135. /*
  191136. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  191137. ** the error code in p. If an error has already occurred when this function
  191138. ** is called, it is a no-op.
  191139. */
  191140. static void sqlite3Fts5BufferSet(
  191141. int *pRc,
  191142. Fts5Buffer *pBuf,
  191143. int nData,
  191144. const u8 *pData
  191145. ){
  191146. pBuf->n = 0;
  191147. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  191148. }
  191149. static int sqlite3Fts5PoslistNext64(
  191150. const u8 *a, int n, /* Buffer containing poslist */
  191151. int *pi, /* IN/OUT: Offset within a[] */
  191152. i64 *piOff /* IN/OUT: Current offset */
  191153. ){
  191154. int i = *pi;
  191155. if( i>=n ){
  191156. /* EOF */
  191157. *piOff = -1;
  191158. return 1;
  191159. }else{
  191160. i64 iOff = *piOff;
  191161. int iVal;
  191162. fts5FastGetVarint32(a, i, iVal);
  191163. if( iVal==1 ){
  191164. fts5FastGetVarint32(a, i, iVal);
  191165. iOff = ((i64)iVal) << 32;
  191166. fts5FastGetVarint32(a, i, iVal);
  191167. }
  191168. *piOff = iOff + ((iVal-2) & 0x7FFFFFFF);
  191169. *pi = i;
  191170. return 0;
  191171. }
  191172. }
  191173. /*
  191174. ** Advance the iterator object passed as the only argument. Return true
  191175. ** if the iterator reaches EOF, or false otherwise.
  191176. */
  191177. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  191178. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  191179. pIter->bEof = 1;
  191180. }
  191181. return pIter->bEof;
  191182. }
  191183. static int sqlite3Fts5PoslistReaderInit(
  191184. const u8 *a, int n, /* Poslist buffer to iterate through */
  191185. Fts5PoslistReader *pIter /* Iterator object to initialize */
  191186. ){
  191187. memset(pIter, 0, sizeof(*pIter));
  191188. pIter->a = a;
  191189. pIter->n = n;
  191190. sqlite3Fts5PoslistReaderNext(pIter);
  191191. return pIter->bEof;
  191192. }
  191193. /*
  191194. ** Append position iPos to the position list being accumulated in buffer
  191195. ** pBuf, which must be already be large enough to hold the new data.
  191196. ** The previous position written to this list is *piPrev. *piPrev is set
  191197. ** to iPos before returning.
  191198. */
  191199. static void sqlite3Fts5PoslistSafeAppend(
  191200. Fts5Buffer *pBuf,
  191201. i64 *piPrev,
  191202. i64 iPos
  191203. ){
  191204. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  191205. if( (iPos & colmask) != (*piPrev & colmask) ){
  191206. pBuf->p[pBuf->n++] = 1;
  191207. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  191208. *piPrev = (iPos & colmask);
  191209. }
  191210. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
  191211. *piPrev = iPos;
  191212. }
  191213. static int sqlite3Fts5PoslistWriterAppend(
  191214. Fts5Buffer *pBuf,
  191215. Fts5PoslistWriter *pWriter,
  191216. i64 iPos
  191217. ){
  191218. int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
  191219. if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
  191220. sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
  191221. return SQLITE_OK;
  191222. }
  191223. static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte){
  191224. void *pRet = 0;
  191225. if( *pRc==SQLITE_OK ){
  191226. pRet = sqlite3_malloc64(nByte);
  191227. if( pRet==0 ){
  191228. if( nByte>0 ) *pRc = SQLITE_NOMEM;
  191229. }else{
  191230. memset(pRet, 0, (size_t)nByte);
  191231. }
  191232. }
  191233. return pRet;
  191234. }
  191235. /*
  191236. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  191237. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  191238. ** the length of the string is determined using strlen().
  191239. **
  191240. ** It is the responsibility of the caller to eventually free the returned
  191241. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  191242. */
  191243. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  191244. char *zRet = 0;
  191245. if( *pRc==SQLITE_OK ){
  191246. if( nIn<0 ){
  191247. nIn = (int)strlen(pIn);
  191248. }
  191249. zRet = (char*)sqlite3_malloc(nIn+1);
  191250. if( zRet ){
  191251. memcpy(zRet, pIn, nIn);
  191252. zRet[nIn] = '\0';
  191253. }else{
  191254. *pRc = SQLITE_NOMEM;
  191255. }
  191256. }
  191257. return zRet;
  191258. }
  191259. /*
  191260. ** Return true if character 't' may be part of an FTS5 bareword, or false
  191261. ** otherwise. Characters that may be part of barewords:
  191262. **
  191263. ** * All non-ASCII characters,
  191264. ** * The 52 upper and lower case ASCII characters, and
  191265. ** * The 10 integer ASCII characters.
  191266. ** * The underscore character "_" (0x5F).
  191267. ** * The unicode "subsitute" character (0x1A).
  191268. */
  191269. static int sqlite3Fts5IsBareword(char t){
  191270. u8 aBareword[128] = {
  191271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  191272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  191273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  191274. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  191275. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  191276. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  191277. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  191278. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  191279. };
  191280. return (t & 0x80) || aBareword[(int)t];
  191281. }
  191282. /*************************************************************************
  191283. */
  191284. typedef struct Fts5TermsetEntry Fts5TermsetEntry;
  191285. struct Fts5TermsetEntry {
  191286. char *pTerm;
  191287. int nTerm;
  191288. int iIdx; /* Index (main or aPrefix[] entry) */
  191289. Fts5TermsetEntry *pNext;
  191290. };
  191291. struct Fts5Termset {
  191292. Fts5TermsetEntry *apHash[512];
  191293. };
  191294. static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
  191295. int rc = SQLITE_OK;
  191296. *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
  191297. return rc;
  191298. }
  191299. static int sqlite3Fts5TermsetAdd(
  191300. Fts5Termset *p,
  191301. int iIdx,
  191302. const char *pTerm, int nTerm,
  191303. int *pbPresent
  191304. ){
  191305. int rc = SQLITE_OK;
  191306. *pbPresent = 0;
  191307. if( p ){
  191308. int i;
  191309. u32 hash = 13;
  191310. Fts5TermsetEntry *pEntry;
  191311. /* Calculate a hash value for this term. This is the same hash checksum
  191312. ** used by the fts5_hash.c module. This is not important for correct
  191313. ** operation of the module, but is necessary to ensure that some tests
  191314. ** designed to produce hash table collisions really do work. */
  191315. for(i=nTerm-1; i>=0; i--){
  191316. hash = (hash << 3) ^ hash ^ pTerm[i];
  191317. }
  191318. hash = (hash << 3) ^ hash ^ iIdx;
  191319. hash = hash % ArraySize(p->apHash);
  191320. for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
  191321. if( pEntry->iIdx==iIdx
  191322. && pEntry->nTerm==nTerm
  191323. && memcmp(pEntry->pTerm, pTerm, nTerm)==0
  191324. ){
  191325. *pbPresent = 1;
  191326. break;
  191327. }
  191328. }
  191329. if( pEntry==0 ){
  191330. pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
  191331. if( pEntry ){
  191332. pEntry->pTerm = (char*)&pEntry[1];
  191333. pEntry->nTerm = nTerm;
  191334. pEntry->iIdx = iIdx;
  191335. memcpy(pEntry->pTerm, pTerm, nTerm);
  191336. pEntry->pNext = p->apHash[hash];
  191337. p->apHash[hash] = pEntry;
  191338. }
  191339. }
  191340. }
  191341. return rc;
  191342. }
  191343. static void sqlite3Fts5TermsetFree(Fts5Termset *p){
  191344. if( p ){
  191345. u32 i;
  191346. for(i=0; i<ArraySize(p->apHash); i++){
  191347. Fts5TermsetEntry *pEntry = p->apHash[i];
  191348. while( pEntry ){
  191349. Fts5TermsetEntry *pDel = pEntry;
  191350. pEntry = pEntry->pNext;
  191351. sqlite3_free(pDel);
  191352. }
  191353. }
  191354. sqlite3_free(p);
  191355. }
  191356. }
  191357. /*
  191358. ** 2014 Jun 09
  191359. **
  191360. ** The author disclaims copyright to this source code. In place of
  191361. ** a legal notice, here is a blessing:
  191362. **
  191363. ** May you do good and not evil.
  191364. ** May you find forgiveness for yourself and forgive others.
  191365. ** May you share freely, never taking more than you give.
  191366. **
  191367. ******************************************************************************
  191368. **
  191369. ** This is an SQLite module implementing full-text search.
  191370. */
  191371. /* #include "fts5Int.h" */
  191372. #define FTS5_DEFAULT_PAGE_SIZE 4050
  191373. #define FTS5_DEFAULT_AUTOMERGE 4
  191374. #define FTS5_DEFAULT_USERMERGE 4
  191375. #define FTS5_DEFAULT_CRISISMERGE 16
  191376. #define FTS5_DEFAULT_HASHSIZE (1024*1024)
  191377. /* Maximum allowed page size */
  191378. #define FTS5_MAX_PAGE_SIZE (128*1024)
  191379. static int fts5_iswhitespace(char x){
  191380. return (x==' ');
  191381. }
  191382. static int fts5_isopenquote(char x){
  191383. return (x=='"' || x=='\'' || x=='[' || x=='`');
  191384. }
  191385. /*
  191386. ** Argument pIn points to a character that is part of a nul-terminated
  191387. ** string. Return a pointer to the first character following *pIn in
  191388. ** the string that is not a white-space character.
  191389. */
  191390. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  191391. const char *p = pIn;
  191392. if( p ){
  191393. while( fts5_iswhitespace(*p) ){ p++; }
  191394. }
  191395. return p;
  191396. }
  191397. /*
  191398. ** Argument pIn points to a character that is part of a nul-terminated
  191399. ** string. Return a pointer to the first character following *pIn in
  191400. ** the string that is not a "bareword" character.
  191401. */
  191402. static const char *fts5ConfigSkipBareword(const char *pIn){
  191403. const char *p = pIn;
  191404. while ( sqlite3Fts5IsBareword(*p) ) p++;
  191405. if( p==pIn ) p = 0;
  191406. return p;
  191407. }
  191408. static int fts5_isdigit(char a){
  191409. return (a>='0' && a<='9');
  191410. }
  191411. static const char *fts5ConfigSkipLiteral(const char *pIn){
  191412. const char *p = pIn;
  191413. switch( *p ){
  191414. case 'n': case 'N':
  191415. if( sqlite3_strnicmp("null", p, 4)==0 ){
  191416. p = &p[4];
  191417. }else{
  191418. p = 0;
  191419. }
  191420. break;
  191421. case 'x': case 'X':
  191422. p++;
  191423. if( *p=='\'' ){
  191424. p++;
  191425. while( (*p>='a' && *p<='f')
  191426. || (*p>='A' && *p<='F')
  191427. || (*p>='0' && *p<='9')
  191428. ){
  191429. p++;
  191430. }
  191431. if( *p=='\'' && 0==((p-pIn)%2) ){
  191432. p++;
  191433. }else{
  191434. p = 0;
  191435. }
  191436. }else{
  191437. p = 0;
  191438. }
  191439. break;
  191440. case '\'':
  191441. p++;
  191442. while( p ){
  191443. if( *p=='\'' ){
  191444. p++;
  191445. if( *p!='\'' ) break;
  191446. }
  191447. p++;
  191448. if( *p==0 ) p = 0;
  191449. }
  191450. break;
  191451. default:
  191452. /* maybe a number */
  191453. if( *p=='+' || *p=='-' ) p++;
  191454. while( fts5_isdigit(*p) ) p++;
  191455. /* At this point, if the literal was an integer, the parse is
  191456. ** finished. Or, if it is a floating point value, it may continue
  191457. ** with either a decimal point or an 'E' character. */
  191458. if( *p=='.' && fts5_isdigit(p[1]) ){
  191459. p += 2;
  191460. while( fts5_isdigit(*p) ) p++;
  191461. }
  191462. if( p==pIn ) p = 0;
  191463. break;
  191464. }
  191465. return p;
  191466. }
  191467. /*
  191468. ** The first character of the string pointed to by argument z is guaranteed
  191469. ** to be an open-quote character (see function fts5_isopenquote()).
  191470. **
  191471. ** This function searches for the corresponding close-quote character within
  191472. ** the string and, if found, dequotes the string in place and adds a new
  191473. ** nul-terminator byte.
  191474. **
  191475. ** If the close-quote is found, the value returned is the byte offset of
  191476. ** the character immediately following it. Or, if the close-quote is not
  191477. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  191478. ** undefined state.
  191479. */
  191480. static int fts5Dequote(char *z){
  191481. char q;
  191482. int iIn = 1;
  191483. int iOut = 0;
  191484. q = z[0];
  191485. /* Set stack variable q to the close-quote character */
  191486. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  191487. if( q=='[' ) q = ']';
  191488. while( ALWAYS(z[iIn]) ){
  191489. if( z[iIn]==q ){
  191490. if( z[iIn+1]!=q ){
  191491. /* Character iIn was the close quote. */
  191492. iIn++;
  191493. break;
  191494. }else{
  191495. /* Character iIn and iIn+1 form an escaped quote character. Skip
  191496. ** the input cursor past both and copy a single quote character
  191497. ** to the output buffer. */
  191498. iIn += 2;
  191499. z[iOut++] = q;
  191500. }
  191501. }else{
  191502. z[iOut++] = z[iIn++];
  191503. }
  191504. }
  191505. z[iOut] = '\0';
  191506. return iIn;
  191507. }
  191508. /*
  191509. ** Convert an SQL-style quoted string into a normal string by removing
  191510. ** the quote characters. The conversion is done in-place. If the
  191511. ** input does not begin with a quote character, then this routine
  191512. ** is a no-op.
  191513. **
  191514. ** Examples:
  191515. **
  191516. ** "abc" becomes abc
  191517. ** 'xyz' becomes xyz
  191518. ** [pqr] becomes pqr
  191519. ** `mno` becomes mno
  191520. */
  191521. static void sqlite3Fts5Dequote(char *z){
  191522. char quote; /* Quote character (if any ) */
  191523. assert( 0==fts5_iswhitespace(z[0]) );
  191524. quote = z[0];
  191525. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  191526. fts5Dequote(z);
  191527. }
  191528. }
  191529. struct Fts5Enum {
  191530. const char *zName;
  191531. int eVal;
  191532. };
  191533. typedef struct Fts5Enum Fts5Enum;
  191534. static int fts5ConfigSetEnum(
  191535. const Fts5Enum *aEnum,
  191536. const char *zEnum,
  191537. int *peVal
  191538. ){
  191539. int nEnum = (int)strlen(zEnum);
  191540. int i;
  191541. int iVal = -1;
  191542. for(i=0; aEnum[i].zName; i++){
  191543. if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
  191544. if( iVal>=0 ) return SQLITE_ERROR;
  191545. iVal = aEnum[i].eVal;
  191546. }
  191547. }
  191548. *peVal = iVal;
  191549. return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
  191550. }
  191551. /*
  191552. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  191553. ** configuration object pConfig as appropriate.
  191554. **
  191555. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  191556. ** an error occurs, an SQLite error code is returned and an error message
  191557. ** may be left in *pzErr. It is the responsibility of the caller to
  191558. ** eventually free any such error message using sqlite3_free().
  191559. */
  191560. static int fts5ConfigParseSpecial(
  191561. Fts5Global *pGlobal,
  191562. Fts5Config *pConfig, /* Configuration object to update */
  191563. const char *zCmd, /* Special command to parse */
  191564. const char *zArg, /* Argument to parse */
  191565. char **pzErr /* OUT: Error message */
  191566. ){
  191567. int rc = SQLITE_OK;
  191568. int nCmd = (int)strlen(zCmd);
  191569. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  191570. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  191571. const char *p;
  191572. int bFirst = 1;
  191573. if( pConfig->aPrefix==0 ){
  191574. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  191575. if( rc ) return rc;
  191576. }
  191577. p = zArg;
  191578. while( 1 ){
  191579. int nPre = 0;
  191580. while( p[0]==' ' ) p++;
  191581. if( bFirst==0 && p[0]==',' ){
  191582. p++;
  191583. while( p[0]==' ' ) p++;
  191584. }else if( p[0]=='\0' ){
  191585. break;
  191586. }
  191587. if( p[0]<'0' || p[0]>'9' ){
  191588. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  191589. rc = SQLITE_ERROR;
  191590. break;
  191591. }
  191592. if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
  191593. *pzErr = sqlite3_mprintf(
  191594. "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
  191595. );
  191596. rc = SQLITE_ERROR;
  191597. break;
  191598. }
  191599. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  191600. nPre = nPre*10 + (p[0] - '0');
  191601. p++;
  191602. }
  191603. if( nPre<=0 || nPre>=1000 ){
  191604. *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
  191605. rc = SQLITE_ERROR;
  191606. break;
  191607. }
  191608. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  191609. pConfig->nPrefix++;
  191610. bFirst = 0;
  191611. }
  191612. assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
  191613. return rc;
  191614. }
  191615. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  191616. const char *p = (const char*)zArg;
  191617. sqlite3_int64 nArg = strlen(zArg) + 1;
  191618. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  191619. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  191620. char *pSpace = pDel;
  191621. if( azArg && pSpace ){
  191622. if( pConfig->pTok ){
  191623. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  191624. rc = SQLITE_ERROR;
  191625. }else{
  191626. for(nArg=0; p && *p; nArg++){
  191627. const char *p2 = fts5ConfigSkipWhitespace(p);
  191628. if( *p2=='\'' ){
  191629. p = fts5ConfigSkipLiteral(p2);
  191630. }else{
  191631. p = fts5ConfigSkipBareword(p2);
  191632. }
  191633. if( p ){
  191634. memcpy(pSpace, p2, p-p2);
  191635. azArg[nArg] = pSpace;
  191636. sqlite3Fts5Dequote(pSpace);
  191637. pSpace += (p - p2) + 1;
  191638. p = fts5ConfigSkipWhitespace(p);
  191639. }
  191640. }
  191641. if( p==0 ){
  191642. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  191643. rc = SQLITE_ERROR;
  191644. }else{
  191645. rc = sqlite3Fts5GetTokenizer(pGlobal,
  191646. (const char**)azArg, (int)nArg, &pConfig->pTok, &pConfig->pTokApi,
  191647. pzErr
  191648. );
  191649. }
  191650. }
  191651. }
  191652. sqlite3_free(azArg);
  191653. sqlite3_free(pDel);
  191654. return rc;
  191655. }
  191656. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  191657. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  191658. *pzErr = sqlite3_mprintf("multiple content=... directives");
  191659. rc = SQLITE_ERROR;
  191660. }else{
  191661. if( zArg[0] ){
  191662. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  191663. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  191664. }else{
  191665. pConfig->eContent = FTS5_CONTENT_NONE;
  191666. }
  191667. }
  191668. return rc;
  191669. }
  191670. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  191671. if( pConfig->zContentRowid ){
  191672. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  191673. rc = SQLITE_ERROR;
  191674. }else{
  191675. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  191676. }
  191677. return rc;
  191678. }
  191679. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  191680. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  191681. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  191682. rc = SQLITE_ERROR;
  191683. }else{
  191684. pConfig->bColumnsize = (zArg[0]=='1');
  191685. }
  191686. return rc;
  191687. }
  191688. if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
  191689. const Fts5Enum aDetail[] = {
  191690. { "none", FTS5_DETAIL_NONE },
  191691. { "full", FTS5_DETAIL_FULL },
  191692. { "columns", FTS5_DETAIL_COLUMNS },
  191693. { 0, 0 }
  191694. };
  191695. if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
  191696. *pzErr = sqlite3_mprintf("malformed detail=... directive");
  191697. }
  191698. return rc;
  191699. }
  191700. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  191701. return SQLITE_ERROR;
  191702. }
  191703. /*
  191704. ** Allocate an instance of the default tokenizer ("simple") at
  191705. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  191706. ** code if an error occurs.
  191707. */
  191708. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  191709. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  191710. return sqlite3Fts5GetTokenizer(
  191711. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  191712. );
  191713. }
  191714. /*
  191715. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  191716. ** Return a pointer to the character immediately following the last in
  191717. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  191718. ** to find close-quote character).
  191719. **
  191720. ** Before returning, set pzOut to point to a new buffer containing a
  191721. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  191722. ** quoted, *pbQuoted is also set to 1 before returning.
  191723. **
  191724. ** If *pRc is other than SQLITE_OK when this function is called, it is
  191725. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  191726. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  191727. ** set if a parse error (failed to find close quote) occurs.
  191728. */
  191729. static const char *fts5ConfigGobbleWord(
  191730. int *pRc, /* IN/OUT: Error code */
  191731. const char *zIn, /* Buffer to gobble string/bareword from */
  191732. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  191733. int *pbQuoted /* OUT: Set to true if dequoting required */
  191734. ){
  191735. const char *zRet = 0;
  191736. sqlite3_int64 nIn = strlen(zIn);
  191737. char *zOut = sqlite3_malloc64(nIn+1);
  191738. assert( *pRc==SQLITE_OK );
  191739. *pbQuoted = 0;
  191740. *pzOut = 0;
  191741. if( zOut==0 ){
  191742. *pRc = SQLITE_NOMEM;
  191743. }else{
  191744. memcpy(zOut, zIn, (size_t)(nIn+1));
  191745. if( fts5_isopenquote(zOut[0]) ){
  191746. int ii = fts5Dequote(zOut);
  191747. zRet = &zIn[ii];
  191748. *pbQuoted = 1;
  191749. }else{
  191750. zRet = fts5ConfigSkipBareword(zIn);
  191751. if( zRet ){
  191752. zOut[zRet-zIn] = '\0';
  191753. }
  191754. }
  191755. }
  191756. if( zRet==0 ){
  191757. sqlite3_free(zOut);
  191758. }else{
  191759. *pzOut = zOut;
  191760. }
  191761. return zRet;
  191762. }
  191763. static int fts5ConfigParseColumn(
  191764. Fts5Config *p,
  191765. char *zCol,
  191766. char *zArg,
  191767. char **pzErr
  191768. ){
  191769. int rc = SQLITE_OK;
  191770. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  191771. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  191772. ){
  191773. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  191774. rc = SQLITE_ERROR;
  191775. }else if( zArg ){
  191776. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  191777. p->abUnindexed[p->nCol] = 1;
  191778. }else{
  191779. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  191780. rc = SQLITE_ERROR;
  191781. }
  191782. }
  191783. p->azCol[p->nCol++] = zCol;
  191784. return rc;
  191785. }
  191786. /*
  191787. ** Populate the Fts5Config.zContentExprlist string.
  191788. */
  191789. static int fts5ConfigMakeExprlist(Fts5Config *p){
  191790. int i;
  191791. int rc = SQLITE_OK;
  191792. Fts5Buffer buf = {0, 0, 0};
  191793. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  191794. if( p->eContent!=FTS5_CONTENT_NONE ){
  191795. for(i=0; i<p->nCol; i++){
  191796. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  191797. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  191798. }else{
  191799. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  191800. }
  191801. }
  191802. }
  191803. assert( p->zContentExprlist==0 );
  191804. p->zContentExprlist = (char*)buf.p;
  191805. return rc;
  191806. }
  191807. /*
  191808. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  191809. ** or xConnect method of the virtual table. This function attempts to
  191810. ** allocate an instance of Fts5Config containing the results of parsing
  191811. ** those arguments.
  191812. **
  191813. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  191814. ** new Fts5Config object. If an error occurs, an SQLite error code is
  191815. ** returned, *ppOut is set to NULL and an error message may be left in
  191816. ** *pzErr. It is the responsibility of the caller to eventually free any
  191817. ** such error message using sqlite3_free().
  191818. */
  191819. static int sqlite3Fts5ConfigParse(
  191820. Fts5Global *pGlobal,
  191821. sqlite3 *db,
  191822. int nArg, /* Number of arguments */
  191823. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  191824. Fts5Config **ppOut, /* OUT: Results of parse */
  191825. char **pzErr /* OUT: Error message */
  191826. ){
  191827. int rc = SQLITE_OK; /* Return code */
  191828. Fts5Config *pRet; /* New object to return */
  191829. int i;
  191830. sqlite3_int64 nByte;
  191831. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  191832. if( pRet==0 ) return SQLITE_NOMEM;
  191833. memset(pRet, 0, sizeof(Fts5Config));
  191834. pRet->db = db;
  191835. pRet->iCookie = -1;
  191836. nByte = nArg * (sizeof(char*) + sizeof(u8));
  191837. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  191838. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  191839. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  191840. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  191841. pRet->bColumnsize = 1;
  191842. pRet->eDetail = FTS5_DETAIL_FULL;
  191843. #ifdef SQLITE_DEBUG
  191844. pRet->bPrefixIndex = 1;
  191845. #endif
  191846. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  191847. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  191848. rc = SQLITE_ERROR;
  191849. }
  191850. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  191851. const char *zOrig = azArg[i];
  191852. const char *z;
  191853. char *zOne = 0;
  191854. char *zTwo = 0;
  191855. int bOption = 0;
  191856. int bMustBeCol = 0;
  191857. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  191858. z = fts5ConfigSkipWhitespace(z);
  191859. if( z && *z=='=' ){
  191860. bOption = 1;
  191861. z++;
  191862. if( bMustBeCol ) z = 0;
  191863. }
  191864. z = fts5ConfigSkipWhitespace(z);
  191865. if( z && z[0] ){
  191866. int bDummy;
  191867. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  191868. if( z && z[0] ) z = 0;
  191869. }
  191870. if( rc==SQLITE_OK ){
  191871. if( z==0 ){
  191872. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  191873. rc = SQLITE_ERROR;
  191874. }else{
  191875. if( bOption ){
  191876. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  191877. }else{
  191878. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  191879. zOne = 0;
  191880. }
  191881. }
  191882. }
  191883. sqlite3_free(zOne);
  191884. sqlite3_free(zTwo);
  191885. }
  191886. /* If a tokenizer= option was successfully parsed, the tokenizer has
  191887. ** already been allocated. Otherwise, allocate an instance of the default
  191888. ** tokenizer (unicode61) now. */
  191889. if( rc==SQLITE_OK && pRet->pTok==0 ){
  191890. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  191891. }
  191892. /* If no zContent option was specified, fill in the default values. */
  191893. if( rc==SQLITE_OK && pRet->zContent==0 ){
  191894. const char *zTail = 0;
  191895. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  191896. || pRet->eContent==FTS5_CONTENT_NONE
  191897. );
  191898. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  191899. zTail = "content";
  191900. }else if( pRet->bColumnsize ){
  191901. zTail = "docsize";
  191902. }
  191903. if( zTail ){
  191904. pRet->zContent = sqlite3Fts5Mprintf(
  191905. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  191906. );
  191907. }
  191908. }
  191909. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  191910. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  191911. }
  191912. /* Formulate the zContentExprlist text */
  191913. if( rc==SQLITE_OK ){
  191914. rc = fts5ConfigMakeExprlist(pRet);
  191915. }
  191916. if( rc!=SQLITE_OK ){
  191917. sqlite3Fts5ConfigFree(pRet);
  191918. *ppOut = 0;
  191919. }
  191920. return rc;
  191921. }
  191922. /*
  191923. ** Free the configuration object passed as the only argument.
  191924. */
  191925. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  191926. if( pConfig ){
  191927. int i;
  191928. if( pConfig->pTok ){
  191929. pConfig->pTokApi->xDelete(pConfig->pTok);
  191930. }
  191931. sqlite3_free(pConfig->zDb);
  191932. sqlite3_free(pConfig->zName);
  191933. for(i=0; i<pConfig->nCol; i++){
  191934. sqlite3_free(pConfig->azCol[i]);
  191935. }
  191936. sqlite3_free(pConfig->azCol);
  191937. sqlite3_free(pConfig->aPrefix);
  191938. sqlite3_free(pConfig->zRank);
  191939. sqlite3_free(pConfig->zRankArgs);
  191940. sqlite3_free(pConfig->zContent);
  191941. sqlite3_free(pConfig->zContentRowid);
  191942. sqlite3_free(pConfig->zContentExprlist);
  191943. sqlite3_free(pConfig);
  191944. }
  191945. }
  191946. /*
  191947. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  191948. ** object passed as the only argument. Return SQLITE_OK if successful, or
  191949. ** an SQLite error code if an error occurs.
  191950. */
  191951. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  191952. int i;
  191953. int rc = SQLITE_OK;
  191954. char *zSql;
  191955. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  191956. for(i=0; zSql && i<pConfig->nCol; i++){
  191957. const char *zSep = (i==0?"":", ");
  191958. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  191959. }
  191960. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  191961. zSql, pConfig->zName, FTS5_RANK_NAME
  191962. );
  191963. assert( zSql || rc==SQLITE_NOMEM );
  191964. if( zSql ){
  191965. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  191966. sqlite3_free(zSql);
  191967. }
  191968. return rc;
  191969. }
  191970. /*
  191971. ** Tokenize the text passed via the second and third arguments.
  191972. **
  191973. ** The callback is invoked once for each token in the input text. The
  191974. ** arguments passed to it are, in order:
  191975. **
  191976. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  191977. ** const char *pToken // Pointer to buffer containing token
  191978. ** int nToken // Size of token in bytes
  191979. ** int iStart // Byte offset of start of token within input text
  191980. ** int iEnd // Byte offset of end of token within input text
  191981. ** int iPos // Position of token in input (first token is 0)
  191982. **
  191983. ** If the callback returns a non-zero value the tokenization is abandoned
  191984. ** and no further callbacks are issued.
  191985. **
  191986. ** This function returns SQLITE_OK if successful or an SQLite error code
  191987. ** if an error occurs. If the tokenization was abandoned early because
  191988. ** the callback returned SQLITE_DONE, this is not an error and this function
  191989. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  191990. ** because the callback returned another non-zero value, it is assumed
  191991. ** to be an SQLite error code and returned to the caller.
  191992. */
  191993. static int sqlite3Fts5Tokenize(
  191994. Fts5Config *pConfig, /* FTS5 Configuration object */
  191995. int flags, /* FTS5_TOKENIZE_* flags */
  191996. const char *pText, int nText, /* Text to tokenize */
  191997. void *pCtx, /* Context passed to xToken() */
  191998. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  191999. ){
  192000. if( pText==0 ) return SQLITE_OK;
  192001. return pConfig->pTokApi->xTokenize(
  192002. pConfig->pTok, pCtx, flags, pText, nText, xToken
  192003. );
  192004. }
  192005. /*
  192006. ** Argument pIn points to the first character in what is expected to be
  192007. ** a comma-separated list of SQL literals followed by a ')' character.
  192008. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  192009. ** NULL to indicate a parse error.
  192010. */
  192011. static const char *fts5ConfigSkipArgs(const char *pIn){
  192012. const char *p = pIn;
  192013. while( 1 ){
  192014. p = fts5ConfigSkipWhitespace(p);
  192015. p = fts5ConfigSkipLiteral(p);
  192016. p = fts5ConfigSkipWhitespace(p);
  192017. if( p==0 || *p==')' ) break;
  192018. if( *p!=',' ){
  192019. p = 0;
  192020. break;
  192021. }
  192022. p++;
  192023. }
  192024. return p;
  192025. }
  192026. /*
  192027. ** Parameter zIn contains a rank() function specification. The format of
  192028. ** this is:
  192029. **
  192030. ** + Bareword (function name)
  192031. ** + Open parenthesis - "("
  192032. ** + Zero or more SQL literals in a comma separated list
  192033. ** + Close parenthesis - ")"
  192034. */
  192035. static int sqlite3Fts5ConfigParseRank(
  192036. const char *zIn, /* Input string */
  192037. char **pzRank, /* OUT: Rank function name */
  192038. char **pzRankArgs /* OUT: Rank function arguments */
  192039. ){
  192040. const char *p = zIn;
  192041. const char *pRank;
  192042. char *zRank = 0;
  192043. char *zRankArgs = 0;
  192044. int rc = SQLITE_OK;
  192045. *pzRank = 0;
  192046. *pzRankArgs = 0;
  192047. if( p==0 ){
  192048. rc = SQLITE_ERROR;
  192049. }else{
  192050. p = fts5ConfigSkipWhitespace(p);
  192051. pRank = p;
  192052. p = fts5ConfigSkipBareword(p);
  192053. if( p ){
  192054. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  192055. if( zRank ) memcpy(zRank, pRank, p-pRank);
  192056. }else{
  192057. rc = SQLITE_ERROR;
  192058. }
  192059. if( rc==SQLITE_OK ){
  192060. p = fts5ConfigSkipWhitespace(p);
  192061. if( *p!='(' ) rc = SQLITE_ERROR;
  192062. p++;
  192063. }
  192064. if( rc==SQLITE_OK ){
  192065. const char *pArgs;
  192066. p = fts5ConfigSkipWhitespace(p);
  192067. pArgs = p;
  192068. if( *p!=')' ){
  192069. p = fts5ConfigSkipArgs(p);
  192070. if( p==0 ){
  192071. rc = SQLITE_ERROR;
  192072. }else{
  192073. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  192074. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  192075. }
  192076. }
  192077. }
  192078. }
  192079. if( rc!=SQLITE_OK ){
  192080. sqlite3_free(zRank);
  192081. assert( zRankArgs==0 );
  192082. }else{
  192083. *pzRank = zRank;
  192084. *pzRankArgs = zRankArgs;
  192085. }
  192086. return rc;
  192087. }
  192088. static int sqlite3Fts5ConfigSetValue(
  192089. Fts5Config *pConfig,
  192090. const char *zKey,
  192091. sqlite3_value *pVal,
  192092. int *pbBadkey
  192093. ){
  192094. int rc = SQLITE_OK;
  192095. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  192096. int pgsz = 0;
  192097. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  192098. pgsz = sqlite3_value_int(pVal);
  192099. }
  192100. if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
  192101. *pbBadkey = 1;
  192102. }else{
  192103. pConfig->pgsz = pgsz;
  192104. }
  192105. }
  192106. else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
  192107. int nHashSize = -1;
  192108. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  192109. nHashSize = sqlite3_value_int(pVal);
  192110. }
  192111. if( nHashSize<=0 ){
  192112. *pbBadkey = 1;
  192113. }else{
  192114. pConfig->nHashSize = nHashSize;
  192115. }
  192116. }
  192117. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  192118. int nAutomerge = -1;
  192119. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  192120. nAutomerge = sqlite3_value_int(pVal);
  192121. }
  192122. if( nAutomerge<0 || nAutomerge>64 ){
  192123. *pbBadkey = 1;
  192124. }else{
  192125. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  192126. pConfig->nAutomerge = nAutomerge;
  192127. }
  192128. }
  192129. else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
  192130. int nUsermerge = -1;
  192131. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  192132. nUsermerge = sqlite3_value_int(pVal);
  192133. }
  192134. if( nUsermerge<2 || nUsermerge>16 ){
  192135. *pbBadkey = 1;
  192136. }else{
  192137. pConfig->nUsermerge = nUsermerge;
  192138. }
  192139. }
  192140. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  192141. int nCrisisMerge = -1;
  192142. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  192143. nCrisisMerge = sqlite3_value_int(pVal);
  192144. }
  192145. if( nCrisisMerge<0 ){
  192146. *pbBadkey = 1;
  192147. }else{
  192148. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  192149. pConfig->nCrisisMerge = nCrisisMerge;
  192150. }
  192151. }
  192152. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  192153. const char *zIn = (const char*)sqlite3_value_text(pVal);
  192154. char *zRank;
  192155. char *zRankArgs;
  192156. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  192157. if( rc==SQLITE_OK ){
  192158. sqlite3_free(pConfig->zRank);
  192159. sqlite3_free(pConfig->zRankArgs);
  192160. pConfig->zRank = zRank;
  192161. pConfig->zRankArgs = zRankArgs;
  192162. }else if( rc==SQLITE_ERROR ){
  192163. rc = SQLITE_OK;
  192164. *pbBadkey = 1;
  192165. }
  192166. }else{
  192167. *pbBadkey = 1;
  192168. }
  192169. return rc;
  192170. }
  192171. /*
  192172. ** Load the contents of the %_config table into memory.
  192173. */
  192174. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  192175. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  192176. char *zSql;
  192177. sqlite3_stmt *p = 0;
  192178. int rc = SQLITE_OK;
  192179. int iVersion = 0;
  192180. /* Set default values */
  192181. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  192182. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  192183. pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
  192184. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  192185. pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
  192186. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  192187. if( zSql ){
  192188. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  192189. sqlite3_free(zSql);
  192190. }
  192191. assert( rc==SQLITE_OK || p==0 );
  192192. if( rc==SQLITE_OK ){
  192193. while( SQLITE_ROW==sqlite3_step(p) ){
  192194. const char *zK = (const char*)sqlite3_column_text(p, 0);
  192195. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  192196. if( 0==sqlite3_stricmp(zK, "version") ){
  192197. iVersion = sqlite3_value_int(pVal);
  192198. }else{
  192199. int bDummy = 0;
  192200. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  192201. }
  192202. }
  192203. rc = sqlite3_finalize(p);
  192204. }
  192205. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  192206. rc = SQLITE_ERROR;
  192207. if( pConfig->pzErrmsg ){
  192208. assert( 0==*pConfig->pzErrmsg );
  192209. *pConfig->pzErrmsg = sqlite3_mprintf(
  192210. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  192211. iVersion, FTS5_CURRENT_VERSION
  192212. );
  192213. }
  192214. }
  192215. if( rc==SQLITE_OK ){
  192216. pConfig->iCookie = iCookie;
  192217. }
  192218. return rc;
  192219. }
  192220. /*
  192221. ** 2014 May 31
  192222. **
  192223. ** The author disclaims copyright to this source code. In place of
  192224. ** a legal notice, here is a blessing:
  192225. **
  192226. ** May you do good and not evil.
  192227. ** May you find forgiveness for yourself and forgive others.
  192228. ** May you share freely, never taking more than you give.
  192229. **
  192230. ******************************************************************************
  192231. **
  192232. */
  192233. /* #include "fts5Int.h" */
  192234. /* #include "fts5parse.h" */
  192235. /*
  192236. ** All token types in the generated fts5parse.h file are greater than 0.
  192237. */
  192238. #define FTS5_EOF 0
  192239. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  192240. typedef struct Fts5ExprTerm Fts5ExprTerm;
  192241. /*
  192242. ** Functions generated by lemon from fts5parse.y.
  192243. */
  192244. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  192245. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  192246. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  192247. #ifndef NDEBUG
  192248. /* #include <stdio.h> */
  192249. static void sqlite3Fts5ParserTrace(FILE*, char*);
  192250. #endif
  192251. static int sqlite3Fts5ParserFallback(int);
  192252. struct Fts5Expr {
  192253. Fts5Index *pIndex;
  192254. Fts5Config *pConfig;
  192255. Fts5ExprNode *pRoot;
  192256. int bDesc; /* Iterate in descending rowid order */
  192257. int nPhrase; /* Number of phrases in expression */
  192258. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  192259. };
  192260. /*
  192261. ** eType:
  192262. ** Expression node type. Always one of:
  192263. **
  192264. ** FTS5_AND (nChild, apChild valid)
  192265. ** FTS5_OR (nChild, apChild valid)
  192266. ** FTS5_NOT (nChild, apChild valid)
  192267. ** FTS5_STRING (pNear valid)
  192268. ** FTS5_TERM (pNear valid)
  192269. */
  192270. struct Fts5ExprNode {
  192271. int eType; /* Node type */
  192272. int bEof; /* True at EOF */
  192273. int bNomatch; /* True if entry is not a match */
  192274. /* Next method for this node. */
  192275. int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
  192276. i64 iRowid; /* Current rowid */
  192277. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  192278. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  192279. ** AND or OR nodes, it contains 2 or more entries. */
  192280. int nChild; /* Number of child nodes */
  192281. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  192282. };
  192283. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  192284. /*
  192285. ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
  192286. ** used as if it has the same signature as the xNext() methods themselves.
  192287. */
  192288. #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
  192289. /*
  192290. ** An instance of the following structure represents a single search term
  192291. ** or term prefix.
  192292. */
  192293. struct Fts5ExprTerm {
  192294. u8 bPrefix; /* True for a prefix term */
  192295. u8 bFirst; /* True if token must be first in column */
  192296. char *zTerm; /* nul-terminated term */
  192297. Fts5IndexIter *pIter; /* Iterator for this term */
  192298. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  192299. };
  192300. /*
  192301. ** A phrase. One or more terms that must appear in a contiguous sequence
  192302. ** within a document for it to match.
  192303. */
  192304. struct Fts5ExprPhrase {
  192305. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  192306. Fts5Buffer poslist; /* Current position list */
  192307. int nTerm; /* Number of entries in aTerm[] */
  192308. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  192309. };
  192310. /*
  192311. ** One or more phrases that must appear within a certain token distance of
  192312. ** each other within each matching document.
  192313. */
  192314. struct Fts5ExprNearset {
  192315. int nNear; /* NEAR parameter */
  192316. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  192317. int nPhrase; /* Number of entries in aPhrase[] array */
  192318. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  192319. };
  192320. /*
  192321. ** Parse context.
  192322. */
  192323. struct Fts5Parse {
  192324. Fts5Config *pConfig;
  192325. char *zErr;
  192326. int rc;
  192327. int nPhrase; /* Size of apPhrase array */
  192328. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  192329. Fts5ExprNode *pExpr; /* Result of a successful parse */
  192330. };
  192331. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  192332. va_list ap;
  192333. va_start(ap, zFmt);
  192334. if( pParse->rc==SQLITE_OK ){
  192335. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  192336. pParse->rc = SQLITE_ERROR;
  192337. }
  192338. va_end(ap);
  192339. }
  192340. static int fts5ExprIsspace(char t){
  192341. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  192342. }
  192343. /*
  192344. ** Read the first token from the nul-terminated string at *pz.
  192345. */
  192346. static int fts5ExprGetToken(
  192347. Fts5Parse *pParse,
  192348. const char **pz, /* IN/OUT: Pointer into buffer */
  192349. Fts5Token *pToken
  192350. ){
  192351. const char *z = *pz;
  192352. int tok;
  192353. /* Skip past any whitespace */
  192354. while( fts5ExprIsspace(*z) ) z++;
  192355. pToken->p = z;
  192356. pToken->n = 1;
  192357. switch( *z ){
  192358. case '(': tok = FTS5_LP; break;
  192359. case ')': tok = FTS5_RP; break;
  192360. case '{': tok = FTS5_LCP; break;
  192361. case '}': tok = FTS5_RCP; break;
  192362. case ':': tok = FTS5_COLON; break;
  192363. case ',': tok = FTS5_COMMA; break;
  192364. case '+': tok = FTS5_PLUS; break;
  192365. case '*': tok = FTS5_STAR; break;
  192366. case '-': tok = FTS5_MINUS; break;
  192367. case '^': tok = FTS5_CARET; break;
  192368. case '\0': tok = FTS5_EOF; break;
  192369. case '"': {
  192370. const char *z2;
  192371. tok = FTS5_STRING;
  192372. for(z2=&z[1]; 1; z2++){
  192373. if( z2[0]=='"' ){
  192374. z2++;
  192375. if( z2[0]!='"' ) break;
  192376. }
  192377. if( z2[0]=='\0' ){
  192378. sqlite3Fts5ParseError(pParse, "unterminated string");
  192379. return FTS5_EOF;
  192380. }
  192381. }
  192382. pToken->n = (z2 - z);
  192383. break;
  192384. }
  192385. default: {
  192386. const char *z2;
  192387. if( sqlite3Fts5IsBareword(z[0])==0 ){
  192388. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  192389. return FTS5_EOF;
  192390. }
  192391. tok = FTS5_STRING;
  192392. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  192393. pToken->n = (z2 - z);
  192394. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  192395. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  192396. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  192397. break;
  192398. }
  192399. }
  192400. *pz = &pToken->p[pToken->n];
  192401. return tok;
  192402. }
  192403. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc64((sqlite3_int64)t);}
  192404. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  192405. static int sqlite3Fts5ExprNew(
  192406. Fts5Config *pConfig, /* FTS5 Configuration */
  192407. int iCol,
  192408. const char *zExpr, /* Expression text */
  192409. Fts5Expr **ppNew,
  192410. char **pzErr
  192411. ){
  192412. Fts5Parse sParse;
  192413. Fts5Token token;
  192414. const char *z = zExpr;
  192415. int t; /* Next token type */
  192416. void *pEngine;
  192417. Fts5Expr *pNew;
  192418. *ppNew = 0;
  192419. *pzErr = 0;
  192420. memset(&sParse, 0, sizeof(sParse));
  192421. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  192422. if( pEngine==0 ){ return SQLITE_NOMEM; }
  192423. sParse.pConfig = pConfig;
  192424. do {
  192425. t = fts5ExprGetToken(&sParse, &z, &token);
  192426. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  192427. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  192428. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  192429. /* If the LHS of the MATCH expression was a user column, apply the
  192430. ** implicit column-filter. */
  192431. if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
  192432. int n = sizeof(Fts5Colset);
  192433. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
  192434. if( pColset ){
  192435. pColset->nCol = 1;
  192436. pColset->aiCol[0] = iCol;
  192437. sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
  192438. }
  192439. }
  192440. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  192441. if( sParse.rc==SQLITE_OK ){
  192442. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  192443. if( pNew==0 ){
  192444. sParse.rc = SQLITE_NOMEM;
  192445. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  192446. }else{
  192447. if( !sParse.pExpr ){
  192448. const int nByte = sizeof(Fts5ExprNode);
  192449. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
  192450. if( pNew->pRoot ){
  192451. pNew->pRoot->bEof = 1;
  192452. }
  192453. }else{
  192454. pNew->pRoot = sParse.pExpr;
  192455. }
  192456. pNew->pIndex = 0;
  192457. pNew->pConfig = pConfig;
  192458. pNew->apExprPhrase = sParse.apPhrase;
  192459. pNew->nPhrase = sParse.nPhrase;
  192460. sParse.apPhrase = 0;
  192461. }
  192462. }else{
  192463. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  192464. }
  192465. sqlite3_free(sParse.apPhrase);
  192466. *pzErr = sParse.zErr;
  192467. return sParse.rc;
  192468. }
  192469. /*
  192470. ** Free the expression node object passed as the only argument.
  192471. */
  192472. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  192473. if( p ){
  192474. int i;
  192475. for(i=0; i<p->nChild; i++){
  192476. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  192477. }
  192478. sqlite3Fts5ParseNearsetFree(p->pNear);
  192479. sqlite3_free(p);
  192480. }
  192481. }
  192482. /*
  192483. ** Free the expression object passed as the only argument.
  192484. */
  192485. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  192486. if( p ){
  192487. sqlite3Fts5ParseNodeFree(p->pRoot);
  192488. sqlite3_free(p->apExprPhrase);
  192489. sqlite3_free(p);
  192490. }
  192491. }
  192492. /*
  192493. ** Argument pTerm must be a synonym iterator. Return the current rowid
  192494. ** that it points to.
  192495. */
  192496. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  192497. i64 iRet = 0;
  192498. int bRetValid = 0;
  192499. Fts5ExprTerm *p;
  192500. assert( pTerm->pSynonym );
  192501. assert( bDesc==0 || bDesc==1 );
  192502. for(p=pTerm; p; p=p->pSynonym){
  192503. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  192504. i64 iRowid = p->pIter->iRowid;
  192505. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  192506. iRet = iRowid;
  192507. bRetValid = 1;
  192508. }
  192509. }
  192510. }
  192511. if( pbEof && bRetValid==0 ) *pbEof = 1;
  192512. return iRet;
  192513. }
  192514. /*
  192515. ** Argument pTerm must be a synonym iterator.
  192516. */
  192517. static int fts5ExprSynonymList(
  192518. Fts5ExprTerm *pTerm,
  192519. i64 iRowid,
  192520. Fts5Buffer *pBuf, /* Use this buffer for space if required */
  192521. u8 **pa, int *pn
  192522. ){
  192523. Fts5PoslistReader aStatic[4];
  192524. Fts5PoslistReader *aIter = aStatic;
  192525. int nIter = 0;
  192526. int nAlloc = 4;
  192527. int rc = SQLITE_OK;
  192528. Fts5ExprTerm *p;
  192529. assert( pTerm->pSynonym );
  192530. for(p=pTerm; p; p=p->pSynonym){
  192531. Fts5IndexIter *pIter = p->pIter;
  192532. if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
  192533. if( pIter->nData==0 ) continue;
  192534. if( nIter==nAlloc ){
  192535. sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  192536. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
  192537. if( aNew==0 ){
  192538. rc = SQLITE_NOMEM;
  192539. goto synonym_poslist_out;
  192540. }
  192541. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  192542. nAlloc = nAlloc*2;
  192543. if( aIter!=aStatic ) sqlite3_free(aIter);
  192544. aIter = aNew;
  192545. }
  192546. sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
  192547. assert( aIter[nIter].bEof==0 );
  192548. nIter++;
  192549. }
  192550. }
  192551. if( nIter==1 ){
  192552. *pa = (u8*)aIter[0].a;
  192553. *pn = aIter[0].n;
  192554. }else{
  192555. Fts5PoslistWriter writer = {0};
  192556. i64 iPrev = -1;
  192557. fts5BufferZero(pBuf);
  192558. while( 1 ){
  192559. int i;
  192560. i64 iMin = FTS5_LARGEST_INT64;
  192561. for(i=0; i<nIter; i++){
  192562. if( aIter[i].bEof==0 ){
  192563. if( aIter[i].iPos==iPrev ){
  192564. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  192565. }
  192566. if( aIter[i].iPos<iMin ){
  192567. iMin = aIter[i].iPos;
  192568. }
  192569. }
  192570. }
  192571. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  192572. rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
  192573. iPrev = iMin;
  192574. }
  192575. if( rc==SQLITE_OK ){
  192576. *pa = pBuf->p;
  192577. *pn = pBuf->n;
  192578. }
  192579. }
  192580. synonym_poslist_out:
  192581. if( aIter!=aStatic ) sqlite3_free(aIter);
  192582. return rc;
  192583. }
  192584. /*
  192585. ** All individual term iterators in pPhrase are guaranteed to be valid and
  192586. ** pointing to the same rowid when this function is called. This function
  192587. ** checks if the current rowid really is a match, and if so populates
  192588. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  192589. ** is set to true if this is really a match, or false otherwise.
  192590. **
  192591. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  192592. ** otherwise. It is not considered an error code if the current rowid is
  192593. ** not a match.
  192594. */
  192595. static int fts5ExprPhraseIsMatch(
  192596. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  192597. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  192598. int *pbMatch /* OUT: Set to true if really a match */
  192599. ){
  192600. Fts5PoslistWriter writer = {0};
  192601. Fts5PoslistReader aStatic[4];
  192602. Fts5PoslistReader *aIter = aStatic;
  192603. int i;
  192604. int rc = SQLITE_OK;
  192605. int bFirst = pPhrase->aTerm[0].bFirst;
  192606. fts5BufferZero(&pPhrase->poslist);
  192607. /* If the aStatic[] array is not large enough, allocate a large array
  192608. ** using sqlite3_malloc(). This approach could be improved upon. */
  192609. if( pPhrase->nTerm>ArraySize(aStatic) ){
  192610. sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  192611. aIter = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
  192612. if( !aIter ) return SQLITE_NOMEM;
  192613. }
  192614. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  192615. /* Initialize a term iterator for each term in the phrase */
  192616. for(i=0; i<pPhrase->nTerm; i++){
  192617. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  192618. int n = 0;
  192619. int bFlag = 0;
  192620. u8 *a = 0;
  192621. if( pTerm->pSynonym ){
  192622. Fts5Buffer buf = {0, 0, 0};
  192623. rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
  192624. if( rc ){
  192625. sqlite3_free(a);
  192626. goto ismatch_out;
  192627. }
  192628. if( a==buf.p ) bFlag = 1;
  192629. }else{
  192630. a = (u8*)pTerm->pIter->pData;
  192631. n = pTerm->pIter->nData;
  192632. }
  192633. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  192634. aIter[i].bFlag = (u8)bFlag;
  192635. if( aIter[i].bEof ) goto ismatch_out;
  192636. }
  192637. while( 1 ){
  192638. int bMatch;
  192639. i64 iPos = aIter[0].iPos;
  192640. do {
  192641. bMatch = 1;
  192642. for(i=0; i<pPhrase->nTerm; i++){
  192643. Fts5PoslistReader *pPos = &aIter[i];
  192644. i64 iAdj = iPos + i;
  192645. if( pPos->iPos!=iAdj ){
  192646. bMatch = 0;
  192647. while( pPos->iPos<iAdj ){
  192648. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  192649. }
  192650. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  192651. }
  192652. }
  192653. }while( bMatch==0 );
  192654. /* Append position iPos to the output */
  192655. if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){
  192656. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  192657. if( rc!=SQLITE_OK ) goto ismatch_out;
  192658. }
  192659. for(i=0; i<pPhrase->nTerm; i++){
  192660. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  192661. }
  192662. }
  192663. ismatch_out:
  192664. *pbMatch = (pPhrase->poslist.n>0);
  192665. for(i=0; i<pPhrase->nTerm; i++){
  192666. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  192667. }
  192668. if( aIter!=aStatic ) sqlite3_free(aIter);
  192669. return rc;
  192670. }
  192671. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  192672. struct Fts5LookaheadReader {
  192673. const u8 *a; /* Buffer containing position list */
  192674. int n; /* Size of buffer a[] in bytes */
  192675. int i; /* Current offset in position list */
  192676. i64 iPos; /* Current position */
  192677. i64 iLookahead; /* Next position */
  192678. };
  192679. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  192680. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  192681. p->iPos = p->iLookahead;
  192682. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  192683. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  192684. }
  192685. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  192686. }
  192687. static int fts5LookaheadReaderInit(
  192688. const u8 *a, int n, /* Buffer to read position list from */
  192689. Fts5LookaheadReader *p /* Iterator object to initialize */
  192690. ){
  192691. memset(p, 0, sizeof(Fts5LookaheadReader));
  192692. p->a = a;
  192693. p->n = n;
  192694. fts5LookaheadReaderNext(p);
  192695. return fts5LookaheadReaderNext(p);
  192696. }
  192697. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  192698. struct Fts5NearTrimmer {
  192699. Fts5LookaheadReader reader; /* Input iterator */
  192700. Fts5PoslistWriter writer; /* Writer context */
  192701. Fts5Buffer *pOut; /* Output poslist */
  192702. };
  192703. /*
  192704. ** The near-set object passed as the first argument contains more than
  192705. ** one phrase. All phrases currently point to the same row. The
  192706. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  192707. ** tests if the current row contains instances of each phrase sufficiently
  192708. ** close together to meet the NEAR constraint. Non-zero is returned if it
  192709. ** does, or zero otherwise.
  192710. **
  192711. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  192712. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  192713. ** occurs within this function (*pRc) is set accordingly before returning.
  192714. ** The return value is undefined in both these cases.
  192715. **
  192716. ** If no error occurs and non-zero (a match) is returned, the position-list
  192717. ** of each phrase object is edited to contain only those entries that
  192718. ** meet the constraint before returning.
  192719. */
  192720. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  192721. Fts5NearTrimmer aStatic[4];
  192722. Fts5NearTrimmer *a = aStatic;
  192723. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  192724. int i;
  192725. int rc = *pRc;
  192726. int bMatch;
  192727. assert( pNear->nPhrase>1 );
  192728. /* If the aStatic[] array is not large enough, allocate a large array
  192729. ** using sqlite3_malloc(). This approach could be improved upon. */
  192730. if( pNear->nPhrase>ArraySize(aStatic) ){
  192731. sqlite3_int64 nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  192732. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  192733. }else{
  192734. memset(aStatic, 0, sizeof(aStatic));
  192735. }
  192736. if( rc!=SQLITE_OK ){
  192737. *pRc = rc;
  192738. return 0;
  192739. }
  192740. /* Initialize a lookahead iterator for each phrase. After passing the
  192741. ** buffer and buffer size to the lookaside-reader init function, zero
  192742. ** the phrase poslist buffer. The new poslist for the phrase (containing
  192743. ** the same entries as the original with some entries removed on account
  192744. ** of the NEAR constraint) is written over the original even as it is
  192745. ** being read. This is safe as the entries for the new poslist are a
  192746. ** subset of the old, so it is not possible for data yet to be read to
  192747. ** be overwritten. */
  192748. for(i=0; i<pNear->nPhrase; i++){
  192749. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  192750. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  192751. pPoslist->n = 0;
  192752. a[i].pOut = pPoslist;
  192753. }
  192754. while( 1 ){
  192755. int iAdv;
  192756. i64 iMin;
  192757. i64 iMax;
  192758. /* This block advances the phrase iterators until they point to a set of
  192759. ** entries that together comprise a match. */
  192760. iMax = a[0].reader.iPos;
  192761. do {
  192762. bMatch = 1;
  192763. for(i=0; i<pNear->nPhrase; i++){
  192764. Fts5LookaheadReader *pPos = &a[i].reader;
  192765. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  192766. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  192767. bMatch = 0;
  192768. while( pPos->iPos<iMin ){
  192769. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  192770. }
  192771. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  192772. }
  192773. }
  192774. }while( bMatch==0 );
  192775. /* Add an entry to each output position list */
  192776. for(i=0; i<pNear->nPhrase; i++){
  192777. i64 iPos = a[i].reader.iPos;
  192778. Fts5PoslistWriter *pWriter = &a[i].writer;
  192779. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  192780. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  192781. }
  192782. }
  192783. iAdv = 0;
  192784. iMin = a[0].reader.iLookahead;
  192785. for(i=0; i<pNear->nPhrase; i++){
  192786. if( a[i].reader.iLookahead < iMin ){
  192787. iMin = a[i].reader.iLookahead;
  192788. iAdv = i;
  192789. }
  192790. }
  192791. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  192792. }
  192793. ismatch_out: {
  192794. int bRet = a[0].pOut->n>0;
  192795. *pRc = rc;
  192796. if( a!=aStatic ) sqlite3_free(a);
  192797. return bRet;
  192798. }
  192799. }
  192800. /*
  192801. ** Advance iterator pIter until it points to a value equal to or laster
  192802. ** than the initial value of *piLast. If this means the iterator points
  192803. ** to a value laster than *piLast, update *piLast to the new lastest value.
  192804. **
  192805. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  192806. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  192807. ** are set, return a non-zero value. Otherwise, return zero.
  192808. */
  192809. static int fts5ExprAdvanceto(
  192810. Fts5IndexIter *pIter, /* Iterator to advance */
  192811. int bDesc, /* True if iterator is "rowid DESC" */
  192812. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  192813. int *pRc, /* OUT: Error code */
  192814. int *pbEof /* OUT: Set to true if EOF */
  192815. ){
  192816. i64 iLast = *piLast;
  192817. i64 iRowid;
  192818. iRowid = pIter->iRowid;
  192819. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  192820. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  192821. if( rc || sqlite3Fts5IterEof(pIter) ){
  192822. *pRc = rc;
  192823. *pbEof = 1;
  192824. return 1;
  192825. }
  192826. iRowid = pIter->iRowid;
  192827. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  192828. }
  192829. *piLast = iRowid;
  192830. return 0;
  192831. }
  192832. static int fts5ExprSynonymAdvanceto(
  192833. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  192834. int bDesc, /* True if iterator is "rowid DESC" */
  192835. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  192836. int *pRc /* OUT: Error code */
  192837. ){
  192838. int rc = SQLITE_OK;
  192839. i64 iLast = *piLast;
  192840. Fts5ExprTerm *p;
  192841. int bEof = 0;
  192842. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  192843. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  192844. i64 iRowid = p->pIter->iRowid;
  192845. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  192846. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  192847. }
  192848. }
  192849. }
  192850. if( rc!=SQLITE_OK ){
  192851. *pRc = rc;
  192852. bEof = 1;
  192853. }else{
  192854. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  192855. }
  192856. return bEof;
  192857. }
  192858. static int fts5ExprNearTest(
  192859. int *pRc,
  192860. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  192861. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  192862. ){
  192863. Fts5ExprNearset *pNear = pNode->pNear;
  192864. int rc = *pRc;
  192865. if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  192866. Fts5ExprTerm *pTerm;
  192867. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  192868. pPhrase->poslist.n = 0;
  192869. for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  192870. Fts5IndexIter *pIter = pTerm->pIter;
  192871. if( sqlite3Fts5IterEof(pIter)==0 ){
  192872. if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
  192873. pPhrase->poslist.n = 1;
  192874. }
  192875. }
  192876. }
  192877. return pPhrase->poslist.n;
  192878. }else{
  192879. int i;
  192880. /* Check that each phrase in the nearset matches the current row.
  192881. ** Populate the pPhrase->poslist buffers at the same time. If any
  192882. ** phrase is not a match, break out of the loop early. */
  192883. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  192884. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  192885. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym
  192886. || pNear->pColset || pPhrase->aTerm[0].bFirst
  192887. ){
  192888. int bMatch = 0;
  192889. rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
  192890. if( bMatch==0 ) break;
  192891. }else{
  192892. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  192893. fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
  192894. }
  192895. }
  192896. *pRc = rc;
  192897. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  192898. return 1;
  192899. }
  192900. return 0;
  192901. }
  192902. }
  192903. /*
  192904. ** Initialize all term iterators in the pNear object. If any term is found
  192905. ** to match no documents at all, return immediately without initializing any
  192906. ** further iterators.
  192907. **
  192908. ** If an error occurs, return an SQLite error code. Otherwise, return
  192909. ** SQLITE_OK. It is not considered an error if some term matches zero
  192910. ** documents.
  192911. */
  192912. static int fts5ExprNearInitAll(
  192913. Fts5Expr *pExpr,
  192914. Fts5ExprNode *pNode
  192915. ){
  192916. Fts5ExprNearset *pNear = pNode->pNear;
  192917. int i;
  192918. assert( pNode->bNomatch==0 );
  192919. for(i=0; i<pNear->nPhrase; i++){
  192920. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  192921. if( pPhrase->nTerm==0 ){
  192922. pNode->bEof = 1;
  192923. return SQLITE_OK;
  192924. }else{
  192925. int j;
  192926. for(j=0; j<pPhrase->nTerm; j++){
  192927. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  192928. Fts5ExprTerm *p;
  192929. int bHit = 0;
  192930. for(p=pTerm; p; p=p->pSynonym){
  192931. int rc;
  192932. if( p->pIter ){
  192933. sqlite3Fts5IterClose(p->pIter);
  192934. p->pIter = 0;
  192935. }
  192936. rc = sqlite3Fts5IndexQuery(
  192937. pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
  192938. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  192939. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  192940. pNear->pColset,
  192941. &p->pIter
  192942. );
  192943. assert( (rc==SQLITE_OK)==(p->pIter!=0) );
  192944. if( rc!=SQLITE_OK ) return rc;
  192945. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  192946. bHit = 1;
  192947. }
  192948. }
  192949. if( bHit==0 ){
  192950. pNode->bEof = 1;
  192951. return SQLITE_OK;
  192952. }
  192953. }
  192954. }
  192955. }
  192956. pNode->bEof = 0;
  192957. return SQLITE_OK;
  192958. }
  192959. /*
  192960. ** If pExpr is an ASC iterator, this function returns a value with the
  192961. ** same sign as:
  192962. **
  192963. ** (iLhs - iRhs)
  192964. **
  192965. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  192966. **
  192967. ** (iRhs - iLhs)
  192968. */
  192969. static int fts5RowidCmp(
  192970. Fts5Expr *pExpr,
  192971. i64 iLhs,
  192972. i64 iRhs
  192973. ){
  192974. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  192975. if( pExpr->bDesc==0 ){
  192976. if( iLhs<iRhs ) return -1;
  192977. return (iLhs > iRhs);
  192978. }else{
  192979. if( iLhs>iRhs ) return -1;
  192980. return (iLhs < iRhs);
  192981. }
  192982. }
  192983. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  192984. int i;
  192985. pNode->bEof = 1;
  192986. pNode->bNomatch = 0;
  192987. for(i=0; i<pNode->nChild; i++){
  192988. fts5ExprSetEof(pNode->apChild[i]);
  192989. }
  192990. }
  192991. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  192992. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  192993. Fts5ExprNearset *pNear = pNode->pNear;
  192994. int i;
  192995. for(i=0; i<pNear->nPhrase; i++){
  192996. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  192997. pPhrase->poslist.n = 0;
  192998. }
  192999. }else{
  193000. int i;
  193001. for(i=0; i<pNode->nChild; i++){
  193002. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  193003. }
  193004. }
  193005. }
  193006. /*
  193007. ** Compare the values currently indicated by the two nodes as follows:
  193008. **
  193009. ** res = (*p1) - (*p2)
  193010. **
  193011. ** Nodes that point to values that come later in the iteration order are
  193012. ** considered to be larger. Nodes at EOF are the largest of all.
  193013. **
  193014. ** This means that if the iteration order is ASC, then numerically larger
  193015. ** rowids are considered larger. Or if it is the default DESC, numerically
  193016. ** smaller rowids are larger.
  193017. */
  193018. static int fts5NodeCompare(
  193019. Fts5Expr *pExpr,
  193020. Fts5ExprNode *p1,
  193021. Fts5ExprNode *p2
  193022. ){
  193023. if( p2->bEof ) return -1;
  193024. if( p1->bEof ) return +1;
  193025. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  193026. }
  193027. /*
  193028. ** All individual term iterators in pNear are guaranteed to be valid when
  193029. ** this function is called. This function checks if all term iterators
  193030. ** point to the same rowid, and if not, advances them until they do.
  193031. ** If an EOF is reached before this happens, *pbEof is set to true before
  193032. ** returning.
  193033. **
  193034. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  193035. ** otherwise. It is not considered an error code if an iterator reaches
  193036. ** EOF.
  193037. */
  193038. static int fts5ExprNodeTest_STRING(
  193039. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  193040. Fts5ExprNode *pNode
  193041. ){
  193042. Fts5ExprNearset *pNear = pNode->pNear;
  193043. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  193044. int rc = SQLITE_OK;
  193045. i64 iLast; /* Lastest rowid any iterator points to */
  193046. int i, j; /* Phrase and token index, respectively */
  193047. int bMatch; /* True if all terms are at the same rowid */
  193048. const int bDesc = pExpr->bDesc;
  193049. /* Check that this node should not be FTS5_TERM */
  193050. assert( pNear->nPhrase>1
  193051. || pNear->apPhrase[0]->nTerm>1
  193052. || pNear->apPhrase[0]->aTerm[0].pSynonym
  193053. || pNear->apPhrase[0]->aTerm[0].bFirst
  193054. );
  193055. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  193056. ** iterator skips through rowids in the default ascending order, this means
  193057. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  193058. ** means the minimum rowid. */
  193059. if( pLeft->aTerm[0].pSynonym ){
  193060. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  193061. }else{
  193062. iLast = pLeft->aTerm[0].pIter->iRowid;
  193063. }
  193064. do {
  193065. bMatch = 1;
  193066. for(i=0; i<pNear->nPhrase; i++){
  193067. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  193068. for(j=0; j<pPhrase->nTerm; j++){
  193069. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  193070. if( pTerm->pSynonym ){
  193071. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  193072. if( iRowid==iLast ) continue;
  193073. bMatch = 0;
  193074. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  193075. pNode->bNomatch = 0;
  193076. pNode->bEof = 1;
  193077. return rc;
  193078. }
  193079. }else{
  193080. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  193081. if( pIter->iRowid==iLast || pIter->bEof ) continue;
  193082. bMatch = 0;
  193083. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  193084. return rc;
  193085. }
  193086. }
  193087. }
  193088. }
  193089. }while( bMatch==0 );
  193090. pNode->iRowid = iLast;
  193091. pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
  193092. assert( pNode->bEof==0 || pNode->bNomatch==0 );
  193093. return rc;
  193094. }
  193095. /*
  193096. ** Advance the first term iterator in the first phrase of pNear. Set output
  193097. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  193098. **
  193099. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  193100. ** occurs.
  193101. */
  193102. static int fts5ExprNodeNext_STRING(
  193103. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  193104. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  193105. int bFromValid,
  193106. i64 iFrom
  193107. ){
  193108. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  193109. int rc = SQLITE_OK;
  193110. pNode->bNomatch = 0;
  193111. if( pTerm->pSynonym ){
  193112. int bEof = 1;
  193113. Fts5ExprTerm *p;
  193114. /* Find the firstest rowid any synonym points to. */
  193115. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  193116. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  193117. ** is valid - each iterator that points to a rowid before iFrom. */
  193118. for(p=pTerm; p; p=p->pSynonym){
  193119. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  193120. i64 ii = p->pIter->iRowid;
  193121. if( ii==iRowid
  193122. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  193123. ){
  193124. if( bFromValid ){
  193125. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  193126. }else{
  193127. rc = sqlite3Fts5IterNext(p->pIter);
  193128. }
  193129. if( rc!=SQLITE_OK ) break;
  193130. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  193131. bEof = 0;
  193132. }
  193133. }else{
  193134. bEof = 0;
  193135. }
  193136. }
  193137. }
  193138. /* Set the EOF flag if either all synonym iterators are at EOF or an
  193139. ** error has occurred. */
  193140. pNode->bEof = (rc || bEof);
  193141. }else{
  193142. Fts5IndexIter *pIter = pTerm->pIter;
  193143. assert( Fts5NodeIsString(pNode) );
  193144. if( bFromValid ){
  193145. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  193146. }else{
  193147. rc = sqlite3Fts5IterNext(pIter);
  193148. }
  193149. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  193150. }
  193151. if( pNode->bEof==0 ){
  193152. assert( rc==SQLITE_OK );
  193153. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  193154. }
  193155. return rc;
  193156. }
  193157. static int fts5ExprNodeTest_TERM(
  193158. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  193159. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  193160. ){
  193161. /* As this "NEAR" object is actually a single phrase that consists
  193162. ** of a single term only, grab pointers into the poslist managed by the
  193163. ** fts5_index.c iterator object. This is much faster than synthesizing
  193164. ** a new poslist the way we have to for more complicated phrase or NEAR
  193165. ** expressions. */
  193166. Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
  193167. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  193168. assert( pNode->eType==FTS5_TERM );
  193169. assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
  193170. assert( pPhrase->aTerm[0].pSynonym==0 );
  193171. pPhrase->poslist.n = pIter->nData;
  193172. if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
  193173. pPhrase->poslist.p = (u8*)pIter->pData;
  193174. }
  193175. pNode->iRowid = pIter->iRowid;
  193176. pNode->bNomatch = (pPhrase->poslist.n==0);
  193177. return SQLITE_OK;
  193178. }
  193179. /*
  193180. ** xNext() method for a node of type FTS5_TERM.
  193181. */
  193182. static int fts5ExprNodeNext_TERM(
  193183. Fts5Expr *pExpr,
  193184. Fts5ExprNode *pNode,
  193185. int bFromValid,
  193186. i64 iFrom
  193187. ){
  193188. int rc;
  193189. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  193190. assert( pNode->bEof==0 );
  193191. if( bFromValid ){
  193192. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  193193. }else{
  193194. rc = sqlite3Fts5IterNext(pIter);
  193195. }
  193196. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  193197. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  193198. }else{
  193199. pNode->bEof = 1;
  193200. pNode->bNomatch = 0;
  193201. }
  193202. return rc;
  193203. }
  193204. static void fts5ExprNodeTest_OR(
  193205. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  193206. Fts5ExprNode *pNode /* Expression node to test */
  193207. ){
  193208. Fts5ExprNode *pNext = pNode->apChild[0];
  193209. int i;
  193210. for(i=1; i<pNode->nChild; i++){
  193211. Fts5ExprNode *pChild = pNode->apChild[i];
  193212. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  193213. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  193214. pNext = pChild;
  193215. }
  193216. }
  193217. pNode->iRowid = pNext->iRowid;
  193218. pNode->bEof = pNext->bEof;
  193219. pNode->bNomatch = pNext->bNomatch;
  193220. }
  193221. static int fts5ExprNodeNext_OR(
  193222. Fts5Expr *pExpr,
  193223. Fts5ExprNode *pNode,
  193224. int bFromValid,
  193225. i64 iFrom
  193226. ){
  193227. int i;
  193228. i64 iLast = pNode->iRowid;
  193229. for(i=0; i<pNode->nChild; i++){
  193230. Fts5ExprNode *p1 = pNode->apChild[i];
  193231. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  193232. if( p1->bEof==0 ){
  193233. if( (p1->iRowid==iLast)
  193234. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  193235. ){
  193236. int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  193237. if( rc!=SQLITE_OK ){
  193238. pNode->bNomatch = 0;
  193239. return rc;
  193240. }
  193241. }
  193242. }
  193243. }
  193244. fts5ExprNodeTest_OR(pExpr, pNode);
  193245. return SQLITE_OK;
  193246. }
  193247. /*
  193248. ** Argument pNode is an FTS5_AND node.
  193249. */
  193250. static int fts5ExprNodeTest_AND(
  193251. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  193252. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  193253. ){
  193254. int iChild;
  193255. i64 iLast = pAnd->iRowid;
  193256. int rc = SQLITE_OK;
  193257. int bMatch;
  193258. assert( pAnd->bEof==0 );
  193259. do {
  193260. pAnd->bNomatch = 0;
  193261. bMatch = 1;
  193262. for(iChild=0; iChild<pAnd->nChild; iChild++){
  193263. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  193264. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  193265. if( cmp>0 ){
  193266. /* Advance pChild until it points to iLast or laster */
  193267. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  193268. if( rc!=SQLITE_OK ){
  193269. pAnd->bNomatch = 0;
  193270. return rc;
  193271. }
  193272. }
  193273. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  193274. ** the child node is guaranteed to have advanced at least as far as
  193275. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  193276. ** new lastest rowid seen so far. */
  193277. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  193278. if( pChild->bEof ){
  193279. fts5ExprSetEof(pAnd);
  193280. bMatch = 1;
  193281. break;
  193282. }else if( iLast!=pChild->iRowid ){
  193283. bMatch = 0;
  193284. iLast = pChild->iRowid;
  193285. }
  193286. if( pChild->bNomatch ){
  193287. pAnd->bNomatch = 1;
  193288. }
  193289. }
  193290. }while( bMatch==0 );
  193291. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  193292. fts5ExprNodeZeroPoslist(pAnd);
  193293. }
  193294. pAnd->iRowid = iLast;
  193295. return SQLITE_OK;
  193296. }
  193297. static int fts5ExprNodeNext_AND(
  193298. Fts5Expr *pExpr,
  193299. Fts5ExprNode *pNode,
  193300. int bFromValid,
  193301. i64 iFrom
  193302. ){
  193303. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  193304. if( rc==SQLITE_OK ){
  193305. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  193306. }else{
  193307. pNode->bNomatch = 0;
  193308. }
  193309. return rc;
  193310. }
  193311. static int fts5ExprNodeTest_NOT(
  193312. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  193313. Fts5ExprNode *pNode /* FTS5_NOT node to advance */
  193314. ){
  193315. int rc = SQLITE_OK;
  193316. Fts5ExprNode *p1 = pNode->apChild[0];
  193317. Fts5ExprNode *p2 = pNode->apChild[1];
  193318. assert( pNode->nChild==2 );
  193319. while( rc==SQLITE_OK && p1->bEof==0 ){
  193320. int cmp = fts5NodeCompare(pExpr, p1, p2);
  193321. if( cmp>0 ){
  193322. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  193323. cmp = fts5NodeCompare(pExpr, p1, p2);
  193324. }
  193325. assert( rc!=SQLITE_OK || cmp<=0 );
  193326. if( cmp || p2->bNomatch ) break;
  193327. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  193328. }
  193329. pNode->bEof = p1->bEof;
  193330. pNode->bNomatch = p1->bNomatch;
  193331. pNode->iRowid = p1->iRowid;
  193332. if( p1->bEof ){
  193333. fts5ExprNodeZeroPoslist(p2);
  193334. }
  193335. return rc;
  193336. }
  193337. static int fts5ExprNodeNext_NOT(
  193338. Fts5Expr *pExpr,
  193339. Fts5ExprNode *pNode,
  193340. int bFromValid,
  193341. i64 iFrom
  193342. ){
  193343. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  193344. if( rc==SQLITE_OK ){
  193345. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  193346. }
  193347. if( rc!=SQLITE_OK ){
  193348. pNode->bNomatch = 0;
  193349. }
  193350. return rc;
  193351. }
  193352. /*
  193353. ** If pNode currently points to a match, this function returns SQLITE_OK
  193354. ** without modifying it. Otherwise, pNode is advanced until it does point
  193355. ** to a match or EOF is reached.
  193356. */
  193357. static int fts5ExprNodeTest(
  193358. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  193359. Fts5ExprNode *pNode /* Expression node to test */
  193360. ){
  193361. int rc = SQLITE_OK;
  193362. if( pNode->bEof==0 ){
  193363. switch( pNode->eType ){
  193364. case FTS5_STRING: {
  193365. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  193366. break;
  193367. }
  193368. case FTS5_TERM: {
  193369. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  193370. break;
  193371. }
  193372. case FTS5_AND: {
  193373. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  193374. break;
  193375. }
  193376. case FTS5_OR: {
  193377. fts5ExprNodeTest_OR(pExpr, pNode);
  193378. break;
  193379. }
  193380. default: assert( pNode->eType==FTS5_NOT ); {
  193381. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  193382. break;
  193383. }
  193384. }
  193385. }
  193386. return rc;
  193387. }
  193388. /*
  193389. ** Set node pNode, which is part of expression pExpr, to point to the first
  193390. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  193391. **
  193392. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  193393. ** It is not an error if there are no matches.
  193394. */
  193395. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  193396. int rc = SQLITE_OK;
  193397. pNode->bEof = 0;
  193398. pNode->bNomatch = 0;
  193399. if( Fts5NodeIsString(pNode) ){
  193400. /* Initialize all term iterators in the NEAR object. */
  193401. rc = fts5ExprNearInitAll(pExpr, pNode);
  193402. }else if( pNode->xNext==0 ){
  193403. pNode->bEof = 1;
  193404. }else{
  193405. int i;
  193406. int nEof = 0;
  193407. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  193408. Fts5ExprNode *pChild = pNode->apChild[i];
  193409. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  193410. assert( pChild->bEof==0 || pChild->bEof==1 );
  193411. nEof += pChild->bEof;
  193412. }
  193413. pNode->iRowid = pNode->apChild[0]->iRowid;
  193414. switch( pNode->eType ){
  193415. case FTS5_AND:
  193416. if( nEof>0 ) fts5ExprSetEof(pNode);
  193417. break;
  193418. case FTS5_OR:
  193419. if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
  193420. break;
  193421. default:
  193422. assert( pNode->eType==FTS5_NOT );
  193423. pNode->bEof = pNode->apChild[0]->bEof;
  193424. break;
  193425. }
  193426. }
  193427. if( rc==SQLITE_OK ){
  193428. rc = fts5ExprNodeTest(pExpr, pNode);
  193429. }
  193430. return rc;
  193431. }
  193432. /*
  193433. ** Begin iterating through the set of documents in index pIdx matched by
  193434. ** the MATCH expression passed as the first argument. If the "bDesc"
  193435. ** parameter is passed a non-zero value, iteration is in descending rowid
  193436. ** order. Or, if it is zero, in ascending order.
  193437. **
  193438. ** If iterating in ascending rowid order (bDesc==0), the first document
  193439. ** visited is that with the smallest rowid that is larger than or equal
  193440. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  193441. ** then the first document visited must have a rowid smaller than or
  193442. ** equal to iFirst.
  193443. **
  193444. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  193445. ** is not considered an error if the query does not match any documents.
  193446. */
  193447. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  193448. Fts5ExprNode *pRoot = p->pRoot;
  193449. int rc; /* Return code */
  193450. p->pIndex = pIdx;
  193451. p->bDesc = bDesc;
  193452. rc = fts5ExprNodeFirst(p, pRoot);
  193453. /* If not at EOF but the current rowid occurs earlier than iFirst in
  193454. ** the iteration order, move to document iFirst or later. */
  193455. if( rc==SQLITE_OK
  193456. && 0==pRoot->bEof
  193457. && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
  193458. ){
  193459. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  193460. }
  193461. /* If the iterator is not at a real match, skip forward until it is. */
  193462. while( pRoot->bNomatch ){
  193463. assert( pRoot->bEof==0 && rc==SQLITE_OK );
  193464. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  193465. }
  193466. return rc;
  193467. }
  193468. /*
  193469. ** Move to the next document
  193470. **
  193471. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  193472. ** is not considered an error if the query does not match any documents.
  193473. */
  193474. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  193475. int rc;
  193476. Fts5ExprNode *pRoot = p->pRoot;
  193477. assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
  193478. do {
  193479. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  193480. assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
  193481. }while( pRoot->bNomatch );
  193482. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  193483. pRoot->bEof = 1;
  193484. }
  193485. return rc;
  193486. }
  193487. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  193488. return p->pRoot->bEof;
  193489. }
  193490. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  193491. return p->pRoot->iRowid;
  193492. }
  193493. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  193494. int rc = SQLITE_OK;
  193495. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  193496. return rc;
  193497. }
  193498. /*
  193499. ** Free the phrase object passed as the only argument.
  193500. */
  193501. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  193502. if( pPhrase ){
  193503. int i;
  193504. for(i=0; i<pPhrase->nTerm; i++){
  193505. Fts5ExprTerm *pSyn;
  193506. Fts5ExprTerm *pNext;
  193507. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  193508. sqlite3_free(pTerm->zTerm);
  193509. sqlite3Fts5IterClose(pTerm->pIter);
  193510. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  193511. pNext = pSyn->pSynonym;
  193512. sqlite3Fts5IterClose(pSyn->pIter);
  193513. fts5BufferFree((Fts5Buffer*)&pSyn[1]);
  193514. sqlite3_free(pSyn);
  193515. }
  193516. }
  193517. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  193518. sqlite3_free(pPhrase);
  193519. }
  193520. }
  193521. /*
  193522. ** Set the "bFirst" flag on the first token of the phrase passed as the
  193523. ** only argument.
  193524. */
  193525. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){
  193526. if( pPhrase && pPhrase->nTerm ){
  193527. pPhrase->aTerm[0].bFirst = 1;
  193528. }
  193529. }
  193530. /*
  193531. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  193532. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  193533. ** appended to it and the results returned.
  193534. **
  193535. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  193536. ** NULL returned.
  193537. */
  193538. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  193539. Fts5Parse *pParse, /* Parse context */
  193540. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  193541. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  193542. ){
  193543. const int SZALLOC = 8;
  193544. Fts5ExprNearset *pRet = 0;
  193545. if( pParse->rc==SQLITE_OK ){
  193546. if( pPhrase==0 ){
  193547. return pNear;
  193548. }
  193549. if( pNear==0 ){
  193550. sqlite3_int64 nByte;
  193551. nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  193552. pRet = sqlite3_malloc64(nByte);
  193553. if( pRet==0 ){
  193554. pParse->rc = SQLITE_NOMEM;
  193555. }else{
  193556. memset(pRet, 0, (size_t)nByte);
  193557. }
  193558. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  193559. int nNew = pNear->nPhrase + SZALLOC;
  193560. sqlite3_int64 nByte;
  193561. nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  193562. pRet = (Fts5ExprNearset*)sqlite3_realloc64(pNear, nByte);
  193563. if( pRet==0 ){
  193564. pParse->rc = SQLITE_NOMEM;
  193565. }
  193566. }else{
  193567. pRet = pNear;
  193568. }
  193569. }
  193570. if( pRet==0 ){
  193571. assert( pParse->rc!=SQLITE_OK );
  193572. sqlite3Fts5ParseNearsetFree(pNear);
  193573. sqlite3Fts5ParsePhraseFree(pPhrase);
  193574. }else{
  193575. if( pRet->nPhrase>0 ){
  193576. Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
  193577. assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
  193578. if( pPhrase->nTerm==0 ){
  193579. fts5ExprPhraseFree(pPhrase);
  193580. pRet->nPhrase--;
  193581. pParse->nPhrase--;
  193582. pPhrase = pLast;
  193583. }else if( pLast->nTerm==0 ){
  193584. fts5ExprPhraseFree(pLast);
  193585. pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
  193586. pParse->nPhrase--;
  193587. pRet->nPhrase--;
  193588. }
  193589. }
  193590. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  193591. }
  193592. return pRet;
  193593. }
  193594. typedef struct TokenCtx TokenCtx;
  193595. struct TokenCtx {
  193596. Fts5ExprPhrase *pPhrase;
  193597. int rc;
  193598. };
  193599. /*
  193600. ** Callback for tokenizing terms used by ParseTerm().
  193601. */
  193602. static int fts5ParseTokenize(
  193603. void *pContext, /* Pointer to Fts5InsertCtx object */
  193604. int tflags, /* Mask of FTS5_TOKEN_* flags */
  193605. const char *pToken, /* Buffer containing token */
  193606. int nToken, /* Size of token in bytes */
  193607. int iUnused1, /* Start offset of token */
  193608. int iUnused2 /* End offset of token */
  193609. ){
  193610. int rc = SQLITE_OK;
  193611. const int SZALLOC = 8;
  193612. TokenCtx *pCtx = (TokenCtx*)pContext;
  193613. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  193614. UNUSED_PARAM2(iUnused1, iUnused2);
  193615. /* If an error has already occurred, this is a no-op */
  193616. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  193617. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  193618. if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
  193619. Fts5ExprTerm *pSyn;
  193620. sqlite3_int64 nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
  193621. pSyn = (Fts5ExprTerm*)sqlite3_malloc64(nByte);
  193622. if( pSyn==0 ){
  193623. rc = SQLITE_NOMEM;
  193624. }else{
  193625. memset(pSyn, 0, (size_t)nByte);
  193626. pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
  193627. memcpy(pSyn->zTerm, pToken, nToken);
  193628. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  193629. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  193630. }
  193631. }else{
  193632. Fts5ExprTerm *pTerm;
  193633. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  193634. Fts5ExprPhrase *pNew;
  193635. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  193636. pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase,
  193637. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  193638. );
  193639. if( pNew==0 ){
  193640. rc = SQLITE_NOMEM;
  193641. }else{
  193642. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  193643. pCtx->pPhrase = pPhrase = pNew;
  193644. pNew->nTerm = nNew - SZALLOC;
  193645. }
  193646. }
  193647. if( rc==SQLITE_OK ){
  193648. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  193649. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  193650. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  193651. }
  193652. }
  193653. pCtx->rc = rc;
  193654. return rc;
  193655. }
  193656. /*
  193657. ** Free the phrase object passed as the only argument.
  193658. */
  193659. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  193660. fts5ExprPhraseFree(pPhrase);
  193661. }
  193662. /*
  193663. ** Free the phrase object passed as the second argument.
  193664. */
  193665. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  193666. if( pNear ){
  193667. int i;
  193668. for(i=0; i<pNear->nPhrase; i++){
  193669. fts5ExprPhraseFree(pNear->apPhrase[i]);
  193670. }
  193671. sqlite3_free(pNear->pColset);
  193672. sqlite3_free(pNear);
  193673. }
  193674. }
  193675. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  193676. assert( pParse->pExpr==0 );
  193677. pParse->pExpr = p;
  193678. }
  193679. /*
  193680. ** This function is called by the parser to process a string token. The
  193681. ** string may or may not be quoted. In any case it is tokenized and a
  193682. ** phrase object consisting of all tokens returned.
  193683. */
  193684. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  193685. Fts5Parse *pParse, /* Parse context */
  193686. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  193687. Fts5Token *pToken, /* String to tokenize */
  193688. int bPrefix /* True if there is a trailing "*" */
  193689. ){
  193690. Fts5Config *pConfig = pParse->pConfig;
  193691. TokenCtx sCtx; /* Context object passed to callback */
  193692. int rc; /* Tokenize return code */
  193693. char *z = 0;
  193694. memset(&sCtx, 0, sizeof(TokenCtx));
  193695. sCtx.pPhrase = pAppend;
  193696. rc = fts5ParseStringFromToken(pToken, &z);
  193697. if( rc==SQLITE_OK ){
  193698. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
  193699. int n;
  193700. sqlite3Fts5Dequote(z);
  193701. n = (int)strlen(z);
  193702. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  193703. }
  193704. sqlite3_free(z);
  193705. if( rc || (rc = sCtx.rc) ){
  193706. pParse->rc = rc;
  193707. fts5ExprPhraseFree(sCtx.pPhrase);
  193708. sCtx.pPhrase = 0;
  193709. }else{
  193710. if( pAppend==0 ){
  193711. if( (pParse->nPhrase % 8)==0 ){
  193712. sqlite3_int64 nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  193713. Fts5ExprPhrase **apNew;
  193714. apNew = (Fts5ExprPhrase**)sqlite3_realloc64(pParse->apPhrase, nByte);
  193715. if( apNew==0 ){
  193716. pParse->rc = SQLITE_NOMEM;
  193717. fts5ExprPhraseFree(sCtx.pPhrase);
  193718. return 0;
  193719. }
  193720. pParse->apPhrase = apNew;
  193721. }
  193722. pParse->nPhrase++;
  193723. }
  193724. if( sCtx.pPhrase==0 ){
  193725. /* This happens when parsing a token or quoted phrase that contains
  193726. ** no token characters at all. (e.g ... MATCH '""'). */
  193727. sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
  193728. }else if( sCtx.pPhrase->nTerm ){
  193729. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;
  193730. }
  193731. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  193732. }
  193733. return sCtx.pPhrase;
  193734. }
  193735. /*
  193736. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  193737. ** expression passed as the second argument.
  193738. */
  193739. static int sqlite3Fts5ExprClonePhrase(
  193740. Fts5Expr *pExpr,
  193741. int iPhrase,
  193742. Fts5Expr **ppNew
  193743. ){
  193744. int rc = SQLITE_OK; /* Return code */
  193745. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  193746. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  193747. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  193748. pOrig = pExpr->apExprPhrase[iPhrase];
  193749. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  193750. if( rc==SQLITE_OK ){
  193751. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  193752. sizeof(Fts5ExprPhrase*));
  193753. }
  193754. if( rc==SQLITE_OK ){
  193755. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  193756. sizeof(Fts5ExprNode));
  193757. }
  193758. if( rc==SQLITE_OK ){
  193759. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  193760. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  193761. }
  193762. if( rc==SQLITE_OK ){
  193763. Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
  193764. if( pColsetOrig ){
  193765. sqlite3_int64 nByte;
  193766. Fts5Colset *pColset;
  193767. nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
  193768. pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
  193769. if( pColset ){
  193770. memcpy(pColset, pColsetOrig, (size_t)nByte);
  193771. }
  193772. pNew->pRoot->pNear->pColset = pColset;
  193773. }
  193774. }
  193775. if( pOrig->nTerm ){
  193776. int i; /* Used to iterate through phrase terms */
  193777. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  193778. int tflags = 0;
  193779. Fts5ExprTerm *p;
  193780. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  193781. const char *zTerm = p->zTerm;
  193782. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
  193783. 0, 0);
  193784. tflags = FTS5_TOKEN_COLOCATED;
  193785. }
  193786. if( rc==SQLITE_OK ){
  193787. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  193788. sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;
  193789. }
  193790. }
  193791. }else{
  193792. /* This happens when parsing a token or quoted phrase that contains
  193793. ** no token characters at all. (e.g ... MATCH '""'). */
  193794. sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
  193795. }
  193796. if( rc==SQLITE_OK ){
  193797. /* All the allocations succeeded. Put the expression object together. */
  193798. pNew->pIndex = pExpr->pIndex;
  193799. pNew->pConfig = pExpr->pConfig;
  193800. pNew->nPhrase = 1;
  193801. pNew->apExprPhrase[0] = sCtx.pPhrase;
  193802. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  193803. pNew->pRoot->pNear->nPhrase = 1;
  193804. sCtx.pPhrase->pNode = pNew->pRoot;
  193805. if( pOrig->nTerm==1
  193806. && pOrig->aTerm[0].pSynonym==0
  193807. && pOrig->aTerm[0].bFirst==0
  193808. ){
  193809. pNew->pRoot->eType = FTS5_TERM;
  193810. pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
  193811. }else{
  193812. pNew->pRoot->eType = FTS5_STRING;
  193813. pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
  193814. }
  193815. }else{
  193816. sqlite3Fts5ExprFree(pNew);
  193817. fts5ExprPhraseFree(sCtx.pPhrase);
  193818. pNew = 0;
  193819. }
  193820. *ppNew = pNew;
  193821. return rc;
  193822. }
  193823. /*
  193824. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  193825. ** is expected. If token pTok does not contain "NEAR", store an error
  193826. ** in the pParse object.
  193827. */
  193828. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  193829. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  193830. sqlite3Fts5ParseError(
  193831. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  193832. );
  193833. }
  193834. }
  193835. static void sqlite3Fts5ParseSetDistance(
  193836. Fts5Parse *pParse,
  193837. Fts5ExprNearset *pNear,
  193838. Fts5Token *p
  193839. ){
  193840. if( pNear ){
  193841. int nNear = 0;
  193842. int i;
  193843. if( p->n ){
  193844. for(i=0; i<p->n; i++){
  193845. char c = (char)p->p[i];
  193846. if( c<'0' || c>'9' ){
  193847. sqlite3Fts5ParseError(
  193848. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  193849. );
  193850. return;
  193851. }
  193852. nNear = nNear * 10 + (p->p[i] - '0');
  193853. }
  193854. }else{
  193855. nNear = FTS5_DEFAULT_NEARDIST;
  193856. }
  193857. pNear->nNear = nNear;
  193858. }
  193859. }
  193860. /*
  193861. ** The second argument passed to this function may be NULL, or it may be
  193862. ** an existing Fts5Colset object. This function returns a pointer to
  193863. ** a new colset object containing the contents of (p) with new value column
  193864. ** number iCol appended.
  193865. **
  193866. ** If an OOM error occurs, store an error code in pParse and return NULL.
  193867. ** The old colset object (if any) is not freed in this case.
  193868. */
  193869. static Fts5Colset *fts5ParseColset(
  193870. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  193871. Fts5Colset *p, /* Existing colset object */
  193872. int iCol /* New column to add to colset object */
  193873. ){
  193874. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  193875. Fts5Colset *pNew; /* New colset object to return */
  193876. assert( pParse->rc==SQLITE_OK );
  193877. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  193878. pNew = sqlite3_realloc64(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  193879. if( pNew==0 ){
  193880. pParse->rc = SQLITE_NOMEM;
  193881. }else{
  193882. int *aiCol = pNew->aiCol;
  193883. int i, j;
  193884. for(i=0; i<nCol; i++){
  193885. if( aiCol[i]==iCol ) return pNew;
  193886. if( aiCol[i]>iCol ) break;
  193887. }
  193888. for(j=nCol; j>i; j--){
  193889. aiCol[j] = aiCol[j-1];
  193890. }
  193891. aiCol[i] = iCol;
  193892. pNew->nCol = nCol+1;
  193893. #ifndef NDEBUG
  193894. /* Check that the array is in order and contains no duplicate entries. */
  193895. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  193896. #endif
  193897. }
  193898. return pNew;
  193899. }
  193900. /*
  193901. ** Allocate and return an Fts5Colset object specifying the inverse of
  193902. ** the colset passed as the second argument. Free the colset passed
  193903. ** as the second argument before returning.
  193904. */
  193905. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
  193906. Fts5Colset *pRet;
  193907. int nCol = pParse->pConfig->nCol;
  193908. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
  193909. sizeof(Fts5Colset) + sizeof(int)*nCol
  193910. );
  193911. if( pRet ){
  193912. int i;
  193913. int iOld = 0;
  193914. for(i=0; i<nCol; i++){
  193915. if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
  193916. pRet->aiCol[pRet->nCol++] = i;
  193917. }else{
  193918. iOld++;
  193919. }
  193920. }
  193921. }
  193922. sqlite3_free(p);
  193923. return pRet;
  193924. }
  193925. static Fts5Colset *sqlite3Fts5ParseColset(
  193926. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  193927. Fts5Colset *pColset, /* Existing colset object */
  193928. Fts5Token *p
  193929. ){
  193930. Fts5Colset *pRet = 0;
  193931. int iCol;
  193932. char *z; /* Dequoted copy of token p */
  193933. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  193934. if( pParse->rc==SQLITE_OK ){
  193935. Fts5Config *pConfig = pParse->pConfig;
  193936. sqlite3Fts5Dequote(z);
  193937. for(iCol=0; iCol<pConfig->nCol; iCol++){
  193938. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  193939. }
  193940. if( iCol==pConfig->nCol ){
  193941. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  193942. }else{
  193943. pRet = fts5ParseColset(pParse, pColset, iCol);
  193944. }
  193945. sqlite3_free(z);
  193946. }
  193947. if( pRet==0 ){
  193948. assert( pParse->rc!=SQLITE_OK );
  193949. sqlite3_free(pColset);
  193950. }
  193951. return pRet;
  193952. }
  193953. /*
  193954. ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
  193955. ** SQLITE_OK when this function is called, NULL is returned.
  193956. **
  193957. ** Otherwise, a copy of (*pOrig) is made into memory obtained from
  193958. ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
  193959. ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
  193960. */
  193961. static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
  193962. Fts5Colset *pRet;
  193963. if( pOrig ){
  193964. sqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
  193965. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
  193966. if( pRet ){
  193967. memcpy(pRet, pOrig, (size_t)nByte);
  193968. }
  193969. }else{
  193970. pRet = 0;
  193971. }
  193972. return pRet;
  193973. }
  193974. /*
  193975. ** Remove from colset pColset any columns that are not also in colset pMerge.
  193976. */
  193977. static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
  193978. int iIn = 0; /* Next input in pColset */
  193979. int iMerge = 0; /* Next input in pMerge */
  193980. int iOut = 0; /* Next output slot in pColset */
  193981. while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
  193982. int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
  193983. if( iDiff==0 ){
  193984. pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
  193985. iMerge++;
  193986. iIn++;
  193987. }else if( iDiff>0 ){
  193988. iMerge++;
  193989. }else{
  193990. iIn++;
  193991. }
  193992. }
  193993. pColset->nCol = iOut;
  193994. }
  193995. /*
  193996. ** Recursively apply colset pColset to expression node pNode and all of
  193997. ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
  193998. ** of pColset. This function may use the spare copy and set (*ppFree) to
  193999. ** zero, or it may create copies of pColset using fts5CloneColset().
  194000. */
  194001. static void fts5ParseSetColset(
  194002. Fts5Parse *pParse,
  194003. Fts5ExprNode *pNode,
  194004. Fts5Colset *pColset,
  194005. Fts5Colset **ppFree
  194006. ){
  194007. if( pParse->rc==SQLITE_OK ){
  194008. assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
  194009. || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
  194010. || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
  194011. );
  194012. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  194013. Fts5ExprNearset *pNear = pNode->pNear;
  194014. if( pNear->pColset ){
  194015. fts5MergeColset(pNear->pColset, pColset);
  194016. if( pNear->pColset->nCol==0 ){
  194017. pNode->eType = FTS5_EOF;
  194018. pNode->xNext = 0;
  194019. }
  194020. }else if( *ppFree ){
  194021. pNear->pColset = pColset;
  194022. *ppFree = 0;
  194023. }else{
  194024. pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
  194025. }
  194026. }else{
  194027. int i;
  194028. assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
  194029. for(i=0; i<pNode->nChild; i++){
  194030. fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
  194031. }
  194032. }
  194033. }
  194034. }
  194035. /*
  194036. ** Apply colset pColset to expression node pExpr and all of its descendents.
  194037. */
  194038. static void sqlite3Fts5ParseSetColset(
  194039. Fts5Parse *pParse,
  194040. Fts5ExprNode *pExpr,
  194041. Fts5Colset *pColset
  194042. ){
  194043. Fts5Colset *pFree = pColset;
  194044. if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
  194045. pParse->rc = SQLITE_ERROR;
  194046. pParse->zErr = sqlite3_mprintf(
  194047. "fts5: column queries are not supported (detail=none)"
  194048. );
  194049. }else{
  194050. fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
  194051. }
  194052. sqlite3_free(pFree);
  194053. }
  194054. static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
  194055. switch( pNode->eType ){
  194056. case FTS5_STRING: {
  194057. Fts5ExprNearset *pNear = pNode->pNear;
  194058. if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
  194059. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  194060. && pNear->apPhrase[0]->aTerm[0].bFirst==0
  194061. ){
  194062. pNode->eType = FTS5_TERM;
  194063. pNode->xNext = fts5ExprNodeNext_TERM;
  194064. }else{
  194065. pNode->xNext = fts5ExprNodeNext_STRING;
  194066. }
  194067. break;
  194068. };
  194069. case FTS5_OR: {
  194070. pNode->xNext = fts5ExprNodeNext_OR;
  194071. break;
  194072. };
  194073. case FTS5_AND: {
  194074. pNode->xNext = fts5ExprNodeNext_AND;
  194075. break;
  194076. };
  194077. default: assert( pNode->eType==FTS5_NOT ); {
  194078. pNode->xNext = fts5ExprNodeNext_NOT;
  194079. break;
  194080. };
  194081. }
  194082. }
  194083. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  194084. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  194085. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  194086. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  194087. p->nChild += pSub->nChild;
  194088. sqlite3_free(pSub);
  194089. }else{
  194090. p->apChild[p->nChild++] = pSub;
  194091. }
  194092. }
  194093. /*
  194094. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  194095. ** OOM error), leave an error code in pParse and return NULL.
  194096. */
  194097. static Fts5ExprNode *sqlite3Fts5ParseNode(
  194098. Fts5Parse *pParse, /* Parse context */
  194099. int eType, /* FTS5_STRING, AND, OR or NOT */
  194100. Fts5ExprNode *pLeft, /* Left hand child expression */
  194101. Fts5ExprNode *pRight, /* Right hand child expression */
  194102. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  194103. ){
  194104. Fts5ExprNode *pRet = 0;
  194105. if( pParse->rc==SQLITE_OK ){
  194106. int nChild = 0; /* Number of children of returned node */
  194107. sqlite3_int64 nByte; /* Bytes of space to allocate for this node */
  194108. assert( (eType!=FTS5_STRING && !pNear)
  194109. || (eType==FTS5_STRING && !pLeft && !pRight)
  194110. );
  194111. if( eType==FTS5_STRING && pNear==0 ) return 0;
  194112. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  194113. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  194114. if( eType==FTS5_NOT ){
  194115. nChild = 2;
  194116. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  194117. nChild = 2;
  194118. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  194119. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  194120. }
  194121. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  194122. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  194123. if( pRet ){
  194124. pRet->eType = eType;
  194125. pRet->pNear = pNear;
  194126. fts5ExprAssignXNext(pRet);
  194127. if( eType==FTS5_STRING ){
  194128. int iPhrase;
  194129. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  194130. pNear->apPhrase[iPhrase]->pNode = pRet;
  194131. if( pNear->apPhrase[iPhrase]->nTerm==0 ){
  194132. pRet->xNext = 0;
  194133. pRet->eType = FTS5_EOF;
  194134. }
  194135. }
  194136. if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  194137. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  194138. if( pNear->nPhrase!=1
  194139. || pPhrase->nTerm>1
  194140. || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
  194141. ){
  194142. assert( pParse->rc==SQLITE_OK );
  194143. pParse->rc = SQLITE_ERROR;
  194144. assert( pParse->zErr==0 );
  194145. pParse->zErr = sqlite3_mprintf(
  194146. "fts5: %s queries are not supported (detail!=full)",
  194147. pNear->nPhrase==1 ? "phrase": "NEAR"
  194148. );
  194149. sqlite3_free(pRet);
  194150. pRet = 0;
  194151. }
  194152. }
  194153. }else{
  194154. fts5ExprAddChildren(pRet, pLeft);
  194155. fts5ExprAddChildren(pRet, pRight);
  194156. }
  194157. }
  194158. }
  194159. if( pRet==0 ){
  194160. assert( pParse->rc!=SQLITE_OK );
  194161. sqlite3Fts5ParseNodeFree(pLeft);
  194162. sqlite3Fts5ParseNodeFree(pRight);
  194163. sqlite3Fts5ParseNearsetFree(pNear);
  194164. }
  194165. return pRet;
  194166. }
  194167. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  194168. Fts5Parse *pParse, /* Parse context */
  194169. Fts5ExprNode *pLeft, /* Left hand child expression */
  194170. Fts5ExprNode *pRight /* Right hand child expression */
  194171. ){
  194172. Fts5ExprNode *pRet = 0;
  194173. Fts5ExprNode *pPrev;
  194174. if( pParse->rc ){
  194175. sqlite3Fts5ParseNodeFree(pLeft);
  194176. sqlite3Fts5ParseNodeFree(pRight);
  194177. }else{
  194178. assert( pLeft->eType==FTS5_STRING
  194179. || pLeft->eType==FTS5_TERM
  194180. || pLeft->eType==FTS5_EOF
  194181. || pLeft->eType==FTS5_AND
  194182. );
  194183. assert( pRight->eType==FTS5_STRING
  194184. || pRight->eType==FTS5_TERM
  194185. || pRight->eType==FTS5_EOF
  194186. );
  194187. if( pLeft->eType==FTS5_AND ){
  194188. pPrev = pLeft->apChild[pLeft->nChild-1];
  194189. }else{
  194190. pPrev = pLeft;
  194191. }
  194192. assert( pPrev->eType==FTS5_STRING
  194193. || pPrev->eType==FTS5_TERM
  194194. || pPrev->eType==FTS5_EOF
  194195. );
  194196. if( pRight->eType==FTS5_EOF ){
  194197. assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
  194198. sqlite3Fts5ParseNodeFree(pRight);
  194199. pRet = pLeft;
  194200. pParse->nPhrase--;
  194201. }
  194202. else if( pPrev->eType==FTS5_EOF ){
  194203. Fts5ExprPhrase **ap;
  194204. if( pPrev==pLeft ){
  194205. pRet = pRight;
  194206. }else{
  194207. pLeft->apChild[pLeft->nChild-1] = pRight;
  194208. pRet = pLeft;
  194209. }
  194210. ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
  194211. assert( ap[0]==pPrev->pNear->apPhrase[0] );
  194212. memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
  194213. pParse->nPhrase--;
  194214. sqlite3Fts5ParseNodeFree(pPrev);
  194215. }
  194216. else{
  194217. pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
  194218. }
  194219. }
  194220. return pRet;
  194221. }
  194222. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  194223. sqlite3_int64 nByte = 0;
  194224. Fts5ExprTerm *p;
  194225. char *zQuoted;
  194226. /* Determine the maximum amount of space required. */
  194227. for(p=pTerm; p; p=p->pSynonym){
  194228. nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
  194229. }
  194230. zQuoted = sqlite3_malloc64(nByte);
  194231. if( zQuoted ){
  194232. int i = 0;
  194233. for(p=pTerm; p; p=p->pSynonym){
  194234. char *zIn = p->zTerm;
  194235. zQuoted[i++] = '"';
  194236. while( *zIn ){
  194237. if( *zIn=='"' ) zQuoted[i++] = '"';
  194238. zQuoted[i++] = *zIn++;
  194239. }
  194240. zQuoted[i++] = '"';
  194241. if( p->pSynonym ) zQuoted[i++] = '|';
  194242. }
  194243. if( pTerm->bPrefix ){
  194244. zQuoted[i++] = ' ';
  194245. zQuoted[i++] = '*';
  194246. }
  194247. zQuoted[i++] = '\0';
  194248. }
  194249. return zQuoted;
  194250. }
  194251. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  194252. char *zNew;
  194253. va_list ap;
  194254. va_start(ap, zFmt);
  194255. zNew = sqlite3_vmprintf(zFmt, ap);
  194256. va_end(ap);
  194257. if( zApp && zNew ){
  194258. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  194259. sqlite3_free(zNew);
  194260. zNew = zNew2;
  194261. }
  194262. sqlite3_free(zApp);
  194263. return zNew;
  194264. }
  194265. /*
  194266. ** Compose a tcl-readable representation of expression pExpr. Return a
  194267. ** pointer to a buffer containing that representation. It is the
  194268. ** responsibility of the caller to at some point free the buffer using
  194269. ** sqlite3_free().
  194270. */
  194271. static char *fts5ExprPrintTcl(
  194272. Fts5Config *pConfig,
  194273. const char *zNearsetCmd,
  194274. Fts5ExprNode *pExpr
  194275. ){
  194276. char *zRet = 0;
  194277. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  194278. Fts5ExprNearset *pNear = pExpr->pNear;
  194279. int i;
  194280. int iTerm;
  194281. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  194282. if( zRet==0 ) return 0;
  194283. if( pNear->pColset ){
  194284. int *aiCol = pNear->pColset->aiCol;
  194285. int nCol = pNear->pColset->nCol;
  194286. if( nCol==1 ){
  194287. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  194288. }else{
  194289. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  194290. for(i=1; i<pNear->pColset->nCol; i++){
  194291. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  194292. }
  194293. zRet = fts5PrintfAppend(zRet, "} ");
  194294. }
  194295. if( zRet==0 ) return 0;
  194296. }
  194297. if( pNear->nPhrase>1 ){
  194298. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  194299. if( zRet==0 ) return 0;
  194300. }
  194301. zRet = fts5PrintfAppend(zRet, "--");
  194302. if( zRet==0 ) return 0;
  194303. for(i=0; i<pNear->nPhrase; i++){
  194304. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  194305. zRet = fts5PrintfAppend(zRet, " {");
  194306. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  194307. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  194308. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  194309. if( pPhrase->aTerm[iTerm].bPrefix ){
  194310. zRet = fts5PrintfAppend(zRet, "*");
  194311. }
  194312. }
  194313. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  194314. if( zRet==0 ) return 0;
  194315. }
  194316. }else{
  194317. char const *zOp = 0;
  194318. int i;
  194319. switch( pExpr->eType ){
  194320. case FTS5_AND: zOp = "AND"; break;
  194321. case FTS5_NOT: zOp = "NOT"; break;
  194322. default:
  194323. assert( pExpr->eType==FTS5_OR );
  194324. zOp = "OR";
  194325. break;
  194326. }
  194327. zRet = sqlite3_mprintf("%s", zOp);
  194328. for(i=0; zRet && i<pExpr->nChild; i++){
  194329. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  194330. if( !z ){
  194331. sqlite3_free(zRet);
  194332. zRet = 0;
  194333. }else{
  194334. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  194335. }
  194336. }
  194337. }
  194338. return zRet;
  194339. }
  194340. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  194341. char *zRet = 0;
  194342. if( pExpr->eType==0 ){
  194343. return sqlite3_mprintf("\"\"");
  194344. }else
  194345. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  194346. Fts5ExprNearset *pNear = pExpr->pNear;
  194347. int i;
  194348. int iTerm;
  194349. if( pNear->pColset ){
  194350. int iCol = pNear->pColset->aiCol[0];
  194351. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  194352. if( zRet==0 ) return 0;
  194353. }
  194354. if( pNear->nPhrase>1 ){
  194355. zRet = fts5PrintfAppend(zRet, "NEAR(");
  194356. if( zRet==0 ) return 0;
  194357. }
  194358. for(i=0; i<pNear->nPhrase; i++){
  194359. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  194360. if( i!=0 ){
  194361. zRet = fts5PrintfAppend(zRet, " ");
  194362. if( zRet==0 ) return 0;
  194363. }
  194364. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  194365. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  194366. if( zTerm ){
  194367. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  194368. sqlite3_free(zTerm);
  194369. }
  194370. if( zTerm==0 || zRet==0 ){
  194371. sqlite3_free(zRet);
  194372. return 0;
  194373. }
  194374. }
  194375. }
  194376. if( pNear->nPhrase>1 ){
  194377. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  194378. if( zRet==0 ) return 0;
  194379. }
  194380. }else{
  194381. char const *zOp = 0;
  194382. int i;
  194383. switch( pExpr->eType ){
  194384. case FTS5_AND: zOp = " AND "; break;
  194385. case FTS5_NOT: zOp = " NOT "; break;
  194386. default:
  194387. assert( pExpr->eType==FTS5_OR );
  194388. zOp = " OR ";
  194389. break;
  194390. }
  194391. for(i=0; i<pExpr->nChild; i++){
  194392. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  194393. if( z==0 ){
  194394. sqlite3_free(zRet);
  194395. zRet = 0;
  194396. }else{
  194397. int e = pExpr->apChild[i]->eType;
  194398. int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
  194399. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  194400. (i==0 ? "" : zOp),
  194401. (b?"(":""), z, (b?")":"")
  194402. );
  194403. }
  194404. if( zRet==0 ) break;
  194405. }
  194406. }
  194407. return zRet;
  194408. }
  194409. /*
  194410. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  194411. ** and fts5_expr_tcl() (bTcl!=0).
  194412. */
  194413. static void fts5ExprFunction(
  194414. sqlite3_context *pCtx, /* Function call context */
  194415. int nArg, /* Number of args */
  194416. sqlite3_value **apVal, /* Function arguments */
  194417. int bTcl
  194418. ){
  194419. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  194420. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  194421. const char *zExpr = 0;
  194422. char *zErr = 0;
  194423. Fts5Expr *pExpr = 0;
  194424. int rc;
  194425. int i;
  194426. const char **azConfig; /* Array of arguments for Fts5Config */
  194427. const char *zNearsetCmd = "nearset";
  194428. int nConfig; /* Size of azConfig[] */
  194429. Fts5Config *pConfig = 0;
  194430. int iArg = 1;
  194431. if( nArg<1 ){
  194432. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  194433. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  194434. );
  194435. sqlite3_result_error(pCtx, zErr, -1);
  194436. sqlite3_free(zErr);
  194437. return;
  194438. }
  194439. if( bTcl && nArg>1 ){
  194440. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  194441. iArg = 2;
  194442. }
  194443. nConfig = 3 + (nArg-iArg);
  194444. azConfig = (const char**)sqlite3_malloc64(sizeof(char*) * nConfig);
  194445. if( azConfig==0 ){
  194446. sqlite3_result_error_nomem(pCtx);
  194447. return;
  194448. }
  194449. azConfig[0] = 0;
  194450. azConfig[1] = "main";
  194451. azConfig[2] = "tbl";
  194452. for(i=3; iArg<nArg; iArg++){
  194453. azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
  194454. }
  194455. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  194456. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  194457. if( rc==SQLITE_OK ){
  194458. rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
  194459. }
  194460. if( rc==SQLITE_OK ){
  194461. char *zText;
  194462. if( pExpr->pRoot->xNext==0 ){
  194463. zText = sqlite3_mprintf("");
  194464. }else if( bTcl ){
  194465. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  194466. }else{
  194467. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  194468. }
  194469. if( zText==0 ){
  194470. rc = SQLITE_NOMEM;
  194471. }else{
  194472. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  194473. sqlite3_free(zText);
  194474. }
  194475. }
  194476. if( rc!=SQLITE_OK ){
  194477. if( zErr ){
  194478. sqlite3_result_error(pCtx, zErr, -1);
  194479. sqlite3_free(zErr);
  194480. }else{
  194481. sqlite3_result_error_code(pCtx, rc);
  194482. }
  194483. }
  194484. sqlite3_free((void *)azConfig);
  194485. sqlite3Fts5ConfigFree(pConfig);
  194486. sqlite3Fts5ExprFree(pExpr);
  194487. }
  194488. static void fts5ExprFunctionHr(
  194489. sqlite3_context *pCtx, /* Function call context */
  194490. int nArg, /* Number of args */
  194491. sqlite3_value **apVal /* Function arguments */
  194492. ){
  194493. fts5ExprFunction(pCtx, nArg, apVal, 0);
  194494. }
  194495. static void fts5ExprFunctionTcl(
  194496. sqlite3_context *pCtx, /* Function call context */
  194497. int nArg, /* Number of args */
  194498. sqlite3_value **apVal /* Function arguments */
  194499. ){
  194500. fts5ExprFunction(pCtx, nArg, apVal, 1);
  194501. }
  194502. /*
  194503. ** The implementation of an SQLite user-defined-function that accepts a
  194504. ** single integer as an argument. If the integer is an alpha-numeric
  194505. ** unicode code point, 1 is returned. Otherwise 0.
  194506. */
  194507. static void fts5ExprIsAlnum(
  194508. sqlite3_context *pCtx, /* Function call context */
  194509. int nArg, /* Number of args */
  194510. sqlite3_value **apVal /* Function arguments */
  194511. ){
  194512. int iCode;
  194513. u8 aArr[32];
  194514. if( nArg!=1 ){
  194515. sqlite3_result_error(pCtx,
  194516. "wrong number of arguments to function fts5_isalnum", -1
  194517. );
  194518. return;
  194519. }
  194520. memset(aArr, 0, sizeof(aArr));
  194521. sqlite3Fts5UnicodeCatParse("L*", aArr);
  194522. sqlite3Fts5UnicodeCatParse("N*", aArr);
  194523. sqlite3Fts5UnicodeCatParse("Co", aArr);
  194524. iCode = sqlite3_value_int(apVal[0]);
  194525. sqlite3_result_int(pCtx, aArr[sqlite3Fts5UnicodeCategory((u32)iCode)]);
  194526. }
  194527. static void fts5ExprFold(
  194528. sqlite3_context *pCtx, /* Function call context */
  194529. int nArg, /* Number of args */
  194530. sqlite3_value **apVal /* Function arguments */
  194531. ){
  194532. if( nArg!=1 && nArg!=2 ){
  194533. sqlite3_result_error(pCtx,
  194534. "wrong number of arguments to function fts5_fold", -1
  194535. );
  194536. }else{
  194537. int iCode;
  194538. int bRemoveDiacritics = 0;
  194539. iCode = sqlite3_value_int(apVal[0]);
  194540. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  194541. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  194542. }
  194543. }
  194544. /*
  194545. ** This is called during initialization to register the fts5_expr() scalar
  194546. ** UDF with the SQLite handle passed as the only argument.
  194547. */
  194548. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  194549. struct Fts5ExprFunc {
  194550. const char *z;
  194551. void (*x)(sqlite3_context*,int,sqlite3_value**);
  194552. } aFunc[] = {
  194553. { "fts5_expr", fts5ExprFunctionHr },
  194554. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  194555. { "fts5_isalnum", fts5ExprIsAlnum },
  194556. { "fts5_fold", fts5ExprFold },
  194557. };
  194558. int i;
  194559. int rc = SQLITE_OK;
  194560. void *pCtx = (void*)pGlobal;
  194561. for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
  194562. struct Fts5ExprFunc *p = &aFunc[i];
  194563. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  194564. }
  194565. /* Avoid warnings indicating that sqlite3Fts5ParserTrace() and
  194566. ** sqlite3Fts5ParserFallback() are unused */
  194567. #ifndef NDEBUG
  194568. (void)sqlite3Fts5ParserTrace;
  194569. #endif
  194570. (void)sqlite3Fts5ParserFallback;
  194571. return rc;
  194572. }
  194573. /*
  194574. ** Return the number of phrases in expression pExpr.
  194575. */
  194576. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  194577. return (pExpr ? pExpr->nPhrase : 0);
  194578. }
  194579. /*
  194580. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  194581. */
  194582. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  194583. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  194584. return pExpr->apExprPhrase[iPhrase]->nTerm;
  194585. }
  194586. /*
  194587. ** This function is used to access the current position list for phrase
  194588. ** iPhrase.
  194589. */
  194590. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  194591. int nRet;
  194592. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  194593. Fts5ExprNode *pNode = pPhrase->pNode;
  194594. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  194595. *pa = pPhrase->poslist.p;
  194596. nRet = pPhrase->poslist.n;
  194597. }else{
  194598. *pa = 0;
  194599. nRet = 0;
  194600. }
  194601. return nRet;
  194602. }
  194603. struct Fts5PoslistPopulator {
  194604. Fts5PoslistWriter writer;
  194605. int bOk; /* True if ok to populate */
  194606. int bMiss;
  194607. };
  194608. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
  194609. Fts5PoslistPopulator *pRet;
  194610. pRet = sqlite3_malloc64(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  194611. if( pRet ){
  194612. int i;
  194613. memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  194614. for(i=0; i<pExpr->nPhrase; i++){
  194615. Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
  194616. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  194617. assert( pExpr->apExprPhrase[i]->nTerm==1 );
  194618. if( bLive &&
  194619. (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
  194620. ){
  194621. pRet[i].bMiss = 1;
  194622. }else{
  194623. pBuf->n = 0;
  194624. }
  194625. }
  194626. }
  194627. return pRet;
  194628. }
  194629. struct Fts5ExprCtx {
  194630. Fts5Expr *pExpr;
  194631. Fts5PoslistPopulator *aPopulator;
  194632. i64 iOff;
  194633. };
  194634. typedef struct Fts5ExprCtx Fts5ExprCtx;
  194635. /*
  194636. ** TODO: Make this more efficient!
  194637. */
  194638. static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
  194639. int i;
  194640. for(i=0; i<pColset->nCol; i++){
  194641. if( pColset->aiCol[i]==iCol ) return 1;
  194642. }
  194643. return 0;
  194644. }
  194645. static int fts5ExprPopulatePoslistsCb(
  194646. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  194647. int tflags, /* Mask of FTS5_TOKEN_* flags */
  194648. const char *pToken, /* Pointer to buffer containing token */
  194649. int nToken, /* Size of token in bytes */
  194650. int iUnused1, /* Byte offset of token within input text */
  194651. int iUnused2 /* Byte offset of end of token within input text */
  194652. ){
  194653. Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
  194654. Fts5Expr *pExpr = p->pExpr;
  194655. int i;
  194656. UNUSED_PARAM2(iUnused1, iUnused2);
  194657. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  194658. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
  194659. for(i=0; i<pExpr->nPhrase; i++){
  194660. Fts5ExprTerm *pTerm;
  194661. if( p->aPopulator[i].bOk==0 ) continue;
  194662. for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  194663. int nTerm = (int)strlen(pTerm->zTerm);
  194664. if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
  194665. && memcmp(pTerm->zTerm, pToken, nTerm)==0
  194666. ){
  194667. int rc = sqlite3Fts5PoslistWriterAppend(
  194668. &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
  194669. );
  194670. if( rc ) return rc;
  194671. break;
  194672. }
  194673. }
  194674. }
  194675. return SQLITE_OK;
  194676. }
  194677. static int sqlite3Fts5ExprPopulatePoslists(
  194678. Fts5Config *pConfig,
  194679. Fts5Expr *pExpr,
  194680. Fts5PoslistPopulator *aPopulator,
  194681. int iCol,
  194682. const char *z, int n
  194683. ){
  194684. int i;
  194685. Fts5ExprCtx sCtx;
  194686. sCtx.pExpr = pExpr;
  194687. sCtx.aPopulator = aPopulator;
  194688. sCtx.iOff = (((i64)iCol) << 32) - 1;
  194689. for(i=0; i<pExpr->nPhrase; i++){
  194690. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  194691. Fts5Colset *pColset = pNode->pNear->pColset;
  194692. if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
  194693. || aPopulator[i].bMiss
  194694. ){
  194695. aPopulator[i].bOk = 0;
  194696. }else{
  194697. aPopulator[i].bOk = 1;
  194698. }
  194699. }
  194700. return sqlite3Fts5Tokenize(pConfig,
  194701. FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
  194702. );
  194703. }
  194704. static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
  194705. if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
  194706. pNode->pNear->apPhrase[0]->poslist.n = 0;
  194707. }else{
  194708. int i;
  194709. for(i=0; i<pNode->nChild; i++){
  194710. fts5ExprClearPoslists(pNode->apChild[i]);
  194711. }
  194712. }
  194713. }
  194714. static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
  194715. pNode->iRowid = iRowid;
  194716. pNode->bEof = 0;
  194717. switch( pNode->eType ){
  194718. case FTS5_TERM:
  194719. case FTS5_STRING:
  194720. return (pNode->pNear->apPhrase[0]->poslist.n>0);
  194721. case FTS5_AND: {
  194722. int i;
  194723. for(i=0; i<pNode->nChild; i++){
  194724. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
  194725. fts5ExprClearPoslists(pNode);
  194726. return 0;
  194727. }
  194728. }
  194729. break;
  194730. }
  194731. case FTS5_OR: {
  194732. int i;
  194733. int bRet = 0;
  194734. for(i=0; i<pNode->nChild; i++){
  194735. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
  194736. bRet = 1;
  194737. }
  194738. }
  194739. return bRet;
  194740. }
  194741. default: {
  194742. assert( pNode->eType==FTS5_NOT );
  194743. if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
  194744. || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
  194745. ){
  194746. fts5ExprClearPoslists(pNode);
  194747. return 0;
  194748. }
  194749. break;
  194750. }
  194751. }
  194752. return 1;
  194753. }
  194754. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
  194755. fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
  194756. }
  194757. /*
  194758. ** This function is only called for detail=columns tables.
  194759. */
  194760. static int sqlite3Fts5ExprPhraseCollist(
  194761. Fts5Expr *pExpr,
  194762. int iPhrase,
  194763. const u8 **ppCollist,
  194764. int *pnCollist
  194765. ){
  194766. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  194767. Fts5ExprNode *pNode = pPhrase->pNode;
  194768. int rc = SQLITE_OK;
  194769. assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
  194770. assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  194771. if( pNode->bEof==0
  194772. && pNode->iRowid==pExpr->pRoot->iRowid
  194773. && pPhrase->poslist.n>0
  194774. ){
  194775. Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
  194776. if( pTerm->pSynonym ){
  194777. Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
  194778. rc = fts5ExprSynonymList(
  194779. pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
  194780. );
  194781. }else{
  194782. *ppCollist = pPhrase->aTerm[0].pIter->pData;
  194783. *pnCollist = pPhrase->aTerm[0].pIter->nData;
  194784. }
  194785. }else{
  194786. *ppCollist = 0;
  194787. *pnCollist = 0;
  194788. }
  194789. return rc;
  194790. }
  194791. /*
  194792. ** 2014 August 11
  194793. **
  194794. ** The author disclaims copyright to this source code. In place of
  194795. ** a legal notice, here is a blessing:
  194796. **
  194797. ** May you do good and not evil.
  194798. ** May you find forgiveness for yourself and forgive others.
  194799. ** May you share freely, never taking more than you give.
  194800. **
  194801. ******************************************************************************
  194802. **
  194803. */
  194804. /* #include "fts5Int.h" */
  194805. typedef struct Fts5HashEntry Fts5HashEntry;
  194806. /*
  194807. ** This file contains the implementation of an in-memory hash table used
  194808. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  194809. ** segment.
  194810. */
  194811. struct Fts5Hash {
  194812. int eDetail; /* Copy of Fts5Config.eDetail */
  194813. int *pnByte; /* Pointer to bytes counter */
  194814. int nEntry; /* Number of entries currently in hash */
  194815. int nSlot; /* Size of aSlot[] array */
  194816. Fts5HashEntry *pScan; /* Current ordered scan item */
  194817. Fts5HashEntry **aSlot; /* Array of hash slots */
  194818. };
  194819. /*
  194820. ** Each entry in the hash table is represented by an object of the
  194821. ** following type. Each object, its key (a nul-terminated string) and
  194822. ** its current data are stored in a single memory allocation. The
  194823. ** key immediately follows the object in memory. The position list
  194824. ** data immediately follows the key data in memory.
  194825. **
  194826. ** The data that follows the key is in a similar, but not identical format
  194827. ** to the doclist data stored in the database. It is:
  194828. **
  194829. ** * Rowid, as a varint
  194830. ** * Position list, without 0x00 terminator.
  194831. ** * Size of previous position list and rowid, as a 4 byte
  194832. ** big-endian integer.
  194833. **
  194834. ** iRowidOff:
  194835. ** Offset of last rowid written to data area. Relative to first byte of
  194836. ** structure.
  194837. **
  194838. ** nData:
  194839. ** Bytes of data written since iRowidOff.
  194840. */
  194841. struct Fts5HashEntry {
  194842. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  194843. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  194844. int nAlloc; /* Total size of allocation */
  194845. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  194846. int nData; /* Total bytes of data (incl. structure) */
  194847. int nKey; /* Length of key in bytes */
  194848. u8 bDel; /* Set delete-flag @ iSzPoslist */
  194849. u8 bContent; /* Set content-flag (detail=none mode) */
  194850. i16 iCol; /* Column of last value written */
  194851. int iPos; /* Position of last value written */
  194852. i64 iRowid; /* Rowid of last value written */
  194853. };
  194854. /*
  194855. ** Eqivalent to:
  194856. **
  194857. ** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
  194858. */
  194859. #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
  194860. /*
  194861. ** Allocate a new hash table.
  194862. */
  194863. static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
  194864. int rc = SQLITE_OK;
  194865. Fts5Hash *pNew;
  194866. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  194867. if( pNew==0 ){
  194868. rc = SQLITE_NOMEM;
  194869. }else{
  194870. sqlite3_int64 nByte;
  194871. memset(pNew, 0, sizeof(Fts5Hash));
  194872. pNew->pnByte = pnByte;
  194873. pNew->eDetail = pConfig->eDetail;
  194874. pNew->nSlot = 1024;
  194875. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  194876. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc64(nByte);
  194877. if( pNew->aSlot==0 ){
  194878. sqlite3_free(pNew);
  194879. *ppNew = 0;
  194880. rc = SQLITE_NOMEM;
  194881. }else{
  194882. memset(pNew->aSlot, 0, (size_t)nByte);
  194883. }
  194884. }
  194885. return rc;
  194886. }
  194887. /*
  194888. ** Free a hash table object.
  194889. */
  194890. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  194891. if( pHash ){
  194892. sqlite3Fts5HashClear(pHash);
  194893. sqlite3_free(pHash->aSlot);
  194894. sqlite3_free(pHash);
  194895. }
  194896. }
  194897. /*
  194898. ** Empty (but do not delete) a hash table.
  194899. */
  194900. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  194901. int i;
  194902. for(i=0; i<pHash->nSlot; i++){
  194903. Fts5HashEntry *pNext;
  194904. Fts5HashEntry *pSlot;
  194905. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  194906. pNext = pSlot->pHashNext;
  194907. sqlite3_free(pSlot);
  194908. }
  194909. }
  194910. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  194911. pHash->nEntry = 0;
  194912. }
  194913. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  194914. int i;
  194915. unsigned int h = 13;
  194916. for(i=n-1; i>=0; i--){
  194917. h = (h << 3) ^ h ^ p[i];
  194918. }
  194919. return (h % nSlot);
  194920. }
  194921. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  194922. int i;
  194923. unsigned int h = 13;
  194924. for(i=n-1; i>=0; i--){
  194925. h = (h << 3) ^ h ^ p[i];
  194926. }
  194927. h = (h << 3) ^ h ^ b;
  194928. return (h % nSlot);
  194929. }
  194930. /*
  194931. ** Resize the hash table by doubling the number of slots.
  194932. */
  194933. static int fts5HashResize(Fts5Hash *pHash){
  194934. int nNew = pHash->nSlot*2;
  194935. int i;
  194936. Fts5HashEntry **apNew;
  194937. Fts5HashEntry **apOld = pHash->aSlot;
  194938. apNew = (Fts5HashEntry**)sqlite3_malloc64(nNew*sizeof(Fts5HashEntry*));
  194939. if( !apNew ) return SQLITE_NOMEM;
  194940. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  194941. for(i=0; i<pHash->nSlot; i++){
  194942. while( apOld[i] ){
  194943. unsigned int iHash;
  194944. Fts5HashEntry *p = apOld[i];
  194945. apOld[i] = p->pHashNext;
  194946. iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
  194947. (int)strlen(fts5EntryKey(p)));
  194948. p->pHashNext = apNew[iHash];
  194949. apNew[iHash] = p;
  194950. }
  194951. }
  194952. sqlite3_free(apOld);
  194953. pHash->nSlot = nNew;
  194954. pHash->aSlot = apNew;
  194955. return SQLITE_OK;
  194956. }
  194957. static int fts5HashAddPoslistSize(
  194958. Fts5Hash *pHash,
  194959. Fts5HashEntry *p,
  194960. Fts5HashEntry *p2
  194961. ){
  194962. int nRet = 0;
  194963. if( p->iSzPoslist ){
  194964. u8 *pPtr = p2 ? (u8*)p2 : (u8*)p;
  194965. int nData = p->nData;
  194966. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  194967. assert( nData==p->iSzPoslist );
  194968. if( p->bDel ){
  194969. pPtr[nData++] = 0x00;
  194970. if( p->bContent ){
  194971. pPtr[nData++] = 0x00;
  194972. }
  194973. }
  194974. }else{
  194975. int nSz = (nData - p->iSzPoslist - 1); /* Size in bytes */
  194976. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  194977. assert( p->bDel==0 || p->bDel==1 );
  194978. if( nPos<=127 ){
  194979. pPtr[p->iSzPoslist] = (u8)nPos;
  194980. }else{
  194981. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  194982. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  194983. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  194984. nData += (nByte-1);
  194985. }
  194986. }
  194987. nRet = nData - p->nData;
  194988. if( p2==0 ){
  194989. p->iSzPoslist = 0;
  194990. p->bDel = 0;
  194991. p->bContent = 0;
  194992. p->nData = nData;
  194993. }
  194994. }
  194995. return nRet;
  194996. }
  194997. /*
  194998. ** Add an entry to the in-memory hash table. The key is the concatenation
  194999. ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
  195000. **
  195001. ** (bByte || pToken) -> (iRowid,iCol,iPos)
  195002. **
  195003. ** Or, if iCol is negative, then the value is a delete marker.
  195004. */
  195005. static int sqlite3Fts5HashWrite(
  195006. Fts5Hash *pHash,
  195007. i64 iRowid, /* Rowid for this entry */
  195008. int iCol, /* Column token appears in (-ve -> delete) */
  195009. int iPos, /* Position of token within column */
  195010. char bByte, /* First byte of token */
  195011. const char *pToken, int nToken /* Token to add or remove to or from index */
  195012. ){
  195013. unsigned int iHash;
  195014. Fts5HashEntry *p;
  195015. u8 *pPtr;
  195016. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  195017. int bNew; /* If non-delete entry should be written */
  195018. bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
  195019. /* Attempt to locate an existing hash entry */
  195020. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  195021. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  195022. char *zKey = fts5EntryKey(p);
  195023. if( zKey[0]==bByte
  195024. && p->nKey==nToken
  195025. && memcmp(&zKey[1], pToken, nToken)==0
  195026. ){
  195027. break;
  195028. }
  195029. }
  195030. /* If an existing hash entry cannot be found, create a new one. */
  195031. if( p==0 ){
  195032. /* Figure out how much space to allocate */
  195033. char *zKey;
  195034. sqlite3_int64 nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
  195035. if( nByte<128 ) nByte = 128;
  195036. /* Grow the Fts5Hash.aSlot[] array if necessary. */
  195037. if( (pHash->nEntry*2)>=pHash->nSlot ){
  195038. int rc = fts5HashResize(pHash);
  195039. if( rc!=SQLITE_OK ) return rc;
  195040. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  195041. }
  195042. /* Allocate new Fts5HashEntry and add it to the hash table. */
  195043. p = (Fts5HashEntry*)sqlite3_malloc64(nByte);
  195044. if( !p ) return SQLITE_NOMEM;
  195045. memset(p, 0, sizeof(Fts5HashEntry));
  195046. p->nAlloc = (int)nByte;
  195047. zKey = fts5EntryKey(p);
  195048. zKey[0] = bByte;
  195049. memcpy(&zKey[1], pToken, nToken);
  195050. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
  195051. p->nKey = nToken;
  195052. zKey[nToken+1] = '\0';
  195053. p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
  195054. p->pHashNext = pHash->aSlot[iHash];
  195055. pHash->aSlot[iHash] = p;
  195056. pHash->nEntry++;
  195057. /* Add the first rowid field to the hash-entry */
  195058. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  195059. p->iRowid = iRowid;
  195060. p->iSzPoslist = p->nData;
  195061. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  195062. p->nData += 1;
  195063. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  195064. }
  195065. nIncr += p->nData;
  195066. }else{
  195067. /* Appending to an existing hash-entry. Check that there is enough
  195068. ** space to append the largest possible new entry. Worst case scenario
  195069. ** is:
  195070. **
  195071. ** + 9 bytes for a new rowid,
  195072. ** + 4 byte reserved for the "poslist size" varint.
  195073. ** + 1 byte for a "new column" byte,
  195074. ** + 3 bytes for a new column number (16-bit max) as a varint,
  195075. ** + 5 bytes for the new position offset (32-bit max).
  195076. */
  195077. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  195078. sqlite3_int64 nNew = p->nAlloc * 2;
  195079. Fts5HashEntry *pNew;
  195080. Fts5HashEntry **pp;
  195081. pNew = (Fts5HashEntry*)sqlite3_realloc64(p, nNew);
  195082. if( pNew==0 ) return SQLITE_NOMEM;
  195083. pNew->nAlloc = (int)nNew;
  195084. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  195085. *pp = pNew;
  195086. p = pNew;
  195087. }
  195088. nIncr -= p->nData;
  195089. }
  195090. assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
  195091. pPtr = (u8*)p;
  195092. /* If this is a new rowid, append the 4-byte size field for the previous
  195093. ** entry, and the new rowid for this entry. */
  195094. if( iRowid!=p->iRowid ){
  195095. fts5HashAddPoslistSize(pHash, p, 0);
  195096. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  195097. p->iRowid = iRowid;
  195098. bNew = 1;
  195099. p->iSzPoslist = p->nData;
  195100. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  195101. p->nData += 1;
  195102. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  195103. p->iPos = 0;
  195104. }
  195105. }
  195106. if( iCol>=0 ){
  195107. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  195108. p->bContent = 1;
  195109. }else{
  195110. /* Append a new column value, if necessary */
  195111. assert( iCol>=p->iCol );
  195112. if( iCol!=p->iCol ){
  195113. if( pHash->eDetail==FTS5_DETAIL_FULL ){
  195114. pPtr[p->nData++] = 0x01;
  195115. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  195116. p->iCol = (i16)iCol;
  195117. p->iPos = 0;
  195118. }else{
  195119. bNew = 1;
  195120. p->iCol = (i16)(iPos = iCol);
  195121. }
  195122. }
  195123. /* Append the new position offset, if necessary */
  195124. if( bNew ){
  195125. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  195126. p->iPos = iPos;
  195127. }
  195128. }
  195129. }else{
  195130. /* This is a delete. Set the delete flag. */
  195131. p->bDel = 1;
  195132. }
  195133. nIncr += p->nData;
  195134. *pHash->pnByte += nIncr;
  195135. return SQLITE_OK;
  195136. }
  195137. /*
  195138. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  195139. ** each sorted in key order. This function merges the two lists into a
  195140. ** single list and returns a pointer to its first element.
  195141. */
  195142. static Fts5HashEntry *fts5HashEntryMerge(
  195143. Fts5HashEntry *pLeft,
  195144. Fts5HashEntry *pRight
  195145. ){
  195146. Fts5HashEntry *p1 = pLeft;
  195147. Fts5HashEntry *p2 = pRight;
  195148. Fts5HashEntry *pRet = 0;
  195149. Fts5HashEntry **ppOut = &pRet;
  195150. while( p1 || p2 ){
  195151. if( p1==0 ){
  195152. *ppOut = p2;
  195153. p2 = 0;
  195154. }else if( p2==0 ){
  195155. *ppOut = p1;
  195156. p1 = 0;
  195157. }else{
  195158. int i = 0;
  195159. char *zKey1 = fts5EntryKey(p1);
  195160. char *zKey2 = fts5EntryKey(p2);
  195161. while( zKey1[i]==zKey2[i] ) i++;
  195162. if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
  195163. /* p2 is smaller */
  195164. *ppOut = p2;
  195165. ppOut = &p2->pScanNext;
  195166. p2 = p2->pScanNext;
  195167. }else{
  195168. /* p1 is smaller */
  195169. *ppOut = p1;
  195170. ppOut = &p1->pScanNext;
  195171. p1 = p1->pScanNext;
  195172. }
  195173. *ppOut = 0;
  195174. }
  195175. }
  195176. return pRet;
  195177. }
  195178. /*
  195179. ** Extract all tokens from hash table iHash and link them into a list
  195180. ** in sorted order. The hash table is cleared before returning. It is
  195181. ** the responsibility of the caller to free the elements of the returned
  195182. ** list.
  195183. */
  195184. static int fts5HashEntrySort(
  195185. Fts5Hash *pHash,
  195186. const char *pTerm, int nTerm, /* Query prefix, if any */
  195187. Fts5HashEntry **ppSorted
  195188. ){
  195189. const int nMergeSlot = 32;
  195190. Fts5HashEntry **ap;
  195191. Fts5HashEntry *pList;
  195192. int iSlot;
  195193. int i;
  195194. *ppSorted = 0;
  195195. ap = sqlite3_malloc64(sizeof(Fts5HashEntry*) * nMergeSlot);
  195196. if( !ap ) return SQLITE_NOMEM;
  195197. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  195198. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  195199. Fts5HashEntry *pIter;
  195200. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  195201. if( pTerm==0
  195202. || (pIter->nKey+1>=nTerm && 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm))
  195203. ){
  195204. Fts5HashEntry *pEntry = pIter;
  195205. pEntry->pScanNext = 0;
  195206. for(i=0; ap[i]; i++){
  195207. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  195208. ap[i] = 0;
  195209. }
  195210. ap[i] = pEntry;
  195211. }
  195212. }
  195213. }
  195214. pList = 0;
  195215. for(i=0; i<nMergeSlot; i++){
  195216. pList = fts5HashEntryMerge(pList, ap[i]);
  195217. }
  195218. pHash->nEntry = 0;
  195219. sqlite3_free(ap);
  195220. *ppSorted = pList;
  195221. return SQLITE_OK;
  195222. }
  195223. /*
  195224. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  195225. */
  195226. static int sqlite3Fts5HashQuery(
  195227. Fts5Hash *pHash, /* Hash table to query */
  195228. int nPre,
  195229. const char *pTerm, int nTerm, /* Query term */
  195230. void **ppOut, /* OUT: Pointer to new object */
  195231. int *pnDoclist /* OUT: Size of doclist in bytes */
  195232. ){
  195233. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  195234. char *zKey = 0;
  195235. Fts5HashEntry *p;
  195236. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  195237. zKey = fts5EntryKey(p);
  195238. assert( p->nKey+1==(int)strlen(zKey) );
  195239. if( nTerm==p->nKey+1 && memcmp(zKey, pTerm, nTerm)==0 ) break;
  195240. }
  195241. if( p ){
  195242. int nHashPre = sizeof(Fts5HashEntry) + nTerm + 1;
  195243. int nList = p->nData - nHashPre;
  195244. u8 *pRet = (u8*)(*ppOut = sqlite3_malloc64(nPre + nList + 10));
  195245. if( pRet ){
  195246. Fts5HashEntry *pFaux = (Fts5HashEntry*)&pRet[nPre-nHashPre];
  195247. memcpy(&pRet[nPre], &((u8*)p)[nHashPre], nList);
  195248. nList += fts5HashAddPoslistSize(pHash, p, pFaux);
  195249. *pnDoclist = nList;
  195250. }else{
  195251. *pnDoclist = 0;
  195252. return SQLITE_NOMEM;
  195253. }
  195254. }else{
  195255. *ppOut = 0;
  195256. *pnDoclist = 0;
  195257. }
  195258. return SQLITE_OK;
  195259. }
  195260. static int sqlite3Fts5HashScanInit(
  195261. Fts5Hash *p, /* Hash table to query */
  195262. const char *pTerm, int nTerm /* Query prefix */
  195263. ){
  195264. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  195265. }
  195266. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  195267. assert( !sqlite3Fts5HashScanEof(p) );
  195268. p->pScan = p->pScan->pScanNext;
  195269. }
  195270. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  195271. return (p->pScan==0);
  195272. }
  195273. static void sqlite3Fts5HashScanEntry(
  195274. Fts5Hash *pHash,
  195275. const char **pzTerm, /* OUT: term (nul-terminated) */
  195276. const u8 **ppDoclist, /* OUT: pointer to doclist */
  195277. int *pnDoclist /* OUT: size of doclist in bytes */
  195278. ){
  195279. Fts5HashEntry *p;
  195280. if( (p = pHash->pScan) ){
  195281. char *zKey = fts5EntryKey(p);
  195282. int nTerm = (int)strlen(zKey);
  195283. fts5HashAddPoslistSize(pHash, p, 0);
  195284. *pzTerm = zKey;
  195285. *ppDoclist = (const u8*)&zKey[nTerm+1];
  195286. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  195287. }else{
  195288. *pzTerm = 0;
  195289. *ppDoclist = 0;
  195290. *pnDoclist = 0;
  195291. }
  195292. }
  195293. /*
  195294. ** 2014 May 31
  195295. **
  195296. ** The author disclaims copyright to this source code. In place of
  195297. ** a legal notice, here is a blessing:
  195298. **
  195299. ** May you do good and not evil.
  195300. ** May you find forgiveness for yourself and forgive others.
  195301. ** May you share freely, never taking more than you give.
  195302. **
  195303. ******************************************************************************
  195304. **
  195305. ** Low level access to the FTS index stored in the database file. The
  195306. ** routines in this file file implement all read and write access to the
  195307. ** %_data table. Other parts of the system access this functionality via
  195308. ** the interface defined in fts5Int.h.
  195309. */
  195310. /* #include "fts5Int.h" */
  195311. /*
  195312. ** Overview:
  195313. **
  195314. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  195315. ** As well as the main term index, there may be up to 31 prefix indexes.
  195316. ** The format is similar to FTS3/4, except that:
  195317. **
  195318. ** * all segment b-tree leaf data is stored in fixed size page records
  195319. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  195320. ** taken to ensure it is possible to iterate in either direction through
  195321. ** the entries in a doclist, or to seek to a specific entry within a
  195322. ** doclist, without loading it into memory.
  195323. **
  195324. ** * large doclists that span many pages have associated "doclist index"
  195325. ** records that contain a copy of the first rowid on each page spanned by
  195326. ** the doclist. This is used to speed up seek operations, and merges of
  195327. ** large doclists with very small doclists.
  195328. **
  195329. ** * extra fields in the "structure record" record the state of ongoing
  195330. ** incremental merge operations.
  195331. **
  195332. */
  195333. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  195334. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  195335. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  195336. #define FTS5_MAIN_PREFIX '0'
  195337. #if FTS5_MAX_PREFIX_INDEXES > 31
  195338. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  195339. #endif
  195340. /*
  195341. ** Details:
  195342. **
  195343. ** The %_data table managed by this module,
  195344. **
  195345. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  195346. **
  195347. ** , contains the following 5 types of records. See the comments surrounding
  195348. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  195349. ** assigned to each fo them.
  195350. **
  195351. ** 1. Structure Records:
  195352. **
  195353. ** The set of segments that make up an index - the index structure - are
  195354. ** recorded in a single record within the %_data table. The record consists
  195355. ** of a single 32-bit configuration cookie value followed by a list of
  195356. ** SQLite varints. If the FTS table features more than one index (because
  195357. ** there are one or more prefix indexes), it is guaranteed that all share
  195358. ** the same cookie value.
  195359. **
  195360. ** Immediately following the configuration cookie, the record begins with
  195361. ** three varints:
  195362. **
  195363. ** + number of levels,
  195364. ** + total number of segments on all levels,
  195365. ** + value of write counter.
  195366. **
  195367. ** Then, for each level from 0 to nMax:
  195368. **
  195369. ** + number of input segments in ongoing merge.
  195370. ** + total number of segments in level.
  195371. ** + for each segment from oldest to newest:
  195372. ** + segment id (always > 0)
  195373. ** + first leaf page number (often 1, always greater than 0)
  195374. ** + final leaf page number
  195375. **
  195376. ** 2. The Averages Record:
  195377. **
  195378. ** A single record within the %_data table. The data is a list of varints.
  195379. ** The first value is the number of rows in the index. Then, for each column
  195380. ** from left to right, the total number of tokens in the column for all
  195381. ** rows of the table.
  195382. **
  195383. ** 3. Segment leaves:
  195384. **
  195385. ** TERM/DOCLIST FORMAT:
  195386. **
  195387. ** Most of each segment leaf is taken up by term/doclist data. The
  195388. ** general format of term/doclist, starting with the first term
  195389. ** on the leaf page, is:
  195390. **
  195391. ** varint : size of first term
  195392. ** blob: first term data
  195393. ** doclist: first doclist
  195394. ** zero-or-more {
  195395. ** varint: number of bytes in common with previous term
  195396. ** varint: number of bytes of new term data (nNew)
  195397. ** blob: nNew bytes of new term data
  195398. ** doclist: next doclist
  195399. ** }
  195400. **
  195401. ** doclist format:
  195402. **
  195403. ** varint: first rowid
  195404. ** poslist: first poslist
  195405. ** zero-or-more {
  195406. ** varint: rowid delta (always > 0)
  195407. ** poslist: next poslist
  195408. ** }
  195409. **
  195410. ** poslist format:
  195411. **
  195412. ** varint: size of poslist in bytes multiplied by 2, not including
  195413. ** this field. Plus 1 if this entry carries the "delete" flag.
  195414. ** collist: collist for column 0
  195415. ** zero-or-more {
  195416. ** 0x01 byte
  195417. ** varint: column number (I)
  195418. ** collist: collist for column I
  195419. ** }
  195420. **
  195421. ** collist format:
  195422. **
  195423. ** varint: first offset + 2
  195424. ** zero-or-more {
  195425. ** varint: offset delta + 2
  195426. ** }
  195427. **
  195428. ** PAGE FORMAT
  195429. **
  195430. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  195431. ** unsigned integer fields in big-endian format. They are:
  195432. **
  195433. ** * The byte offset of the first rowid on the page, if it exists
  195434. ** and occurs before the first term (otherwise 0).
  195435. **
  195436. ** * The byte offset of the start of the page footer. If the page
  195437. ** footer is 0 bytes in size, then this field is the same as the
  195438. ** size of the leaf page in bytes.
  195439. **
  195440. ** The page footer consists of a single varint for each term located
  195441. ** on the page. Each varint is the byte offset of the current term
  195442. ** within the page, delta-compressed against the previous value. In
  195443. ** other words, the first varint in the footer is the byte offset of
  195444. ** the first term, the second is the byte offset of the second less that
  195445. ** of the first, and so on.
  195446. **
  195447. ** The term/doclist format described above is accurate if the entire
  195448. ** term/doclist data fits on a single leaf page. If this is not the case,
  195449. ** the format is changed in two ways:
  195450. **
  195451. ** + if the first rowid on a page occurs before the first term, it
  195452. ** is stored as a literal value:
  195453. **
  195454. ** varint: first rowid
  195455. **
  195456. ** + the first term on each page is stored in the same way as the
  195457. ** very first term of the segment:
  195458. **
  195459. ** varint : size of first term
  195460. ** blob: first term data
  195461. **
  195462. ** 5. Segment doclist indexes:
  195463. **
  195464. ** Doclist indexes are themselves b-trees, however they usually consist of
  195465. ** a single leaf record only. The format of each doclist index leaf page
  195466. ** is:
  195467. **
  195468. ** * Flags byte. Bits are:
  195469. ** 0x01: Clear if leaf is also the root page, otherwise set.
  195470. **
  195471. ** * Page number of fts index leaf page. As a varint.
  195472. **
  195473. ** * First rowid on page indicated by previous field. As a varint.
  195474. **
  195475. ** * A list of varints, one for each subsequent termless page. A
  195476. ** positive delta if the termless page contains at least one rowid,
  195477. ** or an 0x00 byte otherwise.
  195478. **
  195479. ** Internal doclist index nodes are:
  195480. **
  195481. ** * Flags byte. Bits are:
  195482. ** 0x01: Clear for root page, otherwise set.
  195483. **
  195484. ** * Page number of first child page. As a varint.
  195485. **
  195486. ** * Copy of first rowid on page indicated by previous field. As a varint.
  195487. **
  195488. ** * A list of delta-encoded varints - the first rowid on each subsequent
  195489. ** child page.
  195490. **
  195491. */
  195492. /*
  195493. ** Rowids for the averages and structure records in the %_data table.
  195494. */
  195495. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  195496. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  195497. /*
  195498. ** Macros determining the rowids used by segment leaves and dlidx leaves
  195499. ** and nodes. All nodes and leaves are stored in the %_data table with large
  195500. ** positive rowids.
  195501. **
  195502. ** Each segment has a unique non-zero 16-bit id.
  195503. **
  195504. ** The rowid for each segment leaf is found by passing the segment id and
  195505. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  195506. ** sequentially starting from 1.
  195507. */
  195508. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  195509. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  195510. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  195511. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  195512. #define fts5_dri(segid, dlidx, height, pgno) ( \
  195513. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  195514. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  195515. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  195516. ((i64)(pgno)) \
  195517. )
  195518. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  195519. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  195520. /*
  195521. ** Maximum segments permitted in a single index
  195522. */
  195523. #define FTS5_MAX_SEGMENT 2000
  195524. #ifdef SQLITE_DEBUG
  195525. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  195526. #endif
  195527. /*
  195528. ** Each time a blob is read from the %_data table, it is padded with this
  195529. ** many zero bytes. This makes it easier to decode the various record formats
  195530. ** without overreading if the records are corrupt.
  195531. */
  195532. #define FTS5_DATA_ZERO_PADDING 8
  195533. #define FTS5_DATA_PADDING 20
  195534. typedef struct Fts5Data Fts5Data;
  195535. typedef struct Fts5DlidxIter Fts5DlidxIter;
  195536. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  195537. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  195538. typedef struct Fts5Iter Fts5Iter;
  195539. typedef struct Fts5PageWriter Fts5PageWriter;
  195540. typedef struct Fts5SegIter Fts5SegIter;
  195541. typedef struct Fts5DoclistIter Fts5DoclistIter;
  195542. typedef struct Fts5SegWriter Fts5SegWriter;
  195543. typedef struct Fts5Structure Fts5Structure;
  195544. typedef struct Fts5StructureLevel Fts5StructureLevel;
  195545. typedef struct Fts5StructureSegment Fts5StructureSegment;
  195546. struct Fts5Data {
  195547. u8 *p; /* Pointer to buffer containing record */
  195548. int nn; /* Size of record in bytes */
  195549. int szLeaf; /* Size of leaf without page-index */
  195550. };
  195551. /*
  195552. ** One object per %_data table.
  195553. */
  195554. struct Fts5Index {
  195555. Fts5Config *pConfig; /* Virtual table configuration */
  195556. char *zDataTbl; /* Name of %_data table */
  195557. int nWorkUnit; /* Leaf pages in a "unit" of work */
  195558. /*
  195559. ** Variables related to the accumulation of tokens and doclists within the
  195560. ** in-memory hash tables before they are flushed to disk.
  195561. */
  195562. Fts5Hash *pHash; /* Hash table for in-memory data */
  195563. int nPendingData; /* Current bytes of pending data */
  195564. i64 iWriteRowid; /* Rowid for current doc being written */
  195565. int bDelete; /* Current write is a delete */
  195566. /* Error state. */
  195567. int rc; /* Current error code */
  195568. /* State used by the fts5DataXXX() functions. */
  195569. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  195570. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  195571. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  195572. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  195573. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  195574. sqlite3_stmt *pIdxSelect;
  195575. int nRead; /* Total number of blocks read */
  195576. sqlite3_stmt *pDataVersion;
  195577. i64 iStructVersion; /* data_version when pStruct read */
  195578. Fts5Structure *pStruct; /* Current db structure (or NULL) */
  195579. };
  195580. struct Fts5DoclistIter {
  195581. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  195582. /* Output variables. aPoslist==0 at EOF */
  195583. i64 iRowid;
  195584. u8 *aPoslist;
  195585. int nPoslist;
  195586. int nSize;
  195587. };
  195588. /*
  195589. ** The contents of the "structure" record for each index are represented
  195590. ** using an Fts5Structure record in memory. Which uses instances of the
  195591. ** other Fts5StructureXXX types as components.
  195592. */
  195593. struct Fts5StructureSegment {
  195594. int iSegid; /* Segment id */
  195595. int pgnoFirst; /* First leaf page number in segment */
  195596. int pgnoLast; /* Last leaf page number in segment */
  195597. };
  195598. struct Fts5StructureLevel {
  195599. int nMerge; /* Number of segments in incr-merge */
  195600. int nSeg; /* Total number of segments on level */
  195601. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  195602. };
  195603. struct Fts5Structure {
  195604. int nRef; /* Object reference count */
  195605. u64 nWriteCounter; /* Total leaves written to level 0 */
  195606. int nSegment; /* Total segments in this structure */
  195607. int nLevel; /* Number of levels in this index */
  195608. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  195609. };
  195610. /*
  195611. ** An object of type Fts5SegWriter is used to write to segments.
  195612. */
  195613. struct Fts5PageWriter {
  195614. int pgno; /* Page number for this page */
  195615. int iPrevPgidx; /* Previous value written into pgidx */
  195616. Fts5Buffer buf; /* Buffer containing leaf data */
  195617. Fts5Buffer pgidx; /* Buffer containing page-index */
  195618. Fts5Buffer term; /* Buffer containing previous term on page */
  195619. };
  195620. struct Fts5DlidxWriter {
  195621. int pgno; /* Page number for this page */
  195622. int bPrevValid; /* True if iPrev is valid */
  195623. i64 iPrev; /* Previous rowid value written to page */
  195624. Fts5Buffer buf; /* Buffer containing page data */
  195625. };
  195626. struct Fts5SegWriter {
  195627. int iSegid; /* Segid to write to */
  195628. Fts5PageWriter writer; /* PageWriter object */
  195629. i64 iPrevRowid; /* Previous rowid written to current leaf */
  195630. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  195631. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  195632. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  195633. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  195634. int nLeafWritten; /* Number of leaf pages written */
  195635. int nEmpty; /* Number of contiguous term-less nodes */
  195636. int nDlidx; /* Allocated size of aDlidx[] array */
  195637. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  195638. /* Values to insert into the %_idx table */
  195639. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  195640. int iBtPage; /* Page number corresponding to btterm */
  195641. };
  195642. typedef struct Fts5CResult Fts5CResult;
  195643. struct Fts5CResult {
  195644. u16 iFirst; /* aSeg[] index of firstest iterator */
  195645. u8 bTermEq; /* True if the terms are equal */
  195646. };
  195647. /*
  195648. ** Object for iterating through a single segment, visiting each term/rowid
  195649. ** pair in the segment.
  195650. **
  195651. ** pSeg:
  195652. ** The segment to iterate through.
  195653. **
  195654. ** iLeafPgno:
  195655. ** Current leaf page number within segment.
  195656. **
  195657. ** iLeafOffset:
  195658. ** Byte offset within the current leaf that is the first byte of the
  195659. ** position list data (one byte passed the position-list size field).
  195660. ** rowid field of the current entry. Usually this is the size field of the
  195661. ** position list data. The exception is if the rowid for the current entry
  195662. ** is the last thing on the leaf page.
  195663. **
  195664. ** pLeaf:
  195665. ** Buffer containing current leaf page data. Set to NULL at EOF.
  195666. **
  195667. ** iTermLeafPgno, iTermLeafOffset:
  195668. ** Leaf page number containing the last term read from the segment. And
  195669. ** the offset immediately following the term data.
  195670. **
  195671. ** flags:
  195672. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  195673. **
  195674. ** FTS5_SEGITER_ONETERM:
  195675. ** If set, set the iterator to point to EOF after the current doclist
  195676. ** has been exhausted. Do not proceed to the next term in the segment.
  195677. **
  195678. ** FTS5_SEGITER_REVERSE:
  195679. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  195680. ** it is set, iterate through rowid in descending order instead of the
  195681. ** default ascending order.
  195682. **
  195683. ** iRowidOffset/nRowidOffset/aRowidOffset:
  195684. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  195685. **
  195686. ** For each rowid on the page corresponding to the current term, the
  195687. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  195688. ** start of the "position-list-size" field within the page.
  195689. **
  195690. ** iTermIdx:
  195691. ** Index of current term on iTermLeafPgno.
  195692. */
  195693. struct Fts5SegIter {
  195694. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  195695. int flags; /* Mask of configuration flags */
  195696. int iLeafPgno; /* Current leaf page number */
  195697. Fts5Data *pLeaf; /* Current leaf data */
  195698. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  195699. int iLeafOffset; /* Byte offset within current leaf */
  195700. /* Next method */
  195701. void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
  195702. /* The page and offset from which the current term was read. The offset
  195703. ** is the offset of the first rowid in the current doclist. */
  195704. int iTermLeafPgno;
  195705. int iTermLeafOffset;
  195706. int iPgidxOff; /* Next offset in pgidx */
  195707. int iEndofDoclist;
  195708. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  195709. int iRowidOffset; /* Current entry in aRowidOffset[] */
  195710. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  195711. int *aRowidOffset; /* Array of offset to rowid fields */
  195712. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  195713. /* Variables populated based on current entry. */
  195714. Fts5Buffer term; /* Current term */
  195715. i64 iRowid; /* Current rowid */
  195716. int nPos; /* Number of bytes in current position list */
  195717. u8 bDel; /* True if the delete flag is set */
  195718. };
  195719. /*
  195720. ** Argument is a pointer to an Fts5Data structure that contains a
  195721. ** leaf page.
  195722. */
  195723. #define ASSERT_SZLEAF_OK(x) assert( \
  195724. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  195725. )
  195726. #define FTS5_SEGITER_ONETERM 0x01
  195727. #define FTS5_SEGITER_REVERSE 0x02
  195728. /*
  195729. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  195730. ** page. This macro evaluates to true if the leaf contains no terms, or
  195731. ** false if it contains at least one term.
  195732. */
  195733. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  195734. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  195735. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  195736. /*
  195737. ** Object for iterating through the merged results of one or more segments,
  195738. ** visiting each term/rowid pair in the merged data.
  195739. **
  195740. ** nSeg is always a power of two greater than or equal to the number of
  195741. ** segments that this object is merging data from. Both the aSeg[] and
  195742. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  195743. ** with zeroed objects - these are handled as if they were iterators opened
  195744. ** on empty segments.
  195745. **
  195746. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  195747. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  195748. ** comparison in this context is the index of the iterator that currently
  195749. ** points to the smaller term/rowid combination. Iterators at EOF are
  195750. ** considered to be greater than all other iterators.
  195751. **
  195752. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  195753. ** the smallest key overall. aFirst[0] is unused.
  195754. **
  195755. ** poslist:
  195756. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  195757. ** There is no way to tell if this is populated or not.
  195758. */
  195759. struct Fts5Iter {
  195760. Fts5IndexIter base; /* Base class containing output vars */
  195761. Fts5Index *pIndex; /* Index that owns this iterator */
  195762. Fts5Buffer poslist; /* Buffer containing current poslist */
  195763. Fts5Colset *pColset; /* Restrict matches to these columns */
  195764. /* Invoked to set output variables. */
  195765. void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
  195766. int nSeg; /* Size of aSeg[] array */
  195767. int bRev; /* True to iterate in reverse order */
  195768. u8 bSkipEmpty; /* True to skip deleted entries */
  195769. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  195770. Fts5CResult *aFirst; /* Current merge state (see above) */
  195771. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  195772. };
  195773. /*
  195774. ** An instance of the following type is used to iterate through the contents
  195775. ** of a doclist-index record.
  195776. **
  195777. ** pData:
  195778. ** Record containing the doclist-index data.
  195779. **
  195780. ** bEof:
  195781. ** Set to true once iterator has reached EOF.
  195782. **
  195783. ** iOff:
  195784. ** Set to the current offset within record pData.
  195785. */
  195786. struct Fts5DlidxLvl {
  195787. Fts5Data *pData; /* Data for current page of this level */
  195788. int iOff; /* Current offset into pData */
  195789. int bEof; /* At EOF already */
  195790. int iFirstOff; /* Used by reverse iterators */
  195791. /* Output variables */
  195792. int iLeafPgno; /* Page number of current leaf page */
  195793. i64 iRowid; /* First rowid on leaf iLeafPgno */
  195794. };
  195795. struct Fts5DlidxIter {
  195796. int nLvl;
  195797. int iSegid;
  195798. Fts5DlidxLvl aLvl[1];
  195799. };
  195800. static void fts5PutU16(u8 *aOut, u16 iVal){
  195801. aOut[0] = (iVal>>8);
  195802. aOut[1] = (iVal&0xFF);
  195803. }
  195804. static u16 fts5GetU16(const u8 *aIn){
  195805. return ((u16)aIn[0] << 8) + aIn[1];
  195806. }
  195807. /*
  195808. ** Allocate and return a buffer at least nByte bytes in size.
  195809. **
  195810. ** If an OOM error is encountered, return NULL and set the error code in
  195811. ** the Fts5Index handle passed as the first argument.
  195812. */
  195813. static void *fts5IdxMalloc(Fts5Index *p, sqlite3_int64 nByte){
  195814. return sqlite3Fts5MallocZero(&p->rc, nByte);
  195815. }
  195816. /*
  195817. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  195818. **
  195819. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  195820. ** +ve if pRight is smaller than pLeft. In other words:
  195821. **
  195822. ** res = *pLeft - *pRight
  195823. */
  195824. #ifdef SQLITE_DEBUG
  195825. static int fts5BufferCompareBlob(
  195826. Fts5Buffer *pLeft, /* Left hand side of comparison */
  195827. const u8 *pRight, int nRight /* Right hand side of comparison */
  195828. ){
  195829. int nCmp = MIN(pLeft->n, nRight);
  195830. int res = memcmp(pLeft->p, pRight, nCmp);
  195831. return (res==0 ? (pLeft->n - nRight) : res);
  195832. }
  195833. #endif
  195834. /*
  195835. ** Compare the contents of the two buffers using memcmp(). If one buffer
  195836. ** is a prefix of the other, it is considered the lesser.
  195837. **
  195838. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  195839. ** +ve if pRight is smaller than pLeft. In other words:
  195840. **
  195841. ** res = *pLeft - *pRight
  195842. */
  195843. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  195844. int nCmp = MIN(pLeft->n, pRight->n);
  195845. int res = fts5Memcmp(pLeft->p, pRight->p, nCmp);
  195846. return (res==0 ? (pLeft->n - pRight->n) : res);
  195847. }
  195848. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  195849. int ret;
  195850. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  195851. return ret;
  195852. }
  195853. /*
  195854. ** Close the read-only blob handle, if it is open.
  195855. */
  195856. static void fts5CloseReader(Fts5Index *p){
  195857. if( p->pReader ){
  195858. sqlite3_blob *pReader = p->pReader;
  195859. p->pReader = 0;
  195860. sqlite3_blob_close(pReader);
  195861. }
  195862. }
  195863. /*
  195864. ** Retrieve a record from the %_data table.
  195865. **
  195866. ** If an error occurs, NULL is returned and an error left in the
  195867. ** Fts5Index object.
  195868. */
  195869. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  195870. Fts5Data *pRet = 0;
  195871. if( p->rc==SQLITE_OK ){
  195872. int rc = SQLITE_OK;
  195873. if( p->pReader ){
  195874. /* This call may return SQLITE_ABORT if there has been a savepoint
  195875. ** rollback since it was last used. In this case a new blob handle
  195876. ** is required. */
  195877. sqlite3_blob *pBlob = p->pReader;
  195878. p->pReader = 0;
  195879. rc = sqlite3_blob_reopen(pBlob, iRowid);
  195880. assert( p->pReader==0 );
  195881. p->pReader = pBlob;
  195882. if( rc!=SQLITE_OK ){
  195883. fts5CloseReader(p);
  195884. }
  195885. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  195886. }
  195887. /* If the blob handle is not open at this point, open it and seek
  195888. ** to the requested entry. */
  195889. if( p->pReader==0 && rc==SQLITE_OK ){
  195890. Fts5Config *pConfig = p->pConfig;
  195891. rc = sqlite3_blob_open(pConfig->db,
  195892. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  195893. );
  195894. }
  195895. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  195896. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  195897. ** All the reasons those functions might return SQLITE_ERROR - missing
  195898. ** table, missing row, non-blob/text in block column - indicate
  195899. ** backing store corruption. */
  195900. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  195901. if( rc==SQLITE_OK ){
  195902. u8 *aOut = 0; /* Read blob data into this buffer */
  195903. int nByte = sqlite3_blob_bytes(p->pReader);
  195904. sqlite3_int64 nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  195905. pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);
  195906. if( pRet ){
  195907. pRet->nn = nByte;
  195908. aOut = pRet->p = (u8*)&pRet[1];
  195909. }else{
  195910. rc = SQLITE_NOMEM;
  195911. }
  195912. if( rc==SQLITE_OK ){
  195913. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  195914. }
  195915. if( rc!=SQLITE_OK ){
  195916. sqlite3_free(pRet);
  195917. pRet = 0;
  195918. }else{
  195919. /* TODO1: Fix this */
  195920. pRet->p[nByte] = 0x00;
  195921. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  195922. }
  195923. }
  195924. p->rc = rc;
  195925. p->nRead++;
  195926. }
  195927. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  195928. return pRet;
  195929. }
  195930. /*
  195931. ** Release a reference to data record returned by an earlier call to
  195932. ** fts5DataRead().
  195933. */
  195934. static void fts5DataRelease(Fts5Data *pData){
  195935. sqlite3_free(pData);
  195936. }
  195937. static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
  195938. Fts5Data *pRet = fts5DataRead(p, iRowid);
  195939. if( pRet ){
  195940. if( pRet->szLeaf>pRet->nn ){
  195941. p->rc = FTS5_CORRUPT;
  195942. fts5DataRelease(pRet);
  195943. pRet = 0;
  195944. }
  195945. }
  195946. return pRet;
  195947. }
  195948. static int fts5IndexPrepareStmt(
  195949. Fts5Index *p,
  195950. sqlite3_stmt **ppStmt,
  195951. char *zSql
  195952. ){
  195953. if( p->rc==SQLITE_OK ){
  195954. if( zSql ){
  195955. p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
  195956. SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB,
  195957. ppStmt, 0);
  195958. }else{
  195959. p->rc = SQLITE_NOMEM;
  195960. }
  195961. }
  195962. sqlite3_free(zSql);
  195963. return p->rc;
  195964. }
  195965. /*
  195966. ** INSERT OR REPLACE a record into the %_data table.
  195967. */
  195968. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  195969. if( p->rc!=SQLITE_OK ) return;
  195970. if( p->pWriter==0 ){
  195971. Fts5Config *pConfig = p->pConfig;
  195972. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  195973. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  195974. pConfig->zDb, pConfig->zName
  195975. ));
  195976. if( p->rc ) return;
  195977. }
  195978. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  195979. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  195980. sqlite3_step(p->pWriter);
  195981. p->rc = sqlite3_reset(p->pWriter);
  195982. sqlite3_bind_null(p->pWriter, 2);
  195983. }
  195984. /*
  195985. ** Execute the following SQL:
  195986. **
  195987. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  195988. */
  195989. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  195990. if( p->rc!=SQLITE_OK ) return;
  195991. if( p->pDeleter==0 ){
  195992. Fts5Config *pConfig = p->pConfig;
  195993. char *zSql = sqlite3_mprintf(
  195994. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  195995. pConfig->zDb, pConfig->zName
  195996. );
  195997. if( fts5IndexPrepareStmt(p, &p->pDeleter, zSql) ) return;
  195998. }
  195999. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  196000. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  196001. sqlite3_step(p->pDeleter);
  196002. p->rc = sqlite3_reset(p->pDeleter);
  196003. }
  196004. /*
  196005. ** Remove all records associated with segment iSegid.
  196006. */
  196007. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  196008. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  196009. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  196010. fts5DataDelete(p, iFirst, iLast);
  196011. if( p->pIdxDeleter==0 ){
  196012. Fts5Config *pConfig = p->pConfig;
  196013. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  196014. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  196015. pConfig->zDb, pConfig->zName
  196016. ));
  196017. }
  196018. if( p->rc==SQLITE_OK ){
  196019. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  196020. sqlite3_step(p->pIdxDeleter);
  196021. p->rc = sqlite3_reset(p->pIdxDeleter);
  196022. }
  196023. }
  196024. /*
  196025. ** Release a reference to an Fts5Structure object returned by an earlier
  196026. ** call to fts5StructureRead() or fts5StructureDecode().
  196027. */
  196028. static void fts5StructureRelease(Fts5Structure *pStruct){
  196029. if( pStruct && 0>=(--pStruct->nRef) ){
  196030. int i;
  196031. assert( pStruct->nRef==0 );
  196032. for(i=0; i<pStruct->nLevel; i++){
  196033. sqlite3_free(pStruct->aLevel[i].aSeg);
  196034. }
  196035. sqlite3_free(pStruct);
  196036. }
  196037. }
  196038. static void fts5StructureRef(Fts5Structure *pStruct){
  196039. pStruct->nRef++;
  196040. }
  196041. /*
  196042. ** Deserialize and return the structure record currently stored in serialized
  196043. ** form within buffer pData/nData.
  196044. **
  196045. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  196046. ** are over-allocated by one slot. This allows the structure contents
  196047. ** to be more easily edited.
  196048. **
  196049. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  196050. ** returned. Otherwise, *ppOut is set to point to the new object and
  196051. ** SQLITE_OK returned.
  196052. */
  196053. static int fts5StructureDecode(
  196054. const u8 *pData, /* Buffer containing serialized structure */
  196055. int nData, /* Size of buffer pData in bytes */
  196056. int *piCookie, /* Configuration cookie value */
  196057. Fts5Structure **ppOut /* OUT: Deserialized object */
  196058. ){
  196059. int rc = SQLITE_OK;
  196060. int i = 0;
  196061. int iLvl;
  196062. int nLevel = 0;
  196063. int nSegment = 0;
  196064. sqlite3_int64 nByte; /* Bytes of space to allocate at pRet */
  196065. Fts5Structure *pRet = 0; /* Structure object to return */
  196066. /* Grab the cookie value */
  196067. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  196068. i = 4;
  196069. /* Read the total number of levels and segments from the start of the
  196070. ** structure record. */
  196071. i += fts5GetVarint32(&pData[i], nLevel);
  196072. i += fts5GetVarint32(&pData[i], nSegment);
  196073. if( nLevel>FTS5_MAX_SEGMENT || nLevel<0
  196074. || nSegment>FTS5_MAX_SEGMENT || nSegment<0
  196075. ){
  196076. return FTS5_CORRUPT;
  196077. }
  196078. nByte = (
  196079. sizeof(Fts5Structure) + /* Main structure */
  196080. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  196081. );
  196082. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  196083. if( pRet ){
  196084. pRet->nRef = 1;
  196085. pRet->nLevel = nLevel;
  196086. pRet->nSegment = nSegment;
  196087. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  196088. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  196089. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  196090. int nTotal = 0;
  196091. int iSeg;
  196092. if( i>=nData ){
  196093. rc = FTS5_CORRUPT;
  196094. }else{
  196095. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  196096. i += fts5GetVarint32(&pData[i], nTotal);
  196097. if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
  196098. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  196099. nTotal * sizeof(Fts5StructureSegment)
  196100. );
  196101. nSegment -= nTotal;
  196102. }
  196103. if( rc==SQLITE_OK ){
  196104. pLvl->nSeg = nTotal;
  196105. for(iSeg=0; iSeg<nTotal; iSeg++){
  196106. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  196107. if( i>=nData ){
  196108. rc = FTS5_CORRUPT;
  196109. break;
  196110. }
  196111. i += fts5GetVarint32(&pData[i], pSeg->iSegid);
  196112. i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst);
  196113. i += fts5GetVarint32(&pData[i], pSeg->pgnoLast);
  196114. if( pSeg->pgnoLast<pSeg->pgnoFirst ){
  196115. rc = FTS5_CORRUPT;
  196116. break;
  196117. }
  196118. }
  196119. if( iLvl>0 && pLvl[-1].nMerge && nTotal==0 ) rc = FTS5_CORRUPT;
  196120. if( iLvl==nLevel-1 && pLvl->nMerge ) rc = FTS5_CORRUPT;
  196121. }
  196122. }
  196123. if( nSegment!=0 && rc==SQLITE_OK ) rc = FTS5_CORRUPT;
  196124. if( rc!=SQLITE_OK ){
  196125. fts5StructureRelease(pRet);
  196126. pRet = 0;
  196127. }
  196128. }
  196129. *ppOut = pRet;
  196130. return rc;
  196131. }
  196132. /*
  196133. **
  196134. */
  196135. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  196136. if( *pRc==SQLITE_OK ){
  196137. Fts5Structure *pStruct = *ppStruct;
  196138. int nLevel = pStruct->nLevel;
  196139. sqlite3_int64 nByte = (
  196140. sizeof(Fts5Structure) + /* Main structure */
  196141. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  196142. );
  196143. pStruct = sqlite3_realloc64(pStruct, nByte);
  196144. if( pStruct ){
  196145. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  196146. pStruct->nLevel++;
  196147. *ppStruct = pStruct;
  196148. }else{
  196149. *pRc = SQLITE_NOMEM;
  196150. }
  196151. }
  196152. }
  196153. /*
  196154. ** Extend level iLvl so that there is room for at least nExtra more
  196155. ** segments.
  196156. */
  196157. static void fts5StructureExtendLevel(
  196158. int *pRc,
  196159. Fts5Structure *pStruct,
  196160. int iLvl,
  196161. int nExtra,
  196162. int bInsert
  196163. ){
  196164. if( *pRc==SQLITE_OK ){
  196165. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  196166. Fts5StructureSegment *aNew;
  196167. sqlite3_int64 nByte;
  196168. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  196169. aNew = sqlite3_realloc64(pLvl->aSeg, nByte);
  196170. if( aNew ){
  196171. if( bInsert==0 ){
  196172. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  196173. }else{
  196174. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  196175. memmove(&aNew[nExtra], aNew, nMove);
  196176. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  196177. }
  196178. pLvl->aSeg = aNew;
  196179. }else{
  196180. *pRc = SQLITE_NOMEM;
  196181. }
  196182. }
  196183. }
  196184. static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
  196185. Fts5Structure *pRet = 0;
  196186. Fts5Config *pConfig = p->pConfig;
  196187. int iCookie; /* Configuration cookie */
  196188. Fts5Data *pData;
  196189. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  196190. if( p->rc==SQLITE_OK ){
  196191. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  196192. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  196193. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  196194. if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
  196195. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  196196. }
  196197. fts5DataRelease(pData);
  196198. if( p->rc!=SQLITE_OK ){
  196199. fts5StructureRelease(pRet);
  196200. pRet = 0;
  196201. }
  196202. }
  196203. return pRet;
  196204. }
  196205. static i64 fts5IndexDataVersion(Fts5Index *p){
  196206. i64 iVersion = 0;
  196207. if( p->rc==SQLITE_OK ){
  196208. if( p->pDataVersion==0 ){
  196209. p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
  196210. sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
  196211. );
  196212. if( p->rc ) return 0;
  196213. }
  196214. if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
  196215. iVersion = sqlite3_column_int64(p->pDataVersion, 0);
  196216. }
  196217. p->rc = sqlite3_reset(p->pDataVersion);
  196218. }
  196219. return iVersion;
  196220. }
  196221. /*
  196222. ** Read, deserialize and return the structure record.
  196223. **
  196224. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  196225. ** are over-allocated as described for function fts5StructureDecode()
  196226. ** above.
  196227. **
  196228. ** If an error occurs, NULL is returned and an error code left in the
  196229. ** Fts5Index handle. If an error has already occurred when this function
  196230. ** is called, it is a no-op.
  196231. */
  196232. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  196233. if( p->pStruct==0 ){
  196234. p->iStructVersion = fts5IndexDataVersion(p);
  196235. if( p->rc==SQLITE_OK ){
  196236. p->pStruct = fts5StructureReadUncached(p);
  196237. }
  196238. }
  196239. #if 0
  196240. else{
  196241. Fts5Structure *pTest = fts5StructureReadUncached(p);
  196242. if( pTest ){
  196243. int i, j;
  196244. assert_nc( p->pStruct->nSegment==pTest->nSegment );
  196245. assert_nc( p->pStruct->nLevel==pTest->nLevel );
  196246. for(i=0; i<pTest->nLevel; i++){
  196247. assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
  196248. assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
  196249. for(j=0; j<pTest->aLevel[i].nSeg; j++){
  196250. Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
  196251. Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
  196252. assert_nc( p1->iSegid==p2->iSegid );
  196253. assert_nc( p1->pgnoFirst==p2->pgnoFirst );
  196254. assert_nc( p1->pgnoLast==p2->pgnoLast );
  196255. }
  196256. }
  196257. fts5StructureRelease(pTest);
  196258. }
  196259. }
  196260. #endif
  196261. if( p->rc!=SQLITE_OK ) return 0;
  196262. assert( p->iStructVersion!=0 );
  196263. assert( p->pStruct!=0 );
  196264. fts5StructureRef(p->pStruct);
  196265. return p->pStruct;
  196266. }
  196267. static void fts5StructureInvalidate(Fts5Index *p){
  196268. if( p->pStruct ){
  196269. fts5StructureRelease(p->pStruct);
  196270. p->pStruct = 0;
  196271. }
  196272. }
  196273. /*
  196274. ** Return the total number of segments in index structure pStruct. This
  196275. ** function is only ever used as part of assert() conditions.
  196276. */
  196277. #ifdef SQLITE_DEBUG
  196278. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  196279. int nSegment = 0; /* Total number of segments */
  196280. if( pStruct ){
  196281. int iLvl; /* Used to iterate through levels */
  196282. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  196283. nSegment += pStruct->aLevel[iLvl].nSeg;
  196284. }
  196285. }
  196286. return nSegment;
  196287. }
  196288. #endif
  196289. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  196290. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  196291. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  196292. (pBuf)->n += nBlob; \
  196293. }
  196294. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  196295. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  196296. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  196297. }
  196298. /*
  196299. ** Serialize and store the "structure" record.
  196300. **
  196301. ** If an error occurs, leave an error code in the Fts5Index object. If an
  196302. ** error has already occurred, this function is a no-op.
  196303. */
  196304. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  196305. if( p->rc==SQLITE_OK ){
  196306. Fts5Buffer buf; /* Buffer to serialize record into */
  196307. int iLvl; /* Used to iterate through levels */
  196308. int iCookie; /* Cookie value to store */
  196309. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  196310. memset(&buf, 0, sizeof(Fts5Buffer));
  196311. /* Append the current configuration cookie */
  196312. iCookie = p->pConfig->iCookie;
  196313. if( iCookie<0 ) iCookie = 0;
  196314. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
  196315. sqlite3Fts5Put32(buf.p, iCookie);
  196316. buf.n = 4;
  196317. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  196318. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  196319. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  196320. }
  196321. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  196322. int iSeg; /* Used to iterate through segments */
  196323. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  196324. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  196325. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  196326. assert( pLvl->nMerge<=pLvl->nSeg );
  196327. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  196328. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  196329. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  196330. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  196331. }
  196332. }
  196333. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  196334. fts5BufferFree(&buf);
  196335. }
  196336. }
  196337. #if 0
  196338. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  196339. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  196340. int rc = SQLITE_OK;
  196341. Fts5Buffer buf;
  196342. memset(&buf, 0, sizeof(buf));
  196343. fts5DebugStructure(&rc, &buf, pStruct);
  196344. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  196345. fflush(stdout);
  196346. fts5BufferFree(&buf);
  196347. }
  196348. #else
  196349. # define fts5PrintStructure(x,y)
  196350. #endif
  196351. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  196352. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  196353. }
  196354. /*
  196355. ** Return a copy of index structure pStruct. Except, promote as many
  196356. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  196357. ** returned.
  196358. */
  196359. static void fts5StructurePromoteTo(
  196360. Fts5Index *p,
  196361. int iPromote,
  196362. int szPromote,
  196363. Fts5Structure *pStruct
  196364. ){
  196365. int il, is;
  196366. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  196367. if( pOut->nMerge==0 ){
  196368. for(il=iPromote+1; il<pStruct->nLevel; il++){
  196369. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  196370. if( pLvl->nMerge ) return;
  196371. for(is=pLvl->nSeg-1; is>=0; is--){
  196372. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  196373. if( sz>szPromote ) return;
  196374. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  196375. if( p->rc ) return;
  196376. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  196377. pOut->nSeg++;
  196378. pLvl->nSeg--;
  196379. }
  196380. }
  196381. }
  196382. }
  196383. /*
  196384. ** A new segment has just been written to level iLvl of index structure
  196385. ** pStruct. This function determines if any segments should be promoted
  196386. ** as a result. Segments are promoted in two scenarios:
  196387. **
  196388. ** a) If the segment just written is smaller than one or more segments
  196389. ** within the previous populated level, it is promoted to the previous
  196390. ** populated level.
  196391. **
  196392. ** b) If the segment just written is larger than the newest segment on
  196393. ** the next populated level, then that segment, and any other adjacent
  196394. ** segments that are also smaller than the one just written, are
  196395. ** promoted.
  196396. **
  196397. ** If one or more segments are promoted, the structure object is updated
  196398. ** to reflect this.
  196399. */
  196400. static void fts5StructurePromote(
  196401. Fts5Index *p, /* FTS5 backend object */
  196402. int iLvl, /* Index level just updated */
  196403. Fts5Structure *pStruct /* Index structure */
  196404. ){
  196405. if( p->rc==SQLITE_OK ){
  196406. int iTst;
  196407. int iPromote = -1;
  196408. int szPromote = 0; /* Promote anything this size or smaller */
  196409. Fts5StructureSegment *pSeg; /* Segment just written */
  196410. int szSeg; /* Size of segment just written */
  196411. int nSeg = pStruct->aLevel[iLvl].nSeg;
  196412. if( nSeg==0 ) return;
  196413. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  196414. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  196415. /* Check for condition (a) */
  196416. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  196417. if( iTst>=0 ){
  196418. int i;
  196419. int szMax = 0;
  196420. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  196421. assert( pTst->nMerge==0 );
  196422. for(i=0; i<pTst->nSeg; i++){
  196423. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  196424. if( sz>szMax ) szMax = sz;
  196425. }
  196426. if( szMax>=szSeg ){
  196427. /* Condition (a) is true. Promote the newest segment on level
  196428. ** iLvl to level iTst. */
  196429. iPromote = iTst;
  196430. szPromote = szMax;
  196431. }
  196432. }
  196433. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  196434. ** is a no-op if it is not. */
  196435. if( iPromote<0 ){
  196436. iPromote = iLvl;
  196437. szPromote = szSeg;
  196438. }
  196439. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  196440. }
  196441. }
  196442. /*
  196443. ** Advance the iterator passed as the only argument. If the end of the
  196444. ** doclist-index page is reached, return non-zero.
  196445. */
  196446. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  196447. Fts5Data *pData = pLvl->pData;
  196448. if( pLvl->iOff==0 ){
  196449. assert( pLvl->bEof==0 );
  196450. pLvl->iOff = 1;
  196451. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  196452. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  196453. pLvl->iFirstOff = pLvl->iOff;
  196454. }else{
  196455. int iOff;
  196456. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  196457. if( pData->p[iOff] ) break;
  196458. }
  196459. if( iOff<pData->nn ){
  196460. i64 iVal;
  196461. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  196462. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  196463. pLvl->iRowid += iVal;
  196464. pLvl->iOff = iOff;
  196465. }else{
  196466. pLvl->bEof = 1;
  196467. }
  196468. }
  196469. return pLvl->bEof;
  196470. }
  196471. /*
  196472. ** Advance the iterator passed as the only argument.
  196473. */
  196474. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  196475. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  196476. assert( iLvl<pIter->nLvl );
  196477. if( fts5DlidxLvlNext(pLvl) ){
  196478. if( (iLvl+1) < pIter->nLvl ){
  196479. fts5DlidxIterNextR(p, pIter, iLvl+1);
  196480. if( pLvl[1].bEof==0 ){
  196481. fts5DataRelease(pLvl->pData);
  196482. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  196483. pLvl->pData = fts5DataRead(p,
  196484. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  196485. );
  196486. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  196487. }
  196488. }
  196489. }
  196490. return pIter->aLvl[0].bEof;
  196491. }
  196492. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  196493. return fts5DlidxIterNextR(p, pIter, 0);
  196494. }
  196495. /*
  196496. ** The iterator passed as the first argument has the following fields set
  196497. ** as follows. This function sets up the rest of the iterator so that it
  196498. ** points to the first rowid in the doclist-index.
  196499. **
  196500. ** pData:
  196501. ** pointer to doclist-index record,
  196502. **
  196503. ** When this function is called pIter->iLeafPgno is the page number the
  196504. ** doclist is associated with (the one featuring the term).
  196505. */
  196506. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  196507. int i;
  196508. for(i=0; i<pIter->nLvl; i++){
  196509. fts5DlidxLvlNext(&pIter->aLvl[i]);
  196510. }
  196511. return pIter->aLvl[0].bEof;
  196512. }
  196513. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  196514. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  196515. }
  196516. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  196517. int i;
  196518. /* Advance each level to the last entry on the last page */
  196519. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  196520. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  196521. while( fts5DlidxLvlNext(pLvl)==0 );
  196522. pLvl->bEof = 0;
  196523. if( i>0 ){
  196524. Fts5DlidxLvl *pChild = &pLvl[-1];
  196525. fts5DataRelease(pChild->pData);
  196526. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  196527. pChild->pData = fts5DataRead(p,
  196528. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  196529. );
  196530. }
  196531. }
  196532. }
  196533. /*
  196534. ** Move the iterator passed as the only argument to the previous entry.
  196535. */
  196536. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  196537. int iOff = pLvl->iOff;
  196538. assert( pLvl->bEof==0 );
  196539. if( iOff<=pLvl->iFirstOff ){
  196540. pLvl->bEof = 1;
  196541. }else{
  196542. u8 *a = pLvl->pData->p;
  196543. i64 iVal;
  196544. int iLimit;
  196545. int ii;
  196546. int nZero = 0;
  196547. /* Currently iOff points to the first byte of a varint. This block
  196548. ** decrements iOff until it points to the first byte of the previous
  196549. ** varint. Taking care not to read any memory locations that occur
  196550. ** before the buffer in memory. */
  196551. iLimit = (iOff>9 ? iOff-9 : 0);
  196552. for(iOff--; iOff>iLimit; iOff--){
  196553. if( (a[iOff-1] & 0x80)==0 ) break;
  196554. }
  196555. fts5GetVarint(&a[iOff], (u64*)&iVal);
  196556. pLvl->iRowid -= iVal;
  196557. pLvl->iLeafPgno--;
  196558. /* Skip backwards past any 0x00 varints. */
  196559. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  196560. nZero++;
  196561. }
  196562. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  196563. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  196564. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  196565. ** bytes before a[ii]. */
  196566. int bZero = 0; /* True if last 0x00 counts */
  196567. if( (ii-8)>=pLvl->iFirstOff ){
  196568. int j;
  196569. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  196570. bZero = (j>8);
  196571. }
  196572. if( bZero==0 ) nZero--;
  196573. }
  196574. pLvl->iLeafPgno -= nZero;
  196575. pLvl->iOff = iOff - nZero;
  196576. }
  196577. return pLvl->bEof;
  196578. }
  196579. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  196580. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  196581. assert( iLvl<pIter->nLvl );
  196582. if( fts5DlidxLvlPrev(pLvl) ){
  196583. if( (iLvl+1) < pIter->nLvl ){
  196584. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  196585. if( pLvl[1].bEof==0 ){
  196586. fts5DataRelease(pLvl->pData);
  196587. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  196588. pLvl->pData = fts5DataRead(p,
  196589. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  196590. );
  196591. if( pLvl->pData ){
  196592. while( fts5DlidxLvlNext(pLvl)==0 );
  196593. pLvl->bEof = 0;
  196594. }
  196595. }
  196596. }
  196597. }
  196598. return pIter->aLvl[0].bEof;
  196599. }
  196600. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  196601. return fts5DlidxIterPrevR(p, pIter, 0);
  196602. }
  196603. /*
  196604. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  196605. */
  196606. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  196607. if( pIter ){
  196608. int i;
  196609. for(i=0; i<pIter->nLvl; i++){
  196610. fts5DataRelease(pIter->aLvl[i].pData);
  196611. }
  196612. sqlite3_free(pIter);
  196613. }
  196614. }
  196615. static Fts5DlidxIter *fts5DlidxIterInit(
  196616. Fts5Index *p, /* Fts5 Backend to iterate within */
  196617. int bRev, /* True for ORDER BY ASC */
  196618. int iSegid, /* Segment id */
  196619. int iLeafPg /* Leaf page number to load dlidx for */
  196620. ){
  196621. Fts5DlidxIter *pIter = 0;
  196622. int i;
  196623. int bDone = 0;
  196624. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  196625. sqlite3_int64 nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  196626. Fts5DlidxIter *pNew;
  196627. pNew = (Fts5DlidxIter*)sqlite3_realloc64(pIter, nByte);
  196628. if( pNew==0 ){
  196629. p->rc = SQLITE_NOMEM;
  196630. }else{
  196631. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  196632. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  196633. pIter = pNew;
  196634. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  196635. pLvl->pData = fts5DataRead(p, iRowid);
  196636. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  196637. bDone = 1;
  196638. }
  196639. pIter->nLvl = i+1;
  196640. }
  196641. }
  196642. if( p->rc==SQLITE_OK ){
  196643. pIter->iSegid = iSegid;
  196644. if( bRev==0 ){
  196645. fts5DlidxIterFirst(pIter);
  196646. }else{
  196647. fts5DlidxIterLast(p, pIter);
  196648. }
  196649. }
  196650. if( p->rc!=SQLITE_OK ){
  196651. fts5DlidxIterFree(pIter);
  196652. pIter = 0;
  196653. }
  196654. return pIter;
  196655. }
  196656. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  196657. return pIter->aLvl[0].iRowid;
  196658. }
  196659. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  196660. return pIter->aLvl[0].iLeafPgno;
  196661. }
  196662. /*
  196663. ** Load the next leaf page into the segment iterator.
  196664. */
  196665. static void fts5SegIterNextPage(
  196666. Fts5Index *p, /* FTS5 backend object */
  196667. Fts5SegIter *pIter /* Iterator to advance to next page */
  196668. ){
  196669. Fts5Data *pLeaf;
  196670. Fts5StructureSegment *pSeg = pIter->pSeg;
  196671. fts5DataRelease(pIter->pLeaf);
  196672. pIter->iLeafPgno++;
  196673. if( pIter->pNextLeaf ){
  196674. pIter->pLeaf = pIter->pNextLeaf;
  196675. pIter->pNextLeaf = 0;
  196676. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  196677. pIter->pLeaf = fts5LeafRead(p,
  196678. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  196679. );
  196680. }else{
  196681. pIter->pLeaf = 0;
  196682. }
  196683. pLeaf = pIter->pLeaf;
  196684. if( pLeaf ){
  196685. pIter->iPgidxOff = pLeaf->szLeaf;
  196686. if( fts5LeafIsTermless(pLeaf) ){
  196687. pIter->iEndofDoclist = pLeaf->nn+1;
  196688. }else{
  196689. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  196690. pIter->iEndofDoclist
  196691. );
  196692. }
  196693. }
  196694. }
  196695. /*
  196696. ** Argument p points to a buffer containing a varint to be interpreted as a
  196697. ** position list size field. Read the varint and return the number of bytes
  196698. ** read. Before returning, set *pnSz to the number of bytes in the position
  196699. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  196700. */
  196701. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  196702. int nSz;
  196703. int n = 0;
  196704. fts5FastGetVarint32(p, n, nSz);
  196705. assert_nc( nSz>=0 );
  196706. *pnSz = nSz/2;
  196707. *pbDel = nSz & 0x0001;
  196708. return n;
  196709. }
  196710. /*
  196711. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  196712. ** position-list size field. Read the value of the field and store it
  196713. ** in the following variables:
  196714. **
  196715. ** Fts5SegIter.nPos
  196716. ** Fts5SegIter.bDel
  196717. **
  196718. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  196719. ** position list content (if any).
  196720. */
  196721. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  196722. if( p->rc==SQLITE_OK ){
  196723. int iOff = pIter->iLeafOffset; /* Offset to read at */
  196724. ASSERT_SZLEAF_OK(pIter->pLeaf);
  196725. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  196726. int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
  196727. pIter->bDel = 0;
  196728. pIter->nPos = 1;
  196729. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  196730. pIter->bDel = 1;
  196731. iOff++;
  196732. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  196733. pIter->nPos = 1;
  196734. iOff++;
  196735. }else{
  196736. pIter->nPos = 0;
  196737. }
  196738. }
  196739. }else{
  196740. int nSz;
  196741. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  196742. pIter->bDel = (nSz & 0x0001);
  196743. pIter->nPos = nSz>>1;
  196744. assert_nc( pIter->nPos>=0 );
  196745. }
  196746. pIter->iLeafOffset = iOff;
  196747. }
  196748. }
  196749. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  196750. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  196751. int iOff = pIter->iLeafOffset;
  196752. ASSERT_SZLEAF_OK(pIter->pLeaf);
  196753. if( iOff>=pIter->pLeaf->szLeaf ){
  196754. fts5SegIterNextPage(p, pIter);
  196755. if( pIter->pLeaf==0 ){
  196756. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  196757. return;
  196758. }
  196759. iOff = 4;
  196760. a = pIter->pLeaf->p;
  196761. }
  196762. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  196763. pIter->iLeafOffset = iOff;
  196764. }
  196765. /*
  196766. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  196767. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  196768. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  196769. ** the first term in the segment).
  196770. **
  196771. ** This function populates:
  196772. **
  196773. ** Fts5SegIter.term
  196774. ** Fts5SegIter.rowid
  196775. **
  196776. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  196777. ** the first position list. The position list belonging to document
  196778. ** (Fts5SegIter.iRowid).
  196779. */
  196780. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  196781. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  196782. int iOff = pIter->iLeafOffset; /* Offset to read at */
  196783. int nNew; /* Bytes of new data */
  196784. iOff += fts5GetVarint32(&a[iOff], nNew);
  196785. if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){
  196786. p->rc = FTS5_CORRUPT;
  196787. return;
  196788. }
  196789. pIter->term.n = nKeep;
  196790. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  196791. assert( pIter->term.n<=pIter->term.nSpace );
  196792. iOff += nNew;
  196793. pIter->iTermLeafOffset = iOff;
  196794. pIter->iTermLeafPgno = pIter->iLeafPgno;
  196795. pIter->iLeafOffset = iOff;
  196796. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  196797. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  196798. }else{
  196799. int nExtra;
  196800. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  196801. pIter->iEndofDoclist += nExtra;
  196802. }
  196803. fts5SegIterLoadRowid(p, pIter);
  196804. }
  196805. static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
  196806. static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
  196807. static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
  196808. static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
  196809. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  196810. pIter->xNext = fts5SegIterNext_Reverse;
  196811. }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  196812. pIter->xNext = fts5SegIterNext_None;
  196813. }else{
  196814. pIter->xNext = fts5SegIterNext;
  196815. }
  196816. }
  196817. /*
  196818. ** Initialize the iterator object pIter to iterate through the entries in
  196819. ** segment pSeg. The iterator is left pointing to the first entry when
  196820. ** this function returns.
  196821. **
  196822. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  196823. ** an error has already occurred when this function is called, it is a no-op.
  196824. */
  196825. static void fts5SegIterInit(
  196826. Fts5Index *p, /* FTS index object */
  196827. Fts5StructureSegment *pSeg, /* Description of segment */
  196828. Fts5SegIter *pIter /* Object to populate */
  196829. ){
  196830. if( pSeg->pgnoFirst==0 ){
  196831. /* This happens if the segment is being used as an input to an incremental
  196832. ** merge and all data has already been "trimmed". See function
  196833. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  196834. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  196835. ** at EOF already. */
  196836. assert( pIter->pLeaf==0 );
  196837. return;
  196838. }
  196839. if( p->rc==SQLITE_OK ){
  196840. memset(pIter, 0, sizeof(*pIter));
  196841. fts5SegIterSetNext(p, pIter);
  196842. pIter->pSeg = pSeg;
  196843. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  196844. fts5SegIterNextPage(p, pIter);
  196845. }
  196846. if( p->rc==SQLITE_OK ){
  196847. pIter->iLeafOffset = 4;
  196848. assert_nc( pIter->pLeaf->nn>4 );
  196849. assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  196850. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  196851. fts5SegIterLoadTerm(p, pIter, 0);
  196852. fts5SegIterLoadNPos(p, pIter);
  196853. }
  196854. }
  196855. /*
  196856. ** This function is only ever called on iterators created by calls to
  196857. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  196858. **
  196859. ** The iterator is in an unusual state when this function is called: the
  196860. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  196861. ** the position-list size field for the first relevant rowid on the page.
  196862. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  196863. **
  196864. ** This function advances the iterator so that it points to the last
  196865. ** relevant rowid on the page and, if necessary, initializes the
  196866. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  196867. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  196868. ** byte of the position list content associated with said rowid.
  196869. */
  196870. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  196871. int eDetail = p->pConfig->eDetail;
  196872. int n = pIter->pLeaf->szLeaf;
  196873. int i = pIter->iLeafOffset;
  196874. u8 *a = pIter->pLeaf->p;
  196875. int iRowidOffset = 0;
  196876. if( n>pIter->iEndofDoclist ){
  196877. n = pIter->iEndofDoclist;
  196878. }
  196879. ASSERT_SZLEAF_OK(pIter->pLeaf);
  196880. while( 1 ){
  196881. i64 iDelta = 0;
  196882. if( eDetail==FTS5_DETAIL_NONE ){
  196883. /* todo */
  196884. if( i<n && a[i]==0 ){
  196885. i++;
  196886. if( i<n && a[i]==0 ) i++;
  196887. }
  196888. }else{
  196889. int nPos;
  196890. int bDummy;
  196891. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  196892. i += nPos;
  196893. }
  196894. if( i>=n ) break;
  196895. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  196896. pIter->iRowid += iDelta;
  196897. /* If necessary, grow the pIter->aRowidOffset[] array. */
  196898. if( iRowidOffset>=pIter->nRowidOffset ){
  196899. int nNew = pIter->nRowidOffset + 8;
  196900. int *aNew = (int*)sqlite3_realloc64(pIter->aRowidOffset,nNew*sizeof(int));
  196901. if( aNew==0 ){
  196902. p->rc = SQLITE_NOMEM;
  196903. break;
  196904. }
  196905. pIter->aRowidOffset = aNew;
  196906. pIter->nRowidOffset = nNew;
  196907. }
  196908. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  196909. pIter->iLeafOffset = i;
  196910. }
  196911. pIter->iRowidOffset = iRowidOffset;
  196912. fts5SegIterLoadNPos(p, pIter);
  196913. }
  196914. /*
  196915. **
  196916. */
  196917. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  196918. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  196919. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  196920. fts5DataRelease(pIter->pLeaf);
  196921. pIter->pLeaf = 0;
  196922. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  196923. Fts5Data *pNew;
  196924. pIter->iLeafPgno--;
  196925. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  196926. pIter->pSeg->iSegid, pIter->iLeafPgno
  196927. ));
  196928. if( pNew ){
  196929. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  196930. ** thing on the page - i.e. the first rowid is on the following page.
  196931. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  196932. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  196933. assert( pIter->pLeaf==0 );
  196934. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  196935. pIter->pLeaf = pNew;
  196936. pIter->iLeafOffset = pIter->iTermLeafOffset;
  196937. }
  196938. }else{
  196939. int iRowidOff;
  196940. iRowidOff = fts5LeafFirstRowidOff(pNew);
  196941. if( iRowidOff ){
  196942. pIter->pLeaf = pNew;
  196943. pIter->iLeafOffset = iRowidOff;
  196944. }
  196945. }
  196946. if( pIter->pLeaf ){
  196947. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  196948. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  196949. break;
  196950. }else{
  196951. fts5DataRelease(pNew);
  196952. }
  196953. }
  196954. }
  196955. if( pIter->pLeaf ){
  196956. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  196957. fts5SegIterReverseInitPage(p, pIter);
  196958. }
  196959. }
  196960. /*
  196961. ** Return true if the iterator passed as the second argument currently
  196962. ** points to a delete marker. A delete marker is an entry with a 0 byte
  196963. ** position-list.
  196964. */
  196965. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
  196966. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  196967. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  196968. }
  196969. /*
  196970. ** Advance iterator pIter to the next entry.
  196971. **
  196972. ** This version of fts5SegIterNext() is only used by reverse iterators.
  196973. */
  196974. static void fts5SegIterNext_Reverse(
  196975. Fts5Index *p, /* FTS5 backend object */
  196976. Fts5SegIter *pIter, /* Iterator to advance */
  196977. int *pbUnused /* Unused */
  196978. ){
  196979. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  196980. assert( pIter->pNextLeaf==0 );
  196981. UNUSED_PARAM(pbUnused);
  196982. if( pIter->iRowidOffset>0 ){
  196983. u8 *a = pIter->pLeaf->p;
  196984. int iOff;
  196985. i64 iDelta;
  196986. pIter->iRowidOffset--;
  196987. pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
  196988. fts5SegIterLoadNPos(p, pIter);
  196989. iOff = pIter->iLeafOffset;
  196990. if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
  196991. iOff += pIter->nPos;
  196992. }
  196993. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  196994. pIter->iRowid -= iDelta;
  196995. }else{
  196996. fts5SegIterReverseNewPage(p, pIter);
  196997. }
  196998. }
  196999. /*
  197000. ** Advance iterator pIter to the next entry.
  197001. **
  197002. ** This version of fts5SegIterNext() is only used if detail=none and the
  197003. ** iterator is not a reverse direction iterator.
  197004. */
  197005. static void fts5SegIterNext_None(
  197006. Fts5Index *p, /* FTS5 backend object */
  197007. Fts5SegIter *pIter, /* Iterator to advance */
  197008. int *pbNewTerm /* OUT: Set for new term */
  197009. ){
  197010. int iOff;
  197011. assert( p->rc==SQLITE_OK );
  197012. assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  197013. assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
  197014. ASSERT_SZLEAF_OK(pIter->pLeaf);
  197015. iOff = pIter->iLeafOffset;
  197016. /* Next entry is on the next page */
  197017. if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
  197018. fts5SegIterNextPage(p, pIter);
  197019. if( p->rc || pIter->pLeaf==0 ) return;
  197020. pIter->iRowid = 0;
  197021. iOff = 4;
  197022. }
  197023. if( iOff<pIter->iEndofDoclist ){
  197024. /* Next entry is on the current page */
  197025. i64 iDelta;
  197026. iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
  197027. pIter->iLeafOffset = iOff;
  197028. pIter->iRowid += iDelta;
  197029. }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
  197030. if( pIter->pSeg ){
  197031. int nKeep = 0;
  197032. if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
  197033. iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
  197034. }
  197035. pIter->iLeafOffset = iOff;
  197036. fts5SegIterLoadTerm(p, pIter, nKeep);
  197037. }else{
  197038. const u8 *pList = 0;
  197039. const char *zTerm = 0;
  197040. int nList;
  197041. sqlite3Fts5HashScanNext(p->pHash);
  197042. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  197043. if( pList==0 ) goto next_none_eof;
  197044. pIter->pLeaf->p = (u8*)pList;
  197045. pIter->pLeaf->nn = nList;
  197046. pIter->pLeaf->szLeaf = nList;
  197047. pIter->iEndofDoclist = nList;
  197048. sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
  197049. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  197050. }
  197051. if( pbNewTerm ) *pbNewTerm = 1;
  197052. }else{
  197053. goto next_none_eof;
  197054. }
  197055. fts5SegIterLoadNPos(p, pIter);
  197056. return;
  197057. next_none_eof:
  197058. fts5DataRelease(pIter->pLeaf);
  197059. pIter->pLeaf = 0;
  197060. }
  197061. /*
  197062. ** Advance iterator pIter to the next entry.
  197063. **
  197064. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  197065. ** is not considered an error if the iterator reaches EOF. If an error has
  197066. ** already occurred when this function is called, it is a no-op.
  197067. */
  197068. static void fts5SegIterNext(
  197069. Fts5Index *p, /* FTS5 backend object */
  197070. Fts5SegIter *pIter, /* Iterator to advance */
  197071. int *pbNewTerm /* OUT: Set for new term */
  197072. ){
  197073. Fts5Data *pLeaf = pIter->pLeaf;
  197074. int iOff;
  197075. int bNewTerm = 0;
  197076. int nKeep = 0;
  197077. u8 *a;
  197078. int n;
  197079. assert( pbNewTerm==0 || *pbNewTerm==0 );
  197080. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  197081. /* Search for the end of the position list within the current page. */
  197082. a = pLeaf->p;
  197083. n = pLeaf->szLeaf;
  197084. ASSERT_SZLEAF_OK(pLeaf);
  197085. iOff = pIter->iLeafOffset + pIter->nPos;
  197086. if( iOff<n ){
  197087. /* The next entry is on the current page. */
  197088. assert_nc( iOff<=pIter->iEndofDoclist );
  197089. if( iOff>=pIter->iEndofDoclist ){
  197090. bNewTerm = 1;
  197091. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  197092. iOff += fts5GetVarint32(&a[iOff], nKeep);
  197093. }
  197094. }else{
  197095. u64 iDelta;
  197096. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  197097. pIter->iRowid += iDelta;
  197098. assert_nc( iDelta>0 );
  197099. }
  197100. pIter->iLeafOffset = iOff;
  197101. }else if( pIter->pSeg==0 ){
  197102. const u8 *pList = 0;
  197103. const char *zTerm = 0;
  197104. int nList = 0;
  197105. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  197106. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  197107. sqlite3Fts5HashScanNext(p->pHash);
  197108. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  197109. }
  197110. if( pList==0 ){
  197111. fts5DataRelease(pIter->pLeaf);
  197112. pIter->pLeaf = 0;
  197113. }else{
  197114. pIter->pLeaf->p = (u8*)pList;
  197115. pIter->pLeaf->nn = nList;
  197116. pIter->pLeaf->szLeaf = nList;
  197117. pIter->iEndofDoclist = nList+1;
  197118. sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
  197119. (u8*)zTerm);
  197120. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  197121. *pbNewTerm = 1;
  197122. }
  197123. }else{
  197124. iOff = 0;
  197125. /* Next entry is not on the current page */
  197126. while( iOff==0 ){
  197127. fts5SegIterNextPage(p, pIter);
  197128. pLeaf = pIter->pLeaf;
  197129. if( pLeaf==0 ) break;
  197130. ASSERT_SZLEAF_OK(pLeaf);
  197131. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  197132. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  197133. pIter->iLeafOffset = iOff;
  197134. if( pLeaf->nn>pLeaf->szLeaf ){
  197135. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  197136. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  197137. );
  197138. }
  197139. }
  197140. else if( pLeaf->nn>pLeaf->szLeaf ){
  197141. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  197142. &pLeaf->p[pLeaf->szLeaf], iOff
  197143. );
  197144. pIter->iLeafOffset = iOff;
  197145. pIter->iEndofDoclist = iOff;
  197146. bNewTerm = 1;
  197147. }
  197148. assert_nc( iOff<pLeaf->szLeaf );
  197149. if( iOff>pLeaf->szLeaf ){
  197150. p->rc = FTS5_CORRUPT;
  197151. return;
  197152. }
  197153. }
  197154. }
  197155. /* Check if the iterator is now at EOF. If so, return early. */
  197156. if( pIter->pLeaf ){
  197157. if( bNewTerm ){
  197158. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  197159. fts5DataRelease(pIter->pLeaf);
  197160. pIter->pLeaf = 0;
  197161. }else{
  197162. fts5SegIterLoadTerm(p, pIter, nKeep);
  197163. fts5SegIterLoadNPos(p, pIter);
  197164. if( pbNewTerm ) *pbNewTerm = 1;
  197165. }
  197166. }else{
  197167. /* The following could be done by calling fts5SegIterLoadNPos(). But
  197168. ** this block is particularly performance critical, so equivalent
  197169. ** code is inlined.
  197170. **
  197171. ** Later: Switched back to fts5SegIterLoadNPos() because it supports
  197172. ** detail=none mode. Not ideal.
  197173. */
  197174. int nSz;
  197175. assert( p->rc==SQLITE_OK );
  197176. assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
  197177. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  197178. pIter->bDel = (nSz & 0x0001);
  197179. pIter->nPos = nSz>>1;
  197180. assert_nc( pIter->nPos>=0 );
  197181. }
  197182. }
  197183. }
  197184. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  197185. #define fts5IndexSkipVarint(a, iOff) { \
  197186. int iEnd = iOff+9; \
  197187. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  197188. }
  197189. /*
  197190. ** Iterator pIter currently points to the first rowid in a doclist. This
  197191. ** function sets the iterator up so that iterates in reverse order through
  197192. ** the doclist.
  197193. */
  197194. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  197195. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  197196. Fts5Data *pLast = 0;
  197197. int pgnoLast = 0;
  197198. if( pDlidx ){
  197199. int iSegid = pIter->pSeg->iSegid;
  197200. pgnoLast = fts5DlidxIterPgno(pDlidx);
  197201. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  197202. }else{
  197203. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  197204. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  197205. ** position-list content for the current rowid. Back it up so that it
  197206. ** points to the start of the position-list size field. */
  197207. int iPoslist;
  197208. if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
  197209. iPoslist = pIter->iTermLeafOffset;
  197210. }else{
  197211. iPoslist = 4;
  197212. }
  197213. fts5IndexSkipVarint(pLeaf->p, iPoslist);
  197214. pIter->iLeafOffset = iPoslist;
  197215. /* If this condition is true then the largest rowid for the current
  197216. ** term may not be stored on the current page. So search forward to
  197217. ** see where said rowid really is. */
  197218. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  197219. int pgno;
  197220. Fts5StructureSegment *pSeg = pIter->pSeg;
  197221. /* The last rowid in the doclist may not be on the current page. Search
  197222. ** forward to find the page containing the last rowid. */
  197223. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  197224. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  197225. Fts5Data *pNew = fts5DataRead(p, iAbs);
  197226. if( pNew ){
  197227. int iRowid, bTermless;
  197228. iRowid = fts5LeafFirstRowidOff(pNew);
  197229. bTermless = fts5LeafIsTermless(pNew);
  197230. if( iRowid ){
  197231. SWAPVAL(Fts5Data*, pNew, pLast);
  197232. pgnoLast = pgno;
  197233. }
  197234. fts5DataRelease(pNew);
  197235. if( bTermless==0 ) break;
  197236. }
  197237. }
  197238. }
  197239. }
  197240. /* If pLast is NULL at this point, then the last rowid for this doclist
  197241. ** lies on the page currently indicated by the iterator. In this case
  197242. ** pIter->iLeafOffset is already set to point to the position-list size
  197243. ** field associated with the first relevant rowid on the page.
  197244. **
  197245. ** Or, if pLast is non-NULL, then it is the page that contains the last
  197246. ** rowid. In this case configure the iterator so that it points to the
  197247. ** first rowid on this page.
  197248. */
  197249. if( pLast ){
  197250. int iOff;
  197251. fts5DataRelease(pIter->pLeaf);
  197252. pIter->pLeaf = pLast;
  197253. pIter->iLeafPgno = pgnoLast;
  197254. iOff = fts5LeafFirstRowidOff(pLast);
  197255. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  197256. pIter->iLeafOffset = iOff;
  197257. if( fts5LeafIsTermless(pLast) ){
  197258. pIter->iEndofDoclist = pLast->nn+1;
  197259. }else{
  197260. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  197261. }
  197262. }
  197263. fts5SegIterReverseInitPage(p, pIter);
  197264. }
  197265. /*
  197266. ** Iterator pIter currently points to the first rowid of a doclist.
  197267. ** There is a doclist-index associated with the final term on the current
  197268. ** page. If the current term is the last term on the page, load the
  197269. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  197270. */
  197271. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  197272. int iSeg = pIter->pSeg->iSegid;
  197273. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  197274. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  197275. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  197276. assert( pIter->pDlidx==0 );
  197277. /* Check if the current doclist ends on this page. If it does, return
  197278. ** early without loading the doclist-index (as it belongs to a different
  197279. ** term. */
  197280. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  197281. && pIter->iEndofDoclist<pLeaf->szLeaf
  197282. ){
  197283. return;
  197284. }
  197285. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  197286. }
  197287. /*
  197288. ** The iterator object passed as the second argument currently contains
  197289. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  197290. ** function searches the leaf page for a term matching (pTerm/nTerm).
  197291. **
  197292. ** If the specified term is found on the page, then the iterator is left
  197293. ** pointing to it. If argument bGe is zero and the term is not found,
  197294. ** the iterator is left pointing at EOF.
  197295. **
  197296. ** If bGe is non-zero and the specified term is not found, then the
  197297. ** iterator is left pointing to the smallest term in the segment that
  197298. ** is larger than the specified term, even if this term is not on the
  197299. ** current page.
  197300. */
  197301. static void fts5LeafSeek(
  197302. Fts5Index *p, /* Leave any error code here */
  197303. int bGe, /* True for a >= search */
  197304. Fts5SegIter *pIter, /* Iterator to seek */
  197305. const u8 *pTerm, int nTerm /* Term to search for */
  197306. ){
  197307. int iOff;
  197308. const u8 *a = pIter->pLeaf->p;
  197309. int szLeaf = pIter->pLeaf->szLeaf;
  197310. int n = pIter->pLeaf->nn;
  197311. u32 nMatch = 0;
  197312. u32 nKeep = 0;
  197313. u32 nNew = 0;
  197314. u32 iTermOff;
  197315. int iPgidx; /* Current offset in pgidx */
  197316. int bEndOfPage = 0;
  197317. assert( p->rc==SQLITE_OK );
  197318. iPgidx = szLeaf;
  197319. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  197320. iOff = iTermOff;
  197321. if( iOff>n ){
  197322. p->rc = FTS5_CORRUPT;
  197323. return;
  197324. }
  197325. while( 1 ){
  197326. /* Figure out how many new bytes are in this term */
  197327. fts5FastGetVarint32(a, iOff, nNew);
  197328. if( nKeep<nMatch ){
  197329. goto search_failed;
  197330. }
  197331. assert( nKeep>=nMatch );
  197332. if( nKeep==nMatch ){
  197333. u32 nCmp;
  197334. u32 i;
  197335. nCmp = (u32)MIN(nNew, nTerm-nMatch);
  197336. for(i=0; i<nCmp; i++){
  197337. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  197338. }
  197339. nMatch += i;
  197340. if( (u32)nTerm==nMatch ){
  197341. if( i==nNew ){
  197342. goto search_success;
  197343. }else{
  197344. goto search_failed;
  197345. }
  197346. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  197347. goto search_failed;
  197348. }
  197349. }
  197350. if( iPgidx>=n ){
  197351. bEndOfPage = 1;
  197352. break;
  197353. }
  197354. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  197355. iTermOff += nKeep;
  197356. iOff = iTermOff;
  197357. if( iOff>=n ){
  197358. p->rc = FTS5_CORRUPT;
  197359. return;
  197360. }
  197361. /* Read the nKeep field of the next term. */
  197362. fts5FastGetVarint32(a, iOff, nKeep);
  197363. }
  197364. search_failed:
  197365. if( bGe==0 ){
  197366. fts5DataRelease(pIter->pLeaf);
  197367. pIter->pLeaf = 0;
  197368. return;
  197369. }else if( bEndOfPage ){
  197370. do {
  197371. fts5SegIterNextPage(p, pIter);
  197372. if( pIter->pLeaf==0 ) return;
  197373. a = pIter->pLeaf->p;
  197374. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  197375. iPgidx = pIter->pLeaf->szLeaf;
  197376. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  197377. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  197378. p->rc = FTS5_CORRUPT;
  197379. return;
  197380. }else{
  197381. nKeep = 0;
  197382. iTermOff = iOff;
  197383. n = pIter->pLeaf->nn;
  197384. iOff += fts5GetVarint32(&a[iOff], nNew);
  197385. break;
  197386. }
  197387. }
  197388. }while( 1 );
  197389. }
  197390. search_success:
  197391. pIter->iLeafOffset = iOff + nNew;
  197392. if( pIter->iLeafOffset>n || nNew<1 ){
  197393. p->rc = FTS5_CORRUPT;
  197394. return;
  197395. }
  197396. pIter->iTermLeafOffset = pIter->iLeafOffset;
  197397. pIter->iTermLeafPgno = pIter->iLeafPgno;
  197398. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  197399. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  197400. if( iPgidx>=n ){
  197401. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  197402. }else{
  197403. int nExtra;
  197404. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  197405. pIter->iEndofDoclist = iTermOff + nExtra;
  197406. }
  197407. pIter->iPgidxOff = iPgidx;
  197408. fts5SegIterLoadRowid(p, pIter);
  197409. fts5SegIterLoadNPos(p, pIter);
  197410. }
  197411. static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
  197412. if( p->pIdxSelect==0 ){
  197413. Fts5Config *pConfig = p->pConfig;
  197414. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  197415. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  197416. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  197417. pConfig->zDb, pConfig->zName
  197418. ));
  197419. }
  197420. return p->pIdxSelect;
  197421. }
  197422. /*
  197423. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  197424. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  197425. **
  197426. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  197427. ** an error has already occurred when this function is called, it is a no-op.
  197428. */
  197429. static void fts5SegIterSeekInit(
  197430. Fts5Index *p, /* FTS5 backend */
  197431. const u8 *pTerm, int nTerm, /* Term to seek to */
  197432. int flags, /* Mask of FTS5INDEX_XXX flags */
  197433. Fts5StructureSegment *pSeg, /* Description of segment */
  197434. Fts5SegIter *pIter /* Object to populate */
  197435. ){
  197436. int iPg = 1;
  197437. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  197438. int bDlidx = 0; /* True if there is a doclist-index */
  197439. sqlite3_stmt *pIdxSelect = 0;
  197440. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  197441. assert( pTerm && nTerm );
  197442. memset(pIter, 0, sizeof(*pIter));
  197443. pIter->pSeg = pSeg;
  197444. /* This block sets stack variable iPg to the leaf page number that may
  197445. ** contain term (pTerm/nTerm), if it is present in the segment. */
  197446. pIdxSelect = fts5IdxSelectStmt(p);
  197447. if( p->rc ) return;
  197448. sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
  197449. sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  197450. if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
  197451. i64 val = sqlite3_column_int(pIdxSelect, 0);
  197452. iPg = (int)(val>>1);
  197453. bDlidx = (val & 0x0001);
  197454. }
  197455. p->rc = sqlite3_reset(pIdxSelect);
  197456. sqlite3_bind_null(pIdxSelect, 2);
  197457. if( iPg<pSeg->pgnoFirst ){
  197458. iPg = pSeg->pgnoFirst;
  197459. bDlidx = 0;
  197460. }
  197461. pIter->iLeafPgno = iPg - 1;
  197462. fts5SegIterNextPage(p, pIter);
  197463. if( pIter->pLeaf ){
  197464. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  197465. }
  197466. if( p->rc==SQLITE_OK && bGe==0 ){
  197467. pIter->flags |= FTS5_SEGITER_ONETERM;
  197468. if( pIter->pLeaf ){
  197469. if( flags & FTS5INDEX_QUERY_DESC ){
  197470. pIter->flags |= FTS5_SEGITER_REVERSE;
  197471. }
  197472. if( bDlidx ){
  197473. fts5SegIterLoadDlidx(p, pIter);
  197474. }
  197475. if( flags & FTS5INDEX_QUERY_DESC ){
  197476. fts5SegIterReverse(p, pIter);
  197477. }
  197478. }
  197479. }
  197480. fts5SegIterSetNext(p, pIter);
  197481. /* Either:
  197482. **
  197483. ** 1) an error has occurred, or
  197484. ** 2) the iterator points to EOF, or
  197485. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  197486. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  197487. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  197488. */
  197489. assert_nc( p->rc!=SQLITE_OK /* 1 */
  197490. || pIter->pLeaf==0 /* 2 */
  197491. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  197492. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  197493. );
  197494. }
  197495. /*
  197496. ** Initialize the object pIter to point to term pTerm/nTerm within the
  197497. ** in-memory hash table. If there is no such term in the hash-table, the
  197498. ** iterator is set to EOF.
  197499. **
  197500. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  197501. ** an error has already occurred when this function is called, it is a no-op.
  197502. */
  197503. static void fts5SegIterHashInit(
  197504. Fts5Index *p, /* FTS5 backend */
  197505. const u8 *pTerm, int nTerm, /* Term to seek to */
  197506. int flags, /* Mask of FTS5INDEX_XXX flags */
  197507. Fts5SegIter *pIter /* Object to populate */
  197508. ){
  197509. int nList = 0;
  197510. const u8 *z = 0;
  197511. int n = 0;
  197512. Fts5Data *pLeaf = 0;
  197513. assert( p->pHash );
  197514. assert( p->rc==SQLITE_OK );
  197515. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  197516. const u8 *pList = 0;
  197517. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  197518. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  197519. n = (z ? (int)strlen((const char*)z) : 0);
  197520. if( pList ){
  197521. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  197522. if( pLeaf ){
  197523. pLeaf->p = (u8*)pList;
  197524. }
  197525. }
  197526. }else{
  197527. p->rc = sqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data),
  197528. (const char*)pTerm, nTerm, (void**)&pLeaf, &nList
  197529. );
  197530. if( pLeaf ){
  197531. pLeaf->p = (u8*)&pLeaf[1];
  197532. }
  197533. z = pTerm;
  197534. n = nTerm;
  197535. pIter->flags |= FTS5_SEGITER_ONETERM;
  197536. }
  197537. if( pLeaf ){
  197538. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  197539. pLeaf->nn = pLeaf->szLeaf = nList;
  197540. pIter->pLeaf = pLeaf;
  197541. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  197542. pIter->iEndofDoclist = pLeaf->nn;
  197543. if( flags & FTS5INDEX_QUERY_DESC ){
  197544. pIter->flags |= FTS5_SEGITER_REVERSE;
  197545. fts5SegIterReverseInitPage(p, pIter);
  197546. }else{
  197547. fts5SegIterLoadNPos(p, pIter);
  197548. }
  197549. }
  197550. fts5SegIterSetNext(p, pIter);
  197551. }
  197552. /*
  197553. ** Zero the iterator passed as the only argument.
  197554. */
  197555. static void fts5SegIterClear(Fts5SegIter *pIter){
  197556. fts5BufferFree(&pIter->term);
  197557. fts5DataRelease(pIter->pLeaf);
  197558. fts5DataRelease(pIter->pNextLeaf);
  197559. fts5DlidxIterFree(pIter->pDlidx);
  197560. sqlite3_free(pIter->aRowidOffset);
  197561. memset(pIter, 0, sizeof(Fts5SegIter));
  197562. }
  197563. #ifdef SQLITE_DEBUG
  197564. /*
  197565. ** This function is used as part of the big assert() procedure implemented by
  197566. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  197567. ** in *pRes is the correct result of comparing the current positions of the
  197568. ** two iterators.
  197569. */
  197570. static void fts5AssertComparisonResult(
  197571. Fts5Iter *pIter,
  197572. Fts5SegIter *p1,
  197573. Fts5SegIter *p2,
  197574. Fts5CResult *pRes
  197575. ){
  197576. int i1 = p1 - pIter->aSeg;
  197577. int i2 = p2 - pIter->aSeg;
  197578. if( p1->pLeaf || p2->pLeaf ){
  197579. if( p1->pLeaf==0 ){
  197580. assert( pRes->iFirst==i2 );
  197581. }else if( p2->pLeaf==0 ){
  197582. assert( pRes->iFirst==i1 );
  197583. }else{
  197584. int nMin = MIN(p1->term.n, p2->term.n);
  197585. int res = fts5Memcmp(p1->term.p, p2->term.p, nMin);
  197586. if( res==0 ) res = p1->term.n - p2->term.n;
  197587. if( res==0 ){
  197588. assert( pRes->bTermEq==1 );
  197589. assert( p1->iRowid!=p2->iRowid );
  197590. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  197591. }else{
  197592. assert( pRes->bTermEq==0 );
  197593. }
  197594. if( res<0 ){
  197595. assert( pRes->iFirst==i1 );
  197596. }else{
  197597. assert( pRes->iFirst==i2 );
  197598. }
  197599. }
  197600. }
  197601. }
  197602. /*
  197603. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  197604. ** is compiled. In that case, this function is essentially an assert()
  197605. ** statement used to verify that the contents of the pIter->aFirst[] array
  197606. ** are correct.
  197607. */
  197608. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
  197609. if( p->rc==SQLITE_OK ){
  197610. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  197611. int i;
  197612. assert( (pFirst->pLeaf==0)==pIter->base.bEof );
  197613. /* Check that pIter->iSwitchRowid is set correctly. */
  197614. for(i=0; i<pIter->nSeg; i++){
  197615. Fts5SegIter *p1 = &pIter->aSeg[i];
  197616. assert( p1==pFirst
  197617. || p1->pLeaf==0
  197618. || fts5BufferCompare(&pFirst->term, &p1->term)
  197619. || p1->iRowid==pIter->iSwitchRowid
  197620. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  197621. );
  197622. }
  197623. for(i=0; i<pIter->nSeg; i+=2){
  197624. Fts5SegIter *p1 = &pIter->aSeg[i];
  197625. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  197626. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  197627. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  197628. }
  197629. for(i=1; i<(pIter->nSeg / 2); i+=2){
  197630. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  197631. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  197632. Fts5CResult *pRes = &pIter->aFirst[i];
  197633. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  197634. }
  197635. }
  197636. }
  197637. #else
  197638. # define fts5AssertMultiIterSetup(x,y)
  197639. #endif
  197640. /*
  197641. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  197642. **
  197643. ** If the returned value is non-zero, then it is the index of an entry
  197644. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  197645. ** to a key that is a duplicate of another, higher priority,
  197646. ** segment-iterator in the pSeg->aSeg[] array.
  197647. */
  197648. static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
  197649. int i1; /* Index of left-hand Fts5SegIter */
  197650. int i2; /* Index of right-hand Fts5SegIter */
  197651. int iRes;
  197652. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  197653. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  197654. Fts5CResult *pRes = &pIter->aFirst[iOut];
  197655. assert( iOut<pIter->nSeg && iOut>0 );
  197656. assert( pIter->bRev==0 || pIter->bRev==1 );
  197657. if( iOut>=(pIter->nSeg/2) ){
  197658. i1 = (iOut - pIter->nSeg/2) * 2;
  197659. i2 = i1 + 1;
  197660. }else{
  197661. i1 = pIter->aFirst[iOut*2].iFirst;
  197662. i2 = pIter->aFirst[iOut*2+1].iFirst;
  197663. }
  197664. p1 = &pIter->aSeg[i1];
  197665. p2 = &pIter->aSeg[i2];
  197666. pRes->bTermEq = 0;
  197667. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  197668. iRes = i2;
  197669. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  197670. iRes = i1;
  197671. }else{
  197672. int res = fts5BufferCompare(&p1->term, &p2->term);
  197673. if( res==0 ){
  197674. assert_nc( i2>i1 );
  197675. assert_nc( i2!=0 );
  197676. pRes->bTermEq = 1;
  197677. if( p1->iRowid==p2->iRowid ){
  197678. p1->bDel = p2->bDel;
  197679. return i2;
  197680. }
  197681. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  197682. }
  197683. assert( res!=0 );
  197684. if( res<0 ){
  197685. iRes = i1;
  197686. }else{
  197687. iRes = i2;
  197688. }
  197689. }
  197690. pRes->iFirst = (u16)iRes;
  197691. return 0;
  197692. }
  197693. /*
  197694. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  197695. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  197696. */
  197697. static void fts5SegIterGotoPage(
  197698. Fts5Index *p, /* FTS5 backend object */
  197699. Fts5SegIter *pIter, /* Iterator to advance */
  197700. int iLeafPgno
  197701. ){
  197702. assert( iLeafPgno>pIter->iLeafPgno );
  197703. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  197704. p->rc = FTS5_CORRUPT;
  197705. }else{
  197706. fts5DataRelease(pIter->pNextLeaf);
  197707. pIter->pNextLeaf = 0;
  197708. pIter->iLeafPgno = iLeafPgno-1;
  197709. fts5SegIterNextPage(p, pIter);
  197710. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  197711. if( p->rc==SQLITE_OK ){
  197712. int iOff;
  197713. u8 *a = pIter->pLeaf->p;
  197714. int n = pIter->pLeaf->szLeaf;
  197715. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  197716. if( iOff<4 || iOff>=n ){
  197717. p->rc = FTS5_CORRUPT;
  197718. }else{
  197719. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  197720. pIter->iLeafOffset = iOff;
  197721. fts5SegIterLoadNPos(p, pIter);
  197722. }
  197723. }
  197724. }
  197725. }
  197726. /*
  197727. ** Advance the iterator passed as the second argument until it is at or
  197728. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  197729. ** always advanced at least once.
  197730. */
  197731. static void fts5SegIterNextFrom(
  197732. Fts5Index *p, /* FTS5 backend object */
  197733. Fts5SegIter *pIter, /* Iterator to advance */
  197734. i64 iMatch /* Advance iterator at least this far */
  197735. ){
  197736. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  197737. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  197738. int iLeafPgno = pIter->iLeafPgno;
  197739. int bMove = 1;
  197740. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  197741. assert( pIter->pDlidx );
  197742. assert( pIter->pLeaf );
  197743. if( bRev==0 ){
  197744. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  197745. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  197746. fts5DlidxIterNext(p, pDlidx);
  197747. }
  197748. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  197749. if( iLeafPgno>pIter->iLeafPgno ){
  197750. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  197751. bMove = 0;
  197752. }
  197753. }else{
  197754. assert( pIter->pNextLeaf==0 );
  197755. assert( iMatch<pIter->iRowid );
  197756. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  197757. fts5DlidxIterPrev(p, pDlidx);
  197758. }
  197759. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  197760. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  197761. if( iLeafPgno<pIter->iLeafPgno ){
  197762. pIter->iLeafPgno = iLeafPgno+1;
  197763. fts5SegIterReverseNewPage(p, pIter);
  197764. bMove = 0;
  197765. }
  197766. }
  197767. do{
  197768. if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
  197769. if( pIter->pLeaf==0 ) break;
  197770. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  197771. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  197772. bMove = 1;
  197773. }while( p->rc==SQLITE_OK );
  197774. }
  197775. /*
  197776. ** Free the iterator object passed as the second argument.
  197777. */
  197778. static void fts5MultiIterFree(Fts5Iter *pIter){
  197779. if( pIter ){
  197780. int i;
  197781. for(i=0; i<pIter->nSeg; i++){
  197782. fts5SegIterClear(&pIter->aSeg[i]);
  197783. }
  197784. fts5BufferFree(&pIter->poslist);
  197785. sqlite3_free(pIter);
  197786. }
  197787. }
  197788. static void fts5MultiIterAdvanced(
  197789. Fts5Index *p, /* FTS5 backend to iterate within */
  197790. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  197791. int iChanged, /* Index of sub-iterator just advanced */
  197792. int iMinset /* Minimum entry in aFirst[] to set */
  197793. ){
  197794. int i;
  197795. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  197796. int iEq;
  197797. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  197798. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  197799. assert( p->rc==SQLITE_OK );
  197800. pSeg->xNext(p, pSeg, 0);
  197801. i = pIter->nSeg + iEq;
  197802. }
  197803. }
  197804. }
  197805. /*
  197806. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  197807. ** points to the same term though - just a different rowid. This function
  197808. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  197809. ** If it does so successfully, 0 is returned. Otherwise 1.
  197810. **
  197811. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  197812. ** on the iterator instead. That function does the same as this one, except
  197813. ** that it deals with more complicated cases as well.
  197814. */
  197815. static int fts5MultiIterAdvanceRowid(
  197816. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  197817. int iChanged, /* Index of sub-iterator just advanced */
  197818. Fts5SegIter **ppFirst
  197819. ){
  197820. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  197821. if( pNew->iRowid==pIter->iSwitchRowid
  197822. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  197823. ){
  197824. int i;
  197825. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  197826. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  197827. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  197828. Fts5CResult *pRes = &pIter->aFirst[i];
  197829. assert( pNew->pLeaf );
  197830. assert( pRes->bTermEq==0 || pOther->pLeaf );
  197831. if( pRes->bTermEq ){
  197832. if( pNew->iRowid==pOther->iRowid ){
  197833. return 1;
  197834. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  197835. pIter->iSwitchRowid = pOther->iRowid;
  197836. pNew = pOther;
  197837. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  197838. pIter->iSwitchRowid = pOther->iRowid;
  197839. }
  197840. }
  197841. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  197842. if( i==1 ) break;
  197843. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  197844. }
  197845. }
  197846. *ppFirst = pNew;
  197847. return 0;
  197848. }
  197849. /*
  197850. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  197851. */
  197852. static void fts5MultiIterSetEof(Fts5Iter *pIter){
  197853. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  197854. pIter->base.bEof = pSeg->pLeaf==0;
  197855. pIter->iSwitchRowid = pSeg->iRowid;
  197856. }
  197857. /*
  197858. ** Move the iterator to the next entry.
  197859. **
  197860. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  197861. ** considered an error if the iterator reaches EOF, or if it is already at
  197862. ** EOF when this function is called.
  197863. */
  197864. static void fts5MultiIterNext(
  197865. Fts5Index *p,
  197866. Fts5Iter *pIter,
  197867. int bFrom, /* True if argument iFrom is valid */
  197868. i64 iFrom /* Advance at least as far as this */
  197869. ){
  197870. int bUseFrom = bFrom;
  197871. assert( pIter->base.bEof==0 );
  197872. while( p->rc==SQLITE_OK ){
  197873. int iFirst = pIter->aFirst[1].iFirst;
  197874. int bNewTerm = 0;
  197875. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  197876. assert( p->rc==SQLITE_OK );
  197877. if( bUseFrom && pSeg->pDlidx ){
  197878. fts5SegIterNextFrom(p, pSeg, iFrom);
  197879. }else{
  197880. pSeg->xNext(p, pSeg, &bNewTerm);
  197881. }
  197882. if( pSeg->pLeaf==0 || bNewTerm
  197883. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  197884. ){
  197885. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  197886. fts5MultiIterSetEof(pIter);
  197887. pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  197888. if( pSeg->pLeaf==0 ) return;
  197889. }
  197890. fts5AssertMultiIterSetup(p, pIter);
  197891. assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
  197892. if( pIter->bSkipEmpty==0 || pSeg->nPos ){
  197893. pIter->xSetOutputs(pIter, pSeg);
  197894. return;
  197895. }
  197896. bUseFrom = 0;
  197897. }
  197898. }
  197899. static void fts5MultiIterNext2(
  197900. Fts5Index *p,
  197901. Fts5Iter *pIter,
  197902. int *pbNewTerm /* OUT: True if *might* be new term */
  197903. ){
  197904. assert( pIter->bSkipEmpty );
  197905. if( p->rc==SQLITE_OK ){
  197906. *pbNewTerm = 0;
  197907. do{
  197908. int iFirst = pIter->aFirst[1].iFirst;
  197909. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  197910. int bNewTerm = 0;
  197911. assert( p->rc==SQLITE_OK );
  197912. pSeg->xNext(p, pSeg, &bNewTerm);
  197913. if( pSeg->pLeaf==0 || bNewTerm
  197914. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  197915. ){
  197916. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  197917. fts5MultiIterSetEof(pIter);
  197918. *pbNewTerm = 1;
  197919. }
  197920. fts5AssertMultiIterSetup(p, pIter);
  197921. }while( fts5MultiIterIsEmpty(p, pIter) );
  197922. }
  197923. }
  197924. static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
  197925. UNUSED_PARAM2(pUnused1, pUnused2);
  197926. }
  197927. static Fts5Iter *fts5MultiIterAlloc(
  197928. Fts5Index *p, /* FTS5 backend to iterate within */
  197929. int nSeg
  197930. ){
  197931. Fts5Iter *pNew;
  197932. int nSlot; /* Power of two >= nSeg */
  197933. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  197934. pNew = fts5IdxMalloc(p,
  197935. sizeof(Fts5Iter) + /* pNew */
  197936. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  197937. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  197938. );
  197939. if( pNew ){
  197940. pNew->nSeg = nSlot;
  197941. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  197942. pNew->pIndex = p;
  197943. pNew->xSetOutputs = fts5IterSetOutputs_Noop;
  197944. }
  197945. return pNew;
  197946. }
  197947. static void fts5PoslistCallback(
  197948. Fts5Index *pUnused,
  197949. void *pContext,
  197950. const u8 *pChunk, int nChunk
  197951. ){
  197952. UNUSED_PARAM(pUnused);
  197953. assert_nc( nChunk>=0 );
  197954. if( nChunk>0 ){
  197955. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  197956. }
  197957. }
  197958. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  197959. struct PoslistCallbackCtx {
  197960. Fts5Buffer *pBuf; /* Append to this buffer */
  197961. Fts5Colset *pColset; /* Restrict matches to this column */
  197962. int eState; /* See above */
  197963. };
  197964. typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
  197965. struct PoslistOffsetsCtx {
  197966. Fts5Buffer *pBuf; /* Append to this buffer */
  197967. Fts5Colset *pColset; /* Restrict matches to this column */
  197968. int iRead;
  197969. int iWrite;
  197970. };
  197971. /*
  197972. ** TODO: Make this more efficient!
  197973. */
  197974. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  197975. int i;
  197976. for(i=0; i<pColset->nCol; i++){
  197977. if( pColset->aiCol[i]==iCol ) return 1;
  197978. }
  197979. return 0;
  197980. }
  197981. static void fts5PoslistOffsetsCallback(
  197982. Fts5Index *pUnused,
  197983. void *pContext,
  197984. const u8 *pChunk, int nChunk
  197985. ){
  197986. PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
  197987. UNUSED_PARAM(pUnused);
  197988. assert_nc( nChunk>=0 );
  197989. if( nChunk>0 ){
  197990. int i = 0;
  197991. while( i<nChunk ){
  197992. int iVal;
  197993. i += fts5GetVarint32(&pChunk[i], iVal);
  197994. iVal += pCtx->iRead - 2;
  197995. pCtx->iRead = iVal;
  197996. if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
  197997. fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
  197998. pCtx->iWrite = iVal;
  197999. }
  198000. }
  198001. }
  198002. }
  198003. static void fts5PoslistFilterCallback(
  198004. Fts5Index *pUnused,
  198005. void *pContext,
  198006. const u8 *pChunk, int nChunk
  198007. ){
  198008. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  198009. UNUSED_PARAM(pUnused);
  198010. assert_nc( nChunk>=0 );
  198011. if( nChunk>0 ){
  198012. /* Search through to find the first varint with value 1. This is the
  198013. ** start of the next columns hits. */
  198014. int i = 0;
  198015. int iStart = 0;
  198016. if( pCtx->eState==2 ){
  198017. int iCol;
  198018. fts5FastGetVarint32(pChunk, i, iCol);
  198019. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  198020. pCtx->eState = 1;
  198021. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  198022. }else{
  198023. pCtx->eState = 0;
  198024. }
  198025. }
  198026. do {
  198027. while( i<nChunk && pChunk[i]!=0x01 ){
  198028. while( pChunk[i] & 0x80 ) i++;
  198029. i++;
  198030. }
  198031. if( pCtx->eState ){
  198032. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  198033. }
  198034. if( i<nChunk ){
  198035. int iCol;
  198036. iStart = i;
  198037. i++;
  198038. if( i>=nChunk ){
  198039. pCtx->eState = 2;
  198040. }else{
  198041. fts5FastGetVarint32(pChunk, i, iCol);
  198042. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  198043. if( pCtx->eState ){
  198044. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  198045. iStart = i;
  198046. }
  198047. }
  198048. }
  198049. }while( i<nChunk );
  198050. }
  198051. }
  198052. static void fts5ChunkIterate(
  198053. Fts5Index *p, /* Index object */
  198054. Fts5SegIter *pSeg, /* Poslist of this iterator */
  198055. void *pCtx, /* Context pointer for xChunk callback */
  198056. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  198057. ){
  198058. int nRem = pSeg->nPos; /* Number of bytes still to come */
  198059. Fts5Data *pData = 0;
  198060. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  198061. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  198062. int pgno = pSeg->iLeafPgno;
  198063. int pgnoSave = 0;
  198064. /* This function does notmwork with detail=none databases. */
  198065. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  198066. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  198067. pgnoSave = pgno+1;
  198068. }
  198069. while( 1 ){
  198070. xChunk(p, pCtx, pChunk, nChunk);
  198071. nRem -= nChunk;
  198072. fts5DataRelease(pData);
  198073. if( nRem<=0 ){
  198074. break;
  198075. }else{
  198076. pgno++;
  198077. pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  198078. if( pData==0 ) break;
  198079. pChunk = &pData->p[4];
  198080. nChunk = MIN(nRem, pData->szLeaf - 4);
  198081. if( pgno==pgnoSave ){
  198082. assert( pSeg->pNextLeaf==0 );
  198083. pSeg->pNextLeaf = pData;
  198084. pData = 0;
  198085. }
  198086. }
  198087. }
  198088. }
  198089. /*
  198090. ** Iterator pIter currently points to a valid entry (not EOF). This
  198091. ** function appends the position list data for the current entry to
  198092. ** buffer pBuf. It does not make a copy of the position-list size
  198093. ** field.
  198094. */
  198095. static void fts5SegiterPoslist(
  198096. Fts5Index *p,
  198097. Fts5SegIter *pSeg,
  198098. Fts5Colset *pColset,
  198099. Fts5Buffer *pBuf
  198100. ){
  198101. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+FTS5_DATA_ZERO_PADDING) ){
  198102. memset(&pBuf->p[pBuf->n+pSeg->nPos], 0, FTS5_DATA_ZERO_PADDING);
  198103. if( pColset==0 ){
  198104. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  198105. }else{
  198106. if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
  198107. PoslistCallbackCtx sCtx;
  198108. sCtx.pBuf = pBuf;
  198109. sCtx.pColset = pColset;
  198110. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  198111. assert( sCtx.eState==0 || sCtx.eState==1 );
  198112. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  198113. }else{
  198114. PoslistOffsetsCtx sCtx;
  198115. memset(&sCtx, 0, sizeof(sCtx));
  198116. sCtx.pBuf = pBuf;
  198117. sCtx.pColset = pColset;
  198118. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
  198119. }
  198120. }
  198121. }
  198122. }
  198123. /*
  198124. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  198125. ** the position list contains entries for column iCol, then (*pa) is set
  198126. ** to point to the sub-position-list for that column and the number of
  198127. ** bytes in it returned. Or, if the argument position list does not
  198128. ** contain any entries for column iCol, return 0.
  198129. */
  198130. static int fts5IndexExtractCol(
  198131. const u8 **pa, /* IN/OUT: Pointer to poslist */
  198132. int n, /* IN: Size of poslist in bytes */
  198133. int iCol /* Column to extract from poslist */
  198134. ){
  198135. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  198136. const u8 *p = *pa;
  198137. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  198138. while( iCol>iCurrent ){
  198139. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  198140. ** not part of a varint. Note that it is not possible for a negative
  198141. ** or extremely large varint to occur within an uncorrupted position
  198142. ** list. So the last byte of each varint may be assumed to have a clear
  198143. ** 0x80 bit. */
  198144. while( *p!=0x01 ){
  198145. while( *p++ & 0x80 );
  198146. if( p>=pEnd ) return 0;
  198147. }
  198148. *pa = p++;
  198149. iCurrent = *p++;
  198150. if( iCurrent & 0x80 ){
  198151. p--;
  198152. p += fts5GetVarint32(p, iCurrent);
  198153. }
  198154. }
  198155. if( iCol!=iCurrent ) return 0;
  198156. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  198157. ** not part of a varint */
  198158. while( p<pEnd && *p!=0x01 ){
  198159. while( *p++ & 0x80 );
  198160. }
  198161. return p - (*pa);
  198162. }
  198163. static void fts5IndexExtractColset(
  198164. int *pRc,
  198165. Fts5Colset *pColset, /* Colset to filter on */
  198166. const u8 *pPos, int nPos, /* Position list */
  198167. Fts5Buffer *pBuf /* Output buffer */
  198168. ){
  198169. if( *pRc==SQLITE_OK ){
  198170. int i;
  198171. fts5BufferZero(pBuf);
  198172. for(i=0; i<pColset->nCol; i++){
  198173. const u8 *pSub = pPos;
  198174. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  198175. if( nSub ){
  198176. fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
  198177. }
  198178. }
  198179. }
  198180. }
  198181. /*
  198182. ** xSetOutputs callback used by detail=none tables.
  198183. */
  198184. static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
  198185. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
  198186. pIter->base.iRowid = pSeg->iRowid;
  198187. pIter->base.nData = pSeg->nPos;
  198188. }
  198189. /*
  198190. ** xSetOutputs callback used by detail=full and detail=col tables when no
  198191. ** column filters are specified.
  198192. */
  198193. static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  198194. pIter->base.iRowid = pSeg->iRowid;
  198195. pIter->base.nData = pSeg->nPos;
  198196. assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
  198197. assert( pIter->pColset==0 );
  198198. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  198199. /* All data is stored on the current page. Populate the output
  198200. ** variables to point into the body of the page object. */
  198201. pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  198202. }else{
  198203. /* The data is distributed over two or more pages. Copy it into the
  198204. ** Fts5Iter.poslist buffer and then set the output pointer to point
  198205. ** to this buffer. */
  198206. fts5BufferZero(&pIter->poslist);
  198207. fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  198208. pIter->base.pData = pIter->poslist.p;
  198209. }
  198210. }
  198211. /*
  198212. ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
  198213. ** against no columns at all).
  198214. */
  198215. static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  198216. UNUSED_PARAM(pSeg);
  198217. pIter->base.nData = 0;
  198218. }
  198219. /*
  198220. ** xSetOutputs callback used by detail=col when there is a column filter
  198221. ** and there are 100 or more columns. Also called as a fallback from
  198222. ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  198223. */
  198224. static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
  198225. fts5BufferZero(&pIter->poslist);
  198226. fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
  198227. pIter->base.iRowid = pSeg->iRowid;
  198228. pIter->base.pData = pIter->poslist.p;
  198229. pIter->base.nData = pIter->poslist.n;
  198230. }
  198231. /*
  198232. ** xSetOutputs callback used when:
  198233. **
  198234. ** * detail=col,
  198235. ** * there is a column filter, and
  198236. ** * the table contains 100 or fewer columns.
  198237. **
  198238. ** The last point is to ensure all column numbers are stored as
  198239. ** single-byte varints.
  198240. */
  198241. static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
  198242. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  198243. assert( pIter->pColset );
  198244. if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
  198245. fts5IterSetOutputs_Col(pIter, pSeg);
  198246. }else{
  198247. u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
  198248. u8 *pEnd = (u8*)&a[pSeg->nPos];
  198249. int iPrev = 0;
  198250. int *aiCol = pIter->pColset->aiCol;
  198251. int *aiColEnd = &aiCol[pIter->pColset->nCol];
  198252. u8 *aOut = pIter->poslist.p;
  198253. int iPrevOut = 0;
  198254. pIter->base.iRowid = pSeg->iRowid;
  198255. while( a<pEnd ){
  198256. iPrev += (int)a++[0] - 2;
  198257. while( *aiCol<iPrev ){
  198258. aiCol++;
  198259. if( aiCol==aiColEnd ) goto setoutputs_col_out;
  198260. }
  198261. if( *aiCol==iPrev ){
  198262. *aOut++ = (u8)((iPrev - iPrevOut) + 2);
  198263. iPrevOut = iPrev;
  198264. }
  198265. }
  198266. setoutputs_col_out:
  198267. pIter->base.pData = pIter->poslist.p;
  198268. pIter->base.nData = aOut - pIter->poslist.p;
  198269. }
  198270. }
  198271. /*
  198272. ** xSetOutputs callback used by detail=full when there is a column filter.
  198273. */
  198274. static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
  198275. Fts5Colset *pColset = pIter->pColset;
  198276. pIter->base.iRowid = pSeg->iRowid;
  198277. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
  198278. assert( pColset );
  198279. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  198280. /* All data is stored on the current page. Populate the output
  198281. ** variables to point into the body of the page object. */
  198282. const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  198283. if( pColset->nCol==1 ){
  198284. pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
  198285. pIter->base.pData = a;
  198286. }else{
  198287. int *pRc = &pIter->pIndex->rc;
  198288. fts5BufferZero(&pIter->poslist);
  198289. fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
  198290. pIter->base.pData = pIter->poslist.p;
  198291. pIter->base.nData = pIter->poslist.n;
  198292. }
  198293. }else{
  198294. /* The data is distributed over two or more pages. Copy it into the
  198295. ** Fts5Iter.poslist buffer and then set the output pointer to point
  198296. ** to this buffer. */
  198297. fts5BufferZero(&pIter->poslist);
  198298. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  198299. pIter->base.pData = pIter->poslist.p;
  198300. pIter->base.nData = pIter->poslist.n;
  198301. }
  198302. }
  198303. static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
  198304. if( *pRc==SQLITE_OK ){
  198305. Fts5Config *pConfig = pIter->pIndex->pConfig;
  198306. if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  198307. pIter->xSetOutputs = fts5IterSetOutputs_None;
  198308. }
  198309. else if( pIter->pColset==0 ){
  198310. pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  198311. }
  198312. else if( pIter->pColset->nCol==0 ){
  198313. pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
  198314. }
  198315. else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  198316. pIter->xSetOutputs = fts5IterSetOutputs_Full;
  198317. }
  198318. else{
  198319. assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  198320. if( pConfig->nCol<=100 ){
  198321. pIter->xSetOutputs = fts5IterSetOutputs_Col100;
  198322. sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
  198323. }else{
  198324. pIter->xSetOutputs = fts5IterSetOutputs_Col;
  198325. }
  198326. }
  198327. }
  198328. }
  198329. /*
  198330. ** Allocate a new Fts5Iter object.
  198331. **
  198332. ** The new object will be used to iterate through data in structure pStruct.
  198333. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  198334. ** is zero or greater, data from the first nSegment segments on level iLevel
  198335. ** is merged.
  198336. **
  198337. ** The iterator initially points to the first term/rowid entry in the
  198338. ** iterated data.
  198339. */
  198340. static void fts5MultiIterNew(
  198341. Fts5Index *p, /* FTS5 backend to iterate within */
  198342. Fts5Structure *pStruct, /* Structure of specific index */
  198343. int flags, /* FTS5INDEX_QUERY_XXX flags */
  198344. Fts5Colset *pColset, /* Colset to filter on (or NULL) */
  198345. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  198346. int iLevel, /* Level to iterate (-1 for all) */
  198347. int nSegment, /* Number of segments to merge (iLevel>=0) */
  198348. Fts5Iter **ppOut /* New object */
  198349. ){
  198350. int nSeg = 0; /* Number of segment-iters in use */
  198351. int iIter = 0; /* */
  198352. int iSeg; /* Used to iterate through segments */
  198353. Fts5StructureLevel *pLvl;
  198354. Fts5Iter *pNew;
  198355. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  198356. /* Allocate space for the new multi-seg-iterator. */
  198357. if( p->rc==SQLITE_OK ){
  198358. if( iLevel<0 ){
  198359. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  198360. nSeg = pStruct->nSegment;
  198361. nSeg += (p->pHash ? 1 : 0);
  198362. }else{
  198363. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  198364. }
  198365. }
  198366. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  198367. if( pNew==0 ) return;
  198368. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  198369. pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  198370. pNew->pColset = pColset;
  198371. if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
  198372. fts5IterSetOutputCb(&p->rc, pNew);
  198373. }
  198374. /* Initialize each of the component segment iterators. */
  198375. if( p->rc==SQLITE_OK ){
  198376. if( iLevel<0 ){
  198377. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  198378. if( p->pHash ){
  198379. /* Add a segment iterator for the current contents of the hash table. */
  198380. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  198381. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  198382. }
  198383. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  198384. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  198385. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  198386. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  198387. if( pTerm==0 ){
  198388. fts5SegIterInit(p, pSeg, pIter);
  198389. }else{
  198390. fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
  198391. }
  198392. }
  198393. }
  198394. }else{
  198395. pLvl = &pStruct->aLevel[iLevel];
  198396. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  198397. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  198398. }
  198399. }
  198400. assert( iIter==nSeg );
  198401. }
  198402. /* If the above was successful, each component iterators now points
  198403. ** to the first entry in its segment. In this case initialize the
  198404. ** aFirst[] array. Or, if an error has occurred, free the iterator
  198405. ** object and set the output variable to NULL. */
  198406. if( p->rc==SQLITE_OK ){
  198407. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  198408. int iEq;
  198409. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  198410. Fts5SegIter *pSeg = &pNew->aSeg[iEq];
  198411. if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
  198412. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  198413. }
  198414. }
  198415. fts5MultiIterSetEof(pNew);
  198416. fts5AssertMultiIterSetup(p, pNew);
  198417. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  198418. fts5MultiIterNext(p, pNew, 0, 0);
  198419. }else if( pNew->base.bEof==0 ){
  198420. Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
  198421. pNew->xSetOutputs(pNew, pSeg);
  198422. }
  198423. }else{
  198424. fts5MultiIterFree(pNew);
  198425. *ppOut = 0;
  198426. }
  198427. }
  198428. /*
  198429. ** Create an Fts5Iter that iterates through the doclist provided
  198430. ** as the second argument.
  198431. */
  198432. static void fts5MultiIterNew2(
  198433. Fts5Index *p, /* FTS5 backend to iterate within */
  198434. Fts5Data *pData, /* Doclist to iterate through */
  198435. int bDesc, /* True for descending rowid order */
  198436. Fts5Iter **ppOut /* New object */
  198437. ){
  198438. Fts5Iter *pNew;
  198439. pNew = fts5MultiIterAlloc(p, 2);
  198440. if( pNew ){
  198441. Fts5SegIter *pIter = &pNew->aSeg[1];
  198442. pIter->flags = FTS5_SEGITER_ONETERM;
  198443. if( pData->szLeaf>0 ){
  198444. pIter->pLeaf = pData;
  198445. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  198446. pIter->iEndofDoclist = pData->nn;
  198447. pNew->aFirst[1].iFirst = 1;
  198448. if( bDesc ){
  198449. pNew->bRev = 1;
  198450. pIter->flags |= FTS5_SEGITER_REVERSE;
  198451. fts5SegIterReverseInitPage(p, pIter);
  198452. }else{
  198453. fts5SegIterLoadNPos(p, pIter);
  198454. }
  198455. pData = 0;
  198456. }else{
  198457. pNew->base.bEof = 1;
  198458. }
  198459. fts5SegIterSetNext(p, pIter);
  198460. *ppOut = pNew;
  198461. }
  198462. fts5DataRelease(pData);
  198463. }
  198464. /*
  198465. ** Return true if the iterator is at EOF or if an error has occurred.
  198466. ** False otherwise.
  198467. */
  198468. static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
  198469. assert( p->rc
  198470. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
  198471. );
  198472. return (p->rc || pIter->base.bEof);
  198473. }
  198474. /*
  198475. ** Return the rowid of the entry that the iterator currently points
  198476. ** to. If the iterator points to EOF when this function is called the
  198477. ** results are undefined.
  198478. */
  198479. static i64 fts5MultiIterRowid(Fts5Iter *pIter){
  198480. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  198481. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  198482. }
  198483. /*
  198484. ** Move the iterator to the next entry at or following iMatch.
  198485. */
  198486. static void fts5MultiIterNextFrom(
  198487. Fts5Index *p,
  198488. Fts5Iter *pIter,
  198489. i64 iMatch
  198490. ){
  198491. while( 1 ){
  198492. i64 iRowid;
  198493. fts5MultiIterNext(p, pIter, 1, iMatch);
  198494. if( fts5MultiIterEof(p, pIter) ) break;
  198495. iRowid = fts5MultiIterRowid(pIter);
  198496. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  198497. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  198498. }
  198499. }
  198500. /*
  198501. ** Return a pointer to a buffer containing the term associated with the
  198502. ** entry that the iterator currently points to.
  198503. */
  198504. static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
  198505. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  198506. *pn = p->term.n;
  198507. return p->term.p;
  198508. }
  198509. /*
  198510. ** Allocate a new segment-id for the structure pStruct. The new segment
  198511. ** id must be between 1 and 65335 inclusive, and must not be used by
  198512. ** any currently existing segment. If a free segment id cannot be found,
  198513. ** SQLITE_FULL is returned.
  198514. **
  198515. ** If an error has already occurred, this function is a no-op. 0 is
  198516. ** returned in this case.
  198517. */
  198518. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  198519. int iSegid = 0;
  198520. if( p->rc==SQLITE_OK ){
  198521. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  198522. p->rc = SQLITE_FULL;
  198523. }else{
  198524. /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
  198525. ** array is 63 elements, or 252 bytes, in size. */
  198526. u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
  198527. int iLvl, iSeg;
  198528. int i;
  198529. u32 mask;
  198530. memset(aUsed, 0, sizeof(aUsed));
  198531. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  198532. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  198533. int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
  198534. if( iId<=FTS5_MAX_SEGMENT && iId>0 ){
  198535. aUsed[(iId-1) / 32] |= (u32)1 << ((iId-1) % 32);
  198536. }
  198537. }
  198538. }
  198539. for(i=0; aUsed[i]==0xFFFFFFFF; i++);
  198540. mask = aUsed[i];
  198541. for(iSegid=0; mask & ((u32)1 << iSegid); iSegid++);
  198542. iSegid += 1 + i*32;
  198543. #ifdef SQLITE_DEBUG
  198544. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  198545. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  198546. assert_nc( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
  198547. }
  198548. }
  198549. assert_nc( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
  198550. {
  198551. sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
  198552. if( p->rc==SQLITE_OK ){
  198553. u8 aBlob[2] = {0xff, 0xff};
  198554. sqlite3_bind_int(pIdxSelect, 1, iSegid);
  198555. sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
  198556. assert_nc( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
  198557. p->rc = sqlite3_reset(pIdxSelect);
  198558. sqlite3_bind_null(pIdxSelect, 2);
  198559. }
  198560. }
  198561. #endif
  198562. }
  198563. }
  198564. return iSegid;
  198565. }
  198566. /*
  198567. ** Discard all data currently cached in the hash-tables.
  198568. */
  198569. static void fts5IndexDiscardData(Fts5Index *p){
  198570. assert( p->pHash || p->nPendingData==0 );
  198571. if( p->pHash ){
  198572. sqlite3Fts5HashClear(p->pHash);
  198573. p->nPendingData = 0;
  198574. }
  198575. }
  198576. /*
  198577. ** Return the size of the prefix, in bytes, that buffer
  198578. ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
  198579. **
  198580. ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
  198581. ** than buffer (pOld/nOld).
  198582. */
  198583. static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
  198584. int i;
  198585. for(i=0; i<nOld; i++){
  198586. if( pOld[i]!=pNew[i] ) break;
  198587. }
  198588. return i;
  198589. }
  198590. static void fts5WriteDlidxClear(
  198591. Fts5Index *p,
  198592. Fts5SegWriter *pWriter,
  198593. int bFlush /* If true, write dlidx to disk */
  198594. ){
  198595. int i;
  198596. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  198597. for(i=0; i<pWriter->nDlidx; i++){
  198598. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  198599. if( pDlidx->buf.n==0 ) break;
  198600. if( bFlush ){
  198601. assert( pDlidx->pgno!=0 );
  198602. fts5DataWrite(p,
  198603. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  198604. pDlidx->buf.p, pDlidx->buf.n
  198605. );
  198606. }
  198607. sqlite3Fts5BufferZero(&pDlidx->buf);
  198608. pDlidx->bPrevValid = 0;
  198609. }
  198610. }
  198611. /*
  198612. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  198613. ** Any new array elements are zeroed before returning.
  198614. */
  198615. static int fts5WriteDlidxGrow(
  198616. Fts5Index *p,
  198617. Fts5SegWriter *pWriter,
  198618. int nLvl
  198619. ){
  198620. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  198621. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc64(
  198622. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  198623. );
  198624. if( aDlidx==0 ){
  198625. p->rc = SQLITE_NOMEM;
  198626. }else{
  198627. size_t nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  198628. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  198629. pWriter->aDlidx = aDlidx;
  198630. pWriter->nDlidx = nLvl;
  198631. }
  198632. }
  198633. return p->rc;
  198634. }
  198635. /*
  198636. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  198637. ** enough, flush it to disk and return 1. Otherwise discard it and return
  198638. ** zero.
  198639. */
  198640. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  198641. int bFlag = 0;
  198642. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  198643. ** to the database, also write the doclist-index to disk. */
  198644. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  198645. bFlag = 1;
  198646. }
  198647. fts5WriteDlidxClear(p, pWriter, bFlag);
  198648. pWriter->nEmpty = 0;
  198649. return bFlag;
  198650. }
  198651. /*
  198652. ** This function is called whenever processing of the doclist for the
  198653. ** last term on leaf page (pWriter->iBtPage) is completed.
  198654. **
  198655. ** The doclist-index for that term is currently stored in-memory within the
  198656. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  198657. ** writes it out to disk. Or, if it is too small to bother with, discards
  198658. ** it.
  198659. **
  198660. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  198661. */
  198662. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  198663. int bFlag;
  198664. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  198665. if( pWriter->iBtPage==0 ) return;
  198666. bFlag = fts5WriteFlushDlidx(p, pWriter);
  198667. if( p->rc==SQLITE_OK ){
  198668. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  198669. /* The following was already done in fts5WriteInit(): */
  198670. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  198671. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  198672. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  198673. sqlite3_step(p->pIdxWriter);
  198674. p->rc = sqlite3_reset(p->pIdxWriter);
  198675. sqlite3_bind_null(p->pIdxWriter, 2);
  198676. }
  198677. pWriter->iBtPage = 0;
  198678. }
  198679. /*
  198680. ** This is called once for each leaf page except the first that contains
  198681. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  198682. ** is larger than all terms written to earlier leaves, and equal to or
  198683. ** smaller than the first term on the new leaf.
  198684. **
  198685. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  198686. ** has already occurred when this function is called, it is a no-op.
  198687. */
  198688. static void fts5WriteBtreeTerm(
  198689. Fts5Index *p, /* FTS5 backend object */
  198690. Fts5SegWriter *pWriter, /* Writer object */
  198691. int nTerm, const u8 *pTerm /* First term on new page */
  198692. ){
  198693. fts5WriteFlushBtree(p, pWriter);
  198694. if( p->rc==SQLITE_OK ){
  198695. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  198696. pWriter->iBtPage = pWriter->writer.pgno;
  198697. }
  198698. }
  198699. /*
  198700. ** This function is called when flushing a leaf page that contains no
  198701. ** terms at all to disk.
  198702. */
  198703. static void fts5WriteBtreeNoTerm(
  198704. Fts5Index *p, /* FTS5 backend object */
  198705. Fts5SegWriter *pWriter /* Writer object */
  198706. ){
  198707. /* If there were no rowids on the leaf page either and the doclist-index
  198708. ** has already been started, append an 0x00 byte to it. */
  198709. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  198710. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  198711. assert( pDlidx->bPrevValid );
  198712. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  198713. }
  198714. /* Increment the "number of sequential leaves without a term" counter. */
  198715. pWriter->nEmpty++;
  198716. }
  198717. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  198718. i64 iRowid;
  198719. int iOff;
  198720. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  198721. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  198722. return iRowid;
  198723. }
  198724. /*
  198725. ** Rowid iRowid has just been appended to the current leaf page. It is the
  198726. ** first on the page. This function appends an appropriate entry to the current
  198727. ** doclist-index.
  198728. */
  198729. static void fts5WriteDlidxAppend(
  198730. Fts5Index *p,
  198731. Fts5SegWriter *pWriter,
  198732. i64 iRowid
  198733. ){
  198734. int i;
  198735. int bDone = 0;
  198736. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  198737. i64 iVal;
  198738. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  198739. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  198740. /* The current doclist-index page is full. Write it to disk and push
  198741. ** a copy of iRowid (which will become the first rowid on the next
  198742. ** doclist-index leaf page) up into the next level of the b-tree
  198743. ** hierarchy. If the node being flushed is currently the root node,
  198744. ** also push its first rowid upwards. */
  198745. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  198746. fts5DataWrite(p,
  198747. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  198748. pDlidx->buf.p, pDlidx->buf.n
  198749. );
  198750. fts5WriteDlidxGrow(p, pWriter, i+2);
  198751. pDlidx = &pWriter->aDlidx[i];
  198752. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  198753. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  198754. /* This was the root node. Push its first rowid up to the new root. */
  198755. pDlidx[1].pgno = pDlidx->pgno;
  198756. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  198757. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  198758. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  198759. pDlidx[1].bPrevValid = 1;
  198760. pDlidx[1].iPrev = iFirst;
  198761. }
  198762. sqlite3Fts5BufferZero(&pDlidx->buf);
  198763. pDlidx->bPrevValid = 0;
  198764. pDlidx->pgno++;
  198765. }else{
  198766. bDone = 1;
  198767. }
  198768. if( pDlidx->bPrevValid ){
  198769. iVal = iRowid - pDlidx->iPrev;
  198770. }else{
  198771. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  198772. assert( pDlidx->buf.n==0 );
  198773. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  198774. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  198775. iVal = iRowid;
  198776. }
  198777. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  198778. pDlidx->bPrevValid = 1;
  198779. pDlidx->iPrev = iRowid;
  198780. }
  198781. }
  198782. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  198783. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  198784. Fts5PageWriter *pPage = &pWriter->writer;
  198785. i64 iRowid;
  198786. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  198787. /* Set the szLeaf header field. */
  198788. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  198789. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  198790. if( pWriter->bFirstTermInPage ){
  198791. /* No term was written to this page. */
  198792. assert( pPage->pgidx.n==0 );
  198793. fts5WriteBtreeNoTerm(p, pWriter);
  198794. }else{
  198795. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  198796. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  198797. }
  198798. /* Write the page out to disk */
  198799. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  198800. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  198801. /* Initialize the next page. */
  198802. fts5BufferZero(&pPage->buf);
  198803. fts5BufferZero(&pPage->pgidx);
  198804. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  198805. pPage->iPrevPgidx = 0;
  198806. pPage->pgno++;
  198807. /* Increase the leaves written counter */
  198808. pWriter->nLeafWritten++;
  198809. /* The new leaf holds no terms or rowids */
  198810. pWriter->bFirstTermInPage = 1;
  198811. pWriter->bFirstRowidInPage = 1;
  198812. }
  198813. /*
  198814. ** Append term pTerm/nTerm to the segment being written by the writer passed
  198815. ** as the second argument.
  198816. **
  198817. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  198818. ** already occurred, this function is a no-op.
  198819. */
  198820. static void fts5WriteAppendTerm(
  198821. Fts5Index *p,
  198822. Fts5SegWriter *pWriter,
  198823. int nTerm, const u8 *pTerm
  198824. ){
  198825. int nPrefix; /* Bytes of prefix compression for term */
  198826. Fts5PageWriter *pPage = &pWriter->writer;
  198827. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  198828. int nMin = MIN(pPage->term.n, nTerm);
  198829. assert( p->rc==SQLITE_OK );
  198830. assert( pPage->buf.n>=4 );
  198831. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  198832. /* If the current leaf page is full, flush it to disk. */
  198833. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  198834. if( pPage->buf.n>4 ){
  198835. fts5WriteFlushLeaf(p, pWriter);
  198836. if( p->rc!=SQLITE_OK ) return;
  198837. }
  198838. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  198839. }
  198840. /* TODO1: Updating pgidx here. */
  198841. pPgidx->n += sqlite3Fts5PutVarint(
  198842. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  198843. );
  198844. pPage->iPrevPgidx = pPage->buf.n;
  198845. #if 0
  198846. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  198847. pPgidx->n += 2;
  198848. #endif
  198849. if( pWriter->bFirstTermInPage ){
  198850. nPrefix = 0;
  198851. if( pPage->pgno!=1 ){
  198852. /* This is the first term on a leaf that is not the leftmost leaf in
  198853. ** the segment b-tree. In this case it is necessary to add a term to
  198854. ** the b-tree hierarchy that is (a) larger than the largest term
  198855. ** already written to the segment and (b) smaller than or equal to
  198856. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  198857. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  198858. ** previous term.
  198859. **
  198860. ** Usually, the previous term is available in pPage->term. The exception
  198861. ** is if this is the first term written in an incremental-merge step.
  198862. ** In this case the previous term is not available, so just write a
  198863. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  198864. ** inefficient, but still correct. */
  198865. int n = nTerm;
  198866. if( pPage->term.n ){
  198867. n = 1 + fts5PrefixCompress(nMin, pPage->term.p, pTerm);
  198868. }
  198869. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  198870. if( p->rc!=SQLITE_OK ) return;
  198871. pPage = &pWriter->writer;
  198872. }
  198873. }else{
  198874. nPrefix = fts5PrefixCompress(nMin, pPage->term.p, pTerm);
  198875. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  198876. }
  198877. /* Append the number of bytes of new data, then the term data itself
  198878. ** to the page. */
  198879. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  198880. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  198881. /* Update the Fts5PageWriter.term field. */
  198882. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  198883. pWriter->bFirstTermInPage = 0;
  198884. pWriter->bFirstRowidInPage = 0;
  198885. pWriter->bFirstRowidInDoclist = 1;
  198886. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  198887. pWriter->aDlidx[0].pgno = pPage->pgno;
  198888. }
  198889. /*
  198890. ** Append a rowid and position-list size field to the writers output.
  198891. */
  198892. static void fts5WriteAppendRowid(
  198893. Fts5Index *p,
  198894. Fts5SegWriter *pWriter,
  198895. i64 iRowid
  198896. ){
  198897. if( p->rc==SQLITE_OK ){
  198898. Fts5PageWriter *pPage = &pWriter->writer;
  198899. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  198900. fts5WriteFlushLeaf(p, pWriter);
  198901. }
  198902. /* If this is to be the first rowid written to the page, set the
  198903. ** rowid-pointer in the page-header. Also append a value to the dlidx
  198904. ** buffer, in case a doclist-index is required. */
  198905. if( pWriter->bFirstRowidInPage ){
  198906. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  198907. fts5WriteDlidxAppend(p, pWriter, iRowid);
  198908. }
  198909. /* Write the rowid. */
  198910. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  198911. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  198912. }else{
  198913. assert_nc( p->rc || iRowid>pWriter->iPrevRowid );
  198914. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  198915. }
  198916. pWriter->iPrevRowid = iRowid;
  198917. pWriter->bFirstRowidInDoclist = 0;
  198918. pWriter->bFirstRowidInPage = 0;
  198919. }
  198920. }
  198921. static void fts5WriteAppendPoslistData(
  198922. Fts5Index *p,
  198923. Fts5SegWriter *pWriter,
  198924. const u8 *aData,
  198925. int nData
  198926. ){
  198927. Fts5PageWriter *pPage = &pWriter->writer;
  198928. const u8 *a = aData;
  198929. int n = nData;
  198930. assert( p->pConfig->pgsz>0 );
  198931. while( p->rc==SQLITE_OK
  198932. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  198933. ){
  198934. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  198935. int nCopy = 0;
  198936. while( nCopy<nReq ){
  198937. i64 dummy;
  198938. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  198939. }
  198940. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  198941. a += nCopy;
  198942. n -= nCopy;
  198943. fts5WriteFlushLeaf(p, pWriter);
  198944. }
  198945. if( n>0 ){
  198946. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  198947. }
  198948. }
  198949. /*
  198950. ** Flush any data cached by the writer object to the database. Free any
  198951. ** allocations associated with the writer.
  198952. */
  198953. static void fts5WriteFinish(
  198954. Fts5Index *p,
  198955. Fts5SegWriter *pWriter, /* Writer object */
  198956. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  198957. ){
  198958. int i;
  198959. Fts5PageWriter *pLeaf = &pWriter->writer;
  198960. if( p->rc==SQLITE_OK ){
  198961. assert( pLeaf->pgno>=1 );
  198962. if( pLeaf->buf.n>4 ){
  198963. fts5WriteFlushLeaf(p, pWriter);
  198964. }
  198965. *pnLeaf = pLeaf->pgno-1;
  198966. if( pLeaf->pgno>1 ){
  198967. fts5WriteFlushBtree(p, pWriter);
  198968. }
  198969. }
  198970. fts5BufferFree(&pLeaf->term);
  198971. fts5BufferFree(&pLeaf->buf);
  198972. fts5BufferFree(&pLeaf->pgidx);
  198973. fts5BufferFree(&pWriter->btterm);
  198974. for(i=0; i<pWriter->nDlidx; i++){
  198975. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  198976. }
  198977. sqlite3_free(pWriter->aDlidx);
  198978. }
  198979. static void fts5WriteInit(
  198980. Fts5Index *p,
  198981. Fts5SegWriter *pWriter,
  198982. int iSegid
  198983. ){
  198984. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  198985. memset(pWriter, 0, sizeof(Fts5SegWriter));
  198986. pWriter->iSegid = iSegid;
  198987. fts5WriteDlidxGrow(p, pWriter, 1);
  198988. pWriter->writer.pgno = 1;
  198989. pWriter->bFirstTermInPage = 1;
  198990. pWriter->iBtPage = 1;
  198991. assert( pWriter->writer.buf.n==0 );
  198992. assert( pWriter->writer.pgidx.n==0 );
  198993. /* Grow the two buffers to pgsz + padding bytes in size. */
  198994. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  198995. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  198996. if( p->pIdxWriter==0 ){
  198997. Fts5Config *pConfig = p->pConfig;
  198998. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  198999. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  199000. pConfig->zDb, pConfig->zName
  199001. ));
  199002. }
  199003. if( p->rc==SQLITE_OK ){
  199004. /* Initialize the 4-byte leaf-page header to 0x00. */
  199005. memset(pWriter->writer.buf.p, 0, 4);
  199006. pWriter->writer.buf.n = 4;
  199007. /* Bind the current output segment id to the index-writer. This is an
  199008. ** optimization over binding the same value over and over as rows are
  199009. ** inserted into %_idx by the current writer. */
  199010. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  199011. }
  199012. }
  199013. /*
  199014. ** Iterator pIter was used to iterate through the input segments of on an
  199015. ** incremental merge operation. This function is called if the incremental
  199016. ** merge step has finished but the input has not been completely exhausted.
  199017. */
  199018. static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
  199019. int i;
  199020. Fts5Buffer buf;
  199021. memset(&buf, 0, sizeof(Fts5Buffer));
  199022. for(i=0; i<pIter->nSeg && p->rc==SQLITE_OK; i++){
  199023. Fts5SegIter *pSeg = &pIter->aSeg[i];
  199024. if( pSeg->pSeg==0 ){
  199025. /* no-op */
  199026. }else if( pSeg->pLeaf==0 ){
  199027. /* All keys from this input segment have been transfered to the output.
  199028. ** Set both the first and last page-numbers to 0 to indicate that the
  199029. ** segment is now empty. */
  199030. pSeg->pSeg->pgnoLast = 0;
  199031. pSeg->pSeg->pgnoFirst = 0;
  199032. }else{
  199033. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  199034. i64 iLeafRowid;
  199035. Fts5Data *pData;
  199036. int iId = pSeg->pSeg->iSegid;
  199037. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  199038. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  199039. pData = fts5LeafRead(p, iLeafRowid);
  199040. if( pData ){
  199041. if( iOff>pData->szLeaf ){
  199042. /* This can occur if the pages that the segments occupy overlap - if
  199043. ** a single page has been assigned to more than one segment. In
  199044. ** this case a prior iteration of this loop may have corrupted the
  199045. ** segment currently being trimmed. */
  199046. p->rc = FTS5_CORRUPT;
  199047. }else{
  199048. fts5BufferZero(&buf);
  199049. fts5BufferGrow(&p->rc, &buf, pData->nn);
  199050. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  199051. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  199052. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  199053. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff,&pData->p[iOff]);
  199054. if( p->rc==SQLITE_OK ){
  199055. /* Set the szLeaf field */
  199056. fts5PutU16(&buf.p[2], (u16)buf.n);
  199057. }
  199058. /* Set up the new page-index array */
  199059. fts5BufferAppendVarint(&p->rc, &buf, 4);
  199060. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  199061. && pSeg->iEndofDoclist<pData->szLeaf
  199062. && pSeg->iPgidxOff<=pData->nn
  199063. ){
  199064. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  199065. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  199066. fts5BufferAppendBlob(&p->rc, &buf,
  199067. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  199068. );
  199069. }
  199070. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  199071. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  199072. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  199073. }
  199074. fts5DataRelease(pData);
  199075. }
  199076. }
  199077. }
  199078. fts5BufferFree(&buf);
  199079. }
  199080. static void fts5MergeChunkCallback(
  199081. Fts5Index *p,
  199082. void *pCtx,
  199083. const u8 *pChunk, int nChunk
  199084. ){
  199085. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  199086. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  199087. }
  199088. /*
  199089. **
  199090. */
  199091. static void fts5IndexMergeLevel(
  199092. Fts5Index *p, /* FTS5 backend object */
  199093. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  199094. int iLvl, /* Level to read input from */
  199095. int *pnRem /* Write up to this many output leaves */
  199096. ){
  199097. Fts5Structure *pStruct = *ppStruct;
  199098. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  199099. Fts5StructureLevel *pLvlOut;
  199100. Fts5Iter *pIter = 0; /* Iterator to read input data */
  199101. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  199102. int nInput; /* Number of input segments */
  199103. Fts5SegWriter writer; /* Writer object */
  199104. Fts5StructureSegment *pSeg; /* Output segment */
  199105. Fts5Buffer term;
  199106. int bOldest; /* True if the output segment is the oldest */
  199107. int eDetail = p->pConfig->eDetail;
  199108. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  199109. int bTermWritten = 0; /* True if current term already output */
  199110. assert( iLvl<pStruct->nLevel );
  199111. assert( pLvl->nMerge<=pLvl->nSeg );
  199112. memset(&writer, 0, sizeof(Fts5SegWriter));
  199113. memset(&term, 0, sizeof(Fts5Buffer));
  199114. if( pLvl->nMerge ){
  199115. pLvlOut = &pStruct->aLevel[iLvl+1];
  199116. assert( pLvlOut->nSeg>0 );
  199117. nInput = pLvl->nMerge;
  199118. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  199119. fts5WriteInit(p, &writer, pSeg->iSegid);
  199120. writer.writer.pgno = pSeg->pgnoLast+1;
  199121. writer.iBtPage = 0;
  199122. }else{
  199123. int iSegid = fts5AllocateSegid(p, pStruct);
  199124. /* Extend the Fts5Structure object as required to ensure the output
  199125. ** segment exists. */
  199126. if( iLvl==pStruct->nLevel-1 ){
  199127. fts5StructureAddLevel(&p->rc, ppStruct);
  199128. pStruct = *ppStruct;
  199129. }
  199130. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  199131. if( p->rc ) return;
  199132. pLvl = &pStruct->aLevel[iLvl];
  199133. pLvlOut = &pStruct->aLevel[iLvl+1];
  199134. fts5WriteInit(p, &writer, iSegid);
  199135. /* Add the new segment to the output level */
  199136. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  199137. pLvlOut->nSeg++;
  199138. pSeg->pgnoFirst = 1;
  199139. pSeg->iSegid = iSegid;
  199140. pStruct->nSegment++;
  199141. /* Read input from all segments in the input level */
  199142. nInput = pLvl->nSeg;
  199143. }
  199144. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  199145. assert( iLvl>=0 );
  199146. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
  199147. fts5MultiIterEof(p, pIter)==0;
  199148. fts5MultiIterNext(p, pIter, 0, 0)
  199149. ){
  199150. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  199151. int nPos; /* position-list size field value */
  199152. int nTerm;
  199153. const u8 *pTerm;
  199154. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  199155. if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){
  199156. if( pnRem && writer.nLeafWritten>nRem ){
  199157. break;
  199158. }
  199159. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  199160. bTermWritten =0;
  199161. }
  199162. /* Check for key annihilation. */
  199163. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  199164. if( p->rc==SQLITE_OK && bTermWritten==0 ){
  199165. /* This is a new term. Append a term to the output segment. */
  199166. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  199167. bTermWritten = 1;
  199168. }
  199169. /* Append the rowid to the output */
  199170. /* WRITEPOSLISTSIZE */
  199171. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
  199172. if( eDetail==FTS5_DETAIL_NONE ){
  199173. if( pSegIter->bDel ){
  199174. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  199175. if( pSegIter->nPos>0 ){
  199176. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  199177. }
  199178. }
  199179. }else{
  199180. /* Append the position-list data to the output */
  199181. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  199182. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
  199183. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  199184. }
  199185. }
  199186. /* Flush the last leaf page to disk. Set the output segment b-tree height
  199187. ** and last leaf page number at the same time. */
  199188. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  199189. if( fts5MultiIterEof(p, pIter) ){
  199190. int i;
  199191. /* Remove the redundant segments from the %_data table */
  199192. for(i=0; i<nInput; i++){
  199193. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  199194. }
  199195. /* Remove the redundant segments from the input level */
  199196. if( pLvl->nSeg!=nInput ){
  199197. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  199198. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  199199. }
  199200. pStruct->nSegment -= nInput;
  199201. pLvl->nSeg -= nInput;
  199202. pLvl->nMerge = 0;
  199203. if( pSeg->pgnoLast==0 ){
  199204. pLvlOut->nSeg--;
  199205. pStruct->nSegment--;
  199206. }
  199207. }else{
  199208. assert( pSeg->pgnoLast>0 );
  199209. fts5TrimSegments(p, pIter);
  199210. pLvl->nMerge = nInput;
  199211. }
  199212. fts5MultiIterFree(pIter);
  199213. fts5BufferFree(&term);
  199214. if( pnRem ) *pnRem -= writer.nLeafWritten;
  199215. }
  199216. /*
  199217. ** Do up to nPg pages of automerge work on the index.
  199218. **
  199219. ** Return true if any changes were actually made, or false otherwise.
  199220. */
  199221. static int fts5IndexMerge(
  199222. Fts5Index *p, /* FTS5 backend object */
  199223. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  199224. int nPg, /* Pages of work to do */
  199225. int nMin /* Minimum number of segments to merge */
  199226. ){
  199227. int nRem = nPg;
  199228. int bRet = 0;
  199229. Fts5Structure *pStruct = *ppStruct;
  199230. while( nRem>0 && p->rc==SQLITE_OK ){
  199231. int iLvl; /* To iterate through levels */
  199232. int iBestLvl = 0; /* Level offering the most input segments */
  199233. int nBest = 0; /* Number of input segments on best level */
  199234. /* Set iBestLvl to the level to read input segments from. */
  199235. assert( pStruct->nLevel>0 );
  199236. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  199237. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  199238. if( pLvl->nMerge ){
  199239. if( pLvl->nMerge>nBest ){
  199240. iBestLvl = iLvl;
  199241. nBest = pLvl->nMerge;
  199242. }
  199243. break;
  199244. }
  199245. if( pLvl->nSeg>nBest ){
  199246. nBest = pLvl->nSeg;
  199247. iBestLvl = iLvl;
  199248. }
  199249. }
  199250. /* If nBest is still 0, then the index must be empty. */
  199251. #ifdef SQLITE_DEBUG
  199252. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  199253. assert( pStruct->aLevel[iLvl].nSeg==0 );
  199254. }
  199255. #endif
  199256. if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
  199257. break;
  199258. }
  199259. bRet = 1;
  199260. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  199261. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  199262. fts5StructurePromote(p, iBestLvl+1, pStruct);
  199263. }
  199264. }
  199265. *ppStruct = pStruct;
  199266. return bRet;
  199267. }
  199268. /*
  199269. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  199270. ** segment. This function updates the write-counter accordingly and, if
  199271. ** necessary, performs incremental merge work.
  199272. **
  199273. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  199274. ** already occurred, this function is a no-op.
  199275. */
  199276. static void fts5IndexAutomerge(
  199277. Fts5Index *p, /* FTS5 backend object */
  199278. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  199279. int nLeaf /* Number of output leaves just written */
  199280. ){
  199281. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  199282. Fts5Structure *pStruct = *ppStruct;
  199283. u64 nWrite; /* Initial value of write-counter */
  199284. int nWork; /* Number of work-quanta to perform */
  199285. int nRem; /* Number of leaf pages left to write */
  199286. /* Update the write-counter. While doing so, set nWork. */
  199287. nWrite = pStruct->nWriteCounter;
  199288. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  199289. pStruct->nWriteCounter += nLeaf;
  199290. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  199291. fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
  199292. }
  199293. }
  199294. static void fts5IndexCrisismerge(
  199295. Fts5Index *p, /* FTS5 backend object */
  199296. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  199297. ){
  199298. const int nCrisis = p->pConfig->nCrisisMerge;
  199299. Fts5Structure *pStruct = *ppStruct;
  199300. int iLvl = 0;
  199301. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  199302. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  199303. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  199304. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  199305. fts5StructurePromote(p, iLvl+1, pStruct);
  199306. iLvl++;
  199307. }
  199308. *ppStruct = pStruct;
  199309. }
  199310. static int fts5IndexReturn(Fts5Index *p){
  199311. int rc = p->rc;
  199312. p->rc = SQLITE_OK;
  199313. return rc;
  199314. }
  199315. typedef struct Fts5FlushCtx Fts5FlushCtx;
  199316. struct Fts5FlushCtx {
  199317. Fts5Index *pIdx;
  199318. Fts5SegWriter writer;
  199319. };
  199320. /*
  199321. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  199322. ** in a 32-bit integer. Return the size of the largest prefix of this
  199323. ** list nMax bytes or less in size.
  199324. */
  199325. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  199326. int ret;
  199327. u32 dummy;
  199328. ret = fts5GetVarint32(aBuf, dummy);
  199329. if( ret<nMax ){
  199330. while( 1 ){
  199331. int i = fts5GetVarint32(&aBuf[ret], dummy);
  199332. if( (ret + i) > nMax ) break;
  199333. ret += i;
  199334. }
  199335. }
  199336. return ret;
  199337. }
  199338. /*
  199339. ** Flush the contents of in-memory hash table iHash to a new level-0
  199340. ** segment on disk. Also update the corresponding structure record.
  199341. **
  199342. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  199343. ** already occurred, this function is a no-op.
  199344. */
  199345. static void fts5FlushOneHash(Fts5Index *p){
  199346. Fts5Hash *pHash = p->pHash;
  199347. Fts5Structure *pStruct;
  199348. int iSegid;
  199349. int pgnoLast = 0; /* Last leaf page number in segment */
  199350. /* Obtain a reference to the index structure and allocate a new segment-id
  199351. ** for the new level-0 segment. */
  199352. pStruct = fts5StructureRead(p);
  199353. iSegid = fts5AllocateSegid(p, pStruct);
  199354. fts5StructureInvalidate(p);
  199355. if( iSegid ){
  199356. const int pgsz = p->pConfig->pgsz;
  199357. int eDetail = p->pConfig->eDetail;
  199358. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  199359. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  199360. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  199361. Fts5SegWriter writer;
  199362. fts5WriteInit(p, &writer, iSegid);
  199363. pBuf = &writer.writer.buf;
  199364. pPgidx = &writer.writer.pgidx;
  199365. /* fts5WriteInit() should have initialized the buffers to (most likely)
  199366. ** the maximum space required. */
  199367. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  199368. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  199369. /* Begin scanning through hash table entries. This loop runs once for each
  199370. ** term/doclist currently stored within the hash table. */
  199371. if( p->rc==SQLITE_OK ){
  199372. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  199373. }
  199374. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  199375. const char *zTerm; /* Buffer containing term */
  199376. const u8 *pDoclist; /* Pointer to doclist for this term */
  199377. int nDoclist; /* Size of doclist in bytes */
  199378. /* Write the term for this entry to disk. */
  199379. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  199380. fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
  199381. if( p->rc!=SQLITE_OK ) break;
  199382. assert( writer.bFirstRowidInPage==0 );
  199383. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  199384. /* The entire doclist will fit on the current leaf. */
  199385. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  199386. }else{
  199387. i64 iRowid = 0;
  199388. i64 iDelta = 0;
  199389. int iOff = 0;
  199390. /* The entire doclist will not fit on this leaf. The following
  199391. ** loop iterates through the poslists that make up the current
  199392. ** doclist. */
  199393. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  199394. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  199395. iRowid += iDelta;
  199396. if( writer.bFirstRowidInPage ){
  199397. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  199398. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  199399. writer.bFirstRowidInPage = 0;
  199400. fts5WriteDlidxAppend(p, &writer, iRowid);
  199401. if( p->rc!=SQLITE_OK ) break;
  199402. }else{
  199403. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  199404. }
  199405. assert( pBuf->n<=pBuf->nSpace );
  199406. if( eDetail==FTS5_DETAIL_NONE ){
  199407. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  199408. pBuf->p[pBuf->n++] = 0;
  199409. iOff++;
  199410. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  199411. pBuf->p[pBuf->n++] = 0;
  199412. iOff++;
  199413. }
  199414. }
  199415. if( (pBuf->n + pPgidx->n)>=pgsz ){
  199416. fts5WriteFlushLeaf(p, &writer);
  199417. }
  199418. }else{
  199419. int bDummy;
  199420. int nPos;
  199421. int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  199422. nCopy += nPos;
  199423. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  199424. /* The entire poslist will fit on the current leaf. So copy
  199425. ** it in one go. */
  199426. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  199427. }else{
  199428. /* The entire poslist will not fit on this leaf. So it needs
  199429. ** to be broken into sections. The only qualification being
  199430. ** that each varint must be stored contiguously. */
  199431. const u8 *pPoslist = &pDoclist[iOff];
  199432. int iPos = 0;
  199433. while( p->rc==SQLITE_OK ){
  199434. int nSpace = pgsz - pBuf->n - pPgidx->n;
  199435. int n = 0;
  199436. if( (nCopy - iPos)<=nSpace ){
  199437. n = nCopy - iPos;
  199438. }else{
  199439. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  199440. }
  199441. assert( n>0 );
  199442. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  199443. iPos += n;
  199444. if( (pBuf->n + pPgidx->n)>=pgsz ){
  199445. fts5WriteFlushLeaf(p, &writer);
  199446. }
  199447. if( iPos>=nCopy ) break;
  199448. }
  199449. }
  199450. iOff += nCopy;
  199451. }
  199452. }
  199453. }
  199454. /* TODO2: Doclist terminator written here. */
  199455. /* pBuf->p[pBuf->n++] = '\0'; */
  199456. assert( pBuf->n<=pBuf->nSpace );
  199457. if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);
  199458. }
  199459. sqlite3Fts5HashClear(pHash);
  199460. fts5WriteFinish(p, &writer, &pgnoLast);
  199461. /* Update the Fts5Structure. It is written back to the database by the
  199462. ** fts5StructureRelease() call below. */
  199463. if( pStruct->nLevel==0 ){
  199464. fts5StructureAddLevel(&p->rc, &pStruct);
  199465. }
  199466. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  199467. if( p->rc==SQLITE_OK ){
  199468. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  199469. pSeg->iSegid = iSegid;
  199470. pSeg->pgnoFirst = 1;
  199471. pSeg->pgnoLast = pgnoLast;
  199472. pStruct->nSegment++;
  199473. }
  199474. fts5StructurePromote(p, 0, pStruct);
  199475. }
  199476. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  199477. fts5IndexCrisismerge(p, &pStruct);
  199478. fts5StructureWrite(p, pStruct);
  199479. fts5StructureRelease(pStruct);
  199480. }
  199481. /*
  199482. ** Flush any data stored in the in-memory hash tables to the database.
  199483. */
  199484. static void fts5IndexFlush(Fts5Index *p){
  199485. /* Unless it is empty, flush the hash table to disk */
  199486. if( p->nPendingData ){
  199487. assert( p->pHash );
  199488. p->nPendingData = 0;
  199489. fts5FlushOneHash(p);
  199490. }
  199491. }
  199492. static Fts5Structure *fts5IndexOptimizeStruct(
  199493. Fts5Index *p,
  199494. Fts5Structure *pStruct
  199495. ){
  199496. Fts5Structure *pNew = 0;
  199497. sqlite3_int64 nByte = sizeof(Fts5Structure);
  199498. int nSeg = pStruct->nSegment;
  199499. int i;
  199500. /* Figure out if this structure requires optimization. A structure does
  199501. ** not require optimization if either:
  199502. **
  199503. ** + it consists of fewer than two segments, or
  199504. ** + all segments are on the same level, or
  199505. ** + all segments except one are currently inputs to a merge operation.
  199506. **
  199507. ** In the first case, return NULL. In the second, increment the ref-count
  199508. ** on *pStruct and return a copy of the pointer to it.
  199509. */
  199510. if( nSeg<2 ) return 0;
  199511. for(i=0; i<pStruct->nLevel; i++){
  199512. int nThis = pStruct->aLevel[i].nSeg;
  199513. if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
  199514. fts5StructureRef(pStruct);
  199515. return pStruct;
  199516. }
  199517. assert( pStruct->aLevel[i].nMerge<=nThis );
  199518. }
  199519. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  199520. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  199521. if( pNew ){
  199522. Fts5StructureLevel *pLvl;
  199523. nByte = nSeg * sizeof(Fts5StructureSegment);
  199524. pNew->nLevel = pStruct->nLevel+1;
  199525. pNew->nRef = 1;
  199526. pNew->nWriteCounter = pStruct->nWriteCounter;
  199527. pLvl = &pNew->aLevel[pStruct->nLevel];
  199528. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  199529. if( pLvl->aSeg ){
  199530. int iLvl, iSeg;
  199531. int iSegOut = 0;
  199532. /* Iterate through all segments, from oldest to newest. Add them to
  199533. ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
  199534. ** segment in the data structure. */
  199535. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  199536. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  199537. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  199538. iSegOut++;
  199539. }
  199540. }
  199541. pNew->nSegment = pLvl->nSeg = nSeg;
  199542. }else{
  199543. sqlite3_free(pNew);
  199544. pNew = 0;
  199545. }
  199546. }
  199547. return pNew;
  199548. }
  199549. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  199550. Fts5Structure *pStruct;
  199551. Fts5Structure *pNew = 0;
  199552. assert( p->rc==SQLITE_OK );
  199553. fts5IndexFlush(p);
  199554. pStruct = fts5StructureRead(p);
  199555. fts5StructureInvalidate(p);
  199556. if( pStruct ){
  199557. pNew = fts5IndexOptimizeStruct(p, pStruct);
  199558. }
  199559. fts5StructureRelease(pStruct);
  199560. assert( pNew==0 || pNew->nSegment>0 );
  199561. if( pNew ){
  199562. int iLvl;
  199563. for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
  199564. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  199565. int nRem = FTS5_OPT_WORK_UNIT;
  199566. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  199567. }
  199568. fts5StructureWrite(p, pNew);
  199569. fts5StructureRelease(pNew);
  199570. }
  199571. return fts5IndexReturn(p);
  199572. }
  199573. /*
  199574. ** This is called to implement the special "VALUES('merge', $nMerge)"
  199575. ** INSERT command.
  199576. */
  199577. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  199578. Fts5Structure *pStruct = fts5StructureRead(p);
  199579. if( pStruct ){
  199580. int nMin = p->pConfig->nUsermerge;
  199581. fts5StructureInvalidate(p);
  199582. if( nMerge<0 ){
  199583. Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
  199584. fts5StructureRelease(pStruct);
  199585. pStruct = pNew;
  199586. nMin = 2;
  199587. nMerge = nMerge*-1;
  199588. }
  199589. if( pStruct && pStruct->nLevel ){
  199590. if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
  199591. fts5StructureWrite(p, pStruct);
  199592. }
  199593. }
  199594. fts5StructureRelease(pStruct);
  199595. }
  199596. return fts5IndexReturn(p);
  199597. }
  199598. static void fts5AppendRowid(
  199599. Fts5Index *p,
  199600. i64 iDelta,
  199601. Fts5Iter *pUnused,
  199602. Fts5Buffer *pBuf
  199603. ){
  199604. UNUSED_PARAM(pUnused);
  199605. fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
  199606. }
  199607. static void fts5AppendPoslist(
  199608. Fts5Index *p,
  199609. i64 iDelta,
  199610. Fts5Iter *pMulti,
  199611. Fts5Buffer *pBuf
  199612. ){
  199613. int nData = pMulti->base.nData;
  199614. int nByte = nData + 9 + 9 + FTS5_DATA_ZERO_PADDING;
  199615. assert( nData>0 );
  199616. if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nByte) ){
  199617. fts5BufferSafeAppendVarint(pBuf, iDelta);
  199618. fts5BufferSafeAppendVarint(pBuf, nData*2);
  199619. fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
  199620. memset(&pBuf->p[pBuf->n], 0, FTS5_DATA_ZERO_PADDING);
  199621. }
  199622. }
  199623. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  199624. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  199625. assert( pIter->aPoslist );
  199626. if( p>=pIter->aEof ){
  199627. pIter->aPoslist = 0;
  199628. }else{
  199629. i64 iDelta;
  199630. p += fts5GetVarint(p, (u64*)&iDelta);
  199631. pIter->iRowid += iDelta;
  199632. /* Read position list size */
  199633. if( p[0] & 0x80 ){
  199634. int nPos;
  199635. pIter->nSize = fts5GetVarint32(p, nPos);
  199636. pIter->nPoslist = (nPos>>1);
  199637. }else{
  199638. pIter->nPoslist = ((int)(p[0])) >> 1;
  199639. pIter->nSize = 1;
  199640. }
  199641. pIter->aPoslist = p;
  199642. }
  199643. }
  199644. static void fts5DoclistIterInit(
  199645. Fts5Buffer *pBuf,
  199646. Fts5DoclistIter *pIter
  199647. ){
  199648. memset(pIter, 0, sizeof(*pIter));
  199649. pIter->aPoslist = pBuf->p;
  199650. pIter->aEof = &pBuf->p[pBuf->n];
  199651. fts5DoclistIterNext(pIter);
  199652. }
  199653. #if 0
  199654. /*
  199655. ** Append a doclist to buffer pBuf.
  199656. **
  199657. ** This function assumes that space within the buffer has already been
  199658. ** allocated.
  199659. */
  199660. static void fts5MergeAppendDocid(
  199661. Fts5Buffer *pBuf, /* Buffer to write to */
  199662. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  199663. i64 iRowid /* Rowid to append */
  199664. ){
  199665. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  199666. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  199667. *piLastRowid = iRowid;
  199668. }
  199669. #endif
  199670. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  199671. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  199672. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  199673. (iLastRowid) = (iRowid); \
  199674. }
  199675. /*
  199676. ** Swap the contents of buffer *p1 with that of *p2.
  199677. */
  199678. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  199679. Fts5Buffer tmp = *p1;
  199680. *p1 = *p2;
  199681. *p2 = tmp;
  199682. }
  199683. static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
  199684. int i = *piOff;
  199685. if( i>=pBuf->n ){
  199686. *piOff = -1;
  199687. }else{
  199688. u64 iVal;
  199689. *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
  199690. *piRowid += iVal;
  199691. }
  199692. }
  199693. /*
  199694. ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
  199695. ** In this case the buffers consist of a delta-encoded list of rowids only.
  199696. */
  199697. static void fts5MergeRowidLists(
  199698. Fts5Index *p, /* FTS5 backend object */
  199699. Fts5Buffer *p1, /* First list to merge */
  199700. Fts5Buffer *p2 /* Second list to merge */
  199701. ){
  199702. int i1 = 0;
  199703. int i2 = 0;
  199704. i64 iRowid1 = 0;
  199705. i64 iRowid2 = 0;
  199706. i64 iOut = 0;
  199707. Fts5Buffer out;
  199708. memset(&out, 0, sizeof(out));
  199709. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  199710. if( p->rc ) return;
  199711. fts5NextRowid(p1, &i1, &iRowid1);
  199712. fts5NextRowid(p2, &i2, &iRowid2);
  199713. while( i1>=0 || i2>=0 ){
  199714. if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
  199715. assert( iOut==0 || iRowid1>iOut );
  199716. fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
  199717. iOut = iRowid1;
  199718. fts5NextRowid(p1, &i1, &iRowid1);
  199719. }else{
  199720. assert( iOut==0 || iRowid2>iOut );
  199721. fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
  199722. iOut = iRowid2;
  199723. if( i1>=0 && iRowid1==iRowid2 ){
  199724. fts5NextRowid(p1, &i1, &iRowid1);
  199725. }
  199726. fts5NextRowid(p2, &i2, &iRowid2);
  199727. }
  199728. }
  199729. fts5BufferSwap(&out, p1);
  199730. fts5BufferFree(&out);
  199731. }
  199732. /*
  199733. ** Buffers p1 and p2 contain doclists. This function merges the content
  199734. ** of the two doclists together and sets buffer p1 to the result before
  199735. ** returning.
  199736. **
  199737. ** If an error occurs, an error code is left in p->rc. If an error has
  199738. ** already occurred, this function is a no-op.
  199739. */
  199740. static void fts5MergePrefixLists(
  199741. Fts5Index *p, /* FTS5 backend object */
  199742. Fts5Buffer *p1, /* First list to merge */
  199743. Fts5Buffer *p2 /* Second list to merge */
  199744. ){
  199745. if( p2->n ){
  199746. i64 iLastRowid = 0;
  199747. Fts5DoclistIter i1;
  199748. Fts5DoclistIter i2;
  199749. Fts5Buffer out = {0, 0, 0};
  199750. Fts5Buffer tmp = {0, 0, 0};
  199751. /* The maximum size of the output is equal to the sum of the two
  199752. ** input sizes + 1 varint (9 bytes). The extra varint is because if the
  199753. ** first rowid in one input is a large negative number, and the first in
  199754. ** the other a non-negative number, the delta for the non-negative
  199755. ** number will be larger on disk than the literal integer value
  199756. ** was. */
  199757. if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9) ) return;
  199758. fts5DoclistIterInit(p1, &i1);
  199759. fts5DoclistIterInit(p2, &i2);
  199760. while( 1 ){
  199761. if( i1.iRowid<i2.iRowid ){
  199762. /* Copy entry from i1 */
  199763. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  199764. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  199765. fts5DoclistIterNext(&i1);
  199766. if( i1.aPoslist==0 ) break;
  199767. }
  199768. else if( i2.iRowid!=i1.iRowid ){
  199769. /* Copy entry from i2 */
  199770. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  199771. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  199772. fts5DoclistIterNext(&i2);
  199773. if( i2.aPoslist==0 ) break;
  199774. }
  199775. else{
  199776. /* Merge the two position lists. */
  199777. i64 iPos1 = 0;
  199778. i64 iPos2 = 0;
  199779. int iOff1 = 0;
  199780. int iOff2 = 0;
  199781. u8 *a1 = &i1.aPoslist[i1.nSize];
  199782. u8 *a2 = &i2.aPoslist[i2.nSize];
  199783. int nCopy;
  199784. u8 *aCopy;
  199785. i64 iPrev = 0;
  199786. Fts5PoslistWriter writer;
  199787. memset(&writer, 0, sizeof(writer));
  199788. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  199789. fts5BufferZero(&tmp);
  199790. sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
  199791. if( p->rc ) break;
  199792. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  199793. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  199794. assert( iPos1>=0 && iPos2>=0 );
  199795. if( iPos1<iPos2 ){
  199796. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  199797. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  199798. }else{
  199799. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  199800. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  199801. }
  199802. if( iPos1>=0 && iPos2>=0 ){
  199803. while( 1 ){
  199804. if( iPos1<iPos2 ){
  199805. if( iPos1!=iPrev ){
  199806. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  199807. }
  199808. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  199809. if( iPos1<0 ) break;
  199810. }else{
  199811. assert_nc( iPos2!=iPrev );
  199812. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  199813. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  199814. if( iPos2<0 ) break;
  199815. }
  199816. }
  199817. }
  199818. if( iPos1>=0 ){
  199819. if( iPos1!=iPrev ){
  199820. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  199821. }
  199822. aCopy = &a1[iOff1];
  199823. nCopy = i1.nPoslist - iOff1;
  199824. }else{
  199825. assert( iPos2>=0 && iPos2!=iPrev );
  199826. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  199827. aCopy = &a2[iOff2];
  199828. nCopy = i2.nPoslist - iOff2;
  199829. }
  199830. if( nCopy>0 ){
  199831. fts5BufferSafeAppendBlob(&tmp, aCopy, nCopy);
  199832. }
  199833. /* WRITEPOSLISTSIZE */
  199834. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  199835. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  199836. fts5DoclistIterNext(&i1);
  199837. fts5DoclistIterNext(&i2);
  199838. assert( out.n<=(p1->n+p2->n+9) );
  199839. if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
  199840. }
  199841. }
  199842. if( i1.aPoslist ){
  199843. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  199844. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
  199845. }
  199846. else if( i2.aPoslist ){
  199847. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  199848. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
  199849. }
  199850. assert( out.n<=(p1->n+p2->n+9) );
  199851. fts5BufferSet(&p->rc, p1, out.n, out.p);
  199852. fts5BufferFree(&tmp);
  199853. fts5BufferFree(&out);
  199854. }
  199855. }
  199856. static void fts5SetupPrefixIter(
  199857. Fts5Index *p, /* Index to read from */
  199858. int bDesc, /* True for "ORDER BY rowid DESC" */
  199859. const u8 *pToken, /* Buffer containing prefix to match */
  199860. int nToken, /* Size of buffer pToken in bytes */
  199861. Fts5Colset *pColset, /* Restrict matches to these columns */
  199862. Fts5Iter **ppIter /* OUT: New iterator */
  199863. ){
  199864. Fts5Structure *pStruct;
  199865. Fts5Buffer *aBuf;
  199866. const int nBuf = 32;
  199867. void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
  199868. void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
  199869. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  199870. xMerge = fts5MergeRowidLists;
  199871. xAppend = fts5AppendRowid;
  199872. }else{
  199873. xMerge = fts5MergePrefixLists;
  199874. xAppend = fts5AppendPoslist;
  199875. }
  199876. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  199877. pStruct = fts5StructureRead(p);
  199878. if( aBuf && pStruct ){
  199879. const int flags = FTS5INDEX_QUERY_SCAN
  199880. | FTS5INDEX_QUERY_SKIPEMPTY
  199881. | FTS5INDEX_QUERY_NOOUTPUT;
  199882. int i;
  199883. i64 iLastRowid = 0;
  199884. Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
  199885. Fts5Data *pData;
  199886. Fts5Buffer doclist;
  199887. int bNewTerm = 1;
  199888. memset(&doclist, 0, sizeof(doclist));
  199889. fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
  199890. fts5IterSetOutputCb(&p->rc, p1);
  199891. for( /* no-op */ ;
  199892. fts5MultiIterEof(p, p1)==0;
  199893. fts5MultiIterNext2(p, p1, &bNewTerm)
  199894. ){
  199895. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  199896. int nTerm = pSeg->term.n;
  199897. const u8 *pTerm = pSeg->term.p;
  199898. p1->xSetOutputs(p1, pSeg);
  199899. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  199900. if( bNewTerm ){
  199901. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  199902. }
  199903. if( p1->base.nData==0 ) continue;
  199904. if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
  199905. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  199906. assert( i<nBuf );
  199907. if( aBuf[i].n==0 ){
  199908. fts5BufferSwap(&doclist, &aBuf[i]);
  199909. fts5BufferZero(&doclist);
  199910. }else{
  199911. xMerge(p, &doclist, &aBuf[i]);
  199912. fts5BufferZero(&aBuf[i]);
  199913. }
  199914. }
  199915. iLastRowid = 0;
  199916. }
  199917. xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
  199918. iLastRowid = p1->base.iRowid;
  199919. }
  199920. for(i=0; i<nBuf; i++){
  199921. if( p->rc==SQLITE_OK ){
  199922. xMerge(p, &doclist, &aBuf[i]);
  199923. }
  199924. fts5BufferFree(&aBuf[i]);
  199925. }
  199926. fts5MultiIterFree(p1);
  199927. pData = fts5IdxMalloc(p, sizeof(Fts5Data)+doclist.n+FTS5_DATA_ZERO_PADDING);
  199928. if( pData ){
  199929. pData->p = (u8*)&pData[1];
  199930. pData->nn = pData->szLeaf = doclist.n;
  199931. if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
  199932. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  199933. }
  199934. fts5BufferFree(&doclist);
  199935. }
  199936. fts5StructureRelease(pStruct);
  199937. sqlite3_free(aBuf);
  199938. }
  199939. /*
  199940. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  199941. ** to the document with rowid iRowid.
  199942. */
  199943. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  199944. assert( p->rc==SQLITE_OK );
  199945. /* Allocate the hash table if it has not already been allocated */
  199946. if( p->pHash==0 ){
  199947. p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
  199948. }
  199949. /* Flush the hash table to disk if required */
  199950. if( iRowid<p->iWriteRowid
  199951. || (iRowid==p->iWriteRowid && p->bDelete==0)
  199952. || (p->nPendingData > p->pConfig->nHashSize)
  199953. ){
  199954. fts5IndexFlush(p);
  199955. }
  199956. p->iWriteRowid = iRowid;
  199957. p->bDelete = bDelete;
  199958. return fts5IndexReturn(p);
  199959. }
  199960. /*
  199961. ** Commit data to disk.
  199962. */
  199963. static int sqlite3Fts5IndexSync(Fts5Index *p){
  199964. assert( p->rc==SQLITE_OK );
  199965. fts5IndexFlush(p);
  199966. fts5CloseReader(p);
  199967. return fts5IndexReturn(p);
  199968. }
  199969. /*
  199970. ** Discard any data stored in the in-memory hash tables. Do not write it
  199971. ** to the database. Additionally, assume that the contents of the %_data
  199972. ** table may have changed on disk. So any in-memory caches of %_data
  199973. ** records must be invalidated.
  199974. */
  199975. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  199976. fts5CloseReader(p);
  199977. fts5IndexDiscardData(p);
  199978. fts5StructureInvalidate(p);
  199979. /* assert( p->rc==SQLITE_OK ); */
  199980. return SQLITE_OK;
  199981. }
  199982. /*
  199983. ** The %_data table is completely empty when this function is called. This
  199984. ** function populates it with the initial structure objects for each index,
  199985. ** and the initial version of the "averages" record (a zero-byte blob).
  199986. */
  199987. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  199988. Fts5Structure s;
  199989. fts5StructureInvalidate(p);
  199990. memset(&s, 0, sizeof(Fts5Structure));
  199991. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  199992. fts5StructureWrite(p, &s);
  199993. return fts5IndexReturn(p);
  199994. }
  199995. /*
  199996. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  199997. ** and initialize the underlying %_data table.
  199998. **
  199999. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  200000. ** Otherwise, set *pp to NULL and return an SQLite error code.
  200001. */
  200002. static int sqlite3Fts5IndexOpen(
  200003. Fts5Config *pConfig,
  200004. int bCreate,
  200005. Fts5Index **pp,
  200006. char **pzErr
  200007. ){
  200008. int rc = SQLITE_OK;
  200009. Fts5Index *p; /* New object */
  200010. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  200011. if( rc==SQLITE_OK ){
  200012. p->pConfig = pConfig;
  200013. p->nWorkUnit = FTS5_WORK_UNIT;
  200014. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  200015. if( p->zDataTbl && bCreate ){
  200016. rc = sqlite3Fts5CreateTable(
  200017. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  200018. );
  200019. if( rc==SQLITE_OK ){
  200020. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  200021. "segid, term, pgno, PRIMARY KEY(segid, term)",
  200022. 1, pzErr
  200023. );
  200024. }
  200025. if( rc==SQLITE_OK ){
  200026. rc = sqlite3Fts5IndexReinit(p);
  200027. }
  200028. }
  200029. }
  200030. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  200031. if( rc ){
  200032. sqlite3Fts5IndexClose(p);
  200033. *pp = 0;
  200034. }
  200035. return rc;
  200036. }
  200037. /*
  200038. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  200039. */
  200040. static int sqlite3Fts5IndexClose(Fts5Index *p){
  200041. int rc = SQLITE_OK;
  200042. if( p ){
  200043. assert( p->pReader==0 );
  200044. fts5StructureInvalidate(p);
  200045. sqlite3_finalize(p->pWriter);
  200046. sqlite3_finalize(p->pDeleter);
  200047. sqlite3_finalize(p->pIdxWriter);
  200048. sqlite3_finalize(p->pIdxDeleter);
  200049. sqlite3_finalize(p->pIdxSelect);
  200050. sqlite3_finalize(p->pDataVersion);
  200051. sqlite3Fts5HashFree(p->pHash);
  200052. sqlite3_free(p->zDataTbl);
  200053. sqlite3_free(p);
  200054. }
  200055. return rc;
  200056. }
  200057. /*
  200058. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  200059. ** size. Return the number of bytes in the nChar character prefix of the
  200060. ** buffer, or 0 if there are less than nChar characters in total.
  200061. */
  200062. static int sqlite3Fts5IndexCharlenToBytelen(
  200063. const char *p,
  200064. int nByte,
  200065. int nChar
  200066. ){
  200067. int n = 0;
  200068. int i;
  200069. for(i=0; i<nChar; i++){
  200070. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  200071. if( (unsigned char)p[n++]>=0xc0 ){
  200072. while( (p[n] & 0xc0)==0x80 ){
  200073. n++;
  200074. if( n>=nByte ) break;
  200075. }
  200076. }
  200077. }
  200078. return n;
  200079. }
  200080. /*
  200081. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  200082. ** unicode characters in the string.
  200083. */
  200084. static int fts5IndexCharlen(const char *pIn, int nIn){
  200085. int nChar = 0;
  200086. int i = 0;
  200087. while( i<nIn ){
  200088. if( (unsigned char)pIn[i++]>=0xc0 ){
  200089. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  200090. }
  200091. nChar++;
  200092. }
  200093. return nChar;
  200094. }
  200095. /*
  200096. ** Insert or remove data to or from the index. Each time a document is
  200097. ** added to or removed from the index, this function is called one or more
  200098. ** times.
  200099. **
  200100. ** For an insert, it must be called once for each token in the new document.
  200101. ** If the operation is a delete, it must be called (at least) once for each
  200102. ** unique token in the document with an iCol value less than zero. The iPos
  200103. ** argument is ignored for a delete.
  200104. */
  200105. static int sqlite3Fts5IndexWrite(
  200106. Fts5Index *p, /* Index to write to */
  200107. int iCol, /* Column token appears in (-ve -> delete) */
  200108. int iPos, /* Position of token within column */
  200109. const char *pToken, int nToken /* Token to add or remove to or from index */
  200110. ){
  200111. int i; /* Used to iterate through indexes */
  200112. int rc = SQLITE_OK; /* Return code */
  200113. Fts5Config *pConfig = p->pConfig;
  200114. assert( p->rc==SQLITE_OK );
  200115. assert( (iCol<0)==p->bDelete );
  200116. /* Add the entry to the main terms index. */
  200117. rc = sqlite3Fts5HashWrite(
  200118. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  200119. );
  200120. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  200121. const int nChar = pConfig->aPrefix[i];
  200122. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  200123. if( nByte ){
  200124. rc = sqlite3Fts5HashWrite(p->pHash,
  200125. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  200126. nByte
  200127. );
  200128. }
  200129. }
  200130. return rc;
  200131. }
  200132. /*
  200133. ** Open a new iterator to iterate though all rowid that match the
  200134. ** specified token or token prefix.
  200135. */
  200136. static int sqlite3Fts5IndexQuery(
  200137. Fts5Index *p, /* FTS index to query */
  200138. const char *pToken, int nToken, /* Token (or prefix) to query for */
  200139. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  200140. Fts5Colset *pColset, /* Match these columns only */
  200141. Fts5IndexIter **ppIter /* OUT: New iterator object */
  200142. ){
  200143. Fts5Config *pConfig = p->pConfig;
  200144. Fts5Iter *pRet = 0;
  200145. Fts5Buffer buf = {0, 0, 0};
  200146. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  200147. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  200148. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  200149. int iIdx = 0; /* Index to search */
  200150. if( nToken ) memcpy(&buf.p[1], pToken, nToken);
  200151. /* Figure out which index to search and set iIdx accordingly. If this
  200152. ** is a prefix query for which there is no prefix index, set iIdx to
  200153. ** greater than pConfig->nPrefix to indicate that the query will be
  200154. ** satisfied by scanning multiple terms in the main index.
  200155. **
  200156. ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
  200157. ** prefix-query. Instead of using a prefix-index (if one exists),
  200158. ** evaluate the prefix query using the main FTS index. This is used
  200159. ** for internal sanity checking by the integrity-check in debug
  200160. ** mode only. */
  200161. #ifdef SQLITE_DEBUG
  200162. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  200163. assert( flags & FTS5INDEX_QUERY_PREFIX );
  200164. iIdx = 1+pConfig->nPrefix;
  200165. }else
  200166. #endif
  200167. if( flags & FTS5INDEX_QUERY_PREFIX ){
  200168. int nChar = fts5IndexCharlen(pToken, nToken);
  200169. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  200170. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  200171. }
  200172. }
  200173. if( iIdx<=pConfig->nPrefix ){
  200174. /* Straight index lookup */
  200175. Fts5Structure *pStruct = fts5StructureRead(p);
  200176. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  200177. if( pStruct ){
  200178. fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
  200179. pColset, buf.p, nToken+1, -1, 0, &pRet
  200180. );
  200181. fts5StructureRelease(pStruct);
  200182. }
  200183. }else{
  200184. /* Scan multiple terms in the main index */
  200185. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  200186. buf.p[0] = FTS5_MAIN_PREFIX;
  200187. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  200188. assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
  200189. fts5IterSetOutputCb(&p->rc, pRet);
  200190. if( p->rc==SQLITE_OK ){
  200191. Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
  200192. if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
  200193. }
  200194. }
  200195. if( p->rc ){
  200196. sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
  200197. pRet = 0;
  200198. fts5CloseReader(p);
  200199. }
  200200. *ppIter = (Fts5IndexIter*)pRet;
  200201. sqlite3Fts5BufferFree(&buf);
  200202. }
  200203. return fts5IndexReturn(p);
  200204. }
  200205. /*
  200206. ** Return true if the iterator passed as the only argument is at EOF.
  200207. */
  200208. /*
  200209. ** Move to the next matching rowid.
  200210. */
  200211. static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
  200212. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  200213. assert( pIter->pIndex->rc==SQLITE_OK );
  200214. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  200215. return fts5IndexReturn(pIter->pIndex);
  200216. }
  200217. /*
  200218. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  200219. */
  200220. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
  200221. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  200222. Fts5Index *p = pIter->pIndex;
  200223. assert( pIter->pIndex->rc==SQLITE_OK );
  200224. fts5MultiIterNext(p, pIter, 0, 0);
  200225. if( p->rc==SQLITE_OK ){
  200226. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  200227. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  200228. fts5DataRelease(pSeg->pLeaf);
  200229. pSeg->pLeaf = 0;
  200230. pIter->base.bEof = 1;
  200231. }
  200232. }
  200233. return fts5IndexReturn(pIter->pIndex);
  200234. }
  200235. /*
  200236. ** Move to the next matching rowid that occurs at or after iMatch. The
  200237. ** definition of "at or after" depends on whether this iterator iterates
  200238. ** in ascending or descending rowid order.
  200239. */
  200240. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
  200241. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  200242. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  200243. return fts5IndexReturn(pIter->pIndex);
  200244. }
  200245. /*
  200246. ** Return the current term.
  200247. */
  200248. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
  200249. int n;
  200250. const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
  200251. *pn = n-1;
  200252. return &z[1];
  200253. }
  200254. /*
  200255. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  200256. */
  200257. static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
  200258. if( pIndexIter ){
  200259. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  200260. Fts5Index *pIndex = pIter->pIndex;
  200261. fts5MultiIterFree(pIter);
  200262. fts5CloseReader(pIndex);
  200263. }
  200264. }
  200265. /*
  200266. ** Read and decode the "averages" record from the database.
  200267. **
  200268. ** Parameter anSize must point to an array of size nCol, where nCol is
  200269. ** the number of user defined columns in the FTS table.
  200270. */
  200271. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  200272. int nCol = p->pConfig->nCol;
  200273. Fts5Data *pData;
  200274. *pnRow = 0;
  200275. memset(anSize, 0, sizeof(i64) * nCol);
  200276. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  200277. if( p->rc==SQLITE_OK && pData->nn ){
  200278. int i = 0;
  200279. int iCol;
  200280. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  200281. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  200282. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  200283. }
  200284. }
  200285. fts5DataRelease(pData);
  200286. return fts5IndexReturn(p);
  200287. }
  200288. /*
  200289. ** Replace the current "averages" record with the contents of the buffer
  200290. ** supplied as the second argument.
  200291. */
  200292. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  200293. assert( p->rc==SQLITE_OK );
  200294. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  200295. return fts5IndexReturn(p);
  200296. }
  200297. /*
  200298. ** Return the total number of blocks this module has read from the %_data
  200299. ** table since it was created.
  200300. */
  200301. static int sqlite3Fts5IndexReads(Fts5Index *p){
  200302. return p->nRead;
  200303. }
  200304. /*
  200305. ** Set the 32-bit cookie value stored at the start of all structure
  200306. ** records to the value passed as the second argument.
  200307. **
  200308. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  200309. ** occurs.
  200310. */
  200311. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  200312. int rc; /* Return code */
  200313. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  200314. u8 aCookie[4]; /* Binary representation of iNew */
  200315. sqlite3_blob *pBlob = 0;
  200316. assert( p->rc==SQLITE_OK );
  200317. sqlite3Fts5Put32(aCookie, iNew);
  200318. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  200319. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  200320. );
  200321. if( rc==SQLITE_OK ){
  200322. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  200323. rc = sqlite3_blob_close(pBlob);
  200324. }
  200325. return rc;
  200326. }
  200327. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  200328. Fts5Structure *pStruct;
  200329. pStruct = fts5StructureRead(p);
  200330. fts5StructureRelease(pStruct);
  200331. return fts5IndexReturn(p);
  200332. }
  200333. /*************************************************************************
  200334. **************************************************************************
  200335. ** Below this point is the implementation of the integrity-check
  200336. ** functionality.
  200337. */
  200338. /*
  200339. ** Return a simple checksum value based on the arguments.
  200340. */
  200341. static u64 sqlite3Fts5IndexEntryCksum(
  200342. i64 iRowid,
  200343. int iCol,
  200344. int iPos,
  200345. int iIdx,
  200346. const char *pTerm,
  200347. int nTerm
  200348. ){
  200349. int i;
  200350. u64 ret = iRowid;
  200351. ret += (ret<<3) + iCol;
  200352. ret += (ret<<3) + iPos;
  200353. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  200354. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  200355. return ret;
  200356. }
  200357. #ifdef SQLITE_DEBUG
  200358. /*
  200359. ** This function is purely an internal test. It does not contribute to
  200360. ** FTS functionality, or even the integrity-check, in any way.
  200361. **
  200362. ** Instead, it tests that the same set of pgno/rowid combinations are
  200363. ** visited regardless of whether the doclist-index identified by parameters
  200364. ** iSegid/iLeaf is iterated in forwards or reverse order.
  200365. */
  200366. static void fts5TestDlidxReverse(
  200367. Fts5Index *p,
  200368. int iSegid, /* Segment id to load from */
  200369. int iLeaf /* Load doclist-index for this leaf */
  200370. ){
  200371. Fts5DlidxIter *pDlidx = 0;
  200372. u64 cksum1 = 13;
  200373. u64 cksum2 = 13;
  200374. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  200375. fts5DlidxIterEof(p, pDlidx)==0;
  200376. fts5DlidxIterNext(p, pDlidx)
  200377. ){
  200378. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  200379. int pgno = fts5DlidxIterPgno(pDlidx);
  200380. assert( pgno>iLeaf );
  200381. cksum1 += iRowid + ((i64)pgno<<32);
  200382. }
  200383. fts5DlidxIterFree(pDlidx);
  200384. pDlidx = 0;
  200385. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  200386. fts5DlidxIterEof(p, pDlidx)==0;
  200387. fts5DlidxIterPrev(p, pDlidx)
  200388. ){
  200389. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  200390. int pgno = fts5DlidxIterPgno(pDlidx);
  200391. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  200392. cksum2 += iRowid + ((i64)pgno<<32);
  200393. }
  200394. fts5DlidxIterFree(pDlidx);
  200395. pDlidx = 0;
  200396. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  200397. }
  200398. static int fts5QueryCksum(
  200399. Fts5Index *p, /* Fts5 index object */
  200400. int iIdx,
  200401. const char *z, /* Index key to query for */
  200402. int n, /* Size of index key in bytes */
  200403. int flags, /* Flags for Fts5IndexQuery */
  200404. u64 *pCksum /* IN/OUT: Checksum value */
  200405. ){
  200406. int eDetail = p->pConfig->eDetail;
  200407. u64 cksum = *pCksum;
  200408. Fts5IndexIter *pIter = 0;
  200409. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
  200410. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
  200411. i64 rowid = pIter->iRowid;
  200412. if( eDetail==FTS5_DETAIL_NONE ){
  200413. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
  200414. }else{
  200415. Fts5PoslistReader sReader;
  200416. for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
  200417. sReader.bEof==0;
  200418. sqlite3Fts5PoslistReaderNext(&sReader)
  200419. ){
  200420. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  200421. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  200422. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  200423. }
  200424. }
  200425. if( rc==SQLITE_OK ){
  200426. rc = sqlite3Fts5IterNext(pIter);
  200427. }
  200428. }
  200429. sqlite3Fts5IterClose(pIter);
  200430. *pCksum = cksum;
  200431. return rc;
  200432. }
  200433. /*
  200434. ** This function is also purely an internal test. It does not contribute to
  200435. ** FTS functionality, or even the integrity-check, in any way.
  200436. */
  200437. static void fts5TestTerm(
  200438. Fts5Index *p,
  200439. Fts5Buffer *pPrev, /* Previous term */
  200440. const char *z, int n, /* Possibly new term to test */
  200441. u64 expected,
  200442. u64 *pCksum
  200443. ){
  200444. int rc = p->rc;
  200445. if( pPrev->n==0 ){
  200446. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  200447. }else
  200448. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  200449. u64 cksum3 = *pCksum;
  200450. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  200451. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  200452. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  200453. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  200454. u64 ck1 = 0;
  200455. u64 ck2 = 0;
  200456. /* Check that the results returned for ASC and DESC queries are
  200457. ** the same. If not, call this corruption. */
  200458. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  200459. if( rc==SQLITE_OK ){
  200460. int f = flags|FTS5INDEX_QUERY_DESC;
  200461. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  200462. }
  200463. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  200464. /* If this is a prefix query, check that the results returned if the
  200465. ** the index is disabled are the same. In both ASC and DESC order.
  200466. **
  200467. ** This check may only be performed if the hash table is empty. This
  200468. ** is because the hash table only supports a single scan query at
  200469. ** a time, and the multi-iter loop from which this function is called
  200470. ** is already performing such a scan. */
  200471. if( p->nPendingData==0 ){
  200472. if( iIdx>0 && rc==SQLITE_OK ){
  200473. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  200474. ck2 = 0;
  200475. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  200476. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  200477. }
  200478. if( iIdx>0 && rc==SQLITE_OK ){
  200479. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  200480. ck2 = 0;
  200481. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  200482. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  200483. }
  200484. }
  200485. cksum3 ^= ck1;
  200486. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  200487. if( rc==SQLITE_OK && cksum3!=expected ){
  200488. rc = FTS5_CORRUPT;
  200489. }
  200490. *pCksum = cksum3;
  200491. }
  200492. p->rc = rc;
  200493. }
  200494. #else
  200495. # define fts5TestDlidxReverse(x,y,z)
  200496. # define fts5TestTerm(u,v,w,x,y,z)
  200497. #endif
  200498. /*
  200499. ** Check that:
  200500. **
  200501. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  200502. ** contain zero terms.
  200503. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  200504. ** contain zero rowids.
  200505. */
  200506. static void fts5IndexIntegrityCheckEmpty(
  200507. Fts5Index *p,
  200508. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  200509. int iFirst,
  200510. int iNoRowid,
  200511. int iLast
  200512. ){
  200513. int i;
  200514. /* Now check that the iter.nEmpty leaves following the current leaf
  200515. ** (a) exist and (b) contain no terms. */
  200516. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  200517. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  200518. if( pLeaf ){
  200519. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  200520. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  200521. }
  200522. fts5DataRelease(pLeaf);
  200523. }
  200524. }
  200525. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  200526. int iTermOff = 0;
  200527. int ii;
  200528. Fts5Buffer buf1 = {0,0,0};
  200529. Fts5Buffer buf2 = {0,0,0};
  200530. ii = pLeaf->szLeaf;
  200531. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  200532. int res;
  200533. int iOff;
  200534. int nIncr;
  200535. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  200536. iTermOff += nIncr;
  200537. iOff = iTermOff;
  200538. if( iOff>=pLeaf->szLeaf ){
  200539. p->rc = FTS5_CORRUPT;
  200540. }else if( iTermOff==nIncr ){
  200541. int nByte;
  200542. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  200543. if( (iOff+nByte)>pLeaf->szLeaf ){
  200544. p->rc = FTS5_CORRUPT;
  200545. }else{
  200546. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  200547. }
  200548. }else{
  200549. int nKeep, nByte;
  200550. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  200551. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  200552. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  200553. p->rc = FTS5_CORRUPT;
  200554. }else{
  200555. buf1.n = nKeep;
  200556. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  200557. }
  200558. if( p->rc==SQLITE_OK ){
  200559. res = fts5BufferCompare(&buf1, &buf2);
  200560. if( res<=0 ) p->rc = FTS5_CORRUPT;
  200561. }
  200562. }
  200563. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  200564. }
  200565. fts5BufferFree(&buf1);
  200566. fts5BufferFree(&buf2);
  200567. }
  200568. static void fts5IndexIntegrityCheckSegment(
  200569. Fts5Index *p, /* FTS5 backend object */
  200570. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  200571. ){
  200572. Fts5Config *pConfig = p->pConfig;
  200573. sqlite3_stmt *pStmt = 0;
  200574. int rc2;
  200575. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  200576. int iDlidxPrevLeaf = pSeg->pgnoLast;
  200577. if( pSeg->pgnoFirst==0 ) return;
  200578. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  200579. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
  200580. pConfig->zDb, pConfig->zName, pSeg->iSegid
  200581. ));
  200582. /* Iterate through the b-tree hierarchy. */
  200583. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  200584. i64 iRow; /* Rowid for this leaf */
  200585. Fts5Data *pLeaf; /* Data for this leaf */
  200586. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  200587. const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
  200588. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  200589. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  200590. /* If the leaf in question has already been trimmed from the segment,
  200591. ** ignore this b-tree entry. Otherwise, load it into memory. */
  200592. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  200593. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  200594. pLeaf = fts5LeafRead(p, iRow);
  200595. if( pLeaf==0 ) break;
  200596. /* Check that the leaf contains at least one term, and that it is equal
  200597. ** to or larger than the split-key in zIdxTerm. Also check that if there
  200598. ** is also a rowid pointer within the leaf page header, it points to a
  200599. ** location before the term. */
  200600. if( pLeaf->nn<=pLeaf->szLeaf ){
  200601. p->rc = FTS5_CORRUPT;
  200602. }else{
  200603. int iOff; /* Offset of first term on leaf */
  200604. int iRowidOff; /* Offset of first rowid on leaf */
  200605. int nTerm; /* Size of term on leaf in bytes */
  200606. int res; /* Comparison of term and split-key */
  200607. iOff = fts5LeafFirstTermOff(pLeaf);
  200608. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  200609. if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){
  200610. p->rc = FTS5_CORRUPT;
  200611. }else{
  200612. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  200613. res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  200614. if( res==0 ) res = nTerm - nIdxTerm;
  200615. if( res<0 ) p->rc = FTS5_CORRUPT;
  200616. }
  200617. fts5IntegrityCheckPgidx(p, pLeaf);
  200618. }
  200619. fts5DataRelease(pLeaf);
  200620. if( p->rc ) break;
  200621. /* Now check that the iter.nEmpty leaves following the current leaf
  200622. ** (a) exist and (b) contain no terms. */
  200623. fts5IndexIntegrityCheckEmpty(
  200624. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  200625. );
  200626. if( p->rc ) break;
  200627. /* If there is a doclist-index, check that it looks right. */
  200628. if( bIdxDlidx ){
  200629. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  200630. int iPrevLeaf = iIdxLeaf;
  200631. int iSegid = pSeg->iSegid;
  200632. int iPg = 0;
  200633. i64 iKey;
  200634. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  200635. fts5DlidxIterEof(p, pDlidx)==0;
  200636. fts5DlidxIterNext(p, pDlidx)
  200637. ){
  200638. /* Check any rowid-less pages that occur before the current leaf. */
  200639. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  200640. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  200641. pLeaf = fts5DataRead(p, iKey);
  200642. if( pLeaf ){
  200643. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  200644. fts5DataRelease(pLeaf);
  200645. }
  200646. }
  200647. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  200648. /* Check that the leaf page indicated by the iterator really does
  200649. ** contain the rowid suggested by the same. */
  200650. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  200651. pLeaf = fts5DataRead(p, iKey);
  200652. if( pLeaf ){
  200653. i64 iRowid;
  200654. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  200655. ASSERT_SZLEAF_OK(pLeaf);
  200656. if( iRowidOff>=pLeaf->szLeaf ){
  200657. p->rc = FTS5_CORRUPT;
  200658. }else{
  200659. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  200660. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  200661. }
  200662. fts5DataRelease(pLeaf);
  200663. }
  200664. }
  200665. iDlidxPrevLeaf = iPg;
  200666. fts5DlidxIterFree(pDlidx);
  200667. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  200668. }else{
  200669. iDlidxPrevLeaf = pSeg->pgnoLast;
  200670. /* TODO: Check there is no doclist index */
  200671. }
  200672. iIdxPrevLeaf = iIdxLeaf;
  200673. }
  200674. rc2 = sqlite3_finalize(pStmt);
  200675. if( p->rc==SQLITE_OK ) p->rc = rc2;
  200676. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  200677. #if 0
  200678. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  200679. p->rc = FTS5_CORRUPT;
  200680. }
  200681. #endif
  200682. }
  200683. /*
  200684. ** Run internal checks to ensure that the FTS index (a) is internally
  200685. ** consistent and (b) contains entries for which the XOR of the checksums
  200686. ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
  200687. **
  200688. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  200689. ** checksum does not match. Return SQLITE_OK if all checks pass without
  200690. ** error, or some other SQLite error code if another error (e.g. OOM)
  200691. ** occurs.
  200692. */
  200693. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  200694. int eDetail = p->pConfig->eDetail;
  200695. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  200696. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  200697. Fts5Iter *pIter; /* Used to iterate through entire index */
  200698. Fts5Structure *pStruct; /* Index structure */
  200699. #ifdef SQLITE_DEBUG
  200700. /* Used by extra internal tests only run if NDEBUG is not defined */
  200701. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  200702. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  200703. #endif
  200704. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  200705. /* Load the FTS index structure */
  200706. pStruct = fts5StructureRead(p);
  200707. /* Check that the internal nodes of each segment match the leaves */
  200708. if( pStruct ){
  200709. int iLvl, iSeg;
  200710. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  200711. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  200712. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  200713. fts5IndexIntegrityCheckSegment(p, pSeg);
  200714. }
  200715. }
  200716. }
  200717. /* The cksum argument passed to this function is a checksum calculated
  200718. ** based on all expected entries in the FTS index (including prefix index
  200719. ** entries). This block checks that a checksum calculated based on the
  200720. ** actual contents of FTS index is identical.
  200721. **
  200722. ** Two versions of the same checksum are calculated. The first (stack
  200723. ** variable cksum2) based on entries extracted from the full-text index
  200724. ** while doing a linear scan of each individual index in turn.
  200725. **
  200726. ** As each term visited by the linear scans, a separate query for the
  200727. ** same term is performed. cksum3 is calculated based on the entries
  200728. ** extracted by these queries.
  200729. */
  200730. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
  200731. fts5MultiIterEof(p, pIter)==0;
  200732. fts5MultiIterNext(p, pIter, 0, 0)
  200733. ){
  200734. int n; /* Size of term in bytes */
  200735. i64 iPos = 0; /* Position read from poslist */
  200736. int iOff = 0; /* Offset within poslist */
  200737. i64 iRowid = fts5MultiIterRowid(pIter);
  200738. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  200739. /* If this is a new term, query for it. Update cksum3 with the results. */
  200740. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  200741. if( eDetail==FTS5_DETAIL_NONE ){
  200742. if( 0==fts5MultiIterIsEmpty(p, pIter) ){
  200743. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
  200744. }
  200745. }else{
  200746. poslist.n = 0;
  200747. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
  200748. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  200749. int iCol = FTS5_POS2COLUMN(iPos);
  200750. int iTokOff = FTS5_POS2OFFSET(iPos);
  200751. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  200752. }
  200753. }
  200754. }
  200755. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  200756. fts5MultiIterFree(pIter);
  200757. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  200758. fts5StructureRelease(pStruct);
  200759. #ifdef SQLITE_DEBUG
  200760. fts5BufferFree(&term);
  200761. #endif
  200762. fts5BufferFree(&poslist);
  200763. return fts5IndexReturn(p);
  200764. }
  200765. /*************************************************************************
  200766. **************************************************************************
  200767. ** Below this point is the implementation of the fts5_decode() scalar
  200768. ** function only.
  200769. */
  200770. /*
  200771. ** Decode a segment-data rowid from the %_data table. This function is
  200772. ** the opposite of macro FTS5_SEGMENT_ROWID().
  200773. */
  200774. static void fts5DecodeRowid(
  200775. i64 iRowid, /* Rowid from %_data table */
  200776. int *piSegid, /* OUT: Segment id */
  200777. int *pbDlidx, /* OUT: Dlidx flag */
  200778. int *piHeight, /* OUT: Height */
  200779. int *piPgno /* OUT: Page number */
  200780. ){
  200781. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  200782. iRowid >>= FTS5_DATA_PAGE_B;
  200783. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  200784. iRowid >>= FTS5_DATA_HEIGHT_B;
  200785. *pbDlidx = (int)(iRowid & 0x0001);
  200786. iRowid >>= FTS5_DATA_DLI_B;
  200787. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  200788. }
  200789. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  200790. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  200791. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  200792. if( iSegid==0 ){
  200793. if( iKey==FTS5_AVERAGES_ROWID ){
  200794. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  200795. }else{
  200796. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  200797. }
  200798. }
  200799. else{
  200800. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  200801. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  200802. );
  200803. }
  200804. }
  200805. static void fts5DebugStructure(
  200806. int *pRc, /* IN/OUT: error code */
  200807. Fts5Buffer *pBuf,
  200808. Fts5Structure *p
  200809. ){
  200810. int iLvl, iSeg; /* Iterate through levels, segments */
  200811. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  200812. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  200813. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  200814. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  200815. );
  200816. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  200817. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  200818. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  200819. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  200820. );
  200821. }
  200822. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  200823. }
  200824. }
  200825. /*
  200826. ** This is part of the fts5_decode() debugging aid.
  200827. **
  200828. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  200829. ** function appends a human-readable representation of the same object
  200830. ** to the buffer passed as the second argument.
  200831. */
  200832. static void fts5DecodeStructure(
  200833. int *pRc, /* IN/OUT: error code */
  200834. Fts5Buffer *pBuf,
  200835. const u8 *pBlob, int nBlob
  200836. ){
  200837. int rc; /* Return code */
  200838. Fts5Structure *p = 0; /* Decoded structure object */
  200839. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  200840. if( rc!=SQLITE_OK ){
  200841. *pRc = rc;
  200842. return;
  200843. }
  200844. fts5DebugStructure(pRc, pBuf, p);
  200845. fts5StructureRelease(p);
  200846. }
  200847. /*
  200848. ** This is part of the fts5_decode() debugging aid.
  200849. **
  200850. ** Arguments pBlob/nBlob contain an "averages" record. This function
  200851. ** appends a human-readable representation of record to the buffer passed
  200852. ** as the second argument.
  200853. */
  200854. static void fts5DecodeAverages(
  200855. int *pRc, /* IN/OUT: error code */
  200856. Fts5Buffer *pBuf,
  200857. const u8 *pBlob, int nBlob
  200858. ){
  200859. int i = 0;
  200860. const char *zSpace = "";
  200861. while( i<nBlob ){
  200862. u64 iVal;
  200863. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  200864. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  200865. zSpace = " ";
  200866. }
  200867. }
  200868. /*
  200869. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  200870. ** each varint and append its string representation to buffer pBuf. Return
  200871. ** after either the input buffer is exhausted or a 0 value is read.
  200872. **
  200873. ** The return value is the number of bytes read from the input buffer.
  200874. */
  200875. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  200876. int iOff = 0;
  200877. while( iOff<n ){
  200878. int iVal;
  200879. iOff += fts5GetVarint32(&a[iOff], iVal);
  200880. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  200881. }
  200882. return iOff;
  200883. }
  200884. /*
  200885. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  200886. ** may or may not finish within the buffer. This function appends a text
  200887. ** representation of the part of the doclist that is present to buffer
  200888. ** pBuf.
  200889. **
  200890. ** The return value is the number of bytes read from the input buffer.
  200891. */
  200892. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  200893. i64 iDocid = 0;
  200894. int iOff = 0;
  200895. if( n>0 ){
  200896. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  200897. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  200898. }
  200899. while( iOff<n ){
  200900. int nPos;
  200901. int bDel;
  200902. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  200903. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  200904. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  200905. if( iOff<n ){
  200906. i64 iDelta;
  200907. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  200908. iDocid += iDelta;
  200909. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  200910. }
  200911. }
  200912. return iOff;
  200913. }
  200914. /*
  200915. ** This function is part of the fts5_decode() debugging function. It is
  200916. ** only ever used with detail=none tables.
  200917. **
  200918. ** Buffer (pData/nData) contains a doclist in the format used by detail=none
  200919. ** tables. This function appends a human-readable version of that list to
  200920. ** buffer pBuf.
  200921. **
  200922. ** If *pRc is other than SQLITE_OK when this function is called, it is a
  200923. ** no-op. If an OOM or other error occurs within this function, *pRc is
  200924. ** set to an SQLite error code before returning. The final state of buffer
  200925. ** pBuf is undefined in this case.
  200926. */
  200927. static void fts5DecodeRowidList(
  200928. int *pRc, /* IN/OUT: Error code */
  200929. Fts5Buffer *pBuf, /* Buffer to append text to */
  200930. const u8 *pData, int nData /* Data to decode list-of-rowids from */
  200931. ){
  200932. int i = 0;
  200933. i64 iRowid = 0;
  200934. while( i<nData ){
  200935. const char *zApp = "";
  200936. u64 iVal;
  200937. i += sqlite3Fts5GetVarint(&pData[i], &iVal);
  200938. iRowid += iVal;
  200939. if( i<nData && pData[i]==0x00 ){
  200940. i++;
  200941. if( i<nData && pData[i]==0x00 ){
  200942. i++;
  200943. zApp = "+";
  200944. }else{
  200945. zApp = "*";
  200946. }
  200947. }
  200948. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
  200949. }
  200950. }
  200951. /*
  200952. ** The implementation of user-defined scalar function fts5_decode().
  200953. */
  200954. static void fts5DecodeFunction(
  200955. sqlite3_context *pCtx, /* Function call context */
  200956. int nArg, /* Number of args (always 2) */
  200957. sqlite3_value **apVal /* Function arguments */
  200958. ){
  200959. i64 iRowid; /* Rowid for record being decoded */
  200960. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  200961. const u8 *aBlob; int n; /* Record to decode */
  200962. u8 *a = 0;
  200963. Fts5Buffer s; /* Build up text to return here */
  200964. int rc = SQLITE_OK; /* Return code */
  200965. sqlite3_int64 nSpace = 0;
  200966. int eDetailNone = (sqlite3_user_data(pCtx)!=0);
  200967. assert( nArg==2 );
  200968. UNUSED_PARAM(nArg);
  200969. memset(&s, 0, sizeof(Fts5Buffer));
  200970. iRowid = sqlite3_value_int64(apVal[0]);
  200971. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  200972. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  200973. ** buffer overreads even if the record is corrupt. */
  200974. n = sqlite3_value_bytes(apVal[1]);
  200975. aBlob = sqlite3_value_blob(apVal[1]);
  200976. nSpace = n + FTS5_DATA_ZERO_PADDING;
  200977. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  200978. if( a==0 ) goto decode_out;
  200979. if( n>0 ) memcpy(a, aBlob, n);
  200980. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  200981. fts5DebugRowid(&rc, &s, iRowid);
  200982. if( bDlidx ){
  200983. Fts5Data dlidx;
  200984. Fts5DlidxLvl lvl;
  200985. dlidx.p = a;
  200986. dlidx.nn = n;
  200987. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  200988. lvl.pData = &dlidx;
  200989. lvl.iLeafPgno = iPgno;
  200990. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  200991. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  200992. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  200993. );
  200994. }
  200995. }else if( iSegid==0 ){
  200996. if( iRowid==FTS5_AVERAGES_ROWID ){
  200997. fts5DecodeAverages(&rc, &s, a, n);
  200998. }else{
  200999. fts5DecodeStructure(&rc, &s, a, n);
  201000. }
  201001. }else if( eDetailNone ){
  201002. Fts5Buffer term; /* Current term read from page */
  201003. int szLeaf;
  201004. int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  201005. int iTermOff;
  201006. int nKeep = 0;
  201007. int iOff;
  201008. memset(&term, 0, sizeof(Fts5Buffer));
  201009. /* Decode any entries that occur before the first term. */
  201010. if( szLeaf<n ){
  201011. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
  201012. }else{
  201013. iTermOff = szLeaf;
  201014. }
  201015. fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
  201016. iOff = iTermOff;
  201017. while( iOff<szLeaf ){
  201018. int nAppend;
  201019. /* Read the term data for the next term*/
  201020. iOff += fts5GetVarint32(&a[iOff], nAppend);
  201021. term.n = nKeep;
  201022. fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
  201023. sqlite3Fts5BufferAppendPrintf(
  201024. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  201025. );
  201026. iOff += nAppend;
  201027. /* Figure out where the doclist for this term ends */
  201028. if( iPgidxOff<n ){
  201029. int nIncr;
  201030. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
  201031. iTermOff += nIncr;
  201032. }else{
  201033. iTermOff = szLeaf;
  201034. }
  201035. fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
  201036. iOff = iTermOff;
  201037. if( iOff<szLeaf ){
  201038. iOff += fts5GetVarint32(&a[iOff], nKeep);
  201039. }
  201040. }
  201041. fts5BufferFree(&term);
  201042. }else{
  201043. Fts5Buffer term; /* Current term read from page */
  201044. int szLeaf; /* Offset of pgidx in a[] */
  201045. int iPgidxOff;
  201046. int iPgidxPrev = 0; /* Previous value read from pgidx */
  201047. int iTermOff = 0;
  201048. int iRowidOff = 0;
  201049. int iOff;
  201050. int nDoclist;
  201051. memset(&term, 0, sizeof(Fts5Buffer));
  201052. if( n<4 ){
  201053. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  201054. goto decode_out;
  201055. }else{
  201056. iRowidOff = fts5GetU16(&a[0]);
  201057. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  201058. if( iPgidxOff<n ){
  201059. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  201060. }else if( iPgidxOff>n ){
  201061. rc = FTS5_CORRUPT;
  201062. goto decode_out;
  201063. }
  201064. }
  201065. /* Decode the position list tail at the start of the page */
  201066. if( iRowidOff!=0 ){
  201067. iOff = iRowidOff;
  201068. }else if( iTermOff!=0 ){
  201069. iOff = iTermOff;
  201070. }else{
  201071. iOff = szLeaf;
  201072. }
  201073. if( iOff>n ){
  201074. rc = FTS5_CORRUPT;
  201075. goto decode_out;
  201076. }
  201077. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  201078. /* Decode any more doclist data that appears on the page before the
  201079. ** first term. */
  201080. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  201081. if( nDoclist+iOff>n ){
  201082. rc = FTS5_CORRUPT;
  201083. goto decode_out;
  201084. }
  201085. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  201086. while( iPgidxOff<n && rc==SQLITE_OK ){
  201087. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  201088. int nByte; /* Bytes of data */
  201089. int iEnd;
  201090. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  201091. iPgidxPrev += nByte;
  201092. iOff = iPgidxPrev;
  201093. if( iPgidxOff<n ){
  201094. fts5GetVarint32(&a[iPgidxOff], nByte);
  201095. iEnd = iPgidxPrev + nByte;
  201096. }else{
  201097. iEnd = szLeaf;
  201098. }
  201099. if( iEnd>szLeaf ){
  201100. rc = FTS5_CORRUPT;
  201101. break;
  201102. }
  201103. if( bFirst==0 ){
  201104. iOff += fts5GetVarint32(&a[iOff], nByte);
  201105. if( nByte>term.n ){
  201106. rc = FTS5_CORRUPT;
  201107. break;
  201108. }
  201109. term.n = nByte;
  201110. }
  201111. iOff += fts5GetVarint32(&a[iOff], nByte);
  201112. if( iOff+nByte>n ){
  201113. rc = FTS5_CORRUPT;
  201114. break;
  201115. }
  201116. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  201117. iOff += nByte;
  201118. sqlite3Fts5BufferAppendPrintf(
  201119. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  201120. );
  201121. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  201122. }
  201123. fts5BufferFree(&term);
  201124. }
  201125. decode_out:
  201126. sqlite3_free(a);
  201127. if( rc==SQLITE_OK ){
  201128. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  201129. }else{
  201130. sqlite3_result_error_code(pCtx, rc);
  201131. }
  201132. fts5BufferFree(&s);
  201133. }
  201134. /*
  201135. ** The implementation of user-defined scalar function fts5_rowid().
  201136. */
  201137. static void fts5RowidFunction(
  201138. sqlite3_context *pCtx, /* Function call context */
  201139. int nArg, /* Number of args (always 2) */
  201140. sqlite3_value **apVal /* Function arguments */
  201141. ){
  201142. const char *zArg;
  201143. if( nArg==0 ){
  201144. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  201145. }else{
  201146. zArg = (const char*)sqlite3_value_text(apVal[0]);
  201147. if( 0==sqlite3_stricmp(zArg, "segment") ){
  201148. i64 iRowid;
  201149. int segid, pgno;
  201150. if( nArg!=3 ){
  201151. sqlite3_result_error(pCtx,
  201152. "should be: fts5_rowid('segment', segid, pgno))", -1
  201153. );
  201154. }else{
  201155. segid = sqlite3_value_int(apVal[1]);
  201156. pgno = sqlite3_value_int(apVal[2]);
  201157. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  201158. sqlite3_result_int64(pCtx, iRowid);
  201159. }
  201160. }else{
  201161. sqlite3_result_error(pCtx,
  201162. "first arg to fts5_rowid() must be 'segment'" , -1
  201163. );
  201164. }
  201165. }
  201166. }
  201167. /*
  201168. ** This is called as part of registering the FTS5 module with database
  201169. ** connection db. It registers several user-defined scalar functions useful
  201170. ** with FTS5.
  201171. **
  201172. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  201173. ** SQLite error code is returned instead.
  201174. */
  201175. static int sqlite3Fts5IndexInit(sqlite3 *db){
  201176. int rc = sqlite3_create_function(
  201177. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  201178. );
  201179. if( rc==SQLITE_OK ){
  201180. rc = sqlite3_create_function(
  201181. db, "fts5_decode_none", 2,
  201182. SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
  201183. );
  201184. }
  201185. if( rc==SQLITE_OK ){
  201186. rc = sqlite3_create_function(
  201187. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  201188. );
  201189. }
  201190. return rc;
  201191. }
  201192. static int sqlite3Fts5IndexReset(Fts5Index *p){
  201193. assert( p->pStruct==0 || p->iStructVersion!=0 );
  201194. if( fts5IndexDataVersion(p)!=p->iStructVersion ){
  201195. fts5StructureInvalidate(p);
  201196. }
  201197. return fts5IndexReturn(p);
  201198. }
  201199. /*
  201200. ** 2014 Jun 09
  201201. **
  201202. ** The author disclaims copyright to this source code. In place of
  201203. ** a legal notice, here is a blessing:
  201204. **
  201205. ** May you do good and not evil.
  201206. ** May you find forgiveness for yourself and forgive others.
  201207. ** May you share freely, never taking more than you give.
  201208. **
  201209. ******************************************************************************
  201210. **
  201211. ** This is an SQLite module implementing full-text search.
  201212. */
  201213. /* #include "fts5Int.h" */
  201214. /*
  201215. ** This variable is set to false when running tests for which the on disk
  201216. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  201217. ** assert() conditions in the fts5 code are activated - conditions that are
  201218. ** only true if it is guaranteed that the fts5 database is not corrupt.
  201219. */
  201220. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  201221. typedef struct Fts5Auxdata Fts5Auxdata;
  201222. typedef struct Fts5Auxiliary Fts5Auxiliary;
  201223. typedef struct Fts5Cursor Fts5Cursor;
  201224. typedef struct Fts5FullTable Fts5FullTable;
  201225. typedef struct Fts5Sorter Fts5Sorter;
  201226. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  201227. /*
  201228. ** NOTES ON TRANSACTIONS:
  201229. **
  201230. ** SQLite invokes the following virtual table methods as transactions are
  201231. ** opened and closed by the user:
  201232. **
  201233. ** xBegin(): Start of a new transaction.
  201234. ** xSync(): Initial part of two-phase commit.
  201235. ** xCommit(): Final part of two-phase commit.
  201236. ** xRollback(): Rollback the transaction.
  201237. **
  201238. ** Anything that is required as part of a commit that may fail is performed
  201239. ** in the xSync() callback. Current versions of SQLite ignore any errors
  201240. ** returned by xCommit().
  201241. **
  201242. ** And as sub-transactions are opened/closed:
  201243. **
  201244. ** xSavepoint(int S): Open savepoint S.
  201245. ** xRelease(int S): Commit and close savepoint S.
  201246. ** xRollbackTo(int S): Rollback to start of savepoint S.
  201247. **
  201248. ** During a write-transaction the fts5_index.c module may cache some data
  201249. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  201250. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  201251. ** is called.
  201252. **
  201253. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  201254. ** structure is used to record the current transaction state. This information
  201255. ** is not required, but it is used in the assert() statements executed by
  201256. ** function fts5CheckTransactionState() (see below).
  201257. */
  201258. struct Fts5TransactionState {
  201259. int eState; /* 0==closed, 1==open, 2==synced */
  201260. int iSavepoint; /* Number of open savepoints (0 -> none) */
  201261. };
  201262. /*
  201263. ** A single object of this type is allocated when the FTS5 module is
  201264. ** registered with a database handle. It is used to store pointers to
  201265. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  201266. */
  201267. struct Fts5Global {
  201268. fts5_api api; /* User visible part of object (see fts5.h) */
  201269. sqlite3 *db; /* Associated database connection */
  201270. i64 iNextId; /* Used to allocate unique cursor ids */
  201271. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  201272. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  201273. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  201274. Fts5Cursor *pCsr; /* First in list of all open cursors */
  201275. };
  201276. /*
  201277. ** Each auxiliary function registered with the FTS5 module is represented
  201278. ** by an object of the following type. All such objects are stored as part
  201279. ** of the Fts5Global.pAux list.
  201280. */
  201281. struct Fts5Auxiliary {
  201282. Fts5Global *pGlobal; /* Global context for this function */
  201283. char *zFunc; /* Function name (nul-terminated) */
  201284. void *pUserData; /* User-data pointer */
  201285. fts5_extension_function xFunc; /* Callback function */
  201286. void (*xDestroy)(void*); /* Destructor function */
  201287. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  201288. };
  201289. /*
  201290. ** Each tokenizer module registered with the FTS5 module is represented
  201291. ** by an object of the following type. All such objects are stored as part
  201292. ** of the Fts5Global.pTok list.
  201293. */
  201294. struct Fts5TokenizerModule {
  201295. char *zName; /* Name of tokenizer */
  201296. void *pUserData; /* User pointer passed to xCreate() */
  201297. fts5_tokenizer x; /* Tokenizer functions */
  201298. void (*xDestroy)(void*); /* Destructor function */
  201299. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  201300. };
  201301. struct Fts5FullTable {
  201302. Fts5Table p; /* Public class members from fts5Int.h */
  201303. Fts5Storage *pStorage; /* Document store */
  201304. Fts5Global *pGlobal; /* Global (connection wide) data */
  201305. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  201306. #ifdef SQLITE_DEBUG
  201307. struct Fts5TransactionState ts;
  201308. #endif
  201309. };
  201310. struct Fts5MatchPhrase {
  201311. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  201312. int nTerm; /* Size of phrase in terms */
  201313. };
  201314. /*
  201315. ** pStmt:
  201316. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  201317. **
  201318. ** aIdx[]:
  201319. ** There is one entry in the aIdx[] array for each phrase in the query,
  201320. ** the value of which is the offset within aPoslist[] following the last
  201321. ** byte of the position list for the corresponding phrase.
  201322. */
  201323. struct Fts5Sorter {
  201324. sqlite3_stmt *pStmt;
  201325. i64 iRowid; /* Current rowid */
  201326. const u8 *aPoslist; /* Position lists for current row */
  201327. int nIdx; /* Number of entries in aIdx[] */
  201328. int aIdx[1]; /* Offsets into aPoslist for current row */
  201329. };
  201330. /*
  201331. ** Virtual-table cursor object.
  201332. **
  201333. ** iSpecial:
  201334. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  201335. ** then this variable contains the result of the query.
  201336. **
  201337. ** iFirstRowid, iLastRowid:
  201338. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  201339. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  201340. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  201341. ** WHERE clause in the user's query might have been:
  201342. **
  201343. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  201344. **
  201345. ** If the cursor iterates in descending order of rowid, iFirstRowid
  201346. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  201347. ** the lower.
  201348. */
  201349. struct Fts5Cursor {
  201350. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  201351. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  201352. int *aColumnSize; /* Values for xColumnSize() */
  201353. i64 iCsrId; /* Cursor id */
  201354. /* Zero from this point onwards on cursor reset */
  201355. int ePlan; /* FTS5_PLAN_XXX value */
  201356. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  201357. i64 iFirstRowid; /* Return no rowids earlier than this */
  201358. i64 iLastRowid; /* Return no rowids later than this */
  201359. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  201360. Fts5Expr *pExpr; /* Expression for MATCH queries */
  201361. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  201362. int csrflags; /* Mask of cursor flags (see below) */
  201363. i64 iSpecial; /* Result of special query */
  201364. /* "rank" function. Populated on demand from vtab.xColumn(). */
  201365. char *zRank; /* Custom rank function */
  201366. char *zRankArgs; /* Custom rank function args */
  201367. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  201368. int nRankArg; /* Number of trailing arguments for rank() */
  201369. sqlite3_value **apRankArg; /* Array of trailing arguments */
  201370. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  201371. /* Auxiliary data storage */
  201372. Fts5Auxiliary *pAux; /* Currently executing extension function */
  201373. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  201374. /* Cache used by auxiliary functions xInst() and xInstCount() */
  201375. Fts5PoslistReader *aInstIter; /* One for each phrase */
  201376. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  201377. int nInstCount; /* Number of phrase instances */
  201378. int *aInst; /* 3 integers per phrase instance */
  201379. };
  201380. /*
  201381. ** Bits that make up the "idxNum" parameter passed indirectly by
  201382. ** xBestIndex() to xFilter().
  201383. */
  201384. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  201385. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  201386. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  201387. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  201388. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  201389. #define FTS5_BI_ORDER_RANK 0x0020
  201390. #define FTS5_BI_ORDER_ROWID 0x0040
  201391. #define FTS5_BI_ORDER_DESC 0x0080
  201392. /*
  201393. ** Values for Fts5Cursor.csrflags
  201394. */
  201395. #define FTS5CSR_EOF 0x01
  201396. #define FTS5CSR_REQUIRE_CONTENT 0x02
  201397. #define FTS5CSR_REQUIRE_DOCSIZE 0x04
  201398. #define FTS5CSR_REQUIRE_INST 0x08
  201399. #define FTS5CSR_FREE_ZRANK 0x10
  201400. #define FTS5CSR_REQUIRE_RESEEK 0x20
  201401. #define FTS5CSR_REQUIRE_POSLIST 0x40
  201402. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  201403. #define BitFlagTest(x,y) (((x) & (y))!=0)
  201404. /*
  201405. ** Macros to Set(), Clear() and Test() cursor flags.
  201406. */
  201407. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  201408. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  201409. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  201410. struct Fts5Auxdata {
  201411. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  201412. void *pPtr; /* Pointer value */
  201413. void(*xDelete)(void*); /* Destructor */
  201414. Fts5Auxdata *pNext; /* Next object in linked list */
  201415. };
  201416. #ifdef SQLITE_DEBUG
  201417. #define FTS5_BEGIN 1
  201418. #define FTS5_SYNC 2
  201419. #define FTS5_COMMIT 3
  201420. #define FTS5_ROLLBACK 4
  201421. #define FTS5_SAVEPOINT 5
  201422. #define FTS5_RELEASE 6
  201423. #define FTS5_ROLLBACKTO 7
  201424. static void fts5CheckTransactionState(Fts5FullTable *p, int op, int iSavepoint){
  201425. switch( op ){
  201426. case FTS5_BEGIN:
  201427. assert( p->ts.eState==0 );
  201428. p->ts.eState = 1;
  201429. p->ts.iSavepoint = -1;
  201430. break;
  201431. case FTS5_SYNC:
  201432. assert( p->ts.eState==1 );
  201433. p->ts.eState = 2;
  201434. break;
  201435. case FTS5_COMMIT:
  201436. assert( p->ts.eState==2 );
  201437. p->ts.eState = 0;
  201438. break;
  201439. case FTS5_ROLLBACK:
  201440. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  201441. p->ts.eState = 0;
  201442. break;
  201443. case FTS5_SAVEPOINT:
  201444. assert( p->ts.eState==1 );
  201445. assert( iSavepoint>=0 );
  201446. assert( iSavepoint>=p->ts.iSavepoint );
  201447. p->ts.iSavepoint = iSavepoint;
  201448. break;
  201449. case FTS5_RELEASE:
  201450. assert( p->ts.eState==1 );
  201451. assert( iSavepoint>=0 );
  201452. assert( iSavepoint<=p->ts.iSavepoint );
  201453. p->ts.iSavepoint = iSavepoint-1;
  201454. break;
  201455. case FTS5_ROLLBACKTO:
  201456. assert( p->ts.eState==1 );
  201457. assert( iSavepoint>=-1 );
  201458. assert( iSavepoint<=p->ts.iSavepoint );
  201459. p->ts.iSavepoint = iSavepoint;
  201460. break;
  201461. }
  201462. }
  201463. #else
  201464. # define fts5CheckTransactionState(x,y,z)
  201465. #endif
  201466. /*
  201467. ** Return true if pTab is a contentless table.
  201468. */
  201469. static int fts5IsContentless(Fts5FullTable *pTab){
  201470. return pTab->p.pConfig->eContent==FTS5_CONTENT_NONE;
  201471. }
  201472. /*
  201473. ** Delete a virtual table handle allocated by fts5InitVtab().
  201474. */
  201475. static void fts5FreeVtab(Fts5FullTable *pTab){
  201476. if( pTab ){
  201477. sqlite3Fts5IndexClose(pTab->p.pIndex);
  201478. sqlite3Fts5StorageClose(pTab->pStorage);
  201479. sqlite3Fts5ConfigFree(pTab->p.pConfig);
  201480. sqlite3_free(pTab);
  201481. }
  201482. }
  201483. /*
  201484. ** The xDisconnect() virtual table method.
  201485. */
  201486. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  201487. fts5FreeVtab((Fts5FullTable*)pVtab);
  201488. return SQLITE_OK;
  201489. }
  201490. /*
  201491. ** The xDestroy() virtual table method.
  201492. */
  201493. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  201494. Fts5Table *pTab = (Fts5Table*)pVtab;
  201495. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  201496. if( rc==SQLITE_OK ){
  201497. fts5FreeVtab((Fts5FullTable*)pVtab);
  201498. }
  201499. return rc;
  201500. }
  201501. /*
  201502. ** This function is the implementation of both the xConnect and xCreate
  201503. ** methods of the FTS3 virtual table.
  201504. **
  201505. ** The argv[] array contains the following:
  201506. **
  201507. ** argv[0] -> module name ("fts5")
  201508. ** argv[1] -> database name
  201509. ** argv[2] -> table name
  201510. ** argv[...] -> "column name" and other module argument fields.
  201511. */
  201512. static int fts5InitVtab(
  201513. int bCreate, /* True for xCreate, false for xConnect */
  201514. sqlite3 *db, /* The SQLite database connection */
  201515. void *pAux, /* Hash table containing tokenizers */
  201516. int argc, /* Number of elements in argv array */
  201517. const char * const *argv, /* xCreate/xConnect argument array */
  201518. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  201519. char **pzErr /* Write any error message here */
  201520. ){
  201521. Fts5Global *pGlobal = (Fts5Global*)pAux;
  201522. const char **azConfig = (const char**)argv;
  201523. int rc = SQLITE_OK; /* Return code */
  201524. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  201525. Fts5FullTable *pTab = 0; /* New virtual table object */
  201526. /* Allocate the new vtab object and parse the configuration */
  201527. pTab = (Fts5FullTable*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5FullTable));
  201528. if( rc==SQLITE_OK ){
  201529. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  201530. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  201531. }
  201532. if( rc==SQLITE_OK ){
  201533. pTab->p.pConfig = pConfig;
  201534. pTab->pGlobal = pGlobal;
  201535. }
  201536. /* Open the index sub-system */
  201537. if( rc==SQLITE_OK ){
  201538. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->p.pIndex, pzErr);
  201539. }
  201540. /* Open the storage sub-system */
  201541. if( rc==SQLITE_OK ){
  201542. rc = sqlite3Fts5StorageOpen(
  201543. pConfig, pTab->p.pIndex, bCreate, &pTab->pStorage, pzErr
  201544. );
  201545. }
  201546. /* Call sqlite3_declare_vtab() */
  201547. if( rc==SQLITE_OK ){
  201548. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  201549. }
  201550. /* Load the initial configuration */
  201551. if( rc==SQLITE_OK ){
  201552. assert( pConfig->pzErrmsg==0 );
  201553. pConfig->pzErrmsg = pzErr;
  201554. rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
  201555. sqlite3Fts5IndexRollback(pTab->p.pIndex);
  201556. pConfig->pzErrmsg = 0;
  201557. }
  201558. if( rc!=SQLITE_OK ){
  201559. fts5FreeVtab(pTab);
  201560. pTab = 0;
  201561. }else if( bCreate ){
  201562. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  201563. }
  201564. *ppVTab = (sqlite3_vtab*)pTab;
  201565. return rc;
  201566. }
  201567. /*
  201568. ** The xConnect() and xCreate() methods for the virtual table. All the
  201569. ** work is done in function fts5InitVtab().
  201570. */
  201571. static int fts5ConnectMethod(
  201572. sqlite3 *db, /* Database connection */
  201573. void *pAux, /* Pointer to tokenizer hash table */
  201574. int argc, /* Number of elements in argv array */
  201575. const char * const *argv, /* xCreate/xConnect argument array */
  201576. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  201577. char **pzErr /* OUT: sqlite3_malloc'd error message */
  201578. ){
  201579. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  201580. }
  201581. static int fts5CreateMethod(
  201582. sqlite3 *db, /* Database connection */
  201583. void *pAux, /* Pointer to tokenizer hash table */
  201584. int argc, /* Number of elements in argv array */
  201585. const char * const *argv, /* xCreate/xConnect argument array */
  201586. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  201587. char **pzErr /* OUT: sqlite3_malloc'd error message */
  201588. ){
  201589. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  201590. }
  201591. /*
  201592. ** The different query plans.
  201593. */
  201594. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  201595. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  201596. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  201597. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  201598. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  201599. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  201600. /*
  201601. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  201602. ** extension is currently being used by a version of SQLite too old to
  201603. ** support index-info flags. In that case this function is a no-op.
  201604. */
  201605. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  201606. #if SQLITE_VERSION_NUMBER>=3008012
  201607. #ifndef SQLITE_CORE
  201608. if( sqlite3_libversion_number()>=3008012 )
  201609. #endif
  201610. {
  201611. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  201612. }
  201613. #endif
  201614. }
  201615. /*
  201616. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  201617. ** WHERE constraint, it searches for the following:
  201618. **
  201619. ** 1. A MATCH constraint against the special column.
  201620. ** 2. A MATCH constraint against the "rank" column.
  201621. ** 3. An == constraint against the rowid column.
  201622. ** 4. A < or <= constraint against the rowid column.
  201623. ** 5. A > or >= constraint against the rowid column.
  201624. **
  201625. ** Within the ORDER BY, either:
  201626. **
  201627. ** 5. ORDER BY rank [ASC|DESC]
  201628. ** 6. ORDER BY rowid [ASC|DESC]
  201629. **
  201630. ** Costs are assigned as follows:
  201631. **
  201632. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  201633. ** cost is unconditionally set to 1e50 (a really big number).
  201634. **
  201635. ** a) If a MATCH operator is present, the cost depends on the other
  201636. ** constraints also present. As follows:
  201637. **
  201638. ** * No other constraints: cost=1000.0
  201639. ** * One rowid range constraint: cost=750.0
  201640. ** * Both rowid range constraints: cost=500.0
  201641. ** * An == rowid constraint: cost=100.0
  201642. **
  201643. ** b) Otherwise, if there is no MATCH:
  201644. **
  201645. ** * No other constraints: cost=1000000.0
  201646. ** * One rowid range constraint: cost=750000.0
  201647. ** * Both rowid range constraints: cost=250000.0
  201648. ** * An == rowid constraint: cost=10.0
  201649. **
  201650. ** Costs are not modified by the ORDER BY clause.
  201651. */
  201652. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  201653. Fts5Table *pTab = (Fts5Table*)pVTab;
  201654. Fts5Config *pConfig = pTab->pConfig;
  201655. const int nCol = pConfig->nCol;
  201656. int idxFlags = 0; /* Parameter passed through to xFilter() */
  201657. int bHasMatch;
  201658. int iNext;
  201659. int i;
  201660. struct Constraint {
  201661. int op; /* Mask against sqlite3_index_constraint.op */
  201662. int fts5op; /* FTS5 mask for idxFlags */
  201663. int iCol; /* 0==rowid, 1==tbl, 2==rank */
  201664. int omit; /* True to omit this if found */
  201665. int iConsIndex; /* Index in pInfo->aConstraint[] */
  201666. } aConstraint[] = {
  201667. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  201668. FTS5_BI_MATCH, 1, 1, -1},
  201669. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  201670. FTS5_BI_RANK, 2, 1, -1},
  201671. {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
  201672. {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
  201673. FTS5_BI_ROWID_LE, 0, 0, -1},
  201674. {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
  201675. FTS5_BI_ROWID_GE, 0, 0, -1},
  201676. };
  201677. int aColMap[3];
  201678. aColMap[0] = -1;
  201679. aColMap[1] = nCol;
  201680. aColMap[2] = nCol+1;
  201681. assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH );
  201682. assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH );
  201683. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  201684. assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH );
  201685. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  201686. /* Set idxFlags flags for all WHERE clause terms that will be used. */
  201687. for(i=0; i<pInfo->nConstraint; i++){
  201688. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  201689. int iCol = p->iColumn;
  201690. if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
  201691. || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
  201692. ){
  201693. /* A MATCH operator or equivalent */
  201694. if( p->usable ){
  201695. idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
  201696. aConstraint[0].iConsIndex = i;
  201697. }else{
  201698. /* As there exists an unusable MATCH constraint this is an
  201699. ** unusable plan. Set a prohibitively high cost. */
  201700. pInfo->estimatedCost = 1e50;
  201701. return SQLITE_OK;
  201702. }
  201703. }else if( p->op<=SQLITE_INDEX_CONSTRAINT_MATCH ){
  201704. int j;
  201705. for(j=1; j<ArraySize(aConstraint); j++){
  201706. struct Constraint *pC = &aConstraint[j];
  201707. if( iCol==aColMap[pC->iCol] && (p->op & pC->op) && p->usable ){
  201708. pC->iConsIndex = i;
  201709. idxFlags |= pC->fts5op;
  201710. }
  201711. }
  201712. }
  201713. }
  201714. /* Set idxFlags flags for the ORDER BY clause */
  201715. if( pInfo->nOrderBy==1 ){
  201716. int iSort = pInfo->aOrderBy[0].iColumn;
  201717. if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
  201718. idxFlags |= FTS5_BI_ORDER_RANK;
  201719. }else if( iSort==-1 ){
  201720. idxFlags |= FTS5_BI_ORDER_ROWID;
  201721. }
  201722. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  201723. pInfo->orderByConsumed = 1;
  201724. if( pInfo->aOrderBy[0].desc ){
  201725. idxFlags |= FTS5_BI_ORDER_DESC;
  201726. }
  201727. }
  201728. }
  201729. /* Calculate the estimated cost based on the flags set in idxFlags. */
  201730. bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
  201731. if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
  201732. pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
  201733. if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
  201734. }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  201735. pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
  201736. }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  201737. pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
  201738. }else{
  201739. pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
  201740. }
  201741. /* Assign argvIndex values to each constraint in use. */
  201742. iNext = 1;
  201743. for(i=0; i<ArraySize(aConstraint); i++){
  201744. struct Constraint *pC = &aConstraint[i];
  201745. if( pC->iConsIndex>=0 ){
  201746. pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
  201747. pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
  201748. }
  201749. }
  201750. pInfo->idxNum = idxFlags;
  201751. return SQLITE_OK;
  201752. }
  201753. static int fts5NewTransaction(Fts5FullTable *pTab){
  201754. Fts5Cursor *pCsr;
  201755. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  201756. if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
  201757. }
  201758. return sqlite3Fts5StorageReset(pTab->pStorage);
  201759. }
  201760. /*
  201761. ** Implementation of xOpen method.
  201762. */
  201763. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  201764. Fts5FullTable *pTab = (Fts5FullTable*)pVTab;
  201765. Fts5Config *pConfig = pTab->p.pConfig;
  201766. Fts5Cursor *pCsr = 0; /* New cursor object */
  201767. sqlite3_int64 nByte; /* Bytes of space to allocate */
  201768. int rc; /* Return code */
  201769. rc = fts5NewTransaction(pTab);
  201770. if( rc==SQLITE_OK ){
  201771. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  201772. pCsr = (Fts5Cursor*)sqlite3_malloc64(nByte);
  201773. if( pCsr ){
  201774. Fts5Global *pGlobal = pTab->pGlobal;
  201775. memset(pCsr, 0, (size_t)nByte);
  201776. pCsr->aColumnSize = (int*)&pCsr[1];
  201777. pCsr->pNext = pGlobal->pCsr;
  201778. pGlobal->pCsr = pCsr;
  201779. pCsr->iCsrId = ++pGlobal->iNextId;
  201780. }else{
  201781. rc = SQLITE_NOMEM;
  201782. }
  201783. }
  201784. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  201785. return rc;
  201786. }
  201787. static int fts5StmtType(Fts5Cursor *pCsr){
  201788. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  201789. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  201790. }
  201791. return FTS5_STMT_LOOKUP;
  201792. }
  201793. /*
  201794. ** This function is called after the cursor passed as the only argument
  201795. ** is moved to point at a different row. It clears all cached data
  201796. ** specific to the previous row stored by the cursor object.
  201797. */
  201798. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  201799. CsrFlagSet(pCsr,
  201800. FTS5CSR_REQUIRE_CONTENT
  201801. | FTS5CSR_REQUIRE_DOCSIZE
  201802. | FTS5CSR_REQUIRE_INST
  201803. | FTS5CSR_REQUIRE_POSLIST
  201804. );
  201805. }
  201806. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  201807. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  201808. Fts5Auxdata *pData;
  201809. Fts5Auxdata *pNext;
  201810. sqlite3_free(pCsr->aInstIter);
  201811. sqlite3_free(pCsr->aInst);
  201812. if( pCsr->pStmt ){
  201813. int eStmt = fts5StmtType(pCsr);
  201814. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  201815. }
  201816. if( pCsr->pSorter ){
  201817. Fts5Sorter *pSorter = pCsr->pSorter;
  201818. sqlite3_finalize(pSorter->pStmt);
  201819. sqlite3_free(pSorter);
  201820. }
  201821. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  201822. sqlite3Fts5ExprFree(pCsr->pExpr);
  201823. }
  201824. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  201825. pNext = pData->pNext;
  201826. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  201827. sqlite3_free(pData);
  201828. }
  201829. sqlite3_finalize(pCsr->pRankArgStmt);
  201830. sqlite3_free(pCsr->apRankArg);
  201831. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  201832. sqlite3_free(pCsr->zRank);
  201833. sqlite3_free(pCsr->zRankArgs);
  201834. }
  201835. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  201836. }
  201837. /*
  201838. ** Close the cursor. For additional information see the documentation
  201839. ** on the xClose method of the virtual table interface.
  201840. */
  201841. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  201842. if( pCursor ){
  201843. Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
  201844. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  201845. Fts5Cursor **pp;
  201846. fts5FreeCursorComponents(pCsr);
  201847. /* Remove the cursor from the Fts5Global.pCsr list */
  201848. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  201849. *pp = pCsr->pNext;
  201850. sqlite3_free(pCsr);
  201851. }
  201852. return SQLITE_OK;
  201853. }
  201854. static int fts5SorterNext(Fts5Cursor *pCsr){
  201855. Fts5Sorter *pSorter = pCsr->pSorter;
  201856. int rc;
  201857. rc = sqlite3_step(pSorter->pStmt);
  201858. if( rc==SQLITE_DONE ){
  201859. rc = SQLITE_OK;
  201860. CsrFlagSet(pCsr, FTS5CSR_EOF);
  201861. }else if( rc==SQLITE_ROW ){
  201862. const u8 *a;
  201863. const u8 *aBlob;
  201864. int nBlob;
  201865. int i;
  201866. int iOff = 0;
  201867. rc = SQLITE_OK;
  201868. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  201869. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  201870. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  201871. /* nBlob==0 in detail=none mode. */
  201872. if( nBlob>0 ){
  201873. for(i=0; i<(pSorter->nIdx-1); i++){
  201874. int iVal;
  201875. a += fts5GetVarint32(a, iVal);
  201876. iOff += iVal;
  201877. pSorter->aIdx[i] = iOff;
  201878. }
  201879. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  201880. pSorter->aPoslist = a;
  201881. }
  201882. fts5CsrNewrow(pCsr);
  201883. }
  201884. return rc;
  201885. }
  201886. /*
  201887. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  201888. ** open on table pTab.
  201889. */
  201890. static void fts5TripCursors(Fts5FullTable *pTab){
  201891. Fts5Cursor *pCsr;
  201892. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  201893. if( pCsr->ePlan==FTS5_PLAN_MATCH
  201894. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  201895. ){
  201896. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  201897. }
  201898. }
  201899. }
  201900. /*
  201901. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  201902. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  201903. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  201904. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  201905. **
  201906. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  201907. ** to 1 before returning. Otherwise, leave it unchanged.
  201908. **
  201909. ** Return SQLITE_OK if successful or if no reseek was required, or an
  201910. ** error code if an error occurred.
  201911. */
  201912. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  201913. int rc = SQLITE_OK;
  201914. assert( *pbSkip==0 );
  201915. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  201916. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  201917. int bDesc = pCsr->bDesc;
  201918. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  201919. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->p.pIndex, iRowid, bDesc);
  201920. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  201921. *pbSkip = 1;
  201922. }
  201923. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  201924. fts5CsrNewrow(pCsr);
  201925. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  201926. CsrFlagSet(pCsr, FTS5CSR_EOF);
  201927. *pbSkip = 1;
  201928. }
  201929. }
  201930. return rc;
  201931. }
  201932. /*
  201933. ** Advance the cursor to the next row in the table that matches the
  201934. ** search criteria.
  201935. **
  201936. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  201937. ** even if we reach end-of-file. The fts5EofMethod() will be called
  201938. ** subsequently to determine whether or not an EOF was hit.
  201939. */
  201940. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  201941. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  201942. int rc;
  201943. assert( (pCsr->ePlan<3)==
  201944. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  201945. );
  201946. assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
  201947. if( pCsr->ePlan<3 ){
  201948. int bSkip = 0;
  201949. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  201950. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  201951. CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
  201952. fts5CsrNewrow(pCsr);
  201953. }else{
  201954. switch( pCsr->ePlan ){
  201955. case FTS5_PLAN_SPECIAL: {
  201956. CsrFlagSet(pCsr, FTS5CSR_EOF);
  201957. rc = SQLITE_OK;
  201958. break;
  201959. }
  201960. case FTS5_PLAN_SORTED_MATCH: {
  201961. rc = fts5SorterNext(pCsr);
  201962. break;
  201963. }
  201964. default:
  201965. rc = sqlite3_step(pCsr->pStmt);
  201966. if( rc!=SQLITE_ROW ){
  201967. CsrFlagSet(pCsr, FTS5CSR_EOF);
  201968. rc = sqlite3_reset(pCsr->pStmt);
  201969. }else{
  201970. rc = SQLITE_OK;
  201971. }
  201972. break;
  201973. }
  201974. }
  201975. return rc;
  201976. }
  201977. static int fts5PrepareStatement(
  201978. sqlite3_stmt **ppStmt,
  201979. Fts5Config *pConfig,
  201980. const char *zFmt,
  201981. ...
  201982. ){
  201983. sqlite3_stmt *pRet = 0;
  201984. int rc;
  201985. char *zSql;
  201986. va_list ap;
  201987. va_start(ap, zFmt);
  201988. zSql = sqlite3_vmprintf(zFmt, ap);
  201989. if( zSql==0 ){
  201990. rc = SQLITE_NOMEM;
  201991. }else{
  201992. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  201993. SQLITE_PREPARE_PERSISTENT, &pRet, 0);
  201994. if( rc!=SQLITE_OK ){
  201995. *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
  201996. }
  201997. sqlite3_free(zSql);
  201998. }
  201999. va_end(ap);
  202000. *ppStmt = pRet;
  202001. return rc;
  202002. }
  202003. static int fts5CursorFirstSorted(
  202004. Fts5FullTable *pTab,
  202005. Fts5Cursor *pCsr,
  202006. int bDesc
  202007. ){
  202008. Fts5Config *pConfig = pTab->p.pConfig;
  202009. Fts5Sorter *pSorter;
  202010. int nPhrase;
  202011. sqlite3_int64 nByte;
  202012. int rc;
  202013. const char *zRank = pCsr->zRank;
  202014. const char *zRankArgs = pCsr->zRankArgs;
  202015. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  202016. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  202017. pSorter = (Fts5Sorter*)sqlite3_malloc64(nByte);
  202018. if( pSorter==0 ) return SQLITE_NOMEM;
  202019. memset(pSorter, 0, (size_t)nByte);
  202020. pSorter->nIdx = nPhrase;
  202021. /* TODO: It would be better to have some system for reusing statement
  202022. ** handles here, rather than preparing a new one for each query. But that
  202023. ** is not possible as SQLite reference counts the virtual table objects.
  202024. ** And since the statement required here reads from this very virtual
  202025. ** table, saving it creates a circular reference.
  202026. **
  202027. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  202028. rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
  202029. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
  202030. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  202031. (zRankArgs ? ", " : ""),
  202032. (zRankArgs ? zRankArgs : ""),
  202033. bDesc ? "DESC" : "ASC"
  202034. );
  202035. pCsr->pSorter = pSorter;
  202036. if( rc==SQLITE_OK ){
  202037. assert( pTab->pSortCsr==0 );
  202038. pTab->pSortCsr = pCsr;
  202039. rc = fts5SorterNext(pCsr);
  202040. pTab->pSortCsr = 0;
  202041. }
  202042. if( rc!=SQLITE_OK ){
  202043. sqlite3_finalize(pSorter->pStmt);
  202044. sqlite3_free(pSorter);
  202045. pCsr->pSorter = 0;
  202046. }
  202047. return rc;
  202048. }
  202049. static int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){
  202050. int rc;
  202051. Fts5Expr *pExpr = pCsr->pExpr;
  202052. rc = sqlite3Fts5ExprFirst(pExpr, pTab->p.pIndex, pCsr->iFirstRowid, bDesc);
  202053. if( sqlite3Fts5ExprEof(pExpr) ){
  202054. CsrFlagSet(pCsr, FTS5CSR_EOF);
  202055. }
  202056. fts5CsrNewrow(pCsr);
  202057. return rc;
  202058. }
  202059. /*
  202060. ** Process a "special" query. A special query is identified as one with a
  202061. ** MATCH expression that begins with a '*' character. The remainder of
  202062. ** the text passed to the MATCH operator are used as the special query
  202063. ** parameters.
  202064. */
  202065. static int fts5SpecialMatch(
  202066. Fts5FullTable *pTab,
  202067. Fts5Cursor *pCsr,
  202068. const char *zQuery
  202069. ){
  202070. int rc = SQLITE_OK; /* Return code */
  202071. const char *z = zQuery; /* Special query text */
  202072. int n; /* Number of bytes in text at z */
  202073. while( z[0]==' ' ) z++;
  202074. for(n=0; z[n] && z[n]!=' '; n++);
  202075. assert( pTab->p.base.zErrMsg==0 );
  202076. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  202077. if( 0==sqlite3_strnicmp("reads", z, n) ){
  202078. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->p.pIndex);
  202079. }
  202080. else if( 0==sqlite3_strnicmp("id", z, n) ){
  202081. pCsr->iSpecial = pCsr->iCsrId;
  202082. }
  202083. else{
  202084. /* An unrecognized directive. Return an error message. */
  202085. pTab->p.base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  202086. rc = SQLITE_ERROR;
  202087. }
  202088. return rc;
  202089. }
  202090. /*
  202091. ** Search for an auxiliary function named zName that can be used with table
  202092. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  202093. ** structure. Otherwise, if no such function exists, return NULL.
  202094. */
  202095. static Fts5Auxiliary *fts5FindAuxiliary(Fts5FullTable *pTab, const char *zName){
  202096. Fts5Auxiliary *pAux;
  202097. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  202098. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  202099. }
  202100. /* No function of the specified name was found. Return 0. */
  202101. return 0;
  202102. }
  202103. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  202104. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  202105. Fts5Config *pConfig = pTab->p.pConfig;
  202106. int rc = SQLITE_OK;
  202107. Fts5Auxiliary *pAux = 0;
  202108. const char *zRank = pCsr->zRank;
  202109. const char *zRankArgs = pCsr->zRankArgs;
  202110. if( zRankArgs ){
  202111. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  202112. if( zSql ){
  202113. sqlite3_stmt *pStmt = 0;
  202114. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  202115. SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
  202116. sqlite3_free(zSql);
  202117. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  202118. if( rc==SQLITE_OK ){
  202119. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  202120. sqlite3_int64 nByte;
  202121. pCsr->nRankArg = sqlite3_column_count(pStmt);
  202122. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  202123. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  202124. if( rc==SQLITE_OK ){
  202125. int i;
  202126. for(i=0; i<pCsr->nRankArg; i++){
  202127. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  202128. }
  202129. }
  202130. pCsr->pRankArgStmt = pStmt;
  202131. }else{
  202132. rc = sqlite3_finalize(pStmt);
  202133. assert( rc!=SQLITE_OK );
  202134. }
  202135. }
  202136. }
  202137. }
  202138. if( rc==SQLITE_OK ){
  202139. pAux = fts5FindAuxiliary(pTab, zRank);
  202140. if( pAux==0 ){
  202141. assert( pTab->p.base.zErrMsg==0 );
  202142. pTab->p.base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  202143. rc = SQLITE_ERROR;
  202144. }
  202145. }
  202146. pCsr->pRank = pAux;
  202147. return rc;
  202148. }
  202149. static int fts5CursorParseRank(
  202150. Fts5Config *pConfig,
  202151. Fts5Cursor *pCsr,
  202152. sqlite3_value *pRank
  202153. ){
  202154. int rc = SQLITE_OK;
  202155. if( pRank ){
  202156. const char *z = (const char*)sqlite3_value_text(pRank);
  202157. char *zRank = 0;
  202158. char *zRankArgs = 0;
  202159. if( z==0 ){
  202160. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  202161. }else{
  202162. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  202163. }
  202164. if( rc==SQLITE_OK ){
  202165. pCsr->zRank = zRank;
  202166. pCsr->zRankArgs = zRankArgs;
  202167. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  202168. }else if( rc==SQLITE_ERROR ){
  202169. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  202170. "parse error in rank function: %s", z
  202171. );
  202172. }
  202173. }else{
  202174. if( pConfig->zRank ){
  202175. pCsr->zRank = (char*)pConfig->zRank;
  202176. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  202177. }else{
  202178. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  202179. pCsr->zRankArgs = 0;
  202180. }
  202181. }
  202182. return rc;
  202183. }
  202184. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  202185. if( pVal ){
  202186. int eType = sqlite3_value_numeric_type(pVal);
  202187. if( eType==SQLITE_INTEGER ){
  202188. return sqlite3_value_int64(pVal);
  202189. }
  202190. }
  202191. return iDefault;
  202192. }
  202193. /*
  202194. ** This is the xFilter interface for the virtual table. See
  202195. ** the virtual table xFilter method documentation for additional
  202196. ** information.
  202197. **
  202198. ** There are three possible query strategies:
  202199. **
  202200. ** 1. Full-text search using a MATCH operator.
  202201. ** 2. A by-rowid lookup.
  202202. ** 3. A full-table scan.
  202203. */
  202204. static int fts5FilterMethod(
  202205. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  202206. int idxNum, /* Strategy index */
  202207. const char *zUnused, /* Unused */
  202208. int nVal, /* Number of elements in apVal */
  202209. sqlite3_value **apVal /* Arguments for the indexing scheme */
  202210. ){
  202211. Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
  202212. Fts5Config *pConfig = pTab->p.pConfig;
  202213. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  202214. int rc = SQLITE_OK; /* Error code */
  202215. int iVal = 0; /* Counter for apVal[] */
  202216. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  202217. int bOrderByRank; /* True if ORDER BY rank */
  202218. sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
  202219. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  202220. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  202221. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  202222. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  202223. int iCol; /* Column on LHS of MATCH operator */
  202224. char **pzErrmsg = pConfig->pzErrmsg;
  202225. UNUSED_PARAM(zUnused);
  202226. UNUSED_PARAM(nVal);
  202227. if( pCsr->ePlan ){
  202228. fts5FreeCursorComponents(pCsr);
  202229. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  202230. }
  202231. assert( pCsr->pStmt==0 );
  202232. assert( pCsr->pExpr==0 );
  202233. assert( pCsr->csrflags==0 );
  202234. assert( pCsr->pRank==0 );
  202235. assert( pCsr->zRank==0 );
  202236. assert( pCsr->zRankArgs==0 );
  202237. assert( pzErrmsg==0 || pzErrmsg==&pTab->p.base.zErrMsg );
  202238. pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
  202239. /* Decode the arguments passed through to this function.
  202240. **
  202241. ** Note: The following set of if(...) statements must be in the same
  202242. ** order as the corresponding entries in the struct at the top of
  202243. ** fts5BestIndexMethod(). */
  202244. if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
  202245. if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
  202246. if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
  202247. if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
  202248. if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
  202249. iCol = (idxNum>>16);
  202250. assert( iCol>=0 && iCol<=pConfig->nCol );
  202251. assert( iVal==nVal );
  202252. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  202253. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  202254. /* Set the cursor upper and lower rowid limits. Only some strategies
  202255. ** actually use them. This is ok, as the xBestIndex() method leaves the
  202256. ** sqlite3_index_constraint.omit flag clear for range constraints
  202257. ** on the rowid field. */
  202258. if( pRowidEq ){
  202259. pRowidLe = pRowidGe = pRowidEq;
  202260. }
  202261. if( bDesc ){
  202262. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  202263. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  202264. }else{
  202265. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  202266. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  202267. }
  202268. if( pTab->pSortCsr ){
  202269. /* If pSortCsr is non-NULL, then this call is being made as part of
  202270. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  202271. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  202272. ** return results to the user for this query. The current cursor
  202273. ** (pCursor) is used to execute the query issued by function
  202274. ** fts5CursorFirstSorted() above. */
  202275. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  202276. assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
  202277. assert( pCsr->iLastRowid==LARGEST_INT64 );
  202278. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  202279. if( pTab->pSortCsr->bDesc ){
  202280. pCsr->iLastRowid = pTab->pSortCsr->iFirstRowid;
  202281. pCsr->iFirstRowid = pTab->pSortCsr->iLastRowid;
  202282. }else{
  202283. pCsr->iLastRowid = pTab->pSortCsr->iLastRowid;
  202284. pCsr->iFirstRowid = pTab->pSortCsr->iFirstRowid;
  202285. }
  202286. pCsr->ePlan = FTS5_PLAN_SOURCE;
  202287. pCsr->pExpr = pTab->pSortCsr->pExpr;
  202288. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  202289. }else if( pMatch ){
  202290. const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
  202291. if( zExpr==0 ) zExpr = "";
  202292. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  202293. if( rc==SQLITE_OK ){
  202294. if( zExpr[0]=='*' ){
  202295. /* The user has issued a query of the form "MATCH '*...'". This
  202296. ** indicates that the MATCH expression is not a full text query,
  202297. ** but a request for an internal parameter. */
  202298. rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
  202299. }else{
  202300. char **pzErr = &pTab->p.base.zErrMsg;
  202301. rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
  202302. if( rc==SQLITE_OK ){
  202303. if( bOrderByRank ){
  202304. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  202305. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  202306. }else{
  202307. pCsr->ePlan = FTS5_PLAN_MATCH;
  202308. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  202309. }
  202310. }
  202311. }
  202312. }
  202313. }else if( pConfig->zContent==0 ){
  202314. *pConfig->pzErrmsg = sqlite3_mprintf(
  202315. "%s: table does not support scanning", pConfig->zName
  202316. );
  202317. rc = SQLITE_ERROR;
  202318. }else{
  202319. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  202320. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  202321. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  202322. rc = sqlite3Fts5StorageStmt(
  202323. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->p.base.zErrMsg
  202324. );
  202325. if( rc==SQLITE_OK ){
  202326. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  202327. sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  202328. }else{
  202329. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  202330. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  202331. }
  202332. rc = fts5NextMethod(pCursor);
  202333. }
  202334. }
  202335. pConfig->pzErrmsg = pzErrmsg;
  202336. return rc;
  202337. }
  202338. /*
  202339. ** This is the xEof method of the virtual table. SQLite calls this
  202340. ** routine to find out if it has reached the end of a result set.
  202341. */
  202342. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  202343. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  202344. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  202345. }
  202346. /*
  202347. ** Return the rowid that the cursor currently points to.
  202348. */
  202349. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  202350. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  202351. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  202352. || pCsr->ePlan==FTS5_PLAN_SOURCE
  202353. );
  202354. if( pCsr->pSorter ){
  202355. return pCsr->pSorter->iRowid;
  202356. }else{
  202357. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  202358. }
  202359. }
  202360. /*
  202361. ** This is the xRowid method. The SQLite core calls this routine to
  202362. ** retrieve the rowid for the current row of the result set. fts5
  202363. ** exposes %_content.rowid as the rowid for the virtual table. The
  202364. ** rowid should be written to *pRowid.
  202365. */
  202366. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  202367. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  202368. int ePlan = pCsr->ePlan;
  202369. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  202370. switch( ePlan ){
  202371. case FTS5_PLAN_SPECIAL:
  202372. *pRowid = 0;
  202373. break;
  202374. case FTS5_PLAN_SOURCE:
  202375. case FTS5_PLAN_MATCH:
  202376. case FTS5_PLAN_SORTED_MATCH:
  202377. *pRowid = fts5CursorRowid(pCsr);
  202378. break;
  202379. default:
  202380. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  202381. break;
  202382. }
  202383. return SQLITE_OK;
  202384. }
  202385. /*
  202386. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  202387. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  202388. **
  202389. ** If argument bErrormsg is true and an error occurs, an error message may
  202390. ** be left in sqlite3_vtab.zErrMsg.
  202391. */
  202392. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  202393. int rc = SQLITE_OK;
  202394. /* If the cursor does not yet have a statement handle, obtain one now. */
  202395. if( pCsr->pStmt==0 ){
  202396. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  202397. int eStmt = fts5StmtType(pCsr);
  202398. rc = sqlite3Fts5StorageStmt(
  202399. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->p.base.zErrMsg:0)
  202400. );
  202401. assert( rc!=SQLITE_OK || pTab->p.base.zErrMsg==0 );
  202402. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  202403. }
  202404. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  202405. assert( pCsr->pExpr );
  202406. sqlite3_reset(pCsr->pStmt);
  202407. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  202408. rc = sqlite3_step(pCsr->pStmt);
  202409. if( rc==SQLITE_ROW ){
  202410. rc = SQLITE_OK;
  202411. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  202412. }else{
  202413. rc = sqlite3_reset(pCsr->pStmt);
  202414. if( rc==SQLITE_OK ){
  202415. rc = FTS5_CORRUPT;
  202416. }
  202417. }
  202418. }
  202419. return rc;
  202420. }
  202421. static void fts5SetVtabError(Fts5FullTable *p, const char *zFormat, ...){
  202422. va_list ap; /* ... printf arguments */
  202423. va_start(ap, zFormat);
  202424. assert( p->p.base.zErrMsg==0 );
  202425. p->p.base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  202426. va_end(ap);
  202427. }
  202428. /*
  202429. ** This function is called to handle an FTS INSERT command. In other words,
  202430. ** an INSERT statement of the form:
  202431. **
  202432. ** INSERT INTO fts(fts) VALUES($pCmd)
  202433. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  202434. **
  202435. ** Argument pVal is the value assigned to column "fts" by the INSERT
  202436. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  202437. ** error code if an error occurs.
  202438. **
  202439. ** The commands implemented by this function are documented in the "Special
  202440. ** INSERT Directives" section of the documentation. It should be updated if
  202441. ** more commands are added to this function.
  202442. */
  202443. static int fts5SpecialInsert(
  202444. Fts5FullTable *pTab, /* Fts5 table object */
  202445. const char *zCmd, /* Text inserted into table-name column */
  202446. sqlite3_value *pVal /* Value inserted into rank column */
  202447. ){
  202448. Fts5Config *pConfig = pTab->p.pConfig;
  202449. int rc = SQLITE_OK;
  202450. int bError = 0;
  202451. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  202452. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  202453. fts5SetVtabError(pTab,
  202454. "'delete-all' may only be used with a "
  202455. "contentless or external content fts5 table"
  202456. );
  202457. rc = SQLITE_ERROR;
  202458. }else{
  202459. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  202460. }
  202461. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  202462. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  202463. fts5SetVtabError(pTab,
  202464. "'rebuild' may not be used with a contentless fts5 table"
  202465. );
  202466. rc = SQLITE_ERROR;
  202467. }else{
  202468. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  202469. }
  202470. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  202471. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  202472. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  202473. int nMerge = sqlite3_value_int(pVal);
  202474. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  202475. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  202476. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  202477. #ifdef SQLITE_DEBUG
  202478. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  202479. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  202480. #endif
  202481. }else{
  202482. rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
  202483. if( rc==SQLITE_OK ){
  202484. rc = sqlite3Fts5ConfigSetValue(pTab->p.pConfig, zCmd, pVal, &bError);
  202485. }
  202486. if( rc==SQLITE_OK ){
  202487. if( bError ){
  202488. rc = SQLITE_ERROR;
  202489. }else{
  202490. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  202491. }
  202492. }
  202493. }
  202494. return rc;
  202495. }
  202496. static int fts5SpecialDelete(
  202497. Fts5FullTable *pTab,
  202498. sqlite3_value **apVal
  202499. ){
  202500. int rc = SQLITE_OK;
  202501. int eType1 = sqlite3_value_type(apVal[1]);
  202502. if( eType1==SQLITE_INTEGER ){
  202503. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  202504. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
  202505. }
  202506. return rc;
  202507. }
  202508. static void fts5StorageInsert(
  202509. int *pRc,
  202510. Fts5FullTable *pTab,
  202511. sqlite3_value **apVal,
  202512. i64 *piRowid
  202513. ){
  202514. int rc = *pRc;
  202515. if( rc==SQLITE_OK ){
  202516. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  202517. }
  202518. if( rc==SQLITE_OK ){
  202519. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  202520. }
  202521. *pRc = rc;
  202522. }
  202523. /*
  202524. ** This function is the implementation of the xUpdate callback used by
  202525. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  202526. ** inserted, updated or deleted.
  202527. **
  202528. ** A delete specifies a single argument - the rowid of the row to remove.
  202529. **
  202530. ** Update and insert operations pass:
  202531. **
  202532. ** 1. The "old" rowid, or NULL.
  202533. ** 2. The "new" rowid.
  202534. ** 3. Values for each of the nCol matchable columns.
  202535. ** 4. Values for the two hidden columns (<tablename> and "rank").
  202536. */
  202537. static int fts5UpdateMethod(
  202538. sqlite3_vtab *pVtab, /* Virtual table handle */
  202539. int nArg, /* Size of argument array */
  202540. sqlite3_value **apVal, /* Array of arguments */
  202541. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  202542. ){
  202543. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  202544. Fts5Config *pConfig = pTab->p.pConfig;
  202545. int eType0; /* value_type() of apVal[0] */
  202546. int rc = SQLITE_OK; /* Return code */
  202547. /* A transaction must be open when this is called. */
  202548. assert( pTab->ts.eState==1 );
  202549. assert( pVtab->zErrMsg==0 );
  202550. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  202551. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER
  202552. || sqlite3_value_type(apVal[0])==SQLITE_NULL
  202553. );
  202554. assert( pTab->p.pConfig->pzErrmsg==0 );
  202555. pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
  202556. /* Put any active cursors into REQUIRE_SEEK state. */
  202557. fts5TripCursors(pTab);
  202558. eType0 = sqlite3_value_type(apVal[0]);
  202559. if( eType0==SQLITE_NULL
  202560. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  202561. ){
  202562. /* A "special" INSERT op. These are handled separately. */
  202563. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  202564. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  202565. && 0==sqlite3_stricmp("delete", z)
  202566. ){
  202567. rc = fts5SpecialDelete(pTab, apVal);
  202568. }else{
  202569. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  202570. }
  202571. }else{
  202572. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  202573. ** any conflict on the rowid value must be detected before any
  202574. ** modifications are made to the database file. There are 4 cases:
  202575. **
  202576. ** 1) DELETE
  202577. ** 2) UPDATE (rowid not modified)
  202578. ** 3) UPDATE (rowid modified)
  202579. ** 4) INSERT
  202580. **
  202581. ** Cases 3 and 4 may violate the rowid constraint.
  202582. */
  202583. int eConflict = SQLITE_ABORT;
  202584. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  202585. eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  202586. }
  202587. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  202588. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  202589. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  202590. ** This is not suported. */
  202591. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  202592. pTab->p.base.zErrMsg = sqlite3_mprintf(
  202593. "cannot %s contentless fts5 table: %s",
  202594. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  202595. );
  202596. rc = SQLITE_ERROR;
  202597. }
  202598. /* DELETE */
  202599. else if( nArg==1 ){
  202600. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  202601. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
  202602. }
  202603. /* INSERT or UPDATE */
  202604. else{
  202605. int eType1 = sqlite3_value_numeric_type(apVal[1]);
  202606. if( eType1!=SQLITE_INTEGER && eType1!=SQLITE_NULL ){
  202607. rc = SQLITE_MISMATCH;
  202608. }
  202609. else if( eType0!=SQLITE_INTEGER ){
  202610. /* If this is a REPLACE, first remove the current entry (if any) */
  202611. if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){
  202612. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  202613. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  202614. }
  202615. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  202616. }
  202617. /* UPDATE */
  202618. else{
  202619. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  202620. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  202621. if( eType1==SQLITE_INTEGER && iOld!=iNew ){
  202622. if( eConflict==SQLITE_REPLACE ){
  202623. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  202624. if( rc==SQLITE_OK ){
  202625. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  202626. }
  202627. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  202628. }else{
  202629. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  202630. if( rc==SQLITE_OK ){
  202631. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  202632. }
  202633. if( rc==SQLITE_OK ){
  202634. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal,*pRowid);
  202635. }
  202636. }
  202637. }else{
  202638. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  202639. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  202640. }
  202641. }
  202642. }
  202643. }
  202644. pTab->p.pConfig->pzErrmsg = 0;
  202645. return rc;
  202646. }
  202647. /*
  202648. ** Implementation of xSync() method.
  202649. */
  202650. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  202651. int rc;
  202652. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  202653. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  202654. pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
  202655. fts5TripCursors(pTab);
  202656. rc = sqlite3Fts5StorageSync(pTab->pStorage);
  202657. pTab->p.pConfig->pzErrmsg = 0;
  202658. return rc;
  202659. }
  202660. /*
  202661. ** Implementation of xBegin() method.
  202662. */
  202663. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  202664. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_BEGIN, 0);
  202665. fts5NewTransaction((Fts5FullTable*)pVtab);
  202666. return SQLITE_OK;
  202667. }
  202668. /*
  202669. ** Implementation of xCommit() method. This is a no-op. The contents of
  202670. ** the pending-terms hash-table have already been flushed into the database
  202671. ** by fts5SyncMethod().
  202672. */
  202673. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  202674. UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
  202675. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_COMMIT, 0);
  202676. return SQLITE_OK;
  202677. }
  202678. /*
  202679. ** Implementation of xRollback(). Discard the contents of the pending-terms
  202680. ** hash-table. Any changes made to the database are reverted by SQLite.
  202681. */
  202682. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  202683. int rc;
  202684. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  202685. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  202686. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  202687. return rc;
  202688. }
  202689. static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
  202690. static void *fts5ApiUserData(Fts5Context *pCtx){
  202691. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202692. return pCsr->pAux->pUserData;
  202693. }
  202694. static int fts5ApiColumnCount(Fts5Context *pCtx){
  202695. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202696. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  202697. }
  202698. static int fts5ApiColumnTotalSize(
  202699. Fts5Context *pCtx,
  202700. int iCol,
  202701. sqlite3_int64 *pnToken
  202702. ){
  202703. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202704. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  202705. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  202706. }
  202707. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  202708. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202709. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  202710. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  202711. }
  202712. static int fts5ApiTokenize(
  202713. Fts5Context *pCtx,
  202714. const char *pText, int nText,
  202715. void *pUserData,
  202716. int (*xToken)(void*, int, const char*, int, int, int)
  202717. ){
  202718. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202719. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  202720. return sqlite3Fts5Tokenize(
  202721. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  202722. );
  202723. }
  202724. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  202725. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202726. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  202727. }
  202728. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  202729. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202730. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  202731. }
  202732. static int fts5ApiColumnText(
  202733. Fts5Context *pCtx,
  202734. int iCol,
  202735. const char **pz,
  202736. int *pn
  202737. ){
  202738. int rc = SQLITE_OK;
  202739. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202740. if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab))
  202741. || pCsr->ePlan==FTS5_PLAN_SPECIAL
  202742. ){
  202743. *pz = 0;
  202744. *pn = 0;
  202745. }else{
  202746. rc = fts5SeekCursor(pCsr, 0);
  202747. if( rc==SQLITE_OK ){
  202748. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  202749. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  202750. }
  202751. }
  202752. return rc;
  202753. }
  202754. static int fts5CsrPoslist(
  202755. Fts5Cursor *pCsr,
  202756. int iPhrase,
  202757. const u8 **pa,
  202758. int *pn
  202759. ){
  202760. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  202761. int rc = SQLITE_OK;
  202762. int bLive = (pCsr->pSorter==0);
  202763. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
  202764. if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
  202765. Fts5PoslistPopulator *aPopulator;
  202766. int i;
  202767. aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
  202768. if( aPopulator==0 ) rc = SQLITE_NOMEM;
  202769. for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
  202770. int n; const char *z;
  202771. rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
  202772. if( rc==SQLITE_OK ){
  202773. rc = sqlite3Fts5ExprPopulatePoslists(
  202774. pConfig, pCsr->pExpr, aPopulator, i, z, n
  202775. );
  202776. }
  202777. }
  202778. sqlite3_free(aPopulator);
  202779. if( pCsr->pSorter ){
  202780. sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
  202781. }
  202782. }
  202783. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
  202784. }
  202785. if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
  202786. Fts5Sorter *pSorter = pCsr->pSorter;
  202787. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  202788. *pn = pSorter->aIdx[iPhrase] - i1;
  202789. *pa = &pSorter->aPoslist[i1];
  202790. }else{
  202791. *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  202792. }
  202793. return rc;
  202794. }
  202795. /*
  202796. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  202797. ** correctly for the current view. Return SQLITE_OK if successful, or an
  202798. ** SQLite error code otherwise.
  202799. */
  202800. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  202801. int rc = SQLITE_OK;
  202802. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  202803. int nIter; /* Number of iterators/phrases */
  202804. int nCol = ((Fts5Table*)pCsr->base.pVtab)->pConfig->nCol;
  202805. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  202806. if( pCsr->aInstIter==0 ){
  202807. sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nIter;
  202808. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  202809. }
  202810. aIter = pCsr->aInstIter;
  202811. if( aIter ){
  202812. int nInst = 0; /* Number instances seen so far */
  202813. int i;
  202814. /* Initialize all iterators */
  202815. for(i=0; i<nIter && rc==SQLITE_OK; i++){
  202816. const u8 *a;
  202817. int n;
  202818. rc = fts5CsrPoslist(pCsr, i, &a, &n);
  202819. if( rc==SQLITE_OK ){
  202820. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  202821. }
  202822. }
  202823. if( rc==SQLITE_OK ){
  202824. while( 1 ){
  202825. int *aInst;
  202826. int iBest = -1;
  202827. for(i=0; i<nIter; i++){
  202828. if( (aIter[i].bEof==0)
  202829. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  202830. ){
  202831. iBest = i;
  202832. }
  202833. }
  202834. if( iBest<0 ) break;
  202835. nInst++;
  202836. if( nInst>=pCsr->nInstAlloc ){
  202837. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  202838. aInst = (int*)sqlite3_realloc64(
  202839. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  202840. );
  202841. if( aInst ){
  202842. pCsr->aInst = aInst;
  202843. }else{
  202844. rc = SQLITE_NOMEM;
  202845. break;
  202846. }
  202847. }
  202848. aInst = &pCsr->aInst[3 * (nInst-1)];
  202849. aInst[0] = iBest;
  202850. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  202851. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  202852. if( aInst[1]<0 || aInst[1]>=nCol ){
  202853. rc = FTS5_CORRUPT;
  202854. break;
  202855. }
  202856. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  202857. }
  202858. }
  202859. pCsr->nInstCount = nInst;
  202860. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  202861. }
  202862. return rc;
  202863. }
  202864. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  202865. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202866. int rc = SQLITE_OK;
  202867. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  202868. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  202869. *pnInst = pCsr->nInstCount;
  202870. }
  202871. return rc;
  202872. }
  202873. static int fts5ApiInst(
  202874. Fts5Context *pCtx,
  202875. int iIdx,
  202876. int *piPhrase,
  202877. int *piCol,
  202878. int *piOff
  202879. ){
  202880. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202881. int rc = SQLITE_OK;
  202882. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  202883. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  202884. ){
  202885. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  202886. rc = SQLITE_RANGE;
  202887. #if 0
  202888. }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
  202889. *piPhrase = pCsr->aInst[iIdx*3];
  202890. *piCol = pCsr->aInst[iIdx*3 + 2];
  202891. *piOff = -1;
  202892. #endif
  202893. }else{
  202894. *piPhrase = pCsr->aInst[iIdx*3];
  202895. *piCol = pCsr->aInst[iIdx*3 + 1];
  202896. *piOff = pCsr->aInst[iIdx*3 + 2];
  202897. }
  202898. }
  202899. return rc;
  202900. }
  202901. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  202902. return fts5CursorRowid((Fts5Cursor*)pCtx);
  202903. }
  202904. static int fts5ColumnSizeCb(
  202905. void *pContext, /* Pointer to int */
  202906. int tflags,
  202907. const char *pUnused, /* Buffer containing token */
  202908. int nUnused, /* Size of token in bytes */
  202909. int iUnused1, /* Start offset of token */
  202910. int iUnused2 /* End offset of token */
  202911. ){
  202912. int *pCnt = (int*)pContext;
  202913. UNUSED_PARAM2(pUnused, nUnused);
  202914. UNUSED_PARAM2(iUnused1, iUnused2);
  202915. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  202916. (*pCnt)++;
  202917. }
  202918. return SQLITE_OK;
  202919. }
  202920. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  202921. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202922. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  202923. Fts5Config *pConfig = pTab->p.pConfig;
  202924. int rc = SQLITE_OK;
  202925. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  202926. if( pConfig->bColumnsize ){
  202927. i64 iRowid = fts5CursorRowid(pCsr);
  202928. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  202929. }else if( pConfig->zContent==0 ){
  202930. int i;
  202931. for(i=0; i<pConfig->nCol; i++){
  202932. if( pConfig->abUnindexed[i]==0 ){
  202933. pCsr->aColumnSize[i] = -1;
  202934. }
  202935. }
  202936. }else{
  202937. int i;
  202938. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  202939. if( pConfig->abUnindexed[i]==0 ){
  202940. const char *z; int n;
  202941. void *p = (void*)(&pCsr->aColumnSize[i]);
  202942. pCsr->aColumnSize[i] = 0;
  202943. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  202944. if( rc==SQLITE_OK ){
  202945. rc = sqlite3Fts5Tokenize(
  202946. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  202947. );
  202948. }
  202949. }
  202950. }
  202951. }
  202952. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  202953. }
  202954. if( iCol<0 ){
  202955. int i;
  202956. *pnToken = 0;
  202957. for(i=0; i<pConfig->nCol; i++){
  202958. *pnToken += pCsr->aColumnSize[i];
  202959. }
  202960. }else if( iCol<pConfig->nCol ){
  202961. *pnToken = pCsr->aColumnSize[iCol];
  202962. }else{
  202963. *pnToken = 0;
  202964. rc = SQLITE_RANGE;
  202965. }
  202966. return rc;
  202967. }
  202968. /*
  202969. ** Implementation of the xSetAuxdata() method.
  202970. */
  202971. static int fts5ApiSetAuxdata(
  202972. Fts5Context *pCtx, /* Fts5 context */
  202973. void *pPtr, /* Pointer to save as auxdata */
  202974. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  202975. ){
  202976. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  202977. Fts5Auxdata *pData;
  202978. /* Search through the cursors list of Fts5Auxdata objects for one that
  202979. ** corresponds to the currently executing auxiliary function. */
  202980. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  202981. if( pData->pAux==pCsr->pAux ) break;
  202982. }
  202983. if( pData ){
  202984. if( pData->xDelete ){
  202985. pData->xDelete(pData->pPtr);
  202986. }
  202987. }else{
  202988. int rc = SQLITE_OK;
  202989. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  202990. if( pData==0 ){
  202991. if( xDelete ) xDelete(pPtr);
  202992. return rc;
  202993. }
  202994. pData->pAux = pCsr->pAux;
  202995. pData->pNext = pCsr->pAuxdata;
  202996. pCsr->pAuxdata = pData;
  202997. }
  202998. pData->xDelete = xDelete;
  202999. pData->pPtr = pPtr;
  203000. return SQLITE_OK;
  203001. }
  203002. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  203003. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203004. Fts5Auxdata *pData;
  203005. void *pRet = 0;
  203006. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  203007. if( pData->pAux==pCsr->pAux ) break;
  203008. }
  203009. if( pData ){
  203010. pRet = pData->pPtr;
  203011. if( bClear ){
  203012. pData->pPtr = 0;
  203013. pData->xDelete = 0;
  203014. }
  203015. }
  203016. return pRet;
  203017. }
  203018. static void fts5ApiPhraseNext(
  203019. Fts5Context *pUnused,
  203020. Fts5PhraseIter *pIter,
  203021. int *piCol, int *piOff
  203022. ){
  203023. UNUSED_PARAM(pUnused);
  203024. if( pIter->a>=pIter->b ){
  203025. *piCol = -1;
  203026. *piOff = -1;
  203027. }else{
  203028. int iVal;
  203029. pIter->a += fts5GetVarint32(pIter->a, iVal);
  203030. if( iVal==1 ){
  203031. pIter->a += fts5GetVarint32(pIter->a, iVal);
  203032. *piCol = iVal;
  203033. *piOff = 0;
  203034. pIter->a += fts5GetVarint32(pIter->a, iVal);
  203035. }
  203036. *piOff += (iVal-2);
  203037. }
  203038. }
  203039. static int fts5ApiPhraseFirst(
  203040. Fts5Context *pCtx,
  203041. int iPhrase,
  203042. Fts5PhraseIter *pIter,
  203043. int *piCol, int *piOff
  203044. ){
  203045. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203046. int n;
  203047. int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  203048. if( rc==SQLITE_OK ){
  203049. pIter->b = &pIter->a[n];
  203050. *piCol = 0;
  203051. *piOff = 0;
  203052. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  203053. }
  203054. return rc;
  203055. }
  203056. static void fts5ApiPhraseNextColumn(
  203057. Fts5Context *pCtx,
  203058. Fts5PhraseIter *pIter,
  203059. int *piCol
  203060. ){
  203061. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203062. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  203063. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  203064. if( pIter->a>=pIter->b ){
  203065. *piCol = -1;
  203066. }else{
  203067. int iIncr;
  203068. pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
  203069. *piCol += (iIncr-2);
  203070. }
  203071. }else{
  203072. while( 1 ){
  203073. int dummy;
  203074. if( pIter->a>=pIter->b ){
  203075. *piCol = -1;
  203076. return;
  203077. }
  203078. if( pIter->a[0]==0x01 ) break;
  203079. pIter->a += fts5GetVarint32(pIter->a, dummy);
  203080. }
  203081. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  203082. }
  203083. }
  203084. static int fts5ApiPhraseFirstColumn(
  203085. Fts5Context *pCtx,
  203086. int iPhrase,
  203087. Fts5PhraseIter *pIter,
  203088. int *piCol
  203089. ){
  203090. int rc = SQLITE_OK;
  203091. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203092. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  203093. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  203094. Fts5Sorter *pSorter = pCsr->pSorter;
  203095. int n;
  203096. if( pSorter ){
  203097. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  203098. n = pSorter->aIdx[iPhrase] - i1;
  203099. pIter->a = &pSorter->aPoslist[i1];
  203100. }else{
  203101. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
  203102. }
  203103. if( rc==SQLITE_OK ){
  203104. pIter->b = &pIter->a[n];
  203105. *piCol = 0;
  203106. fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
  203107. }
  203108. }else{
  203109. int n;
  203110. rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  203111. if( rc==SQLITE_OK ){
  203112. pIter->b = &pIter->a[n];
  203113. if( n<=0 ){
  203114. *piCol = -1;
  203115. }else if( pIter->a[0]==0x01 ){
  203116. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  203117. }else{
  203118. *piCol = 0;
  203119. }
  203120. }
  203121. }
  203122. return rc;
  203123. }
  203124. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  203125. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  203126. );
  203127. static const Fts5ExtensionApi sFts5Api = {
  203128. 2, /* iVersion */
  203129. fts5ApiUserData,
  203130. fts5ApiColumnCount,
  203131. fts5ApiRowCount,
  203132. fts5ApiColumnTotalSize,
  203133. fts5ApiTokenize,
  203134. fts5ApiPhraseCount,
  203135. fts5ApiPhraseSize,
  203136. fts5ApiInstCount,
  203137. fts5ApiInst,
  203138. fts5ApiRowid,
  203139. fts5ApiColumnText,
  203140. fts5ApiColumnSize,
  203141. fts5ApiQueryPhrase,
  203142. fts5ApiSetAuxdata,
  203143. fts5ApiGetAuxdata,
  203144. fts5ApiPhraseFirst,
  203145. fts5ApiPhraseNext,
  203146. fts5ApiPhraseFirstColumn,
  203147. fts5ApiPhraseNextColumn,
  203148. };
  203149. /*
  203150. ** Implementation of API function xQueryPhrase().
  203151. */
  203152. static int fts5ApiQueryPhrase(
  203153. Fts5Context *pCtx,
  203154. int iPhrase,
  203155. void *pUserData,
  203156. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  203157. ){
  203158. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  203159. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  203160. int rc;
  203161. Fts5Cursor *pNew = 0;
  203162. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  203163. if( rc==SQLITE_OK ){
  203164. pNew->ePlan = FTS5_PLAN_MATCH;
  203165. pNew->iFirstRowid = SMALLEST_INT64;
  203166. pNew->iLastRowid = LARGEST_INT64;
  203167. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  203168. rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
  203169. }
  203170. if( rc==SQLITE_OK ){
  203171. for(rc = fts5CursorFirst(pTab, pNew, 0);
  203172. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  203173. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  203174. ){
  203175. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  203176. if( rc!=SQLITE_OK ){
  203177. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  203178. break;
  203179. }
  203180. }
  203181. }
  203182. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  203183. return rc;
  203184. }
  203185. static void fts5ApiInvoke(
  203186. Fts5Auxiliary *pAux,
  203187. Fts5Cursor *pCsr,
  203188. sqlite3_context *context,
  203189. int argc,
  203190. sqlite3_value **argv
  203191. ){
  203192. assert( pCsr->pAux==0 );
  203193. pCsr->pAux = pAux;
  203194. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  203195. pCsr->pAux = 0;
  203196. }
  203197. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  203198. Fts5Cursor *pCsr;
  203199. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  203200. if( pCsr->iCsrId==iCsrId ) break;
  203201. }
  203202. return pCsr;
  203203. }
  203204. static void fts5ApiCallback(
  203205. sqlite3_context *context,
  203206. int argc,
  203207. sqlite3_value **argv
  203208. ){
  203209. Fts5Auxiliary *pAux;
  203210. Fts5Cursor *pCsr;
  203211. i64 iCsrId;
  203212. assert( argc>=1 );
  203213. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  203214. iCsrId = sqlite3_value_int64(argv[0]);
  203215. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  203216. if( pCsr==0 ){
  203217. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  203218. sqlite3_result_error(context, zErr, -1);
  203219. sqlite3_free(zErr);
  203220. }else{
  203221. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  203222. }
  203223. }
  203224. /*
  203225. ** Given cursor id iId, return a pointer to the corresponding Fts5Table
  203226. ** object. Or NULL If the cursor id does not exist.
  203227. */
  203228. static Fts5Table *sqlite3Fts5TableFromCsrid(
  203229. Fts5Global *pGlobal, /* FTS5 global context for db handle */
  203230. i64 iCsrId /* Id of cursor to find */
  203231. ){
  203232. Fts5Cursor *pCsr;
  203233. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  203234. if( pCsr ){
  203235. return (Fts5Table*)pCsr->base.pVtab;
  203236. }
  203237. return 0;
  203238. }
  203239. /*
  203240. ** Return a "position-list blob" corresponding to the current position of
  203241. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  203242. ** the current position-list for each phrase in the query associated with
  203243. ** cursor pCsr.
  203244. **
  203245. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  203246. ** the number of phrases in the query. Following the varints are the
  203247. ** concatenated position lists for each phrase, in order.
  203248. **
  203249. ** The first varint (if it exists) contains the size of the position list
  203250. ** for phrase 0. The second (same disclaimer) contains the size of position
  203251. ** list 1. And so on. There is no size field for the final position list,
  203252. ** as it can be derived from the total size of the blob.
  203253. */
  203254. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  203255. int i;
  203256. int rc = SQLITE_OK;
  203257. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  203258. Fts5Buffer val;
  203259. memset(&val, 0, sizeof(Fts5Buffer));
  203260. switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
  203261. case FTS5_DETAIL_FULL:
  203262. /* Append the varints */
  203263. for(i=0; i<(nPhrase-1); i++){
  203264. const u8 *dummy;
  203265. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  203266. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  203267. }
  203268. /* Append the position lists */
  203269. for(i=0; i<nPhrase; i++){
  203270. const u8 *pPoslist;
  203271. int nPoslist;
  203272. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  203273. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  203274. }
  203275. break;
  203276. case FTS5_DETAIL_COLUMNS:
  203277. /* Append the varints */
  203278. for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
  203279. const u8 *dummy;
  203280. int nByte;
  203281. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
  203282. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  203283. }
  203284. /* Append the position lists */
  203285. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  203286. const u8 *pPoslist;
  203287. int nPoslist;
  203288. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
  203289. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  203290. }
  203291. break;
  203292. default:
  203293. break;
  203294. }
  203295. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  203296. return rc;
  203297. }
  203298. /*
  203299. ** This is the xColumn method, called by SQLite to request a value from
  203300. ** the row that the supplied cursor currently points to.
  203301. */
  203302. static int fts5ColumnMethod(
  203303. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  203304. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  203305. int iCol /* Index of column to read value from */
  203306. ){
  203307. Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
  203308. Fts5Config *pConfig = pTab->p.pConfig;
  203309. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  203310. int rc = SQLITE_OK;
  203311. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  203312. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  203313. if( iCol==pConfig->nCol ){
  203314. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  203315. }
  203316. }else
  203317. if( iCol==pConfig->nCol ){
  203318. /* User is requesting the value of the special column with the same name
  203319. ** as the table. Return the cursor integer id number. This value is only
  203320. ** useful in that it may be passed as the first argument to an FTS5
  203321. ** auxiliary function. */
  203322. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  203323. }else if( iCol==pConfig->nCol+1 ){
  203324. /* The value of the "rank" column. */
  203325. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  203326. fts5PoslistBlob(pCtx, pCsr);
  203327. }else if(
  203328. pCsr->ePlan==FTS5_PLAN_MATCH
  203329. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  203330. ){
  203331. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  203332. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  203333. }
  203334. }
  203335. }else if( !fts5IsContentless(pTab) ){
  203336. rc = fts5SeekCursor(pCsr, 1);
  203337. if( rc==SQLITE_OK ){
  203338. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  203339. }
  203340. }
  203341. return rc;
  203342. }
  203343. /*
  203344. ** This routine implements the xFindFunction method for the FTS3
  203345. ** virtual table.
  203346. */
  203347. static int fts5FindFunctionMethod(
  203348. sqlite3_vtab *pVtab, /* Virtual table handle */
  203349. int nUnused, /* Number of SQL function arguments */
  203350. const char *zName, /* Name of SQL function */
  203351. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  203352. void **ppArg /* OUT: User data for *pxFunc */
  203353. ){
  203354. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  203355. Fts5Auxiliary *pAux;
  203356. UNUSED_PARAM(nUnused);
  203357. pAux = fts5FindAuxiliary(pTab, zName);
  203358. if( pAux ){
  203359. *pxFunc = fts5ApiCallback;
  203360. *ppArg = (void*)pAux;
  203361. return 1;
  203362. }
  203363. /* No function of the specified name was found. Return 0. */
  203364. return 0;
  203365. }
  203366. /*
  203367. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  203368. */
  203369. static int fts5RenameMethod(
  203370. sqlite3_vtab *pVtab, /* Virtual table handle */
  203371. const char *zName /* New name of table */
  203372. ){
  203373. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  203374. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  203375. }
  203376. static int sqlite3Fts5FlushToDisk(Fts5Table *pTab){
  203377. fts5TripCursors((Fts5FullTable*)pTab);
  203378. return sqlite3Fts5StorageSync(((Fts5FullTable*)pTab)->pStorage);
  203379. }
  203380. /*
  203381. ** The xSavepoint() method.
  203382. **
  203383. ** Flush the contents of the pending-terms table to disk.
  203384. */
  203385. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  203386. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  203387. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_SAVEPOINT, iSavepoint);
  203388. return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
  203389. }
  203390. /*
  203391. ** The xRelease() method.
  203392. **
  203393. ** This is a no-op.
  203394. */
  203395. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  203396. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  203397. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_RELEASE, iSavepoint);
  203398. return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
  203399. }
  203400. /*
  203401. ** The xRollbackTo() method.
  203402. **
  203403. ** Discard the contents of the pending terms table.
  203404. */
  203405. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  203406. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  203407. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  203408. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  203409. fts5TripCursors(pTab);
  203410. return sqlite3Fts5StorageRollback(pTab->pStorage);
  203411. }
  203412. /*
  203413. ** Register a new auxiliary function with global context pGlobal.
  203414. */
  203415. static int fts5CreateAux(
  203416. fts5_api *pApi, /* Global context (one per db handle) */
  203417. const char *zName, /* Name of new function */
  203418. void *pUserData, /* User data for aux. function */
  203419. fts5_extension_function xFunc, /* Aux. function implementation */
  203420. void(*xDestroy)(void*) /* Destructor for pUserData */
  203421. ){
  203422. Fts5Global *pGlobal = (Fts5Global*)pApi;
  203423. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  203424. if( rc==SQLITE_OK ){
  203425. Fts5Auxiliary *pAux;
  203426. sqlite3_int64 nName; /* Size of zName in bytes, including \0 */
  203427. sqlite3_int64 nByte; /* Bytes of space to allocate */
  203428. nName = strlen(zName) + 1;
  203429. nByte = sizeof(Fts5Auxiliary) + nName;
  203430. pAux = (Fts5Auxiliary*)sqlite3_malloc64(nByte);
  203431. if( pAux ){
  203432. memset(pAux, 0, (size_t)nByte);
  203433. pAux->zFunc = (char*)&pAux[1];
  203434. memcpy(pAux->zFunc, zName, nName);
  203435. pAux->pGlobal = pGlobal;
  203436. pAux->pUserData = pUserData;
  203437. pAux->xFunc = xFunc;
  203438. pAux->xDestroy = xDestroy;
  203439. pAux->pNext = pGlobal->pAux;
  203440. pGlobal->pAux = pAux;
  203441. }else{
  203442. rc = SQLITE_NOMEM;
  203443. }
  203444. }
  203445. return rc;
  203446. }
  203447. /*
  203448. ** Register a new tokenizer. This is the implementation of the
  203449. ** fts5_api.xCreateTokenizer() method.
  203450. */
  203451. static int fts5CreateTokenizer(
  203452. fts5_api *pApi, /* Global context (one per db handle) */
  203453. const char *zName, /* Name of new function */
  203454. void *pUserData, /* User data for aux. function */
  203455. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  203456. void(*xDestroy)(void*) /* Destructor for pUserData */
  203457. ){
  203458. Fts5Global *pGlobal = (Fts5Global*)pApi;
  203459. Fts5TokenizerModule *pNew;
  203460. sqlite3_int64 nName; /* Size of zName and its \0 terminator */
  203461. sqlite3_int64 nByte; /* Bytes of space to allocate */
  203462. int rc = SQLITE_OK;
  203463. nName = strlen(zName) + 1;
  203464. nByte = sizeof(Fts5TokenizerModule) + nName;
  203465. pNew = (Fts5TokenizerModule*)sqlite3_malloc64(nByte);
  203466. if( pNew ){
  203467. memset(pNew, 0, (size_t)nByte);
  203468. pNew->zName = (char*)&pNew[1];
  203469. memcpy(pNew->zName, zName, nName);
  203470. pNew->pUserData = pUserData;
  203471. pNew->x = *pTokenizer;
  203472. pNew->xDestroy = xDestroy;
  203473. pNew->pNext = pGlobal->pTok;
  203474. pGlobal->pTok = pNew;
  203475. if( pNew->pNext==0 ){
  203476. pGlobal->pDfltTok = pNew;
  203477. }
  203478. }else{
  203479. rc = SQLITE_NOMEM;
  203480. }
  203481. return rc;
  203482. }
  203483. static Fts5TokenizerModule *fts5LocateTokenizer(
  203484. Fts5Global *pGlobal,
  203485. const char *zName
  203486. ){
  203487. Fts5TokenizerModule *pMod = 0;
  203488. if( zName==0 ){
  203489. pMod = pGlobal->pDfltTok;
  203490. }else{
  203491. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  203492. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  203493. }
  203494. }
  203495. return pMod;
  203496. }
  203497. /*
  203498. ** Find a tokenizer. This is the implementation of the
  203499. ** fts5_api.xFindTokenizer() method.
  203500. */
  203501. static int fts5FindTokenizer(
  203502. fts5_api *pApi, /* Global context (one per db handle) */
  203503. const char *zName, /* Name of new function */
  203504. void **ppUserData,
  203505. fts5_tokenizer *pTokenizer /* Populate this object */
  203506. ){
  203507. int rc = SQLITE_OK;
  203508. Fts5TokenizerModule *pMod;
  203509. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  203510. if( pMod ){
  203511. *pTokenizer = pMod->x;
  203512. *ppUserData = pMod->pUserData;
  203513. }else{
  203514. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  203515. rc = SQLITE_ERROR;
  203516. }
  203517. return rc;
  203518. }
  203519. static int sqlite3Fts5GetTokenizer(
  203520. Fts5Global *pGlobal,
  203521. const char **azArg,
  203522. int nArg,
  203523. Fts5Tokenizer **ppTok,
  203524. fts5_tokenizer **ppTokApi,
  203525. char **pzErr
  203526. ){
  203527. Fts5TokenizerModule *pMod;
  203528. int rc = SQLITE_OK;
  203529. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  203530. if( pMod==0 ){
  203531. assert( nArg>0 );
  203532. rc = SQLITE_ERROR;
  203533. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  203534. }else{
  203535. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  203536. *ppTokApi = &pMod->x;
  203537. if( rc!=SQLITE_OK && pzErr ){
  203538. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  203539. }
  203540. }
  203541. if( rc!=SQLITE_OK ){
  203542. *ppTokApi = 0;
  203543. *ppTok = 0;
  203544. }
  203545. return rc;
  203546. }
  203547. static void fts5ModuleDestroy(void *pCtx){
  203548. Fts5TokenizerModule *pTok, *pNextTok;
  203549. Fts5Auxiliary *pAux, *pNextAux;
  203550. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  203551. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  203552. pNextAux = pAux->pNext;
  203553. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  203554. sqlite3_free(pAux);
  203555. }
  203556. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  203557. pNextTok = pTok->pNext;
  203558. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  203559. sqlite3_free(pTok);
  203560. }
  203561. sqlite3_free(pGlobal);
  203562. }
  203563. static void fts5Fts5Func(
  203564. sqlite3_context *pCtx, /* Function call context */
  203565. int nArg, /* Number of args */
  203566. sqlite3_value **apArg /* Function arguments */
  203567. ){
  203568. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  203569. fts5_api **ppApi;
  203570. UNUSED_PARAM(nArg);
  203571. assert( nArg==1 );
  203572. ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
  203573. if( ppApi ) *ppApi = &pGlobal->api;
  203574. }
  203575. /*
  203576. ** Implementation of fts5_source_id() function.
  203577. */
  203578. static void fts5SourceIdFunc(
  203579. sqlite3_context *pCtx, /* Function call context */
  203580. int nArg, /* Number of args */
  203581. sqlite3_value **apUnused /* Function arguments */
  203582. ){
  203583. assert( nArg==0 );
  203584. UNUSED_PARAM2(nArg, apUnused);
  203585. sqlite3_result_text(pCtx, "fts5: 2019-04-16 19:49:53 884b4b7e502b4e991677b53971277adfaf0a04a284f8e483e2553d0f83156b50", -1, SQLITE_TRANSIENT);
  203586. }
  203587. /*
  203588. ** Return true if zName is the extension on one of the shadow tables used
  203589. ** by this module.
  203590. */
  203591. static int fts5ShadowName(const char *zName){
  203592. static const char *azName[] = {
  203593. "config", "content", "data", "docsize", "idx"
  203594. };
  203595. unsigned int i;
  203596. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  203597. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  203598. }
  203599. return 0;
  203600. }
  203601. static int fts5Init(sqlite3 *db){
  203602. static const sqlite3_module fts5Mod = {
  203603. /* iVersion */ 3,
  203604. /* xCreate */ fts5CreateMethod,
  203605. /* xConnect */ fts5ConnectMethod,
  203606. /* xBestIndex */ fts5BestIndexMethod,
  203607. /* xDisconnect */ fts5DisconnectMethod,
  203608. /* xDestroy */ fts5DestroyMethod,
  203609. /* xOpen */ fts5OpenMethod,
  203610. /* xClose */ fts5CloseMethod,
  203611. /* xFilter */ fts5FilterMethod,
  203612. /* xNext */ fts5NextMethod,
  203613. /* xEof */ fts5EofMethod,
  203614. /* xColumn */ fts5ColumnMethod,
  203615. /* xRowid */ fts5RowidMethod,
  203616. /* xUpdate */ fts5UpdateMethod,
  203617. /* xBegin */ fts5BeginMethod,
  203618. /* xSync */ fts5SyncMethod,
  203619. /* xCommit */ fts5CommitMethod,
  203620. /* xRollback */ fts5RollbackMethod,
  203621. /* xFindFunction */ fts5FindFunctionMethod,
  203622. /* xRename */ fts5RenameMethod,
  203623. /* xSavepoint */ fts5SavepointMethod,
  203624. /* xRelease */ fts5ReleaseMethod,
  203625. /* xRollbackTo */ fts5RollbackToMethod,
  203626. /* xShadowName */ fts5ShadowName
  203627. };
  203628. int rc;
  203629. Fts5Global *pGlobal = 0;
  203630. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  203631. if( pGlobal==0 ){
  203632. rc = SQLITE_NOMEM;
  203633. }else{
  203634. void *p = (void*)pGlobal;
  203635. memset(pGlobal, 0, sizeof(Fts5Global));
  203636. pGlobal->db = db;
  203637. pGlobal->api.iVersion = 2;
  203638. pGlobal->api.xCreateFunction = fts5CreateAux;
  203639. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  203640. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  203641. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  203642. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  203643. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  203644. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  203645. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  203646. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  203647. if( rc==SQLITE_OK ){
  203648. rc = sqlite3_create_function(
  203649. db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  203650. );
  203651. }
  203652. if( rc==SQLITE_OK ){
  203653. rc = sqlite3_create_function(
  203654. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  203655. );
  203656. }
  203657. }
  203658. /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
  203659. ** fts5_test_mi.c is compiled and linked into the executable. And call
  203660. ** its entry point to enable the matchinfo() demo. */
  203661. #ifdef SQLITE_FTS5_ENABLE_TEST_MI
  203662. if( rc==SQLITE_OK ){
  203663. extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
  203664. rc = sqlite3Fts5TestRegisterMatchinfo(db);
  203665. }
  203666. #endif
  203667. return rc;
  203668. }
  203669. /*
  203670. ** The following functions are used to register the module with SQLite. If
  203671. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  203672. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  203673. **
  203674. ** Or, if this module is being built as a loadable extension,
  203675. ** sqlite3Fts5Init() is omitted and the two standard entry points
  203676. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  203677. */
  203678. #ifndef SQLITE_CORE
  203679. #ifdef _WIN32
  203680. __declspec(dllexport)
  203681. #endif
  203682. SQLITE_API int sqlite3_fts_init(
  203683. sqlite3 *db,
  203684. char **pzErrMsg,
  203685. const sqlite3_api_routines *pApi
  203686. ){
  203687. SQLITE_EXTENSION_INIT2(pApi);
  203688. (void)pzErrMsg; /* Unused parameter */
  203689. return fts5Init(db);
  203690. }
  203691. #ifdef _WIN32
  203692. __declspec(dllexport)
  203693. #endif
  203694. SQLITE_API int sqlite3_fts5_init(
  203695. sqlite3 *db,
  203696. char **pzErrMsg,
  203697. const sqlite3_api_routines *pApi
  203698. ){
  203699. SQLITE_EXTENSION_INIT2(pApi);
  203700. (void)pzErrMsg; /* Unused parameter */
  203701. return fts5Init(db);
  203702. }
  203703. #else
  203704. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  203705. return fts5Init(db);
  203706. }
  203707. #endif
  203708. /*
  203709. ** 2014 May 31
  203710. **
  203711. ** The author disclaims copyright to this source code. In place of
  203712. ** a legal notice, here is a blessing:
  203713. **
  203714. ** May you do good and not evil.
  203715. ** May you find forgiveness for yourself and forgive others.
  203716. ** May you share freely, never taking more than you give.
  203717. **
  203718. ******************************************************************************
  203719. **
  203720. */
  203721. /* #include "fts5Int.h" */
  203722. struct Fts5Storage {
  203723. Fts5Config *pConfig;
  203724. Fts5Index *pIndex;
  203725. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  203726. i64 nTotalRow; /* Total number of rows in FTS table */
  203727. i64 *aTotalSize; /* Total sizes of each column */
  203728. sqlite3_stmt *aStmt[11];
  203729. };
  203730. #if FTS5_STMT_SCAN_ASC!=0
  203731. # error "FTS5_STMT_SCAN_ASC mismatch"
  203732. #endif
  203733. #if FTS5_STMT_SCAN_DESC!=1
  203734. # error "FTS5_STMT_SCAN_DESC mismatch"
  203735. #endif
  203736. #if FTS5_STMT_LOOKUP!=2
  203737. # error "FTS5_STMT_LOOKUP mismatch"
  203738. #endif
  203739. #define FTS5_STMT_INSERT_CONTENT 3
  203740. #define FTS5_STMT_REPLACE_CONTENT 4
  203741. #define FTS5_STMT_DELETE_CONTENT 5
  203742. #define FTS5_STMT_REPLACE_DOCSIZE 6
  203743. #define FTS5_STMT_DELETE_DOCSIZE 7
  203744. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  203745. #define FTS5_STMT_REPLACE_CONFIG 9
  203746. #define FTS5_STMT_SCAN 10
  203747. /*
  203748. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  203749. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  203750. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  203751. ** occurs.
  203752. */
  203753. static int fts5StorageGetStmt(
  203754. Fts5Storage *p, /* Storage handle */
  203755. int eStmt, /* FTS5_STMT_XXX constant */
  203756. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  203757. char **pzErrMsg /* OUT: Error message (if any) */
  203758. ){
  203759. int rc = SQLITE_OK;
  203760. /* If there is no %_docsize table, there should be no requests for
  203761. ** statements to operate on it. */
  203762. assert( p->pConfig->bColumnsize || (
  203763. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  203764. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  203765. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  203766. ));
  203767. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  203768. if( p->aStmt[eStmt]==0 ){
  203769. const char *azStmt[] = {
  203770. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  203771. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  203772. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  203773. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  203774. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  203775. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  203776. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  203777. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  203778. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  203779. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  203780. "SELECT %s FROM %s AS T", /* SCAN */
  203781. };
  203782. Fts5Config *pC = p->pConfig;
  203783. char *zSql = 0;
  203784. switch( eStmt ){
  203785. case FTS5_STMT_SCAN:
  203786. zSql = sqlite3_mprintf(azStmt[eStmt],
  203787. pC->zContentExprlist, pC->zContent
  203788. );
  203789. break;
  203790. case FTS5_STMT_SCAN_ASC:
  203791. case FTS5_STMT_SCAN_DESC:
  203792. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  203793. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  203794. pC->zContentRowid
  203795. );
  203796. break;
  203797. case FTS5_STMT_LOOKUP:
  203798. zSql = sqlite3_mprintf(azStmt[eStmt],
  203799. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  203800. );
  203801. break;
  203802. case FTS5_STMT_INSERT_CONTENT:
  203803. case FTS5_STMT_REPLACE_CONTENT: {
  203804. int nCol = pC->nCol + 1;
  203805. char *zBind;
  203806. int i;
  203807. zBind = sqlite3_malloc64(1 + nCol*2);
  203808. if( zBind ){
  203809. for(i=0; i<nCol; i++){
  203810. zBind[i*2] = '?';
  203811. zBind[i*2 + 1] = ',';
  203812. }
  203813. zBind[i*2-1] = '\0';
  203814. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  203815. sqlite3_free(zBind);
  203816. }
  203817. break;
  203818. }
  203819. default:
  203820. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  203821. break;
  203822. }
  203823. if( zSql==0 ){
  203824. rc = SQLITE_NOMEM;
  203825. }else{
  203826. int f = SQLITE_PREPARE_PERSISTENT;
  203827. if( eStmt>FTS5_STMT_LOOKUP ) f |= SQLITE_PREPARE_NO_VTAB;
  203828. rc = sqlite3_prepare_v3(pC->db, zSql, -1, f, &p->aStmt[eStmt], 0);
  203829. sqlite3_free(zSql);
  203830. if( rc!=SQLITE_OK && pzErrMsg ){
  203831. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  203832. }
  203833. }
  203834. }
  203835. *ppStmt = p->aStmt[eStmt];
  203836. sqlite3_reset(*ppStmt);
  203837. return rc;
  203838. }
  203839. static int fts5ExecPrintf(
  203840. sqlite3 *db,
  203841. char **pzErr,
  203842. const char *zFormat,
  203843. ...
  203844. ){
  203845. int rc;
  203846. va_list ap; /* ... printf arguments */
  203847. char *zSql;
  203848. va_start(ap, zFormat);
  203849. zSql = sqlite3_vmprintf(zFormat, ap);
  203850. if( zSql==0 ){
  203851. rc = SQLITE_NOMEM;
  203852. }else{
  203853. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  203854. sqlite3_free(zSql);
  203855. }
  203856. va_end(ap);
  203857. return rc;
  203858. }
  203859. /*
  203860. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  203861. ** code otherwise.
  203862. */
  203863. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  203864. int rc = fts5ExecPrintf(pConfig->db, 0,
  203865. "DROP TABLE IF EXISTS %Q.'%q_data';"
  203866. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  203867. "DROP TABLE IF EXISTS %Q.'%q_config';",
  203868. pConfig->zDb, pConfig->zName,
  203869. pConfig->zDb, pConfig->zName,
  203870. pConfig->zDb, pConfig->zName
  203871. );
  203872. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  203873. rc = fts5ExecPrintf(pConfig->db, 0,
  203874. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  203875. pConfig->zDb, pConfig->zName
  203876. );
  203877. }
  203878. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  203879. rc = fts5ExecPrintf(pConfig->db, 0,
  203880. "DROP TABLE IF EXISTS %Q.'%q_content';",
  203881. pConfig->zDb, pConfig->zName
  203882. );
  203883. }
  203884. return rc;
  203885. }
  203886. static void fts5StorageRenameOne(
  203887. Fts5Config *pConfig, /* Current FTS5 configuration */
  203888. int *pRc, /* IN/OUT: Error code */
  203889. const char *zTail, /* Tail of table name e.g. "data", "config" */
  203890. const char *zName /* New name of FTS5 table */
  203891. ){
  203892. if( *pRc==SQLITE_OK ){
  203893. *pRc = fts5ExecPrintf(pConfig->db, 0,
  203894. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  203895. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  203896. );
  203897. }
  203898. }
  203899. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  203900. Fts5Config *pConfig = pStorage->pConfig;
  203901. int rc = sqlite3Fts5StorageSync(pStorage);
  203902. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  203903. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  203904. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  203905. if( pConfig->bColumnsize ){
  203906. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  203907. }
  203908. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  203909. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  203910. }
  203911. return rc;
  203912. }
  203913. /*
  203914. ** Create the shadow table named zPost, with definition zDefn. Return
  203915. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  203916. */
  203917. static int sqlite3Fts5CreateTable(
  203918. Fts5Config *pConfig, /* FTS5 configuration */
  203919. const char *zPost, /* Shadow table to create (e.g. "content") */
  203920. const char *zDefn, /* Columns etc. for shadow table */
  203921. int bWithout, /* True for without rowid */
  203922. char **pzErr /* OUT: Error message */
  203923. ){
  203924. int rc;
  203925. char *zErr = 0;
  203926. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  203927. pConfig->zDb, pConfig->zName, zPost, zDefn,
  203928. #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
  203929. bWithout?" WITHOUT ROWID":
  203930. #endif
  203931. ""
  203932. );
  203933. if( zErr ){
  203934. *pzErr = sqlite3_mprintf(
  203935. "fts5: error creating shadow table %q_%s: %s",
  203936. pConfig->zName, zPost, zErr
  203937. );
  203938. sqlite3_free(zErr);
  203939. }
  203940. return rc;
  203941. }
  203942. /*
  203943. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  203944. ** and initialize the underlying tables
  203945. **
  203946. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  203947. ** Otherwise, set *pp to NULL and return an SQLite error code.
  203948. */
  203949. static int sqlite3Fts5StorageOpen(
  203950. Fts5Config *pConfig,
  203951. Fts5Index *pIndex,
  203952. int bCreate,
  203953. Fts5Storage **pp,
  203954. char **pzErr /* OUT: Error message */
  203955. ){
  203956. int rc = SQLITE_OK;
  203957. Fts5Storage *p; /* New object */
  203958. sqlite3_int64 nByte; /* Bytes of space to allocate */
  203959. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  203960. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  203961. *pp = p = (Fts5Storage*)sqlite3_malloc64(nByte);
  203962. if( !p ) return SQLITE_NOMEM;
  203963. memset(p, 0, (size_t)nByte);
  203964. p->aTotalSize = (i64*)&p[1];
  203965. p->pConfig = pConfig;
  203966. p->pIndex = pIndex;
  203967. if( bCreate ){
  203968. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  203969. int nDefn = 32 + pConfig->nCol*10;
  203970. char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 10);
  203971. if( zDefn==0 ){
  203972. rc = SQLITE_NOMEM;
  203973. }else{
  203974. int i;
  203975. int iOff;
  203976. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  203977. iOff = (int)strlen(zDefn);
  203978. for(i=0; i<pConfig->nCol; i++){
  203979. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  203980. iOff += (int)strlen(&zDefn[iOff]);
  203981. }
  203982. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  203983. }
  203984. sqlite3_free(zDefn);
  203985. }
  203986. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  203987. rc = sqlite3Fts5CreateTable(
  203988. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  203989. );
  203990. }
  203991. if( rc==SQLITE_OK ){
  203992. rc = sqlite3Fts5CreateTable(
  203993. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  203994. );
  203995. }
  203996. if( rc==SQLITE_OK ){
  203997. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  203998. }
  203999. }
  204000. if( rc ){
  204001. sqlite3Fts5StorageClose(p);
  204002. *pp = 0;
  204003. }
  204004. return rc;
  204005. }
  204006. /*
  204007. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  204008. */
  204009. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  204010. int rc = SQLITE_OK;
  204011. if( p ){
  204012. int i;
  204013. /* Finalize all SQL statements */
  204014. for(i=0; i<ArraySize(p->aStmt); i++){
  204015. sqlite3_finalize(p->aStmt[i]);
  204016. }
  204017. sqlite3_free(p);
  204018. }
  204019. return rc;
  204020. }
  204021. typedef struct Fts5InsertCtx Fts5InsertCtx;
  204022. struct Fts5InsertCtx {
  204023. Fts5Storage *pStorage;
  204024. int iCol;
  204025. int szCol; /* Size of column value in tokens */
  204026. };
  204027. /*
  204028. ** Tokenization callback used when inserting tokens into the FTS index.
  204029. */
  204030. static int fts5StorageInsertCallback(
  204031. void *pContext, /* Pointer to Fts5InsertCtx object */
  204032. int tflags,
  204033. const char *pToken, /* Buffer containing token */
  204034. int nToken, /* Size of token in bytes */
  204035. int iUnused1, /* Start offset of token */
  204036. int iUnused2 /* End offset of token */
  204037. ){
  204038. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  204039. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  204040. UNUSED_PARAM2(iUnused1, iUnused2);
  204041. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  204042. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  204043. pCtx->szCol++;
  204044. }
  204045. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  204046. }
  204047. /*
  204048. ** If a row with rowid iDel is present in the %_content table, add the
  204049. ** delete-markers to the FTS index necessary to delete it. Do not actually
  204050. ** remove the %_content row at this time though.
  204051. */
  204052. static int fts5StorageDeleteFromIndex(
  204053. Fts5Storage *p,
  204054. i64 iDel,
  204055. sqlite3_value **apVal
  204056. ){
  204057. Fts5Config *pConfig = p->pConfig;
  204058. sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
  204059. int rc; /* Return code */
  204060. int rc2; /* sqlite3_reset() return code */
  204061. int iCol;
  204062. Fts5InsertCtx ctx;
  204063. if( apVal==0 ){
  204064. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  204065. if( rc!=SQLITE_OK ) return rc;
  204066. sqlite3_bind_int64(pSeek, 1, iDel);
  204067. if( sqlite3_step(pSeek)!=SQLITE_ROW ){
  204068. return sqlite3_reset(pSeek);
  204069. }
  204070. }
  204071. ctx.pStorage = p;
  204072. ctx.iCol = -1;
  204073. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  204074. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  204075. if( pConfig->abUnindexed[iCol-1]==0 ){
  204076. const char *zText;
  204077. int nText;
  204078. if( pSeek ){
  204079. zText = (const char*)sqlite3_column_text(pSeek, iCol);
  204080. nText = sqlite3_column_bytes(pSeek, iCol);
  204081. }else{
  204082. zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
  204083. nText = sqlite3_value_bytes(apVal[iCol-1]);
  204084. }
  204085. ctx.szCol = 0;
  204086. rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
  204087. zText, nText, (void*)&ctx, fts5StorageInsertCallback
  204088. );
  204089. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  204090. }
  204091. }
  204092. p->nTotalRow--;
  204093. rc2 = sqlite3_reset(pSeek);
  204094. if( rc==SQLITE_OK ) rc = rc2;
  204095. return rc;
  204096. }
  204097. /*
  204098. ** Insert a record into the %_docsize table. Specifically, do:
  204099. **
  204100. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  204101. **
  204102. ** If there is no %_docsize table (as happens if the columnsize=0 option
  204103. ** is specified when the FTS5 table is created), this function is a no-op.
  204104. */
  204105. static int fts5StorageInsertDocsize(
  204106. Fts5Storage *p, /* Storage module to write to */
  204107. i64 iRowid, /* id value */
  204108. Fts5Buffer *pBuf /* sz value */
  204109. ){
  204110. int rc = SQLITE_OK;
  204111. if( p->pConfig->bColumnsize ){
  204112. sqlite3_stmt *pReplace = 0;
  204113. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  204114. if( rc==SQLITE_OK ){
  204115. sqlite3_bind_int64(pReplace, 1, iRowid);
  204116. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  204117. sqlite3_step(pReplace);
  204118. rc = sqlite3_reset(pReplace);
  204119. sqlite3_bind_null(pReplace, 2);
  204120. }
  204121. }
  204122. return rc;
  204123. }
  204124. /*
  204125. ** Load the contents of the "averages" record from disk into the
  204126. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  204127. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  204128. ** that the contents of aTotalSize[] and nTotalRow are valid until
  204129. ** further notice.
  204130. **
  204131. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  204132. ** occurs.
  204133. */
  204134. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  204135. int rc = SQLITE_OK;
  204136. if( p->bTotalsValid==0 ){
  204137. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  204138. p->bTotalsValid = bCache;
  204139. }
  204140. return rc;
  204141. }
  204142. /*
  204143. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  204144. ** variables in the "averages" record on disk.
  204145. **
  204146. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  204147. ** occurs.
  204148. */
  204149. static int fts5StorageSaveTotals(Fts5Storage *p){
  204150. int nCol = p->pConfig->nCol;
  204151. int i;
  204152. Fts5Buffer buf;
  204153. int rc = SQLITE_OK;
  204154. memset(&buf, 0, sizeof(buf));
  204155. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  204156. for(i=0; i<nCol; i++){
  204157. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  204158. }
  204159. if( rc==SQLITE_OK ){
  204160. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  204161. }
  204162. sqlite3_free(buf.p);
  204163. return rc;
  204164. }
  204165. /*
  204166. ** Remove a row from the FTS table.
  204167. */
  204168. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
  204169. Fts5Config *pConfig = p->pConfig;
  204170. int rc;
  204171. sqlite3_stmt *pDel = 0;
  204172. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
  204173. rc = fts5StorageLoadTotals(p, 1);
  204174. /* Delete the index records */
  204175. if( rc==SQLITE_OK ){
  204176. rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
  204177. }
  204178. /* Delete the %_docsize record */
  204179. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  204180. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  204181. if( rc==SQLITE_OK ){
  204182. sqlite3_bind_int64(pDel, 1, iDel);
  204183. sqlite3_step(pDel);
  204184. rc = sqlite3_reset(pDel);
  204185. }
  204186. }
  204187. /* Delete the %_content record */
  204188. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  204189. if( rc==SQLITE_OK ){
  204190. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  204191. }
  204192. if( rc==SQLITE_OK ){
  204193. sqlite3_bind_int64(pDel, 1, iDel);
  204194. sqlite3_step(pDel);
  204195. rc = sqlite3_reset(pDel);
  204196. }
  204197. }
  204198. return rc;
  204199. }
  204200. /*
  204201. ** Delete all entries in the FTS5 index.
  204202. */
  204203. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  204204. Fts5Config *pConfig = p->pConfig;
  204205. int rc;
  204206. /* Delete the contents of the %_data and %_docsize tables. */
  204207. rc = fts5ExecPrintf(pConfig->db, 0,
  204208. "DELETE FROM %Q.'%q_data';"
  204209. "DELETE FROM %Q.'%q_idx';",
  204210. pConfig->zDb, pConfig->zName,
  204211. pConfig->zDb, pConfig->zName
  204212. );
  204213. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  204214. rc = fts5ExecPrintf(pConfig->db, 0,
  204215. "DELETE FROM %Q.'%q_docsize';",
  204216. pConfig->zDb, pConfig->zName
  204217. );
  204218. }
  204219. /* Reinitialize the %_data table. This call creates the initial structure
  204220. ** and averages records. */
  204221. if( rc==SQLITE_OK ){
  204222. rc = sqlite3Fts5IndexReinit(p->pIndex);
  204223. }
  204224. if( rc==SQLITE_OK ){
  204225. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  204226. }
  204227. return rc;
  204228. }
  204229. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  204230. Fts5Buffer buf = {0,0,0};
  204231. Fts5Config *pConfig = p->pConfig;
  204232. sqlite3_stmt *pScan = 0;
  204233. Fts5InsertCtx ctx;
  204234. int rc, rc2;
  204235. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  204236. ctx.pStorage = p;
  204237. rc = sqlite3Fts5StorageDeleteAll(p);
  204238. if( rc==SQLITE_OK ){
  204239. rc = fts5StorageLoadTotals(p, 1);
  204240. }
  204241. if( rc==SQLITE_OK ){
  204242. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  204243. }
  204244. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  204245. i64 iRowid = sqlite3_column_int64(pScan, 0);
  204246. sqlite3Fts5BufferZero(&buf);
  204247. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  204248. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  204249. ctx.szCol = 0;
  204250. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  204251. rc = sqlite3Fts5Tokenize(pConfig,
  204252. FTS5_TOKENIZE_DOCUMENT,
  204253. (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
  204254. sqlite3_column_bytes(pScan, ctx.iCol+1),
  204255. (void*)&ctx,
  204256. fts5StorageInsertCallback
  204257. );
  204258. }
  204259. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  204260. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  204261. }
  204262. p->nTotalRow++;
  204263. if( rc==SQLITE_OK ){
  204264. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  204265. }
  204266. }
  204267. sqlite3_free(buf.p);
  204268. rc2 = sqlite3_reset(pScan);
  204269. if( rc==SQLITE_OK ) rc = rc2;
  204270. /* Write the averages record */
  204271. if( rc==SQLITE_OK ){
  204272. rc = fts5StorageSaveTotals(p);
  204273. }
  204274. return rc;
  204275. }
  204276. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  204277. return sqlite3Fts5IndexOptimize(p->pIndex);
  204278. }
  204279. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  204280. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  204281. }
  204282. static int sqlite3Fts5StorageReset(Fts5Storage *p){
  204283. return sqlite3Fts5IndexReset(p->pIndex);
  204284. }
  204285. /*
  204286. ** Allocate a new rowid. This is used for "external content" tables when
  204287. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  204288. ** by inserting a dummy row into the %_docsize table. The dummy will be
  204289. ** overwritten later.
  204290. **
  204291. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  204292. ** this case the user is required to provide a rowid explicitly.
  204293. */
  204294. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  204295. int rc = SQLITE_MISMATCH;
  204296. if( p->pConfig->bColumnsize ){
  204297. sqlite3_stmt *pReplace = 0;
  204298. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  204299. if( rc==SQLITE_OK ){
  204300. sqlite3_bind_null(pReplace, 1);
  204301. sqlite3_bind_null(pReplace, 2);
  204302. sqlite3_step(pReplace);
  204303. rc = sqlite3_reset(pReplace);
  204304. }
  204305. if( rc==SQLITE_OK ){
  204306. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  204307. }
  204308. }
  204309. return rc;
  204310. }
  204311. /*
  204312. ** Insert a new row into the FTS content table.
  204313. */
  204314. static int sqlite3Fts5StorageContentInsert(
  204315. Fts5Storage *p,
  204316. sqlite3_value **apVal,
  204317. i64 *piRowid
  204318. ){
  204319. Fts5Config *pConfig = p->pConfig;
  204320. int rc = SQLITE_OK;
  204321. /* Insert the new row into the %_content table. */
  204322. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  204323. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  204324. *piRowid = sqlite3_value_int64(apVal[1]);
  204325. }else{
  204326. rc = fts5StorageNewRowid(p, piRowid);
  204327. }
  204328. }else{
  204329. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  204330. int i; /* Counter variable */
  204331. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  204332. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  204333. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  204334. }
  204335. if( rc==SQLITE_OK ){
  204336. sqlite3_step(pInsert);
  204337. rc = sqlite3_reset(pInsert);
  204338. }
  204339. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  204340. }
  204341. return rc;
  204342. }
  204343. /*
  204344. ** Insert new entries into the FTS index and %_docsize table.
  204345. */
  204346. static int sqlite3Fts5StorageIndexInsert(
  204347. Fts5Storage *p,
  204348. sqlite3_value **apVal,
  204349. i64 iRowid
  204350. ){
  204351. Fts5Config *pConfig = p->pConfig;
  204352. int rc = SQLITE_OK; /* Return code */
  204353. Fts5InsertCtx ctx; /* Tokenization callback context object */
  204354. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  204355. memset(&buf, 0, sizeof(Fts5Buffer));
  204356. ctx.pStorage = p;
  204357. rc = fts5StorageLoadTotals(p, 1);
  204358. if( rc==SQLITE_OK ){
  204359. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  204360. }
  204361. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  204362. ctx.szCol = 0;
  204363. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  204364. rc = sqlite3Fts5Tokenize(pConfig,
  204365. FTS5_TOKENIZE_DOCUMENT,
  204366. (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
  204367. sqlite3_value_bytes(apVal[ctx.iCol+2]),
  204368. (void*)&ctx,
  204369. fts5StorageInsertCallback
  204370. );
  204371. }
  204372. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  204373. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  204374. }
  204375. p->nTotalRow++;
  204376. /* Write the %_docsize record */
  204377. if( rc==SQLITE_OK ){
  204378. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  204379. }
  204380. sqlite3_free(buf.p);
  204381. return rc;
  204382. }
  204383. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  204384. Fts5Config *pConfig = p->pConfig;
  204385. char *zSql;
  204386. int rc;
  204387. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  204388. pConfig->zDb, pConfig->zName, zSuffix
  204389. );
  204390. if( zSql==0 ){
  204391. rc = SQLITE_NOMEM;
  204392. }else{
  204393. sqlite3_stmt *pCnt = 0;
  204394. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  204395. if( rc==SQLITE_OK ){
  204396. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  204397. *pnRow = sqlite3_column_int64(pCnt, 0);
  204398. }
  204399. rc = sqlite3_finalize(pCnt);
  204400. }
  204401. }
  204402. sqlite3_free(zSql);
  204403. return rc;
  204404. }
  204405. /*
  204406. ** Context object used by sqlite3Fts5StorageIntegrity().
  204407. */
  204408. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  204409. struct Fts5IntegrityCtx {
  204410. i64 iRowid;
  204411. int iCol;
  204412. int szCol;
  204413. u64 cksum;
  204414. Fts5Termset *pTermset;
  204415. Fts5Config *pConfig;
  204416. };
  204417. /*
  204418. ** Tokenization callback used by integrity check.
  204419. */
  204420. static int fts5StorageIntegrityCallback(
  204421. void *pContext, /* Pointer to Fts5IntegrityCtx object */
  204422. int tflags,
  204423. const char *pToken, /* Buffer containing token */
  204424. int nToken, /* Size of token in bytes */
  204425. int iUnused1, /* Start offset of token */
  204426. int iUnused2 /* End offset of token */
  204427. ){
  204428. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  204429. Fts5Termset *pTermset = pCtx->pTermset;
  204430. int bPresent;
  204431. int ii;
  204432. int rc = SQLITE_OK;
  204433. int iPos;
  204434. int iCol;
  204435. UNUSED_PARAM2(iUnused1, iUnused2);
  204436. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  204437. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  204438. pCtx->szCol++;
  204439. }
  204440. switch( pCtx->pConfig->eDetail ){
  204441. case FTS5_DETAIL_FULL:
  204442. iPos = pCtx->szCol-1;
  204443. iCol = pCtx->iCol;
  204444. break;
  204445. case FTS5_DETAIL_COLUMNS:
  204446. iPos = pCtx->iCol;
  204447. iCol = 0;
  204448. break;
  204449. default:
  204450. assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
  204451. iPos = 0;
  204452. iCol = 0;
  204453. break;
  204454. }
  204455. rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
  204456. if( rc==SQLITE_OK && bPresent==0 ){
  204457. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  204458. pCtx->iRowid, iCol, iPos, 0, pToken, nToken
  204459. );
  204460. }
  204461. for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
  204462. const int nChar = pCtx->pConfig->aPrefix[ii];
  204463. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  204464. if( nByte ){
  204465. rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
  204466. if( bPresent==0 ){
  204467. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  204468. pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
  204469. );
  204470. }
  204471. }
  204472. }
  204473. return rc;
  204474. }
  204475. /*
  204476. ** Check that the contents of the FTS index match that of the %_content
  204477. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  204478. ** some other SQLite error code if an error occurs while attempting to
  204479. ** determine this.
  204480. */
  204481. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  204482. Fts5Config *pConfig = p->pConfig;
  204483. int rc; /* Return code */
  204484. int *aColSize; /* Array of size pConfig->nCol */
  204485. i64 *aTotalSize; /* Array of size pConfig->nCol */
  204486. Fts5IntegrityCtx ctx;
  204487. sqlite3_stmt *pScan;
  204488. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  204489. ctx.pConfig = p->pConfig;
  204490. aTotalSize = (i64*)sqlite3_malloc64(pConfig->nCol*(sizeof(int)+sizeof(i64)));
  204491. if( !aTotalSize ) return SQLITE_NOMEM;
  204492. aColSize = (int*)&aTotalSize[pConfig->nCol];
  204493. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  204494. /* Generate the expected index checksum based on the contents of the
  204495. ** %_content table. This block stores the checksum in ctx.cksum. */
  204496. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  204497. if( rc==SQLITE_OK ){
  204498. int rc2;
  204499. while( SQLITE_ROW==sqlite3_step(pScan) ){
  204500. int i;
  204501. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  204502. ctx.szCol = 0;
  204503. if( pConfig->bColumnsize ){
  204504. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  204505. }
  204506. if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
  204507. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  204508. }
  204509. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  204510. if( pConfig->abUnindexed[i] ) continue;
  204511. ctx.iCol = i;
  204512. ctx.szCol = 0;
  204513. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  204514. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  204515. }
  204516. if( rc==SQLITE_OK ){
  204517. rc = sqlite3Fts5Tokenize(pConfig,
  204518. FTS5_TOKENIZE_DOCUMENT,
  204519. (const char*)sqlite3_column_text(pScan, i+1),
  204520. sqlite3_column_bytes(pScan, i+1),
  204521. (void*)&ctx,
  204522. fts5StorageIntegrityCallback
  204523. );
  204524. }
  204525. if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  204526. rc = FTS5_CORRUPT;
  204527. }
  204528. aTotalSize[i] += ctx.szCol;
  204529. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  204530. sqlite3Fts5TermsetFree(ctx.pTermset);
  204531. ctx.pTermset = 0;
  204532. }
  204533. }
  204534. sqlite3Fts5TermsetFree(ctx.pTermset);
  204535. ctx.pTermset = 0;
  204536. if( rc!=SQLITE_OK ) break;
  204537. }
  204538. rc2 = sqlite3_reset(pScan);
  204539. if( rc==SQLITE_OK ) rc = rc2;
  204540. }
  204541. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  204542. if( rc==SQLITE_OK ){
  204543. int i;
  204544. rc = fts5StorageLoadTotals(p, 0);
  204545. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  204546. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  204547. }
  204548. }
  204549. /* Check that the %_docsize and %_content tables contain the expected
  204550. ** number of rows. */
  204551. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  204552. i64 nRow = 0;
  204553. rc = fts5StorageCount(p, "content", &nRow);
  204554. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  204555. }
  204556. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  204557. i64 nRow = 0;
  204558. rc = fts5StorageCount(p, "docsize", &nRow);
  204559. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  204560. }
  204561. /* Pass the expected checksum down to the FTS index module. It will
  204562. ** verify, amongst other things, that it matches the checksum generated by
  204563. ** inspecting the index itself. */
  204564. if( rc==SQLITE_OK ){
  204565. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  204566. }
  204567. sqlite3_free(aTotalSize);
  204568. return rc;
  204569. }
  204570. /*
  204571. ** Obtain an SQLite statement handle that may be used to read data from the
  204572. ** %_content table.
  204573. */
  204574. static int sqlite3Fts5StorageStmt(
  204575. Fts5Storage *p,
  204576. int eStmt,
  204577. sqlite3_stmt **pp,
  204578. char **pzErrMsg
  204579. ){
  204580. int rc;
  204581. assert( eStmt==FTS5_STMT_SCAN_ASC
  204582. || eStmt==FTS5_STMT_SCAN_DESC
  204583. || eStmt==FTS5_STMT_LOOKUP
  204584. );
  204585. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  204586. if( rc==SQLITE_OK ){
  204587. assert( p->aStmt[eStmt]==*pp );
  204588. p->aStmt[eStmt] = 0;
  204589. }
  204590. return rc;
  204591. }
  204592. /*
  204593. ** Release an SQLite statement handle obtained via an earlier call to
  204594. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  204595. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  204596. */
  204597. static void sqlite3Fts5StorageStmtRelease(
  204598. Fts5Storage *p,
  204599. int eStmt,
  204600. sqlite3_stmt *pStmt
  204601. ){
  204602. assert( eStmt==FTS5_STMT_SCAN_ASC
  204603. || eStmt==FTS5_STMT_SCAN_DESC
  204604. || eStmt==FTS5_STMT_LOOKUP
  204605. );
  204606. if( p->aStmt[eStmt]==0 ){
  204607. sqlite3_reset(pStmt);
  204608. p->aStmt[eStmt] = pStmt;
  204609. }else{
  204610. sqlite3_finalize(pStmt);
  204611. }
  204612. }
  204613. static int fts5StorageDecodeSizeArray(
  204614. int *aCol, int nCol, /* Array to populate */
  204615. const u8 *aBlob, int nBlob /* Record to read varints from */
  204616. ){
  204617. int i;
  204618. int iOff = 0;
  204619. for(i=0; i<nCol; i++){
  204620. if( iOff>=nBlob ) return 1;
  204621. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  204622. }
  204623. return (iOff!=nBlob);
  204624. }
  204625. /*
  204626. ** Argument aCol points to an array of integers containing one entry for
  204627. ** each table column. This function reads the %_docsize record for the
  204628. ** specified rowid and populates aCol[] with the results.
  204629. **
  204630. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  204631. ** otherwise.
  204632. */
  204633. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  204634. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  204635. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  204636. int rc; /* Return Code */
  204637. assert( p->pConfig->bColumnsize );
  204638. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  204639. if( rc==SQLITE_OK ){
  204640. int bCorrupt = 1;
  204641. sqlite3_bind_int64(pLookup, 1, iRowid);
  204642. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  204643. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  204644. int nBlob = sqlite3_column_bytes(pLookup, 0);
  204645. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  204646. bCorrupt = 0;
  204647. }
  204648. }
  204649. rc = sqlite3_reset(pLookup);
  204650. if( bCorrupt && rc==SQLITE_OK ){
  204651. rc = FTS5_CORRUPT;
  204652. }
  204653. }
  204654. return rc;
  204655. }
  204656. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  204657. int rc = fts5StorageLoadTotals(p, 0);
  204658. if( rc==SQLITE_OK ){
  204659. *pnToken = 0;
  204660. if( iCol<0 ){
  204661. int i;
  204662. for(i=0; i<p->pConfig->nCol; i++){
  204663. *pnToken += p->aTotalSize[i];
  204664. }
  204665. }else if( iCol<p->pConfig->nCol ){
  204666. *pnToken = p->aTotalSize[iCol];
  204667. }else{
  204668. rc = SQLITE_RANGE;
  204669. }
  204670. }
  204671. return rc;
  204672. }
  204673. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  204674. int rc = fts5StorageLoadTotals(p, 0);
  204675. if( rc==SQLITE_OK ){
  204676. /* nTotalRow being zero does not necessarily indicate a corrupt
  204677. ** database - it might be that the FTS5 table really does contain zero
  204678. ** rows. However this function is only called from the xRowCount() API,
  204679. ** and there is no way for that API to be invoked if the table contains
  204680. ** no rows. Hence the FTS5_CORRUPT return. */
  204681. *pnRow = p->nTotalRow;
  204682. if( p->nTotalRow<=0 ) rc = FTS5_CORRUPT;
  204683. }
  204684. return rc;
  204685. }
  204686. /*
  204687. ** Flush any data currently held in-memory to disk.
  204688. */
  204689. static int sqlite3Fts5StorageSync(Fts5Storage *p){
  204690. int rc = SQLITE_OK;
  204691. i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  204692. if( p->bTotalsValid ){
  204693. rc = fts5StorageSaveTotals(p);
  204694. p->bTotalsValid = 0;
  204695. }
  204696. if( rc==SQLITE_OK ){
  204697. rc = sqlite3Fts5IndexSync(p->pIndex);
  204698. }
  204699. sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
  204700. return rc;
  204701. }
  204702. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  204703. p->bTotalsValid = 0;
  204704. return sqlite3Fts5IndexRollback(p->pIndex);
  204705. }
  204706. static int sqlite3Fts5StorageConfigValue(
  204707. Fts5Storage *p,
  204708. const char *z,
  204709. sqlite3_value *pVal,
  204710. int iVal
  204711. ){
  204712. sqlite3_stmt *pReplace = 0;
  204713. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  204714. if( rc==SQLITE_OK ){
  204715. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  204716. if( pVal ){
  204717. sqlite3_bind_value(pReplace, 2, pVal);
  204718. }else{
  204719. sqlite3_bind_int(pReplace, 2, iVal);
  204720. }
  204721. sqlite3_step(pReplace);
  204722. rc = sqlite3_reset(pReplace);
  204723. sqlite3_bind_null(pReplace, 1);
  204724. }
  204725. if( rc==SQLITE_OK && pVal ){
  204726. int iNew = p->pConfig->iCookie + 1;
  204727. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  204728. if( rc==SQLITE_OK ){
  204729. p->pConfig->iCookie = iNew;
  204730. }
  204731. }
  204732. return rc;
  204733. }
  204734. /*
  204735. ** 2014 May 31
  204736. **
  204737. ** The author disclaims copyright to this source code. In place of
  204738. ** a legal notice, here is a blessing:
  204739. **
  204740. ** May you do good and not evil.
  204741. ** May you find forgiveness for yourself and forgive others.
  204742. ** May you share freely, never taking more than you give.
  204743. **
  204744. ******************************************************************************
  204745. */
  204746. /* #include "fts5Int.h" */
  204747. /**************************************************************************
  204748. ** Start of ascii tokenizer implementation.
  204749. */
  204750. /*
  204751. ** For tokenizers with no "unicode" modifier, the set of token characters
  204752. ** is the same as the set of ASCII range alphanumeric characters.
  204753. */
  204754. static unsigned char aAsciiTokenChar[128] = {
  204755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  204756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  204757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  204758. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  204759. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  204760. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  204761. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  204762. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  204763. };
  204764. typedef struct AsciiTokenizer AsciiTokenizer;
  204765. struct AsciiTokenizer {
  204766. unsigned char aTokenChar[128];
  204767. };
  204768. static void fts5AsciiAddExceptions(
  204769. AsciiTokenizer *p,
  204770. const char *zArg,
  204771. int bTokenChars
  204772. ){
  204773. int i;
  204774. for(i=0; zArg[i]; i++){
  204775. if( (zArg[i] & 0x80)==0 ){
  204776. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  204777. }
  204778. }
  204779. }
  204780. /*
  204781. ** Delete a "ascii" tokenizer.
  204782. */
  204783. static void fts5AsciiDelete(Fts5Tokenizer *p){
  204784. sqlite3_free(p);
  204785. }
  204786. /*
  204787. ** Create an "ascii" tokenizer.
  204788. */
  204789. static int fts5AsciiCreate(
  204790. void *pUnused,
  204791. const char **azArg, int nArg,
  204792. Fts5Tokenizer **ppOut
  204793. ){
  204794. int rc = SQLITE_OK;
  204795. AsciiTokenizer *p = 0;
  204796. UNUSED_PARAM(pUnused);
  204797. if( nArg%2 ){
  204798. rc = SQLITE_ERROR;
  204799. }else{
  204800. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  204801. if( p==0 ){
  204802. rc = SQLITE_NOMEM;
  204803. }else{
  204804. int i;
  204805. memset(p, 0, sizeof(AsciiTokenizer));
  204806. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  204807. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  204808. const char *zArg = azArg[i+1];
  204809. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  204810. fts5AsciiAddExceptions(p, zArg, 1);
  204811. }else
  204812. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  204813. fts5AsciiAddExceptions(p, zArg, 0);
  204814. }else{
  204815. rc = SQLITE_ERROR;
  204816. }
  204817. }
  204818. if( rc!=SQLITE_OK ){
  204819. fts5AsciiDelete((Fts5Tokenizer*)p);
  204820. p = 0;
  204821. }
  204822. }
  204823. }
  204824. *ppOut = (Fts5Tokenizer*)p;
  204825. return rc;
  204826. }
  204827. static void asciiFold(char *aOut, const char *aIn, int nByte){
  204828. int i;
  204829. for(i=0; i<nByte; i++){
  204830. char c = aIn[i];
  204831. if( c>='A' && c<='Z' ) c += 32;
  204832. aOut[i] = c;
  204833. }
  204834. }
  204835. /*
  204836. ** Tokenize some text using the ascii tokenizer.
  204837. */
  204838. static int fts5AsciiTokenize(
  204839. Fts5Tokenizer *pTokenizer,
  204840. void *pCtx,
  204841. int iUnused,
  204842. const char *pText, int nText,
  204843. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  204844. ){
  204845. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  204846. int rc = SQLITE_OK;
  204847. int ie;
  204848. int is = 0;
  204849. char aFold[64];
  204850. int nFold = sizeof(aFold);
  204851. char *pFold = aFold;
  204852. unsigned char *a = p->aTokenChar;
  204853. UNUSED_PARAM(iUnused);
  204854. while( is<nText && rc==SQLITE_OK ){
  204855. int nByte;
  204856. /* Skip any leading divider characters. */
  204857. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  204858. is++;
  204859. }
  204860. if( is==nText ) break;
  204861. /* Count the token characters */
  204862. ie = is+1;
  204863. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  204864. ie++;
  204865. }
  204866. /* Fold to lower case */
  204867. nByte = ie-is;
  204868. if( nByte>nFold ){
  204869. if( pFold!=aFold ) sqlite3_free(pFold);
  204870. pFold = sqlite3_malloc64((sqlite3_int64)nByte*2);
  204871. if( pFold==0 ){
  204872. rc = SQLITE_NOMEM;
  204873. break;
  204874. }
  204875. nFold = nByte*2;
  204876. }
  204877. asciiFold(pFold, &pText[is], nByte);
  204878. /* Invoke the token callback */
  204879. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  204880. is = ie+1;
  204881. }
  204882. if( pFold!=aFold ) sqlite3_free(pFold);
  204883. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  204884. return rc;
  204885. }
  204886. /**************************************************************************
  204887. ** Start of unicode61 tokenizer implementation.
  204888. */
  204889. /*
  204890. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  204891. ** from the sqlite3 source file utf.c. If this file is compiled as part
  204892. ** of the amalgamation, they are not required.
  204893. */
  204894. #ifndef SQLITE_AMALGAMATION
  204895. static const unsigned char sqlite3Utf8Trans1[] = {
  204896. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  204897. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  204898. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  204899. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  204900. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  204901. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  204902. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  204903. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  204904. };
  204905. #define READ_UTF8(zIn, zTerm, c) \
  204906. c = *(zIn++); \
  204907. if( c>=0xc0 ){ \
  204908. c = sqlite3Utf8Trans1[c-0xc0]; \
  204909. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  204910. c = (c<<6) + (0x3f & *(zIn++)); \
  204911. } \
  204912. if( c<0x80 \
  204913. || (c&0xFFFFF800)==0xD800 \
  204914. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  204915. }
  204916. #define WRITE_UTF8(zOut, c) { \
  204917. if( c<0x00080 ){ \
  204918. *zOut++ = (unsigned char)(c&0xFF); \
  204919. } \
  204920. else if( c<0x00800 ){ \
  204921. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  204922. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  204923. } \
  204924. else if( c<0x10000 ){ \
  204925. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  204926. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  204927. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  204928. }else{ \
  204929. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  204930. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  204931. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  204932. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  204933. } \
  204934. }
  204935. #endif /* ifndef SQLITE_AMALGAMATION */
  204936. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  204937. struct Unicode61Tokenizer {
  204938. unsigned char aTokenChar[128]; /* ASCII range token characters */
  204939. char *aFold; /* Buffer to fold text into */
  204940. int nFold; /* Size of aFold[] in bytes */
  204941. int eRemoveDiacritic; /* True if remove_diacritics=1 is set */
  204942. int nException;
  204943. int *aiException;
  204944. unsigned char aCategory[32]; /* True for token char categories */
  204945. };
  204946. /* Values for eRemoveDiacritic (must match internals of fts5_unicode2.c) */
  204947. #define FTS5_REMOVE_DIACRITICS_NONE 0
  204948. #define FTS5_REMOVE_DIACRITICS_SIMPLE 1
  204949. #define FTS5_REMOVE_DIACRITICS_COMPLEX 2
  204950. static int fts5UnicodeAddExceptions(
  204951. Unicode61Tokenizer *p, /* Tokenizer object */
  204952. const char *z, /* Characters to treat as exceptions */
  204953. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  204954. ){
  204955. int rc = SQLITE_OK;
  204956. int n = (int)strlen(z);
  204957. int *aNew;
  204958. if( n>0 ){
  204959. aNew = (int*)sqlite3_realloc64(p->aiException,
  204960. (n+p->nException)*sizeof(int));
  204961. if( aNew ){
  204962. int nNew = p->nException;
  204963. const unsigned char *zCsr = (const unsigned char*)z;
  204964. const unsigned char *zTerm = (const unsigned char*)&z[n];
  204965. while( zCsr<zTerm ){
  204966. u32 iCode;
  204967. int bToken;
  204968. READ_UTF8(zCsr, zTerm, iCode);
  204969. if( iCode<128 ){
  204970. p->aTokenChar[iCode] = (unsigned char)bTokenChars;
  204971. }else{
  204972. bToken = p->aCategory[sqlite3Fts5UnicodeCategory(iCode)];
  204973. assert( (bToken==0 || bToken==1) );
  204974. assert( (bTokenChars==0 || bTokenChars==1) );
  204975. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  204976. int i;
  204977. for(i=0; i<nNew; i++){
  204978. if( (u32)aNew[i]>iCode ) break;
  204979. }
  204980. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  204981. aNew[i] = iCode;
  204982. nNew++;
  204983. }
  204984. }
  204985. }
  204986. p->aiException = aNew;
  204987. p->nException = nNew;
  204988. }else{
  204989. rc = SQLITE_NOMEM;
  204990. }
  204991. }
  204992. return rc;
  204993. }
  204994. /*
  204995. ** Return true if the p->aiException[] array contains the value iCode.
  204996. */
  204997. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  204998. if( p->nException>0 ){
  204999. int *a = p->aiException;
  205000. int iLo = 0;
  205001. int iHi = p->nException-1;
  205002. while( iHi>=iLo ){
  205003. int iTest = (iHi + iLo) / 2;
  205004. if( iCode==a[iTest] ){
  205005. return 1;
  205006. }else if( iCode>a[iTest] ){
  205007. iLo = iTest+1;
  205008. }else{
  205009. iHi = iTest-1;
  205010. }
  205011. }
  205012. }
  205013. return 0;
  205014. }
  205015. /*
  205016. ** Delete a "unicode61" tokenizer.
  205017. */
  205018. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  205019. if( pTok ){
  205020. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  205021. sqlite3_free(p->aiException);
  205022. sqlite3_free(p->aFold);
  205023. sqlite3_free(p);
  205024. }
  205025. return;
  205026. }
  205027. static int unicodeSetCategories(Unicode61Tokenizer *p, const char *zCat){
  205028. const char *z = zCat;
  205029. while( *z ){
  205030. while( *z==' ' || *z=='\t' ) z++;
  205031. if( *z && sqlite3Fts5UnicodeCatParse(z, p->aCategory) ){
  205032. return SQLITE_ERROR;
  205033. }
  205034. while( *z!=' ' && *z!='\t' && *z!='\0' ) z++;
  205035. }
  205036. sqlite3Fts5UnicodeAscii(p->aCategory, p->aTokenChar);
  205037. return SQLITE_OK;
  205038. }
  205039. /*
  205040. ** Create a "unicode61" tokenizer.
  205041. */
  205042. static int fts5UnicodeCreate(
  205043. void *pUnused,
  205044. const char **azArg, int nArg,
  205045. Fts5Tokenizer **ppOut
  205046. ){
  205047. int rc = SQLITE_OK; /* Return code */
  205048. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  205049. UNUSED_PARAM(pUnused);
  205050. if( nArg%2 ){
  205051. rc = SQLITE_ERROR;
  205052. }else{
  205053. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  205054. if( p ){
  205055. const char *zCat = "L* N* Co";
  205056. int i;
  205057. memset(p, 0, sizeof(Unicode61Tokenizer));
  205058. p->eRemoveDiacritic = FTS5_REMOVE_DIACRITICS_SIMPLE;
  205059. p->nFold = 64;
  205060. p->aFold = sqlite3_malloc64(p->nFold * sizeof(char));
  205061. if( p->aFold==0 ){
  205062. rc = SQLITE_NOMEM;
  205063. }
  205064. /* Search for a "categories" argument */
  205065. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  205066. if( 0==sqlite3_stricmp(azArg[i], "categories") ){
  205067. zCat = azArg[i+1];
  205068. }
  205069. }
  205070. if( rc==SQLITE_OK ){
  205071. rc = unicodeSetCategories(p, zCat);
  205072. }
  205073. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  205074. const char *zArg = azArg[i+1];
  205075. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  205076. if( (zArg[0]!='0' && zArg[0]!='1' && zArg[0]!='2') || zArg[1] ){
  205077. rc = SQLITE_ERROR;
  205078. }else{
  205079. p->eRemoveDiacritic = (zArg[0] - '0');
  205080. assert( p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_NONE
  205081. || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_SIMPLE
  205082. || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_COMPLEX
  205083. );
  205084. }
  205085. }else
  205086. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  205087. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  205088. }else
  205089. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  205090. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  205091. }else
  205092. if( 0==sqlite3_stricmp(azArg[i], "categories") ){
  205093. /* no-op */
  205094. }else{
  205095. rc = SQLITE_ERROR;
  205096. }
  205097. }
  205098. }else{
  205099. rc = SQLITE_NOMEM;
  205100. }
  205101. if( rc!=SQLITE_OK ){
  205102. fts5UnicodeDelete((Fts5Tokenizer*)p);
  205103. p = 0;
  205104. }
  205105. *ppOut = (Fts5Tokenizer*)p;
  205106. }
  205107. return rc;
  205108. }
  205109. /*
  205110. ** Return true if, for the purposes of tokenizing with the tokenizer
  205111. ** passed as the first argument, codepoint iCode is considered a token
  205112. ** character (not a separator).
  205113. */
  205114. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  205115. return (
  205116. p->aCategory[sqlite3Fts5UnicodeCategory((u32)iCode)]
  205117. ^ fts5UnicodeIsException(p, iCode)
  205118. );
  205119. }
  205120. static int fts5UnicodeTokenize(
  205121. Fts5Tokenizer *pTokenizer,
  205122. void *pCtx,
  205123. int iUnused,
  205124. const char *pText, int nText,
  205125. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  205126. ){
  205127. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  205128. int rc = SQLITE_OK;
  205129. unsigned char *a = p->aTokenChar;
  205130. unsigned char *zTerm = (unsigned char*)&pText[nText];
  205131. unsigned char *zCsr = (unsigned char *)pText;
  205132. /* Output buffer */
  205133. char *aFold = p->aFold;
  205134. int nFold = p->nFold;
  205135. const char *pEnd = &aFold[nFold-6];
  205136. UNUSED_PARAM(iUnused);
  205137. /* Each iteration of this loop gobbles up a contiguous run of separators,
  205138. ** then the next token. */
  205139. while( rc==SQLITE_OK ){
  205140. u32 iCode; /* non-ASCII codepoint read from input */
  205141. char *zOut = aFold;
  205142. int is;
  205143. int ie;
  205144. /* Skip any separator characters. */
  205145. while( 1 ){
  205146. if( zCsr>=zTerm ) goto tokenize_done;
  205147. if( *zCsr & 0x80 ) {
  205148. /* A character outside of the ascii range. Skip past it if it is
  205149. ** a separator character. Or break out of the loop if it is not. */
  205150. is = zCsr - (unsigned char*)pText;
  205151. READ_UTF8(zCsr, zTerm, iCode);
  205152. if( fts5UnicodeIsAlnum(p, iCode) ){
  205153. goto non_ascii_tokenchar;
  205154. }
  205155. }else{
  205156. if( a[*zCsr] ){
  205157. is = zCsr - (unsigned char*)pText;
  205158. goto ascii_tokenchar;
  205159. }
  205160. zCsr++;
  205161. }
  205162. }
  205163. /* Run through the tokenchars. Fold them into the output buffer along
  205164. ** the way. */
  205165. while( zCsr<zTerm ){
  205166. /* Grow the output buffer so that there is sufficient space to fit the
  205167. ** largest possible utf-8 character. */
  205168. if( zOut>pEnd ){
  205169. aFold = sqlite3_malloc64((sqlite3_int64)nFold*2);
  205170. if( aFold==0 ){
  205171. rc = SQLITE_NOMEM;
  205172. goto tokenize_done;
  205173. }
  205174. zOut = &aFold[zOut - p->aFold];
  205175. memcpy(aFold, p->aFold, nFold);
  205176. sqlite3_free(p->aFold);
  205177. p->aFold = aFold;
  205178. p->nFold = nFold = nFold*2;
  205179. pEnd = &aFold[nFold-6];
  205180. }
  205181. if( *zCsr & 0x80 ){
  205182. /* An non-ascii-range character. Fold it into the output buffer if
  205183. ** it is a token character, or break out of the loop if it is not. */
  205184. READ_UTF8(zCsr, zTerm, iCode);
  205185. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  205186. non_ascii_tokenchar:
  205187. iCode = sqlite3Fts5UnicodeFold(iCode, p->eRemoveDiacritic);
  205188. if( iCode ) WRITE_UTF8(zOut, iCode);
  205189. }else{
  205190. break;
  205191. }
  205192. }else if( a[*zCsr]==0 ){
  205193. /* An ascii-range separator character. End of token. */
  205194. break;
  205195. }else{
  205196. ascii_tokenchar:
  205197. if( *zCsr>='A' && *zCsr<='Z' ){
  205198. *zOut++ = *zCsr + 32;
  205199. }else{
  205200. *zOut++ = *zCsr;
  205201. }
  205202. zCsr++;
  205203. }
  205204. ie = zCsr - (unsigned char*)pText;
  205205. }
  205206. /* Invoke the token callback */
  205207. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  205208. }
  205209. tokenize_done:
  205210. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  205211. return rc;
  205212. }
  205213. /**************************************************************************
  205214. ** Start of porter stemmer implementation.
  205215. */
  205216. /* Any tokens larger than this (in bytes) are passed through without
  205217. ** stemming. */
  205218. #define FTS5_PORTER_MAX_TOKEN 64
  205219. typedef struct PorterTokenizer PorterTokenizer;
  205220. struct PorterTokenizer {
  205221. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  205222. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  205223. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  205224. };
  205225. /*
  205226. ** Delete a "porter" tokenizer.
  205227. */
  205228. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  205229. if( pTok ){
  205230. PorterTokenizer *p = (PorterTokenizer*)pTok;
  205231. if( p->pTokenizer ){
  205232. p->tokenizer.xDelete(p->pTokenizer);
  205233. }
  205234. sqlite3_free(p);
  205235. }
  205236. }
  205237. /*
  205238. ** Create a "porter" tokenizer.
  205239. */
  205240. static int fts5PorterCreate(
  205241. void *pCtx,
  205242. const char **azArg, int nArg,
  205243. Fts5Tokenizer **ppOut
  205244. ){
  205245. fts5_api *pApi = (fts5_api*)pCtx;
  205246. int rc = SQLITE_OK;
  205247. PorterTokenizer *pRet;
  205248. void *pUserdata = 0;
  205249. const char *zBase = "unicode61";
  205250. if( nArg>0 ){
  205251. zBase = azArg[0];
  205252. }
  205253. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  205254. if( pRet ){
  205255. memset(pRet, 0, sizeof(PorterTokenizer));
  205256. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  205257. }else{
  205258. rc = SQLITE_NOMEM;
  205259. }
  205260. if( rc==SQLITE_OK ){
  205261. int nArg2 = (nArg>0 ? nArg-1 : 0);
  205262. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  205263. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  205264. }
  205265. if( rc!=SQLITE_OK ){
  205266. fts5PorterDelete((Fts5Tokenizer*)pRet);
  205267. pRet = 0;
  205268. }
  205269. *ppOut = (Fts5Tokenizer*)pRet;
  205270. return rc;
  205271. }
  205272. typedef struct PorterContext PorterContext;
  205273. struct PorterContext {
  205274. void *pCtx;
  205275. int (*xToken)(void*, int, const char*, int, int, int);
  205276. char *aBuf;
  205277. };
  205278. typedef struct PorterRule PorterRule;
  205279. struct PorterRule {
  205280. const char *zSuffix;
  205281. int nSuffix;
  205282. int (*xCond)(char *zStem, int nStem);
  205283. const char *zOutput;
  205284. int nOutput;
  205285. };
  205286. #if 0
  205287. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  205288. int ret = -1;
  205289. int nBuf = *pnBuf;
  205290. PorterRule *p;
  205291. for(p=aRule; p->zSuffix; p++){
  205292. assert( strlen(p->zSuffix)==p->nSuffix );
  205293. assert( strlen(p->zOutput)==p->nOutput );
  205294. if( nBuf<p->nSuffix ) continue;
  205295. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  205296. }
  205297. if( p->zSuffix ){
  205298. int nStem = nBuf - p->nSuffix;
  205299. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  205300. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  205301. *pnBuf = nStem + p->nOutput;
  205302. ret = p - aRule;
  205303. }
  205304. }
  205305. return ret;
  205306. }
  205307. #endif
  205308. static int fts5PorterIsVowel(char c, int bYIsVowel){
  205309. return (
  205310. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  205311. );
  205312. }
  205313. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  205314. int i;
  205315. int bCons = bPrevCons;
  205316. /* Scan for a vowel */
  205317. for(i=0; i<nStem; i++){
  205318. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  205319. }
  205320. /* Scan for a consonent */
  205321. for(i++; i<nStem; i++){
  205322. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  205323. }
  205324. return 0;
  205325. }
  205326. /* porter rule condition: (m > 0) */
  205327. static int fts5Porter_MGt0(char *zStem, int nStem){
  205328. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  205329. }
  205330. /* porter rule condition: (m > 1) */
  205331. static int fts5Porter_MGt1(char *zStem, int nStem){
  205332. int n;
  205333. n = fts5PorterGobbleVC(zStem, nStem, 0);
  205334. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  205335. return 1;
  205336. }
  205337. return 0;
  205338. }
  205339. /* porter rule condition: (m = 1) */
  205340. static int fts5Porter_MEq1(char *zStem, int nStem){
  205341. int n;
  205342. n = fts5PorterGobbleVC(zStem, nStem, 0);
  205343. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  205344. return 1;
  205345. }
  205346. return 0;
  205347. }
  205348. /* porter rule condition: (*o) */
  205349. static int fts5Porter_Ostar(char *zStem, int nStem){
  205350. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  205351. return 0;
  205352. }else{
  205353. int i;
  205354. int mask = 0;
  205355. int bCons = 0;
  205356. for(i=0; i<nStem; i++){
  205357. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  205358. assert( bCons==0 || bCons==1 );
  205359. mask = (mask << 1) + bCons;
  205360. }
  205361. return ((mask & 0x0007)==0x0005);
  205362. }
  205363. }
  205364. /* porter rule condition: (m > 1 and (*S or *T)) */
  205365. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  205366. assert( nStem>0 );
  205367. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  205368. && fts5Porter_MGt1(zStem, nStem);
  205369. }
  205370. /* porter rule condition: (*v*) */
  205371. static int fts5Porter_Vowel(char *zStem, int nStem){
  205372. int i;
  205373. for(i=0; i<nStem; i++){
  205374. if( fts5PorterIsVowel(zStem[i], i>0) ){
  205375. return 1;
  205376. }
  205377. }
  205378. return 0;
  205379. }
  205380. /**************************************************************************
  205381. ***************************************************************************
  205382. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  205383. */
  205384. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  205385. int ret = 0;
  205386. int nBuf = *pnBuf;
  205387. switch( aBuf[nBuf-2] ){
  205388. case 'a':
  205389. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  205390. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  205391. *pnBuf = nBuf - 2;
  205392. }
  205393. }
  205394. break;
  205395. case 'c':
  205396. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  205397. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  205398. *pnBuf = nBuf - 4;
  205399. }
  205400. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  205401. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  205402. *pnBuf = nBuf - 4;
  205403. }
  205404. }
  205405. break;
  205406. case 'e':
  205407. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  205408. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  205409. *pnBuf = nBuf - 2;
  205410. }
  205411. }
  205412. break;
  205413. case 'i':
  205414. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  205415. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  205416. *pnBuf = nBuf - 2;
  205417. }
  205418. }
  205419. break;
  205420. case 'l':
  205421. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  205422. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  205423. *pnBuf = nBuf - 4;
  205424. }
  205425. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  205426. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  205427. *pnBuf = nBuf - 4;
  205428. }
  205429. }
  205430. break;
  205431. case 'n':
  205432. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  205433. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  205434. *pnBuf = nBuf - 3;
  205435. }
  205436. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  205437. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  205438. *pnBuf = nBuf - 5;
  205439. }
  205440. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  205441. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  205442. *pnBuf = nBuf - 4;
  205443. }
  205444. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  205445. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  205446. *pnBuf = nBuf - 3;
  205447. }
  205448. }
  205449. break;
  205450. case 'o':
  205451. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  205452. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  205453. *pnBuf = nBuf - 3;
  205454. }
  205455. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  205456. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  205457. *pnBuf = nBuf - 2;
  205458. }
  205459. }
  205460. break;
  205461. case 's':
  205462. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  205463. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  205464. *pnBuf = nBuf - 3;
  205465. }
  205466. }
  205467. break;
  205468. case 't':
  205469. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  205470. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  205471. *pnBuf = nBuf - 3;
  205472. }
  205473. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  205474. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  205475. *pnBuf = nBuf - 3;
  205476. }
  205477. }
  205478. break;
  205479. case 'u':
  205480. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  205481. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  205482. *pnBuf = nBuf - 3;
  205483. }
  205484. }
  205485. break;
  205486. case 'v':
  205487. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  205488. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  205489. *pnBuf = nBuf - 3;
  205490. }
  205491. }
  205492. break;
  205493. case 'z':
  205494. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  205495. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  205496. *pnBuf = nBuf - 3;
  205497. }
  205498. }
  205499. break;
  205500. }
  205501. return ret;
  205502. }
  205503. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  205504. int ret = 0;
  205505. int nBuf = *pnBuf;
  205506. switch( aBuf[nBuf-2] ){
  205507. case 'a':
  205508. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  205509. memcpy(&aBuf[nBuf-2], "ate", 3);
  205510. *pnBuf = nBuf - 2 + 3;
  205511. ret = 1;
  205512. }
  205513. break;
  205514. case 'b':
  205515. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  205516. memcpy(&aBuf[nBuf-2], "ble", 3);
  205517. *pnBuf = nBuf - 2 + 3;
  205518. ret = 1;
  205519. }
  205520. break;
  205521. case 'i':
  205522. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  205523. memcpy(&aBuf[nBuf-2], "ize", 3);
  205524. *pnBuf = nBuf - 2 + 3;
  205525. ret = 1;
  205526. }
  205527. break;
  205528. }
  205529. return ret;
  205530. }
  205531. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  205532. int ret = 0;
  205533. int nBuf = *pnBuf;
  205534. switch( aBuf[nBuf-2] ){
  205535. case 'a':
  205536. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  205537. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  205538. memcpy(&aBuf[nBuf-7], "ate", 3);
  205539. *pnBuf = nBuf - 7 + 3;
  205540. }
  205541. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  205542. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  205543. memcpy(&aBuf[nBuf-6], "tion", 4);
  205544. *pnBuf = nBuf - 6 + 4;
  205545. }
  205546. }
  205547. break;
  205548. case 'c':
  205549. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  205550. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  205551. memcpy(&aBuf[nBuf-4], "ence", 4);
  205552. *pnBuf = nBuf - 4 + 4;
  205553. }
  205554. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  205555. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  205556. memcpy(&aBuf[nBuf-4], "ance", 4);
  205557. *pnBuf = nBuf - 4 + 4;
  205558. }
  205559. }
  205560. break;
  205561. case 'e':
  205562. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  205563. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  205564. memcpy(&aBuf[nBuf-4], "ize", 3);
  205565. *pnBuf = nBuf - 4 + 3;
  205566. }
  205567. }
  205568. break;
  205569. case 'g':
  205570. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  205571. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  205572. memcpy(&aBuf[nBuf-4], "log", 3);
  205573. *pnBuf = nBuf - 4 + 3;
  205574. }
  205575. }
  205576. break;
  205577. case 'l':
  205578. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  205579. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  205580. memcpy(&aBuf[nBuf-3], "ble", 3);
  205581. *pnBuf = nBuf - 3 + 3;
  205582. }
  205583. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  205584. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  205585. memcpy(&aBuf[nBuf-4], "al", 2);
  205586. *pnBuf = nBuf - 4 + 2;
  205587. }
  205588. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  205589. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  205590. memcpy(&aBuf[nBuf-5], "ent", 3);
  205591. *pnBuf = nBuf - 5 + 3;
  205592. }
  205593. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  205594. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  205595. memcpy(&aBuf[nBuf-3], "e", 1);
  205596. *pnBuf = nBuf - 3 + 1;
  205597. }
  205598. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  205599. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  205600. memcpy(&aBuf[nBuf-5], "ous", 3);
  205601. *pnBuf = nBuf - 5 + 3;
  205602. }
  205603. }
  205604. break;
  205605. case 'o':
  205606. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  205607. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  205608. memcpy(&aBuf[nBuf-7], "ize", 3);
  205609. *pnBuf = nBuf - 7 + 3;
  205610. }
  205611. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  205612. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  205613. memcpy(&aBuf[nBuf-5], "ate", 3);
  205614. *pnBuf = nBuf - 5 + 3;
  205615. }
  205616. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  205617. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  205618. memcpy(&aBuf[nBuf-4], "ate", 3);
  205619. *pnBuf = nBuf - 4 + 3;
  205620. }
  205621. }
  205622. break;
  205623. case 's':
  205624. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  205625. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  205626. memcpy(&aBuf[nBuf-5], "al", 2);
  205627. *pnBuf = nBuf - 5 + 2;
  205628. }
  205629. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  205630. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  205631. memcpy(&aBuf[nBuf-7], "ive", 3);
  205632. *pnBuf = nBuf - 7 + 3;
  205633. }
  205634. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  205635. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  205636. memcpy(&aBuf[nBuf-7], "ful", 3);
  205637. *pnBuf = nBuf - 7 + 3;
  205638. }
  205639. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  205640. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  205641. memcpy(&aBuf[nBuf-7], "ous", 3);
  205642. *pnBuf = nBuf - 7 + 3;
  205643. }
  205644. }
  205645. break;
  205646. case 't':
  205647. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  205648. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  205649. memcpy(&aBuf[nBuf-5], "al", 2);
  205650. *pnBuf = nBuf - 5 + 2;
  205651. }
  205652. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  205653. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  205654. memcpy(&aBuf[nBuf-5], "ive", 3);
  205655. *pnBuf = nBuf - 5 + 3;
  205656. }
  205657. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  205658. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  205659. memcpy(&aBuf[nBuf-6], "ble", 3);
  205660. *pnBuf = nBuf - 6 + 3;
  205661. }
  205662. }
  205663. break;
  205664. }
  205665. return ret;
  205666. }
  205667. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  205668. int ret = 0;
  205669. int nBuf = *pnBuf;
  205670. switch( aBuf[nBuf-2] ){
  205671. case 'a':
  205672. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  205673. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  205674. memcpy(&aBuf[nBuf-4], "ic", 2);
  205675. *pnBuf = nBuf - 4 + 2;
  205676. }
  205677. }
  205678. break;
  205679. case 's':
  205680. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  205681. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  205682. *pnBuf = nBuf - 4;
  205683. }
  205684. }
  205685. break;
  205686. case 't':
  205687. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  205688. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  205689. memcpy(&aBuf[nBuf-5], "ic", 2);
  205690. *pnBuf = nBuf - 5 + 2;
  205691. }
  205692. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  205693. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  205694. memcpy(&aBuf[nBuf-5], "ic", 2);
  205695. *pnBuf = nBuf - 5 + 2;
  205696. }
  205697. }
  205698. break;
  205699. case 'u':
  205700. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  205701. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  205702. *pnBuf = nBuf - 3;
  205703. }
  205704. }
  205705. break;
  205706. case 'v':
  205707. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  205708. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  205709. *pnBuf = nBuf - 5;
  205710. }
  205711. }
  205712. break;
  205713. case 'z':
  205714. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  205715. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  205716. memcpy(&aBuf[nBuf-5], "al", 2);
  205717. *pnBuf = nBuf - 5 + 2;
  205718. }
  205719. }
  205720. break;
  205721. }
  205722. return ret;
  205723. }
  205724. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  205725. int ret = 0;
  205726. int nBuf = *pnBuf;
  205727. switch( aBuf[nBuf-2] ){
  205728. case 'e':
  205729. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  205730. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  205731. memcpy(&aBuf[nBuf-3], "ee", 2);
  205732. *pnBuf = nBuf - 3 + 2;
  205733. }
  205734. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  205735. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  205736. *pnBuf = nBuf - 2;
  205737. ret = 1;
  205738. }
  205739. }
  205740. break;
  205741. case 'n':
  205742. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  205743. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  205744. *pnBuf = nBuf - 3;
  205745. ret = 1;
  205746. }
  205747. }
  205748. break;
  205749. }
  205750. return ret;
  205751. }
  205752. /*
  205753. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  205754. ***************************************************************************
  205755. **************************************************************************/
  205756. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  205757. int nBuf = *pnBuf;
  205758. if( aBuf[nBuf-1]=='s' ){
  205759. if( aBuf[nBuf-2]=='e' ){
  205760. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  205761. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  205762. ){
  205763. *pnBuf = nBuf-2;
  205764. }else{
  205765. *pnBuf = nBuf-1;
  205766. }
  205767. }
  205768. else if( aBuf[nBuf-2]!='s' ){
  205769. *pnBuf = nBuf-1;
  205770. }
  205771. }
  205772. }
  205773. static int fts5PorterCb(
  205774. void *pCtx,
  205775. int tflags,
  205776. const char *pToken,
  205777. int nToken,
  205778. int iStart,
  205779. int iEnd
  205780. ){
  205781. PorterContext *p = (PorterContext*)pCtx;
  205782. char *aBuf;
  205783. int nBuf;
  205784. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  205785. aBuf = p->aBuf;
  205786. nBuf = nToken;
  205787. memcpy(aBuf, pToken, nBuf);
  205788. /* Step 1. */
  205789. fts5PorterStep1A(aBuf, &nBuf);
  205790. if( fts5PorterStep1B(aBuf, &nBuf) ){
  205791. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  205792. char c = aBuf[nBuf-1];
  205793. if( fts5PorterIsVowel(c, 0)==0
  205794. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  205795. ){
  205796. nBuf--;
  205797. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  205798. aBuf[nBuf++] = 'e';
  205799. }
  205800. }
  205801. }
  205802. /* Step 1C. */
  205803. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  205804. aBuf[nBuf-1] = 'i';
  205805. }
  205806. /* Steps 2 through 4. */
  205807. fts5PorterStep2(aBuf, &nBuf);
  205808. fts5PorterStep3(aBuf, &nBuf);
  205809. fts5PorterStep4(aBuf, &nBuf);
  205810. /* Step 5a. */
  205811. assert( nBuf>0 );
  205812. if( aBuf[nBuf-1]=='e' ){
  205813. if( fts5Porter_MGt1(aBuf, nBuf-1)
  205814. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  205815. ){
  205816. nBuf--;
  205817. }
  205818. }
  205819. /* Step 5b. */
  205820. if( nBuf>1 && aBuf[nBuf-1]=='l'
  205821. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  205822. ){
  205823. nBuf--;
  205824. }
  205825. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  205826. pass_through:
  205827. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  205828. }
  205829. /*
  205830. ** Tokenize using the porter tokenizer.
  205831. */
  205832. static int fts5PorterTokenize(
  205833. Fts5Tokenizer *pTokenizer,
  205834. void *pCtx,
  205835. int flags,
  205836. const char *pText, int nText,
  205837. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  205838. ){
  205839. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  205840. PorterContext sCtx;
  205841. sCtx.xToken = xToken;
  205842. sCtx.pCtx = pCtx;
  205843. sCtx.aBuf = p->aBuf;
  205844. return p->tokenizer.xTokenize(
  205845. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  205846. );
  205847. }
  205848. /*
  205849. ** Register all built-in tokenizers with FTS5.
  205850. */
  205851. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  205852. struct BuiltinTokenizer {
  205853. const char *zName;
  205854. fts5_tokenizer x;
  205855. } aBuiltin[] = {
  205856. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  205857. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  205858. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  205859. };
  205860. int rc = SQLITE_OK; /* Return code */
  205861. int i; /* To iterate through builtin functions */
  205862. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  205863. rc = pApi->xCreateTokenizer(pApi,
  205864. aBuiltin[i].zName,
  205865. (void*)pApi,
  205866. &aBuiltin[i].x,
  205867. 0
  205868. );
  205869. }
  205870. return rc;
  205871. }
  205872. /*
  205873. ** 2012-05-25
  205874. **
  205875. ** The author disclaims copyright to this source code. In place of
  205876. ** a legal notice, here is a blessing:
  205877. **
  205878. ** May you do good and not evil.
  205879. ** May you find forgiveness for yourself and forgive others.
  205880. ** May you share freely, never taking more than you give.
  205881. **
  205882. ******************************************************************************
  205883. */
  205884. /*
  205885. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  205886. */
  205887. /* #include <assert.h> */
  205888. /*
  205889. ** If the argument is a codepoint corresponding to a lowercase letter
  205890. ** in the ASCII range with a diacritic added, return the codepoint
  205891. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  205892. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  205893. ** E"). The resuls of passing a codepoint that corresponds to an
  205894. ** uppercase letter are undefined.
  205895. */
  205896. static int fts5_remove_diacritic(int c, int bComplex){
  205897. unsigned short aDia[] = {
  205898. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  205899. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  205900. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  205901. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  205902. 3456, 3696, 3712, 3728, 3744, 3766, 3832, 3896,
  205903. 3912, 3928, 3944, 3968, 4008, 4040, 4056, 4106,
  205904. 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344,
  205905. 4408, 4424, 4442, 4472, 4488, 4504, 6148, 6198,
  205906. 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468,
  205907. 61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
  205908. 61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
  205909. 61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
  205910. 62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
  205911. 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
  205912. 62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
  205913. 63182, 63242, 63274, 63310, 63368, 63390,
  205914. };
  205915. #define HIBIT ((unsigned char)0x80)
  205916. unsigned char aChar[] = {
  205917. '\0', 'a', 'c', 'e', 'i', 'n',
  205918. 'o', 'u', 'y', 'y', 'a', 'c',
  205919. 'd', 'e', 'e', 'g', 'h', 'i',
  205920. 'j', 'k', 'l', 'n', 'o', 'r',
  205921. 's', 't', 'u', 'u', 'w', 'y',
  205922. 'z', 'o', 'u', 'a', 'i', 'o',
  205923. 'u', 'u'|HIBIT, 'a'|HIBIT, 'g', 'k', 'o',
  205924. 'o'|HIBIT, 'j', 'g', 'n', 'a'|HIBIT, 'a',
  205925. 'e', 'i', 'o', 'r', 'u', 's',
  205926. 't', 'h', 'a', 'e', 'o'|HIBIT, 'o',
  205927. 'o'|HIBIT, 'y', '\0', '\0', '\0', '\0',
  205928. '\0', '\0', '\0', '\0', 'a', 'b',
  205929. 'c'|HIBIT, 'd', 'd', 'e'|HIBIT, 'e', 'e'|HIBIT,
  205930. 'f', 'g', 'h', 'h', 'i', 'i'|HIBIT,
  205931. 'k', 'l', 'l'|HIBIT, 'l', 'm', 'n',
  205932. 'o'|HIBIT, 'p', 'r', 'r'|HIBIT, 'r', 's',
  205933. 's'|HIBIT, 't', 'u', 'u'|HIBIT, 'v', 'w',
  205934. 'w', 'x', 'y', 'z', 'h', 't',
  205935. 'w', 'y', 'a', 'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
  205936. 'e', 'e'|HIBIT, 'e'|HIBIT, 'i', 'o', 'o'|HIBIT,
  205937. 'o'|HIBIT, 'o'|HIBIT, 'u', 'u'|HIBIT, 'u'|HIBIT, 'y',
  205938. };
  205939. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  205940. int iRes = 0;
  205941. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  205942. int iLo = 0;
  205943. while( iHi>=iLo ){
  205944. int iTest = (iHi + iLo) / 2;
  205945. if( key >= aDia[iTest] ){
  205946. iRes = iTest;
  205947. iLo = iTest+1;
  205948. }else{
  205949. iHi = iTest-1;
  205950. }
  205951. }
  205952. assert( key>=aDia[iRes] );
  205953. if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
  205954. return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
  205955. }
  205956. /*
  205957. ** Return true if the argument interpreted as a unicode codepoint
  205958. ** is a diacritical modifier character.
  205959. */
  205960. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  205961. unsigned int mask0 = 0x08029FDF;
  205962. unsigned int mask1 = 0x000361F8;
  205963. if( c<768 || c>817 ) return 0;
  205964. return (c < 768+32) ?
  205965. (mask0 & ((unsigned int)1 << (c-768))) :
  205966. (mask1 & ((unsigned int)1 << (c-768-32)));
  205967. }
  205968. /*
  205969. ** Interpret the argument as a unicode codepoint. If the codepoint
  205970. ** is an upper case character that has a lower case equivalent,
  205971. ** return the codepoint corresponding to the lower case version.
  205972. ** Otherwise, return a copy of the argument.
  205973. **
  205974. ** The results are undefined if the value passed to this function
  205975. ** is less than zero.
  205976. */
  205977. static int sqlite3Fts5UnicodeFold(int c, int eRemoveDiacritic){
  205978. /* Each entry in the following array defines a rule for folding a range
  205979. ** of codepoints to lower case. The rule applies to a range of nRange
  205980. ** codepoints starting at codepoint iCode.
  205981. **
  205982. ** If the least significant bit in flags is clear, then the rule applies
  205983. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  205984. ** need to be folded). Or, if it is set, then the rule only applies to
  205985. ** every second codepoint in the range, starting with codepoint C.
  205986. **
  205987. ** The 7 most significant bits in flags are an index into the aiOff[]
  205988. ** array. If a specific codepoint C does require folding, then its lower
  205989. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  205990. **
  205991. ** The contents of this array are generated by parsing the CaseFolding.txt
  205992. ** file distributed as part of the "Unicode Character Database". See
  205993. ** http://www.unicode.org for details.
  205994. */
  205995. static const struct TableEntry {
  205996. unsigned short iCode;
  205997. unsigned char flags;
  205998. unsigned char nRange;
  205999. } aEntry[] = {
  206000. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  206001. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  206002. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  206003. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  206004. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  206005. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  206006. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  206007. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  206008. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  206009. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  206010. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  206011. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  206012. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  206013. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  206014. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  206015. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  206016. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  206017. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  206018. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  206019. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  206020. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  206021. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  206022. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  206023. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  206024. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  206025. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  206026. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  206027. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  206028. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  206029. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  206030. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  206031. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  206032. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  206033. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  206034. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  206035. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  206036. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  206037. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  206038. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  206039. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  206040. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  206041. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  206042. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  206043. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  206044. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  206045. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  206046. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  206047. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  206048. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  206049. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  206050. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  206051. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  206052. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  206053. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  206054. {65313, 14, 26},
  206055. };
  206056. static const unsigned short aiOff[] = {
  206057. 1, 2, 8, 15, 16, 26, 28, 32,
  206058. 37, 38, 40, 48, 63, 64, 69, 71,
  206059. 79, 80, 116, 202, 203, 205, 206, 207,
  206060. 209, 210, 211, 213, 214, 217, 218, 219,
  206061. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  206062. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  206063. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  206064. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  206065. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  206066. 65514, 65521, 65527, 65528, 65529,
  206067. };
  206068. int ret = c;
  206069. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  206070. if( c<128 ){
  206071. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  206072. }else if( c<65536 ){
  206073. const struct TableEntry *p;
  206074. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  206075. int iLo = 0;
  206076. int iRes = -1;
  206077. assert( c>aEntry[0].iCode );
  206078. while( iHi>=iLo ){
  206079. int iTest = (iHi + iLo) / 2;
  206080. int cmp = (c - aEntry[iTest].iCode);
  206081. if( cmp>=0 ){
  206082. iRes = iTest;
  206083. iLo = iTest+1;
  206084. }else{
  206085. iHi = iTest-1;
  206086. }
  206087. }
  206088. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  206089. p = &aEntry[iRes];
  206090. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  206091. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  206092. assert( ret>0 );
  206093. }
  206094. if( eRemoveDiacritic ){
  206095. ret = fts5_remove_diacritic(ret, eRemoveDiacritic==2);
  206096. }
  206097. }
  206098. else if( c>=66560 && c<66600 ){
  206099. ret = c + 40;
  206100. }
  206101. return ret;
  206102. }
  206103. static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
  206104. aArray[0] = 1;
  206105. switch( zCat[0] ){
  206106. case 'C':
  206107. switch( zCat[1] ){
  206108. case 'c': aArray[1] = 1; break;
  206109. case 'f': aArray[2] = 1; break;
  206110. case 'n': aArray[3] = 1; break;
  206111. case 's': aArray[4] = 1; break;
  206112. case 'o': aArray[31] = 1; break;
  206113. case '*':
  206114. aArray[1] = 1;
  206115. aArray[2] = 1;
  206116. aArray[3] = 1;
  206117. aArray[4] = 1;
  206118. aArray[31] = 1;
  206119. break;
  206120. default: return 1; }
  206121. break;
  206122. case 'L':
  206123. switch( zCat[1] ){
  206124. case 'l': aArray[5] = 1; break;
  206125. case 'm': aArray[6] = 1; break;
  206126. case 'o': aArray[7] = 1; break;
  206127. case 't': aArray[8] = 1; break;
  206128. case 'u': aArray[9] = 1; break;
  206129. case 'C': aArray[30] = 1; break;
  206130. case '*':
  206131. aArray[5] = 1;
  206132. aArray[6] = 1;
  206133. aArray[7] = 1;
  206134. aArray[8] = 1;
  206135. aArray[9] = 1;
  206136. aArray[30] = 1;
  206137. break;
  206138. default: return 1; }
  206139. break;
  206140. case 'M':
  206141. switch( zCat[1] ){
  206142. case 'c': aArray[10] = 1; break;
  206143. case 'e': aArray[11] = 1; break;
  206144. case 'n': aArray[12] = 1; break;
  206145. case '*':
  206146. aArray[10] = 1;
  206147. aArray[11] = 1;
  206148. aArray[12] = 1;
  206149. break;
  206150. default: return 1; }
  206151. break;
  206152. case 'N':
  206153. switch( zCat[1] ){
  206154. case 'd': aArray[13] = 1; break;
  206155. case 'l': aArray[14] = 1; break;
  206156. case 'o': aArray[15] = 1; break;
  206157. case '*':
  206158. aArray[13] = 1;
  206159. aArray[14] = 1;
  206160. aArray[15] = 1;
  206161. break;
  206162. default: return 1; }
  206163. break;
  206164. case 'P':
  206165. switch( zCat[1] ){
  206166. case 'c': aArray[16] = 1; break;
  206167. case 'd': aArray[17] = 1; break;
  206168. case 'e': aArray[18] = 1; break;
  206169. case 'f': aArray[19] = 1; break;
  206170. case 'i': aArray[20] = 1; break;
  206171. case 'o': aArray[21] = 1; break;
  206172. case 's': aArray[22] = 1; break;
  206173. case '*':
  206174. aArray[16] = 1;
  206175. aArray[17] = 1;
  206176. aArray[18] = 1;
  206177. aArray[19] = 1;
  206178. aArray[20] = 1;
  206179. aArray[21] = 1;
  206180. aArray[22] = 1;
  206181. break;
  206182. default: return 1; }
  206183. break;
  206184. case 'S':
  206185. switch( zCat[1] ){
  206186. case 'c': aArray[23] = 1; break;
  206187. case 'k': aArray[24] = 1; break;
  206188. case 'm': aArray[25] = 1; break;
  206189. case 'o': aArray[26] = 1; break;
  206190. case '*':
  206191. aArray[23] = 1;
  206192. aArray[24] = 1;
  206193. aArray[25] = 1;
  206194. aArray[26] = 1;
  206195. break;
  206196. default: return 1; }
  206197. break;
  206198. case 'Z':
  206199. switch( zCat[1] ){
  206200. case 'l': aArray[27] = 1; break;
  206201. case 'p': aArray[28] = 1; break;
  206202. case 's': aArray[29] = 1; break;
  206203. case '*':
  206204. aArray[27] = 1;
  206205. aArray[28] = 1;
  206206. aArray[29] = 1;
  206207. break;
  206208. default: return 1; }
  206209. break;
  206210. }
  206211. return 0;
  206212. }
  206213. static u16 aFts5UnicodeBlock[] = {
  206214. 0, 1471, 1753, 1760, 1760, 1760, 1760, 1760, 1760, 1760,
  206215. 1760, 1760, 1760, 1760, 1760, 1763, 1765,
  206216. };
  206217. static u16 aFts5UnicodeMap[] = {
  206218. 0, 32, 33, 36, 37, 40, 41, 42, 43, 44,
  206219. 45, 46, 48, 58, 60, 63, 65, 91, 92, 93,
  206220. 94, 95, 96, 97, 123, 124, 125, 126, 127, 160,
  206221. 161, 162, 166, 167, 168, 169, 170, 171, 172, 173,
  206222. 174, 175, 176, 177, 178, 180, 181, 182, 184, 185,
  206223. 186, 187, 188, 191, 192, 215, 216, 223, 247, 248,
  206224. 256, 312, 313, 329, 330, 377, 383, 385, 387, 388,
  206225. 391, 394, 396, 398, 402, 403, 405, 406, 409, 412,
  206226. 414, 415, 417, 418, 423, 427, 428, 431, 434, 436,
  206227. 437, 440, 442, 443, 444, 446, 448, 452, 453, 454,
  206228. 455, 456, 457, 458, 459, 460, 461, 477, 478, 496,
  206229. 497, 498, 499, 500, 503, 505, 506, 564, 570, 572,
  206230. 573, 575, 577, 580, 583, 584, 592, 660, 661, 688,
  206231. 706, 710, 722, 736, 741, 748, 749, 750, 751, 768,
  206232. 880, 884, 885, 886, 890, 891, 894, 900, 902, 903,
  206233. 904, 908, 910, 912, 913, 931, 940, 975, 977, 978,
  206234. 981, 984, 1008, 1012, 1014, 1015, 1018, 1020, 1021, 1072,
  206235. 1120, 1154, 1155, 1160, 1162, 1217, 1231, 1232, 1329, 1369,
  206236. 1370, 1377, 1417, 1418, 1423, 1425, 1470, 1471, 1472, 1473,
  206237. 1475, 1476, 1478, 1479, 1488, 1520, 1523, 1536, 1542, 1545,
  206238. 1547, 1548, 1550, 1552, 1563, 1566, 1568, 1600, 1601, 1611,
  206239. 1632, 1642, 1646, 1648, 1649, 1748, 1749, 1750, 1757, 1758,
  206240. 1759, 1765, 1767, 1769, 1770, 1774, 1776, 1786, 1789, 1791,
  206241. 1792, 1807, 1808, 1809, 1810, 1840, 1869, 1958, 1969, 1984,
  206242. 1994, 2027, 2036, 2038, 2039, 2042, 2048, 2070, 2074, 2075,
  206243. 2084, 2085, 2088, 2089, 2096, 2112, 2137, 2142, 2208, 2210,
  206244. 2276, 2304, 2307, 2308, 2362, 2363, 2364, 2365, 2366, 2369,
  206245. 2377, 2381, 2382, 2384, 2385, 2392, 2402, 2404, 2406, 2416,
  206246. 2417, 2418, 2425, 2433, 2434, 2437, 2447, 2451, 2474, 2482,
  206247. 2486, 2492, 2493, 2494, 2497, 2503, 2507, 2509, 2510, 2519,
  206248. 2524, 2527, 2530, 2534, 2544, 2546, 2548, 2554, 2555, 2561,
  206249. 2563, 2565, 2575, 2579, 2602, 2610, 2613, 2616, 2620, 2622,
  206250. 2625, 2631, 2635, 2641, 2649, 2654, 2662, 2672, 2674, 2677,
  206251. 2689, 2691, 2693, 2703, 2707, 2730, 2738, 2741, 2748, 2749,
  206252. 2750, 2753, 2759, 2761, 2763, 2765, 2768, 2784, 2786, 2790,
  206253. 2800, 2801, 2817, 2818, 2821, 2831, 2835, 2858, 2866, 2869,
  206254. 2876, 2877, 2878, 2879, 2880, 2881, 2887, 2891, 2893, 2902,
  206255. 2903, 2908, 2911, 2914, 2918, 2928, 2929, 2930, 2946, 2947,
  206256. 2949, 2958, 2962, 2969, 2972, 2974, 2979, 2984, 2990, 3006,
  206257. 3008, 3009, 3014, 3018, 3021, 3024, 3031, 3046, 3056, 3059,
  206258. 3065, 3066, 3073, 3077, 3086, 3090, 3114, 3125, 3133, 3134,
  206259. 3137, 3142, 3146, 3157, 3160, 3168, 3170, 3174, 3192, 3199,
  206260. 3202, 3205, 3214, 3218, 3242, 3253, 3260, 3261, 3262, 3263,
  206261. 3264, 3270, 3271, 3274, 3276, 3285, 3294, 3296, 3298, 3302,
  206262. 3313, 3330, 3333, 3342, 3346, 3389, 3390, 3393, 3398, 3402,
  206263. 3405, 3406, 3415, 3424, 3426, 3430, 3440, 3449, 3450, 3458,
  206264. 3461, 3482, 3507, 3517, 3520, 3530, 3535, 3538, 3542, 3544,
  206265. 3570, 3572, 3585, 3633, 3634, 3636, 3647, 3648, 3654, 3655,
  206266. 3663, 3664, 3674, 3713, 3716, 3719, 3722, 3725, 3732, 3737,
  206267. 3745, 3749, 3751, 3754, 3757, 3761, 3762, 3764, 3771, 3773,
  206268. 3776, 3782, 3784, 3792, 3804, 3840, 3841, 3844, 3859, 3860,
  206269. 3861, 3864, 3866, 3872, 3882, 3892, 3893, 3894, 3895, 3896,
  206270. 3897, 3898, 3899, 3900, 3901, 3902, 3904, 3913, 3953, 3967,
  206271. 3968, 3973, 3974, 3976, 3981, 3993, 4030, 4038, 4039, 4046,
  206272. 4048, 4053, 4057, 4096, 4139, 4141, 4145, 4146, 4152, 4153,
  206273. 4155, 4157, 4159, 4160, 4170, 4176, 4182, 4184, 4186, 4190,
  206274. 4193, 4194, 4197, 4199, 4206, 4209, 4213, 4226, 4227, 4229,
  206275. 4231, 4237, 4238, 4239, 4240, 4250, 4253, 4254, 4256, 4295,
  206276. 4301, 4304, 4347, 4348, 4349, 4682, 4688, 4696, 4698, 4704,
  206277. 4746, 4752, 4786, 4792, 4800, 4802, 4808, 4824, 4882, 4888,
  206278. 4957, 4960, 4969, 4992, 5008, 5024, 5120, 5121, 5741, 5743,
  206279. 5760, 5761, 5787, 5788, 5792, 5867, 5870, 5888, 5902, 5906,
  206280. 5920, 5938, 5941, 5952, 5970, 5984, 5998, 6002, 6016, 6068,
  206281. 6070, 6071, 6078, 6086, 6087, 6089, 6100, 6103, 6104, 6107,
  206282. 6108, 6109, 6112, 6128, 6144, 6150, 6151, 6155, 6158, 6160,
  206283. 6176, 6211, 6212, 6272, 6313, 6314, 6320, 6400, 6432, 6435,
  206284. 6439, 6441, 6448, 6450, 6451, 6457, 6464, 6468, 6470, 6480,
  206285. 6512, 6528, 6576, 6593, 6600, 6608, 6618, 6622, 6656, 6679,
  206286. 6681, 6686, 6688, 6741, 6742, 6743, 6744, 6752, 6753, 6754,
  206287. 6755, 6757, 6765, 6771, 6783, 6784, 6800, 6816, 6823, 6824,
  206288. 6912, 6916, 6917, 6964, 6965, 6966, 6971, 6972, 6973, 6978,
  206289. 6979, 6981, 6992, 7002, 7009, 7019, 7028, 7040, 7042, 7043,
  206290. 7073, 7074, 7078, 7080, 7082, 7083, 7084, 7086, 7088, 7098,
  206291. 7142, 7143, 7144, 7146, 7149, 7150, 7151, 7154, 7164, 7168,
  206292. 7204, 7212, 7220, 7222, 7227, 7232, 7245, 7248, 7258, 7288,
  206293. 7294, 7360, 7376, 7379, 7380, 7393, 7394, 7401, 7405, 7406,
  206294. 7410, 7412, 7413, 7424, 7468, 7531, 7544, 7545, 7579, 7616,
  206295. 7676, 7680, 7830, 7838, 7936, 7944, 7952, 7960, 7968, 7976,
  206296. 7984, 7992, 8000, 8008, 8016, 8025, 8027, 8029, 8031, 8033,
  206297. 8040, 8048, 8064, 8072, 8080, 8088, 8096, 8104, 8112, 8118,
  206298. 8120, 8124, 8125, 8126, 8127, 8130, 8134, 8136, 8140, 8141,
  206299. 8144, 8150, 8152, 8157, 8160, 8168, 8173, 8178, 8182, 8184,
  206300. 8188, 8189, 8192, 8203, 8208, 8214, 8216, 8217, 8218, 8219,
  206301. 8221, 8222, 8223, 8224, 8232, 8233, 8234, 8239, 8240, 8249,
  206302. 8250, 8251, 8255, 8257, 8260, 8261, 8262, 8263, 8274, 8275,
  206303. 8276, 8277, 8287, 8288, 8298, 8304, 8305, 8308, 8314, 8317,
  206304. 8318, 8319, 8320, 8330, 8333, 8334, 8336, 8352, 8400, 8413,
  206305. 8417, 8418, 8421, 8448, 8450, 8451, 8455, 8456, 8458, 8459,
  206306. 8462, 8464, 8467, 8468, 8469, 8470, 8472, 8473, 8478, 8484,
  206307. 8485, 8486, 8487, 8488, 8489, 8490, 8494, 8495, 8496, 8500,
  206308. 8501, 8505, 8506, 8508, 8510, 8512, 8517, 8519, 8522, 8523,
  206309. 8524, 8526, 8527, 8528, 8544, 8579, 8581, 8585, 8592, 8597,
  206310. 8602, 8604, 8608, 8609, 8611, 8612, 8614, 8615, 8622, 8623,
  206311. 8654, 8656, 8658, 8659, 8660, 8661, 8692, 8960, 8968, 8972,
  206312. 8992, 8994, 9001, 9002, 9003, 9084, 9085, 9115, 9140, 9180,
  206313. 9186, 9216, 9280, 9312, 9372, 9450, 9472, 9655, 9656, 9665,
  206314. 9666, 9720, 9728, 9839, 9840, 9985, 10088, 10089, 10090, 10091,
  206315. 10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101,
  206316. 10102, 10132, 10176, 10181, 10182, 10183, 10214, 10215, 10216, 10217,
  206317. 10218, 10219, 10220, 10221, 10222, 10223, 10224, 10240, 10496, 10627,
  206318. 10628, 10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636, 10637,
  206319. 10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647,
  206320. 10648, 10649, 10712, 10713, 10714, 10715, 10716, 10748, 10749, 10750,
  206321. 11008, 11056, 11077, 11079, 11088, 11264, 11312, 11360, 11363, 11365,
  206322. 11367, 11374, 11377, 11378, 11380, 11381, 11383, 11388, 11390, 11393,
  206323. 11394, 11492, 11493, 11499, 11503, 11506, 11513, 11517, 11518, 11520,
  206324. 11559, 11565, 11568, 11631, 11632, 11647, 11648, 11680, 11688, 11696,
  206325. 11704, 11712, 11720, 11728, 11736, 11744, 11776, 11778, 11779, 11780,
  206326. 11781, 11782, 11785, 11786, 11787, 11788, 11789, 11790, 11799, 11800,
  206327. 11802, 11803, 11804, 11805, 11806, 11808, 11809, 11810, 11811, 11812,
  206328. 11813, 11814, 11815, 11816, 11817, 11818, 11823, 11824, 11834, 11904,
  206329. 11931, 12032, 12272, 12288, 12289, 12292, 12293, 12294, 12295, 12296,
  206330. 12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 12306,
  206331. 12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317,
  206332. 12318, 12320, 12321, 12330, 12334, 12336, 12337, 12342, 12344, 12347,
  206333. 12348, 12349, 12350, 12353, 12441, 12443, 12445, 12447, 12448, 12449,
  206334. 12539, 12540, 12543, 12549, 12593, 12688, 12690, 12694, 12704, 12736,
  206335. 12784, 12800, 12832, 12842, 12872, 12880, 12881, 12896, 12928, 12938,
  206336. 12977, 12992, 13056, 13312, 19893, 19904, 19968, 40908, 40960, 40981,
  206337. 40982, 42128, 42192, 42232, 42238, 42240, 42508, 42509, 42512, 42528,
  206338. 42538, 42560, 42606, 42607, 42608, 42611, 42612, 42622, 42623, 42624,
  206339. 42655, 42656, 42726, 42736, 42738, 42752, 42775, 42784, 42786, 42800,
  206340. 42802, 42864, 42865, 42873, 42878, 42888, 42889, 42891, 42896, 42912,
  206341. 43000, 43002, 43003, 43010, 43011, 43014, 43015, 43019, 43020, 43043,
  206342. 43045, 43047, 43048, 43056, 43062, 43064, 43065, 43072, 43124, 43136,
  206343. 43138, 43188, 43204, 43214, 43216, 43232, 43250, 43256, 43259, 43264,
  206344. 43274, 43302, 43310, 43312, 43335, 43346, 43359, 43360, 43392, 43395,
  206345. 43396, 43443, 43444, 43446, 43450, 43452, 43453, 43457, 43471, 43472,
  206346. 43486, 43520, 43561, 43567, 43569, 43571, 43573, 43584, 43587, 43588,
  206347. 43596, 43597, 43600, 43612, 43616, 43632, 43633, 43639, 43642, 43643,
  206348. 43648, 43696, 43697, 43698, 43701, 43703, 43705, 43710, 43712, 43713,
  206349. 43714, 43739, 43741, 43742, 43744, 43755, 43756, 43758, 43760, 43762,
  206350. 43763, 43765, 43766, 43777, 43785, 43793, 43808, 43816, 43968, 44003,
  206351. 44005, 44006, 44008, 44009, 44011, 44012, 44013, 44016, 44032, 55203,
  206352. 55216, 55243, 55296, 56191, 56319, 57343, 57344, 63743, 63744, 64112,
  206353. 64256, 64275, 64285, 64286, 64287, 64297, 64298, 64312, 64318, 64320,
  206354. 64323, 64326, 64434, 64467, 64830, 64831, 64848, 64914, 65008, 65020,
  206355. 65021, 65024, 65040, 65047, 65048, 65049, 65056, 65072, 65073, 65075,
  206356. 65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084, 65085, 65086,
  206357. 65087, 65088, 65089, 65090, 65091, 65092, 65093, 65095, 65096, 65097,
  206358. 65101, 65104, 65108, 65112, 65113, 65114, 65115, 65116, 65117, 65118,
  206359. 65119, 65122, 65123, 65124, 65128, 65129, 65130, 65136, 65142, 65279,
  206360. 65281, 65284, 65285, 65288, 65289, 65290, 65291, 65292, 65293, 65294,
  206361. 65296, 65306, 65308, 65311, 65313, 65339, 65340, 65341, 65342, 65343,
  206362. 65344, 65345, 65371, 65372, 65373, 65374, 65375, 65376, 65377, 65378,
  206363. 65379, 65380, 65382, 65392, 65393, 65438, 65440, 65474, 65482, 65490,
  206364. 65498, 65504, 65506, 65507, 65508, 65509, 65512, 65513, 65517, 65529,
  206365. 65532, 0, 13, 40, 60, 63, 80, 128, 256, 263,
  206366. 311, 320, 373, 377, 394, 400, 464, 509, 640, 672,
  206367. 768, 800, 816, 833, 834, 842, 896, 927, 928, 968,
  206368. 976, 977, 1024, 1064, 1104, 1184, 2048, 2056, 2058, 2103,
  206369. 2108, 2111, 2135, 2136, 2304, 2326, 2335, 2336, 2367, 2432,
  206370. 2494, 2560, 2561, 2565, 2572, 2576, 2581, 2585, 2616, 2623,
  206371. 2624, 2640, 2656, 2685, 2687, 2816, 2873, 2880, 2904, 2912,
  206372. 2936, 3072, 3680, 4096, 4097, 4098, 4099, 4152, 4167, 4178,
  206373. 4198, 4224, 4226, 4227, 4272, 4275, 4279, 4281, 4283, 4285,
  206374. 4286, 4304, 4336, 4352, 4355, 4391, 4396, 4397, 4406, 4416,
  206375. 4480, 4482, 4483, 4531, 4534, 4543, 4545, 4549, 4560, 5760,
  206376. 5803, 5804, 5805, 5806, 5808, 5814, 5815, 5824, 8192, 9216,
  206377. 9328, 12288, 26624, 28416, 28496, 28497, 28559, 28563, 45056, 53248,
  206378. 53504, 53545, 53605, 53607, 53610, 53613, 53619, 53627, 53635, 53637,
  206379. 53644, 53674, 53678, 53760, 53826, 53829, 54016, 54112, 54272, 54298,
  206380. 54324, 54350, 54358, 54376, 54402, 54428, 54430, 54434, 54437, 54441,
  206381. 54446, 54454, 54459, 54461, 54469, 54480, 54506, 54532, 54535, 54541,
  206382. 54550, 54558, 54584, 54587, 54592, 54598, 54602, 54610, 54636, 54662,
  206383. 54688, 54714, 54740, 54766, 54792, 54818, 54844, 54870, 54896, 54922,
  206384. 54952, 54977, 54978, 55003, 55004, 55010, 55035, 55036, 55061, 55062,
  206385. 55068, 55093, 55094, 55119, 55120, 55126, 55151, 55152, 55177, 55178,
  206386. 55184, 55209, 55210, 55235, 55236, 55242, 55246, 60928, 60933, 60961,
  206387. 60964, 60967, 60969, 60980, 60985, 60987, 60994, 60999, 61001, 61003,
  206388. 61005, 61009, 61012, 61015, 61017, 61019, 61021, 61023, 61025, 61028,
  206389. 61031, 61036, 61044, 61049, 61054, 61056, 61067, 61089, 61093, 61099,
  206390. 61168, 61440, 61488, 61600, 61617, 61633, 61649, 61696, 61712, 61744,
  206391. 61808, 61926, 61968, 62016, 62032, 62208, 62256, 62263, 62336, 62368,
  206392. 62406, 62432, 62464, 62528, 62530, 62713, 62720, 62784, 62800, 62971,
  206393. 63045, 63104, 63232, 0, 42710, 42752, 46900, 46912, 47133, 63488,
  206394. 1, 32, 256, 0, 65533,
  206395. };
  206396. static u16 aFts5UnicodeData[] = {
  206397. 1025, 61, 117, 55, 117, 54, 50, 53, 57, 53,
  206398. 49, 85, 333, 85, 121, 85, 841, 54, 53, 50,
  206399. 56, 48, 56, 837, 54, 57, 50, 57, 1057, 61,
  206400. 53, 151, 58, 53, 56, 58, 39, 52, 57, 34,
  206401. 58, 56, 58, 57, 79, 56, 37, 85, 56, 47,
  206402. 39, 51, 111, 53, 745, 57, 233, 773, 57, 261,
  206403. 1822, 37, 542, 37, 1534, 222, 69, 73, 37, 126,
  206404. 126, 73, 69, 137, 37, 73, 37, 105, 101, 73,
  206405. 37, 73, 37, 190, 158, 37, 126, 126, 73, 37,
  206406. 126, 94, 37, 39, 94, 69, 135, 41, 40, 37,
  206407. 41, 40, 37, 41, 40, 37, 542, 37, 606, 37,
  206408. 41, 40, 37, 126, 73, 37, 1886, 197, 73, 37,
  206409. 73, 69, 126, 105, 37, 286, 2181, 39, 869, 582,
  206410. 152, 390, 472, 166, 248, 38, 56, 38, 568, 3596,
  206411. 158, 38, 56, 94, 38, 101, 53, 88, 41, 53,
  206412. 105, 41, 73, 37, 553, 297, 1125, 94, 37, 105,
  206413. 101, 798, 133, 94, 57, 126, 94, 37, 1641, 1541,
  206414. 1118, 58, 172, 75, 1790, 478, 37, 2846, 1225, 38,
  206415. 213, 1253, 53, 49, 55, 1452, 49, 44, 53, 76,
  206416. 53, 76, 53, 44, 871, 103, 85, 162, 121, 85,
  206417. 55, 85, 90, 364, 53, 85, 1031, 38, 327, 684,
  206418. 333, 149, 71, 44, 3175, 53, 39, 236, 34, 58,
  206419. 204, 70, 76, 58, 140, 71, 333, 103, 90, 39,
  206420. 469, 34, 39, 44, 967, 876, 2855, 364, 39, 333,
  206421. 1063, 300, 70, 58, 117, 38, 711, 140, 38, 300,
  206422. 38, 108, 38, 172, 501, 807, 108, 53, 39, 359,
  206423. 876, 108, 42, 1735, 44, 42, 44, 39, 106, 268,
  206424. 138, 44, 74, 39, 236, 327, 76, 85, 333, 53,
  206425. 38, 199, 231, 44, 74, 263, 71, 711, 231, 39,
  206426. 135, 44, 39, 106, 140, 74, 74, 44, 39, 42,
  206427. 71, 103, 76, 333, 71, 87, 207, 58, 55, 76,
  206428. 42, 199, 71, 711, 231, 71, 71, 71, 44, 106,
  206429. 76, 76, 108, 44, 135, 39, 333, 76, 103, 44,
  206430. 76, 42, 295, 103, 711, 231, 71, 167, 44, 39,
  206431. 106, 172, 76, 42, 74, 44, 39, 71, 76, 333,
  206432. 53, 55, 44, 74, 263, 71, 711, 231, 71, 167,
  206433. 44, 39, 42, 44, 42, 140, 74, 74, 44, 44,
  206434. 42, 71, 103, 76, 333, 58, 39, 207, 44, 39,
  206435. 199, 103, 135, 71, 39, 71, 71, 103, 391, 74,
  206436. 44, 74, 106, 106, 44, 39, 42, 333, 111, 218,
  206437. 55, 58, 106, 263, 103, 743, 327, 167, 39, 108,
  206438. 138, 108, 140, 76, 71, 71, 76, 333, 239, 58,
  206439. 74, 263, 103, 743, 327, 167, 44, 39, 42, 44,
  206440. 170, 44, 74, 74, 76, 74, 39, 71, 76, 333,
  206441. 71, 74, 263, 103, 1319, 39, 106, 140, 106, 106,
  206442. 44, 39, 42, 71, 76, 333, 207, 58, 199, 74,
  206443. 583, 775, 295, 39, 231, 44, 106, 108, 44, 266,
  206444. 74, 53, 1543, 44, 71, 236, 55, 199, 38, 268,
  206445. 53, 333, 85, 71, 39, 71, 39, 39, 135, 231,
  206446. 103, 39, 39, 71, 135, 44, 71, 204, 76, 39,
  206447. 167, 38, 204, 333, 135, 39, 122, 501, 58, 53,
  206448. 122, 76, 218, 333, 335, 58, 44, 58, 44, 58,
  206449. 44, 54, 50, 54, 50, 74, 263, 1159, 460, 42,
  206450. 172, 53, 76, 167, 364, 1164, 282, 44, 218, 90,
  206451. 181, 154, 85, 1383, 74, 140, 42, 204, 42, 76,
  206452. 74, 76, 39, 333, 213, 199, 74, 76, 135, 108,
  206453. 39, 106, 71, 234, 103, 140, 423, 44, 74, 76,
  206454. 202, 44, 39, 42, 333, 106, 44, 90, 1225, 41,
  206455. 41, 1383, 53, 38, 10631, 135, 231, 39, 135, 1319,
  206456. 135, 1063, 135, 231, 39, 135, 487, 1831, 135, 2151,
  206457. 108, 309, 655, 519, 346, 2727, 49, 19847, 85, 551,
  206458. 61, 839, 54, 50, 2407, 117, 110, 423, 135, 108,
  206459. 583, 108, 85, 583, 76, 423, 103, 76, 1671, 76,
  206460. 42, 236, 266, 44, 74, 364, 117, 38, 117, 55,
  206461. 39, 44, 333, 335, 213, 49, 149, 108, 61, 333,
  206462. 1127, 38, 1671, 1319, 44, 39, 2247, 935, 108, 138,
  206463. 76, 106, 74, 44, 202, 108, 58, 85, 333, 967,
  206464. 167, 1415, 554, 231, 74, 333, 47, 1114, 743, 76,
  206465. 106, 85, 1703, 42, 44, 42, 236, 44, 42, 44,
  206466. 74, 268, 202, 332, 44, 333, 333, 245, 38, 213,
  206467. 140, 42, 1511, 44, 42, 172, 42, 44, 170, 44,
  206468. 74, 231, 333, 245, 346, 300, 314, 76, 42, 967,
  206469. 42, 140, 74, 76, 42, 44, 74, 71, 333, 1415,
  206470. 44, 42, 76, 106, 44, 42, 108, 74, 149, 1159,
  206471. 266, 268, 74, 76, 181, 333, 103, 333, 967, 198,
  206472. 85, 277, 108, 53, 428, 42, 236, 135, 44, 135,
  206473. 74, 44, 71, 1413, 2022, 421, 38, 1093, 1190, 1260,
  206474. 140, 4830, 261, 3166, 261, 265, 197, 201, 261, 265,
  206475. 261, 265, 197, 201, 261, 41, 41, 41, 94, 229,
  206476. 265, 453, 261, 264, 261, 264, 261, 264, 165, 69,
  206477. 137, 40, 56, 37, 120, 101, 69, 137, 40, 120,
  206478. 133, 69, 137, 120, 261, 169, 120, 101, 69, 137,
  206479. 40, 88, 381, 162, 209, 85, 52, 51, 54, 84,
  206480. 51, 54, 52, 277, 59, 60, 162, 61, 309, 52,
  206481. 51, 149, 80, 117, 57, 54, 50, 373, 57, 53,
  206482. 48, 341, 61, 162, 194, 47, 38, 207, 121, 54,
  206483. 50, 38, 335, 121, 54, 50, 422, 855, 428, 139,
  206484. 44, 107, 396, 90, 41, 154, 41, 90, 37, 105,
  206485. 69, 105, 37, 58, 41, 90, 57, 169, 218, 41,
  206486. 58, 41, 58, 41, 58, 137, 58, 37, 137, 37,
  206487. 135, 37, 90, 69, 73, 185, 94, 101, 58, 57,
  206488. 90, 37, 58, 527, 1134, 94, 142, 47, 185, 186,
  206489. 89, 154, 57, 90, 57, 90, 57, 250, 57, 1018,
  206490. 89, 90, 57, 58, 57, 1018, 8601, 282, 153, 666,
  206491. 89, 250, 54, 50, 2618, 57, 986, 825, 1306, 217,
  206492. 602, 1274, 378, 1935, 2522, 719, 5882, 57, 314, 57,
  206493. 1754, 281, 3578, 57, 4634, 3322, 54, 50, 54, 50,
  206494. 54, 50, 54, 50, 54, 50, 54, 50, 54, 50,
  206495. 975, 1434, 185, 54, 50, 1017, 54, 50, 54, 50,
  206496. 54, 50, 54, 50, 54, 50, 537, 8218, 4217, 54,
  206497. 50, 54, 50, 54, 50, 54, 50, 54, 50, 54,
  206498. 50, 54, 50, 54, 50, 54, 50, 54, 50, 54,
  206499. 50, 2041, 54, 50, 54, 50, 1049, 54, 50, 8281,
  206500. 1562, 697, 90, 217, 346, 1513, 1509, 126, 73, 69,
  206501. 254, 105, 37, 94, 37, 94, 165, 70, 105, 37,
  206502. 3166, 37, 218, 158, 108, 94, 149, 47, 85, 1221,
  206503. 37, 37, 1799, 38, 53, 44, 743, 231, 231, 231,
  206504. 231, 231, 231, 231, 231, 1036, 85, 52, 51, 52,
  206505. 51, 117, 52, 51, 53, 52, 51, 309, 49, 85,
  206506. 49, 53, 52, 51, 85, 52, 51, 54, 50, 54,
  206507. 50, 54, 50, 54, 50, 181, 38, 341, 81, 858,
  206508. 2874, 6874, 410, 61, 117, 58, 38, 39, 46, 54,
  206509. 50, 54, 50, 54, 50, 54, 50, 54, 50, 90,
  206510. 54, 50, 54, 50, 54, 50, 54, 50, 49, 54,
  206511. 82, 58, 302, 140, 74, 49, 166, 90, 110, 38,
  206512. 39, 53, 90, 2759, 76, 88, 70, 39, 49, 2887,
  206513. 53, 102, 39, 1319, 3015, 90, 143, 346, 871, 1178,
  206514. 519, 1018, 335, 986, 271, 58, 495, 1050, 335, 1274,
  206515. 495, 2042, 8218, 39, 39, 2074, 39, 39, 679, 38,
  206516. 36583, 1786, 1287, 198, 85, 8583, 38, 117, 519, 333,
  206517. 71, 1502, 39, 44, 107, 53, 332, 53, 38, 798,
  206518. 44, 2247, 334, 76, 213, 760, 294, 88, 478, 69,
  206519. 2014, 38, 261, 190, 350, 38, 88, 158, 158, 382,
  206520. 70, 37, 231, 44, 103, 44, 135, 44, 743, 74,
  206521. 76, 42, 154, 207, 90, 55, 58, 1671, 149, 74,
  206522. 1607, 522, 44, 85, 333, 588, 199, 117, 39, 333,
  206523. 903, 268, 85, 743, 364, 74, 53, 935, 108, 42,
  206524. 1511, 44, 74, 140, 74, 44, 138, 437, 38, 333,
  206525. 85, 1319, 204, 74, 76, 74, 76, 103, 44, 263,
  206526. 44, 42, 333, 149, 519, 38, 199, 122, 39, 42,
  206527. 1543, 44, 39, 108, 71, 76, 167, 76, 39, 44,
  206528. 39, 71, 38, 85, 359, 42, 76, 74, 85, 39,
  206529. 70, 42, 44, 199, 199, 199, 231, 231, 1127, 74,
  206530. 44, 74, 44, 74, 53, 42, 44, 333, 39, 39,
  206531. 743, 1575, 36, 68, 68, 36, 63, 63, 11719, 3399,
  206532. 229, 165, 39, 44, 327, 57, 423, 167, 39, 71,
  206533. 71, 3463, 536, 11623, 54, 50, 2055, 1735, 391, 55,
  206534. 58, 524, 245, 54, 50, 53, 236, 53, 81, 80,
  206535. 54, 50, 54, 50, 54, 50, 54, 50, 54, 50,
  206536. 54, 50, 54, 50, 54, 50, 85, 54, 50, 149,
  206537. 112, 117, 149, 49, 54, 50, 54, 50, 54, 50,
  206538. 117, 57, 49, 121, 53, 55, 85, 167, 4327, 34,
  206539. 117, 55, 117, 54, 50, 53, 57, 53, 49, 85,
  206540. 333, 85, 121, 85, 841, 54, 53, 50, 56, 48,
  206541. 56, 837, 54, 57, 50, 57, 54, 50, 53, 54,
  206542. 50, 85, 327, 38, 1447, 70, 999, 199, 199, 199,
  206543. 103, 87, 57, 56, 58, 87, 58, 153, 90, 98,
  206544. 90, 391, 839, 615, 71, 487, 455, 3943, 117, 1455,
  206545. 314, 1710, 143, 570, 47, 410, 1466, 44, 935, 1575,
  206546. 999, 143, 551, 46, 263, 46, 967, 53, 1159, 263,
  206547. 53, 174, 1289, 1285, 2503, 333, 199, 39, 1415, 71,
  206548. 39, 743, 53, 271, 711, 207, 53, 839, 53, 1799,
  206549. 71, 39, 108, 76, 140, 135, 103, 871, 108, 44,
  206550. 271, 309, 935, 79, 53, 1735, 245, 711, 271, 615,
  206551. 271, 2343, 1007, 42, 44, 42, 1703, 492, 245, 655,
  206552. 333, 76, 42, 1447, 106, 140, 74, 76, 85, 34,
  206553. 149, 807, 333, 108, 1159, 172, 42, 268, 333, 149,
  206554. 76, 42, 1543, 106, 300, 74, 135, 149, 333, 1383,
  206555. 44, 42, 44, 74, 204, 42, 44, 333, 28135, 3182,
  206556. 149, 34279, 18215, 2215, 39, 1482, 140, 422, 71, 7898,
  206557. 1274, 1946, 74, 108, 122, 202, 258, 268, 90, 236,
  206558. 986, 140, 1562, 2138, 108, 58, 2810, 591, 841, 837,
  206559. 841, 229, 581, 841, 837, 41, 73, 41, 73, 137,
  206560. 265, 133, 37, 229, 357, 841, 837, 73, 137, 265,
  206561. 233, 837, 73, 137, 169, 41, 233, 837, 841, 837,
  206562. 841, 837, 841, 837, 841, 837, 841, 837, 841, 901,
  206563. 809, 57, 805, 57, 197, 809, 57, 805, 57, 197,
  206564. 809, 57, 805, 57, 197, 809, 57, 805, 57, 197,
  206565. 809, 57, 805, 57, 197, 94, 1613, 135, 871, 71,
  206566. 39, 39, 327, 135, 39, 39, 39, 39, 39, 39,
  206567. 103, 71, 39, 39, 39, 39, 39, 39, 71, 39,
  206568. 135, 231, 135, 135, 39, 327, 551, 103, 167, 551,
  206569. 89, 1434, 3226, 506, 474, 506, 506, 367, 1018, 1946,
  206570. 1402, 954, 1402, 314, 90, 1082, 218, 2266, 666, 1210,
  206571. 186, 570, 2042, 58, 5850, 154, 2010, 154, 794, 2266,
  206572. 378, 2266, 3738, 39, 39, 39, 39, 39, 39, 17351,
  206573. 34, 3074, 7692, 63, 63,
  206574. };
  206575. static int sqlite3Fts5UnicodeCategory(u32 iCode) {
  206576. int iRes = -1;
  206577. int iHi;
  206578. int iLo;
  206579. int ret;
  206580. u16 iKey;
  206581. if( iCode>=(1<<20) ){
  206582. return 0;
  206583. }
  206584. iLo = aFts5UnicodeBlock[(iCode>>16)];
  206585. iHi = aFts5UnicodeBlock[1+(iCode>>16)];
  206586. iKey = (iCode & 0xFFFF);
  206587. while( iHi>iLo ){
  206588. int iTest = (iHi + iLo) / 2;
  206589. assert( iTest>=iLo && iTest<iHi );
  206590. if( iKey>=aFts5UnicodeMap[iTest] ){
  206591. iRes = iTest;
  206592. iLo = iTest+1;
  206593. }else{
  206594. iHi = iTest;
  206595. }
  206596. }
  206597. if( iRes<0 ) return 0;
  206598. if( iKey>=(aFts5UnicodeMap[iRes]+(aFts5UnicodeData[iRes]>>5)) ) return 0;
  206599. ret = aFts5UnicodeData[iRes] & 0x1F;
  206600. if( ret!=30 ) return ret;
  206601. return ((iKey - aFts5UnicodeMap[iRes]) & 0x01) ? 5 : 9;
  206602. }
  206603. static void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){
  206604. int i = 0;
  206605. int iTbl = 0;
  206606. while( i<128 ){
  206607. int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ];
  206608. int n = (aFts5UnicodeData[iTbl] >> 5) + i;
  206609. for(; i<128 && i<n; i++){
  206610. aAscii[i] = (u8)bToken;
  206611. }
  206612. iTbl++;
  206613. }
  206614. }
  206615. /*
  206616. ** 2015 May 30
  206617. **
  206618. ** The author disclaims copyright to this source code. In place of
  206619. ** a legal notice, here is a blessing:
  206620. **
  206621. ** May you do good and not evil.
  206622. ** May you find forgiveness for yourself and forgive others.
  206623. ** May you share freely, never taking more than you give.
  206624. **
  206625. ******************************************************************************
  206626. **
  206627. ** Routines for varint serialization and deserialization.
  206628. */
  206629. /* #include "fts5Int.h" */
  206630. /*
  206631. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  206632. ** Except, this version does handle the single byte case that the core
  206633. ** version depends on being handled before its function is called.
  206634. */
  206635. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  206636. u32 a,b;
  206637. /* The 1-byte case. Overwhelmingly the most common. */
  206638. a = *p;
  206639. /* a: p0 (unmasked) */
  206640. if (!(a&0x80))
  206641. {
  206642. /* Values between 0 and 127 */
  206643. *v = a;
  206644. return 1;
  206645. }
  206646. /* The 2-byte case */
  206647. p++;
  206648. b = *p;
  206649. /* b: p1 (unmasked) */
  206650. if (!(b&0x80))
  206651. {
  206652. /* Values between 128 and 16383 */
  206653. a &= 0x7f;
  206654. a = a<<7;
  206655. *v = a | b;
  206656. return 2;
  206657. }
  206658. /* The 3-byte case */
  206659. p++;
  206660. a = a<<14;
  206661. a |= *p;
  206662. /* a: p0<<14 | p2 (unmasked) */
  206663. if (!(a&0x80))
  206664. {
  206665. /* Values between 16384 and 2097151 */
  206666. a &= (0x7f<<14)|(0x7f);
  206667. b &= 0x7f;
  206668. b = b<<7;
  206669. *v = a | b;
  206670. return 3;
  206671. }
  206672. /* A 32-bit varint is used to store size information in btrees.
  206673. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  206674. ** A 3-byte varint is sufficient, for example, to record the size
  206675. ** of a 1048569-byte BLOB or string.
  206676. **
  206677. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  206678. ** rare larger cases can be handled by the slower 64-bit varint
  206679. ** routine.
  206680. */
  206681. {
  206682. u64 v64;
  206683. u8 n;
  206684. p -= 2;
  206685. n = sqlite3Fts5GetVarint(p, &v64);
  206686. *v = ((u32)v64) & 0x7FFFFFFF;
  206687. assert( n>3 && n<=9 );
  206688. return n;
  206689. }
  206690. }
  206691. /*
  206692. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  206693. ** are defined here rather than simply putting the constant expressions
  206694. ** inline in order to work around bugs in the RVT compiler.
  206695. **
  206696. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  206697. **
  206698. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  206699. */
  206700. #define SLOT_2_0 0x001fc07f
  206701. #define SLOT_4_2_0 0xf01fc07f
  206702. /*
  206703. ** Read a 64-bit variable-length integer from memory starting at p[0].
  206704. ** Return the number of bytes read. The value is stored in *v.
  206705. */
  206706. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  206707. u32 a,b,s;
  206708. a = *p;
  206709. /* a: p0 (unmasked) */
  206710. if (!(a&0x80))
  206711. {
  206712. *v = a;
  206713. return 1;
  206714. }
  206715. p++;
  206716. b = *p;
  206717. /* b: p1 (unmasked) */
  206718. if (!(b&0x80))
  206719. {
  206720. a &= 0x7f;
  206721. a = a<<7;
  206722. a |= b;
  206723. *v = a;
  206724. return 2;
  206725. }
  206726. /* Verify that constants are precomputed correctly */
  206727. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  206728. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  206729. p++;
  206730. a = a<<14;
  206731. a |= *p;
  206732. /* a: p0<<14 | p2 (unmasked) */
  206733. if (!(a&0x80))
  206734. {
  206735. a &= SLOT_2_0;
  206736. b &= 0x7f;
  206737. b = b<<7;
  206738. a |= b;
  206739. *v = a;
  206740. return 3;
  206741. }
  206742. /* CSE1 from below */
  206743. a &= SLOT_2_0;
  206744. p++;
  206745. b = b<<14;
  206746. b |= *p;
  206747. /* b: p1<<14 | p3 (unmasked) */
  206748. if (!(b&0x80))
  206749. {
  206750. b &= SLOT_2_0;
  206751. /* moved CSE1 up */
  206752. /* a &= (0x7f<<14)|(0x7f); */
  206753. a = a<<7;
  206754. a |= b;
  206755. *v = a;
  206756. return 4;
  206757. }
  206758. /* a: p0<<14 | p2 (masked) */
  206759. /* b: p1<<14 | p3 (unmasked) */
  206760. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  206761. /* moved CSE1 up */
  206762. /* a &= (0x7f<<14)|(0x7f); */
  206763. b &= SLOT_2_0;
  206764. s = a;
  206765. /* s: p0<<14 | p2 (masked) */
  206766. p++;
  206767. a = a<<14;
  206768. a |= *p;
  206769. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  206770. if (!(a&0x80))
  206771. {
  206772. /* we can skip these cause they were (effectively) done above in calc'ing s */
  206773. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  206774. /* b &= (0x7f<<14)|(0x7f); */
  206775. b = b<<7;
  206776. a |= b;
  206777. s = s>>18;
  206778. *v = ((u64)s)<<32 | a;
  206779. return 5;
  206780. }
  206781. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  206782. s = s<<7;
  206783. s |= b;
  206784. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  206785. p++;
  206786. b = b<<14;
  206787. b |= *p;
  206788. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  206789. if (!(b&0x80))
  206790. {
  206791. /* we can skip this cause it was (effectively) done above in calc'ing s */
  206792. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  206793. a &= SLOT_2_0;
  206794. a = a<<7;
  206795. a |= b;
  206796. s = s>>18;
  206797. *v = ((u64)s)<<32 | a;
  206798. return 6;
  206799. }
  206800. p++;
  206801. a = a<<14;
  206802. a |= *p;
  206803. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  206804. if (!(a&0x80))
  206805. {
  206806. a &= SLOT_4_2_0;
  206807. b &= SLOT_2_0;
  206808. b = b<<7;
  206809. a |= b;
  206810. s = s>>11;
  206811. *v = ((u64)s)<<32 | a;
  206812. return 7;
  206813. }
  206814. /* CSE2 from below */
  206815. a &= SLOT_2_0;
  206816. p++;
  206817. b = b<<14;
  206818. b |= *p;
  206819. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  206820. if (!(b&0x80))
  206821. {
  206822. b &= SLOT_4_2_0;
  206823. /* moved CSE2 up */
  206824. /* a &= (0x7f<<14)|(0x7f); */
  206825. a = a<<7;
  206826. a |= b;
  206827. s = s>>4;
  206828. *v = ((u64)s)<<32 | a;
  206829. return 8;
  206830. }
  206831. p++;
  206832. a = a<<15;
  206833. a |= *p;
  206834. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  206835. /* moved CSE2 up */
  206836. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  206837. b &= SLOT_2_0;
  206838. b = b<<8;
  206839. a |= b;
  206840. s = s<<4;
  206841. b = p[-4];
  206842. b &= 0x7f;
  206843. b = b>>3;
  206844. s |= b;
  206845. *v = ((u64)s)<<32 | a;
  206846. return 9;
  206847. }
  206848. /*
  206849. ** The variable-length integer encoding is as follows:
  206850. **
  206851. ** KEY:
  206852. ** A = 0xxxxxxx 7 bits of data and one flag bit
  206853. ** B = 1xxxxxxx 7 bits of data and one flag bit
  206854. ** C = xxxxxxxx 8 bits of data
  206855. **
  206856. ** 7 bits - A
  206857. ** 14 bits - BA
  206858. ** 21 bits - BBA
  206859. ** 28 bits - BBBA
  206860. ** 35 bits - BBBBA
  206861. ** 42 bits - BBBBBA
  206862. ** 49 bits - BBBBBBA
  206863. ** 56 bits - BBBBBBBA
  206864. ** 64 bits - BBBBBBBBC
  206865. */
  206866. #ifdef SQLITE_NOINLINE
  206867. # define FTS5_NOINLINE SQLITE_NOINLINE
  206868. #else
  206869. # define FTS5_NOINLINE
  206870. #endif
  206871. /*
  206872. ** Write a 64-bit variable-length integer to memory starting at p[0].
  206873. ** The length of data write will be between 1 and 9 bytes. The number
  206874. ** of bytes written is returned.
  206875. **
  206876. ** A variable-length integer consists of the lower 7 bits of each byte
  206877. ** for all bytes that have the 8th bit set and one byte with the 8th
  206878. ** bit clear. Except, if we get to the 9th byte, it stores the full
  206879. ** 8 bits and is the last byte.
  206880. */
  206881. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  206882. int i, j, n;
  206883. u8 buf[10];
  206884. if( v & (((u64)0xff000000)<<32) ){
  206885. p[8] = (u8)v;
  206886. v >>= 8;
  206887. for(i=7; i>=0; i--){
  206888. p[i] = (u8)((v & 0x7f) | 0x80);
  206889. v >>= 7;
  206890. }
  206891. return 9;
  206892. }
  206893. n = 0;
  206894. do{
  206895. buf[n++] = (u8)((v & 0x7f) | 0x80);
  206896. v >>= 7;
  206897. }while( v!=0 );
  206898. buf[0] &= 0x7f;
  206899. assert( n<=9 );
  206900. for(i=0, j=n-1; j>=0; j--, i++){
  206901. p[i] = buf[j];
  206902. }
  206903. return n;
  206904. }
  206905. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  206906. if( v<=0x7f ){
  206907. p[0] = v&0x7f;
  206908. return 1;
  206909. }
  206910. if( v<=0x3fff ){
  206911. p[0] = ((v>>7)&0x7f)|0x80;
  206912. p[1] = v&0x7f;
  206913. return 2;
  206914. }
  206915. return fts5PutVarint64(p,v);
  206916. }
  206917. static int sqlite3Fts5GetVarintLen(u32 iVal){
  206918. #if 0
  206919. if( iVal<(1 << 7 ) ) return 1;
  206920. #endif
  206921. assert( iVal>=(1 << 7) );
  206922. if( iVal<(1 << 14) ) return 2;
  206923. if( iVal<(1 << 21) ) return 3;
  206924. if( iVal<(1 << 28) ) return 4;
  206925. return 5;
  206926. }
  206927. /*
  206928. ** 2015 May 08
  206929. **
  206930. ** The author disclaims copyright to this source code. In place of
  206931. ** a legal notice, here is a blessing:
  206932. **
  206933. ** May you do good and not evil.
  206934. ** May you find forgiveness for yourself and forgive others.
  206935. ** May you share freely, never taking more than you give.
  206936. **
  206937. ******************************************************************************
  206938. **
  206939. ** This is an SQLite virtual table module implementing direct access to an
  206940. ** existing FTS5 index. The module may create several different types of
  206941. ** tables:
  206942. **
  206943. ** col:
  206944. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  206945. **
  206946. ** One row for each term/column combination. The value of $doc is set to
  206947. ** the number of fts5 rows that contain at least one instance of term
  206948. ** $term within column $col. Field $cnt is set to the total number of
  206949. ** instances of term $term in column $col (in any row of the fts5 table).
  206950. **
  206951. ** row:
  206952. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  206953. **
  206954. ** One row for each term in the database. The value of $doc is set to
  206955. ** the number of fts5 rows that contain at least one instance of term
  206956. ** $term. Field $cnt is set to the total number of instances of term
  206957. ** $term in the database.
  206958. **
  206959. ** instance:
  206960. ** CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
  206961. **
  206962. ** One row for each term instance in the database.
  206963. */
  206964. /* #include "fts5Int.h" */
  206965. typedef struct Fts5VocabTable Fts5VocabTable;
  206966. typedef struct Fts5VocabCursor Fts5VocabCursor;
  206967. struct Fts5VocabTable {
  206968. sqlite3_vtab base;
  206969. char *zFts5Tbl; /* Name of fts5 table */
  206970. char *zFts5Db; /* Db containing fts5 table */
  206971. sqlite3 *db; /* Database handle */
  206972. Fts5Global *pGlobal; /* FTS5 global object for this database */
  206973. int eType; /* FTS5_VOCAB_COL, ROW or INSTANCE */
  206974. };
  206975. struct Fts5VocabCursor {
  206976. sqlite3_vtab_cursor base;
  206977. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  206978. Fts5Table *pFts5; /* Associated FTS5 table */
  206979. int bEof; /* True if this cursor is at EOF */
  206980. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  206981. int nLeTerm; /* Size of zLeTerm in bytes */
  206982. char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
  206983. /* These are used by 'col' tables only */
  206984. int iCol;
  206985. i64 *aCnt;
  206986. i64 *aDoc;
  206987. /* Output values used by all tables. */
  206988. i64 rowid; /* This table's current rowid value */
  206989. Fts5Buffer term; /* Current value of 'term' column */
  206990. /* Output values Used by 'instance' tables only */
  206991. i64 iInstPos;
  206992. int iInstOff;
  206993. };
  206994. #define FTS5_VOCAB_COL 0
  206995. #define FTS5_VOCAB_ROW 1
  206996. #define FTS5_VOCAB_INSTANCE 2
  206997. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  206998. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  206999. #define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
  207000. /*
  207001. ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
  207002. */
  207003. #define FTS5_VOCAB_TERM_EQ 0x01
  207004. #define FTS5_VOCAB_TERM_GE 0x02
  207005. #define FTS5_VOCAB_TERM_LE 0x04
  207006. /*
  207007. ** Translate a string containing an fts5vocab table type to an
  207008. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  207009. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  207010. ** and return SQLITE_ERROR.
  207011. */
  207012. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  207013. int rc = SQLITE_OK;
  207014. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  207015. if( rc==SQLITE_OK ){
  207016. sqlite3Fts5Dequote(zCopy);
  207017. if( sqlite3_stricmp(zCopy, "col")==0 ){
  207018. *peType = FTS5_VOCAB_COL;
  207019. }else
  207020. if( sqlite3_stricmp(zCopy, "row")==0 ){
  207021. *peType = FTS5_VOCAB_ROW;
  207022. }else
  207023. if( sqlite3_stricmp(zCopy, "instance")==0 ){
  207024. *peType = FTS5_VOCAB_INSTANCE;
  207025. }else
  207026. {
  207027. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  207028. rc = SQLITE_ERROR;
  207029. }
  207030. sqlite3_free(zCopy);
  207031. }
  207032. return rc;
  207033. }
  207034. /*
  207035. ** The xDisconnect() virtual table method.
  207036. */
  207037. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  207038. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  207039. sqlite3_free(pTab);
  207040. return SQLITE_OK;
  207041. }
  207042. /*
  207043. ** The xDestroy() virtual table method.
  207044. */
  207045. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  207046. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  207047. sqlite3_free(pTab);
  207048. return SQLITE_OK;
  207049. }
  207050. /*
  207051. ** This function is the implementation of both the xConnect and xCreate
  207052. ** methods of the FTS3 virtual table.
  207053. **
  207054. ** The argv[] array contains the following:
  207055. **
  207056. ** argv[0] -> module name ("fts5vocab")
  207057. ** argv[1] -> database name
  207058. ** argv[2] -> table name
  207059. **
  207060. ** then:
  207061. **
  207062. ** argv[3] -> name of fts5 table
  207063. ** argv[4] -> type of fts5vocab table
  207064. **
  207065. ** or, for tables in the TEMP schema only.
  207066. **
  207067. ** argv[3] -> name of fts5 tables database
  207068. ** argv[4] -> name of fts5 table
  207069. ** argv[5] -> type of fts5vocab table
  207070. */
  207071. static int fts5VocabInitVtab(
  207072. sqlite3 *db, /* The SQLite database connection */
  207073. void *pAux, /* Pointer to Fts5Global object */
  207074. int argc, /* Number of elements in argv array */
  207075. const char * const *argv, /* xCreate/xConnect argument array */
  207076. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  207077. char **pzErr /* Write any error message here */
  207078. ){
  207079. const char *azSchema[] = {
  207080. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  207081. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")",
  207082. "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
  207083. };
  207084. Fts5VocabTable *pRet = 0;
  207085. int rc = SQLITE_OK; /* Return code */
  207086. int bDb;
  207087. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  207088. if( argc!=5 && bDb==0 ){
  207089. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  207090. rc = SQLITE_ERROR;
  207091. }else{
  207092. int nByte; /* Bytes of space to allocate */
  207093. const char *zDb = bDb ? argv[3] : argv[1];
  207094. const char *zTab = bDb ? argv[4] : argv[3];
  207095. const char *zType = bDb ? argv[5] : argv[4];
  207096. int nDb = (int)strlen(zDb)+1;
  207097. int nTab = (int)strlen(zTab)+1;
  207098. int eType = 0;
  207099. rc = fts5VocabTableType(zType, pzErr, &eType);
  207100. if( rc==SQLITE_OK ){
  207101. assert( eType>=0 && eType<ArraySize(azSchema) );
  207102. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  207103. }
  207104. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  207105. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  207106. if( pRet ){
  207107. pRet->pGlobal = (Fts5Global*)pAux;
  207108. pRet->eType = eType;
  207109. pRet->db = db;
  207110. pRet->zFts5Tbl = (char*)&pRet[1];
  207111. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  207112. memcpy(pRet->zFts5Tbl, zTab, nTab);
  207113. memcpy(pRet->zFts5Db, zDb, nDb);
  207114. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  207115. sqlite3Fts5Dequote(pRet->zFts5Db);
  207116. }
  207117. }
  207118. *ppVTab = (sqlite3_vtab*)pRet;
  207119. return rc;
  207120. }
  207121. /*
  207122. ** The xConnect() and xCreate() methods for the virtual table. All the
  207123. ** work is done in function fts5VocabInitVtab().
  207124. */
  207125. static int fts5VocabConnectMethod(
  207126. sqlite3 *db, /* Database connection */
  207127. void *pAux, /* Pointer to tokenizer hash table */
  207128. int argc, /* Number of elements in argv array */
  207129. const char * const *argv, /* xCreate/xConnect argument array */
  207130. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  207131. char **pzErr /* OUT: sqlite3_malloc'd error message */
  207132. ){
  207133. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  207134. }
  207135. static int fts5VocabCreateMethod(
  207136. sqlite3 *db, /* Database connection */
  207137. void *pAux, /* Pointer to tokenizer hash table */
  207138. int argc, /* Number of elements in argv array */
  207139. const char * const *argv, /* xCreate/xConnect argument array */
  207140. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  207141. char **pzErr /* OUT: sqlite3_malloc'd error message */
  207142. ){
  207143. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  207144. }
  207145. /*
  207146. ** Implementation of the xBestIndex method.
  207147. **
  207148. ** Only constraints of the form:
  207149. **
  207150. ** term <= ?
  207151. ** term == ?
  207152. ** term >= ?
  207153. **
  207154. ** are interpreted. Less-than and less-than-or-equal are treated
  207155. ** identically, as are greater-than and greater-than-or-equal.
  207156. */
  207157. static int fts5VocabBestIndexMethod(
  207158. sqlite3_vtab *pUnused,
  207159. sqlite3_index_info *pInfo
  207160. ){
  207161. int i;
  207162. int iTermEq = -1;
  207163. int iTermGe = -1;
  207164. int iTermLe = -1;
  207165. int idxNum = 0;
  207166. int nArg = 0;
  207167. UNUSED_PARAM(pUnused);
  207168. for(i=0; i<pInfo->nConstraint; i++){
  207169. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  207170. if( p->usable==0 ) continue;
  207171. if( p->iColumn==0 ){ /* term column */
  207172. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
  207173. if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
  207174. if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
  207175. if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
  207176. if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
  207177. }
  207178. }
  207179. if( iTermEq>=0 ){
  207180. idxNum |= FTS5_VOCAB_TERM_EQ;
  207181. pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
  207182. pInfo->estimatedCost = 100;
  207183. }else{
  207184. pInfo->estimatedCost = 1000000;
  207185. if( iTermGe>=0 ){
  207186. idxNum |= FTS5_VOCAB_TERM_GE;
  207187. pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
  207188. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  207189. }
  207190. if( iTermLe>=0 ){
  207191. idxNum |= FTS5_VOCAB_TERM_LE;
  207192. pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
  207193. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  207194. }
  207195. }
  207196. /* This virtual table always delivers results in ascending order of
  207197. ** the "term" column (column 0). So if the user has requested this
  207198. ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
  207199. ** sqlite3_index_info.orderByConsumed flag to tell the core the results
  207200. ** are already in sorted order. */
  207201. if( pInfo->nOrderBy==1
  207202. && pInfo->aOrderBy[0].iColumn==0
  207203. && pInfo->aOrderBy[0].desc==0
  207204. ){
  207205. pInfo->orderByConsumed = 1;
  207206. }
  207207. pInfo->idxNum = idxNum;
  207208. return SQLITE_OK;
  207209. }
  207210. /*
  207211. ** Implementation of xOpen method.
  207212. */
  207213. static int fts5VocabOpenMethod(
  207214. sqlite3_vtab *pVTab,
  207215. sqlite3_vtab_cursor **ppCsr
  207216. ){
  207217. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  207218. Fts5Table *pFts5 = 0;
  207219. Fts5VocabCursor *pCsr = 0;
  207220. int rc = SQLITE_OK;
  207221. sqlite3_stmt *pStmt = 0;
  207222. char *zSql = 0;
  207223. zSql = sqlite3Fts5Mprintf(&rc,
  207224. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  207225. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  207226. );
  207227. if( zSql ){
  207228. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  207229. }
  207230. sqlite3_free(zSql);
  207231. assert( rc==SQLITE_OK || pStmt==0 );
  207232. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  207233. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  207234. i64 iId = sqlite3_column_int64(pStmt, 0);
  207235. pFts5 = sqlite3Fts5TableFromCsrid(pTab->pGlobal, iId);
  207236. }
  207237. if( rc==SQLITE_OK ){
  207238. if( pFts5==0 ){
  207239. rc = sqlite3_finalize(pStmt);
  207240. pStmt = 0;
  207241. if( rc==SQLITE_OK ){
  207242. pVTab->zErrMsg = sqlite3_mprintf(
  207243. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  207244. );
  207245. rc = SQLITE_ERROR;
  207246. }
  207247. }else{
  207248. rc = sqlite3Fts5FlushToDisk(pFts5);
  207249. }
  207250. }
  207251. if( rc==SQLITE_OK ){
  207252. int nByte = pFts5->pConfig->nCol * sizeof(i64)*2 + sizeof(Fts5VocabCursor);
  207253. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  207254. }
  207255. if( pCsr ){
  207256. pCsr->pFts5 = pFts5;
  207257. pCsr->pStmt = pStmt;
  207258. pCsr->aCnt = (i64*)&pCsr[1];
  207259. pCsr->aDoc = &pCsr->aCnt[pFts5->pConfig->nCol];
  207260. }else{
  207261. sqlite3_finalize(pStmt);
  207262. }
  207263. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  207264. return rc;
  207265. }
  207266. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  207267. pCsr->rowid = 0;
  207268. sqlite3Fts5IterClose(pCsr->pIter);
  207269. pCsr->pIter = 0;
  207270. sqlite3_free(pCsr->zLeTerm);
  207271. pCsr->nLeTerm = -1;
  207272. pCsr->zLeTerm = 0;
  207273. pCsr->bEof = 0;
  207274. }
  207275. /*
  207276. ** Close the cursor. For additional information see the documentation
  207277. ** on the xClose method of the virtual table interface.
  207278. */
  207279. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  207280. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  207281. fts5VocabResetCursor(pCsr);
  207282. sqlite3Fts5BufferFree(&pCsr->term);
  207283. sqlite3_finalize(pCsr->pStmt);
  207284. sqlite3_free(pCsr);
  207285. return SQLITE_OK;
  207286. }
  207287. static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
  207288. int rc = SQLITE_OK;
  207289. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  207290. pCsr->bEof = 1;
  207291. }else{
  207292. const char *zTerm;
  207293. int nTerm;
  207294. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  207295. if( pCsr->nLeTerm>=0 ){
  207296. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  207297. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  207298. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  207299. pCsr->bEof = 1;
  207300. }
  207301. }
  207302. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  207303. }
  207304. return rc;
  207305. }
  207306. static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
  207307. int eDetail = pCsr->pFts5->pConfig->eDetail;
  207308. int rc = SQLITE_OK;
  207309. Fts5IndexIter *pIter = pCsr->pIter;
  207310. i64 *pp = &pCsr->iInstPos;
  207311. int *po = &pCsr->iInstOff;
  207312. assert( sqlite3Fts5IterEof(pIter)==0 );
  207313. assert( pCsr->bEof==0 );
  207314. while( eDetail==FTS5_DETAIL_NONE
  207315. || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
  207316. ){
  207317. pCsr->iInstPos = 0;
  207318. pCsr->iInstOff = 0;
  207319. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  207320. if( rc==SQLITE_OK ){
  207321. rc = fts5VocabInstanceNewTerm(pCsr);
  207322. if( pCsr->bEof || eDetail==FTS5_DETAIL_NONE ) break;
  207323. }
  207324. if( rc ){
  207325. pCsr->bEof = 1;
  207326. break;
  207327. }
  207328. }
  207329. return rc;
  207330. }
  207331. /*
  207332. ** Advance the cursor to the next row in the table.
  207333. */
  207334. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  207335. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  207336. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  207337. int rc = SQLITE_OK;
  207338. int nCol = pCsr->pFts5->pConfig->nCol;
  207339. pCsr->rowid++;
  207340. if( pTab->eType==FTS5_VOCAB_INSTANCE ){
  207341. return fts5VocabInstanceNext(pCsr);
  207342. }
  207343. if( pTab->eType==FTS5_VOCAB_COL ){
  207344. for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
  207345. if( pCsr->aDoc[pCsr->iCol] ) break;
  207346. }
  207347. }
  207348. if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
  207349. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  207350. pCsr->bEof = 1;
  207351. }else{
  207352. const char *zTerm;
  207353. int nTerm;
  207354. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  207355. assert( nTerm>=0 );
  207356. if( pCsr->nLeTerm>=0 ){
  207357. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  207358. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  207359. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  207360. pCsr->bEof = 1;
  207361. return SQLITE_OK;
  207362. }
  207363. }
  207364. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  207365. memset(pCsr->aCnt, 0, nCol * sizeof(i64));
  207366. memset(pCsr->aDoc, 0, nCol * sizeof(i64));
  207367. pCsr->iCol = 0;
  207368. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  207369. while( rc==SQLITE_OK ){
  207370. int eDetail = pCsr->pFts5->pConfig->eDetail;
  207371. const u8 *pPos; int nPos; /* Position list */
  207372. i64 iPos = 0; /* 64-bit position read from poslist */
  207373. int iOff = 0; /* Current offset within position list */
  207374. pPos = pCsr->pIter->pData;
  207375. nPos = pCsr->pIter->nData;
  207376. switch( pTab->eType ){
  207377. case FTS5_VOCAB_ROW:
  207378. if( eDetail==FTS5_DETAIL_FULL ){
  207379. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  207380. pCsr->aCnt[0]++;
  207381. }
  207382. }
  207383. pCsr->aDoc[0]++;
  207384. break;
  207385. case FTS5_VOCAB_COL:
  207386. if( eDetail==FTS5_DETAIL_FULL ){
  207387. int iCol = -1;
  207388. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  207389. int ii = FTS5_POS2COLUMN(iPos);
  207390. if( iCol!=ii ){
  207391. if( ii>=nCol ){
  207392. rc = FTS5_CORRUPT;
  207393. break;
  207394. }
  207395. pCsr->aDoc[ii]++;
  207396. iCol = ii;
  207397. }
  207398. pCsr->aCnt[ii]++;
  207399. }
  207400. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  207401. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
  207402. assert_nc( iPos>=0 && iPos<nCol );
  207403. if( iPos>=nCol ){
  207404. rc = FTS5_CORRUPT;
  207405. break;
  207406. }
  207407. pCsr->aDoc[iPos]++;
  207408. }
  207409. }else{
  207410. assert( eDetail==FTS5_DETAIL_NONE );
  207411. pCsr->aDoc[0]++;
  207412. }
  207413. break;
  207414. default:
  207415. assert( pTab->eType==FTS5_VOCAB_INSTANCE );
  207416. break;
  207417. }
  207418. if( rc==SQLITE_OK ){
  207419. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  207420. }
  207421. if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
  207422. if( rc==SQLITE_OK ){
  207423. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  207424. if( nTerm!=pCsr->term.n
  207425. || (nTerm>0 && memcmp(zTerm, pCsr->term.p, nTerm))
  207426. ){
  207427. break;
  207428. }
  207429. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  207430. }
  207431. }
  207432. }
  207433. }
  207434. if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  207435. while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
  207436. assert( pCsr->iCol<pCsr->pFts5->pConfig->nCol );
  207437. }
  207438. return rc;
  207439. }
  207440. /*
  207441. ** This is the xFilter implementation for the virtual table.
  207442. */
  207443. static int fts5VocabFilterMethod(
  207444. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  207445. int idxNum, /* Strategy index */
  207446. const char *zUnused, /* Unused */
  207447. int nUnused, /* Number of elements in apVal */
  207448. sqlite3_value **apVal /* Arguments for the indexing scheme */
  207449. ){
  207450. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  207451. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  207452. int eType = pTab->eType;
  207453. int rc = SQLITE_OK;
  207454. int iVal = 0;
  207455. int f = FTS5INDEX_QUERY_SCAN;
  207456. const char *zTerm = 0;
  207457. int nTerm = 0;
  207458. sqlite3_value *pEq = 0;
  207459. sqlite3_value *pGe = 0;
  207460. sqlite3_value *pLe = 0;
  207461. UNUSED_PARAM2(zUnused, nUnused);
  207462. fts5VocabResetCursor(pCsr);
  207463. if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
  207464. if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
  207465. if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
  207466. if( pEq ){
  207467. zTerm = (const char *)sqlite3_value_text(pEq);
  207468. nTerm = sqlite3_value_bytes(pEq);
  207469. f = 0;
  207470. }else{
  207471. if( pGe ){
  207472. zTerm = (const char *)sqlite3_value_text(pGe);
  207473. nTerm = sqlite3_value_bytes(pGe);
  207474. }
  207475. if( pLe ){
  207476. const char *zCopy = (const char *)sqlite3_value_text(pLe);
  207477. if( zCopy==0 ) zCopy = "";
  207478. pCsr->nLeTerm = sqlite3_value_bytes(pLe);
  207479. pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
  207480. if( pCsr->zLeTerm==0 ){
  207481. rc = SQLITE_NOMEM;
  207482. }else{
  207483. memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
  207484. }
  207485. }
  207486. }
  207487. if( rc==SQLITE_OK ){
  207488. Fts5Index *pIndex = pCsr->pFts5->pIndex;
  207489. rc = sqlite3Fts5IndexQuery(pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
  207490. }
  207491. if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
  207492. rc = fts5VocabInstanceNewTerm(pCsr);
  207493. }
  207494. if( rc==SQLITE_OK && !pCsr->bEof
  207495. && (eType!=FTS5_VOCAB_INSTANCE
  207496. || pCsr->pFts5->pConfig->eDetail!=FTS5_DETAIL_NONE)
  207497. ){
  207498. rc = fts5VocabNextMethod(pCursor);
  207499. }
  207500. return rc;
  207501. }
  207502. /*
  207503. ** This is the xEof method of the virtual table. SQLite calls this
  207504. ** routine to find out if it has reached the end of a result set.
  207505. */
  207506. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  207507. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  207508. return pCsr->bEof;
  207509. }
  207510. static int fts5VocabColumnMethod(
  207511. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  207512. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  207513. int iCol /* Index of column to read value from */
  207514. ){
  207515. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  207516. int eDetail = pCsr->pFts5->pConfig->eDetail;
  207517. int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
  207518. i64 iVal = 0;
  207519. if( iCol==0 ){
  207520. sqlite3_result_text(
  207521. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  207522. );
  207523. }else if( eType==FTS5_VOCAB_COL ){
  207524. assert( iCol==1 || iCol==2 || iCol==3 );
  207525. if( iCol==1 ){
  207526. if( eDetail!=FTS5_DETAIL_NONE ){
  207527. const char *z = pCsr->pFts5->pConfig->azCol[pCsr->iCol];
  207528. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  207529. }
  207530. }else if( iCol==2 ){
  207531. iVal = pCsr->aDoc[pCsr->iCol];
  207532. }else{
  207533. iVal = pCsr->aCnt[pCsr->iCol];
  207534. }
  207535. }else if( eType==FTS5_VOCAB_ROW ){
  207536. assert( iCol==1 || iCol==2 );
  207537. if( iCol==1 ){
  207538. iVal = pCsr->aDoc[0];
  207539. }else{
  207540. iVal = pCsr->aCnt[0];
  207541. }
  207542. }else{
  207543. assert( eType==FTS5_VOCAB_INSTANCE );
  207544. switch( iCol ){
  207545. case 1:
  207546. sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
  207547. break;
  207548. case 2: {
  207549. int ii = -1;
  207550. if( eDetail==FTS5_DETAIL_FULL ){
  207551. ii = FTS5_POS2COLUMN(pCsr->iInstPos);
  207552. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  207553. ii = (int)pCsr->iInstPos;
  207554. }
  207555. if( ii>=0 && ii<pCsr->pFts5->pConfig->nCol ){
  207556. const char *z = pCsr->pFts5->pConfig->azCol[ii];
  207557. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  207558. }
  207559. break;
  207560. }
  207561. default: {
  207562. assert( iCol==3 );
  207563. if( eDetail==FTS5_DETAIL_FULL ){
  207564. int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
  207565. sqlite3_result_int(pCtx, ii);
  207566. }
  207567. break;
  207568. }
  207569. }
  207570. }
  207571. if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
  207572. return SQLITE_OK;
  207573. }
  207574. /*
  207575. ** This is the xRowid method. The SQLite core calls this routine to
  207576. ** retrieve the rowid for the current row of the result set. The
  207577. ** rowid should be written to *pRowid.
  207578. */
  207579. static int fts5VocabRowidMethod(
  207580. sqlite3_vtab_cursor *pCursor,
  207581. sqlite_int64 *pRowid
  207582. ){
  207583. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  207584. *pRowid = pCsr->rowid;
  207585. return SQLITE_OK;
  207586. }
  207587. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  207588. static const sqlite3_module fts5Vocab = {
  207589. /* iVersion */ 2,
  207590. /* xCreate */ fts5VocabCreateMethod,
  207591. /* xConnect */ fts5VocabConnectMethod,
  207592. /* xBestIndex */ fts5VocabBestIndexMethod,
  207593. /* xDisconnect */ fts5VocabDisconnectMethod,
  207594. /* xDestroy */ fts5VocabDestroyMethod,
  207595. /* xOpen */ fts5VocabOpenMethod,
  207596. /* xClose */ fts5VocabCloseMethod,
  207597. /* xFilter */ fts5VocabFilterMethod,
  207598. /* xNext */ fts5VocabNextMethod,
  207599. /* xEof */ fts5VocabEofMethod,
  207600. /* xColumn */ fts5VocabColumnMethod,
  207601. /* xRowid */ fts5VocabRowidMethod,
  207602. /* xUpdate */ 0,
  207603. /* xBegin */ 0,
  207604. /* xSync */ 0,
  207605. /* xCommit */ 0,
  207606. /* xRollback */ 0,
  207607. /* xFindFunction */ 0,
  207608. /* xRename */ 0,
  207609. /* xSavepoint */ 0,
  207610. /* xRelease */ 0,
  207611. /* xRollbackTo */ 0,
  207612. /* xShadowName */ 0
  207613. };
  207614. void *p = (void*)pGlobal;
  207615. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  207616. }
  207617. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  207618. /************** End of fts5.c ************************************************/
  207619. /************** Begin file stmt.c ********************************************/
  207620. /*
  207621. ** 2017-05-31
  207622. **
  207623. ** The author disclaims copyright to this source code. In place of
  207624. ** a legal notice, here is a blessing:
  207625. **
  207626. ** May you do good and not evil.
  207627. ** May you find forgiveness for yourself and forgive others.
  207628. ** May you share freely, never taking more than you give.
  207629. **
  207630. *************************************************************************
  207631. **
  207632. ** This file demonstrates an eponymous virtual table that returns information
  207633. ** about all prepared statements for the database connection.
  207634. **
  207635. ** Usage example:
  207636. **
  207637. ** .load ./stmt
  207638. ** .mode line
  207639. ** .header on
  207640. ** SELECT * FROM stmt;
  207641. */
  207642. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
  207643. #if !defined(SQLITEINT_H)
  207644. /* #include "sqlite3ext.h" */
  207645. #endif
  207646. SQLITE_EXTENSION_INIT1
  207647. /* #include <assert.h> */
  207648. /* #include <string.h> */
  207649. #ifndef SQLITE_OMIT_VIRTUALTABLE
  207650. /* stmt_vtab is a subclass of sqlite3_vtab which will
  207651. ** serve as the underlying representation of a stmt virtual table
  207652. */
  207653. typedef struct stmt_vtab stmt_vtab;
  207654. struct stmt_vtab {
  207655. sqlite3_vtab base; /* Base class - must be first */
  207656. sqlite3 *db; /* Database connection for this stmt vtab */
  207657. };
  207658. /* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
  207659. ** serve as the underlying representation of a cursor that scans
  207660. ** over rows of the result
  207661. */
  207662. typedef struct stmt_cursor stmt_cursor;
  207663. struct stmt_cursor {
  207664. sqlite3_vtab_cursor base; /* Base class - must be first */
  207665. sqlite3 *db; /* Database connection for this cursor */
  207666. sqlite3_stmt *pStmt; /* Statement cursor is currently pointing at */
  207667. sqlite3_int64 iRowid; /* The rowid */
  207668. };
  207669. /*
  207670. ** The stmtConnect() method is invoked to create a new
  207671. ** stmt_vtab that describes the stmt virtual table.
  207672. **
  207673. ** Think of this routine as the constructor for stmt_vtab objects.
  207674. **
  207675. ** All this routine needs to do is:
  207676. **
  207677. ** (1) Allocate the stmt_vtab object and initialize all fields.
  207678. **
  207679. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  207680. ** result set of queries against stmt will look like.
  207681. */
  207682. static int stmtConnect(
  207683. sqlite3 *db,
  207684. void *pAux,
  207685. int argc, const char *const*argv,
  207686. sqlite3_vtab **ppVtab,
  207687. char **pzErr
  207688. ){
  207689. stmt_vtab *pNew;
  207690. int rc;
  207691. /* Column numbers */
  207692. #define STMT_COLUMN_SQL 0 /* SQL for the statement */
  207693. #define STMT_COLUMN_NCOL 1 /* Number of result columns */
  207694. #define STMT_COLUMN_RO 2 /* True if read-only */
  207695. #define STMT_COLUMN_BUSY 3 /* True if currently busy */
  207696. #define STMT_COLUMN_NSCAN 4 /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
  207697. #define STMT_COLUMN_NSORT 5 /* SQLITE_STMTSTATUS_SORT */
  207698. #define STMT_COLUMN_NAIDX 6 /* SQLITE_STMTSTATUS_AUTOINDEX */
  207699. #define STMT_COLUMN_NSTEP 7 /* SQLITE_STMTSTATUS_VM_STEP */
  207700. #define STMT_COLUMN_REPREP 8 /* SQLITE_STMTSTATUS_REPREPARE */
  207701. #define STMT_COLUMN_RUN 9 /* SQLITE_STMTSTATUS_RUN */
  207702. #define STMT_COLUMN_MEM 10 /* SQLITE_STMTSTATUS_MEMUSED */
  207703. rc = sqlite3_declare_vtab(db,
  207704. "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
  207705. "reprep,run,mem)");
  207706. if( rc==SQLITE_OK ){
  207707. pNew = sqlite3_malloc( sizeof(*pNew) );
  207708. *ppVtab = (sqlite3_vtab*)pNew;
  207709. if( pNew==0 ) return SQLITE_NOMEM;
  207710. memset(pNew, 0, sizeof(*pNew));
  207711. pNew->db = db;
  207712. }
  207713. return rc;
  207714. }
  207715. /*
  207716. ** This method is the destructor for stmt_cursor objects.
  207717. */
  207718. static int stmtDisconnect(sqlite3_vtab *pVtab){
  207719. sqlite3_free(pVtab);
  207720. return SQLITE_OK;
  207721. }
  207722. /*
  207723. ** Constructor for a new stmt_cursor object.
  207724. */
  207725. static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  207726. stmt_cursor *pCur;
  207727. pCur = sqlite3_malloc( sizeof(*pCur) );
  207728. if( pCur==0 ) return SQLITE_NOMEM;
  207729. memset(pCur, 0, sizeof(*pCur));
  207730. pCur->db = ((stmt_vtab*)p)->db;
  207731. *ppCursor = &pCur->base;
  207732. return SQLITE_OK;
  207733. }
  207734. /*
  207735. ** Destructor for a stmt_cursor.
  207736. */
  207737. static int stmtClose(sqlite3_vtab_cursor *cur){
  207738. sqlite3_free(cur);
  207739. return SQLITE_OK;
  207740. }
  207741. /*
  207742. ** Advance a stmt_cursor to its next row of output.
  207743. */
  207744. static int stmtNext(sqlite3_vtab_cursor *cur){
  207745. stmt_cursor *pCur = (stmt_cursor*)cur;
  207746. pCur->iRowid++;
  207747. pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
  207748. return SQLITE_OK;
  207749. }
  207750. /*
  207751. ** Return values of columns for the row at which the stmt_cursor
  207752. ** is currently pointing.
  207753. */
  207754. static int stmtColumn(
  207755. sqlite3_vtab_cursor *cur, /* The cursor */
  207756. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  207757. int i /* Which column to return */
  207758. ){
  207759. stmt_cursor *pCur = (stmt_cursor*)cur;
  207760. switch( i ){
  207761. case STMT_COLUMN_SQL: {
  207762. sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
  207763. break;
  207764. }
  207765. case STMT_COLUMN_NCOL: {
  207766. sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
  207767. break;
  207768. }
  207769. case STMT_COLUMN_RO: {
  207770. sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
  207771. break;
  207772. }
  207773. case STMT_COLUMN_BUSY: {
  207774. sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
  207775. break;
  207776. }
  207777. case STMT_COLUMN_MEM: {
  207778. i = SQLITE_STMTSTATUS_MEMUSED +
  207779. STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
  207780. /* Fall thru */
  207781. }
  207782. case STMT_COLUMN_NSCAN:
  207783. case STMT_COLUMN_NSORT:
  207784. case STMT_COLUMN_NAIDX:
  207785. case STMT_COLUMN_NSTEP:
  207786. case STMT_COLUMN_REPREP:
  207787. case STMT_COLUMN_RUN: {
  207788. sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
  207789. i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
  207790. break;
  207791. }
  207792. }
  207793. return SQLITE_OK;
  207794. }
  207795. /*
  207796. ** Return the rowid for the current row. In this implementation, the
  207797. ** rowid is the same as the output value.
  207798. */
  207799. static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  207800. stmt_cursor *pCur = (stmt_cursor*)cur;
  207801. *pRowid = pCur->iRowid;
  207802. return SQLITE_OK;
  207803. }
  207804. /*
  207805. ** Return TRUE if the cursor has been moved off of the last
  207806. ** row of output.
  207807. */
  207808. static int stmtEof(sqlite3_vtab_cursor *cur){
  207809. stmt_cursor *pCur = (stmt_cursor*)cur;
  207810. return pCur->pStmt==0;
  207811. }
  207812. /*
  207813. ** This method is called to "rewind" the stmt_cursor object back
  207814. ** to the first row of output. This method is always called at least
  207815. ** once prior to any call to stmtColumn() or stmtRowid() or
  207816. ** stmtEof().
  207817. */
  207818. static int stmtFilter(
  207819. sqlite3_vtab_cursor *pVtabCursor,
  207820. int idxNum, const char *idxStr,
  207821. int argc, sqlite3_value **argv
  207822. ){
  207823. stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
  207824. pCur->pStmt = 0;
  207825. pCur->iRowid = 0;
  207826. return stmtNext(pVtabCursor);
  207827. }
  207828. /*
  207829. ** SQLite will invoke this method one or more times while planning a query
  207830. ** that uses the stmt virtual table. This routine needs to create
  207831. ** a query plan for each invocation and compute an estimated cost for that
  207832. ** plan.
  207833. */
  207834. static int stmtBestIndex(
  207835. sqlite3_vtab *tab,
  207836. sqlite3_index_info *pIdxInfo
  207837. ){
  207838. pIdxInfo->estimatedCost = (double)500;
  207839. pIdxInfo->estimatedRows = 500;
  207840. return SQLITE_OK;
  207841. }
  207842. /*
  207843. ** This following structure defines all the methods for the
  207844. ** stmt virtual table.
  207845. */
  207846. static sqlite3_module stmtModule = {
  207847. 0, /* iVersion */
  207848. 0, /* xCreate */
  207849. stmtConnect, /* xConnect */
  207850. stmtBestIndex, /* xBestIndex */
  207851. stmtDisconnect, /* xDisconnect */
  207852. 0, /* xDestroy */
  207853. stmtOpen, /* xOpen - open a cursor */
  207854. stmtClose, /* xClose - close a cursor */
  207855. stmtFilter, /* xFilter - configure scan constraints */
  207856. stmtNext, /* xNext - advance a cursor */
  207857. stmtEof, /* xEof - check for end of scan */
  207858. stmtColumn, /* xColumn - read data */
  207859. stmtRowid, /* xRowid - read data */
  207860. 0, /* xUpdate */
  207861. 0, /* xBegin */
  207862. 0, /* xSync */
  207863. 0, /* xCommit */
  207864. 0, /* xRollback */
  207865. 0, /* xFindMethod */
  207866. 0, /* xRename */
  207867. 0, /* xSavepoint */
  207868. 0, /* xRelease */
  207869. 0, /* xRollbackTo */
  207870. 0, /* xShadowName */
  207871. };
  207872. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  207873. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
  207874. int rc = SQLITE_OK;
  207875. #ifndef SQLITE_OMIT_VIRTUALTABLE
  207876. rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
  207877. #endif
  207878. return rc;
  207879. }
  207880. #ifndef SQLITE_CORE
  207881. #ifdef _WIN32
  207882. __declspec(dllexport)
  207883. #endif
  207884. SQLITE_API int sqlite3_stmt_init(
  207885. sqlite3 *db,
  207886. char **pzErrMsg,
  207887. const sqlite3_api_routines *pApi
  207888. ){
  207889. int rc = SQLITE_OK;
  207890. SQLITE_EXTENSION_INIT2(pApi);
  207891. #ifndef SQLITE_OMIT_VIRTUALTABLE
  207892. rc = sqlite3StmtVtabInit(db);
  207893. #endif
  207894. return rc;
  207895. }
  207896. #endif /* SQLITE_CORE */
  207897. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
  207898. /************** End of stmt.c ************************************************/
  207899. #if __LINE__!=222870
  207900. #undef SQLITE_SOURCE_ID
  207901. #define SQLITE_SOURCE_ID "2019-04-16 19:49:53 884b4b7e502b4e991677b53971277adfaf0a04a284f8e483e2553d0f8315alt2"
  207902. #endif
  207903. /* Return the source-id for this library */
  207904. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  207905. /************************** End of sqlite3.c ******************************/